4 ms·
Yes, weirdly missing. Also omitted: my_dict.get('existing_key', foo()) does not short-circuits foo(). That always felt like a bug to me.
by avip 7y ago
Yes, weirdly missing.
Also omitted:
my_dict.get('existing_key', foo())
does not short-circuits foo(). That always felt like a bug to me.
- stefco_ 7y agoFunctions in most popular languages behave this way. `get` is just a method; its arguments will never be short-circuited. If you wanted short-circuiting, use the ternary operator: my_dict['existing_key'] if 'existing_key' in my_dict else foo() You could also define a `get_lazy` method that does the above, taking a nullary function as its key and evaluating it if the key is missing. But then you would need to wrap your default values in a lambda, which would look absurd for the common use case of calling `get` with some constant default value. Seems unnecessary when the ternary operator works fine.
- arijun 7y agoIf I know my_dict doesn't hold values that that are false-like, e.g. 0 or [], I use `or` to lazily alternate between options. This works because in python, `or` returns the first value that has a truthy value. In this case it would be my_dict.get('existing_key') or foo() This would also easily let you do multiple alternations (much more annoying with the ternary operator).
- majewsky 7y agoThis is dangerous because sometimes you have legitimate values that are not truthy. print(player_data['score'] or 'does not exist') This will print "does not exist" when the score is zero.
- stefco_ 7y agogp's approach works best when you know that the argument is a list or tuple (something which can be empty). Of course, due to python's lack of typing, you should only use that approach when the function is being used in well-understood contexts.