code base 5000
code base 5000

Reputation: 4102

Determining Python Class' Type with Inherited Classes

I have multiple class that all inherit from a single base class, and here is a simple example:

class DataSource(object):
    pass
class TableDataSource(DataSource):
    pass

If I want to determine if these classes are of type DataSource, I figured I could do the following:

>>> tdl = TableDataSource()
>>> print tdl is DataSource
False

So I get back false here, how can I check if all my class that inherit from DataSource are datasource type objects without having to check for each class type specifically? It would make checking for object types easier for other functions down the road.

Thank you.

Upvotes: 1

Views: 88

Answers (2)

wheaties
wheaties

Reputation: 35970

The things about is is that it's testing to if the two objects reference the same thing. DataSource the class is an object. Hence, only something referencing DataSource itself would compare true. What you should use is isinstance like this:

  isinstance(x, DataSource)

Upvotes: 6

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Use isinstance:

>>> tdl = TableDataSource()
>>> isinstance(tdl, DataSource)
True

For classes use issubclass:

>>> issubclass(TableDataSource, DataSource)
True

Upvotes: 4

Related Questions