Why does not Python accept functions with no names?

Python python at example.invalid
Sun Feb 20 11:33:55 EST 2022


Barry wrote:
> 
> 
>> On 20 Feb 2022, at 15:35, Abdur-Rahmaan Janhangeer <arj.python at gmail.com> wrote:
>>
>> Greetings list.
>>
>> Out of curiosity, why doesn't Python accept
>> def ():
>>     return '---'
>>
>> ()
>>
>> Where the function name is ''?
> 
> Because there is no variable that is holding a ref to the code.
> So it’s pointless.

Fun fact, it can be done, but it's (afaik) then (almost) unusable...

 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
 >>> locals()['a'] = 42
 >>> a
42
 >>> locals()[''] = 42
 >>> locals()['']
42
 >>> locals()[''] = (lambda x: x*42)
 >>> locals()[''](1)
42



More information about the Python-list mailing list