How to inject variable into scope with a decorator?

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

    Update __globals__ works for me.

    def f():
        print(a)
    
    
    def with_context(**kw):
        def deco(fn):
            g = fn.__globals__
            g.update(kw)
            return fn
    
        return deco
    
    
    with_context(a=3)(f)() # 3
    

提交回复
热议问题