繁体   English   中英

类实例未通过isinstance检查

[英]Class instance fails isinstance check

你好

我的CI上有一些代码失败(本地运行不会失败)。 问题在于类实例未通过isinstance()检查。

码:

档案:main.py

...
def get_variables_context(self: SuperController, **kwargs):
    from main import MyController
    self: MyController

    print(f"type(self) is {type(self)} (it {'IS' if (isinstance(self, MyController)) else 'IS NOT'} a subclass of MyController)")
    _super = super(MyController, self).get_variables_context(**kwargs) or dict()
    _super.update(result)
    return _super

档案:my_options.py

type(self) is <class '__main__.SomeController'> (it IS NOT a subclass of SomeController
Traceback (most recent call last):
  File "main.py", line 24, in <module>
    SomeController.main(**params)
  File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 391, in main
    _tests_suite, _, _ = self.prepare()
  File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 359, in prepare
    context['variables_context'] = self.get_variables_context(**context)
  File "/builds/RND/my/tests/integration/my_options.py", line 81, in get_variables_context
    _super = super(SomeController, self).get_variables_context(**kwargs) or dict()
TypeError: super(type, obj): obj must be an instance or subtype of type

得到输出和错误:

 type(self) is <class '__main__.SomeController'> (it IS NOT a subclass of SomeController Traceback (most recent call last): File "main.py", line 24, in <module> SomeController.main(**params) File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 391, in main _tests_suite, _, _ = self.prepare() File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 359, in prepare context['variables_context'] = self.get_variables_context(**context) File "/builds/RND/my/tests/integration/my_options.py", line 81, in get_variables_context _super = super(SomeController, self).get_variables_context(**kwargs) or dict() TypeError: super(type, obj): obj must be an instance or subtype of type 

在调查根本原因时,我已经找到了解决方案。

在当地,...

实际上调用python unittest,然后调用main.py ,然后创建一个MyController类,然后再调用my_options.py ,并将该类添加到已加载的模块'main' 然后, MyController.get_variables_context询问已加载的模块'main' ,然后询问该模块中'main' MyController类,因此返回相同的类型实例,并且类型检查成功。

在CI运行中,...

我直接用参数"test"调用main.py (这将创建一个控制器,并通过unittest从中运行所有测试),因此MyController类在__main__内部创建。 MyController.get_variables_context仍在main.py请求MyController类,但是此处未加载模块'main' ,因此python加载了它,创建了MyController ,然后返回了它。

所以,基本上答案是...

MyControllermain.py移到另一个文件,即controller.py

暂无
暂无

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

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