Keeping track of things with dictionaries
Steven D'Aprano
steve at pearwood.info
Tue Apr 8 03:47:49 EDT 2014
On Tue, 08 Apr 2014 09:14:39 +0200, Frank Millman wrote:
> 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?
It's not a feature of setdefault. It's how Python works: arguments to
functions and methods are always evaluated before the function is called.
The same applies to most languages.
Only a very few number of syntactic features involve delayed evaluation.
Off the top of my head:
- the second argument to short-circuit "or" and "and" operators:
if obj and obj[0]: ...
- ternary if:
1/x if x != 0 else float("inf")
- generator expressions
- and of course the body of functions and methods don't execute until
the function is called.
--
Steven
More information about the Python-list
mailing list