What is so important about __name__ in python?

Viewed 297

A __name__ attribute is assigned to every python function. For example

>>> def f(*args, **kwargs):
...     pass
... 
>>> f.__name__
'f'

Now if we decorate this function with some decorator, we, essentially, return another function with different __name__

>>> def d(f):
...     def w(*args, **kwargs):
...         f(*args, **kwargs)
...     return w
... 
>>> f = d(f)
>>> f.__name__
'w'

It is highly recommended to use wraps from functools to decorate returned function, so that information like __name__ and __doc__ can be copied to original function.

>>> from functools import wraps
>>> def d(f):
...     @wraps(f)
...     def w(*args, **kwargs):
...         f(*args, **kwargs)
...     return w
... 
>>> f = d(f)
>>> f.__name__
'f' 

My question is that what are some serious troubles we can get into if we don't use wraps to copy information? Simply what is so important about __name__ that it should be copied? Simple code, like my example, works fine if we don't use wrap.

One problem, I can think if, is serialization. For example, Django does not allow to use lambda expressions (they are nameless) to be used as default value for model fields.

Can somebody add some more problematic examples? Same question is for class decorators.

0 Answers
Related