(*args, **kwargs)
| 517 | def enforce_types(func): |
| 518 | @wraps(func) |
| 519 | def wrapper(*args, **kwargs): |
| 520 | # Get type hints, excluding the return type hint |
| 521 | hints = {k: v for k, v in get_type_hints(func).items() if k != "return"} |
| 522 | |
| 523 | # Get the function's argument names |
| 524 | arg_names = inspect.getfullargspec(func).args |
| 525 | |
| 526 | # Pair each argument with its corresponding type hint |
| 527 | args_with_hints = dict(zip(arg_names[1:], args[1:])) # Skipping 'self' |
| 528 | |
| 529 | # Function to check if a value matches a given type hint |
| 530 | def matches_type(value, hint): |
| 531 | origin = get_origin(hint) |
| 532 | args = get_args(hint) |
| 533 | |
| 534 | if origin is Union: # Handle Union types (including Optional) |
| 535 | return any(matches_type(value, arg) for arg in args) |
| 536 | elif origin is list and isinstance(value, list): # Handle List[T] |
| 537 | element_type = args[0] if args else None |
| 538 | return all(isinstance(v, element_type) for v in value) if element_type else True |
| 539 | elif origin: # Handle other generics like Dict, Tuple, etc. |
| 540 | return isinstance(value, origin) |
| 541 | else: # Handle non-generic types |
| 542 | return isinstance(value, hint) |
| 543 | |
| 544 | # Check types of arguments |
| 545 | for arg_name, arg_value in args_with_hints.items(): |
| 546 | hint = hints.get(arg_name) |
| 547 | if hint and not matches_type(arg_value, hint): |
| 548 | raise ValueError(f"Argument {arg_name} does not match type {hint}; is {arg_value}") |
| 549 | |
| 550 | # Check types of keyword arguments |
| 551 | for arg_name, arg_value in kwargs.items(): |
| 552 | hint = hints.get(arg_name) |
| 553 | if hint and not matches_type(arg_value, hint): |
| 554 | raise ValueError(f"Argument {arg_name} does not match type {hint}; is {arg_value}") |
| 555 | |
| 556 | return func(*args, **kwargs) |
| 557 | |
| 558 | return wrapper |
| 559 |
nothing calls this directly
no test coverage detected