X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;ds=sidebyside;f=conversion_utils.py;h=57902a79754e2b7950f800cf82d3bdabc74114a9;hb=e46158e49121b8a955bb07b73f5bcf9928b79c90;hp=cf4fcaab93f75291d7e24bf54d55f672eace1578;hpb=0d63d44ac89aab38fe95f36497adaf95110ab949;p=python_utils.git diff --git a/conversion_utils.py b/conversion_utils.py index cf4fcaa..57902a7 100644 --- a/conversion_utils.py +++ b/conversion_utils.py @@ -1,6 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +# © Copyright 2021-2022, Scott Gasch + """Utilities involving converting between different units.""" from typing import Callable, SupportsFloat @@ -32,22 +34,39 @@ class Converter(object): category: str, to_canonical: Callable, # convert to canonical unit from_canonical: Callable, # convert from canonical unit - unit: str, + suffix: str, ) -> None: + """Construct a converter. + + Args: + name: the unit name + category: the converter category + to_canonical: a Callable to convert this unit into the + canonical unit of the category. + from_canonical: a Callable to convert from the canonical + unit of this category into this unit. + suffix: the abbreviation of the unit name. + """ + self.name = name self.category = category self.to_canonical_f = to_canonical self.from_canonical_f = from_canonical - self.unit = unit + self.suffix = suffix def to_canonical(self, n: SupportsFloat) -> SupportsFloat: + """Convert into the canonical unit of this caregory by using the + Callable provided during construction.""" return self.to_canonical_f(n) def from_canonical(self, n: SupportsFloat) -> SupportsFloat: + """Convert from the canonical unit of this category by using the + Callable provided during construction.""" return self.from_canonical_f(n) def unit_suffix(self) -> str: - return self.unit + """Get this unit's suffix abbreviation.""" + return self.suffix # A catalog of converters. @@ -100,6 +119,16 @@ conversion_catalog = { def convert(magnitude: SupportsFloat, from_thing: str, to_thing: str) -> float: + """Convert between units using the internal catalog. + + Args: + magnitude: the quantity from which to convert + from_thing: the quantity's source unit we're coverting from + to_thing: the unit we are coverting to + + Returns: + The converted magnitude. Raises on error. + """ src = conversion_catalog.get(from_thing, None) dst = conversion_catalog.get(to_thing, None) if src is None or dst is None: @@ -110,6 +139,7 @@ def convert(magnitude: SupportsFloat, from_thing: str, to_thing: str) -> float: def _convert(magnitude: SupportsFloat, from_unit: Converter, to_unit: Converter) -> float: + """Internal conversion code.""" canonical = from_unit.to_canonical(magnitude) converted = to_unit.from_canonical(canonical) return float(converted)