为什么相对导入会将我导入的模块添加到我的命名空间?

时间:2017-09-19 12:44:23

标签: python import python-import relative

当我执行from .module import something之类的相对导入时,something module都会添加到我的命名空间中:

from .module import something
print(module) # output: <module 'package.module' from '/.../package/module.py'>

我希望print(module)抛出一个NameError。

然而,这并不总是发生 。考虑一下这个包结构:

package/
    __init__.py
    module.py
    subpackage/
        submodule.py
        another_submodule.py

module.py包含def function(): pass

another_submodule.py包含something = 0

submodule.py包含

from .another_submodule import something
stuff = 0

__init__.py包含

from .module import function
from .subpackage.submodule import stuff

print('"module" in package?', 'module' in globals())
print('"subpackage" in package?', 'subpackage' in globals())
print('"submodule" in package?', 'submodule' in globals())
print('"submodule" in subpackage?', 'submodule' in subpackage.__dict__)
print('"another_submodule" in submodule?', 'another_submodule' in subpackage.submodule.__dict__)

运行import package会产生此输出:

"module" in package? True
"subpackage" in package? True
"submodule" in package? False
"submodule" in subpackage? True
"another_submodule" in submodule? False

正如我们在此处所见,即使another_submodule执行相对导入,submodule也无法导入Clear-Host $SubscriptionName = "MySubName" $StorageAccountName = "MyStorageAccountName" $StorageAccountKey = "SecretKey" $ContainerName = "MyContainerName" $localTargetDirectory = "/home/" #Set up the storage account context $ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey Get-AzureStorageContainer -Context $ctx $blobs = Get-AzureStorageBlob -Container $ContainerName -Context $ctx foreach($Blob in $blobs){ Get-AzureStorageBlobContent -Blob $Blob.Name -Container $ContainerName -Destination $localTargetDirectory -Context $ctx -Force }

这里发生了什么?这是一个错误还是记录在案的功能?

0 个答案:

没有答案