[英]Class instance fails isinstance check
我的CI上有一些代码失败(本地运行不会失败)。 问题在于类实例未通过isinstance()
检查。
...
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
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
类,因此返回相同的类型实例,并且类型检查成功。
我直接用参数"test"
调用main.py
(这将创建一个控制器,并通过unittest从中运行所有测试),因此MyController
类在__main__
内部创建。 MyController.get_variables_context
仍在main.py
请求MyController
类,但是此处未加载模块'main'
,因此python加载了它,创建了新类MyController
,然后返回了它。
将MyController
从main.py
移到另一个文件,即controller.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.