From 76c562316046778b1154f643da385f7f1b452004 Mon Sep 17 00:00:00 2001 From: Zahari Date: Tue, 19 Sep 2017 12:25:22 +0200 Subject: [PATCH] Add ValueErrorTuple This just prints a value and an error nicely, e.g. in the report. --- src/reportengine/floatformatting.py | 11 +++++++++++ src/reportengine/tests/test_floatformatting.py | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/reportengine/floatformatting.py b/src/reportengine/floatformatting.py index 57f160a..4d2c3b2 100644 --- a/src/reportengine/floatformatting.py +++ b/src/reportengine/floatformatting.py @@ -5,6 +5,8 @@ it looks like. """ import decimal +import numbers +from typing import NamedTuple def significant_digits(value, digits): """Return a `Decimal` object with all the digits less signingicant than @@ -69,3 +71,12 @@ def format_error_value_columns(df, valcol, errcol, inplace=False, **kwargs): if not inplace: return df + +class ValueErrorTuple(NamedTuple): + """A class to represent a value and its error. The only functionality it + adds is the ``__str__`` method, to represent the quantity.""" + value: numbers.Real + error: numbers.Real + def __str__(self): + valstr, errstr = format_value_error(self.value, self.error) + return f'{valstr}±{errstr}' diff --git a/src/reportengine/tests/test_floatformatting.py b/src/reportengine/tests/test_floatformatting.py index a509f30..d913f15 100644 --- a/src/reportengine/tests/test_floatformatting.py +++ b/src/reportengine/tests/test_floatformatting.py @@ -5,7 +5,9 @@ import pandas as pd import numpy as np -from reportengine.floatformatting import format_number, significant_digits, format_error_value_columns +from reportengine.floatformatting import (format_number, significant_digits, + format_error_value_columns, + ValueErrorTuple) @given(floats(allow_nan=False)) def test_format_rountrip(x): @@ -24,3 +26,7 @@ def test_cols(valerr): formatted = format_error_value_columns(df, 'Val', 'Err') format_error_value_columns(df, 'Val', 'Err', inplace=True) assert (formatted == df).all().all() + +@given(floats(), floats()) +def test_valueerrortuple(value, error): + assert '±' in str(ValueErrorTuple(value,error))