Custom Decorator

We use the concept of kwargs vs args to create a decorator. For example:

def TestDecorator(fn):
    def helper(*args, **kwargs):
        print(fn(*args, **kwargs))
    return helper

@TestDecorator
def hi():
    return "hello"

if __name__ == "__main__":
    hi()

Output:

hello

Note: without calling fn(*args, **kwargs) the function will never run.

For example:

def Disabled(fn):
    def neverRun(*args, **kwargs):
        pass
    return neverRun 


@Disabled
def hi():
    return "hello"

if __name__ == "__main__":
    print(hi())

This function will output

None

With parameters

To pass a parameter, we need another nested function outside

def Enabled(value: bool):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            if not value: return
            return fn(*args, **kwargs)
        return wrapper
    return decorator

@Enabled(True)
def hi():
    return "hello"
    
if __name__ == "__main__":
    print(hi())

will output

hello

With

@Enabled(False)
def hi():
    return "hello"

will output

None