|
1 | 1 | """Age Controller Module |
2 | | -
|
3 | 2 | This module provides functionality to validate and process age input. |
4 | 3 | Related to issue #12809. |
5 | 4 | """ |
6 | 5 |
|
7 | 6 |
|
8 | | -def validate_age(age): |
| 7 | +def validate_age(age: int | str | float) -> int: |
9 | 8 | """Validate and process age input. |
10 | 9 |
|
11 | 10 | This function validates that the provided age is a valid positive integer |
@@ -35,36 +34,32 @@ def validate_age(age): |
35 | 34 | >>> validate_age(200) |
36 | 35 | Traceback (most recent call last): |
37 | 36 | ... |
38 | | - ValueError: Age must be between 0 and 150 |
| 37 | + ValueError: Age must be between 0 and 150 years |
39 | 38 | >>> validate_age('invalid') |
40 | 39 | Traceback (most recent call last): |
41 | 40 | ... |
42 | | - ValueError: Age must be a valid number |
| 41 | + ValueError: Invalid age format |
| 42 | + >>> validate_age(25.5) |
| 43 | + Traceback (most recent call last): |
| 44 | + ... |
| 45 | + ValueError: Age must be a whole number |
43 | 46 | """ |
44 | | - try: |
45 | | - # Convert to float first to handle string numbers |
46 | | - age_float = float(age) |
47 | | - |
48 | | - # Check if it's a whole number |
49 | | - if age_float != int(age_float): |
50 | | - age_int = int(age_float) |
51 | | - else: |
52 | | - age_int = int(age_float) |
| 47 | + # Convert age to appropriate numeric type |
| 48 | + age_int = int(age) if isinstance(age, int | float) else int(str(age)) |
53 | 49 |
|
54 | | - except (ValueError, TypeError): |
55 | | - raise ValueError("Age must be a valid number") |
| 50 | + # Validate that the age is a whole number if it was a float |
| 51 | + if isinstance(age, float) and age != age_int: |
| 52 | + msg = "Age must be a whole number" |
| 53 | + raise ValueError(msg) |
56 | 54 |
|
57 | | - # Validate range |
| 55 | + # Validate age is positive |
58 | 56 | if age_int < 0: |
59 | | - raise ValueError("Age must be a positive number") |
| 57 | + msg = "Age must be a positive number" |
| 58 | + raise ValueError(msg) |
60 | 59 |
|
61 | | - if age_int > 150: |
62 | | - raise ValueError("Age must be between 0 and 150") |
| 60 | + # Validate age is within reasonable range |
| 61 | + if age_int > 150: # noqa: PLR2004 |
| 62 | + msg = "Age must be between 0 and 150 years" |
| 63 | + raise ValueError(msg) |
63 | 64 |
|
64 | 65 | return age_int |
65 | | - |
66 | | - |
67 | | -if __name__ == "__main__": |
68 | | - import doctest |
69 | | - |
70 | | - doctest.testmod() |
0 commit comments