简体   繁体   English

Python:“ import package1.module1”的导入行为不一致吗?

[英]Python: Inconsistent importing behavior for “import package1.module1”?

I was assuming that statements of the form 我当时以这种形式的陈述

import package1.module1

were only for packages and modules , but not for an object in a module, so for instance if module1 contains variable1 , I am not able to do 用于模块而不适用于模块中的对象 ,因此例如,如果module1包含variable1 ,则无法执行

import package1.module1.variable1

Here's the perceived inconsistency: assume that module1 and variable1 have the same name, for instance let's say both are called module1 . 这是感知到的不一致:假设module1variable1具有相同的名称,例如,假设两者都称为module1 And, in the __init__.py of package1 I have 而且,在package1__init__.py ,我有

from .module1 import module1

then doing 然后做

import package1.module1

will import the object module1 , not the module module1 . 将导入对象 module1 ,而不是模块 module1 This only works if module1 is the same name for both the object and the module . module1对象模块名称相同时,此方法有效。

The official explanation can be found in the docs : 官方说明可以在docs中找到:

The import statement first tests whether the item is defined in the package; import语句首先测试项目是否在包装中定义; if not, it assumes it is a module and attempts to load it. 如果不是,则假定它是一个模块并尝试加载它。 If it fails to find it, an ImportError exception is raised. 如果找不到它,则会引发ImportError异常。

It seems that import appears to think the object module1 from the module module1 is a module, which is why the import package1.module1 works but yields the object instead. 似乎import似乎认为来自模块module1的对象module1是一个模块,这就是为什么import package1.module1起作用但产生该对象的原因。

As far as a workaround goes, if you try the from _ import _ as x , that will rename the attribute and get around the name shadowing. 就一种解决方法而言,如果您尝试将from _ import _ as x ,将重命名该属性并绕开名称阴影。 It should yield the result you're looking for - a path import of the module module1 (since Python will see type <module> ) and not an object import of the variable module1 . 它应该产生您想要的结果-模块module1的路径导入(因为Python会看到类型<module> ),而不是变量module1的对象导入。

Here is some code output to help illustrate things more clearly: 以下是一些代码输出,可帮助您更清楚地说明问题:

>>> import package1.module1
>>> print(package1.module1)
<module 'package1.module1' from 'package1/module1.pyc'>
>>> from package1.module1 import module1
>>> print(module1)
1
>>> from package1 import m
>>> print(m)
1

Here I did from module1 import module1 as m in the __init__.py of package1 and I set the module1 variable to 1 in module1.py . 在这里,我没有from module1 import module1 as m__init__.pypackage1和我的设置module1变到1 module1.py

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

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