3

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?

Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107
Madhusudan.C.S
  • 831
  • 1
  • 7
  • 19
  • Why can't you read the source? What's wrong with your source? – S.Lott Nov 26 '09 at 13:10
  • What does that mean? You mean I should read the source code, parse it and find out? I want to find out programmatically and dynamically at run time. How can I achieve this by reading the source code? – Madhusudan.C.S Nov 27 '09 at 04:15

4 Answers4

11

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
  • 83,368
  • 10
  • 76
  • 104
  • +1 Didn't know about this one, much better than the `isinstance` alternatives – abyx Nov 26 '09 at 10:17
  • 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 Nov 27 '09 at 04:16
4

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

>>> isinstance(int, type)
True

>>> isinstance(1, type)
False
abyx
  • 69,862
  • 18
  • 95
  • 117
3

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
  • 1,146
  • 6
  • 11
1

Use type()

>>> class A: pass
>>> print type(A)
<type 'classobj'>
>>> A = "abc"
>>> print type(A)
<type 'str'>
luc
  • 41,928
  • 25
  • 127
  • 172