Issue #8 open

Can't return a value for __getitem__

Anonymous created an issue

It doesn't seem possible to have a return element for getitem. For example:

{{{

!python

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:

{{{

!python

d = Dingus(**{"['bar']__returns": 'foo'}) d['bar'] }}}

This ends up adding a getitem call to the call list.

Comments (2)

  1. Gary Bernhardt repo owner
    • changed status to open

    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! :)

  2. Gary Bernhardt repo owner

    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! ;)

  3. Log in to comment