Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 886
Isac Casapu Avatar asked Aug 23 '19 16:08

Isac Casapu


People also ask

How do I know if a Python module is imported?

Use: if "sys" not in dir(): print("sys not imported!")

What is a Python file often called when it is intended to be imported and used by another Python file?

A module is a Python file that's intended to be imported into scripts or other modules. It often defines members like classes, functions, and variables intended to be used in other files that import it.

What does unused import statement mean in Python?

unused import means you imported something that you never used Remove that import line and that is it.07-Feb-2021.

What are the two ways of importing a module in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.


1 Answers

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
like image 52
Sagar Gupta Avatar answered Oct 19 '22 07:10

Sagar Gupta