Skip to content

Commit 4590015

Browse files
committed
Use Python 3 type hints for functions
Unfortunately, we can't do the same for variables as that is only supported in Python 3.6+.
1 parent 1914bac commit 4590015

File tree

5 files changed

+98
-127
lines changed

5 files changed

+98
-127
lines changed

src/dotenv/__init__.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@
44
unset_key)
55

66

7-
def load_ipython_extension(ipython):
8-
# type: (Any) -> None
7+
def load_ipython_extension(ipython: Any) -> None:
98
from .ipython import load_ipython_extension
109
load_ipython_extension(ipython)
1110

1211

13-
def get_cli_string(path=None, action=None, key=None, value=None, quote=None):
14-
# type: (Optional[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> str
12+
def get_cli_string(
13+
path: Optional[str] = None,
14+
action: Optional[str] = None,
15+
key: Optional[str] = None,
16+
value: Optional[str] = None,
17+
quote: Optional[str] = None,
18+
):
1519
"""Returns a string suitable for running as a shell script.
1620
1721
Useful for converting a arguments passed to a fabric task

src/dotenv/cli.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
help="Whether to write the dot file as an executable bash script.")
2727
@click.version_option(version=__version__)
2828
@click.pass_context
29-
def cli(ctx, file, quote, export):
30-
# type: (click.Context, Any, Any, Any) -> None
29+
def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None:
3130
'''This script is used to set, get or unset values from a .env file.'''
3231
ctx.obj = {}
3332
ctx.obj['QUOTE'] = quote
@@ -37,8 +36,7 @@ def cli(ctx, file, quote, export):
3736

3837
@cli.command()
3938
@click.pass_context
40-
def list(ctx):
41-
# type: (click.Context) -> None
39+
def list(ctx: click.Context) -> None:
4240
'''Display all the stored key/value.'''
4341
file = ctx.obj['FILE']
4442
if not os.path.isfile(file):
@@ -55,8 +53,7 @@ def list(ctx):
5553
@click.pass_context
5654
@click.argument('key', required=True)
5755
@click.argument('value', required=True)
58-
def set(ctx, key, value):
59-
# type: (click.Context, Any, Any) -> None
56+
def set(ctx: click.Context, key: Any, value: Any) -> None:
6057
'''Store the given key/value.'''
6158
file = ctx.obj['FILE']
6259
quote = ctx.obj['QUOTE']
@@ -71,8 +68,7 @@ def set(ctx, key, value):
7168
@cli.command()
7269
@click.pass_context
7370
@click.argument('key', required=True)
74-
def get(ctx, key):
75-
# type: (click.Context, Any) -> None
71+
def get(ctx: click.Context, key: Any) -> None:
7672
'''Retrieve the value for the given key.'''
7773
file = ctx.obj['FILE']
7874
if not os.path.isfile(file):
@@ -90,8 +86,7 @@ def get(ctx, key):
9086
@cli.command()
9187
@click.pass_context
9288
@click.argument('key', required=True)
93-
def unset(ctx, key):
94-
# type: (click.Context, Any) -> None
89+
def unset(ctx: click.Context, key: Any) -> None:
9590
'''Removes the given key.'''
9691
file = ctx.obj['FILE']
9792
quote = ctx.obj['QUOTE']
@@ -110,8 +105,7 @@ def unset(ctx, key):
110105
help="Override variables from the environment file with those from the .env file.",
111106
)
112107
@click.argument('commandline', nargs=-1, type=click.UNPROCESSED)
113-
def run(ctx, override, commandline):
114-
# type: (click.Context, bool, List[str]) -> None
108+
def run(ctx: click.Context, override: bool, commandline: List[str]) -> None:
115109
"""Run command with environment variables present."""
116110
file = ctx.obj['FILE']
117111
if not os.path.isfile(file):
@@ -132,8 +126,7 @@ def run(ctx, override, commandline):
132126
exit(ret)
133127

134128

135-
def run_command(command, env):
136-
# type: (List[str], Dict[str, str]) -> int
129+
def run_command(command: List[str], env: Dict[str, str]) -> int:
137130
"""Run command in sub process.
138131
139132
Runs the command in a sub process with the variables from `env`

src/dotenv/main.py

Lines changed: 51 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@
2020
_PathLike = Text
2121

2222

23-
def with_warn_for_invalid_lines(mappings):
24-
# type: (Iterator[Binding]) -> Iterator[Binding]
23+
def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding]:
2524
for mapping in mappings:
2625
if mapping.error:
2726
logger.warning(
@@ -32,9 +31,14 @@ def with_warn_for_invalid_lines(mappings):
3231

3332

3433
class DotEnv():
35-
36-
def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True, override=True):
37-
# type: (Union[Text, _PathLike, io.StringIO], bool, Union[None, Text], bool, bool) -> None
34+
def __init__(
35+
self,
36+
dotenv_path: Union[Text, _PathLike, io.StringIO],
37+
verbose: bool = False,
38+
encoding: Union[None, Text] = None,
39+
interpolate: bool = True,
40+
override: bool = True,
41+
) -> None:
3842
self.dotenv_path = dotenv_path # type: Union[Text,_PathLike, io.StringIO]
3943
self._dict = None # type: Optional[Dict[Text, Optional[Text]]]
4044
self.verbose = verbose # type: bool
@@ -43,8 +47,7 @@ def __init__(self, dotenv_path, verbose=False, encoding=None, interpolate=True,
4347
self.override = override # type: bool
4448

4549
@contextmanager
46-
def _get_stream(self):
47-
# type: () -> Iterator[IO[Text]]
50+
def _get_stream(self) -> Iterator[IO[Text]]:
4851
if isinstance(self.dotenv_path, io.StringIO):
4952
yield self.dotenv_path
5053
elif os.path.isfile(self.dotenv_path):
@@ -55,8 +58,7 @@ def _get_stream(self):
5558
logger.info("Python-dotenv could not find configuration file %s.", self.dotenv_path or '.env')
5659
yield io.StringIO('')
5760

58-
def dict(self):
59-
# type: () -> Dict[Text, Optional[Text]]
61+
def dict(self) -> Dict[Text, Optional[Text]]:
6062
"""Return dotenv as dict"""
6163
if self._dict:
6264
return self._dict
@@ -70,15 +72,13 @@ def dict(self):
7072

7173
return self._dict
7274

73-
def parse(self):
74-
# type: () -> Iterator[Tuple[Text, Optional[Text]]]
75+
def parse(self) -> Iterator[Tuple[Text, Optional[Text]]]:
7576
with self._get_stream() as stream:
7677
for mapping in with_warn_for_invalid_lines(parse_stream(stream)):
7778
if mapping.key is not None:
7879
yield mapping.key, mapping.value
7980

80-
def set_as_environment_variables(self):
81-
# type: () -> bool
81+
def set_as_environment_variables(self) -> bool:
8282
"""
8383
Load the current dotenv as system environment variable.
8484
"""
@@ -90,8 +90,7 @@ def set_as_environment_variables(self):
9090

9191
return True
9292

93-
def get(self, key):
94-
# type: (Text) -> Optional[Text]
93+
def get(self, key: Text) -> Optional[Text]:
9594
"""
9695
"""
9796
data = self.dict()
@@ -105,8 +104,7 @@ def get(self, key):
105104
return None
106105

107106

108-
def get_key(dotenv_path, key_to_get):
109-
# type: (Union[Text, _PathLike], Text) -> Optional[Text]
107+
def get_key(dotenv_path: Union[Text, _PathLike], key_to_get: Text) -> Optional[Text]:
110108
"""
111109
Gets the value of a given key from the given .env
112110
@@ -116,8 +114,7 @@ def get_key(dotenv_path, key_to_get):
116114

117115

118116
@contextmanager
119-
def rewrite(path):
120-
# type: (_PathLike) -> Iterator[Tuple[IO[Text], IO[Text]]]
117+
def rewrite(path: _PathLike) -> Iterator[Tuple[IO[Text], IO[Text]]]:
121118
try:
122119
if not os.path.isfile(path):
123120
with io.open(path, "w+") as source:
@@ -133,8 +130,13 @@ def rewrite(path):
133130
shutil.move(dest.name, path)
134131

135132

136-
def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always", export=False):
137-
# type: (_PathLike, Text, Text, Text, bool) -> Tuple[Optional[bool], Text, Text]
133+
def set_key(
134+
dotenv_path: _PathLike,
135+
key_to_set: Text,
136+
value_to_set: Text,
137+
quote_mode: Text = "always",
138+
export: bool = False,
139+
) -> Tuple[Optional[bool], Text, Text]:
138140
"""
139141
Adds or Updates a key/value to the given .env
140142
@@ -172,8 +174,11 @@ def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always", export=F
172174
return True, key_to_set, value_to_set
173175

174176

175-
def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
176-
# type: (_PathLike, Text, Text) -> Tuple[Optional[bool], Text]
177+
def unset_key(
178+
dotenv_path: _PathLike,
179+
key_to_unset: Text,
180+
quote_mode: Text = "always",
181+
) -> Tuple[Optional[bool], Text]:
177182
"""
178183
Removes a given key from the given .env
179184
@@ -199,9 +204,10 @@ def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
199204
return removed, key_to_unset
200205

201206

202-
def resolve_variables(values, override):
203-
# type: (Iterable[Tuple[Text, Optional[Text]]], bool) -> Mapping[Text, Optional[Text]]
204-
207+
def resolve_variables(
208+
values: Iterable[Tuple[Text, Optional[Text]]],
209+
override: bool,
210+
) -> Mapping[Text, Optional[Text]]:
205211
new_values = {} # type: Dict[Text, Optional[Text]]
206212

207213
for (name, value) in values:
@@ -223,8 +229,7 @@ def resolve_variables(values, override):
223229
return new_values
224230

225231

226-
def _walk_to_root(path):
227-
# type: (Text) -> Iterator[Text]
232+
def _walk_to_root(path: Text) -> Iterator[Text]:
228233
"""
229234
Yield directories starting from the given directory up to the root
230235
"""
@@ -242,8 +247,11 @@ def _walk_to_root(path):
242247
last_dir, current_dir = current_dir, parent_dir
243248

244249

245-
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
246-
# type: (Text, bool, bool) -> Text
250+
def find_dotenv(
251+
filename: Text = '.env',
252+
raise_error_if_not_found: bool = False,
253+
usecwd: bool = False,
254+
) -> Text:
247255
"""
248256
Search in increasingly higher folders for the given file
249257
@@ -281,14 +289,13 @@ def _is_interactive():
281289

282290

283291
def load_dotenv(
284-
dotenv_path=None,
285-
stream=None,
286-
verbose=False,
287-
override=False,
288-
interpolate=True,
289-
encoding="utf-8",
290-
):
291-
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, bool, Optional[Text]) -> bool # noqa
292+
dotenv_path: Union[Text, _PathLike, None] = None,
293+
stream: Optional[io.StringIO] = None,
294+
verbose: bool = False,
295+
override: bool = False,
296+
interpolate: bool = True,
297+
encoding: Optional[Text] = "utf-8",
298+
) -> bool:
292299
"""Parse a .env file and then load all the variables found as environment variables.
293300
294301
- *dotenv_path*: absolute or relative path to .env file.
@@ -313,13 +320,12 @@ def load_dotenv(
313320

314321

315322
def dotenv_values(
316-
dotenv_path=None,
317-
stream=None,
318-
verbose=False,
319-
interpolate=True,
320-
encoding="utf-8",
321-
):
322-
# type: (Union[Text, _PathLike, None], Optional[io.StringIO], bool, bool, Optional[Text]) -> Dict[Text, Optional[Text]] # noqa: E501
323+
dotenv_path: Union[Text, _PathLike, None] = None,
324+
stream: Optional[io.StringIO] = None,
325+
verbose: bool = False,
326+
interpolate: bool = True,
327+
encoding: Optional[Text] = "utf-8",
328+
) -> Dict[Text, Optional[Text]]:
323329
"""
324330
Parse a .env file and return its content as a dict.
325331

0 commit comments

Comments
 (0)