编程语言
首页 > 编程语言> > 限制可能值的Python类型提示友好类型

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

作者:互联网

我想要一种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(我找不到对“微小类型”的规范引用,这似乎是最好的)我可以找到的资源).

标签:python-3-x,python-typing,python
来源: https://codeday.me/bug/20191211/2106421.html