问题描述
假设我有以下结构:
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
a.py、b.py 和 c.py 共享一些常见的导入(日志记录、操作系统、re 等).是否可以从 __init__.py
文件中导入这三个或四个常用模块,这样我就不必在每个文件中都导入它们?
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py
file so I don't have to import them in every one of the files?
我的目标是避免在每个文件中导入 5-6 个模块,这与性能原因无关.
My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.
推荐答案
不,它们必须放在每个模块的命名空间中,因此您必须以某种方式导入它们(除非您将 logging
作为一个函数参数,至少可以说这是一种奇怪的做事方式).
No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass logging
around as a function argument, which would be a weird way to do things, to say the least).
但是这些模块无论如何都只导入一次(然后放入 a
、b
和 c
命名空间),所以不要不用担心使用太多内存或类似的东西.
But the modules are only imported once anyway (and then put into the a
, b
, and c
namespaces), so don't worry about using too much memory or something like that.
您当然可以将它们放入一个单独的模块中,然后将 that 导入到每个 a
、b
和 c代码>,但是这个单独的模块仍然需要每次都被导入.
You can of course put them into a separate module and import that into each a
, b
, and c
, but this separate module would still have to be imported everytime.
这篇关于从 __init__.py 在 Python 中导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!