The Python Oracle

Difference between os.getenv and os.environ.get

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Difference Between Os.Getenv And Os.Environ.Get
00:23 Accepted Answer Score 222
00:55 Answer 2 Score 182
01:23 Answer 3 Score 66
02:20 Answer 4 Score 55
02:47 Answer 5 Score 9
03:04 Thank you

--

Full question
https://stackoverflow.com/questions/1692...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #environmentvariables #pythonos

#avk47



ACCEPTED ANSWER

Score 232


See this related thread. Basically, os.environ is found on import, and os.getenv is a wrapper to os.environ.get, at least in CPython.

EDIT: To respond to a comment, in CPython, os.getenv is basically a shortcut to os.environ.get ; since os.environ is loaded at import of os, and only then, the same holds for os.getenv.




ANSWER 2

Score 198


One difference (observed in Python 2.7 and 3.8) between getenv() and environ[]:

  • os.getenv() does not raise an exception, but returns None
  • os.environ.get() similarly returns None
  • os.environ[] raises an exception if the environmental variable does not exist



ANSWER 3

Score 55


In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.




ANSWER 4

Score 13


In addition to the answers above:

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

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

EDIT: meaning, no difference