Python typing.NewType() Examples
The following are 28
code examples of typing.NewType().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: test_schema.py From pydantic with MIT License | 6 votes |
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', }
Example #2
Source File: _typing.py From pytablewriter with MIT License | 6 votes |
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
Example #3
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_new_type_and_matching_value_type(): assert is_instance("test", NewType("MyStr", str))
Example #4
Source File: test_schema.py From pydantic with MIT License | 5 votes |
def test_new_type(): new_type = NewType('NewStr', str) class Model(BaseModel): a: new_type assert Model.schema() == { 'title': 'Model', 'type': 'object', 'properties': {'a': {'title': 'A', 'type': 'string'}}, 'required': ['a'], }
Example #5
Source File: test_utils.py From pydantic with MIT License | 5 votes |
def test_new_type_supertype(): new_type = NewType('new_type', str) new_new_type = NewType('new_new_type', new_type) assert new_type_supertype(new_type) == str assert new_type_supertype(new_new_type) == str
Example #6
Source File: test_utils.py From pydantic with MIT License | 5 votes |
def test_is_new_type(): new_type = NewType('new_type', str) new_new_type = NewType('new_new_type', new_type) assert is_new_type(new_type) assert is_new_type(new_new_type) assert not is_new_type(str)
Example #7
Source File: __init__.py From corrscope with BSD 2-Clause "Simplified" License | 5 votes |
def safe_property(unsafe_getter: Callable, *args, **kwargs) -> SafeProperty: """Prevents (AttributeError from leaking outside a property, which causes hasattr() to return False).""" @functools.wraps(unsafe_getter) def safe_getter(self): try: return unsafe_getter(self) except AttributeError as e: raise RuntimeError(e) from e # NewType("", cls)(x) == x. return SafeProperty(property(safe_getter, *args, **kwargs))
Example #8
Source File: test_field_for_schema.py From marshmallow_dataclass with MIT License | 5 votes |
def test_newtype(self): self.assertFieldsEqual( field_for_schema(typing.NewType("UserId", int), default=0), fields.Integer(required=False, description="UserId", default=0, missing=0), )
Example #9
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_errors(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserName): pass
Example #10
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_basic(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) self.assertIsInstance(UserId(5), int) self.assertIsInstance(UserName('Joe'), str) self.assertEqual(UserId(5) + 1, 6)
Example #11
Source File: test_optional.py From dacite with MIT License | 5 votes |
def test_from_dict_with_optional_new_type(): MyStr = NewType("MyStr", str) @dataclass class X: s: Optional[MyStr] result = from_dict(X, {"s": MyStr("test")}) assert result == X(s=MyStr("test"))
Example #12
Source File: test_base.py From dacite with MIT License | 5 votes |
def test_from_dict_with_new_type(): MyStr = NewType("MyStr", str) @dataclass class X: s: MyStr result = from_dict(X, {"s": "test"}) assert result == X(s=MyStr("test"))
Example #13
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_numeric_tower_and_new_type(): assert is_instance(1, NewType("NewType", float))
Example #14
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_new_type_and_not_matching_value_type(): assert not is_instance(1, NewType("MyStr", str))
Example #15
Source File: brain_typing.py From python-netsurv with MIT License | 5 votes |
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)
Example #16
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_extract_new_type(): assert extract_new_type(NewType("NewType", int)) == int
Example #17
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_new_type_with_new_type(): assert is_new_type(NewType("NewType", int))
Example #18
Source File: test_typing_inspect.py From typing_inspect with MIT License | 5 votes |
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)
Example #19
Source File: test_newtype.py From attrs-strict with Apache License 2.0 | 5 votes |
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 -----------------------------------
Example #20
Source File: test_newtype.py From attrs-strict with Apache License 2.0 | 5 votes |
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)
Example #21
Source File: test_newtype.py From attrs-strict with Apache License 2.0 | 5 votes |
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 )
Example #22
Source File: test_newtype.py From attrs-strict with Apache License 2.0 | 5 votes |
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))
Example #23
Source File: base.py From marshmallow-annotations with MIT License | 5 votes |
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
Example #24
Source File: brain_typing.py From pySINDy with MIT License | 5 votes |
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)
Example #25
Source File: test_core.py From dataclasses-jsonschema with MIT License | 5 votes |
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'
Example #26
Source File: brain_typing.py From python-netsurv with MIT License | 5 votes |
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)
Example #27
Source File: test_core.py From dataclasses-jsonschema with MIT License | 4 votes |
def test_field_types(): Currency = NewType('Currency', Decimal) JsonSchemaMixin.register_field_encoders({ Currency: DecimalField(precision=2) }) @dataclass class AllFieldTypes(JsonSchemaMixin): """All field types used""" ip_address: IPv4Address ipv6_address: IPv6Address cost: Currency uuid: UUID expected_schema = compose_schema({ 'description': 'All field types used', 'type': 'object', 'properties': { 'ip_address': {'type': 'string', 'format': 'ipv4'}, 'ipv6_address': {'type': 'string', 'format': 'ipv6'}, 'cost': {'type': 'number', 'multipleOf': 0.01}, 'uuid': { 'type': 'string', 'format': 'uuid', 'pattern': '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' } }, 'required': ['ip_address', 'ipv6_address', 'cost', 'uuid'] }) assert AllFieldTypes.json_schema() == expected_schema expected_uuid = UUID('032bbcad-9ca2-4f36-9a63-43a036bc5755') expected_obj = AllFieldTypes( ip_address=IPv4Address('127.0.0.1'), ipv6_address=IPv6Address('::1'), cost=Currency(Decimal('49.99')), uuid=expected_uuid ) expected_dict = { "ip_address": "127.0.0.1", "ipv6_address": "::1", "cost": 49.99, "uuid": str(expected_uuid) } assert expected_obj == AllFieldTypes.from_dict(expected_dict) assert expected_obj.to_dict() == expected_dict
Example #28
Source File: cast_test.py From yui with GNU Affero General Public License v3.0 | 4 votes |
def test_cast(): bot = FakeBot() bot.add_user('U1', 'kirito') bot.add_channel('C1', 'general') bot.add_channel('C2', 'random') bot.add_channel('C3', 'food') bot.add_dm('D1', 'U1') bot.add_private_channel('G1', 'secret') ID = NewType('ID', str) assert cast(int, '3') == 3 assert cast(List[str], ('kirito', 'asuna')) == ['kirito', 'asuna'] assert cast(List[int], ('1', '2', '3')) == [1, 2, 3] assert cast(Tuple[int, float, str], ['1', '2', '3']) == (1, 2.0, '3') assert cast(Set[int], ['1', '1', '2']) == {1, 2} assert cast(Optional[int], 3) == 3 assert cast(Optional[int], None) is None assert cast(Union[int, float], '3.2') == 3.2 assert cast(List[ID], [1, 2, 3]) == [ID('1'), ID('2'), ID('3')] assert cast(Dict[str, Any], {1: 1, 2: 2.2}) == {'1': 1, '2': 2.2} assert cast(Dict[str, str], {1: 1, 2: 2.2}) == {'1': '1', '2': '2.2'} assert cast(List, ('kirito', 'asuna', 16.5)) == ['kirito', 'asuna', 16.5] assert cast(Tuple, ['1', 2, 3.0]) == ('1', 2, 3.0) assert cast(Set, {'1', 2, 3.0, 2}) == {'1', 2, 3.0} assert cast(Dict, {'1': 'kirito', 2: 'asuna', 3: 16.5}) == { '1': 'kirito', 2: 'asuna', 3: 16.5, } user = cast(UserRecord, {'id': 'item4', 'pw': 'supersecret'}) assert user.id == 'item4' assert user.pw == 'supersecret' assert user.addresses is None users = cast( List[UserRecord], [ {'id': 'item4', 'pw': 'supersecret'}, {'id': 'item2', 'pw': 'weak', 'addresses': [1, 2]}, ], ) assert users[0].id == 'item4' assert users[0].pw == 'supersecret' assert users[0].addresses is None assert users[1].id == 'item2' assert users[1].pw == 'weak' assert users[1].addresses == ['1', '2'] with pytest.raises(ValueError): cast(Union[int, float], 'asdf')