dict.get(key, default) evaluates default even if key exists
jak
nospam at please.ty
Thu Dec 17 06:32:39 EST 2020
Il 17/12/2020 12:16, jak ha scritto:
> Il 15/12/2020 18:07, Mark Polesky ha scritto:
>> Hi.
>>
>> # Running this script....
>>
>> D = {'a':1}
>> def get_default():
>> print('Nobody expects this')
>> return 0
>> print(D.get('a', get_default()))
>>
>> # ...generates this output:
>>
>> Nobody expects this
>> 1
>>
>> ###
>>
>> Since I'm brand new to this community, I thought I'd ask here first...
>> Is this worthy of a bug report? This behavior is definitely
>> unexpected to me, and I accidentally coded an endless loop in a mutual
>> recursion situation because of it. Calling dict.get.__doc__ only
>> gives this short sentence: Return the value for key if key is in the
>> dictionary, else default. Nothing in that docstring suggests that the
>> default value is evaluated even if the key exists, and I can't think
>> of any good reason to do so.
>>
>> Am I missing something?
>>
>> Thanks,
>> Mark
>>
>
> print(_ if d.get('a', None) is not None else get_default())
>
>
>
ops...
print((_ if d.get('a', None) is not None else get_default()))
More information about the Python-list
mailing list