DEV Community

ilija
ilija

Posted on • Updated on

Dotenv: Python app environment variable vs. Linux environment variable

When it comes to usage of dotenv inside our python scripts there is one important caveat: if you use Linux you can not use env names like HOME or NAME or LOGNAME. Because your app variables from .env file (in currently working directory) will be overwritten by the global one (from Linux).

For example: in case you put in .env NAME=Michale and you are logged in as user Daniel, inside your python script os.getenv("NAME") will return Daniel instead of Michael. And most probably this is not something you want in your app....

I guess there is different ways to resolve this but most obvious for me is to avoid this names entirely and to use some convention like APP_NAME or APP_HOME_DIR....

Example:

local .env used in our Python script

NAME=Michale
USER=Michale
Enter fullscreen mode Exit fullscreen mode

Linux NAME and USER var for currently logged user (you can check with for example os.environ.keys())

NAME=Daniel
USER=Daniel

Enter fullscreen mode Exit fullscreen mode

test_env.py

import os
from dotenv import load_dotenv

load_dotenv()

name = os.getenv("NAME")
user = os.getenv("USER")

print(name, user)

Enter fullscreen mode Exit fullscreen mode

$ Daniel, Daniel

At this point inside your script you will have something you don't want and potentially break your program...

Top comments (0)