Mypy fails to infer the type of the decorated function used in the decorator
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Hi mypy team,
Bug Report
I'm looking into the issue with design-by-contract library icontract which heavily uses decorators to formalize contracts. For many functions and methods, the contracts involve the decorated function (or method) itself.
See the example from the issue https://github.com/Parquery/icontract/issues/243:
from icontract import ensure
@ensure(
lambda a, b, result:
result == myadd(b, a),
"Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
return a + b
Mypy 0.960 says:
tests_3_10\deleteme.py:5: error: Cannot determine type of "myadd"
If I add # type: ignore:
from icontract import ensure
@ensure(
lambda a, b, result:
result == myadd(b, a), # type: ignore
"Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
return a + b
mypy does not complain any more.
I was actually a bit surprised that mypy tried to infer the types in the lambda. @claudio-ebel tried a couple of fixes using casting (see his comment https://github.com/Parquery/icontract/issues/243#issue-1229622746), but none of them worked.
I am actually not sure if this is a misunderstanding on our part or a bug in mypy. Any pointers about how to resolve the issue are very much appreciated! Please let us know if you need more information, or if there is anything we can do to help to fix this.
Your Environment
- Mypy version used: 0.960
- Mypy command-line flags: `--strict``
- Python version used: 3.10.0
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the provided icontract example with mypy 0.960 and --strict, then trace the decorator and lambda type-inference entry points implicated by the error. Compare the behavior with and without the type: ignore comment; done means determining whether the diagnostic is expected or correcting inference so the example is checked without that suppression.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100