进口项目图书馆
我有一个带有多个类和文件的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一种方法可以将您的导入在父模块中,然后从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 !
除非有所有其他文件导入的单个文件,否则您将无法执行此操作。即使在这种情况下,您要么必须使用< file>导入 *(这不是一个好练习),或使用
< file>。od; module>
每次您要参考这些模块之一,这只是使事物不必要地长时间长。因此,这样做通常不是一个好主意...
...但是,如果所有文件共享了很多导入,并且您确定这样做会使您的代码更加清晰,那么您可以考虑创建一个新文件专门用于此目的。
例如,您可以在顶级添加一个名为
common_imports
的文件,将所有导入放入其中,然后在每个文件开始时只能从common_imports import *中使用。
因此:
common_imports.py
其他文件
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 usefrom common_imports import *
at the start of each file.So:
common_imports.py
Other files