python / python/typing

Generic strings/regex patterns in strings

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

还没有人认领这个 Issue。

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

描述

Currently, we have str and LiteralStr. These don't do a good job expressing the range of values a string may have. Let's say we have the following function:

Email: TypeAlias = str

def send_email(email: Email) -> int:
    # Send an email
    ...

# passes
send_email("test@example.com")

# passes
send_email("badddd")

# passes even if unknown_var is only identified as `str`
send_email(unknown_var)

We could improve it by having something like this:

# This is a bad regex pattern, but you get the idea :)
Email: TypeAlias = str['[a-z0-9]+@[a-z0-9]+\.[a-z0-9]+']

def send_email(email: Email) -> int:
    # Send an email
    ...

# passes
send_email("test@example.com")

# fails
send_email("badddd")

# passes even if unknown_var is only identified as `str`
send_email(unknown_var)

A static type checker would be able to validate strings passed in by code. I would imagine this idea can be extended to Pattern and Match generics as well, but I haven't thought too deeply about them yet.

If we don't want to make str generic, we could add a new type to typing called StrPattern. We would need it anyways to backport to typing_extensions.

贡献指南

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

从这里开始

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

调研方向

未指定实现文件或测试。首先检查现有对 str 和 LiteralStr 的处理方式,以及 typing_extensions 的约定;明确该功能使用通用 str 还是新的 StrPattern 类型,并在确定能够证明完成的测试之前,定义对字面量、变量、Pattern 和 Match 的预期行为。

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

评估

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

把新 issue 发到你的邮箱

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