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 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 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.
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
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.