> On Sat, Feb 6, 2021 at 5:21 PM Random832 <random...@fastmail.com> wrote:
> >
> > While we're on the subject of assignment expression limitations, I've 
> > occasionally wanted to write something like
> >
> > try:
> >     return a_dict[key]
> > except KeyError:
> >     return (a_dict[key] := expression to construct value)

On Sat, Feb 6, 2021, at 01:26, Chris Angelico wrote:
> 
> That's what the __missing__ method is for.

Requires a dict subclass

Requires that the value be determinable from the key alone [rather than any 
other variables available in the function containing the above code]

On Sat, Feb 6, 2021, at 01:50, Brendan Barnwell wrote:
>       You can already do that with `return a_dict.setdefault(key, 
> your_expression_here)`.  If the expression is expensive to evaluate you 
> can use a short-circuiting conditional expression to guard it.

How exactly would you use a short-circuiting conditional expression to do this?

If you're suggesting `... if key not in a_dict else ...` this creates a race 
condition, and also involves checking the key in the dictionary twice.

Perhaps a constructdefault method could be added to dict, broadly equivalent to

def constructdefault(self, func):
    try:
        return self[key]
    except KeyError:
        return (self[key] := func())

you could use self[key] = value = func(); return value; and the same in the 
original [not part of dict class] snippet I posted above, but the point is this 
seems so much like exactly the sort of use case that := is intended for, that 
it comes across as weird that it's not usable.
_______________________________________________
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/OYTML3CG5G5NUX4GSGS533NPAV4CRW46/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to