How to use the typing.Generic 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 / mypy / mypyc / test-data / fixtures / ir.py View on Github external
def __getitem__(self, key: K) -> V: pass
    def __setitem__(self, k: K, v: V) -> None: pass
    def __delitem__(self, k: K) -> None: pass
    def __contains__(self, item: object) -> int: pass
    def __iter__(self) -> Iterator[K]: pass
    def __len__(self) -> int: pass
    @overload
    def update(self, __m: Mapping[K, V], **kwargs: V) -> None: pass
    @overload
    def update(self, __m: Iterable[Tuple[K, V]], **kwargs: V) -> None: ...
    @overload
    def update(self, **kwargs: V) -> None: ...
    def pop(self, x: int) -> K: pass
    def keys(self) -> List[K]: pass

class set(Generic[T]):
    def __init__(self, i: Optional[Iterable[T]] = None) -> None: pass
    def __iter__(self) -> Iterator[T]: pass
    def __len__(self) -> int: pass
    def add(self, x: T) -> None: pass
    def remove(self, x: T) -> None: pass
    def discard(self, x: T) -> None: pass
    def clear(self) -> None: pass
    def pop(self) -> T: pass
    def update(self, x: Iterable[S]) -> None: pass
    def __or__(self, s: Set[S]) -> Set[Union[T, S]]: ...

class slice: pass

class property:
    def __init__(self, fget: Optional[Callable[[Any], Any]] = ...,
                 fset: Optional[Callable[[Any, Any], None]] = ...,
github mil-tokyo / webdnn / src / graph_transpiler / webdnn / backend / interface / descriptor_generator.py View on Github external
from collections import defaultdict
from typing import Generic, TypeVar, Type, Callable, List, Dict

from webdnn.backend.code_generator.allocator import MemoryLayout
from webdnn.graph import traverse
from webdnn.graph.graph import Graph
from webdnn.graph.operator import Operator
from webdnn.util import console

T_KERNEL = TypeVar("T_KERNEL")
T_EXEC_DATA = TypeVar("T_EXEC_DATA")


class DescriptorGenerator(Generic[T_KERNEL, T_EXEC_DATA]):
    _handler_map = defaultdict(dict)  # type: Dict[str, Dict[str, Callable[[Operator, MemoryLayout], List[T_KERNEL]]]]

    @classmethod
    def generate(cls, graph: Graph, constant_encoder_name: str = None) -> T_EXEC_DATA:
        raise NotImplementedError

    @classmethod
    def register_handler(cls, OperatorClass: Type[Operator]):
        key = OperatorClass.__name__

        def decorator(handler: Callable[[Operator, MemoryLayout], List[T_KERNEL]]):
            if key in cls._handler_map[cls.__name__]:
                console.warning(f"[{cls.__name__}] Generator handler of '{key}' is already registered and overwritten.")

            cls._handler_map[cls.__name__][key] = handler
github mortoray / mdl / mdl / doc_tree.py View on Github external
class Node(abc.ABC):
	def __init__(self):
		super().__init__()
		
	def visit( self, proc : VisitCallback ) -> None:
		if proc.enter( self ):
			self.visit_children( proc )
		proc.exit( self )
		
	def visit_children( self, proc : VisitCallback ) -> None:
		pass

		
T = typing.TypeVar('T', bound = Node)
class NodeContainer(typing.Generic[T]):
	def __init__(self):
		super().__init__()
		self._sub : typing.List[T] = []

	def _validate_sub( self, sub : T ) -> None:
		# There is no way to check if sub is of type T here :/
		pass
	
	def add_sub( self, sub : T ) -> None:
		self._validate_sub( sub )
		self._sub.append( sub )
		
	def add_subs( self, subs : typing.Sequence[T] ) -> None:
		for sub in subs:
			self.add_sub( sub )
github allenai / allennlp / allennlp / state_machines / states / state.py View on Github external
from typing import Generic, List, TypeVar

import torch

# Note that the bound here is `State` itself.  This is what lets us have methods that take
# lists of a `State` subclass and output structures with the subclass.  Really ugly that we
# have to do this generic typing _for our own class_, but it makes mypy happy and gives us good
# type checking in a few important methods.
T = TypeVar("T", bound="State")


class State(Generic[T]):
    """
    Represents the (batched) state of a transition-based decoder.

    There are two different kinds of batching we need to distinguish here.  First, there's the
    batch of training instances passed to ``model.forward()``.  We'll use "batch" and
    ``batch_size`` to refer to this through the docs and code.  We additionally batch together
    computation for several states at the same time, where each state could be from the same
    training instance in the original batch, or different instances.  We use "group" and
    ``group_size`` in the docs and code to refer to this kind of batching, to distinguish it from
    the batch of training instances.

    So, using this terminology, a single ``State`` object represents a `grouped` collection of
    states.  Because different states in this group might finish at different timesteps, we have
    methods and member variables to handle some bookkeeping around this, to split and regroup
    things.
github binderclip / code-snippets-python / packages / typing_snippets / generics_sp.py View on Github external
# coding: utf-8
import logging
from typing import Sequence, TypeVar, Generic, Iterable
from typing import TypeVar, Generic
from logging import Logger

T = TypeVar('T')


class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)
github dry-python / returns / returns / typeclasses / functor.py View on Github external
from abc import abstractmethod
from typing import Callable, Generic, TypeVar

from returns.hkt import Kind

_ValueType = TypeVar('_ValueType')
_NewValueType = TypeVar('_NewValueType')
_FunctorType = TypeVar('_FunctorType', bound='Functor')


class Functor(Generic[_ValueType]):
    """Functor typeclass definition."""

    @abstractmethod  # noqa: WPS125
    def map(  # noqa: WPS125
        self: _FunctorType,
        function: Callable[[_ValueType], _NewValueType],
    ) -> Kind[_FunctorType, _NewValueType]:
        """Allows to run a pure function over a container."""
github ClearcodeHQ / matchbox / src / matchbox / index.py View on Github external
# matchbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with matchbox.  If not, see .
"""Data structure that allows indexing includes and excludes of values."""
from collections import defaultdict
from typing import Set, Hashable, Dict, TypeVar, Generic

ET = TypeVar('ET', bound=Hashable)
TT = TypeVar('TT', bound=Hashable)


class MatchIndex(Generic[TT, ET]):
    """
    An index for matching or mismatching of entities by hashable traits.

    It can answer one question - 'given a trait, what entities are excluded by it?'.
    It can be used to filter a set of potential matches - not for general querying ('given a trait
    return all mathing entities').
    When used as a filter, all entities in the input set must also be indexed by the MatchIndex to be fully filtered.

    .. note ::
        We can index entities by including or excluding them for given traits.
        Matching an object for some characteristic traits means that this object will match those values and it will NOT
        match any other traits.
        Mismatching an object for some traits means that this object will NOT match those traits and will match
        any other trait.
        It makes no sense for an entity to both match and mismatch the same characteristic.
github gromacs / gromacs / python_packaging / src / gmxapi / typing.py View on Github external
def dtype(self) -> Type[ResultTypeVar]:
        ...

    def result(self) -> ResultTypeVar:
        ...


class OperationReference(gmxapi.abc.OperationReference, Generic[_Op]):
    """Object with an OperationReference interface.

    Generic version of AbstractOperationReference, parameterized by operation
    implementation.
    """


class OperationDirector(Generic[_Op, _Context]):
    """Generic abstract operation director.

    An operation director is instantiated for a specific operation and context
    by a dispatching factory to add a computational element to the work managed
    by the context.

    Note:
        This is a generic class, as defined with the Python `typing` module.
        If used as a base class, re-expression of the TypeVar parameters in class
        subscripts will cause the derived class to be generic unless regular
        classes (non-TypeVar) are given. Omission of the subscripts causes `Any`
        to be bound, which also results in a non-generic subclass.
    """


class OperationImplementation(Generic[_Op], gmxapi.abc.OperationImplementation):
github python / mypy / mypy / visitor.py View on Github external
    @abstractmethod
    def visit_try_stmt(self, o: 'mypy.nodes.TryStmt') -> T:
        pass

    @abstractmethod
    def visit_print_stmt(self, o: 'mypy.nodes.PrintStmt') -> T:
        pass

    @abstractmethod
    def visit_exec_stmt(self, o: 'mypy.nodes.ExecStmt') -> T:
        pass


@trait
class NodeVisitor(Generic[T], ExpressionVisitor[T], StatementVisitor[T]):
    """Empty base class for parse tree node visitors.

    The T type argument specifies the return type of the visit
    methods. As all methods defined here return None by default,
    subclasses do not always need to override all the methods.

    TODO make the default return value explicit
    """

    # Not in superclasses:

    def visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> T:
        pass

    # TODO: We have a visit_var method, but no visit_typeinfo or any
    # other non-Statement SymbolNode (accepting those will raise a