PyCharm: how to infer types of objects created at runtime

谁说我不能喝 提交于 2020-03-21 20:12:46

问题


I am trying to use a library that creates objects, and adds them to the global namespace at runtime.

PyCharm cannot find the references to the objects, because they aren't originally in the namespace.

How can I get PyCharm introspection to not complain "Cannot find reference..."? I don't want to use noinspection tags.


Sample Code

To help make my question clear, I have drawn up sample code of using an object created at runtime in PyCharm.

main.py

from some_import import some_obj_1


if __name__ == "__main__":
    print(f"obj_1.some_attr = {some_obj_1.some_attr}")

some_import.py

class SomeClass:
    def __init__(self, attr_init: int = 0):
        self.some_attr = attr_init


globals()["some_obj_1"] = SomeClass(1)

Output of running main.py:

obj_1.some_attr = 1

What I see in PyCharm:


Relevant Articles

Dynamic runtime type inference in PyCharm 2.7

This article suggests enabling Collect run-time types information for code insight. However, enabling this settings and running the debugger did not solve my problem.


Possible Solutions

  • Making a PyCharm stub file
  • Suppressing the error message using PyCharm noinspection tag + a type hint
    • This is "manual", and thus I don't like this solution very much
# noinspection PyUnresolvedReferences
from some_import import some_obj_1, SomeClass

some_obj_1: SomeClass


if __name__ == "__main__":
    print(f"obj_1.some_attr = {some_obj_1.some_attr}")

This was made using Python 3.7.6 and PyCharm 2019.2.5 CE.


回答1:


The below link makes me think it is possible just by using the module name.

Behaviour of global variables in "run with Python console"

I've written this code but it's tough for me to test as I'm using Spyder and that works with your original attempt

import some_import as si


if __name__ == "__main__":
    print(f"obj_1.some_attr = {si.some_obj_1.some_attr}")


来源:https://stackoverflow.com/questions/60383370/pycharm-how-to-infer-types-of-objects-created-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!