Why does not Python accept functions with no names?

Avi Gross avigross at verizon.net
Sun Feb 20 13:22:50 EST 2022


Not really. Anonymous functions are anonymous in name only, so to speak.
When you call a function and pass it an argument that is an anonymous function definition, it is bound to a variable within the function and used mostly in a non-anonymous way. You did not bother giving it a name but it is referenced and retains an existence until it goes out of scope. Not having a name within your own scope means you do not have to do anything like deleting it further in your code. But most code that uses anonymous functions could be rewritten to use a named function. 
However, a compiler or interpreter may well be optimized to decide to ignore or even rewrite things. Consider what it might do to something like "if (5 < 4) ..." where all the code in the ellipsis can never be reached and hence it and the entire statement can be silently removed or ignored OR perhaps reported as a logical error. The code is absolutely valid in terms of syntax, but not valid as having any purpose. But what if all the above is the body of another statement like an "else" which would become a problem if you removed this code? Obviously you might have to walk up the tree and trim more.
Declaring an anonymous function in a context where it attaches to no names anywhere can be allowed to proceed, if that is important to anyone, but garbage collection will rapidly reclaim the space, I would think. So why bother allocating the space? And note if the allocation method is odd and leaves it entirely out of the tables that keep track, you then would have a memory leak.


-----Original Message-----
From: Abdur-Rahmaan Janhangeer <arj.python at gmail.com>
To: Chris Angelico <rosuav at gmail.com>
Cc: Python <python-list at python.org>
Sent: Sun, Feb 20, 2022 12:27 pm
Subject: Re: Why does not Python accept functions with no names?

Thanks for the answers.

@Chris 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.

Kind Regards,

Abdur-Rahmaan Janhangeer
about <https://compileralchemy.github.io/> | blog
<https://www.pythonkitchen.com>
github <https://github.com/Abdur-RahmaanJ>
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list