Why is lambda allowed as a key in a dict?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 10 11:23:43 EDT 2009


En Tue, 10 Mar 2009 13:00:18 -0200, Vito De Tullio  
<zak.mc.kraken at libero.it> escribió:

> MRAB wrote:
>
>>  >>> (lambda arg: arg) == (lambda arg: arg)
>> False
>
> curious...
> I somehow thinked that, whereas
>
>>>> (lambda: 0) is (lambda: 0)
> should be False (obviously)
>
>>>> (lambda: 0) == (lambda: 0)
> could be True... maybe because `{} == {} and {} is not {}` (also for [])

Neither {} nor [] have any attributes by their own; people is only  
interested in their contents. Even a bare object() (that has no  
attributes) compare unequal to another instance:

py> object() == object()
False

But functions (and lambda is just syntactic sugar for an anonymous  
function) have many attributes:

__dict__, func_dict
__doc__, func_doc
__module__
__name__, func_name
func_closure
func_code
func_defaults
func_globals

'==' should compare all of them, and hash() should take them into account  
too... Too much effort just for the very few cases when two functions  
actually would compare "equal" - and, who cares?

-- 
Gabriel Genellina




More information about the Python-list mailing list