python - 分包导入或全路径差

标签 python python-2.7 import global-variables global

从不同路径导入相同的 Python 模块似乎会导致创建两个不同的模块引用。

例如采用以下三个 Python 脚本。 Script1和Script2位于OuterPackage中,TestWithGlobals位于SubPackage中。

+ Root
|_+ OuterPackage
  | - Script1
  | - Script2
  |_+ SubPackage
    | - TestWithGlobals

脚本 1:

from OuterPackage.SubPackage import TestWithGlobals
import Script2
print TestWithGlobals.__name__

print TestWithGlobals.global_string
Script2.MakeStringBall()
print TestWithGlobals.global_string

和脚本2:

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__

def MakeStringBall():
    TestWithGlobals.global_string = "ball"

最后是 TestWithGlobals 本身

global_string = "test"

现在,当 Script1 运行时,输出如下:

SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
test

在 Script2 中将 from SubPackage 更改为 from OuterPackage.SubPackage 将导致 Script1 的输出不同:

OuterPackage.SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
ball

Root 在运行 Script1 之前附加到 pythonpath。

为什么 TestWithGlobals 在 Script1 和 Script2 之间不同,而引用的是同一个模块?这背后的原因是什么?

最佳答案

如果您按如下方式更改代码,它会告诉您更多发生的事情:

脚本1.py

import sys
from OuterPackage.SubPackage import TestWithGlobals
print "In Script1", id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
import Script2
print TestWithGlobals.__name__

print "TestWithGlobals:", TestWithGlobals.global_string
Script2.MakeStringBall()
print "TestWithGlobals:", TestWithGlobals.global_string
print "Script2.TestWithGlobals:", Script2.TestWithGlobals.global_string

脚本2.py

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__
import sys

def MakeStringBall():
    print "In MakeStringBall", id(TestWithGlobals)
    print "In MakeStringBall Subpackage.TestWithGlobals", id(sys.modules['SubPackage.TestWithGlobals'])
    print "In MakeStringBall OuterPackage.SubPackage.TestWithGlobals", id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
    TestWithGlobals.global_string = "ball"

这个的输出是:

In Script1 4301912560
SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
TestWithGlobals: test
In MakeStringBall 4301912784
In MakeStringBall Subpackage.TestWithGlobals 4301912784
In MakeStringBall OuterPackage.SubPackage.TestWithGlobals 4301912560
TestWithGlobals: test
Script2.TestWithGlobals: ball

python 中的导入系统构造新模块并通过它们在 sys.modules 缓存中的导入路径引用它们。在这种情况下,模块在 2 个不同的路径下导入,因此创建了 2 个不同的模块对象(正如您从 id 函数的输出中看到的那样)。

关于python - 分包导入或全路径差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505472/

相关文章:

css - 为什么导入的 css 文件存储在 localstorage 中而不像链接的 css 文件那样刷新?

Python 套接字,高级聊天框

python - 在 Python 中将列表定义为全局变量

python - 测试函数对象(functor)是否相等,如何求值?我使用 `is` 还是 `==` ?

python - 如何根据条件为数据框的列分配值?

python - 如何在对象上进行 str.replace?

python - pyodbc 不报告 sql server 错误

Java 包 - 创建一个按钮并在需要时导入一个按钮

python - Tkinter 文本 : Setting tab spaces not working

c# - 使用 Epplus 的 Excel 时间格式