Edit: For the people marking it as duplicate with logical operators, I found the link Python Logical Operators and the answers there to be rather vague and had to deep dive into it before finding the "or" answer. So while the issue here is that Python throws None, False and 0 together, great, but here we want to make a distinction between the earlier two and an actual integer or float value. That post really doesn't help my question here except for explaining some of the basic behaviour and doesn't address the "how can we handle this specific situation in the most pythonic way". //
I've ran into some unexpected behaviour with converting integers using the int(... or ...). I didn't notice it before, because I usually use something like:
int(value or 0)
Which always worked fine, but when I change the or 0 to another value and we enter 0, I get something I didn't expect. The example is int, but same goes for float.
In [88]: int(None or 1)
Out[88]: 1
In [89]: int(2 or 1)
Out[89]: 2
In [90]: int(0 or 1)
Out[90]: 1
In [91]: int(0)
Out[91]: 0
Edit: I would expect [90] to do the same as [91], but obviously it doesn't. My question here is: why does it do that behaviour and how can I handle this in a Pythonic way without having to resort to try excepts.
Is this because it evaluates like a boolean and 0 therefore returns the or value? What is common practice to handle this? Because this is a very common thing in our program and to use try except will create some ugly, not very readable code... Using python 2.7 here.
This is my current workaround to get my expected behaviour:
try:
value = int(value)
except (TypeError, ValueError) as e:
value = 1
Kind regards,
Carst
Edit 2: as the underlying mechanism is clear now, the help I'm really looking for is about how to handle this situation. As stated in the comments, I mostly do this to handle Nones. Another way to handle this would be:
if value is None:
value = 1
else:
value = int(value)
What I'm trying to understand really, is how to handle Nones in a way that does not transform the code into an endless parade of if/else statements or write my own function that does it (because to me None handling seems something that should be common?).