python - Python 中的每次激活 "global"变量?

标签 python

这看起来似乎是一件相当奇怪的事情,但我很好奇是否可以在 Python 中的调用链中隐式传递变量而不将其作为参数传递。为了更好地说明这里有一个例子:

这是“正常”方式:

def three(something):
    print(something)

def two(something):
    # ...
    three(something)

def one(something):
    # ...
    two(something)

这就是我想要做的事情:

def three():
    # something is defined implicitly
    print(something)

def two():
    # ...
    three()

def one(something):
    # somehow define something inside a context
    # for this activation 
    two()

为此,onetwothird 不在同一个类中,甚至不在同一个模块中。

最佳答案

  1. 您不想这样做。

  2. 如果您确实想折磨自己,那么您可以创建一个单独的线程并在该线程中运行对 one() 的调用。然后只需使用 threading.local 作为共享状态即可。

  3. 你真的不想这样做。

以下是如何使用线程本地存储:

import threading
state = threading.local()

def three():
    # something is defined implicitly
    print(state.something)

def two():
    # ...
    three()

def one(something):
    # somehow define something inside a context
    # for this activation
    def inner():
        state.something = something
        two()
    t = threading.Thread(target=inner)
    t.start()
    t.join()

if __name__=='__main__':
    one(42)
    one(24)

关于python - Python 中的每次激活 "global"变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032824/

相关文章:

python - 使用 NLTK 在 Python 中的文件的特定区域中使用 sent_tokenize?

python - QtWebkit:loadFinished 和 loadProgress 槽永远不会执行

Python:检查电子邮件时代码随机崩溃

python - 如何判断 InstrumentedAttribute 是否是 sqlalchemy 中的关系?

python - 更改 pycharm 中终端的 virtualenv

python - 设置后是否可以抑制 SQLAlchemy 急切/加入的负载?

python - 用电视节目将消息转发给 super 组

python - 获取 peewee ORM 中的最后一个插入 ID (python)

Python - 将相邻元素分组到列表中的元组中?

python - 合并从 contigs.fa 生成的两行