How to inject variable into scope with a decorator?

前端 未结 11 2103
我寻月下人不归
我寻月下人不归 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:56

    Python is lexically scoped, so I'm afraid there is no clean way to do what you want without some potentially nasty side effects. I recommend just passing var into the function via the decorator.

    c = 'Message'
    
    def decorator_factory(value):
        def msg_decorator(f):
            def inner_dec(*args, **kwargs):
                res = f(value, *args, **kwargs)
                return res
            inner_dec.__name__ = f.__name__
            inner_dec.__doc__ = f.__doc__
            return inner_dec
        return msg_decorator
    
    @decorator_factory(c)
    def msg_printer(var):
        print var
    
    msg_printer()  # prints 'Message'
    

提交回复
热议问题