python / python/mypy

Mypy should allow for Self in parametrized parent class definition — issues with contextlib.AbstractContextManager

Open
#17,758 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

AbstractContextManager defines a __enter__ that returns self

But it's impossible to just inherit from contextlib.AbstractContextManager and have the type of __enter__ be correctly assumed to be Self, without a bit of boilerplate.

To Reproduce

class A(contextlib.AbstractContextManager):
    pass

reveal_type(A().__enter__())  # should be Self but assumed to be Any

and mypy disallows writing

class B(contextlib.AbstractContextManager[Self]):  # error: Self type is only allowed in annotations within class definition  [misc]
    pass

and doesn't issue a warning for this runtime error:

class C(contextlib.AbstractContextManager[C]):
    pass

Full example here
https://mypy-play.net/?mypy=latest&python=3.11&gist=7e76e56be6c702005a7ffbb7846b69c2

Expected Behavior

Either Self is allowed in the AbstractContextManager parameter list, or the type vars work by default.

Actual Behavior

Errors. See the playground.
(Although pyright doesn't error when using Self in the parameter list, but it still wrongly infers Any as the return of __enter__)

Workaround

Repeat the class name, and repeat the __enter__ impelmentation

class E(contextlib.AbstractContextManager["E"]):
    def __enter__(self) -> Self:
        return self

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: n/a
  • Python version used: 3.11

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 reproducing the examples in the mypy-play link, especially the AbstractContextManager and Self cases, and compare the revealed types and reported errors with the expected behavior. Done means a focused regression test demonstrates the chosen Self or type-variable behavior without requiring the workaround, while preserving the relevant Python 3.11 semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
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.