Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 591
Sumod Avatar asked Feb 13 '12 09:02

Sumod


People also ask

What is type of OS environ?

os. environ is a mapping object.

What does OS environ mean?

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.

What is the difference between OS Getenv and OS environ get?

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.

What does OS environ Setdefault do?

environ. setdefault(key, default) is guaranteed to modify the dictionary exactly the same way as os. environ[key] = os. environ.


2 Answers

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

like image 130
Lauritz V. Thaulow Avatar answered Sep 29 '22 08:09

Lauritz V. Thaulow


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.

like image 22
Duncan Avatar answered Sep 29 '22 06:09

Duncan