Relatively new to Python, I find myself having to evaluate a lot of arguments in functions/static methods and I was thinking if there is a user-friendly way to do this, so I ended up writing a function like so:
from typing import Any, Optional, Union
# Standard evaluator for default values
def eval_default(x: Any, default: Any, type: Optional[Any] = None) -> Any:
"""Helper function to set default value if None and basic type checking
Args:
x: the value to be evaluated
default: the value to return if x is None
type: the expected type of x, one of bool, int, float, str
Raises:
TypeError: for bool, int, float, str if x is not None and not of type
Returns:
x: either 'as is' if not None, or default if None, unless exception is raised.
"""
# Infer type from default
type = type(default) if type is None else type
# Return default value if x is None, else check type and/or return x
if x is None:
return default
elif not isinstance(x, type):
if type == bool:
raise TypeError("Variable can be either True or False.")
elif type == int:
raise TypeError("Variable must be an integer.")
elif type == float:
raise TypeError("Variable must be a float.")
elif type == str:
raise TypeError("Variable must be a string.")
else:
return x
Then in my main code I can do something like:
def some_method(self, some_variable:Optional[bool] = None) -> bool:
"""Some description
"""
try:
some_variable = eval_default(some_variable, False, bool)
except TypeError:
print("some_variable must be True or False.")
return some_variable
Is there a simpler, more concise or more elegant standard practice to handle such a situation?
Many thanks in advance.