如何在 Python 中进行相对导入? [英] How to do relative imports in Python?

查看:66
本文介绍了如何在 Python 中进行相对导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这个目录结构:

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

我正在编写 mod1,我需要从 mod2 导入一些东西.我该怎么做?

I'm coding mod1, and I need to import something from mod2. How should I do it?

我尝试了 from ..sub2 import mod2 但我得到了在非包中尝试相对导入".

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

我用谷歌搜索,但只发现了sys.path 操作"黑客.没有干净的方法吗?

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

我所有的 __init__.py 目前都是空的

all my __init__.py's are currently empty

Edit2:我尝试这样做是因为 sub2 包含跨子包(sub1subX 等)共享的类.

I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).

Edit3:我正在寻找的行为与 PEP 366 中描述的相同(感谢约翰 B)

The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)

推荐答案

似乎每个人都想告诉你你应该做什么,而不是仅仅回答问题.

Everyone seems to want to tell you what you should be doing rather than just answering the question.

问题是您通过将 mod1.py 作为参数传递给解释器来将模块作为__main__"运行.

The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.

来自 PEP 328:

相对导入使用模块的 __name__ 属性来确定该模块在包层次结构中的位置.如果模块的名称不包含任何包信息(例如,它被设置为__main__"),那么相对导入将被解析为好像该模块是顶级模块,而不管该模块实际位于文件系统上的哪个位置.

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

在 Python 2.6 中,他们添加了相对于主模块引用模块的功能.PEP 366 描述了这一变化.

In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

更新:根据 Nick Coghlan 的说法,推荐的替代方法是使用 -m 开关在包内运行模块.

Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

这篇关于如何在 Python 中进行相对导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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