Why does not Python accept functions with no names?

Eryk Sun eryksun at gmail.com
Sun Feb 20 17:36:54 EST 2022


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)
    )

Since parsing Python depends on white space, if a `def (...) :=`
expression is multiline, the first statement on a new line would set
the indentation level, up to but not including the closing
parenthesis. (Style guides would likely restrict what's considered
good form.) The anonymous function could be called immediately. For
example:

    results[i] = def (x, *, y=0) := (
        if x < y:
            return spam(x)
        return eggs(x)
    )(z)


More information about the Python-list mailing list