Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting numeric values which can also be None

Tags:

python

format

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.

like image 593
VPfB Avatar asked May 09 '26 20:05

VPfB


1 Answers

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)
like image 162
user4437749 Avatar answered May 11 '26 10:05

user4437749



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!