The following Python code executes normally without raising an exception:
class Foo:
pass
class Foo:
pass
def bar():
pass
def bar():
pass
print(Foo.__module__ + Foo.__name__)
Yet clearly, there are multiple instances of __main__.Foo and __main__.bar. Why does Python not raise an error when it encounters this namespace collision? And since it doesn’t raise an error, what exactly is it doing? Is the first class __main__.Foo replaced by the second class __main__.Foo?
In Python everything is an object – instance of some type. E.g.
1is an instance of typeint,def foo(): passcreates objectfoowhich is an instance of typefunction(same for classes – objects, created byclassstatement are instances of typetype). Given this, there no difference (at the level of name binding mechanism) betweenand
BTW, class definition may be performed using
typefunction (yeah, there is typetypeand built-in functiontype):So classes and functions are not some different kind of data, although special syntax may be used for creating their instances.
See also related Data Model section.