"Chris Angelico" <[email protected]> wrote in message
news:captjjmqfbt2xx+bdfnhz0gagordkhtpbzrr29duwn36girz...@mail.gmail.com...
> On Tue, Apr 8, 2014 at 2:02 PM, Josh English <[email protected]>
> wrote:
>>
>> Would dict.setdefault() solve this problem? Is there any advantage to
>> defaultdict over setdefault()
>
> That depends on whether calling Brand() unnecessarily is a problem.
> Using setdefault() is handy when you're working with a simple list or
> something, but if calling Brand() is costly, or (worse) if it has side
> effects that you don't want, then you need to use a defaultdict.
>
It appears that when you use 'setdefault', the default is always evaluated,
even if the key exists.
>>> def get_value(val):
... print('getting value', val)
... return val*2
...
>>> my_dict = {}
>>> my_dict.setdefault('a', get_value('xyz'))
getting value xyz
'xyzxyz'
>>> my_dict.setdefault('a', get_value('abc'))
getting value abc
'xyzxyz'
>>> my_dict
{'a': 'xyzxyz'}
>>>
It seems odd. Is there a situation where this behaviour is useful?
Frank Millman
--
https://mail.python.org/mailman/listinfo/python-list