Context variables in Python

后端 未结 3 2060
梦如初夏
梦如初夏 2020-12-31 07:49

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

3条回答
  •  借酒劲吻你
    2020-12-31 07:57

    You can use kwargs in your function calls in order to pass

    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, user_id=user_id)
    
    def f2(operation, **kwargs):
        # do something, not important, and then call another function
        f3(operation, **kwargs)
    
    def f3(operation, **kwargs):
        # get user_id if there is a variable user_id in the context, get `None` otherwise
        user_id = kwargs.get("user_id")
        # do something with user_id and operation
    

    the kwargs dict is the equivalent to what you are looking at in context variables, but limited at a call stack. It is the same memory element passed (through pointer-like) in each function and not duplicates variables in memory.

    In my opinion, but I would like to see what you all think, context variables is an elegant way to authorize globals variables and to control it.

提交回复
热议问题