Search code examples
pythonclassinstances

Determine the type of a (not built in) class in python


I've got a grid representing a tessellation, which is a set of instances of the Polygon class (a class I made). I also have a Boundary class, which is the class representing the boundary of the simulation I'm running (another class I've made). Any line of any pentagon can either have two Polygon objects or a Polygon and a Boundary object as "parents" (an attribute which I've defined for the line class). The type of the object determines how I do certain computations.

So, in short, I need a way to tell which of two classes a particular variable is an instance of, where I've made both classes. When I call type(parent), I get:

 <type 'instance'>

How am I supposed to determine this?


Solution

  • The idiomatic way to perform typechecking in Python is to use isinstance:

    if isinstance(x, Boundary):
        # x is of type Boundary
    elif isinstance(x, Polygon):
        # x is of type Polygon
    

    Demo:

    >>> class Boundary:
    ...     pass
    ...
    >>> x = Boundary()
    >>> isinstance(x, Boundary)
    True
    >>>
    

    Note that doing type(x) is Boundary would also work, but it will not factor in inheritance like isinstance does.