views:

62

answers:

3

I want the wrapper my_function to be able to receive either a class or class instance, instead of writing two different functions:

>>> from module import MyClass

>>> my_function(MyClass)

True

>>> cls_inst = MyClass()

>>> my_function(cls_inst)

True

the problem is that I don't know in advance which type of classes or class instances I am going to receive. So I can't, for example, use functions like isinstance...

How can I type check if a param contains a class or a class instance, in a generic way?

Any idea?

A: 

Use the type() buitlin function.

E.g.:

import avahi
print type(avahi)

<type 'module'>
jldupont
+7  A: 
>>> class A: pass

>>> isinstance(A, type)
True
>>> isinstance(A(), type)
False
SilentGhost
Your example is an old-style class, but this does also work with new-style classes.
steveha
my example is py3k ;)
SilentGhost
+1  A: 
import types

def myfun(maybe_class):
    if type(maybe_class) == types.ClassType:
        print "It's a class."
    else:
        print "It's an instance."
Jonathan Feinberg