简体   繁体   English

从__init__.py导入Python文件

[英]Importing files in Python from __init__.py

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). a.py,b.py和c.py共享一些常见的导入(logging,os,re等)。 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? 是否可以从__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个模块,这与性能原因无关。

You can do this using a common file such as include.py , but it goes against recommended practices because it involves a wildcard import. 您可以使用诸如include.py类的公共文件来执行此操作,但这违反了建议的做法,因为它涉及通配符导入。 Consider the following files: 请考虑以下文件:

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. 如上所述,不建议使用,因为不鼓励使用通配符导入。

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). 不,它们必须放在每个模块的命名空间中,因此您必须以某种方式导入它们(除非您将logging作为函数参数传递,这将是一种奇怪的做事方式,至少可以说)。

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. 但模块只会导入一次(然后放入abc命名空间),所以不要担心使用太多内存或类似的东西。

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. 当然,你可以把它们放入一个单独的模块,并导入到每abc ,但这种单独的模块仍然必须进口每次。

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__.py like that. 我说不要这样做,不仅因为它太乱,没有意义,还因为你的包不是真的应该使用__init__.py It's package initialization code. 它是包初始化代码。

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

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