1

I'm trying to decorate a function but I want the decorated version of the function to "look" like the original function. Trivial example:

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    wrapper.__name__ = func.__name__
    wrapper.__str__ = lambda x: str(func)
    wrapper.__repr__ = lambda x: repr(func)

    return wrapper

But when I do something like str(wrapped_function) I get something uninformative like <function decorator.<locals>.wrapper at 0x10323e048>.

How can I edit this so that it returns the correct repr and str?

Not a duplicate of this question as (although the solution is the same), the question is useful and different.

Hameer Abbasi
  • 1,292
  • 1
  • 12
  • 34
  • 2
    Possible duplicate of [What does functools.wraps do?](https://stackoverflow.com/questions/308999/what-does-functools-wraps-do) – Aran-Fey Feb 10 '18 at 10:29
  • @Aran-Fey I was not aware of `functools.wraps`. That said, this is a different question with a similar solution, I don't think that counts as a duplicate. – Hameer Abbasi Feb 10 '18 at 10:31
  • 1
    If the *answer* is the same, you should accept the duplicate nomination. There is no way you can realistically hope to receive several long, detailed, correct, informative answers when everyone agrees that the other question already has them. Your question will remain visible, though no new answers can be posted here if it's closed as a duplicate. – tripleee Feb 10 '18 at 10:46
  • It answers your question and explains every last detail of what's happening and why you get that output. I don't see a problem with closing this as a duplicate. Would you prefer to get a 3-word answer "Use `functools.wraps`" instead? – Aran-Fey Feb 10 '18 at 10:46
  • You're right. Can I accept the nomination after declining it? I already voted to close. – Hameer Abbasi Feb 10 '18 at 10:47
  • I don't think you can. You already have 3 close votes so things will probably run their course. Ping me in a couple of days if this is still open, or flag for moderator attention and explain the situation. – tripleee Feb 10 '18 at 11:11

0 Answers0