简体   繁体   English

无法解决“导入为”的情况(“AttributeError模块x没有属性y”)

[英]Cannot resolve “import as” situation (“AttributeError module x has no attribute y”)

I have a project with the following structure: 我有一个具有以下结构的项目:

project/
    driver.py
    lib/
        __init__.py
        core/
            util.py
            common.py
            __init__.py

# project/driver.py

import lib.core.common as abc
pass

# project/lib/core/__init__.py

from .util import Worker

# project/lib/core/util.py

import lib.core.common as abc

class Worker:
    pass

# project/lib/core/common.py

def stuff():
    pass

Now when I run python3 driver.py (from project's directory), I get the following error: 现在,当我运行python3 driver.py (从项目的目录)时,我收到以下错误:

Traceback (most recent call last):
  File "driver.py", line 1, in <module>
    import lib.core.common as abc
  File "/home/user/project/lib/core/__init__.py", line 1, in <module>
    from .util import Worker
  File "/home/user/project/lib/core/util.py", line 1, in <module>
    import lib.core.common as abc
AttributeError: module 'lib' has no attribute 'core'

This happens only when both conditions are met: 当满足两个条件时才会发生这种情况:

  1. When I do import lib.core.common as abc instead of import lib.core.common . 当我import lib.core.common as abc而不是import lib.core.common
  2. When the project/lib/core/__init__.py contains from .util import Worker import. project/lib/core/__init__.py包含from .util import Worker导入时。

The thing is that I would like to keep the import lib.core.common as abc import form. 问题是我想将import lib.core.common as abc导入表单。

Could anybody explain what's going on here, please? 有人能解释一下这里发生了什么吗?

You have circular dependent imports. 您有循环依赖导入。 you try to execute 你试着执行

import lib.core.common as abc

in two files, in driver.py and in util.py 在两个文件中,在driver.pyutil.py

The easiest way to fix this is to move the path import to the end of the node module, some docs , or 解决此问题的最简单方法是将路径导入移动到节点模块的末尾, 某些文档

def dostuff():
    from foo import bar
    ...

or this also will work, 或者这也会起作用,

from lib.core import common as abc

When Python imports a module, it checks the module registry to see if the module was already imported. 当Python导入模块时,它会检查模块注册表以查看模块是否已导入。 If the module was already registered, Python uses that existing object from cache. 如果模块已经注册,Python将使用缓存中的现有对象。 The module registry is a table of modules that have been initialized and indexed by module name. 模块注册表是已按模块名称初始化和索引的模块表。 This table can be accessed through sys.modules . 可以通过sys.modules访问此表。

If it was not registered, Python finds the module, initializes it if necessary, and executes it in the new module's namespace. 如果它没有注册,Python会找到该模块,必要时对其进行初始化,并在新模块的命名空间中执行它。

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

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