python / python/typing

Annotations for Type factories

未关闭
#1,309 7 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

Context: at my company, we have a wildly used framework that at the time of writing didn't consider good static type hints for the framework users as one of the design objectives.

It makes use of the "type factory" pattern that could be illustrated with the following (much simplified) example

# framework code

# `make_int_in_range_class` is a "type factory" method
def make_int_in_range_class(lower: int, upper: int):
    # imagine here some very elaborated machinery that constructs the type dynamically
    class IntInRange(int):
        def __init__(self, v: int) -> None:
            if v < lower or v > upper:
                raise ValueError("not in range")
            self.v = v
        
        # many more methods like
        def custom_serialization() -> bytes:
            return b"foo"
    
    return IntInRange

# user code in another file

MyIntInRange = make_int_in_range_class(0, 10)  # Create the `MyIntInRange` Type

def foo(x: MyIntInRange) -> None:  # use `MyIntInRange` type in the annotation 
    print(x)

foo(MyIntInRange(4))  # example usage

When I run mypy on this code I'm rightfully getting

-----------------------------------------------------------------------------
demo.py: note: In function "foo":
demo.py:12:12: error: Variable
"robotypes_toy_generic.demo.MyIntInRange" is not valid as a type  [valid-type]
    def foo(x: MyIntInRange) -> None:
               ^
demo.py:12:12: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

Note that Pyright seems to be more permissive here and doesn't error out, but this seems to be a non-standard behavior from PEPs point of view.

The goal of having the type hint at the first place in this code is 2 fold:

  1. Documentation.
  2. We could not afford yet to enable globally the check_untyped_defs = True flag, too many errors. But I'd like to remove one obstacle from getting type check coverage in the new code, so it's desirable to have the type hints (however poor they could be). And I'd like to avoid having excessive use of Any or type: ignore[untyped-def].

Ideally, I'd like to have some syntax to tell any type checker that make_int_in_range_class produces a valid type (let's say even Any to make things simple, but maybe it could be some Protocol).

I was not able to find a good way of doing it short of asking ALL USERS to write some typing lie like

if TYPE_CHECKING:
  MyIntInRange = Any
else:
  MyIntInRange = make_int_in_range_class(0, 10)  # Create the `MyIntInRange` Type

This is kind of a sad solution and also we have something like 1000 call sites that would need to be updated like that.
So I'm looking for advice on how this could be addressed on the framework level OR if people think it's not too fringy, maybe we could add a new feature in typing for that.

I was imagining that it could be possible to make something like this work

def make_int_in_range_class() -> Type[Any]:

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 没有指出任何 repository 文件或测试;请从简化的 type-factory 示例和 mypy 的 valid-type 诊断开始。将提议的 Type[Any] 注解与 issue 中描述的 typing 行为进行比较,并且只有在达成具体的类型标注变更或形成文档化指导后,才认为工作完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
developer-experience
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。