If I print os.environ
, the output looks like a dictionary. Some posts I read online say that it is a memory based dictionary.
But it does not support .viewkeys()
method and tells me that: _Environ instance does not support this method
. So what is the exact type of os.environ
. If I try:
print type(os.environ)
I get instance
as the answer.
Can please clarify this behavior of os.environ
?
os. environ is a mapping object.
This module provides a portable way of using operating system dependent functionality. os. environ in Python is a mapping object that represents the user's environmental variables. It returns a dictionary having user's environmental variable as key and their values as value.
environ. get() – If the key does not exist, it returns None or default value. os. getenv() – If the key does not exist, it returns None or default value.
environ. setdefault(key, default) is guaranteed to modify the dictionary exactly the same way as os. environ[key] = os. environ.
>>> os.environ.__class__
<class os._Environ at 0xb7865e6c>
It is a subclass of UserDict.IterableUserDict.
In python 2.7 the source can be found is in os.py on line 413 (Windows) and line 466 (Posix). Here is the python 3.2 source.
It is an os._Environ
instance:
>>> os.environ.__class__
<class os._Environ at 0x01DDA928>
It is defined in Python's library, file os.py
and cannot be a plain dictionary because updating the dictionary must also update the process's environment. Also the key lookups need to be case insensitive on Windows.
In Python 2.x it subclasses UserDict.IterableUserDict
which presumably doesn't have the new viewkeys()
method. In Python 3.x it implements the MutableMapping
abc but has no other explicit base classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With