· coding  · 1 min read

Environment Variables in Python

Python code reference and cookbook.

Python code reference and cookbook.

Q: Difference between os.getenv and os.environ

When the environment variable has been set, there is no difference.

$ python -m timeit -s 'import os' 'os.environ.get("ENV_VAR_FOO")'
200000 loops, best of 5: 1.65 usec per loop

$ python -m timeit -s 'import os' 'os.getenv("ENV_VAR_FOO")'
200000 loops, best of 5: 1.83 usec per loop

os.environ is of the built-in type _Environ, which is a MutableMapping.

from _collections_abc import MutableMapping
class _Environ(MutableMapping):
  ...

In other words, os.environ is a dictionary. Its keys-value pairs are formed by your environment variables.

import dotenv # poetry add python-dotenv

dotenv.load_dotenv()
Back to Blog

Related Posts

View All Posts »