0
def Decorator(*pos, **kwargs):
    def innerFunc(arg, num):
        arg()
        print('Inner function')
        print(kwargs['name'])
    return innerFunc

@Decorator(name = 'Michael')
def inputFunc():
    print('Input Function')

Why does applying the Decorator to inputFunc automatically call it? I would like to pass in some arguments to the decorated function but cannot because the Decorator already calls it

Streamline Astra
  • 307
  • 2
  • 11
  • 2
    That's just the way Python decorators work, if you want to pass arguments, you need to add a 2nd wrapper between `inner_func` and `decorator`, call it `outer_func`. Google around and you'll find it. – Mark Mikofski Feb 08 '20 at 22:55
  • 1
    `@decorator def f(): ...` is equivalent to `def f(): ...` and then `f = decorator(f)`, so that's why the `decorator` function is called immediately. – kaya3 Feb 08 '20 at 22:58
  • It doesnt call the innerFunc when i dont pass in arguments to the decorator – Streamline Astra Feb 08 '20 at 23:02

1 Answers1

-3

In your example, remove the arg() call:

def Decorator(*pos, **kwargs):
    def innerFunc(arg, num):
        # arg()  <-- this is calling the function
        print('Inner function')
        print(kwargs['name'])
    return innerFunc

@Decorator(name = 'Michael')
def inputFunc():
    print('Input Function')
Tiger-222
  • 6,677
  • 3
  • 47
  • 60
  • 1
    This isn't really right; if you run the OP's code, it gives a `TypeError` on calling `innerFunc` so `arg` never actually gets called. This also isn't a correct way to write a decorator which takes arguments, and if you don't use `arg` then it's not really a proper decorator at all. You need two levels of nested functions, one returning a decorator, which returns a wrapped function. – kaya3 Feb 08 '20 at 23:00
  • I answered to the "Why does applying the Decorator to inputFunc automatically call it?" question. You are right, this is not a good example nor the good way to create a decorator. – Tiger-222 Feb 08 '20 at 23:13
  • 1
    But your answer doesn't answer it; the OP's code never actually calls `arg` because there is a `TypeError` first. Your code raises the same `TypeError` for the same reason. The OP's code calls `innerFunc`, and your answer doesn't explain why. – kaya3 Feb 08 '20 at 23:14