Strange error when calling len() on a class without __len__ and then using the result for division
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Consider this code:
class A: ...
b = 3.0
c = b / len(A())
reveal_type(c)
mypy gives this result:
division.py:4: error: Unsupported operand types for / ("float" and "int")
division.py:4: error: Argument 1 to "len" has incompatible type "A"; expected "Sized"
division.py:5: note: Revealed type is "Any"
Found 2 errors in 1 file (checked 1 source file)
The second error is expected, but the first one (“Unsupported operand types for / ("float" and "int").”) is very confusing, because clearly division is defined for float and int.
If A has __len__, everything is fine:
class A:
def __len__(self) -> int: return 0
b = 3.0
c = b / len(A())
reveal_type(c)
mypy output:
division.py:6: note: Revealed type is "builtins.float"
Success: no issues found in 1 source file
Your Environment
- Mypy version used: 0.960
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10
- Operating system and version: Ubuntu 22.04
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 with the reported Python snippet using len(), division, and reveal_type, and reproduce it with the stated mypy version and no flags. Trace how the type checker handles the invalid len() argument and the resulting division, then add focused coverage showing that the diagnostic for the division is not misleading while the invalid len() call remains reported.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 48/100