Skip to content

Commit

Permalink
fix(converter): Fix Py2.7 error when can't find unit-type
Browse files Browse the repository at this point in the history
  • Loading branch information
ed-p-may committed Dec 19, 2023
1 parent 2c6eb62 commit 0b4df04
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions ph_units/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""Functions for converting Values from one unit to another (ie: meter->foot)."""

try:
from typing import Union, Optional, Tuple, Dict
from typing import Union, Optional, Tuple, Dict, List
except ImportError:
pass # IronPython 2.7

Expand All @@ -17,8 +17,29 @@

class UnitTypeNameNotFound(Exception):
def __init__(self, message):
# type: (str) -> None
self.message = message
super().__init__(self.message)
super(UnitTypeNameNotFound, self).__init__(self.message)


def _find_valid_unit_names_matching_first_letter(_unit_type_alias_dict, _input_string):
# type: (Dict[str, str], str) -> List[str]
"""Find all valid unit-type names that start with a given letter."""
matches = []

try:
first_letter = str(_input_string).strip()[0].upper()
except IndexError:
return matches

for k in sorted(_unit_type_alias_dict.keys()):
try:
if k[0] == first_letter:
matches.append(k)
except IndexError:
pass

return matches

def _standardize_unit_name(_input, _unit_type_alias_dict):
# type: (str, Dict[str, str]) -> str
Expand All @@ -40,9 +61,12 @@ def _standardize_unit_name(_input, _unit_type_alias_dict):
if _input_string == "%":
input_unit = "%"
else:
suggested_matches = _find_valid_unit_names_matching_first_letter(_unit_type_alias_dict, _input_string)
raise UnitTypeNameNotFound(
"\n\tI do not know how to understand the input unit: '{}'?\nValid formats include: {}".format(
_input_string, sorted(_unit_type_alias_dict.keys())
"\nI do not understand the unit: '{}'? "\
"\nPerhaps you meant on of these: '{}'?"
"\n\nValid formats include only: {}".format(
_input_string, suggested_matches, sorted(_unit_type_alias_dict.keys())
)
)

Expand Down

0 comments on commit 0b4df04

Please sign in to comment.