[Fixed]-Passing import context variables to decorators

1👍

This should provide a dynamic decorator that is evaluated at runtime instead of at definition time

class Config(object):
     x = 5
     y = 6

config = Config()
config2 = Config()

# takes object and atribute as arguments
def dynamic_dec(reference,atrib,kw=None):

    # gets function pointer to wraped function
    def dynamic_dec_functor(functor):

        # creates lamda function to revalueate config value
        def func_wrapper(ref_wrapper=(lambda ref=reference: getattr(ref,atrib))):

            #call original function with result of lambda
            if(kw):
                #store lambda result to keyword arg
                functor(**{kw:ref_wrapper()})
            else:
                #pass lambda result to positional arg
                functor(ref_wrapper())

        return func_wrapper

    return dynamic_dec_functor

@dynamic_dec(config,'x','param')
def func(param="default"):
    print(param)

@dynamic_dec(config2,'y')
def func2(param):
    print(param)

#time to test


print("\n call func and func2 with original config \n")

func()
func2()

print("\n update original config \n")

config.x = 9
config.y = 10

print("\n call func and func2 after config change \n")

func()
func2()

print("\n func2 did not change as it used a different config object \n")

Leave a comment