[Edu-sig] generic objects (including lambdas) as dict keys?: not usually a problem
kirby urner
kirby.urner at gmail.com
Tue Mar 20 13:47:13 EDT 2018
I just discovered for myself what many must already know: lambda
expressions may serve as dict keys (I knew values). That means they may
partake of the mutability of some functions, in having mutable default
parameter values.
In [122]: d = {lambda x=[10]: print(x.append(11), x) : 3}
In [123]: list(d.keys())[0]()
None [10, 11]
In [124]: list(d.keys())[0]()
None [10, 11, 11]
In [125]: list(d.keys())[0]()
None [10, 11, 11, 11]
In [126]: list(d.keys())[0]()
None [10, 11, 11, 11, 11]
That's not going to corrupt the dict though. In general, callable objects
may serve as keys, with lambda expressions a special case. So what if the
object points to mutable content.
In [127]: class Callable:
...: def __init__(self):
...: self.the_list = []
...: def __call__(self, *args):
...: self.the_list.extend(args)
In [128]: obj = Callable()
In [129]: the_dict = {obj : 3}
In [130]: list(the_dict.keys())[0]("troll farm")
In [131]: obj.__dict__
Out[131]: {'the_list': ['troll farm']}
On the other hand, if you define __eq__ vis-a-vis something mutable, then
the dict-maker will have 2nd thoughts about the viability of your
enterprise.
So nothing that earth-shaking. It's the Python we all know.
Just thought I'd say hi. More soon.
Kirby Urner
Portland, OR
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20180320/0e4823f0/attachment.html>
More information about the Edu-sig
mailing list