Skip to content

Commit

Permalink
Merge pull request #86 from opengisch/better_conversion
Browse files Browse the repository at this point in the history
Fix typing for conversion and make less reliant on exceptions
  • Loading branch information
suricactus authored Apr 19, 2024
2 parents ff67379 + f65a20d commit bae6a8f
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions open_alaqs/core/tools/conversion.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,42 @@
import calendar
import time
from datetime import datetime
from typing import Any, Union
from typing import Any, Optional, Union


# For time conversions: Use UTC time only
def convertToFloat(value: Any, default: Any = None) -> Union[float, None]:
def convertToFloat(value: Any, default: Optional[float] = None) -> Optional[float]:
"""
Convert value to a float or if not possible return a default value.
:param value:
:param default:
:return:
"""
if value is None or value == "":
return default

try:
if value is None:
raise ValueError("Could not convert value 'None' to float.")
return float(value) # float takes only string or float
except ValueError:
if default is not None:
return convertToFloat(default)
return None
return default


def convertToInt(value: Any, default: Any = None) -> Union[int, None]:
def convertToInt(value: Any, default: Optional[int] = None) -> Optional[int]:
"""
Convert value to an integer or if not possible return a default value.
:param value:
:param default:
:return:
"""
if value is None or value == "":
return default

try:
if value is None:
raise ValueError("Could not convert value 'None' to int.")
return int(value)
except ValueError:
if default is not None:
return convertToInt(default)
return None
return default


def convertSecondsToTime(value: float) -> Union[time.struct_time, None]:
Expand Down

0 comments on commit bae6a8f

Please sign in to comment.