Python3、全局变量、模块

Python 3, Global Variables, Modules

如何将此代码移动到模块中的函数中? 我有全局变量 'last_msg' 和 'fake'。我试图在我的函数中将 'global' 用于 'last_msg',但它超出了范围,因为函数在模块中,但在主范围中是 'last_msg'。

main.py

from module import Timeout

last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake = Timeout(fake, name, timeout)

>> NameError: name 'last_msg' is not defined

<>

module.py

def Timeout(fake, name, timeout):
    global last_msg

    if not fake:
        if name not in last_msg:
            last_msg[name] = 0

        if last_msg[name] > 0:
            last_msg[name] -= 1
            fake = True
        else:
            last_msg[name] = timeout
    else:
        if name in last_msg:
            last_msg[name] = 0

    return fake

看来我已经做到了。

main.py

from module import Timeout

last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake, last_msg = Timeout(fake, name, last_msg, timeout)

<>

module.py

def Timeout(fake, name, last_msg, timeout):
    if not fake:
        if name not in last_msg:
            last_msg[name] = 0

        if last_msg[name] > 0:
            last_msg[name] -= 1
            fake = True
        else:
            last_msg[name] = timeout
    else:
        if name in last_msg:
            last_msg[name] = 0

    return fake, last_msg

link 提供了一些有关如何访问全局变量以及 python 如何处理全局变量的信息。为此,代码将是:

module.py
def Timeout(fake, name, timeout):
    import main

    if not fake:
        if name not in main.last_msg:
            main.last_msg[name] = 0

        if main.last_msg[name] > 0:
            main.last_msg[name] -= 1
            fake = True
        else:
            main.last_msg[name] = timeout
    else:
        if name in main.last_msg:
            main.last_msg[name] = 0

    return fake

并且 main.py 看起来像这样:

last_msg = {'Foo': 0}
from module import Timeout

# last_msg = {'Foo': 0}
name = 'Foo'
fake = False
timeout = 3

fake = Timeout(fake, name, timeout)