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 
3
  • possible duplicate of Python `if x is not None` or `if not x is None`? Commented Nov 12, 2014 at 9:22
  • It's not a duplicate of that, at all. Commented Nov 12, 2014 at 9: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? Commented Nov 12, 2014 at 9:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.