B
B
BelBES2017-02-04 23:43:02
Python
BelBES, 2017-02-04 23:43:02

Why is decorator in python called at script start?

Found strange behavior in python3.5.
We write dumb code with a decorator:

def foo(f):
    print("foo")
    f()

@foo
def bar():
    print("bar")

And now, when you try to run a script containing only these lines, it calls the decorated function, and if you try to do something else like this:
print (bar)
First, the decorated function will be called again, and then None will be displayed.
It seemed to me that decorators are syntactic sugar in python and, in theory, should only replace this call with foo (bar) when calling the bar function. Am I misunderstanding something, or is this a bug in python?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2017-02-04
@BelBES

this is syntactic sugar in python and, in theory, should only replace this call with foo (bar) when calling the bar function

A strange causal relationship.
Yes, sugar. And code
@foo
def bar():
    print("bar")

is tantamount to
def bar():
    print("bar")
bar = foo(bar)

Has it become clearer?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question