PyCharm unable to resolve dynamic references for multiprocessing module

Viewed 310

This is perfectly valid code:

globals().update({"variable": "val"})
variable
# do-something-with-variable

However, PyCharm is not able to recognise the variable:

enter image description here

I don't want to disable the marking of unresolved references; it is a very useful feature. I want PyCharm to recognise my variable. How can I do this? (even if it is a dirty trick for development that I will later erase in production)

Explanation

I would not care about globals().update if it were not for that Python's multiprocessing module from version 3.4 incorporates dynamic creation of variables through a context class instead of defining them in the __init__.py file (see this link) For this reason, PyCharm does not recognise the module's attributes at all, so I have to be looking up docs constantly instead of making use of PyCharm's introspective features for this package, let alone not getting the unresolved reference error that makes me doubt constantly of whether I am getting the code right or not. Basically like writing code in Windows' notepad ;-)

2 Answers

Since Python is a dynamic language, it is not possible for PyCharm to check whether this is valid or not using static inferrence.

Consider the following:

globals = lambda: {}

globals().update({'variable': 'val'})

print(variable) # NameError: name 'variable' is not defined

Now that you overshadowed globals, this is not valid code anymore and PyCharm has no way to know.

The above being possible is a downside of dynamic languages: you cannot know if a program is valid before running it.

You can add: # noinspection PyUnresolvedReferences on the line above the line you want the unresolved reference inspection to be disabled.

It will not disable it anywhere else (from what I can see in my Pycharm 2018.2)

Related