dict.get(key, default) evaluates default even if key exists

jak nospam at please.ty
Thu Dec 17 07:36:03 EST 2020


Il 17/12/2020 12:40, Peter J. Holzer ha scritto:
> On 2020-12-17 12:16:29 +0100, jak wrote:
>> print(_ if d.get('a', None) is not None else get_default())
> 
> That doesn't work:
> 
>>>> print(_ if d.get('a', None) is not None else get_default())
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> NameError: name '_' is not defined
> 
> But this works:
> 
>>>> print(_ if (_ := d.get('a', None)) is not None else get_default())
> 1
> 
> (I would prefer ChrisA's solution, though.)
> 
>          hp
> 

I had already corrected my oversight (jak 12:32):

 > print((_ if d.get('a', None) is not None else get_default()))

while your fix works but not correctly because in that way does not 
collect the return code of the function get_default().


More information about the Python-list mailing list