How to use the typing.Iterable 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 kkyon / botflow / tests / View on Github external
def test_iterable(self):
        def f():
            yield 1
        self.assertTrue(isinstance((), typing.Iterable))
        self.assertTrue(isinstance((), typing.Tuple))
        self.assertTrue(isinstance([], typing.List))
        self.assertTrue(isinstance(f(), typing.Iterable))
        self.assertTrue(isinstance(f(), typing.Generator))
github python / typing / src / View on Github external
def test_iterable(self):
        self.assertIsInstance([], typing.Iterable)
        # Due to ABC caching, the second time takes a separate code
        # path and could fail.  So call this a few times.
        self.assertIsInstance([], typing.Iterable)
        self.assertIsInstance([], typing.Iterable)
        self.assertNotIsInstance(42, typing.Iterable)
        # Just in case, also test issubclass() a few times.
        self.assertIsSubclass(list, typing.Iterable)
        self.assertIsSubclass(list, typing.Iterable)
github Amulet-Team / Amulet-Core / amulet / api / chunk / View on Github external
from collections import UserDict
from typing import TYPE_CHECKING, Tuple, Iterable, Generator
import copy
import weakref
import numpy

from amulet.api.block_entity import BlockEntity

    from amulet.api.chunk import Chunk

Coordinate = Tuple[int, int, int]

class BlockEntityDict(UserDict):
    InputType = Iterable[BlockEntity]

    def __init__(self, parent_chunk: "Chunk", block_entities: InputType = ()):
        super(BlockEntityDict, self).__init__()
        for block_entity in block_entities:
  [block_entity.location] = block_entity

        self._parent_chunk = weakref.ref(parent_chunk)

    def _assert_key(self, key):
        assert self._check_key(
        ), f"Key must be in the format Tuple[int, int, int]. Got: {key}"

    def _check_key(key):
github bogdandm / json2python-models / json_to_models / View on Github external
Optimize whole models registry by merging same or similar models (uses given models comparators)

        :param generator: Generator instance that will be used to metadata merging and optimization
        :param strict: if True ALL models in merge group should meet the conditions
            else groups will form from pairs of models as is.
        :return: pairs of (new model, set of old models)
        # TODO: Implement strict mode
        models2merge: Dict[ModelMeta, Set[ModelMeta]] = defaultdict(set)
        for model_a, model_b in combinations(self.models, 2):
            if self._models_cmp_fn(model_a, model_b):

        # Groups of models to merge
        groups: Iterable[Set[ModelMeta]] = [{model, *models} for model, models in models2merge.items()]
        # Make groups non-overlapping.
        # This is not optimal algorithm but it works and we probably will not have thousands of models here.
        flag = True
        while flag:
            flag = False
            new_groups: OrderedSet[Set[ModelMeta]] = OrderedSet()
            for gr1, gr2 in combinations(groups, 2):
                if gr1 & gr2:
                    old_len = len(new_groups)
                    new_groups.add(frozenset(gr1 | gr2))
                    added = old_len < len(new_groups)
                    flag = flag or added
            if flag:
                groups = new_groups

        replaces = []
github groboclown / petronia / src / petronia / boot / platform / general / View on Github external
def get_preboot_extension_sets() -> Iterable[Iterable[str]]:
    ret: List[Iterable[str]] = []

    # TODO load the defaults from an ini or config file?

    return ret
github delphix / sdb / sdb / View on Github external, 'no handler for input of type {}'.format(i.type_))

    def _call(self,
              objs: Iterable[drgn.Object]) -> Optional[Iterable[drgn.Object]]:
        # pylint: disable=missing-docstring
        # If this is a hybrid locator/pretty printer, this is where that is
        # leveraged.
        if self.islast and isinstance(self, PrettyPrinter):
            # pylint: disable=no-member
            yield from self.caller(objs)

T = TypeVar("T", bound=Locator)
IH = Callable[[T, drgn.Object], Iterable[drgn.Object]]

def InputHandler(typename: str) -> Callable[[IH[T]], IH[T]]:
    This is a decorator which should be applied to methods of subclasses of
    Locator. The decorator causes this method to be called when the pipeline
    passes an object of the specified type to this Locator.

    def decorator(func: IH[T]) -> IH[T]:
        func.input_typename_handled = typename  # type: ignore
        return func

    return decorator
github quantumlib / Cirq / cirq / ops / View on Github external
            Operations applying this gate to the target qubits.

            ValueError if targets are not instances of Qid or List[Qid] or
            the gate from which this is applied is not a single qubit identity
        if len(self._qid_shape) != 1:
            raise ValueError(
                'IdentityGate only supports on_each when it is a one qubit '
        operations: List['cirq.Operation'] = []
        for target in targets:
            if isinstance(target, Iterable) and not isinstance(target, str):
            elif isinstance(target, raw_types.Qid):
                raise ValueError(
                    'Gate was called with type different than Qid. Type: {}'.
        return operations
github joelgrus / data-science-from-scratch / scratch / View on Github external
values: List[int] = []
best_so_far: Optional[float] = None  # allowed to be either a float or None

lazy = True

# the type annotations in this snippet are all unnecessary
from typing import Dict, Iterable, Tuple

# keys are strings, values are ints
counts: Dict[str, int] = {'data': 1, 'science': 2}

# lists and generators are both iterable
if lazy:
    evens: Iterable[int] = (x for x in range(10) if x % 2 == 0)
    evens = [0, 2, 4, 6, 8]

# tuples specify a type for each element
triple: Tuple[int, float, int] = (10, 2.3, 5)

from typing import Callable

# The type hint says that repeater is a function that takes
# two arguments, a string and an int, and returns a string.
def twice(repeater: Callable[[str, int], str], s: str) -> str:
    return repeater(s, 2)

def comma_repeater(s: str, n: int) -> str:
    n_copies = [s for _ in range(n)]
    return ', '.join(n_copies)
github jdidion / xphyle / xphyle / View on Github external
self._closed = False

    def closed(self) -> bool:
        return self._closed

    def _close(self):
        self._closed = True

PopenStdArg = Union[PathOrFile, int]  # pylint: disable=invalid-name

# noinspection PyAbstractClass
class Process(Popen, EventManager, FileLikeBase, Iterable):
    """Subclass of :class:`subprocess.Popen` with the following additions:

    * Provides :method:`Process.wrap_pipes` for wrapping stdin/stdout/stderr
    (e.g. to send compressed data to a process' stdin or read compressed data
    from its stdout/stderr).
    * Provides :method:`Process.close` for properly closing stdin/stdout/stderr
    streams and terminating the process.
    * Implements required methods to make objects 'file-like'.

        args: Positional arguments, passed to :class:`subprocess.Popen`
        stdin, stdout, stderr: Identical to the same arguments to
        kwargs: Keyword arguments, passed to :class:`subprocess.Popen`