Why does not Python accept functions with no names?

Chris Angelico rosuav at gmail.com
Sun Feb 20 17:49:23 EST 2022


On Mon, 21 Feb 2022 at 09:38, Eryk Sun <eryksun at gmail.com> wrote:
>
> On 2/20/22, Abdur-Rahmaan Janhangeer <arj.python at gmail.com> wrote:
> >
> > Out of curiosity, why doesn't Python accept
> > def ():
> >     return '---'
>
> The `def` keyword is compiled as an assignment statement, not an
> expression that evaluates anonymously on the stack. Using `def` as an
> expression would require new syntax. For example, maybe something like
> the following:
>
>     funcs[i] = def (x, *, y=0) := (
>         if x < y:
>             return spam(x)
>         return eggs(x)
>     )
>

There's always decorators.

>>> @functools.partial(operator.setitem, funcs, i)
... def _(x, *, y=0):
...     if x < y:
...             return spam(x)
...     return eggs(x)
...
>>> funcs[i]
<function _ at 0x7f6fd4b36b90>

(Has the side effect of setting _ to None.)

ChrisA


More information about the Python-list mailing list