python / python/typing

Runtime Access to Generic Types on Class Method

Open
#629 17 comments 49 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

I would like to be able to access the type arguments of a class from its class methods.

To make this concrete, here is a generic instance:

import typing
import typing_inspect

T = typing.TypeVar("T")

class Inst(typing.Generic[T]):
    @classmethod
    def hi(cls):
        return cls

I can get its generic args:

>>> typing_inspect.get_args(Inst[int])
(int,)

But, these seem to get erased inside the class methods:

>>> typing_inspect.get_args(Inst[int].hi())
()

Contributor guide

No contributing guide indexed for this repository

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 with the Inst[int] and classmethod examples in the issue, then inspect the typing and typing_inspect behavior involved in resolving generic aliases at runtime. The work is done when a class method can access the type arguments of the specialized class without erasing them, with behavior demonstrated for the reported example.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.