python / python/mypy

Protocols for types with fields that can be verified

Open
#6,656 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

$ pip freeze | rg mypy
mypy-extensions==0.4.1
mypy-mypyc==0.670

I have some complex objects that can be in one of several states once they have been verified, and I'd like to represent that verification as different types, but I'm having a hard time getting it to work with protocols.

I believe that something like this should work:

from __future__ import annotations
from typing import NamedTuple, Protocol, Optional

class Simple:
    two: Optional[int]

    def as_simpl_verified(self) -> SimpleVerified:
        assert self.two is not None
        return self

class SimpleVerified(Protocol):
    two: int

but I get this error:

$ mypy example_simple.py
example_simple.py:11: error: Incompatible return value type (got "Simple", expected "SimpleVerified")
example_simple.py:11: note: Following member(s) of "Simple" have conflicts:
example_simple.py:11: note:     two: expected "int", got "Optional[int]

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

Reproduce the report in example_simple.py with the shown mypy command, then investigate how protocols handle verified field types. Clarify the intended accepted behavior and add coverage for it; done means the example produces the agreed result instead of the reported incompatible return diagnostic.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.