Skip to content

Commit

Permalink
Remove some code specific to Python 2
Browse files Browse the repository at this point in the history
`to_env` and `to_text` are no longer necessary since they were identity
functions with Python 3.
  • Loading branch information
bbc2 committed Jul 13, 2021
1 parent fbc7a63 commit 9e522b1
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 73 deletions.
6 changes: 3 additions & 3 deletions src/dotenv/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
'Run pip install "python-dotenv[cli]" to fix this.')
sys.exit(1)

from .compat import IS_TYPE_CHECKING, to_env
from .compat import IS_TYPE_CHECKING
from .main import dotenv_values, get_key, set_key, unset_key
from .version import __version__

Expand Down Expand Up @@ -123,9 +123,9 @@ def run(ctx, override, commandline):
ctx=ctx
)
dotenv_as_dict = {
to_env(k): to_env(v)
k: v
for (k, v) in dotenv_values(file).items()
if v is not None and (override or to_env(k) not in os.environ)
if v is not None and (override or k not in os.environ)
}

if not commandline:
Expand Down
39 changes: 0 additions & 39 deletions src/dotenv/compat.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
import sys

PY2 = sys.version_info[0] == 2 # type: bool

if PY2:
from StringIO import StringIO # noqa
else:
from io import StringIO # noqa


def is_type_checking():
# type: () -> bool
try:
Expand All @@ -18,32 +8,3 @@ def is_type_checking():


IS_TYPE_CHECKING = is_type_checking()


if IS_TYPE_CHECKING:
from typing import Text


def to_env(text):
# type: (Text) -> str
"""
Encode a string the same way whether it comes from the environment or a `.env` file.
"""
if PY2:
return text.encode(sys.getfilesystemencoding() or "utf-8")
else:
return text


def to_text(string):
# type: (str) -> Text
"""
Make a string Unicode if it isn't already.
This is useful for defining raw unicode strings because `ur"foo"` isn't valid in
Python 3.
"""
if PY2:
return string.decode("utf-8")
else:
return string
29 changes: 9 additions & 20 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from collections import OrderedDict
from contextlib import contextmanager

from .compat import IS_TYPE_CHECKING, PY2, StringIO, to_env
from .compat import IS_TYPE_CHECKING
from .parser import Binding, parse_stream
from .variables import parse_variables

Expand All @@ -24,11 +24,6 @@
else:
_PathLike = Text

if sys.version_info >= (3, 0):
_StringIO = StringIO
else:
_StringIO = StringIO[Text]


def with_warn_for_invalid_lines(mappings):
# type: (Iterator[Binding]) -> Iterator[Binding]
Expand All @@ -44,8 +39,8 @@ def with_warn_for_invalid_lines(mappings):
class DotEnv():

def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True, override=True):
# type: (Union[Text, _PathLike, _StringIO], bool, Union[None, Text], bool, bool) -> None
self.dotenv_path = dotenv_path # type: Union[Text,_PathLike, _StringIO]
# type: (Union[Text, _PathLike, io.StringIO], bool, Union[None, Text], bool, bool) -> None
self.dotenv_path = dotenv_path # type: Union[Text,_PathLike, io.StringIO]
self._dict = None # type: Optional[Dict[Text, Optional[Text]]]
self.verbose = verbose # type: bool
self.encoding = encoding # type: Union[None, Text]
Expand All @@ -55,15 +50,15 @@ def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True,
@contextmanager
def _get_stream(self):
# type: () -> Iterator[IO[Text]]
if isinstance(self.dotenv_path, StringIO):
if isinstance(self.dotenv_path, io.StringIO):
yield self.dotenv_path
elif os.path.isfile(self.dotenv_path):
with io.open(self.dotenv_path, encoding=self.encoding) as stream:
yield stream
else:
if self.verbose:
logger.info("Python-dotenv could not find configuration file %s.", self.dotenv_path or '.env')
yield StringIO('')
yield io.StringIO('')

def dict(self):
# type: () -> Dict[Text, Optional[Text]]
Expand Down Expand Up @@ -96,7 +91,7 @@ def set_as_environment_variables(self):
if k in os.environ and not self.override:
continue
if v is not None:
os.environ[to_env(k)] = to_env(v)
os.environ[k] = v

return True

Expand Down Expand Up @@ -271,13 +266,7 @@ def _is_interactive():
else:
# will work for .py files
frame = sys._getframe()
# find first frame that is outside of this file
if PY2 and not __file__.endswith('.py'):
# in Python2 __file__ extension could be .pyc or .pyo (this doesn't account
# for edge case of Python compiled for non-standard extension)
current_file = __file__.rsplit('.', 1)[0] + '.py'
else:
current_file = __file__
current_file = __file__

while frame.f_code.co_filename == current_file:
assert frame.f_back is not None
Expand All @@ -304,7 +293,7 @@ def load_dotenv(
interpolate=True,
encoding="utf-8",
):
# type: (Union[Text, _PathLike, None], Optional[_StringIO], bool, bool, bool, Optional[Text]) -> bool # noqa
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, bool, Optional[Text]) -> bool # noqa
"""Parse a .env file and then load all the variables found as environment variables.
- *dotenv_path*: absolute or relative path to .env file.
Expand Down Expand Up @@ -335,7 +324,7 @@ def dotenv_values(
interpolate=True,
encoding="utf-8",
):
# type: (Union[Text, _PathLike, None], Optional[_StringIO], bool, bool, Optional[Text]) -> Dict[Text, Optional[Text]] # noqa: E501
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, Optional[Text]) -> Dict[Text, Optional[Text]] # noqa: E501
"""
Parse a .env file and return its content as a dict.
Expand Down
4 changes: 2 additions & 2 deletions src/dotenv/parser.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import codecs
import re

from .compat import IS_TYPE_CHECKING, to_text
from .compat import IS_TYPE_CHECKING

if IS_TYPE_CHECKING:
from typing import ( # noqa:F401
Expand All @@ -12,7 +12,7 @@

def make_regex(string, extra_flags=0):
# type: (str, int) -> Pattern[Text]
return re.compile(to_text(string), re.UNICODE | extra_flags)
return re.compile(string, re.UNICODE | extra_flags)


_newline = make_regex(r"(\r\n|\n|\r)")
Expand Down
11 changes: 4 additions & 7 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import io
import logging
import os
import sys
Expand All @@ -11,7 +12,6 @@
import sh

import dotenv
from dotenv.compat import PY2, StringIO


def test_set_key_no_file(tmp_path):
Expand Down Expand Up @@ -281,15 +281,12 @@ def test_load_dotenv_redefine_var_used_in_file_with_override(dotenv_file):

@mock.patch.dict(os.environ, {}, clear=True)
def test_load_dotenv_utf_8():
stream = StringIO("a=à")
stream = io.StringIO("a=à")

result = dotenv.load_dotenv(stream=stream)

assert result is True
if PY2:
assert os.environ == {"a": "à".encode(sys.getfilesystemencoding())}
else:
assert os.environ == {"a": "à"}
assert os.environ == {"a": "à"}


def test_load_dotenv_in_current_dir(tmp_path):
Expand Down Expand Up @@ -361,7 +358,7 @@ def test_dotenv_values_file(dotenv_file):
)
def test_dotenv_values_stream(env, string, interpolate, expected):
with mock.patch.dict(os.environ, env, clear=True):
stream = StringIO(string)
stream = io.StringIO(string)
stream.seek(0)

result = dotenv.dotenv_values(stream=stream, interpolate=interpolate)
Expand Down
5 changes: 3 additions & 2 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
import io

import pytest

from dotenv.compat import StringIO
from dotenv.parser import Binding, Original, parse_stream


Expand Down Expand Up @@ -166,6 +167,6 @@
),
])
def test_parse_stream(test_input, expected):
result = parse_stream(StringIO(test_input))
result = parse_stream(io.StringIO(test_input))

assert list(result) == expected

0 comments on commit 9e522b1

Please sign in to comment.