The Python Oracle

Difference between os.getenv and os.environ.get

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Difference Between Os.Getenv And Os.Environ.Get
00:20 Accepted Answer Score 232
00:48 Answer 2 Score 198
01:10 Answer 3 Score 55
01:33 Answer 4 Score 13
01:46 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