[Tutor] Some "type" confusion...

Kent Johnson kent37 at tds.net
Tue Jan 23 14:11:05 CET 2007


Gizmo wrote:
> Hello
> I am learning Python via the excellent Dive Into Python book. I have 
> little question
> 
> 1)
>  >>> import os
>  >>> type(os.environ)
> <type 'instance'>
> 
> Why is this considered "instance" ? Should'nt it be "dict" type?
> I have a feeling I am missing something deeper here.

'instance' is the type of instances of old-style classes. For example:

In [4]: class Foo: pass
    ...:

In [6]: f=Foo()

In [7]: type(f)
Out[7]: <type 'instance'>

On the other hand, the type of an instance of a new-style class reflects 
its actual class:

In [9]: class Bar(object): pass
    ...:

In [10]: b=Bar()

In [11]: type(b)
Out[11]: <class '__main__.Bar'>

You can find out the class of an instance by looking at its __class__ 
attribute:
In [3]: os.environ.__class__
Out[3]: <class os._Environ at 0x00B42F30>

You can also see the base classes of the class:
In [8]: os.environ.__class__.__bases__
Out[8]: (<class UserDict.IterableUserDict at 0x00B4E1E0>,)

So os.environ is not a dict or a subclass of dict. It is a subclass of 
UserDict.IterableUserDict. This is a class that is used to make custom 
mapping objects.

If you look at the docs for os.environ you see that it does not say it 
is a dict, it says it is a mapping object; that is, it is something that 
acts like a dict.

See also http://docs.python.org/ref/node33.html

> 2) What would happen if I did this
>  >>> os.environ = {}
> Hopefully, I wont be allowed to do that...but I am too scared to try.

You can do it. That would replace the os.environ object with an empty 
dict, which would have a bad effect on any code that reads values from 
os.environ. On the other hand you can restore the old value just by 
restarting Python so it is not such a disaster.

Kent



More information about the Tutor mailing list