Skip to content

Commit 9e522b1

Browse files
committed
Remove some code specific to Python 2
`to_env` and `to_text` are no longer necessary since they were identity functions with Python 3.
1 parent fbc7a63 commit 9e522b1

File tree

6 files changed

+21
-73
lines changed

6 files changed

+21
-73
lines changed

src/dotenv/cli.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
'Run pip install "python-dotenv[cli]" to fix this.')
1010
sys.exit(1)
1111

12-
from .compat import IS_TYPE_CHECKING, to_env
12+
from .compat import IS_TYPE_CHECKING
1313
from .main import dotenv_values, get_key, set_key, unset_key
1414
from .version import __version__
1515

@@ -123,9 +123,9 @@ def run(ctx, override, commandline):
123123
ctx=ctx
124124
)
125125
dotenv_as_dict = {
126-
to_env(k): to_env(v)
126+
k: v
127127
for (k, v) in dotenv_values(file).items()
128-
if v is not None and (override or to_env(k) not in os.environ)
128+
if v is not None and (override or k not in os.environ)
129129
}
130130

131131
if not commandline:

src/dotenv/compat.py

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,3 @@
1-
import sys
2-
3-
PY2 = sys.version_info[0] == 2 # type: bool
4-
5-
if PY2:
6-
from StringIO import StringIO # noqa
7-
else:
8-
from io import StringIO # noqa
9-
10-
111
def is_type_checking():
122
# type: () -> bool
133
try:
@@ -18,32 +8,3 @@ def is_type_checking():
188

199

2010
IS_TYPE_CHECKING = is_type_checking()
21-
22-
23-
if IS_TYPE_CHECKING:
24-
from typing import Text
25-
26-
27-
def to_env(text):
28-
# type: (Text) -> str
29-
"""
30-
Encode a string the same way whether it comes from the environment or a `.env` file.
31-
"""
32-
if PY2:
33-
return text.encode(sys.getfilesystemencoding() or "utf-8")
34-
else:
35-
return text
36-
37-
38-
def to_text(string):
39-
# type: (str) -> Text
40-
"""
41-
Make a string Unicode if it isn't already.
42-
43-
This is useful for defining raw unicode strings because `ur"foo"` isn't valid in
44-
Python 3.
45-
"""
46-
if PY2:
47-
return string.decode("utf-8")
48-
else:
49-
return string

src/dotenv/main.py

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from collections import OrderedDict
1111
from contextlib import contextmanager
1212

13-
from .compat import IS_TYPE_CHECKING, PY2, StringIO, to_env
13+
from .compat import IS_TYPE_CHECKING
1414
from .parser import Binding, parse_stream
1515
from .variables import parse_variables
1616

@@ -24,11 +24,6 @@
2424
else:
2525
_PathLike = Text
2626

27-
if sys.version_info >= (3, 0):
28-
_StringIO = StringIO
29-
else:
30-
_StringIO = StringIO[Text]
31-
3227

3328
def with_warn_for_invalid_lines(mappings):
3429
# type: (Iterator[Binding]) -> Iterator[Binding]
@@ -44,8 +39,8 @@ def with_warn_for_invalid_lines(mappings):
4439
class DotEnv():
4540

4641
def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True, override=True):
47-
# type: (Union[Text, _PathLike, _StringIO], bool, Union[None, Text], bool, bool) -> None
48-
self.dotenv_path = dotenv_path # type: Union[Text,_PathLike, _StringIO]
42+
# type: (Union[Text, _PathLike, io.StringIO], bool, Union[None, Text], bool, bool) -> None
43+
self.dotenv_path = dotenv_path # type: Union[Text,_PathLike, io.StringIO]
4944
self._dict = None # type: Optional[Dict[Text, Optional[Text]]]
5045
self.verbose = verbose # type: bool
5146
self.encoding = encoding # type: Union[None, Text]
@@ -55,15 +50,15 @@ def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True,
5550
@contextmanager
5651
def _get_stream(self):
5752
# type: () -> Iterator[IO[Text]]
58-
if isinstance(self.dotenv_path, StringIO):
53+
if isinstance(self.dotenv_path, io.StringIO):
5954
yield self.dotenv_path
6055
elif os.path.isfile(self.dotenv_path):
6156
with io.open(self.dotenv_path, encoding=self.encoding) as stream:
6257
yield stream
6358
else:
6459
if self.verbose:
6560
logger.info("Python-dotenv could not find configuration file %s.", self.dotenv_path or '.env')
66-
yield StringIO('')
61+
yield io.StringIO('')
6762

6863
def dict(self):
6964
# type: () -> Dict[Text, Optional[Text]]
@@ -96,7 +91,7 @@ def set_as_environment_variables(self):
9691
if k in os.environ and not self.override:
9792
continue
9893
if v is not None:
99-
os.environ[to_env(k)] = to_env(v)
94+
os.environ[k] = v
10095

10196
return True
10297

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

282271
while frame.f_code.co_filename == current_file:
283272
assert frame.f_back is not None
@@ -304,7 +293,7 @@ def load_dotenv(
304293
interpolate=True,
305294
encoding="utf-8",
306295
):
307-
# type: (Union[Text, _PathLike, None], Optional[_StringIO], bool, bool, bool, Optional[Text]) -> bool # noqa
296+
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, bool, Optional[Text]) -> bool # noqa
308297
"""Parse a .env file and then load all the variables found as environment variables.
309298
310299
- *dotenv_path*: absolute or relative path to .env file.
@@ -335,7 +324,7 @@ def dotenv_values(
335324
interpolate=True,
336325
encoding="utf-8",
337326
):
338-
# type: (Union[Text, _PathLike, None], Optional[_StringIO], bool, bool, Optional[Text]) -> Dict[Text, Optional[Text]] # noqa: E501
327+
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, Optional[Text]) -> Dict[Text, Optional[Text]] # noqa: E501
339328
"""
340329
Parse a .env file and return its content as a dict.
341330

src/dotenv/parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import codecs
22
import re
33

4-
from .compat import IS_TYPE_CHECKING, to_text
4+
from .compat import IS_TYPE_CHECKING
55

66
if IS_TYPE_CHECKING:
77
from typing import ( # noqa:F401
@@ -12,7 +12,7 @@
1212

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

1717

1818
_newline = make_regex(r"(\r\n|\n|\r)")

tests/test_main.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from __future__ import unicode_literals
33

4+
import io
45
import logging
56
import os
67
import sys
@@ -11,7 +12,6 @@
1112
import sh
1213

1314
import dotenv
14-
from dotenv.compat import PY2, StringIO
1515

1616

1717
def test_set_key_no_file(tmp_path):
@@ -281,15 +281,12 @@ def test_load_dotenv_redefine_var_used_in_file_with_override(dotenv_file):
281281

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

286286
result = dotenv.load_dotenv(stream=stream)
287287

288288
assert result is True
289-
if PY2:
290-
assert os.environ == {"a": "à".encode(sys.getfilesystemencoding())}
291-
else:
292-
assert os.environ == {"a": "à"}
289+
assert os.environ == {"a": "à"}
293290

294291

295292
def test_load_dotenv_in_current_dir(tmp_path):
@@ -361,7 +358,7 @@ def test_dotenv_values_file(dotenv_file):
361358
)
362359
def test_dotenv_values_stream(env, string, interpolate, expected):
363360
with mock.patch.dict(os.environ, env, clear=True):
364-
stream = StringIO(string)
361+
stream = io.StringIO(string)
365362
stream.seek(0)
366363

367364
result = dotenv.dotenv_values(stream=stream, interpolate=interpolate)

tests/test_parser.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# -*- coding: utf-8 -*-
2+
import io
3+
24
import pytest
35

4-
from dotenv.compat import StringIO
56
from dotenv.parser import Binding, Original, parse_stream
67

78

@@ -166,6 +167,6 @@
166167
),
167168
])
168169
def test_parse_stream(test_input, expected):
169-
result = parse_stream(StringIO(test_input))
170+
result = parse_stream(io.StringIO(test_input))
170171

171172
assert list(result) == expected

0 commit comments

Comments
 (0)