Repository navigation
Closed
Labels
bugmypy got something wrong
Description
Bug Report
The following example using Concatenate to represent a method passes mypy in strict mode:
from collections.abc import Callable
from typing import Any, Concatenate
def func(x: int) -> None:
return
class MyClass:
def method(self, x: int) -> None:
return
def check[**P](f: Callable[P, None], m: Callable[Concatenate[Any, P], None]) -> None:
return
check(func, MyClass.method)However, if the signature has **kwargs, it fails with Argument 2 to "check" has incompatible type ... This is likely because "method of MyClass" has named arguments: "self".
from collections.abc import Callable
from typing import Any, Concatenate
def func(**kwargs: Any) -> None:
return
class MyClass:
def method(self, **kwargs: Any) -> None:
return
def check[**P](f: Callable[P, None], m: Callable[Concatenate[Any, P], None]) -> None:
return
check(func, MyClass.method)Explicitly making self positional-only fixes this, but in my case, I don't control the method signature (in my actual use case, the method is argparse.ArgumentParser.add_argument() and the function is copy_method_params() from python/cpython#121693).
To Reproduce
Expected Behavior
There should be no errors.
Actual Behavior
There is an error:
main.py:18: error: Argument 2 to "check" has incompatible type "Callable[[Arg(MyClass, 'self'), KwArg(Any)], None]"; expected "Callable[[Any, KwArg(Any)], None]" [arg-type]
main.py:18: note: This is likely because "method of MyClass" has named arguments: "self". Consider marking them positional-only
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: master, latest version
- Mypy command-line flags: --strict
Metadata
Metadata
Assignees
Labels
bugmypy got something wrong
Activity
sterliakov commentedon May 8, 2025
selfis never positional-only unless declared as such. Consider:playground
osandov commentedon May 8, 2025
In that case, why doesn't my first example (https://mypy-play.net/?mypy=master&python=3.12&flags=strict&gist=5d5a1b27f2838371bee58b2d9c9a7721) produce an error?
sterliakov commentedon May 8, 2025
Because there's no fallback
**kwargsor explicitselfkw-only argument - yourConcatenatestrips the first argument, and you're left with one, positional-or-keyword argumentx, there's no uncertainty whetherselfcan be also passed as kwarg later.Concatenatetreats that as posonly, anddef method(self, /, **kwargs)won't raise the runtime error, so we shouldn't reject it insidecheck.osandov commentedon May 8, 2025
Ok, that makes sense now, thanks! I found a solution by replacing the
Callablewith aProtocolthat includes theselfparameter.