简体   繁体   English

python 2.7 isinstance在动态导入的模块类上失败

[英]python 2.7 isinstance fails at dynamically imported module class

I'm currently writing some kind of tiny api to support extending module classes. 我目前正在编写某种微型API,以支持扩展模块类。 Users should be able to just write their class name in a config and it gets used in our program. 用户应该能够在配置中写入其类名,并且该类名将在我们的程序中使用。 The contract is, that the class' module has a function called create(**kwargs) to return an instance of our base module class, and is placed in a special folder. 合同规定,该类的模块具有一个名为create(**kwargs)的函数,用于返回我们基本模块类的实例,并放置在一个特殊的文件夹中。 But the isinstance check Fails as soon as the import is made dynamically. 但是,一旦动态完成导入,isinstance检查就会失败。

modules are placed in lib/services/ name 模块放在lib / services / 名称中

module base class (in lib/services/service) 模块基类(在lib / services / service中)

class Service:
    def __init__(self, **kwargs):
        #some initialization

example module class (in lib/services/ping) 示例模块类(在lib / services / ping中)

class PingService(Service):
    def __init__(self, **kwargs):
        Service.__init__(self,**kwargs)
        # uninteresting init

def create(kwargs):
    return PingService(**kwargs)

importing function 导入功能

import sys
from lib.services.service import Service

def doimport( clazz, modPart, kw, class_check):
    path = "lib/" + modPart
    sys.path.append(path)
    mod = __import__(clazz)
    item = mod.create(kw)

    if class_check(item):
        print "im happy"
        return item

calling code 呼叫码

class_check = lambda service: isinstance(service, Service)
s = doimport("ping", "services", {},class_check)

print s

from lib.services.ping import create

pingService = create({})
if isinstance(pingService, Service):
    print "why this?"

what the hell am I doing wrong 我到底在做什么错

here is a small example zipped up, just extract and run test.py without arguments zip example 这是一个压缩的小示例,仅提取并运行不带参数的test.py zip示例

The problem was in your ping.py file. 问题出在您的ping.py文件中。 I don't know exactly why, but when dinamically importing it was not accepting the line from service import Service , so you just have to change it to the relative path: from lib.services.service import Service . 我不知道为什么,但是在进行动态导入时,它不接受from service import Service的行,因此您只需要将其更改为相对路径即可: from lib.services.service import Service Adding lib/services to the sys.path could not make it work the inheritance, which I found strange... lib/services添加到sys.path不能使其继承工作,我发现这很奇怪...

Also, I am using imp.load_source which seems more robust: 另外,我正在使用imp.load_source ,它似乎更可靠:

import os, imp
def doimport( clazz, modPart, kw, class_check):
    path = os.path.join('lib', modPart, clazz + '.py')
    mod = imp.load_source( clazz, path )
    item = mod.create(kw)

    if class_check(item):
        print "im happy"
        return item

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

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