On Tue, Sep 1, 2020, at 21:06, Ricky Teachey wrote:
> Here's my attempt, it is probably lacking. I'm five years into a 
> self-taught venture in python... If I can't get this right the first 
> time, it worries me a little. 
> 
> 
> MISSING=object()
> 
> def __getitem__(self, key=MISSING, time=MISSING, money=MISSING):
>     if time is MISSING or money is MISSING:
>         if time is not MISSING and key is not MISSING:
>             money = key
>         elif money is not MISSING and key is not MISSING:
>             time = key
>         else:
>             time, money = key
>     
> Is this right? Wrong? The hard way? The slow way? 
> 
> What about when there are three arguments? What then?

I'm using () rather than a MISSING as the sentinel here because it makes the 
code simpler. For the same reason, if we need to choose a key to pass in by 
default for a[**kwargs only] without defining a () in __getitem__, I have 
consistently advocated using () for this. Likewise, *not* having a default [or 
requiring the method to define its own default] key presents a slight problem 
for __setitem__, illustrated below.

def __getitem__(self, key=(), /, **kwargs):
    return self._getitem(*(key if isinstance(key, tuple) else (key,)), **kwargs)
def __setitem__(self, key=(), value=???, /, **kwargs):
    return self._setitem(value, *(key if isinstance(key, tuple) else (key,)), 
**kwargs)
def _getitem(self, time, money):
    ...
def _setitem(self, value, time, money):
    ...
[delitem the same as getitem]

Basically, you can easily write code that leverages the existing function 
argument parsing, simply by performing a function call.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EWJAKIBXQQJNMWT7EXZHAKOUP35YOREV/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to