generic objects (including lambdas) as dict keys?: not usually a problem

kirby urner <[email protected]>
Newsgroups gmane.comp.python.education
Message-ID <CAPJgG3Rpzk6xJBrf_cstthywXmVrFrr_vXYOqqjedtYKq+584A@mail.gmail.com>
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

_______________________________________________
Edu-sig mailing list
[email protected]
https://mail.python.org/mailman/listinfo/edu-sig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.