简体   繁体   English

导入 main.py 中的所有包

[英]Import all packages in main.py

I'd like to import all my packages in only one file.我只想将我所有的包导入到一个文件中。

Let assume that I have a main.py file where I call all my class (from others.py files located in a src folder):假设我有一个 main.py 文件,我在其中调用了我所有的 class(来自位于 src 文件夹中的 others.py 文件):

main.py
|-- src
  |-- package1.py
  |-- package2.py

the main.py looks like this: main.py 看起来像这样:

from src.package1 import *
from src.package2 import *

def main():
    class1 = ClassFromPackage1()
    class2 = ClassFromPackage2()

if __name__ == '__main__':
    main()

in package1.py I import let say numpy, scipy and pandas在 package1.py 我导入说 numpy、scipy 和 pandas

import numpy
import scipy
import pandas

class ClassFromPackage1():
    #  Do stuff using numpy, scipy and pandas

and in package2.py I use numpy and scikit learn:在 package2.py 我使用 numpy 和 scikit 学习:

import numpy
import sklearn

class ClassFromPackage2():
    #  Do stuff using numpy and sklearn

Is there a way to import all packages in one file Foo.py where I only write:有没有办法在一个文件 Foo.py 中导入所有包,我只写:

import numpy
import sklearn
import scipy
import pandas

and import this Foo.py in src.py?并在 src.py 中导入这个 Foo.py? like this for example with package1.py像这样,例如 package1.py

import Foo

class ClassFromPackage1():
    #  Do stuff using numpy, scipy and pandas

Is this a good idea?这是一个好主意吗? Does it reduce memory consumption?它会减少 memory 消耗吗? Will it helps python to start the main.py faster?它会帮助 python 更快地启动 main.py 吗?

Looks like you want to make code cleaner?看起来你想让代码更干净? What you can do is create a file like foo.py and put all imports in it.您可以做的是创建一个像foo.py这样的文件并将所有导入文件放入其中。 Then you can import modules inside foo.py by doing然后你可以通过做在foo.py中导入模块

from foo import *

This will indirectly import all modules.这将间接导入所有模块。

The way you have already done it is how it is usually done.您已经完成的方式就是通常的方式。 Similar to header files in C/C++, you make the dependencies explicit.与 C/C++ 中的 header 文件类似,您可以明确依赖关系。 And that it is a good thing.这是一件好事。

You asked if it will run faster, the answer is no.你问它是否会跑得更快,答案是否定的。 All imports are shared.所有导入都是共享的。 This, sometimes, causes unwanted side effects, but that is not the question here.这有时会导致不必要的副作用,但这不是这里的问题。

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

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