Suppose that I have a function in my Python application that define some kind of context - a user_id
for example. This function call other functions that do not take this context as a function argument. For example:
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
My questions are:
- Can the Context Variables of Python 3.7 be used for this? How?
- Is this what these Context Variables are intended for?
- How to do this with Python v3.6 or earlier?
EDIT
For multiple reasons (architectural legacy, libraries, etc) I can't/won't change the signature of intermediary functions like f2
, so I can't just pass user_id
as arguments, neither place all those functions inside the same class.