[英]How do I share a python script's imports with another script?
Let's say I have a script1.py with imports. 假设我有一个带有导入的script1.py。
How can I share script1.py imports with script2.py? 如何与script2.py共享script1.py导入? without copy and pasting. 无需复制和粘贴。
Your application should consist of many modules that are logically independent. 您的应用程序应包含许多逻辑上独立的模块。 It makes your program easier to read, debug etc. Just like Python's standard library is divided into many modules (as you said - you have to import things from many of them). 它使您的程序更易于阅读,调试等。就像Python的标准库分为许多模块一样(正如您所说-您必须从其中的许多模块中导入内容)。
The more modules you have, the fewer imports you need to do in each of them. 您拥有的模块越多,在每个模块中需要执行的导入就越少。 It's because each separate part of your program only imports what it needs. 这是因为程序的每个单独部分仅导入所需的内容。 Thanks to this attitude you and other programmers can easily understand the code. 由于这种态度,您和其他程序员可以轻松理解代码。
Another way to deal with it (not really recommended): 处理它的另一种方式(不建议这样做):
imports.py: (in this example I assume you put it in the same directory as test.py) imports.py :(在此示例中,我假设您将其放置在与test.py相同的目录中)
from datetime import date
from re import *
test.py: test.py:
from imports import * #you import your imports
today = date.today() #using what you imported in imports.py
print(today)
It might be dangerous due to possibly same names imported. 由于可能导入了相同的名称,因此可能很危险。 Be careful! 小心!
though I agree with the comments... you can have a module that defines the all attribute 尽管我同意这些意见...您可以有一个定义all属性的模块
from crazyapp import all, my, imports
__all__ =['all', 'my', 'imports']
then just call to import the modules. 然后只需调用即可导入模块。
from allmyimports import *
But fix things if you have that many.... 200? 但是,如果您有那么多,请解决问题... 200? Think of a module as something that does one thing and does that one thing good. 可以将模块想像为一件事情,一件事情做得很好。 you'll find your imports will drop for the most part. 您会发现您的进口大部分会下降。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.