當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。