简体   繁体   English

Python3:模块“ x”没有属性“ y”

[英]Python3: module 'x' has no attribute 'y'

Python import statement is confusing the heck out of me. Python import语句使我感到困惑。 Can someone help me clear this up? 有人可以帮我解决这个问题吗?

file tree looks like this 文件树看起来像这样

root
+- notebook.ipynb
+- lib/
  +- basestation_config.py
  +- config.py
+- config/
  +- valence_pod.json
  +- etc…

in config.py I have: config.py我有:

import json
import os

default_config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'config'))

def read_filepath(filepath):
    with open(filepath, "r") as read_file:
        return json.load(read_file)

def read(filename):
    filepath = os.path.join(default_config_path, filename) + '.json'
    return read_filepath(filepath)

in basestation_config.py I have: basestation_config.py我有:

import config as config
# … a buncha class libraries, including BasestationConfig
def read_basestation_config(config_name = 'valence_pod'):
    return BasestationConfig(config.read(config_name))

in notebook.ipynb I have a test cell: notebook.ipynb我有一个测试单元:

import lib.basestation_config as bsc
bs_config = bsc.read_basestation_config()
display(bs_config)

and when I run it, I get: 当我运行它时,我得到:

<module 'config' (namespace)>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-f2942fb5fb2d> in <module>
      1 import lib.basestation_config as bsc
----> 2 bs_config = bsc.read_basestation_config()
      3 display(bs_config)

/mnt/eng_store/pod/logs/embedded/utils/logutils/indot-py/lib/basestation_config.py in read_basestation_config(config_name)
    270 def read_basestation_config(config_name = 'valence_pod'):
    271     print(config)
--> 272     return BasestationConfig(config.read(config_name))

AttributeError: module 'config' has no attribute ‘read’

When you import config , Python is using the config folder (the one with the JSON file) instead of the lib/config.py module. 当您import config ,Python使用的是config文件夹(一个带有JSON文件的文件夹),而不是lib/config.py模块。 You can check this by printing config.__path__ after importing it: 您可以在导入后通过打印config.__path__进行检查:

import config as config
print(config.__path__)
# _NamespacePath(['/path/to/root/config']) 

_NamespacePath indicates that the folder config is being treated as an implicit Python package , it does not contain an __init__.py like a regular Python package , but the name matches the "config" being imported. _NamespacePath表示文件夹配置被视为隐式Python包 ,它不像常规Python包一样包含__init__.py ,但名称与导入的“ config”匹配。

While looking for a module or package named "foo", for each directory in the parent path: 在为父路径中的每个目录查找名为“ foo”的模块或软件包时:

  • If <directory>/foo/__init__.py is found, a regular package is imported and returned. 如果找到<directory>/foo/__init__.py<directory>/foo/__init__.py导入并返回常规包。
  • If not, but <directory>/foo.{py,pyc,so,pyd} is found, a module is imported and returned. 如果没有,则找到<directory>/foo.{py,pyc,so,pyd} ,将导入并返回一个模块。 The exact list of extension varies by platform and whether the -O flag is specified. 扩展的确切列表因平台以及是否指定-O标志而异。 The list here is representative. 这里的列表是代表性的。
  • If not, but <directory>/foo is found and is a directory, it is recorded and the scan continues with the next directory in the parent path. 如果不是,而是找到<directory>/foo并且它是一个目录,则会记录该目录,并且扫描将继续使用父路径中的下一个目录。
  • Otherwise the scan continues with the next directory in the parent path. 否则,扫描将继续使用父路径中的下一个目录。

Your setup falls under bullet #3, as <directory>/config matches the import config target. 您的设置属于项目符号3,因为<directory>/configimport config目标匹配。 You might then wonder what is <directory> here? 然后,您可能想知道这里的<directory>是什么? That depends on the Module Search Path , stored in sys.path , which is a list of all the directories where Python will look for import targets. 这取决于存储在sys.path模块搜索路径 ,该路径是Python将在其中查找导入目标的所有目录的列表。 When you run your test script under root , the root directory is then added to your sys.path . 当您在root用户下运行测试脚本时, sys.path 目录添加到sys.path

The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. 包含正在运行的脚本的目录位于搜索路径的开始,在标准库路径之前。

Check it by adding this before import config in basestation_config.py : 通过在basestation_config.py中 import config之前添加此选项来进行检查:

import sys
print(sys.path)
# ['/path/to/root', ... ]

import config as config

That explains the why. 这就解释了为什么。 To fix this, you can do this: 要解决此问题,您可以执行以下操作:

  1. Rename the config folder to something else (ex. jsonfiles ), just to prevent future errors like this and to distinguish it from the config.py module config文件夹重命名为其他名称(例如jsonfiles ),只是为了防止将来发生此类错误并将其与config.py模块区分开
  2. Change lib to follow the regular Python package structure , by adding a __init__.py file under lib to clearly mark it as a package. 更改lib以遵循常规的Python包结构 ,方法是在lib下添加__init__.py文件以将其明确标记为包。

     lib ├── __init__.py ├── basestation_config.py └── config.py 
  3. Lastly, make it clear in basestation_config.py that you are importing the config.py in the same directory. 最后,在basestation_config.py中明确指出要在同一目录中导入config.py
     from . import config as config print(config.__file__) # /path/to/lib/config.py 

Note that, before doing step 3, if you added the print(config.__path__) earlier, make sure to remove it after applying the corrected codes, since it's mostly likely not available on your config.py (you might get " AttributeError: module 'lib.config' has no attribute __path__ "). 请注意,在执行第3步之前,如果您早先添加了print(config.__path__) ,请确保在应用更正后的代码后将其删除 ,因为它很可能在config.py中不可用(您可能会收到“ AttributeError:模块'lib.config'没有属性__path__ “)。

It should now work after those changes. 这些更改之后,它现在应该可以工作了。

暂无
暂无

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

相关问题 Python:AttributeError模块x没有属性y - Python: AttributeError module x has no attribute y 无法解决“导入为”的情况(“AttributeError模块x没有属性y”) - Cannot resolve “import as” situation (“AttributeError module x has no attribute y”) Google Colaboratory-AttributeError:模块X没有属性Y - Google Colaboratory - AttributeError: module X has no attribute Y Python3(anaconda)中的tkinter,“ AttributeError:模块&#39;tkinter&#39;没有属性&#39;Tk&#39;” - tkinter in Python3 (anaconda), “AttributeError: module 'tkinter' has no attribute 'Tk'” GZIP python3 AttributeError:“模块”对象没有属性“压缩” - GZIP python3 AttributeError: 'module' object has no attribute 'compress' AttributeError:模块&#39;selenium.webdriver&#39;没有属性&#39;Chrome&#39;Python3 - AttributeError: module 'selenium.webdriver' has no attribute 'Chrome' Python3 Django Python3-AttributeError:“模块”对象没有属性“ META” - Django Python3 - AttributeError: 'module' object has no attribute 'META' Python3 错误:AttributeError:模块 'urllib' 没有属性 'request' - Python3 error : AttributeError: module 'urllib' has no attribute 'request' Python导入错误:&#39;module&#39;对象没有属性&#39;x&#39; - Python import error: 'module' object has no attribute 'x' AttributeError:部分初始化的模块 x 没有属性 y(很可能是由于循环导入) - AttributeError: partially initialized module x has no attribute y (most likely due to a circular import)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM