-
Notifications
You must be signed in to change notification settings - Fork 23
Description
Imported from BitBucket:
Reported by Anonymous, created 6 months ago.
It doesn't seem possible to have a return element for getitem. For example:
from dingus import Dingus
d = Dingus(__getitem____returns='foo')
print d['bar'] # expects 'foo' but you get the initial dingus
Another option is to try this:
d = Dingus(**{"['bar']__returns": 'foo'})
d['bar']
This ends up adding a getitem call to the call list.
Gary Bernhardt / garybernhardt
Wow, good catch. This is because getitem is an actual method, not just another dingus like most attributes. I'm at a bit of a loss about how to make this work without introducing a ton of internally confusing complexity. I think that the getattr function would have to return a special dingus that, when called, logs the special method name in the parent and does the normal getattr stuff.
That last bit is important: dinguses act as perfectly valid dictionaries, and that needs to remain true.
Fortunately, that means you can temporarily work around your problem by doing:
>>> d = Dingus()
>>> d['foo'] = 'bar'
>>> print d['foo']
bar
You could also monkey patch a new getattr onto the dingus if you really need it to return a specific value regardless of how it's called. Ugly, I know, but I'm definitely not going to have time to fix this soon. :( Clever patches are encouraged, of course! :)
Gary Bernhardt / garybernhardt
Actually, if you need a dingus to return a value regardless of the getitem key, a better short-term solution would be to just subclass Dingus and override getitem to return the value.
My allergy to inheritance sometimes keeps me from seeing it when it really is the solution you want! ;)