Q:

Python: program to get the real name of decorated function

I want to write a decorator to show the really name of the decorated functions, but something goes wrong when I write in this way.
from functools import update_wrapper

def decorator(d):
    def _decorator(f):
        update_wrapper(d(f), f)
        return d(f)
    return _decorator

@decorator
def add2(f):
    def _add2(x,y):
        return f(x,y)*2
    return _add2

@add2
def add(x,y): return x+y

If I want to get the name of add(x,y), it shows like this:
>>>print add.__name__
_add2

But if I make little change to func decorator like this:
def decorator(d):
    def _decorator(f):
        return update_wrapper(d(f), f)
    return _decorator

The result will be correct:
>>>print add.__name__
add

I'm really confused about that. In my mind, that shouldn't make such difference because they are almost the same. 

A:

You call d(f) twice, and each creates a new wrapper function object; these are independent, new copies. You only a apply update_wrapper() to the first result and return the second.
Call it once:
def decorator(d):
    def _decorator(f):
        wrapper = d(f)
        update_wrapper(wrapper, f)
        return wrapper
    return _decorator

