当前位置: 首页>>代码示例>>Python>>正文


Python typing.NewType方法代码示例

本文整理汇总了Python中typing.NewType方法的典型用法代码示例。如果您正苦于以下问题:Python typing.NewType方法的具体用法?Python typing.NewType怎么用?Python typing.NewType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.NewType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_newtype_decoding

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_newtype_decoding():
    StrippedString = NewType('StrippedString', str)

    class StrippedStringField(FieldEncoder[StrippedString, str]):

        def to_python(self, value: str) -> StrippedString:
            return cast(StrippedString, value.strip())

        @property
        def json_schema(self) -> JsonDict:
            return {'type': 'string'}

    JsonSchemaMixin.register_field_encoders({StrippedString: StrippedStringField()})

    @dataclass
    class Pet(JsonSchemaMixin):
        name: StrippedString
        type: str

    p = Pet.from_dict({'name': '  Fido ', 'type': 'dog'})
    assert p.name == 'Fido' 
开发者ID:s-knibbs,项目名称:dataclasses-jsonschema,代码行数:23,代码来源:test_core.py

示例2: test_new_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_new_type(self):
        T = TypeVar('T')
        samples = [
            NewType('A', int),
            NewType('B', complex),
            NewType('C', List[int]),
            NewType('D', Union['p', 'y', 't', 'h', 'o', 'n']),
            NewType('E', List[Dict[str, float]]),
            NewType('F', NewType('F_', int)),
        ]
        nonsamples = [
            int,
            42,
            Iterable,
            List[int],
            Union["u", "v"],
            type,
            T,
        ]
        self.sample_test(is_new_type, samples, nonsamples) 
开发者ID:ilevkivskyi,项目名称:typing_inspect,代码行数:22,代码来源:test_typing_inspect.py

示例3: NewType

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def NewType(name, tp):
        """NewType creates simple unique types with almost zero
        runtime overhead. NewType(name, tp) is considered a subtype of tp
        by static type checkers. At runtime, NewType(name, tp) returns
        a dummy function that simply returns its argument. Usage::

            UserId = NewType('UserId', int)

            def name_by_id(user_id: UserId) -> str:
                ...

            UserId('user')          # Fails type check

            name_by_id(42)          # Fails type check
            name_by_id(UserId(42))  # OK

            num = UserId(5) + 1     # type: int
        """

        def new_type(x):
            return x

        new_type.__name__ = name
        new_type.__supertype__ = tp
        return new_type 
开发者ID:thombashi,项目名称:pytablewriter,代码行数:27,代码来源:_typing.py

示例4: test_new_type_schema

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_new_type_schema():
    a_type = NewType('a_type', int)
    b_type = NewType('b_type', a_type)
    c_type = NewType('c_type', str)

    class Model(BaseModel):
        a: a_type
        b: b_type
        c: c_type

    assert Model.schema() == {
        'properties': {
            'a': {'title': 'A', 'type': 'integer'},
            'b': {'title': 'B', 'type': 'integer'},
            'c': {'title': 'C', 'type': 'string'},
        },
        'required': ['a', 'b', 'c'],
        'title': 'Model',
        'type': 'object',
    } 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:22,代码来源:test_schema.py

示例5: infer_typing_typevar_or_newtype

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def infer_typing_typevar_or_newtype(node, context=None):
    """Infer a typing.TypeVar(...) or typing.NewType(...) call"""
    try:
        func = next(node.func.infer(context=context))
    except InferenceError as exc:
        raise UseInferenceDefault from exc

    if func.qname() not in TYPING_TYPEVARS_QUALIFIED:
        raise UseInferenceDefault
    if not node.args:
        raise UseInferenceDefault

    typename = node.args[0].as_string().strip("'")
    node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))
    return node.infer(context=context) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:17,代码来源:brain_typing.py

示例6: register_field_for_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def register_field_for_type(self, target: type, field: FieldABC) -> None:
        """
        Registers a raw marshmallow field to be associated with a type::

            from typing import NewType
            Email = NewType("Email", str)

            registry.register_field_for_type(Email, EmailField)

        """
        pass 
开发者ID:justanr,项目名称:marshmallow-annotations,代码行数:13,代码来源:base.py

示例7: test_typing_newtype_single_validation_success

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_typing_newtype_single_validation_success(test_type, correct):
    SomeNew = typing.NewType("SomeNew", test_type)

    validator = type_validator()
    attr = MagicMock()
    attr.type = SomeNew

    validator(None, attr, correct)
    validator(None, attr, SomeNew(correct)) 
开发者ID:bloomberg,项目名称:attrs-strict,代码行数:11,代码来源:test_newtype.py

示例8: test_typing_newtype_single_validation_failure

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_typing_newtype_single_validation_failure(test_type, wrongs):
    SomeNew = typing.NewType("SomeNew", test_type)

    validator = type_validator()
    attr = MagicMock()
    attr.type = SomeNew

    for wrong in wrongs:
        with pytest.raises(AttributeTypeError) as error:
            validator(None, attr, wrong)

    assert "must be NewType(SomeNew, {})".format(str(test_type)) in str(
        error.value
    ) 
开发者ID:bloomberg,项目名称:attrs-strict,代码行数:16,代码来源:test_newtype.py

示例9: test_typing_newtype_within_container_validation_success

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_typing_newtype_within_container_validation_success(
    container, test_type, correct
):
    SomeNew = typing.NewType("SomeNew", test_type)

    validator = type_validator()
    attr = MagicMock()
    attr.type = container[SomeNew]

    validator(None, attr, correct) 
开发者ID:bloomberg,项目名称:attrs-strict,代码行数:12,代码来源:test_newtype.py

示例10: test_typing_newtype_within_container_validation_failure

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_typing_newtype_within_container_validation_failure(
    container, test_type, wrongs
):
    SomeNew = typing.NewType("SomeNew", test_type)

    validator = type_validator()
    attr = MagicMock()
    attr.type = container[SomeNew]

    for wrong in wrongs:
        with pytest.raises(BadTypeError) as error:
            validator(None, attr, wrong)

    assert "must be {}".format(str(attr.type)) in str(
        error.value
    ) or "is not of type {}".format(str(attr.type)) in str(error.value)


# -----------------------------------------------------------------------------
# Copyright 2019 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------- END-OF-FILE ----------------------------------- 
开发者ID:bloomberg,项目名称:attrs-strict,代码行数:35,代码来源:test_newtype.py

示例11: test_is_new_type_with_new_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_is_new_type_with_new_type():
    assert is_new_type(NewType("NewType", int)) 
开发者ID:konradhalas,项目名称:dacite,代码行数:4,代码来源:test_types.py

示例12: test_extract_new_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_extract_new_type():
    assert extract_new_type(NewType("NewType", int)) == int 
开发者ID:konradhalas,项目名称:dacite,代码行数:4,代码来源:test_types.py

示例13: test_is_instance_with_new_type_and_matching_value_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_is_instance_with_new_type_and_matching_value_type():
    assert is_instance("test", NewType("MyStr", str)) 
开发者ID:konradhalas,项目名称:dacite,代码行数:4,代码来源:test_types.py

示例14: test_is_instance_with_new_type_and_not_matching_value_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_is_instance_with_new_type_and_not_matching_value_type():
    assert not is_instance(1, NewType("MyStr", str)) 
开发者ID:konradhalas,项目名称:dacite,代码行数:4,代码来源:test_types.py

示例15: test_is_instance_with_numeric_tower_and_new_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import NewType [as 别名]
def test_is_instance_with_numeric_tower_and_new_type():
    assert is_instance(1, NewType("NewType", float)) 
开发者ID:konradhalas,项目名称:dacite,代码行数:4,代码来源:test_types.py


注:本文中的typing.NewType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。