Idiomatic way in Python to indicate an unused module import is intentional
Asked Answered
C

1

7

Sometimes a Python module import that appears to be unused, is in fact essential to the proper functioning of the program. Having seemingly unused imports gives rise to spurious messages from tools like PyFlakes, and can attract unwarranted attention from overzealous programmers. C++, for instance, has (since C++ 11) an idiomatic way to indicate this with the [[unused]] attribute (and [[maybe_unused]] since C++ 17).

I'm asking this question in particular in the context of web frameworks like Flask, where this is often the case. For example, this boilerplate code from a Flask application, which is essential for proper its function:

from app import auth_routes, app, db
from app.resources import api

I usually handle this situation by

import X
assert X is not None # Explanatory comment

Is there a way that's more explicit about intent and more "Pythonic" to accomplish this?

Chlorpromazine answered 23/8, 2019 at 16:17 Comment(3)
Can you give a specific example?Epencephalon
E.g. this piece of Flask boilerplate code: from app import auth_routes, app, db from app.resources import apiChlorpromazine
So since those imports are not used in the file, but still required, it seems that the problem is that the library you are using is "unpythonic". That is, importing the module has a hidden side effect. I think that breaks the principle that "Explicit is better than implicit.". On the other hand, it is also said that "practicality beats purity."Saintly
F
9

Every tool will have its own way of error-suppression. For instance:

Pylint:

import X  # pylint: disable=unused-import

Pyflakes:

import X  # NOQA

PyCharm:

# noinspection PyUnresolvedReferences
import X
Fraktur answered 23/8, 2019 at 16:21 Comment(3)
I feel this scales poorly, with all the linting tools out there.Chlorpromazine
It would be nice if there were at least one directive that was respected by every linting tool. For example # NOQA. Even when you are only using one linter, it can be hard to figure out which specific directive to use in any given situation.Saintly
@HåkenLid I would love to see that too.Fraktur

© 2022 - 2024 — McMap. All rights reserved.