Python: Importing an “import file”

后端 未结 2 1422
醉话见心
醉话见心 2020-12-05 14:47

I am importing a lot of different scripts, so at the top of my file it gets cluttered with import statements, i.e.:

from somewhere.fileA import ...
from some         


        
相关标签:
2条回答
  • 2020-12-05 15:15

    I strongly advise against what you want to do. You are doing the global include file mistake again. Although only one module is importing all your modules (as opposed to all modules importing the global one), the remaining point is that if there's a valid reason for all those modules to be collected under a common name, fine. If there's no reason, then they should be kept as separate includes. The reason is documentation. If I open your file, and see only one import, I don't get any information about what is imported and where it comes from. If on the other hand, I have the list of imports, I know at a glance what is needed and what not.

    Also, there's another important error I assume you are doing. When you say

    from somewhere.fileA import ...
    from somewhere.fileB import ...
    from somewhere.fileC import ...
    

    I assume you are importing, for example, a class, like this

    from somewhere.fileA import MyClass
    

    this is wrong. This alternative solution is much better

     from somewhere import fileA 
    
     <later>
    
     a=fileA.MyClass()
    

    Why? two reasons: first, namespacing. If you have two modules having a class named MyClass, you would have a clash. Second, documentation. Suppose you use the first option, and I find in your code the following line

     a=MyClass()
    

    now I have no idea where this MyClass comes from, and I will have to grep around all your files in order to find it. Having it qualified with the module name allows me to immediately understand where it comes from, and immediately find, via a /search, where stuff coming from the fileA module is used in your program.

    Final note: when you say "fileA" you are doing a mistake. There are modules (or packages), not files. Modules map to files, and packages map to directories, but they may also map to egg files, and you may even create a module having no file at all. This is naming of concepts, and it's a lateral issue.

    0 讨论(0)
  • 2020-12-05 15:25

    Of course there is; just create a file called myimports.py in the same directory where your main file is and put your imports there. Then you can simply use from myimports import * in your main script.

    0 讨论(0)
提交回复
热议问题