Check keyword argument compatibility across class hierarchies

Open
#1,013 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
compilers

Research direction

Start by investigating mypy's class-hierarchy analysis and the separate type-checking pass proposed in the issue. Determine how keyword calls and all subclasses could be connected without producing errors for positional-only usage. Done means a considered implementation or design that reports incompatible overrides only when a keyword argument is used, with false-positive behavior addressed.

Written by the indexing model from the issue text.

Description

feature needs discussion priority-2-low topic-inheritance

Currently mypy doesn't check that a method override has keyword argument names that are compatible with the overridden method. The reason is that a lot of code doesn't define these names consistently, and mypy would generate a ton of useless errors if it insisted on compatibility here. So mypy doesn't complain about this:

class A:
    def f(self, x): ...
class B(A):
    def f(self, xx): ...

However, this means that calls via keyword arguments can fail at runtime:

def f(a: A) -> None:
    a.f(x=1)  # Failure if a is an instance of B

f(B())

We could do better than this: if we call a method m of A using a keyword argument x, we could verify that all methods m in the class hierarchy below A define the keyword argument x. So we'd only enforce this if some code actually depends on the keyword argument name. Mypy would then give a list of all classes that have an incompatible definition of m and explain why the code could go wrong. If a method is always called using positional arguments only, no errors would be reported.

We might want to give a warning instead of an error for this, as it could generate false positives.

Implementing this would be fairly complicated as it would require access to all subclasses of a given class. In practice, this could happen in a separate type checking pass that happens after the entire program has been type checked, but I'm not really sure what's the best way to implement this and whether this is useful enough to implement at all.

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.