PyCharm: how to infer types of objects created at runtime

Viewed 400

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:

main.py view


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 Answers

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}")
Related