python / python/mypy

Allow specifying length of sized object

Open
#7,626 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature needs discussion priority-2-low
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Sometimes I want to specify the size of a container. This could be done manually with casts, but it would be really cool if Mypy could figure this out automatically. __len__() is guaranteed to return an int, and since a is defined as a literal the match could be statically inferrable. The same is true of other container types.

from typing_extensions import Protocol, Literal


class Char(Protocol):
    def __len__(self) -> Literal[1]:
        ...


a: Char = "X"

Mypy reports

error: Incompatible types in assignment (expression has type "str", variable has type "Char")
note: Following member(s) of "str" have conflicts:
note:     Expected:
note:         def __len__(self) -> Literal[1]
note:     Got:
note:         def __len__(self) -> int


Mypy 0.720
CPython 3.7.3

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.

Research direction

Start by running the supplied Python 3.7.3 example against the reported Mypy 0.720 behavior and examine how protocol compatibility handles len return types and Literal values. Done means the assignment to Char is accepted when the container size is statically inferable, with equivalent behavior for other container types.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.