Skip to content

Commit

Permalink
Fix docstring for load_dotenv
Browse files Browse the repository at this point in the history
The docstring for load_dotenv was missing a word, rendering it confusing.
This commits modifies it for clarity.
  • Loading branch information
larsks committed Mar 15, 2022
1 parent 3832011 commit 9047c6a
Showing 1 changed file with 27 additions and 23 deletions.
50 changes: 27 additions & 23 deletions src/dotenv/main.py
Expand Up @@ -6,8 +6,7 @@
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from typing import (IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple,
Union)
from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union

from .parser import Binding, parse_stream
from .variables import parse_variables
Expand All @@ -30,7 +29,7 @@ def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding
yield mapping


class DotEnv():
class DotEnv:
def __init__(
self,
dotenv_path: Optional[Union[str, _PathLike]],
Expand Down Expand Up @@ -59,9 +58,9 @@ def _get_stream(self) -> Iterator[IO[str]]:
if self.verbose:
logger.info(
"Python-dotenv could not find configuration file %s.",
self.dotenv_path or '.env',
self.dotenv_path or ".env",
)
yield io.StringIO('')
yield io.StringIO("")

def dict(self) -> Dict[str, Optional[str]]:
"""Return dotenv as dict"""
Expand All @@ -71,7 +70,9 @@ def dict(self) -> Dict[str, Optional[str]]:
raw_values = self.parse()

if self.interpolate:
self._dict = OrderedDict(resolve_variables(raw_values, override=self.override))
self._dict = OrderedDict(
resolve_variables(raw_values, override=self.override)
)
else:
self._dict = OrderedDict(raw_values)

Expand All @@ -96,8 +97,7 @@ def set_as_environment_variables(self) -> bool:
return True

def get(self, key: str) -> Optional[str]:
"""
"""
""" """
data = self.dict()

if key in data:
Expand Down Expand Up @@ -131,7 +131,9 @@ def rewrite(
if not os.path.isfile(path):
with io.open(path, "w+", encoding=encoding) as source:
source.write("")
with tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding) as dest:
with tempfile.NamedTemporaryFile(
mode="w+", delete=False, encoding=encoding
) as dest:
with io.open(path, encoding=encoding) as source:
yield (source, dest) # type: ignore
except BaseException:
Expand Down Expand Up @@ -159,17 +161,16 @@ def set_key(
if quote_mode not in ("always", "auto", "never"):
raise ValueError("Unknown quote_mode: {}".format(quote_mode))

quote = (
quote_mode == "always"
or (quote_mode == "auto" and not value_to_set.isalnum())
quote = quote_mode == "always" or (
quote_mode == "auto" and not value_to_set.isalnum()
)

if quote:
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
else:
value_out = value_to_set
if export:
line_out = 'export {}={}\n'.format(key_to_set, value_out)
line_out = "export {}={}\n".format(key_to_set, value_out)
else:
line_out = "{}={}\n".format(key_to_set, value_out)

Expand Down Expand Up @@ -216,7 +217,9 @@ def unset_key(
dest.write(mapping.original.string)

if not removed:
logger.warning("Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path)
logger.warning(
"Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path
)
return None, key_to_unset

return removed, key_to_unset
Expand Down Expand Up @@ -252,7 +255,7 @@ def _walk_to_root(path: str) -> Iterator[str]:
Yield directories starting from the given directory up to the root
"""
if not os.path.exists(path):
raise IOError('Starting path not found')
raise IOError("Starting path not found")

if os.path.isfile(path):
path = os.path.dirname(path)
Expand All @@ -266,7 +269,7 @@ def _walk_to_root(path: str) -> Iterator[str]:


def find_dotenv(
filename: str = '.env',
filename: str = ".env",
raise_error_if_not_found: bool = False,
usecwd: bool = False,
) -> str:
Expand All @@ -277,11 +280,11 @@ def find_dotenv(
"""

def _is_interactive():
""" Decide whether this is running in a REPL or IPython notebook """
main = __import__('__main__', None, None, fromlist=['__file__'])
return not hasattr(main, '__file__')
"""Decide whether this is running in a REPL or IPython notebook"""
main = __import__("__main__", None, None, fromlist=["__file__"])
return not hasattr(main, "__file__")

if usecwd or _is_interactive() or getattr(sys, 'frozen', False):
if usecwd or _is_interactive() or getattr(sys, "frozen", False):
# Should work without __file__, e.g. in REPL or IPython notebook.
path = os.getcwd()
else:
Expand All @@ -301,9 +304,9 @@ def _is_interactive():
return check_path

if raise_error_if_not_found:
raise IOError('File not found')
raise IOError("File not found")

return ''
return ""


def load_dotenv(
Expand All @@ -325,7 +328,8 @@ def load_dotenv(
in `.env` file. Defaults to `False`.
- *encoding*: encoding to be used to read the file.
If both `dotenv_path` and `stream`, `find_dotenv()` is used to find the .env file.
If neither `dotenv_path` nor `stream` are provided, `find_dotenv()` is used
to find the .env file.
"""
if dotenv_path is None and stream is None:
dotenv_path = find_dotenv()
Expand Down

0 comments on commit 9047c6a

Please sign in to comment.