From e8c94e7f7b337b06badb2366d6c432d464039920 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sat, 14 Feb 2026 20:37:37 -0500 Subject: [PATCH] Create util module with first function --- util/__init__.py | 0 util/convert.py | 26 ++++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 util/__init__.py create mode 100644 util/convert.py diff --git a/util/__init__.py b/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/util/convert.py b/util/convert.py new file mode 100644 index 0000000..284b5ce --- /dev/null +++ b/util/convert.py @@ -0,0 +1,26 @@ +import re + + +class InvalidStringException(Exception): + """Raised when a string cannot be converted to an integer.""" + pass + + +def convert_string_to_integer(data: str) -> int | Exception: + """ + Converts a string to an integer value. + :param data: A string containing an integer or float value to convert + :return: The converted integer value or exception object + + Examples: + >>> safe_int_from_string("4") + >>> safe_int_from_string("3.0") + """ + + try: + if '.' in data: + return int(float(data)) + else: + return int(data) + except ValueError as exc: + raise InvalidStringException("The string could not be converted to an integer.") from exc \ No newline at end of file