Closed
Description
Discussed in #83
Originally posted by Batalex November 20, 2023
The current sciform
implementation eagerly formats values as soon as Formatter.__call__
is called.
This discussion is about making sciform
implementation lazy so the actual format would happen when the value is printed.
Here is a quick look at what it could look like
# sciform.formatter.py
class Formatter:
# ...
# __init__
def __call__(self, value: Number, uncertainty: Number = None, /):
- rendered_options = self.user_options.render()
- if uncertainty is None:
- return format_num(Decimal(str(value)), rendered_options)
- else:
- return format_val_unc(Decimal(str(value)),
- Decimal(str(uncertainty)),
- rendered_options)
+ return FormattedValue(self, value, uncertainty)
+class FormattedValue(str):
+
+ def __init__(self, fmt: Formatter, value: Number, uncertainty: Optional[Number] = None, /) -> None:
+ self.fmt = fmt
+ self.value = value
+ self.uncertainty = uncertainty
+
+ def __str__(self) -> str:
rendered_options = self.fmt.user_options.render()
if self.uncertainty is None:
return format_num(Decimal(str(self.value)), rendered_options)
else:
return format_val_unc(Decimal(str(self.value)),
Decimal(str(self.uncertainty)),
rendered_options)
The example above would be similar to the current implementation, but you could then add _repr_html_
or _repr_latex_
methods so that your displayed value uses \textsuperscript
in a LaTeX document or <sup></sup>
in a notebook.