python / python/mypy

There should be an inverse of `Type`

Open
#8,103 5 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Specifically, it would be nice if there was a keyword Instance such that Instance[Type[_T]] is equivalent to _T

I'm thinking about this mostly in the context of working with metaclasses.

Suppose I have a class with a class method that creates an instance of the class written so it can be reused by subclasses. This can be typed in the following way:

_ThingInstance = TypeVar('_ThingInstance', bound='Thing')

class Thing():

    @classmethod
    def make_new(cls: Type[_ThingInstance]) -> _ThingInstance:
        return cls()

And this is automatically usable by subclasses.

What I want is an Instance type such that I can correctly type the same logic defined within a metaclass like so:

_ThingClass = TypeVar('_ThingClass', bound='MetaThing')

class MetaThing(type):

  def make_new(cls: _ThingClass) -> Instance[_ThingClass]:
      return cls()

As far as I can tell, there's no way to correctly annotate this

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 from the proposed Instance[_ThingClass] annotation and compare it with the shown Type[_ThingInstance] pattern. Define how the inverse should behave for metaclass methods and verify the examples with type-checking coverage; done means the requested annotations are accepted with the intended inferred instance types.

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
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.