def test_resolves_NewType(): typ = NewType("T", int) nested = NewType("NestedT", typ) uni = NewType("UnionT", Union[int, None]) assert isinstance(from_type(typ).example(), int) assert isinstance(from_type(nested).example(), int) assert isinstance(from_type(uni).example(), (int, type(None)))
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
def test_basic(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) self.assertIsInstance(UserId(5), int) self.assertIsInstance(UserName('Joe'), type('Joe')) self.assertEqual(UserId(5) + 1, 6)
import base64 import logging from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, IO from typing_extensions import NewType import telegram from ehforwarderbot import EFBChat, EFBChannel from ehforwarderbot.types import ChatID, ModuleID from .locale_mixin import LocaleMixin if TYPE_CHECKING: from . import TelegramChannel TelegramChatID = NewType('TelegramChatID', str) TelegramMessageID = NewType('TelegramMessageID', str) TgChatMsgIDStr = NewType('TgChatMsgIDStr', str) EFBChannelChatIDStr = NewType('EFBChannelChatIDStr', str) # TelegramChatID = Union[str, int] # TelegramMessageID = Union[str, int] # TgChatMsgIDStr = str # EFBChannelChatIDStr = str class ExperimentalFlagsManager(LocaleMixin): DEFAULT_VALUES = { "chats_per_page": 10, "multiple_slave_chats": True, "network_error_prompt_interval": 100,
"""A list of type aliases when no separate class is defined for some types of values. User-facing types (display names, descriptions, message text, etc.) shall not be included here, """ from typing import Collection, TYPE_CHECKING, Mapping from typing_extensions import NewType if TYPE_CHECKING: from .chat import EFBChat ReactionName = NewType('ReactionName', str) """Canonical representation of a reaction, usually an emoji.""" Reactions = Mapping[ReactionName, Collection['EFBChat']] """Reactions to a message.""" ModuleID = NewType('ModuleID', str) "Module ID, including instance ID after ``#`` if available." InstanceID = NewType('InstanceID', str) "Instance ID of a module." ChatID = NewType('ChatID', str) "Chat ID from slave channel or middleware." MessageID = NewType('MessageID', str) "Message ID from slave channel or middleware." ExtraCommandName = NewType('ExtraCommandName', str) """Command name of additional features, in the format of ``^[A-Za-z][A-Za-z0-9_]{0,19}$``.
from typing import Any, Dict from typing_extensions import Literal, NewType, TypedDict RoomId = NewType("RoomId", str) UserId = NewType("UserId", str) Role = Literal["admin", "owner", "bot", "host", "mod", "driver", "player", "voice", "prizewinner"] JsonDict = Dict[str, Any] # type: ignore[misc] TiersDict = TypedDict( "TiersDict", { "name": str, "section": str, "random": bool, }, )
from vartable.translation import TResult, translate_one from Bio.SeqFeature import CompoundLocation, FeatureLocation, SeqFeature, ExactPosition from Bio.Seq import Seq from Bio.Data.CodonTable import TranslationError from Bio.SeqFeature import ExactPosition from typing import Union, List from typing_extensions import NewType, Literal from nose.tools import eq_, ok_ from dataclasses import dataclass # Warning: all tests should use 0-based indexing. #@dataclass #class Seq: # _data: str ExactPosition = NewType('ExactPosition', int) ''' all one-indexed ''' Strand = Literal[-1, 1] #@dataclass #class FeatureLocation: # _start: ExactPosition # _end: ExactPosition # strand: Strand # #@dataclass #class CompoundLocation: # parts: List[FeatureLocation] # location_operator: str #
return None def get_state_region(self) -> "Region": """Returns a Region object for the state of a county or place, otherwise raises a ValueError.""" if len(self.fips) != 5 and len(self.fips) != 7: raise ValueError(f"No state for {self}") return Region.from_fips(self.fips[:2]) @final @dataclass(frozen=True) class RegionMask: """Represents attributes which may be used to select a subset of regions.""" # A level (county, state, ...) OR None to select regions ignoring their level. level: Optional[AggregationLevel] = None # A list of states, each a two letter string OR None to select regions ignoring their state. states: Optional[List[str]] = None RegionMaskOrRegion = NewType("RegionMaskOrRegion", Union[RegionMask, Region]) def us_states_and_territories_to_country_map() -> Mapping[Region, Region]: us_country_region = Region.from_location_id("iso1:us") return { Region.from_state(state): us_country_region for state in us_state_abbrev.US_STATE_ABBREV.values() }
from typing import Union, NamedTuple, List, Dict, Tuple, Callable, TypeVar, Iterator, Optional, Callable, Iterable, Sequence from typing_extensions import NewType, Literal from abc import ABCMeta, ABC T = TypeVar('T') Nuc = Literal['A', 'C', 'G', 'T', 'N'] AA = Literal['A', 'R', 'N', 'D', 'C', 'E', \ 'Q', 'G', 'H', 'I', 'L', 'K', 'M', \ 'F', 'P', 'S', 'T', 'W', 'Y', 'V'] Ref = NewType('Ref', str) Codon = NewType('Codon', str) # Codon = Tuple[Nuc, Nuc, Nuc] #TODO: check math of one-based indexing #class CDS(metaclass=ABCMeta): #class CDS(ABC): # pass class SimpleCDS: '''note: uses 1-based indexing.''' def __init__(self, is_reverse: bool, start: int, end: int): self.isReverse = is_reverse self.start = start self.end = end class CompoundCDS: def __init__(self, is_reverse: bool, regions: List[SimpleCDS]):