开发者

Python: Importing an "import file"

开发者 https://www.devze.com 2023-03-09 16:55 出处:网络
I am importing a lot of different scripts, so at the top of my file it gets cluttered with import statements, i.e.:

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

from somewh开发者_Go百科ere.fileA import ...
from somewhere.fileB import ...
from somewhere.fileC import ...
...

Is there a way to move all of these somewhere else and then all I have to do is import that file instead so it's just one clean import?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号