Source code for pyopus.misc.format

"""
**Formattting with f-strings support**
"""

[docs] class NA: """ Wrapper for values that may be None, formats None as `noneStr` with width support. """ def __init__(self, value): self.value = value noneStr = "None" def __format__(self, spec): if self.value is None: # Parse width and alignment from the spec import re m = re.match(r'([<>=^])?(\d+)?', spec) if m: align, width = m.group(1), m.group(2) width = int(width) if width else None else: align, width = None, None # Default alignment is right (>) if width is given, else no padding # align = align or '>' print(spec, align, width) if width: if align is None: return f"{self.noneStr:{width}}" else: return f"{self.noneStr:{align}{width}}" else: return self.noneStr # For normal values, fall back to standard formatting return format(self.value, spec)
if __name__=="__main__": print(f"{NA(None):>10f} {NA(None):>10.2f} {NA(None):>.2f} {NA(None):.2f} {NA(None):10f} {NA(None):f} {NA(0.5):>10f}")