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
.