进口项目图书馆

发布于 2025-02-02 19:13:56 字数 268 浏览 3 评论 0原文

我有一个带有多个类和文件的Python项目。

这是我的文件夹结构:

main.py
directory
  |_ parent_class.py
  |_sub_directory_1
     |_child_class_1.py
  |_sub_directory_2
     |_child_class_2.py

我在所有文件中使用了相同的导入,例如pandas和numpy。有没有办法一次导入这些时间,以便我的代码更干净? 非常感谢。

I have a python project with multiple classes and files.

This is my folder structure:

main.py
directory
  |_ parent_class.py
  |_sub_directory_1
     |_child_class_1.py
  |_sub_directory_2
     |_child_class_2.py

I am using the same imports like pandas and numpy e.g. in all files. Is there a way to import those a single time so my code is cleaner?
Many Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅暮の光 2025-02-09 19:13:56

有一种方法可以将您的导入在父模块中,然后从parent_module导入 *。

但是,我不建议这样做,因为您的项目的发展越多,您就越有可能产生循环进口!

我要说的是,最好的做法是仅导入您真正需要的包装/模块。如果您想要一个清洁的代码库,我可以建议您使用 isort 它将自动格式化您的导入!

There is a way to "refacto" your imports inside a parent module and then import * from parent_module.

However I would not recommend such practice as the more your project grows the more likely you are to produce circular imports !

I would say that the best practice is to only import your packages/modules where you really need them. If you want a cleaner code base, I can suggest you tools such as isort that will automatically format your imports !

阿楠 2025-02-09 19:13:56

除非有所有其他文件导入的单个文件,否则您将无法执行此操作。即使在这种情况下,您要么必须使用< file>导入 *(这不是一个好练习),或使用< file>。od; module>每次您要参考这些模块之一,这只是使事物不必要地长时间长。

因此,这样做通常不是一个好主意...

...但是,如果所有文件共享了很多导入,并且您确定这样做会使您的代码更加清晰,那么您可以考虑创建一个新文件专门用于此目的。

例如,您可以在顶级添加一个名为common_imports的文件,将所有导入放入其中,然后在每个文件开始时只能从common_imports import *中使用

因此:

common_imports.py

import numpy as np
import pandas as pd
...
...

其他文件

from common_imports import *
...  # Other imports

...
...

You can't do this unless there is a single file which is imported by all of the other files. And even in that case, you either have to use from <file> import * (which is not a good practice), or use <file>.<module> every time you want to reference one of those modules, which just makes things unnecessarily long.

Therefore, doing this is not usually a good idea...

...However, if there are a lot of imports shared by all files and you are sure that doing this would make your code much clearer, you could consider creating a new file specifically for this purpose.

For example, you could add a file called common_imports at the top level, put all the imports in there, and just use from common_imports import * at the start of each file.

So:

common_imports.py

import numpy as np
import pandas as pd
...
...

Other files

from common_imports import *
...  # Other imports

...
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文