Wör Du Schnaffzig
Wör Du Schnaffzig

Reputation: 1051

Pylint gives warnings for centralised imports

In a python project I would like to globber imports into a single file called common_imports.py in order to reduce number of import statements in python files. Instead of writing

file1.py

import foo 
import bar
import baz

[...]

file2.py

import foo 
import bar
import baz

[...]

I would like to write

file1.py

from common_imports import *

[...]

file2.py

from common_imports import *

[...]

common_imports.py

import foo 
import bar
import baz

However, this gives me a lot of pylint false positives.

I can disable pylint warnings in the common_imports.py file by adding a pylint disable comment. I can disable wildcard imports. Unfortunately, I can disable unused imports only globally but not specific for all imports from common_imports.py. Somebody has an idea howto get pylint on the track?

Upvotes: 1

Views: 524

Answers (1)

s3dev
s3dev

Reputation: 9721

Summarising my comments above into a proper answer:


TL;DR:

While the reusable code motive is commendable, it's not fit for purpose here. Listen to the linter, and save your hard-earned respect among your colleagues. :-)

Pythonic Viewpoint:

  • Don't

  • Why? Python convention, in all its organisational glory and documented structure, states that if you use a library in a module, import it in the module. Plain and simple.

    Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

    -- PEP8 - Imports

  • At a lower level, the sys.modules dict, which tracks imports, will only import a library if it hasn’t been imported already. So from an efficiency point of view, there is no gain.

Maintainer's Viewpoint:

  • Don't
  • Why? If (when) the code is changed / optimised in a module, thus alleviating the need for a specific import … "remind me where I look to find where that library is imported? Oh ya, here. But this other module needs that import, but not this new library I’m using to optimise this code. Where should I import that? Ugh!!!"
    • You've lost the hard-earned respect of following maintainers.

Upvotes: 2

Related Questions