Why does not Python accept functions with no names?

Chris Angelico rosuav at gmail.com
Sun Feb 20 23:21:52 EST 2022


On Mon, 21 Feb 2022 at 14:36, Python <python at example.invalid> wrote:
>
> 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
>

Minor nitpick: Please use globals() rather than locals() for this sort
of demo. At module level (including the REPL), they are the same, but
inside a function there's no guarantee that locals() can be mutated in
this way.

ChrisA


More information about the Python-list mailing list