How to use the typing.TypeVar 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 python / typing / src / test_typing.py View on Github external
def test_cannot_instantiate_vars(self):
        with self.assertRaises(TypeError):
            TypeVar('A')()
github common-workflow-language / schema_salad / schema_salad / ref_resolver.py View on Github external
from rdflib.graph import Graph
from rdflib.namespace import OWL, RDF, RDFS
from rdflib.plugins.parsers.notation3 import BadSyntax
from six.moves import range, urllib

from ruamel import yaml
from ruamel.yaml.comments import CommentedMap, CommentedSeq, LineCol

from .exceptions import SchemaSaladException, ValidationException
from .sourceline import SourceLine, add_lc_filename, relname
from .utils import aslist, onWindows


_logger = logging.getLogger("salad")
ContextType = Dict[str, Union[Dict[str, Any], str, Iterable[str]]]
DocumentType = TypeVar("DocumentType", CommentedSeq, CommentedMap)
DocumentOrStrType = TypeVar("DocumentOrStrType", CommentedSeq, CommentedMap, str)

_re_drive = re.compile(r"/([a-zA-Z]):")


def file_uri(path, split_frag=False):  # type: (str, bool) -> str
    if path.startswith("file://"):
        return path
    if split_frag:
        pathsp = path.split("#", 2)
        frag = "#" + urllib.parse.quote(str(pathsp[1])) if len(pathsp) == 2 else ""
        urlpath = urllib.request.pathname2url(str(pathsp[0]))
    else:
        urlpath = urllib.request.pathname2url(path)
        frag = ""
    if urlpath.startswith("//"):
github emilkarlen / exactly / src / exactly_lib / symbol / logic / matcher.py View on Github external
from abc import ABC, abstractmethod
from typing import Generic, TypeVar

from exactly_lib.symbol.logic.logic_type_sdv import LogicSdv
from exactly_lib.type_system.logic.matcher_base_class import MatcherDdv, MatcherWTrace
from exactly_lib.util.symbol_table import SymbolTable

MODEL = TypeVar('MODEL')


class MatcherSdv(Generic[MODEL],
                 LogicSdv[MatcherWTrace[MODEL]],
                 ABC):
    @abstractmethod
    def resolve(self, symbols: SymbolTable) -> MatcherDdv[MODEL]:
        pass
github allenai / citeomatic / citeomatic / traits.py View on Github external
import typing

import traitlets

T1 = typing.TypeVar('T1')
T2 = typing.TypeVar('T2')
T3 = typing.TypeVar('T3')
T4 = typing.TypeVar('T4')

T = typing.TypeVar('T')
K = typing.TypeVar('K')
V = typing.TypeVar('V')


# Define wrappers for traitlets classes.  These simply provide Python type hints
# that correspond to actual instance type that will result after a class is
# instantiated (e.g. Unicode() becomes a string).
#
# This allows PyCharm style type hinting to resolve types properly.
def Float(*args, **kw) -> float:
    return traitlets.Float(*args, **kw)


def CFloat(*args, **kw) -> float:
github jreese / aioitertools / aioitertools / types.py View on Github external
AsyncIterable,
    AsyncIterator,
    Awaitable,
    Callable,
    Iterable,
    Iterator,
    TypeVar,
    Union,
)

R = TypeVar("R")
T = TypeVar("T")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
T4 = TypeVar("T4")
T5 = TypeVar("T5")
N = TypeVar("N", int, float)

AnyFunction = Union[Callable[..., R], Callable[..., Awaitable[R]]]
AnyIterable = Union[Iterable[T], AsyncIterable[T]]
AnyIterableIterable = Union[Iterable[AnyIterable[T]], AsyncIterable[AnyIterable[T]]]
AnyIterator = Union[Iterator[T], AsyncIterator[T]]
AnyStop = (StopIteration, StopAsyncIteration)
Accumulator = Union[Callable[[T, T], T], Callable[[T, T], Awaitable[T]]]
KeyFunction = Union[Callable[[T], R], Callable[[T], Awaitable[R]]]
Predicate = Union[Callable[[T], object], Callable[[T], Awaitable[object]]]
github Tatsh / youtube-unofficial / youtube_unofficial / util.py View on Github external
from .typing.history import DescriptionSnippetDict
from .typing.ytcfg import YtcfgDict

__all__ = (
    'context_client_body',
    'extract_attributes',
    'extract_keys',
    'get_text_runs',
    'html_hidden_inputs',
    'path',
    'path_default',
    'remove_start',
    'try_get',
)

T = TypeVar('T')


class HTMLAttributeParser(HTMLParser):  # pylint: disable=abstract-method
    """Trivial HTML parser to gather the attributes for a single element"""
    def __init__(self) -> None:
        self.attrs: Dict[Any, Any] = {}
        HTMLParser.__init__(self)

    def handle_starttag(self, tag: Any, attrs: Any) -> None:
        self.attrs = dict(attrs)


def extract_attributes(html_element: str) -> Mapping[str, str]:
    """Given a string for an HTML element such as
github life4 / deal / deal / _decorators / inv.py View on Github external
# built-in
from functools import partial, update_wrapper
from types import MethodType
from typing import Callable, TypeVar

# app
from .._exceptions import InvContractError
from .._types import ExceptionType
from .base import Base


_CallableType = TypeVar('_CallableType', bound=Callable)


class InvariantedClass:
    _disable_patching: bool = False

    def _validate(self) -> None:
        """
        Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
        """
        # disable methods matching before validation
        self._disable_patching = True
        # validation by Invariant.validate
        self._validate_base(self)
        # enable methods matching after validation
        self._disable_patching = False
github HypothesisWorks / hypothesis / hypothesis-python / src / hypothesis / core.py View on Github external
)
from hypothesis.statistics import note_engine_for_statistics
from hypothesis.strategies._internal.collections import TupleStrategy
from hypothesis.strategies._internal.strategies import (
    MappedSearchStrategy,
    SearchStrategy,
)
from hypothesis.utils.conventions import infer
from hypothesis.vendor.pretty import CUnicodeIO, RepresentationPrinter
from hypothesis.version import __version__

if False:
    from typing import Any, Dict, Callable, Hashable, Optional, Union, TypeVar  # noqa
    from hypothesis.utils.conventions import InferType  # noqa

    TestFunc = TypeVar("TestFunc", bound=Callable)


running_under_pytest = False
global_force_seed = None


@attr.s()
class Example(object):
    args = attr.ib()
    kwargs = attr.ib()


def example(*args, **kwargs):
    # type: (*Any, **Any) -> Callable[[TestFunc], TestFunc]
    """A decorator which ensures a specific example is always tested."""
    if args and kwargs:
github zero323 / pyspark-stubs / third_party / 3 / pyspark / ml / _typing.py View on Github external
from typing import Any, Dict, TypeVar, Union
from typing_extensions import Literal

import pyspark.ml.base
import pyspark.ml.param
import pyspark.ml.util
import pyspark.ml.wrapper

ParamMap = Dict[pyspark.ml.param.Param, Any]
PipelineStage = Union[pyspark.ml.base.Estimator, pyspark.ml.base.Transformer]

T = TypeVar("T")
P = TypeVar("P", bound=pyspark.ml.param.Params)
M = TypeVar("M", bound=pyspark.ml.base.Transformer)
JM = TypeVar("JM", bound=pyspark.ml.wrapper.JavaTransformer)

BinaryClassificationEvaluatorMetricType = Union[
    Literal["areaUnderROC"], Literal["areaUnderPR"]
]
RegressionEvaluatorMetricType = Union[
    Literal["rmse"], Literal["mse"], Literal["r2"], Literal["mae"], Literal["var"]
]
MulticlassClassificationEvaluatorMetricType = Union[
    Literal["f1"],
    Literal["accuracy"],
    Literal["weightedPrecision"],
    Literal["weightedRecall"],
    Literal["weightedTruePositiveRate"],
    Literal["weightedFalsePositiveRate"],
github TeamSpen210 / HammerAddons / unify_fgd.py View on Github external
'BEE2',  # BEEmod's templates.
}

ALL_TAGS = set()  # type: Set[str]
ALL_TAGS.update(GAME_ORDER)
ALL_TAGS.update(ALL_FEATURES)
ALL_TAGS.update(TAGS_SPECIAL)
ALL_TAGS.update('SINCE_' + t.upper() for t in GAME_ORDER)
ALL_TAGS.update('UNTIL_' + t.upper() for t in GAME_ORDER)


# If the tag is present, run to backport newer FGD syntax to older engines.
POLYFILLS = []  # type: List[Tuple[str, Callable[[FGD], None]]]


PolyfillFuncT = TypeVar('PolyfillFuncT', bound=Callable[[FGD], None])

# This ends up being the C1 Reverse Line Feed in CP1252,
# which Hammer displays as nothing. We can suffix visgroups with this to
# have duplicates with the same name.
VISGROUP_SUFFIX = '\x8D'


def _polyfill(*tags: str) -> Callable[[PolyfillFuncT], PolyfillFuncT]:
    """Register a polyfill, which backports newer FGD syntax to older engines."""
    def deco(func: PolyfillFuncT) -> PolyfillFuncT:
        for tag in tags:
            POLYFILLS.append((tag.upper(), func))
        return func
    return deco