Since this thing is on the innerwebs I suppose it should have a
[python_utils.git] / conversion_utils.py
index 684edc0a9116aa827db2c7c83a52de10dbbba73b..68292caccbc692570010ab5ed98c10cbcc05d9c7 100644 (file)
@@ -1,7 +1,11 @@
 #!/usr/bin/env python3
+# -*- coding: utf-8 -*-
 
-from numbers import Number
-from typing import Callable
+# © Copyright 2021-2022, Scott Gasch
+
+"""Utilities involving converting between different units."""
+
+from typing import Callable, SupportsFloat
 
 import constants
 
@@ -38,10 +42,10 @@ class Converter(object):
         self.from_canonical_f = from_canonical
         self.unit = unit
 
-    def to_canonical(self, n: Number) -> Number:
+    def to_canonical(self, n: SupportsFloat) -> SupportsFloat:
         return self.to_canonical_f(n)
 
-    def from_canonical(self, n: Number) -> Number:
+    def from_canonical(self, n: SupportsFloat) -> SupportsFloat:
         return self.from_canonical_f(n)
 
     def unit_suffix(self) -> str:
@@ -97,7 +101,7 @@ conversion_catalog = {
 }
 
 
-def convert(magnitude: Number, from_thing: str, to_thing: str) -> float:
+def convert(magnitude: SupportsFloat, from_thing: str, to_thing: str) -> float:
     src = conversion_catalog.get(from_thing, None)
     dst = conversion_catalog.get(to_thing, None)
     if src is None or dst is None:
@@ -107,7 +111,7 @@ def convert(magnitude: Number, from_thing: str, to_thing: str) -> float:
     return _convert(magnitude, src, dst)
 
 
-def _convert(magnitude: Number, from_unit: Converter, to_unit: Converter) -> float:
+def _convert(magnitude: SupportsFloat, from_unit: Converter, to_unit: Converter) -> float:
     canonical = from_unit.to_canonical(magnitude)
     converted = to_unit.from_canonical(canonical)
     return float(converted)