I made this utility function to check for parameters. All it does is checking whether a given variable is an int, or a float/str that represent exactly an int (ie. no decimal part or NaN), and casting to that int (raising a ValueError exception on failure).
I'm not very experienced with Python (especially Python 3+), so I'm still learning and trying to improve my programming skills.
I'm open to any critics, improvements, and bad/good practices tips. Also I'm trying to learn how to properly document Python code (my IDE is PyCharm and hints me to use reStructuredText docblocks, and default Python3 typing hints).
I'm using Python3.6 for the following code:
from typing import Union def int_exact_cast(n: Union[int, float, str]) -> int: """ Tries to cast parameter to int without losing decimal part or raise an exception :param Union[int, float] n: The value to be converted :type n: Union[int, float] :return: The converted int value :rtype: int :raises ValueError: raises ValueError exception if the parameter can't be casted exactly to int """ t = type(n) if t is int: return n # return immediately if is already int (optimization) if not (t is str or t is float): raise ValueError('Parameter must be an int, str or float') f = float(n) if not f.is_integer(): # not checking for math.nan because in that case is_integer() returns False raise ValueError('Parameter contains a decimal part') return int(f)