Skip to content

Commit

Permalink
Stop raising UserWarning if .env file isn't found
Browse files Browse the repository at this point in the history
Currently, if a `.env` file isn't found by the read_env() classmethod,
it raises a UserWarning. Based on Python's logging guide,
warnings.warn() is only appropriate to be raised in library code if the
issue is avoidable and the client application should be modified to
eliminate the warning.

Conversely, it recommends logging.warning() if there is nothing the
client application can do about the situation, but the event should
still be noted (see ref1).

In this particular case, the function is working with `.env` files that
should only ever exist in development environments, which means that
the function will erroneously warn the consumer in production and
staging environments.

With this in mind, I believe the most sensible thing to do would be to
convert read_env from using the warnings module to using the logging
module. Additionally, since the lack of a `.env` file is going to occur
regularly during normal operation of the program, I also believe that
this should be downgraded to an INFO level message from a WARNING
level message.

joke2k#243 requests that the .env file be made
optional, and as far as I can the .env file is indeed optional, it's
just that a UserWarning is being raised instead of a logged message.
With that in mind, I'm referencing it as being closed by this change.

ref1: https://docs.python.org/3/howto/logging.html#when-to-use-logging

fixes: joke2k#243
  • Loading branch information
birdcar committed Mar 19, 2020
1 parent dc2d281 commit a5e1072
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions environ/environ.py
Expand Up @@ -636,7 +636,7 @@ def read_env(cls, env_file=None, **overrides):
frame = sys._getframe()
env_file = os.path.join(os.path.dirname(frame.f_back.f_code.co_filename), '.env')
if not os.path.exists(env_file):
warnings.warn(
logger.info(
"%s doesn't exist - if you're not configuring your "
"environment separately, create one." % env_file)
return
Expand All @@ -645,8 +645,8 @@ def read_env(cls, env_file=None, **overrides):
with open(env_file) if isinstance(env_file, basestring) else env_file as f:
content = f.read()
except IOError:
warnings.warn(
"Error reading %s - if you're not configuring your "
logger.info(
"%s not found - if you're not configuring your "
"environment separately, check this." % env_file)
return

Expand Down

0 comments on commit a5e1072

Please sign in to comment.