Mohammadreza Khoshbin
Mohammadreza Khoshbin

Reputation: 329

Use isinstance with an undefined class

Assume that class MyClass is sometimes, but not always, defined. I have a function foo(a=None) in which argument a can be None, a string, or an object of MyClass.

My question is: If MyClass is not defined in my Python session, how can I check the type of argument a in a fashion similar to isinstance without getting a NameError?

Note on duck-typing: I am deliberately limiting the function.

I'm using Python 2.6.x and Updating is not an option. A forward-compatible solution (especially for 2.7.x) is highly appreciated.

Upvotes: 1

Views: 1729

Answers (3)

Jarekczek
Jarekczek

Reputation: 7866

I workarounded the problem by overriding a method in MyClass and doing nothing in it (pass). After that I no longer needed to check its type.

Different workarounds may exist for different cases. Catching the NameError could be another one.

t = 'asdfas'
print(isinstance(t, str))
try:
    print(isinstance(t, MyClass))
except NameError:
    print(False)

Seems to me, that such a construct may appear in future python. Like typed python, which is quite new. And in typed python we have a possibility to use future types, in apos.

Upvotes: 1

deceze
deceze

Reputation: 522016

I would suggest a different approach: polyfill the class so all code that wants to refer to it can simply do so:

try:
    from foo import Bar  # load the native class
except ImportError:
    class Bar:
        pass  # implement necessary parts here

You can put this into your own module and then from mymodule import Bar everywhere it's needed. That allows all your code to use Bar regardless of whether it's defined natively or not.

Even if redefining the class isn't your preferred way to handle this, handling the ImportError is still the way to handle this situation, since you will have to import the class either way and that's where the error will occur. Instead of defining the class, you may instead want to set a class_exists = False flag or something.

Upvotes: 3

holdenweb
holdenweb

Reputation: 37003

If MyClass isn't defined then you have no way to reference its type.

Therefore you can have no way to verify that type(a) has the correct value.

Upvotes: 1

Related Questions