导入模块,因为它是更高的级别 [英] Importing module as it was a level higher

查看:49
本文介绍了导入模块,因为它是更高的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有通过setuptools获得的目录结构:

I have this directory structure obtained with setuptools:

root/
    A/
      __init__.py
      1.py
      2.py
    B/
      __init__.py
      3.py
    __init__.py

包装部分如下:

packages=['root', 'root.A', 'root.B', ],

导入我使用的内部.py文件的内容:

to import the content of the inner .py files i use:

from root.A import 1
from root.B.3 import a_func

现在,如果我想直接从根模块导入a_func,我会将以下行添加到根目录的init文件中

now, if i wanted to import a_func directly from the root module, i would add the following line to the init file in the root directory

# to allow root.a_func access
from .B.3 import a_func

但是有没有办法导入整个模块而不是单个特定项目(同时保留相同的目录结构)?

but is there a way to import an entire module instead of a single specific item (while preserving the same directory structure) ?

from root import 1
from root.3 import a_func

换句话说,是否可以在导入期间隐藏中间级别模块的访问权限?

in other words, is it possible to hide the access of an intermediate level module during import?

我已经尝试将以下行添加到根目录中的init文件中,但是它不起作用.

I have already tried to add the following lines to the init file in the root dir, but it does not work.

from .A import *
from .B import *

有什么建议吗?

推荐答案

修改 __ path __ 变量可能会有所帮助.

Modifying the __path__ variable might help.

# root/__init__.py
import os
__path__.append(os.path.join(os.path.dirname(__file__), 'A'))

# root/A/__init__.py
# empty

# root/A/one.py
def first_func():
    print("first_func belongs to:", __name__, "in:", __file__)


这允许执行以下操作:


This allows to do the following:

$ python3 -c "from root import one; one.first_func()"
first_func belongs to: root.one in: /home/sinoroc/workspace/root/.venv/lib/python3.6/site-packages/root-0.0.0.dev0-py3.6.egg/root/A/one.py

以及:

$ python3 -c "from root.A import one; one.first_func()"
first_func belongs to: root.A.one in: /home/sinoroc/workspace/root/.venv/lib/python3.6/site-packages/root-0.0.0.dev0-py3.6.egg/root/A/one.py


请参阅:


See:

这篇关于导入模块,因为它是更高的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆