Python 3.10 - implementing Type Hints in Recursive Function Calls
I keep running into I've spent hours debugging this and I'm currently developing a recursive function in Python 3.10 to calculate the factorial of a number, but I'm running into issues with type hints... I want to specify that the function accepts an integer and returns an integer, but I'm getting a weird type behavior during runtime. Here's the basic structure of my function: ```python from typing import Union def factorial(n: Union[int, float]) -> int: if n < 0: raise ValueError("Input must be a non-negative integer") elif n == 0: return 1 else: return n * factorial(n - 1) ``` When I run the function with a float like `factorial(5.0)`, I expected it to work since the input is effectively an integer. However, I get this behavior: ``` TypeError: 'float' object want to be interpreted as an integer ``` I've tried casting the input to an integer within the function like this: ```python def factorial(n: Union[int, float]) -> int: n = int(n) # rest of the code ``` But this doesn't seem to resolve the scenario, and I still get the same type behavior if I call `factorial(5.0)`. I also read that using `Union` might not be the best practice here, especially for such a recursive function. What's the correct way to handle type hints in this case, and how can I ensure my function works with integers or whole number floats without throwing errors? Am I approaching this the right way? This is part of a larger application I'm building.