[Tutor] The Whole Tree

Steven D'Aprano steve at pearwood.info
Sun Jun 16 21:17:24 CEST 2013


On 17/06/13 03:21, Jim Mooney wrote:
> My first impression of Python was that it had dynamic types but didn't
> mix them. so if I was wrong on equality, is there a general rule of
> what different types can still be equal? Is it an inheritance thing?

The general rule is, types can define equality whatever way makes sense for themselves. That usually means:

* All numeric types are normally considered compatible; that is,
   if two numbers have the same numeric value, they should compare
   equal even if they have different types.

* Instances of a class and any of its subclasses are expected to
   compare equal if they have the same value.

* Unrelated classes are expected to compare unequal.

* By default, objects compare equal only to themselves.

* But equality is under the programmer's control with the __eq__
   and __ne__ (equal and not-equal) methods.


> Speaking of which, I put "Python class hierarchy" in Google but just
> got a bunch of specific wheeze. What I want is a
> list of the whole tree. Is there such, or a way I can generate it?

It's a pretty shallow tree. Off the top of my head, the built-ins look something like this in Python 3:


object
+-- BaseException
     +-- a bunch of exception subclasses
+-- BuiltinFunctionType (*)
+-- bytearray
+-- bytes
+-- CodeType (*)
+-- complex
+-- dict
+-- float
+-- frozenset
+-- FunctionType (*)
+-- int
     +-- bool
+-- list
+-- NoneType (*)
+-- range
+-- set
+-- str
+-- tuple
+-- type


plus some more exotic built-ins, which I haven't shown. Items marked (*) are built-in types, but you need to import them from the types module to get access to them by name.

Nearly all other classes and types inherit directly from object, Python doesn't usually go in for the sort of deeply nested hierarchies that Java loves.

However, there is a complication: ABCs (Abstract Base Classes). ABCs introduce something of a hierarchy to Python objects, one which is not reflected by the (shallow) inheritance hierarchy shown above. ABCs can be considered relatively advanced, so don't worry about them if you don't wish to.

As far as I know, there is no documented tree of *all* Python types in the standard library. It would be big, boring, shallow, and contain an awful lot types which are for internal use only and not useable by the programmer.


-- 
Steven


More information about the Tutor mailing list