This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| python:decorators [2024/08/30 16:22] – created, page about decorators. Niels | python:decorators [2024/09/30 08:09] (current) – Niels | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| ====== Decorators ====== | ====== Decorators ====== | ||
| - | Decorators | + | Decorators |
| - | the implementation | + | example |
| - | that the decorator is supposed to add and calls the original function. | + | |
| + | <code python> | ||
| + | def decorator_function(func): | ||
| + | ''' | ||
| + | |||
| + | def actual_decorator(*args, | ||
| + | ''' | ||
| + | |||
| + | # do something, before original logic | ||
| + | |||
| + | #call the original function | ||
| + | func(*args, | ||
| + | |||
| + | # and/or do something after. | ||
| + | |||
| + | #return result | ||
| + | |||
| + | #return the actual decorator so it gets called by calling context . | ||
| + | return actual_decorator | ||
| + | |||
| + | </ | ||
| + | |||
| + | example | ||
| + | |||
| + | <code python> | ||
| + | def decorator_function(a, b): | ||
| + | ''' | ||
| + | |||
| + | def additional_wrapper(func): | ||
| + | ''' | ||
| + | |||
| + | def actual_decorator(*args, | ||
| + | ''' | ||
| + | |||
| + | #arguments a and b passed from outer fuction are in scope but read only. | ||
| + | if a > b: | ||
| + | | ||
| + | # do something, before original logic | ||
| + | |||
| + | #call the original function | ||
| + | func(*args, | ||
| + | |||
| + | # and/or do something after. | ||
| + | |||
| + | #return result | ||
| + | |||
| + | # return function to calling context (so that it gets executed). | ||
| + | return actual_decorator | ||
| + | |||
| + | #return fuction to calling context (so that it gets executed). | ||
| + | return additional_wrapper | ||
| + | </ | ||
| - | Than the decorator returns a reference to its inner function. | ||
| - | So the decorator itself does not execute the decorator logic, the calling context does! | ||
| **Related: | **Related: | ||
| Line 13: | Line 62: | ||
| *[[https:// | *[[https:// | ||
| *[[https:// | *[[https:// | ||
| + | *[[https:// | ||
| + | *[[https:// | ||
| + | *[[https:// | ||
| + | *[[https:// | ||
| + | |||
| {{tag> | {{tag> | ||