如何在Python中正确定义整个包中全局变量?

时间:2019-06-12 11:03:29

标签: python global-variables python-import

具有两个具有以下内容的文件var undef: undefined; const mapped: Mapped = {a: undef, b: undef}; // Warnings! a.py可以正常工作:

b.py
# a.py

import b

def a_logger(msg):
    print("a logger:", msg)

b.run()

b.set_logger(a_logger)
b.run()

打印

# b.py

def b_logger(msg):
    print("b logger:", msg)

def set_logger(logf):
    global b_logger
    b_logger = logf

def run():
    b_logger('hello world!')

b logger: hello world! a logger: hello world! 移入模块也可以。 但是,当按如下方式组织成一个包时,它会破坏:

b.py
# aa.py
import bb

def a_logger(msg):
    print("a logger:", msg)

bb.run()

bb.set_logger(a_logger)
bb.run()
# __init__.py

from .bb import set_logger
from .cc import run
# bb.py

def _bb_logger(msg):
    print("b logger:", msg)

def set_logger(logf):
    global _bb_logger
    _bb_logger = logf

打印

# cc.py

from .bb import _bb_logger

def run():
    _bb_logger('hello world!')

显然,b logger: hello world! b logger: hello world! 保留了自己的cc.py副本。为什么,如何获得预期的行为?


一些观察:

  • 使用类或列表将函数封装起来,所以问题似乎出在
  • _bb_logger语句移到from .bb import _bb_logger函数中也可以正常工作

0 个答案:

没有答案