Python变量声明和函数错误

Python variable declaration and function error

我有一个关于 Python 的问题。

我想在函数内部使用一个变量,但我得到了这个错误:

NameError: name 'BP' is not defined

这是我的代码:

# File 1 test.py:
from importlib import import_module

def test():
    print(BP)
    print(BP["test2"].d)

if __name__ == "__main__":
    BP: (dict) = {}
    BP.update({"test2": import_module(".test2", "test_folder")})



# File 2 file2.py in test_folder:
from test import test

d: (dict) = {"Hello": "World"}

print("hi")
test()

所以我的问题是:为什么这不起作用?

关于:

if __name__ == "__main__":

只有当您实际上 运行 test.py 文件时才会如此,而 而不是 当您只是导入它时,就像您在 file2.py 中所做的那样。在后一种情况下,没有代码 运行 将 BP 变量绑定到对象,因此调用 test 会报错。