I'm using Python 3.13 for a generic CQRS design. A command declares int as its response type, and its handler inherits from CommandHandler with int as the response type, but the handler's async method is annotated to return str. PyCharm doesn't flag it. Am I defining the generics wrong?
Why doesn't PyCharm catch this generic handler's wrong return type?
Answers
The override is incompatible. Once the handler inherits from CommandHandler with int as its response type, handle is expected to return int when awaited. An override annotated as returning str doesn't satisfy that contract.
The missing warning looks like a limitation of PyCharm's built-in analysis for this example, not permission to change the return type. Static annotations don't enforce the type at runtime, either.
Reply to this answer
Try another type checker on the same snippet. Pyrefly and ty have been reported to flag the incompatible override, and PyCharm supports a Pyrefly integration. Running a separate check can help distinguish a checker limitation from a problem in your code.
Reply to this answer
There's a separate design issue lurking here. The handler's command type and response type are independent parameters. A handler could be declared with CreateUserCommand and str, even though CreateUserCommand inherits from Command[int]. Its own handle method returning str would then match the handler's declared response type.
Catching the bad override doesn't automatically enforce the relationship between a command and its handler's response. That relationship needs to be expressed or checked elsewhere in the design.
Reply to this answer
Python 3.13 also lets you write generic parameters using the newer class parameter syntax instead of declaring TypeVar objects separately. That can make the definitions easier to read, though changing the syntax alone won't fix a missed override warning or connect the two handler parameters.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Mavlori+7q:
Check the integration and configuration available in your PyCharm version. Different checkers can still disagree on some typing features.