Do all calls have __name__?

I have a decorator that writes the name of a decorated function (by the way).

Is it safe to access the attribute of a __name__decorated function? Or is there some called type that does not have a name that is not running yet?

+4
source share
2 answers

Answering my own question with a summary of other answers and comments.

Not all challenges have __name__.

  • Instances of classes that define __call__may not have an attribute __name__.

  • Objects created with help functools.partialdo not have an attribute __name__.

The workaround is to use three arguments getattr:

name = getattr(callable, '__name__', 'Unknown')

repr(callable) 'Unknown', :

name = getattr(callable, '__name__', repr(callable))
+3

:

def d():
    pass

l = lambda: None
print(d.__name__)
print(l.__name__)

:

> d 
> <lambda>

( ):

l.__name__ = 'Empty function'
print(l.__name__)  # Empty function

__call__, __name__.

class C(object):
    def __call__(self):
        print('call')

print(C().__name__)  # AttributeError: 'C' object has no attribute '__name__'

@felipsmartins , functools.partial __name__.

:

"" Python?

+5

Source: https://habr.com/ru/post/1614816/


All Articles