1

Is there a built-in function in python which does the following:

def none_safe(int_value):
    return int_value if int_value is not None else 0
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
paweloque
  • 18,466
  • 26
  • 80
  • 136
  • possible duplicate of [Python \`if x is not None\` or \`if not x is None\`?](http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none) – ha9u63a7 Nov 12 '14 at 09:22
  • It's not a duplicate of that, at all. – Ffisegydd Nov 12 '14 at 09:22
  • 1
    You have a typo in your post which @UriAgassi has decided to fix without knowing if it was broken or not, could you please check that the code as edited is what you actually have? – Ffisegydd Nov 12 '14 at 09:25

2 Answers2

3

Assuming that the only possible inputs are None and instances of int:

int_value or 0

Some APIS, such as dict.get, have an argument where you can pass the default. In this case it's just a value, but note that or is evaluated lazily whereas a function argument is necessarily evaluated eagerly.

Other APIs, such as the constructor of collections.defaultdict, take a factory to construct defaults, i.e. you would have to pass lambda: 0 (or just int since that is also a callable that returns 0), which avoids the eagerness if that's a problem, as well as the possibility of other falsy elements.

o11c
  • 15,265
  • 4
  • 50
  • 75
0

Even safer (usually) is to just return 0 for any value that can't be an int

def none_safe(int_value):
    try:
        return int(int_value)
    except (TypeError, ValueError):
        return 0

Other variations might use isinstance or similar depending on your exact requirements

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • `except` without an `Exception` is too broad for general usage. It can catch anything, even Control-C! I think that `except (TypeError, ValueError):` would be appropriate here. – twasbrillig Nov 12 '14 at 10:24