"Push" attribute from decorator to decorated function in Python
<p>Some basic question from beginner. Is there a way to "push" attribute to a decorated function not using function arguments ?</p>

<pre><code>import sys
from functools import wraps


def decorator_(func):
    @wraps(func)
    def newfunc():
        func.some_attr = 'some_attr'
        func()
    return newfunc

@decorator_
def decorated_function():
    # ??? access some_attr ???
    print some_attr

def main():
    decorated_function()

if __name__ == '__main__':
    sys.exit(main())
</code></pre>

<p>Thanks in advance.</p>

<p>If you set the attribute on <code>new_func</code> instead, you can access it simply as <code>decorated_function.some_attr</code>:</p>

<pre><code>def decorator_(func):
    @wraps(func)
    def newfunc():
        newfunc.some_attr = 'some_attr'
        func()
    return newfunc

@decorator_
def decorated_function():
    print(decorated_function.some_attr)
</code></pre>

<p>Otherwise, <code>wraps</code> makes the original function available as <code>decorated_function.__wrapped__</code> in Python 3:</p>

<pre><code>def decorator_(func):
    @wraps(func)
    def newfunc():
        func.some_attr = 'some_attr'
        func()
    return newfunc

@decorator_
def decorated_function():
    print(decorated_function.__wrapped__.some_attr)
</code></pre>

<p>In Python 2, the <code>__wrapped__</code> is not set by <code>wraps</code>, so we need to set it up manually:</p>

<pre><code>def decorator_(func):
    @wraps(func)
    def newfunc():
        func.some_attr = 'some_attr'
        func()
    newfunc.__wraps__ = func
    return newfunc
</code></pre>

<p>However, this sounds like an XY problem; if you want to pass a value to the <code>decorated_function</code> you should let <code>decorator_</code> pass it as an argument instead.</p>

python decorator