Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want a function that returns a decorator:</p> <pre><code>def status_display_with_comment(comment): def decorator(function): def wrapper(): print(comment) print("Entering", function.__name__) result = function() print("Exited", function.__name__) return result return wrapper return decorator def a_function(): print('a_function executes') a_function_SD_WC = status_display_with_comment('a comment')(a_function) a_function_SD_WC() </code></pre> <p>Also works:</p> <pre><code>@status_display_with_comment('a comment') def a_function(): print('a_function executes') a_function() </code></pre> <hr> <p>The regular, direct decorator already returns a closure:</p> <pre><code>def a_normal_decorator(function): def wrapper(): return function() return wrapper </code></pre> <p><code>wrapper</code> here is a closure since it has to keep <code>function</code> around even after <code>a_normal_decorator</code> finished executing.</p> <hr> <p>For reference, this is how an idiomatic decorator is usually written:</p> <pre><code>import functools def decorator(function): @functools.wraps(function) def wrapper(*a, **kw): return function(*a, **kw) return wrapper </code></pre> <p>That is, it passes arguments to the wrapped function and doesn't throw away its return value. </p> <p><code>functools.wraps</code> copies from the function being wrapped to the wrapper function <code>__name__</code>, <code>__module__</code>, <code>__annotations__</code> and <code>__doc__</code>, the documentation string.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload