how to inform PyCharm that a module is indeed imported?

Answered
Hello,

In order to account for exotic modules in a script (exotic = modules that a user may not have) I do not import them straight away but rather use a more friendly approach (see second comment in this Stack Overflow question of mine for details).

import sys, importlib
extramodules = {
    "requests": "http://docs.python-requests.org/en/latest/user/install/#install or aptitude install python-requests",
    "simplejson": "https://github.com/simplejson/simplejson or aptitude install python-simplejson"
}
missingmodules = []
for k, v in extramodules.iteritems():
    try:
        globals()[k] = importlib.import_module(k)
    except:
        missingmodules.append(k)
if missingmodules:
    for k in missingmodules:
        print "MISSING MODULE {}, see {}".format(k,extramodules[k])
    print "ABORTING, need to install missing modules above"
    sys.exit(1)


PyCharm rightfully raises an error when using a module which seems not to be imported, even though it (indirectly) is. Is there a way to inform PyCharm that some modules should not be reported as missing? (or, worst case, disable this particular error – which I would like to avoid)

Thank you!
3 comments
Comment actions Permalink
Hi WoJ,
you can do that: just invoke alt+enter quick-fix and there in menu 'Mark all unresolved attributes as ignored' you can a) Select 'Edit inspection profile settings' and add your import to Ignore references list b) Suppress it for statement
0
Comment actions Permalink

I've just got the same problem. The highlighting solution mentioned by Dmitry is not good enough, for PyCharm does not help with code completion for modules loaded with `importlib`. For large projects, I have to use two versions of imports. This is not convenient at all.

As a hot fix, I'd suggest the following:

  1. If a package is imported with `importlib.import_module('package')`, and the result of the function is stored to `package` variable, then PyCharm looks for a package called 'package' among the installed packages.
  2. If the package called 'package' is found, it is considered imported just like if there is `import package`.
0
Comment actions Permalink

Please vote for the corresponding ticket in our issue tracker https://youtrack.jetbrains.com/issue/PY-25571

1

Please sign in to leave a comment.