Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class object

Tags:

python

Is it possible in python to check if an object is a class object. IE if you have

class Foo(object):
    pass

How could you check if o is Foo (or some other class) or an instance of Foo (or any other class instance)? In Java this would be a simple matter. Just check if the object is an instance of Class. Is there something similar in python or are you supposed to just not care?

Slight clarification: I'm trying to make a function that prints information about the parameter its given. So if you pass in o, where o = Foo() it prints out information about Foo. If you pass in Foo it should print out the exact same information. Not information about Type.

like image 987
Cadyyan Avatar asked Aug 28 '13 22:08

Cadyyan


2 Answers

Use the isinstance builtin function.

>>> o = Foo()
>>> isinstance(o, Foo)
True
>>> isinstance(13, Foo)
False

This also works for subclasses:

>>> class Bar(Foo): pass

>>> b = Bar()
>>> isinstance(b, Foo)
True
>>> isinstance(b, Bar)
True

Yes, normally, you are supposed to not particularly care what type the object is. Instead, you just call the method you want on o so that people can plug in arbitrary objects that conform to your interface. This wouldn't be possible if you were to aggressively check the types of objects that you're using. This principle is called duck typing, and allows you a bit more freedom in how you choose to write your code.

Python is pragmatic though, so feel free to use isinstance if it makes sense for your particular program.

Edit:

To check if some variable is a class vs an instance, you can do this:

>>> isinstance(Foo, type)   # returns true if the variable is a type.
True
>>> isinstance(o, type)
False
like image 152
Michael0x2a Avatar answered Oct 12 '22 13:10

Michael0x2a


My end goal is to make a function that prints out information about an object if its an instance and print something different if its a class. So this time I do care.

First, understand that classes are instances — they're instances of type:

>>> class Foo(object):
...     pass
...
>>> isinstance(Foo, type)
True

So, you can pick out classes that way, but keep in mind that classes are instances too. (And thus, you can pass classes to functions, return them from functions store them in lists, create the on the fly…)

like image 42
Thanatos Avatar answered Oct 12 '22 13:10

Thanatos