加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

限制可能值的Python类型提示友好类型

发布时间:2020-12-17 17:37:09 所属栏目:Python 来源:网络整理
导读:我想要一种python type-hint友好的方法来创建具有约束值范围的Type. 例如,基于类型str的URL类型,它将仅接受看起来像“ http” URL的字符串. # this code is made up and will not compileclass URL(typing.NewType('_URL',str)): def __init__(self,value: s

我想要一种python type-hint友好的方法来创建具有约束值范围的Type.

例如,基于类型str的URL类型,它将仅接受看起来像“ http” URL的字符串.

# this code is made up and will not compile
class URL(typing.NewType('_URL',str)):
    def __init__(self,value: str,*args,**kwargs):
        if not (value.startswith('http://') or value.startswith('https://')):
            raise ValueError('string is not an acceptable URL')
最佳答案
对内置类型进行子类化可能会导致一些奇怪的情况(请考虑代码来检查type(…)是否为str.

这是一种纯类型方法,它是类型安全的,并且完全保留了字符串的类型:

from typing import NewType

_Url = NewType('_Url',str)

def URL(s: str) -> _Url:
    if not s.startswith('https://'):
        raise AssertionError(s)
    return _Url(s)

print(type(URL('https://example.com')) is str)  # prints `True`

这里的方法“隐藏”了函数运行时检查,该函数从api的角度看起来像构造函数,但实际上只是一个tiny type(我找不到对“微小类型”的规范引用,这似乎是最好的)我可以找到的资源).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读