简体   繁体   English

对未定义的类使用isinstance

[英]Use isinstance with an undefined class

Assume that class MyClass is sometimes, but not always, defined. 假定有时(但并非总是)定义了MyClass类。 I have a function foo(a=None) in which argument a can be None , a string, or an object of MyClass . 我有一个函数foo(a=None) ,其中参数a可以是None ,字符串或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 ? 我的问题是:如果在我的Python会话中未定义MyClass ,如何以类似于isinstance的方式检查参数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. 我正在使用Python 2.6.x,并且不能选择更新。 A forward-compatible solution (especially for 2.7.x) is highly appreciated. 前向兼容的解决方案(尤其是2.7.x版)受到高度赞赏。

If MyClass isn't defined then you have no way to reference its type. 如果未定义MyClass则无法引用其类型。

Therefore you can have no way to verify that type(a) has the correct value. 因此,您将无法验证type(a)具有正确的值。

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. 您可以将其放入自己的模块中,然后from mymodule import Bar到需要的地方。 That allows all your code to use Bar regardless of whether it's defined natively or not. 这样一来,所有代码都可以使用Bar而无论它是否是本地定义的。

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. 即使重新定义类不是处理此问题的首选方法,但处理ImportError仍然是处理这种情况的方法,因为您将不得不以任何一种方式import该类,而这正是发生错误的地方。 Instead of defining the class, you may instead want to set a class_exists = False flag or something. 除了定义类之外,您可能还想设置class_exists = False标志或其他东西。

I workarounded the problem by overriding a method in MyClass and doing nothing in it ( pass ). 我通过重写 MyClass 的方法而不执行任何操作( 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. 捕获NameError可能是另一个。

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. 在我看来,这样的构造可能会出现在未来的python中。 Like typed python, which is quite new. 就像输入python一样,这是很新的。 And in typed python we have a possibility to use future types, in apos. 在键入的python中,我们有可能在apos中使用将来的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM