0

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?

1
  • Could you provide a use case for doing this? It doesn't make a lot of sense on the surface. Why can't you use my_function( object.__class__ ) so that things are at least consistent? Commented Oct 28, 2009 at 17:54

3 Answers 3

7
>>> class A: pass

>>> isinstance(A, type)
True
>>> isinstance(A(), type)
False
Sign up to request clarification or add additional context in comments.

1 Comment

Your example is an old-style class, but this does also work with new-style classes.
1
import types

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

Comments

0

Use the type() buitlin function.

E.g.:

import avahi
print type(avahi)

<type 'module'>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.