tags:

views:

291

answers:

1

I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions.

(To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.)

issubclass only works for instances, not class objects themselves. I suppose I could instantiate the class, do issubclass and throw away the instance, but that seems a bit wasteful.

Here's what I'm doing at the moment, relying on the built-in mro attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it?

if GenericClass in myclass.__mro__:
    result = generic_factory(myclass)
else:
    result = other_factory(myclass)
+15  A: 

issubclass only works for instances, not class objects themselves.

It works fine for me:

>>> class test(object):pass
...
>>> issubclass(test,object)
True
Unknown
Aargh, I was confusing it with isinstance. Thanks.
Daniel Roseman