Why does not Python accept functions with no names?

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Feb 20 17:17:53 EST 2022


On 21/02/22 6:27 am, Abdur-Rahmaan Janhangeer wrote:
> Well Python deliberately throws an exception if we do not
> pass in a function name. Just wanted to know why it should. As the
> above case is a 100% pure anonymous function.

The syntax for a function definition is defined in the grammar
as requiring an identifier. An identifier in turn is defined
as consisting of at least one character. So the grammar would
need to be changed to make the name optional. Also, the
compiler would need a special case to treat a missing name
there as though it were an empty string.

So again, why *should* it be allowed, given that the parser and
compiler would have to go out of their way to treat it as a
special case, only to create a function that there is no
easy way to call?

BTW, this is not what is usually meant by the term "anonymous
function". An anonymous function is one that is not bound
to *any* name. The thing you're proposing wouldn't be
anonymous -- it would have a name, that name being the empty
string.

-- 
Greg


More information about the Python-list mailing list