Reputation: 722
In our project there is a utils.py
file that provides functions for several files (DRY).
Needless to say how this is done, but I will note in case it is not understood,
in those files we do import utils
and use the necessary functions.
During development one of our developers uploaded a PR in which he added serveral functions to the utils.py
file, this is one of them:
list_dir(directory):
return os.listdir(directory)
When we asked him why he wrote this function (just import os
in the file you need, and use os.listdir
)
He said:
import os
in those files (then more imports
for every one-line use of external module ,then you have thousand of imports
in the top of the file)import utils
already exists in those files.import os
already exists in the utils.py
file.Needless to say, we all know that Python makes a one-time import for modules, the question here is different:
What is more called Pythonic ? When there is a one-line (maybe two) function, just import the module into the file that needs the function (though it looks like the code gets ugly), or write it in utils.py
. ?
Upvotes: 1
Views: 13437
Reputation: 226486
What is more called Pythonic?
The usual practice is to just import modules in the places where you need them. That would mean writing "import os" in every module where it is used.
There is legitimate reason I can think of. If in the future, you need to change what list_dir() does (perhaps filtering-out certain categories of files), it is nice to have all the users referencing the same source.
One other thought. As currently written, there is no need to have a wrapper function at all. In utils.py
just write from os import listdir as list_dir
.
Also, why change the name at all? Minimize complexity by sticking with listdir.
Upvotes: 8