Skip to content Skip to sidebar Skip to footer

Python Decorator Function Called At Compile Time

I hope that someone familiar with Python's compilation / run-time procedures could shed some light on my question relating to how Python compiles decorator functions. Within my s

Solution 1:

Your code runs when the module is imported. Python executes all top-level statements, including class definitions at that time.

A class definition body is executed as a function, with the local namespace becoming the class attributes. This means that class bodies are executed on import, provided the class is defined at the top-level of the module.

When Python encounters a decorated function when executing, it'll define the class, then execute the decorator function, passing in the function object and binding the return value of the decorator to the name of the function. Since the class body is executed during import, this means your decorator is executed at that time.

Solution 2:

There is no compile time. A def statement, and the associated decorator calls are executable statements.

Accordingly, when Python loads a module, it executes the statements in order. When executing a class statement, one of the early stages is executing all of the statements in the class body. As part of that defs are run to create functions, and those function objects will be passed to decorators for processing.

Your "testing" print statement will run whenever the decorator is called, not when the function it returns is called. If you want that behaviour, move the decorator into the inner function.

Post a Comment for "Python Decorator Function Called At Compile Time"