Difference between os.getenv and os.environ.get

André Staltz picture André Staltz · Jun 4, 2013 · Viewed 144k times · Source

Is there any difference at all between both approaches?

>>> os.getenv('TERM')
'xterm'
>>> os.environ.get('TERM')
'xterm'

>>> os.getenv('FOOBAR', "not found") == "not found"
True
>>> os.environ.get('FOOBAR', "not found") == "not found"
True

They seem to have the exact same functionality.

Answer

W. Conrad Walden picture W. Conrad Walden · Jun 4, 2013

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.