See if type meta object is an instance of another class

Question:

I’m wondering if there’s a way of seeing whether a class is inherited from another class based on the type object for a given object.

Say I have the class MyList as defined below:

class MyList(list):
    pass

Now consider the following:

>>> my_list = MyList()
>>> type(my_list).__name__
'MyList'
>>> isinstance(my_list, list)
True  # as expected
>>> isinstance(type(my_list), list)
False  # how can I get this to be True?

So my questions are:

  1. What is a pythonic way of seeing whether the type object for a class is an instance of (inherited from) another class?
  2. Can you retrieve the class of an object based on the type metaclass instance for it? I would imagine this as something like type(my_list).class
Asked By: Ethan Posner

||

Answers:

Purely as a pro-forma action

The solution is to use issubclass():

>>> class MyList(list):
...     pass
...
>>> my_list = MyList()
>>> issubclass(MyList, list)
True
>>> issubclass(my_list.__class__, list)
True
Answered By: sj95126
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.