Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The fundamental types of Python – a diagram

DZone's Guide to

The fundamental types of Python – a diagram

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

 

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}