本文介绍了从__init__.py导入Python文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下结构:

app/
  __init__.py
  foo/
    a.py
    b.py
    c.py
    __init__.py

a.py,b.py和c.py共享一些常见的导入(logging,os,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.

推荐答案

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

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.

您当然可以将它们放入一个单独的模块中并将 导入每个 a b c ,但这个单独的模块会仍然需要进口ime。

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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:05