Formatting numeric values which can also be None
I'm looking for a better way to handle optional None
value (missing value) in a statement like this:
logger.info("temp1 = %.1f, temp2 = %.1f, position = %.2f", t1, t2, pos)
in order to prevent:
TypeError: must be real number, not NoneType
This is what I'm doing now:
logger.info(
"temp1 = %s, temp2 = %s, position = %s",
"null" if t1 is None else format(t1, '.1f'),
"null" if t2 is None else format(t2, '.1f'),
"null" if pos is None else format(pos, '.2f'))
# any placeholder like "null", "None", "---", or "N/A" is fine
and I don't like it. Is there a better way? A solution for this small problem using str.format
or f-strings
would help too.
Solution 1:
Create a wrapper that checks itself when __format__
is called.
class AnyOrNone(object): # The wrapper is not type-specific
def __init__(self, value):
self.value = value
def __format__(self, *args, **kwargs):
if self.value is None:
return "None"
else:
return self.value.__format__(*args, **kwargs)