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,078
  • 12
  • 73
  • 92
paweloque
  • 17,890
  • 25
  • 77
  • 135
  • 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) – ha9u63ar 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
  • 14,462
  • 4
  • 48
  • 70
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
  • 281,034
  • 50
  • 354
  • 495
  • `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