Why is lambda allowed as a key in a dict?

D

Daniel Fetchinson

Python 2.5.1 (r251:54863, Oct 30 2007, 13:45:26)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
x = { }
x[lambda arg: arg] = 5
x[lambda arg: arg]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: <function <lambda> at 0x2aaaaabaab18>

Is this a case of "we are all adults here"? I should only blame myself
for making an unnamed function a dictionary key or should it be
forbidden? Or am I missing something completely?

Cheers,
Daniel
 
I

Iain King

Thanks a lot for all the helpful replies!
Yes, I should name the unnamed lambda function, or better, just use 'def'..

Cheers,
Daniel


Sort of tangenitally; is there any real difference between the outcome
of the two following pieces of code?

a = lambda x: x+2

def a(x):
return x+2

Iain
 
S

S Arrowsmith

Iain King said:
Sort of tangenitally; is there any real difference between the outcome
of the two following pieces of code?

a = lambda x: x+2

def a(x):
return x+2

a.__name__

As for why that matters, try a(None) and see which gives the more
informative traceback.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top