Reputation: 875
I have an odd mypy failure when using decorators from an installed (via pip install
) package.
The same decorator written within my app code, works just fine.
I have a function like such:
def _subscription_entity(self) -> Optional[SubscriptionEntity]:
return get_subscription(...) # get_subscription() is a decorated function
MyPy is failing with an error: Returning Any from function declared to return Optional[SubscriptionEntity]
However, if I copy the whole decorator code, and place it within my app code (in a separate file, and importing that file instead of package installed one), all works as expected. No errors. I have also tested with changing _subscription_entity
signature to return an int
and I get an expected error Returning Optional[SubscriptionEntity] from function declared to return int
Why would mypy fail when decorator code lives inside a package, but not when lives inside app code ?
The simplified decorator is as follows
F = TypeVar('F', bound=Callable[..., Any])
def test_cache(wrapped_func: F) -> F:
@wraps(wrapped_func)
def decorated_func(*args: Any, **kwargs: Any)-> F:
return _handle(wrapped_func, *args, **kwargs)
return cast(F, decorated_func)
def _handle( wrapped_func: Callable, *args: Any, **kwargs: Any) -> F:
return wrapped_func(*args, **kwargs)
The decorated function is:
@test_cache
def get_subscription(cls, request: GetSubscriptionRequest) -> Optional[SubscriptionEntity]:
....
Upvotes: 2
Views: 2328
Reputation: 875
Turns out my imported package didn't have the right metadata to let MyPy know that package has typing.
https://mypy.readthedocs.io/en/stable/installed_packages.html?highlight=py.typed#making-pep-561-compatible-packages
After adding py.typed
to package_data
in setup
all worked OK with imported package
Upvotes: 1