Sumod
Sumod

Reputation: 3846

What is the type of os.environ? and Why does it not support viewkeys method

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?

Upvotes: 5

Views: 5166

Answers (5)

Basil Musa
Basil Musa

Reputation: 8738

To iterate through it, first convert it to a dictionary by doing this:

environment_items = dict(**os.environ)

for env_key in environment_items:
    print(env_key, environment_items[env_key])

Upvotes: 0

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 51015

>>> 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.

Upvotes: 5

Duncan
Duncan

Reputation: 95722

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.

Upvotes: 4

avasal
avasal

Reputation: 14864

os.environ is instance of a class,

try:

os.environ.__dict__

it will give you all it's attributes..

Upvotes: -1

shadyabhi
shadyabhi

Reputation: 17234

os.environ is a mapping object. dict is a type of mapping object & os.environ is not a dict. Makes sense?

Upvotes: 0

Related Questions