繁体   English   中英

Python类型提示友好类型,约束可能的值

[英]Python type-hint friendly type that constrains possible values

我想要一个python类型提示友好的方式来创建一个具有约束值范围的类型。

例如,基于类型strURL类型只接受看起来像“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')

覆盖内置的不可变类型效果很好

超越str ; http URL字符串

这是一个覆盖str的示例。 这不需要typing模块,但仍然可以使用类型提示。

这个str派生类声明初始化的字符串看起来像一个http URL字符串。

class URL(str):
    def __new__(cls, *value):
        if value:
            v0 = value[0]
            if not type(v0) is str:
                raise TypeError('Unexpected type for URL: "%s"' % type(v0))
            if not (v0.startswith('http://') or v0.startswith('https://')):
                raise ValueError('Passed string value "%s" is not an'
                                 ' "http*://" URL' % (v0,))
        # else allow None to be passed. This allows an "empty" URL instance, e.g. `URL()`
        # `URL()` evaluates False

        return str.__new__(cls, *value)

这导致一个类只允许一些字符串。 否则,它的行为就像一个不可变的str实例。

# these are okay
URL()
URL('http://example.com')
URL('https://example.com')
URL('https://')

# these raise ValueError
URL('example')  # ValueError: Passed string value "example" is not an "http*://" URL
URL('')  # ValueError: Passed string value "" is not an "http*://" URL

# these evaluate as you would expect
for url in (URL(),  # 'False'
            URL('https://'),  # 'True'
            URL('https://example.com'),  # 'True'
           ):
    print('True') if url else print('False')

(更新:后来我找到了purl Python库)

另一个例子,

重写int ; 约束整数范围Number

int派生类仅允许值19包括19

这也有一个特殊功能。 如果实例初始化为nothing( Number() ),则该值等于0 (此行为派生自int类)。 在这种情况下, __str__应该是'.' (计划要求)。

class Number(int):
    """integer type with constraints; part of a Sudoku game"""

    MIN = 1  # minimum
    MAX = 9  # maximum

    def __new__(cls, *value):
        if value:
            v0 = int(value[0])
            if not (cls.MIN <= v0 <= cls.MAX):
                raise ValueError('Bad value "%s" is not acceptable in'
                                 ' Sudoku' % (v0,))
        # else:
        #    allow None to be passed. This allows an "empty" Number instance that
        #    evaluates False, e.g. `Number()`

        return int.__new__(cls, *value)

    def __str__(self):
        """print the Number accounting for an "empty" value"""
        if self == 0:
            return '.'
        return int.__str__(self)

这可以确保尽快处理错误的输入。 否则,它的行为就像一个int

# these are okay
Number(1)
Number(9)
Number('9')

# this will evaluate True, just like an int
Number(9) == int(9)
Number('9') == int(9)
Number('9') == float(9)

# this is okay, it will evaluate False
Number()
print('True') if Number() else print('False')  # 'False'

# these raise ValueError
Number(0)  # ValueError: Bad value "0" is not acceptable in Sudoku
Number(11)  # ValueError: Bad value "11" is not acceptable in Sudoku
Number('11')  # ValueError: Bad value "11" is not acceptable in Sudoku

而特殊的“功能”

print(Number(1)) # '1' (expected)
print(Number())  # '.' (special feature)




继承不可变类型的技术来自这个SO答案

子类化内置类型可能导致一些奇怪的情况(考虑完全检查type(...) is str代码type(...) is 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视角的构造函数,但实际上只是一个很小的类型 (我找不到规范的“微小类型”,这似乎只是我能找到的最好的资源)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM