How to inject variable into scope with a decorator?

前端 未结 11 2091
我寻月下人不归
我寻月下人不归 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条回答
  •  Happy的楠姐
    2020-12-04 18:07

    I found an interesting post provides a different solution by creating functions on the fly. Basically:

    def wrapper(func):
        cust_globals = func.__globals__.copy()
    
        # Update cust_globals to your liking
    
        # Return a new function
        return types.FunctionType(
            func.__code__, cust_globals, func.__name__, func.__defaults__, func.__closure__
        )
    

    See https://hardenedapple.github.io/stories/computers/python_function_override/

提交回复
热议问题