简体   繁体   English

将所有Python导入文件保存在一个文件中

[英]Keeping all Python imports in one file

I have a file and it has lot of imports: 我有一个文件,并且有很多导入:

import x
from y import z
and so on .... 

Is there a way to keep all the imports in another file called 'AllImports.py' and be able to do something as: 有没有一种方法可以将所有导入保存在另一个名为“ AllImports.py”的文件中,并能够执行以下操作:

import AllImports as im

Then be able to use: 然后可以使用:

im.x
im.z
and so on

I want to do this because my file has about 20 rows of imports, and it's going to increase. 我想这样做是因为我的文件有大约20行导入,并且将会增加。 Why is it not a good practice? 为什么这不是一个好习惯?

When you do this: 执行此操作时:

File a.py : 文件a.py

import x

It imports everything in x ... including the other imports. 它以x ...的形式导入所有内容,包括其他导入内容。 If x has this defined at the top: 如果x在顶部定义了这个:

import y

Then you can do this in a : 然后,你可以在做a

x.y

Therefore, if you do this in a : 因此,如果你在做这a

import x as z

You can also then do: 然后,您还可以执行以下操作:

z.y

The difficulty with this is that you are importing a function at the point where it is imported: adding degrees of indirection makes things such as testing, and determining what is actually going on in your file, harder. 这样做的困难在于,要在导入函数时导入函数:添加间接程度会使诸如测试之类的事情以及确定文件中实际发生的事情变得更加困难。 Good IDEs allow you to collapse import lists, which means the problem you're trying to solve (not having to see a huge list of imports) is more simply solved with a good tool. 好的IDE可以折叠导入列表,这意味着您可以使用一个好的工具来简单地解决您要解决的问题(不必查看大量的导入列表)。

I would note, too, that one of the most important things code can be is readable. 我还要指出,代码可以读取的最重要内容之一是可读性。 By forcing yourself to use the im. 通过强迫自己使用im. namespace in front of everything, you are occluding what your code is doing, and preventing you from writing code that is elegant and easy to read and understand. 命名空间摆在所有事物的最前面,您将遮挡代码的工作,并阻止编写优雅,易于阅读和理解的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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