How to use the typing.NewType function in typing

To help you get started, we’ve selected a few typing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ramonhagenaars / jsons / tests / test_various.py View on Github external
def test_dump_load_newtype(self):
        Uid = NewType('uid', str)

        class User:
            def __init__(self, uid: Uid, name: str):
                self.uid = uid
                self.name = name

        dumped = jsons.dump(User('uid', 'name'))
        loaded = jsons.load(dumped, User)

        self.assertEqual('uid', loaded.uid)
        self.assertEqual('name', loaded.name)
github python / typing / src / test_typing.py View on Github external
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
github samuelcolvin / pydantic / tests / test_types.py View on Github external
def test_new_type_fails():
    a_type = NewType('a_type', int)
    b_type = NewType('b_type', a_type)

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

    with pytest.raises(ValidationError) as exc_info:
        Model(a='foo', b='bar')
    assert exc_info.value.errors() == [
        {'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'},
        {'loc': ('b',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'},
    ]
github ethereum / trinity / eth / typing.py View on Github external
{'nonce': int,
                             'gasLimit': int,
                             'gasPrice': int,
                             'to': Address,
                             'value': int,
                             'data': bytes,
                             'secretKey': bytes,
                             })

TransactionNormalizer = Callable[[TransactionDict], TransactionDict]

VMFork = Tuple[BlockNumber, Type['BaseVM']]

VMConfiguration = Sequence[VMFork]

VRS = NewType("VRS", Tuple[int, int, int])

IntConvertible = Union[int, bytes, HexStr, str]


TFunc = TypeVar('TFunc')


class StaticMethod(Generic[TFunc]):
    """
    A property class purely to convince mypy to let us assign a function to an
    instance variable. See more at: https://github.com/python/mypy/issues/708#issuecomment-405812141
    """
    def __get__(self, oself: Any, owner: Any) -> TFunc:
        return self._func

    def __set__(self, oself: Any, value: TFunc) -> None:
github byceps / byceps / byceps / services / snippet / transfer / models.py View on Github external
@dataclass(frozen=True)
class Scope:
    type_: str
    name: str

    @classmethod
    def for_brand(cls, brand_id: BrandID) -> Scope:
        return cls('brand', str(brand_id))

    @classmethod
    def for_site(cls, site_id: SiteID) -> Scope:
        return cls('site', str(site_id))


SnippetID = NewType('SnippetID', UUID)


SnippetType = Enum('SnippetType', ['document', 'fragment'])


SnippetVersionID = NewType('SnippetVersionID', UUID)


MountpointID = NewType('MountpointID', UUID)


@dataclass(frozen=True)
class Mountpoint:
    id: MountpointID
    site_id: SiteID
    endpoint_suffix: str
github jansenmarc / WavesGatewayFramework / waves_gateway / __init__.py View on Github external
gevent.hub.Hub.NOT_ERROR = (Exception, )

from waves_gateway.factory import CoinAddressFactory
from waves_gateway.model import KeyPair, \
    TransactionAttemptReceiver, \
    TransactionAttempt, Transaction, TransactionReceiver, TransactionSender, PollingDelayConfig, GatewayConfigFile
from .gateway import Gateway
from waves_gateway.service import ChainQueryService, TransactionService, IntegerConverterService, \
    FeeService, ConstantFeeServiceImpl, AddressValidationService, COIN_INTEGER_CONVERTER_SERVICE, COIN_TRANSACTION_SERVICE, COIN_CHAIN_QUERY_SERVICE, COIN_ADDRESS_VALIDATION_SERVICE, GatewayConfigParser, GatewayApplicationService
from waves_gateway.storage import WalletStorage, MapStorage, KeyValueStorage
from waves_gateway.common import convert_to_int, convert_to_decimal, ProxyGuard, InvalidTransactionIdentifier, InjectionToken, Injectable, Factory, INJECTOR, Injector, InjectorError, Token, COIN_NODE, CUSTOM_CURRENCY_NAME, WAVES_ASSET_ID, ProxyFactory

from typing import NewType

CoinAddress = NewType('CoinAddress', str)
WavesAddress = NewType('WavesAddress', str)

WavesAddressSecret = NewType('WavesAddressSecret', KeyPair)
CoinAddressSecret = NewType('CoinAddressSecret', KeyPair)

CoinTransactionIdentifier = NewType('CoinTransactionIdentifier', str)
WavesTransactionIdentifier = NewType('WavesTransactionIdentifier', str)

CoinBlockHeight = NewType('CoinBlockHeight', int)
WavesBlockHeight = NewType('WavesBlockHeight', int)

WavesTransaction = NewType('WavesTransaction', Transaction)
CoinTransaction = NewType('CoinTransaction', Transaction)

CoinAmount = NewType('CoinAmount', int)
github jansenmarc / WavesGatewayFramework / waves_gateway / __init__.py View on Github external
from typing import NewType

CoinAddress = NewType('CoinAddress', str)
WavesAddress = NewType('WavesAddress', str)

WavesAddressSecret = NewType('WavesAddressSecret', KeyPair)
CoinAddressSecret = NewType('CoinAddressSecret', KeyPair)

CoinTransactionIdentifier = NewType('CoinTransactionIdentifier', str)
WavesTransactionIdentifier = NewType('WavesTransactionIdentifier', str)

CoinBlockHeight = NewType('CoinBlockHeight', int)
WavesBlockHeight = NewType('WavesBlockHeight', int)

WavesTransaction = NewType('WavesTransaction', Transaction)
CoinTransaction = NewType('CoinTransaction', Transaction)

CoinAmount = NewType('CoinAmount', int)
github dahlia / wikidata / wikidata / cache.py View on Github external
.. versionchanged:: 0.5.0

"""
import collections
import hashlib
import logging
import pickle
import re
from typing import NewType, Optional

__all__ = ('CacheKey', 'CachePolicy', 'CacheValue',
           'MemoryCachePolicy', 'NullCachePolicy', 'ProxyCachePolicy')


#: The type of keys to look up cached values.  Alias of :class:`str`.
CacheKey = NewType('CacheKey', str)

#: The type of cached values.
CacheValue = NewType('CacheValue', object)


class CachePolicy:
    """Interface for caching policies."""

    def get(self, key: CacheKey) -> Optional[CacheValue]:
        r"""Look up a cached value by its ``key``.

        :param key: The key string to look up a cached value.
        :type key: :const:`CacheKey`
        :return: The cached value if it exists.
                 :const:`None` if there's no such ``key``.
        :rtype: :class:`~typing.Optional`\ [:const:`CacheValue`]