Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark unused imported items in Python

Tags:

python

In Python if you need to import a module for its side effects then you can't use something like autoflake to automatically remove unused imports. There's a fairly clean way to work around that that I described here (I didn't come up with it but I don't remember where I saw it):

import something
assert something, "Something is imported for its side effects."

But what if you are importing something so that it is re-exported. In other words:

# api.py
from internal_details import version
# main.py
import api
print(api.version)

Unfortunately Python is not well enough designed to have an export statement, so there's no way for autoflake to know that you imported version just to expose it to other modules.

What's the cleanest way to mark version as unused? Note that you can't do the same thing as the with the module:

assert version, "Version is part of the exported API."

That won't work (exercise for the reader!).

The best I can come up with is:

assert True or version, "Version is part of the export API."

But it's a bit ugly. Is there a better solution?

To be clear, I don't want to use lint-disabling comments like # noqa unless there is one that is de facto supported by everyone. Autoflake was just an example; Pylint also does this analysis. There's probably more.

like image 430
Timmmm Avatar asked Mar 17 '26 16:03

Timmmm


1 Answers

The autoflake tool can ignore certain imports that you are not using directly.

Append # noqa to the relevant import line. For example:

from .endpoints import role, token, user, utils  # noqa
like image 114
jarmod Avatar answered Mar 20 '26 06:03

jarmod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!