CodexBloom - Programming Q&A Platform

TypeError when using type hints with custom decorators in Python 3.10

๐Ÿ‘€ Views: 34 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-24
python-3.x type-hints decorators Python

I am working with a `TypeError` when attempting to use type hints with a custom decorator in Python 3.10... My decorator is designed to enforce the types of arguments passed to the decorated function, but when I include type hints, it raises an behavior. Hereโ€™s the code for my decorator: ```python from typing import Callable, TypeVar, Any F = TypeVar('F', bound=Callable[..., Any]) def enforce_types(func: F) -> F: def wrapper(*args: Any, **kwargs: Any) -> Any: # Here I would validate the types based on some logic return func(*args, **kwargs) return wrapper ``` I then apply this decorator to a function: ```python @enforce_types def add(x: int, y: int) -> int: return x + y ``` However, when I try to call `add(1, 2)` I get the following behavior message: ``` TypeError: 'NoneType' object is not callable ``` I suspect this is related to how I'm using the `TypeVar`, but Iโ€™m not sure how to fix it. Iโ€™ve tried adding `cast` from `typing` to return the function type explicitly, but it hasn't resolved the scenario: ```python from typing import cast def enforce_types(func: F) -> F: def wrapper(*args: Any, **kwargs: Any) -> Any: # Type validation logic return func(*args, **kwargs) return cast(F, wrapper) ``` Unfortunately, this change still results in the same `TypeError`. Iโ€™ve also checked if the decorator might be altering the function signature somehow, but I canโ€™t find any related issues. Can anyone guide to determine why Iโ€™m getting this behavior and how to resolve it while keeping my type hints intact?