473,881 Members | 1,759 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lambda

why functions created with lambda forms cannot contain statements?

how to get unnamed function with statements?
Jul 18 '05
57 3641
David Eppstein wrote:
Yes, and what should the following do?

lst1 = [1]
lst2 = [2]
dct = {lst1: "1", lst2: "2"}
lst2[0]=1
lst1[0]=2
print dct[[1]]
print dct[[2]]


Provide yet another example for why mutable keys are almost guaranteed to result
in suprising semantics :)

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #51
Antoon Pardon wrote:
As you said yourself, people use shortcuts when they express themselves.
With 'mutable key' I mean a mutable object that is used as a key.
That doesn't contradict that the key itself can't change because
it is inaccessible.
Yeah - this was the point of terminology that was getting confused, I think. And
your interpretation was closer to the strict sense of the words.
Well, the Zen of Python states "In the face of ambiguity, refuse the temptation
to guess".


But python does guess in the case of the value. If I want to establish a
relationship between "foo" and [3, 5, 8] then I can be in big trouble
if that list gets mutated in something else.


However, the actual promise a Python dict makes is that it maps from keys by
value to values by identity.

That is, "k1 == k2" implies "d[k1] is d[k2]". An identity test on mutable
objects is entirely unambiguous (hence they can be values), but comparison is
not (hence they cannot be keys). Restricting keys to immutable objects
eliminates the ambiguity. Copying keys would also prevent mutation and eliminate
the ambiguity. The restriction approach is a *definite* performance enhancement
over the copying approach, though (this is probably the origin of the mantra
"the restriction to mutable keys is a performance enhancement"). The resulting
semantics of the restriction to immutable objects are also significantly less
surprising than those of the copying approach.

An identity dict would make the promise that "k1 is k2" implies "d[k1] is
d[k2]". In this case, the mutability of the key is irrelevant, so the behaviour
is unambiguous without any additional restrictions.
But they don't have to be immutable within the dictionary itself, that
is just an implementation detail. The only thing that matters is that
the dictionary can reproduce the relationship. How that is done is
immaterial.
Given the Python interpreter's current definition of "immutable" as "defines
__hash__", it's a little hard to have an unhashable object as a key :)
In short, sane hash tables require immutable keys, and how mutable keys acquire
the requisite immutability is going to be application dependent.

No they don't, that is just the most easy implementation. If some
implementation would constantly change the internal objects but
consulting the dictionary wouldn't show any different effect then
that would be fine too. And even in this case a mutation
from the outside would probably cause havoc because it would ruin
the sanity of the internal structure.


If you insist: s/immutable/effectively immutable/

And no data type can be expected to tolerate having their invariants violated by
external code messing with internal data structures.
Provision of a safe_dict or identity_dict would merely allow a programmer to
state their intent at the time the container is created, rather than having to
state it whenever keys are generated or referenced.


Well that would be a good thing IMO.


True - I'm not sure how that 'merely' snuck in there :)
Good enough in any case for me to
spend some time analyzing the requirements. Whether I'll actually
implement something depends on how much time I have and how often I
need it.


My preference is for the identity dict - its performance would actually be
*better* than that of a standard dict in the domains where it applies
(annotation and classification of objects are the two main uses I can see for
such a data structure). This aligns quite well with the stated goal of the
collections module (providing data structures that are less general purpose than
the standard builtins, but deliver better performance for their particular use
cases)

Regards,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #52
Antoon Pardon wrote:
Interesting idea. But I think you are wrong when you say that two lists
that compare equal at the time they are frozen, will get the same
dictionary entry. The problem is an object must compare equal to
the key in the dictionary to get at the same entry. So if you freeze
a list and its copy but then mutate them differently, they no longer
are equal and so wont get you at the same entry.


The trick is that the result of the freezing operation is cached until such time
as you explicitly unfreeze the object.

Output:

x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Write via x, read via y: Hi there!
x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y: [0, 1, 2, 3, 4, 5, 6, 7, 8]
Read via mutated x: Hi there!
Read via mutated y: Hi there!
x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y: [0, 1, 2, 3, 4, 5, 6, 7, 8]
Found unfrozen x: False
Found unfrozen y: False
Produced by:

class mylist(list):
def __init__(self, arg):
super(mylist, self).__init__( arg)
self._tuple = None
def frozen(self):
if self._tuple is None:
self._tuple = tuple(self)
return self._tuple
def unfreeze(self):
self._tuple = None

x = mylist(range(10 ))
y = mylist(range(10 ))
dct = {}
dct[x.frozen()] = "Hi there!"
print "x:", x
print "y:", y
print "Write via x, read via y:", dct[y.frozen()]
x.append(10)
del y[-1]
print "x:", x
print "y:", y
print "Read via mutated x:", dct[x.frozen()]
print "Read via mutated y:", dct[y.frozen()]
x.unfreeze()
y.unfreeze()
print "x:", x
print "y:", y
print "Found unfrozen x:", x.frozen() in dct
print "Found unfrozen y:", y.frozen() in dct

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #53
Op 2005-01-20, Nick Coghlan schreef <nc******@iinet .net.au>:
Antoon Pardon wrote:
Interesting idea. But I think you are wrong when you say that two lists
that compare equal at the time they are frozen, will get the same
dictionary entry. The problem is an object must compare equal to
the key in the dictionary to get at the same entry. So if you freeze
a list and its copy but then mutate them differently, they no longer
are equal and so wont get you at the same entry.


The trick is that the result of the freezing operation is cached until such time
as you explicitly unfreeze the object.


I missed that you would use it with the idiom: dct[x.frozen()]

I have two problems with this approach.

1) It doesn't work when you get your keys via the keys/items
methods.

2) This is rather minor, but a user could still unfreeze
untimely

--
Antoon Pardon
Jul 18 '05 #54
Antoon Pardon wrote:
I missed that you would use it with the idiom: dct[x.frozen()]
The list itself isn't hashable with this approach, so you don't have much
choice. I wasn't particularly clear about that point, though.
I have two problems with this approach.

1) It doesn't work when you get your keys via the keys/items
methods.
True - the frozen object has no link back to the original object. That could be
added though (by returning a tuple subtype with the extra attribute)
2) This is rather minor, but a user could still unfreeze
untimely


True - doing that is less likely than mutating a hashable list though :)

I'm just noting this as a way to avoid copying data more than once when storing
immutable copies of mutable data in a dictionary. You're quite right that there
isn't a really clean idiom for doing that in Python (aside from moving to a
different data structure that works natively as a dict key, naturally).

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #55
Op 2005-01-20, Nick Coghlan schreef <nc******@iinet .net.au>:
Antoon Pardon wrote:
I missed that you would use it with the idiom: dct[x.frozen()]


The list itself isn't hashable with this approach, so you don't have much
choice. I wasn't particularly clear about that point, though.
I have two problems with this approach.

1) It doesn't work when you get your keys via the keys/items
methods.


True - the frozen object has no link back to the original object. That could be
added though (by returning a tuple subtype with the extra attribute)
2) This is rather minor, but a user could still unfreeze
untimely


True - doing that is less likely than mutating a hashable list though :)

I'm just noting this as a way to avoid copying data more than once when storing
immutable copies of mutable data in a dictionary. You're quite right that there
isn't a really clean idiom for doing that in Python (aside from moving to a
different data structure that works natively as a dict key, naturally).


The problem here is IMO is the, we are all consenting adults (which we
are not but I wont start on this now), approach.

I have been thinking a bit in your freeze direction, but more thorough.
The idea i had was that freeze would replace all mutating methods
with methods that would throw an exception. a thaw method would inverse
the proces. It would then be the responsibilty of the dictionary to
freeze an object on entry and thaw it when removed. However this
wouldn't work with ordinary python objects, since there is no easy way
to have readonly or private variables.

--
Antoon Pardon
Jul 18 '05 #56
On 20 Jan 2005 14:07:57 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-01-20, Nick Coghlan schreef <nc******@iinet .net.au>:
Antoon Pardon wrote:
I missed that you would use it with the idiom: dct[x.frozen()]


The list itself isn't hashable with this approach, so you don't have much
choice. I wasn't particularly clear about that point, though.
I have two problems with this approach.

1) It doesn't work when you get your keys via the keys/items
methods.


True - the frozen object has no link back to the original object. That could be
added though (by returning a tuple subtype with the extra attribute)
2) This is rather minor, but a user could still unfreeze
untimely


True - doing that is less likely than mutating a hashable list though :)

I'm just noting this as a way to avoid copying data more than once when storing
immutable copies of mutable data in a dictionary. You're quite right that there
isn't a really clean idiom for doing that in Python (aside from moving to a
different data structure that works natively as a dict key, naturally).


The problem here is IMO is the, we are all consenting adults (which we
are not but I wont start on this now), approach.

I have been thinking a bit in your freeze direction, but more thorough.
The idea i had was that freeze would replace all mutating methods
with methods that would throw an exception. a thaw method would inverse
the proces. It would then be the responsibilty of the dictionary to
freeze an object on entry and thaw it when removed. However this
wouldn't work with ordinary python objects, since there is no easy way
to have readonly or private variables.

Would you like a dictionary that acts as you want and takes care of all
problems internally, and accepts keys and values of any type without wrapping
or other modification -- or do you want a wrapper that can make any object
suitable for use as key or value in python's curent definition of dict?

Just DYFR please. You still haven't you know ;-)

Regards,
Bengt Richter
Jul 18 '05 #57
Op 2005-01-21, Bengt Richter schreef <bo**@oz.net> :
On 20 Jan 2005 14:07:57 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:

Would you like a dictionary that acts as you want and takes care of all
problems internally, and accepts keys and values of any type without wrapping
or other modification -- or do you want a wrapper that can make any object
suitable for use as key or value in python's curent definition of dict?

Just DYFR please. You still haven't you know ;-)


My feeling is that I'm hungry and would like to eat and you ask whether
my requirements are a sandwhich or a bowl of soup. :-)

The real requirement IMO is that any attempt to mutate an object wont
result in a mutated key. Both proposals seem to solve that. The second
is at the moment for me the most interesting to discuss, since it is
a new approach to me, and most likely to learn me something new.

--
Antoon Pardon
Jul 18 '05 #58

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

53
3719
by: Oliver Fromme | last post by:
Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions are constructed on the fly. Now my problem is lazy evaluation. Or at least I think it is. :-)
63
3437
by: Stephen Thorne | last post by:
Hi guys, I'm a little worried about the expected disappearance of lambda in python3000. I've had my brain badly broken by functional programming in the past, and I would hate to see things suddenly become harder than they need to be. An example of what I mean is a quick script I wrote for doing certain actions based on a regexp, which I will simlify in this instance to make the pertanant points more relevent.
26
3517
by: Steven Bethard | last post by:
I thought it might be useful to put the recent lambda threads into perspective a bit. I was wondering what lambda gets used for in "real" code, so I grepped my Python Lib directory. Here are some of the ones I looked, classified by how I would rewrite them (if I could): * Rewritable as def statements (<name> = lambda <args>: <expr> usage) These are lambdas used when a lambda wasn't needed -- an anonymous function was created with...
181
8957
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
25
2591
by: Russell | last post by:
I want my code to be Python 3000 compliant, and hear that lambda is being eliminated. The problem is that I want to partially bind an existing function with a value "foo" that isn't known until run-time: someobject.newfunc = lambda x: f(foo, x) The reason a nested function doesn't work for this is that it is, well, dynamic. I don't know how many times or with what foo's this will be done.
4
2638
by: Xah Lee | last post by:
A Lambda Logo Tour (and why LISP languages using λ as logo should not be looked upon kindly) Xah Lee, 2002-02 Dear lispers, The lambda character λ, always struck a awe in me, as with other mathematical symbols. In my mind, i imagine that those obscure math
23
5353
by: Kaz Kylheku | last post by:
I've been reading the recent cross-posted flamewar, and read Guido's article where he posits that embedding multi-line lambdas in expressions is an unsolvable puzzle. So for the last 15 minutes I applied myself to this problem and come up with this off-the-wall proposal for you people. Perhaps this idea has been proposed before, I don't know. The solutions I have seen all assume that the lambda must be completely inlined within the...
5
2170
by: Octal | last post by:
How does the lambda library actually works. How does it know how to evaluate _1, how does it recognize _1 as a placeholder, how does it then calculate _1+_2, or _1+2 etc. The source files seem a bit complicated so any explanation would be appreciated. Thanks
21
1872
by: globalrev | last post by:
i have a rough understanding of lambda but so far only have found use for it once(in tkinter when passing lambda as an argument i could circumvent some tricky stuff). what is the point of the following function? def addn(n): return lambda x,inc=n: x+inc if i do addn(5) it returns
1
2635
by: Tim H | last post by:
Compiling with g++ 4: This line: if_then_else_return(_1 == 0, 64, _1) When called with a bignum class as an argument yields: /usr/include/boost/lambda/if.hpp: In member function 'RET boost::lambda::lambda_ functor_base<boost::lambda::other_action<boost::lambda::ifthenelsereturn_action>
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10399
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5780
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.