【发布时间】:2018-06-14 10:10:00
【问题描述】:
假设我的 Python 应用程序中有一个定义某种上下文的函数——例如 user_id。此函数调用不将此上下文作为函数参数的其他函数。例如:
def f1(user, operation):
user_id = user.id
# somehow define user_id as a global/context variable for any function call inside this scope
f2(operation)
def f2(operation):
# do something, not important, and then call another function
f3(operation)
def f3(operation):
# get user_id if there is a variable user_id in the context, get `None` otherwise
user_id = getcontext("user_id")
# do something with user_id and operation
我的问题是:
- Python 3.7 的Context Variables 可以用于这个吗?怎么样?
- 这就是这些上下文变量的用途吗?
- 如何使用 Python v3.6 或更早版本执行此操作?
编辑
出于多种原因(架构遗留、库等)我不能/不会更改像 f2 这样的中间函数的签名,所以我不能只通过 user_id作为参数,不要将所有这些函数放在同一个类中。
【问题讨论】:
-
您有什么理由不将
user_id作为参数传递给f2和f3? -
您似乎被context这个词的广泛含义所误导;因为我在这里无法识别任何 异步 我不认为这是该概念的预期用途。有点难以决定,但我强烈建议将 user_id 作为参数传递给
f2()和f3()或创建一个类,使用 f1、f2 和 f3 作为方法。您的使用看起来与全局变量非常相似。 -
在你的情况下,使用全局变量有什么区别?
标签: python python-3.x python-3.7