How to inject variable into scope with a decorator?

前端 未结 11 2099
我寻月下人不归
我寻月下人不归 2020-12-04 17:31

[Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python\'s scoping works here]

I\'m trying to find a way to make a dec

11条回答
  •  星月不相逢
    2020-12-04 17:58

    There is a clean way to do what you want without using global variable. If you want to be stateless and threads safe, you don't really have the choice.

    Use the "kwargs" variable:

    c = 'Message'
    
    def decorator_factory(value):
        def msg_decorator(f):
        def inner_dec(*args, **kwargs):
            kwargs["var"] = value
            res = f(*args, **kwargs)
            return res
        return inner_dec
    return msg_decorator
    
    @decorator_factory(c)
    def msg_printer(*args, **kwargs):
        print kwargs["var"]
    
    msg_printer()
    

提交回复
热议问题