Python中的相对导入 [英] Relative imports in Python

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

问题描述

嘿所有 - 我用Python中的相对导入拉出我的头发。我已经阅读了30次文档和SO和其他论坛上的大量帖子 - 似乎仍然没有用。

Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.

我的目录结构目前看起来像这样

My directory structure currently looks like this

src/
    __init__.py
    main.py
    components/
        __init__.py
        expander.py
        language_id.py
    utilities/
        __init__.py
        functions.py

我希望expandder.py和language_id.py能够访问功能模块。我运行python main.py,它可以很好地从components.expander import *和components.language_id import *。访问模块。

I want expander.py and language_id.py to have access to the functions module. I run python main.py which accesses the modules just fine with from components.expander import * and components.language_id import *.

然而,扩展器内的代码和language_id到访问功能模块:

However, the code inside expander and language_id to access the functions module:

from ..utilities.functions import *

我收到此错误:

ValueError: Attempted relative import beyond toplevel package

我已经过了很多次,似乎遵循文档。任何人对这里出了什么问题都有任何想法吗?

I have gone over it a bunch of times and it seems to follow the documentation. Anyone have any ideas of what's going wrong here?

推荐答案

没关系,我解决了这个问题:

Nevermind, I solved it:

src/
    main.py
    mod/
        __init__.py
        components/
            __init__.py
            expander.py
            language_id.py
        utilities/
            __init__.py
            functions.py

main.py然后将子包引用为:

main.py then refers to the subpackages as:

from mod.components.expander import *
from mod.utilities.functions import *

expander.py和language_id.py可以访问functions.py,其中包含:

expander.py and language_id.py have access to functions.py with:

from ..utilities.functions import *

但有趣的是我在componentsder.py使用的components目录中有一个文本文件。但是,在运行时,即使文件位于同一目录中,也无法找到该文件。我将文本文件移动到与main.py相同的目录,并且它工作正常。似乎违反直觉。

But the interesting thing is that I had a text file inside the components directory that expander.py uses. However, at runtime it couldn't locate the file even though it was in the same directory. I moved the text file to the same directory as main.py and it worked. Seems counter-intuitive.

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

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