What does type() return for imported classes?

Question

In this exercise, the type() function returns __main__ for classes defined in the current script. What does it return for classes that are imported?

Answer

The type() command returns the namespace and class for the object provided. For classes defined in the local file, the namespace will be reported as __main__. For classes imported from other modules, the namespace reported will be the same as the module. The following code example shows, the results from type() on objects created from two different modules.

from collections import OrderedDict

mycoll = OrderedDict()

print(type(mycoll))
# <class 'collections.OrderedDict'>


from calendar import Calendar

mycal = Calendar()

print(type(mycal))
# <class 'calendar.Calendar'>
7 Likes

No it doesn’t…

5 Likes
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
...   pass
... 
>>> myobj = MyClass()
>>> print(type(myobj))
<class '__main__.MyClass'>
1 Like

That’s a class, __main__ is a module

>>> import __main__
>>> class MyClass:
...     pass
...
>>> type(MyClass()) is __main__
False

type doesn’t behave differently because something was imported.
type returns the type of the object passed to it

>>> type(MyClass()) is MyClass
True
>>> __main__
<module '__main__' (<_frozen_importlib_external.SourceFileLoader object at 0x7f7b747e3b70>)>
15 Likes