0

Suppose you have a decorator which accepts an argument as an input decor(N). This decorator is used to decorate a method within a module funcs.py

# funcs.py

@decor(N=10)    
def testMethod():
# do something
return something

This funcs.py module is now imported in main.py where testMethod is called.

# main.py

import funcs as funcs

funcs.testMethod()

Question: How can I alter N from `main.py' ?

My attemp was to set N as an attribute of funcs.py , but when I tried to alter this attribute funcs.N = 20 within main.py, funcs.testMethod run with N=10.

NSK
  • 95
  • 7
  • 1
    Does this answer your question? [Does python allow me to pass dynamic variables to a decorator at runtime?](https://stackoverflow.com/questions/37789212/does-python-allow-me-to-pass-dynamic-variables-to-a-decorator-at-runtime) – MrJuicyBacon Jul 21 '21 at 09:45
  • Not really, as i was looking a way to alter the decorator's argument without passing it in my testMethod argument's at all. Anyway, i worked it another way around. I ll post it below as an answer. Thanks a lot – NSK Jul 23 '21 at 12:36

1 Answers1

0

My workaround was this. I removed the argument from the decorator, and i handled it as an argument from the main.py

# funcs.py

N=10

def decor(function):
    def run_function_for_some_N(*args, **kwargs):
        if N == 10:
            print(f'N = {N}. Run testMethod ')
            return function(*args, **kwargs)
        else:
            print('N != 10. Will not run testMethod')
    return run_function_for_some_N

@decor
def testMethod():
    print('hello world')

I can now alter N from main.py

# main.py

import funcs as funcs

for funcs.N in [10,11]:
    funcs.testMethod()

Output

N = 10. Run testMethod 
hello world
N != 10. Will not run testMethod
NSK
  • 95
  • 7