0

If I was trying to do

safe_value = dict_[key] if key in dict_ else default

a more concise way would be

safe_value =  dict_.get(key, default)

Is there something similar to shorten the following (in Python 3.11)?

safe_value = value if value is not None else default
user357269
  • 1,835
  • 14
  • 40
  • 3
    If you specifically need to check `is not None`, and not generally *falsey*, then no. – deceze Mar 27 '23 at 10:09
  • `safe_value = default if value is None else value` is slightly shorter – bereal Mar 27 '23 at 10:10
  • 2
    @Guy `value or default` then, but that's not equivalent to OP's code! – deceze Mar 27 '23 at 10:11
  • I think this question should not be closed because the asker has give the code that the accepted answer in the [duplicate] post and after reading the other answers in the [duplicate] post, none of the results are shorter (concise) (in terms of characters) than what the asker has suggested. Some, such as using a function, which may be more concise depending on what the usage for the code (the number of times this is needed, thus function calls). The question may be related to [codegolf](codegolf.stackexchange.com) however this is not really a competition so probably not suitable to be migrated. – yxz Mar 27 '23 at 11:05
  • Since this question has been closed, I will write them here. From [this code golf tip for python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python/62#62), you can use `(value, default)[value is None]`. However this may be much less readable than the answer posted so depends what you value more (short in bytes or readable) – yxz Mar 27 '23 at 11:25

1 Answers1

1

You could always write your own function for it:

def safe(value, default):
    return value if value is not None else default

Usage:

>>> safe(4, 0)
4
>>> safe(None, 0)
0

Note however that this will always evaluate the default expression, whereas a ternary value if value is not None else default will not evaluate it when value isn't None. So it should probably only be used when default is a simple expression with no side-effects (e.g. a literal value, or a variable).

kaya3
  • 47,440
  • 4
  • 68
  • 97