Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Specify methods that are allowed for inference of partially initialized generics #1989

Open
Labels
topic: featureDiscussions about new features for Python's type annotations
@vnmabus

Description

@vnmabus

The inference of generic types for classes in most type-checkers assume that all the generic types can be inferred from the parameters to__init__. This is not always the case. For example, it is a common pattern to create an empty container class and add elements to it later, e.g.:

a= []a.append("hello world")

Currently for builtin classes, such aslist ordict, this idiom is understood by MyPy, but not by Pyright. Moreover, even MyPy is incapable of applying this type inference to custom types (seepython/mypy#13134). As mentioned in that issue, the problem is not only with empty containers, but also with some widely used APIs, such as theEstimator API from scikit-learn and related projects, in which the type of the data used is only known when thefit method is called.

My proposal would be to add functionality to the type system to define which methods can be used to infer generic types, apart from__init__. This could be made for example with a decorator (e.g.allow_generic_inference), so that one can define a method such as:

@allow_generic_inferencedefappend(value:T):    ...

In this case the value of the class generic parameterT could be inferred fromappend if it was undefined before.

I think this proposal may also be similar to the previously suggestedTypeAssert mentioned by@erictraut in#1013 (comment). However I am not completely sure thatTypeAssert could do what I explained here. I am also not sure that the proposedTypeAssert syntax is better than a decorator.

I hope you too consider this proposal useful, and I look forward to your feedback.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp