tags:

views:

185

answers:

4

I am working at a bit lower level writing a small framework for creating test fixtures for my project in Python. In this I want to find out whether a particular variable is an instance of a certain class or a class itself and if it is a class, I want to know if it is a subclass of a certain class defined by my framework. How do I do it?

class MyBase(object):
    pass

class A(MyBase):
    a1 = 'Val1'
    a2 = 'Val2'

class B(MyBase):
    a1 = 'Val3'
    a2 = A

I want to find out if the properties a1 and a2 are instances of a class/type (a1 is a string type in B) or a class object itself (i.e a2 is A in B). Can you please help me how do I find this out?

+3  A: 

Use the type() function. It will return the type of the object. You can get 'stock' types to match with from the types library. Old-style classes (that don't inherit from anything) have the type types.ClassType. New-style classes like in your example have the type types.TypeType. There are plenty of other useful types in this module for strings and such.

Calling type() on an instance of an old-style class returns types.InstanceType. Calling it on an instance of a new-style class returns the class itself.

inklesspen
+3  A: 

Use isinstance and type, types.ClassType (that latter is for old-style classes):

>>> isinstance(int, type)
True

>>> isinstance(1, type)
False
abyx
+1  A: 

Use type()

>>> class A: pass
>>> print type(A)
<type 'classobj'>
>>> A = "abc"
>>> print type(A)
<type 'str'>
luc
+9  A: 

Use the inspect module.

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

For example, the inspect.isclass() function returns true if the object is a class:

>>> import inspect
>>> inspect.isclass(inspect)
False
>>> inspect.isclass(inspect.ArgInfo)
True
>>>
gimel
+1 Didn't know about this one, much better than the `isinstance` alternatives
abyx
Thanks a lot. I did not know about this too. Helps me a lot. I am using a combination of this and the solution given by inklesspen and abyx. Thanks everyone for the solution
Madhusudan.C.S