Difference between os.getenv and os.environ.get
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:26 Accepted answer (Score 183)
01:03 Answer 2 (Score 146)
01:33 Answer 3 (Score 55)
02:49 Answer 4 (Score 52)
03:14 Thank you
--
Full question
https://stackoverflow.com/questions/1692...
Accepted answer links:
[this related thread]: https://stackoverflow.com/questions/1095...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #environmentvariables #pythonos
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:26 Accepted answer (Score 183)
01:03 Answer 2 (Score 146)
01:33 Answer 3 (Score 55)
02:49 Answer 4 (Score 52)
03:14 Thank you
--
Full question
https://stackoverflow.com/questions/1692...
Accepted answer links:
[this related thread]: https://stackoverflow.com/questions/1095...
--
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 Noneos.environ.get()similarly returns Noneos.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