简体   繁体   中英

Python imports, utils file and how to combine them

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:

  1. He needed this functionality in several files
  2. Why would he make the code ugly with 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)
  3. import utils already exists in those files .
  4. Moreover, 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 . ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM