Eli's favorite programming languages are Python and C. He's also proficient in C++, and has various levels of familiarity with Perl, Java, Ruby, Javascript, Common Lisp, Scheme, Ada and a few assembly languages. Eli is a DZone MVB and is not an employee of DZone and has posted 38 posts at DZone. You can read more from them at their website. View Full User Profile

The fundamental types of Python – a diagram

04.05.2012
| 5079 views |
  • submit to reddit

The aim of this post is to present a succinct diagram that correlates some basic properties of all Python objects with the fundamental types type and object. This is not a tutorial – it’s more of a reference snapshot that puts things in order. To properly understand why things are the way they are, check out the existing and future writings in the Python internals category of this blog, as well as other resources available online.

In Python, every object has a type. Types are also objects – rather special objects. A type object, like any other object, has a type of its own. It also has a sequence of "base types" – in other words, types from which it inherits. This is unlike non-type objects, which don’t have base types.

Consider this exemplary piece of code (Python 3):

# Some types
class Base:
    pass

class Klass(Base):
    pass

class Meta(type):
    pass

class KlassWithMeta(metaclass=Meta):
    pass

# Non-types
kwm = KlassWithMeta()
mylist = []

The following diagram describes the types and bases of all the objects created in this code. Non-type objects only have types and no bases:

http://eli.thegreenplace.net/wp-content/uploads/2012/04/typediagram.png

Some interesting things to note:

  • The default type of all new types is type. This can be overridden by explicitly specifying the metaclass for a type.
  • Built-in types like list and user-defined types like Base are equivalent as far as Python is concerned.
  • The special type type is the default type of all objects – including itself. It is an object, and as such, inherits from object.
  • The special type object is the pinnacle of every inheritance hierarchy – it’s the ultimate base type of all Python types.
  • type and object are the only types in Python that really stand out from other types (and hence they are colored differently). type is its own type. object has no base type.

 

Published at DZone with permission of Eli Bendersky, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)