[Tutor] modified dictionary class

Hugo Arts hugo.yoshi at gmail.com
Mon Dec 6 15:37:52 CET 2010

On Mon, Dec 6, 2010 at 2:47 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Oops, too quick. I neant to add:
> But this line seems to return a value so the return values of this function
> seem to be incompatible which is not a good design pattern.

I agree it's not the clearest way to do this, but not because of
incompatible return values. Attribute and Method access have the same
syntax on objects, and __getattr__ is only called if the attribute
isn't found "in the usual places," so it won't hide other methods. In
other words:

>>> a = Structure()
>>> a["spam"] = 5
>>> a.__getstate__()
>>> a.spam

Doesn't look that strange to me, interface-wise. Attribute access
sometimes returns a function and sometimes not. The comment
specifically states it's faking a method, so it's pretty clear.

I do have a few other gripes though:

* why not just define __getstate__ in the class? why return a new
lambda every time when you can just write "def __getstate__(self):
return None"  and be done with it? This also simplifies getattr.

* it's now impossible to have keys that collide with a method name:
dict, items, keys, clear, popitem, et cetera. You can set them without
error, but when you try to get them you'll get the old method, which
might cause hard-to-find bugs

* it's not much of an advantage over regular dicts, really. You limit
yourself to string keys, you make it very unclear that you're using a
dict, it's not as efficient, and really just unpythonic in general.
Why do this at all? To make python more Matlab-like?


More information about the Tutor mailing list