Why doesn't PyCharm catch this generic handler's wrong return type?

November 19, 2026 4 answers
Asked by _x47!quendalo.9

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?

Answers

_e49!queldavi.8

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
8d!gasketvisor_527

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.

Mavlori+7q:

Check the integration and configuration available in your PyCharm version. Different checkers can still disagree on some typing features.

Reply to this answer
2a+brindlevisor_547

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
8m~quavelo_473

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.

Related Discussions