假设我的 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的上下文变量可以用于此目的吗?如何?
- 这就是这些上下文变量的用途吗?
- 如何使用 Python v3.6 或更早版本执行此操作?
编辑
由于多种原因(架构遗留、库等),我不能/不会更改中间函数的签名f2,所以我不能只user_id作为参数传递,也不能将所有这些函数放在同一个类中。