从 __init__.py 在 Python 中导入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1201115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:42:01  来源:igfitidea点击:

Importing files in Python from __init__.py

pythonimportmodule

提问by Federico Builes

Suppose I have the following structure:

假设我有以下结构:

app/
  __init__.py
  foo/
    a.py
    b.py
    c.py
    __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__.pyfile so I don't have to import them in every one of the files?

a.py、b.py 和 c.py 共享一些常见的导入(日志记录、操作系统、重新等)。是否可以从__init__.py文件中导入这三个或四个常用模块,这样我就不必在每个文件中都导入它们?

Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.

编辑:我的目标是避免在每个文件中导入 5-6 个模块,这与性能原因无关。

采纳答案by balpha

No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass loggingaround as a function argument, which would be a weird way to do things, to say the least).

不,它们必须放在每个模块的命名空间中,所以你必须以某种方式导入它们(除非你logging作为函数参数传递,至少可以说这是一种奇怪的做事方式)。

But the modules are only imported once anyway (and then put into the a, b, and cnamespaces), so don't worry about using too much memory or something like that.

但模块仅导入一次呢(然后放入abc命名空间),所以不用担心使用太多内存或者类似的东西。

You can of course put them into a separate module and import thatinto each a, b, and c, but this separate module would still have to be imported everytime.

当然,你可以把它们放入一个单独的模块和进口为每一个abc,但这种单独的模块仍然必须进口每次。

回答by jkp

You can do this using a common file such as include.py, but it goes against recommended practices because it involves a wildcard import. Consider the following files:

您可以使用通用文件(例如 )来执行此操作include.py,但它违反了推荐的做法,因为它涉及通配符导入。考虑以下文件:

app/
    __init__.py
foo/
    a.py
    b.py
    c.py
    include.py <- put the includes here.
    __init__.py

Now, in a.py, etc., do:

现在,在a.py等中,执行:

from include import *

As stated above, it's not recommended because wildcard-imports are discouraged.

如上所述,不推荐这样做,因为不鼓励通配符导入。

回答by Evan Fosmark

Yes, but don't do it. Seriously, don't. But if you still want to know how to do it, it'd look like this:

是的,但不要这样做。说真的,不要。但如果你仍然想知道如何去做,它看起来像这样:

import __init__

re = __init__.re
logging = __init__.logging
os = __init__.os

I say not to do it not only because it's messy and pointless, but also because your package isn't really supposed to use __init__.pylike that. It's package initialization code.

我说不要这样做,不仅是因为它很乱而且毫无意义,还因为你的包不应该这样使用__init__.py。这是包初始化代码。