简体   繁体   English

变量和模块的实例检查

[英]isinstance check of variable and module

I have a list of strings, which all are modules that are imported (I parsed the __init__.py file earlier for some other validation). 我有一个字符串列表,所有字符串都是导入的模块(我之前解析了__init__.py文件以进行其他验证)。 For example mods = ['mod_one', 'mod_two', 'mod_three'] . 例如mods = ['mod_one', 'mod_two', 'mod_three'] I now need to verify that all of these are an instance of a pre-defined superclass ( skeleton.py ) - like 现在,我需要验证所有这些都是预定义超类( skeleton.py )的实例,例如

for x in mods:
    if not isinstance(x.Operation,skeleton.OperationSkeleton): 
        print("error with: "+x)`

My problem is that x is in this case a string - obviously, but is the name of the imported module I want to check. 我的问题是,在这种情况下,x是一个字符串-显然是我要检查的导入模块的名称。 The string doesn't have a Operation .. 该字符串没有Operation ..

And odd enough.. for testing purpose did I try to 而且奇怪的是..为了测试目的,我试图

print(isinstance(mod_one.Operation,skeleton.OperationSkeleton))

and it prints False . 并输出False But in mod_one.py the OperationSkeleton is imported from skeleton and class Clustering(ClusteringSkeleton): is created. 但是在mod_one.pyOperationSkeleton是从skeleton导入的,并且创建了class Clustering(ClusteringSkeleton): mod_one.py

If your modules are already imported, you can access them by their name in the sys.modules mapping : 如果您的模块已经导入,则可以在sys.modules映射中按其名称访问它们:

import sys

for x in mods:
    mod = sys.modules[x]
    if not issubclass(mod.Operation, skeleton.OperationSkeleton): 

You need to use issubclass() here as Operation is not an instance. 您需要在此处使用issubclass() ,因为Operation不是实例。

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

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