简体   繁体   English

python3.6和python3.7的导入区别

[英]Importing difference in python3.6 and python3.7

I have a question about imports in python3.6 and python3.7.我对 python3.6 和 python3.7 中的导入有疑问。

I have the following dir structure:我有以下目录结构:

.
└── lib
    ├── feature
    │   ├── feature1.py
    │   ├── __init__.py
    │   └── new
    │       ├── feature1.py
    │       └── __init__.py
    └── __init__.py

I have the following in the file lib/feature/__init__.py :我在文件lib/feature/__init__.py有以下lib/feature/__init__.py

from lib.feature.feature1 import Feature1

I have the following in the file lib/feature/feature1.py :我在文件lib/feature/feature1.py有以下lib/feature/feature1.py

import lib.feature.new.feature1 as new

class Feature1: pass

To recreate my environment, you can use the following:要重新创建我的环境,您可以使用以下命令:

mkdir lib
touch lib/__init__.py
mkdir -p lib/feature/new
echo "from lib.feature.feature1 import Feature1" > lib/feature/__init__.py
echo -e "import lib.feature.new.feature1 as new\nclass Feature1: pass" > lib/feature/feature1.py
touch lib/feature/new/__init__.py
touch lib/feature/new/feature1.py

When I run this code with python3.7 it works perfectly fine.当我用 python3.7 运行这段代码时,它工作得很好。 When I run this code with python3.6, I get the following error:当我使用 python3.6 运行此代码时,出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "***/import_test/lib/feature/__init__.py", line 1, in <module>
    from lib.feature.feature1 import Feature1
  File "***/import_test/lib/feature/feature1.py", line 2, in <module>
    import lib.feature.new.feature1 as new
AttributeError: module 'lib' has no attribute 'feature'

So my question is, why is there a different outcome, when you run the code with python3.6 or python3.7?所以我的问题是,当您使用 python3.6 或 python3.7 运行代码时,为什么会有不同的结果?

To fix this issue, I have change the import in lib/feature/feature1.py to:为了解决这个问题,我将lib/feature/feature1.py的导入更改为:

from .new import feature1 as new

To test, I just go to python and try to import the module:为了测试,我只是去 python 并尝试导入模块:

import_test$ python
Python 3.6.8 (default, Dec 25 2018, 00:00:00)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.feature

After that change, it works on python3.6 as well.更改之后,它也适用于 python3.6。

Thanks in advance.提前致谢。

这是一个带有“别名”导入( import .. as )的错误,在 Python 3.7 中得到修复。

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

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