False Unused Import Statement in PyCharm?

40,155

Solution 1

As far as I can tell this behaviour is not handled as an inspection or some other configurable option, which means there is no #noinspection UnusedImport (or equivalent) that can be placed before the imports.

If you don't want to define an unused block where you use those variables there's an other simple and probably better way to achieve what you want:

#b.py code
import A

# [...] your code


__all__ = ['A', ...]  # *all* the names you want to export

PyCharm is smart enough to look at __all__ and avoid removing A as unused import. However there's a limitation that __all__ must be a simple list literal. You cannot do things like:

__all__ = ['A'] + [name for name in iterable if condition(name)]

Not even:

x = 'b'
__all__ = ['A', x]

Defining __all__ is a best-practice to make your module *-import safe anyway, so is something you should already do.

Solution 2

You can actually use the PyUnresolvedReferences marker to deactivate the inspection for your import statement:

# noinspection PyUnresolvedReferences
import A

Reference: PyCharm bug PY-2240

Solution 3

from C import A, B
_ = (A, B); del _

Works for me. I don't like

# noinspection PyUnresolvedReferences

as it would give false negatives in case A cannot be imported. And

__all__ = ['A', 'B', ...]

is cryptic and is not convenient for refactoring.

Share:
40,155
Mihnea Simian
Author by

Mihnea Simian

Updated on July 09, 2022

Comments

  • Mihnea Simian
    Mihnea Simian almost 2 years

    Given this scenario:

    b.py:

    import A
    # A is unused here
    

    c.py:

    from b import A
    # A is used here
    

    PyCharm complains in b.py that "import A" is an unused import and Optimize imports deletes it, breaking import in c.py

    I know these chained imports are not a good practice (although you may use it to implement a facade module), but is it me or is it a PyCharm fail?

  • kunambi
    kunambi about 8 years
    This solved my issue! Your answer helped me find a comprehensive list with all markers, at codeoptimism.com/blog/pycharm-suppress-inspections-list
  • Scott
    Scott over 5 years
    Thanks, I was looking for the right noinspection. I haz a sad that the link to codeoptimism isn't working anymore, a list would be great. This seems like a better targeted answer than the accepted answer.
  • proinsias
    proinsias over 5 years
    @Scott – I found a new link github.com/whitews/pc-inspection-suppression-list if that helps.