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 / test_python_lang.py View on Github external
def test_iterable(self):
        def f():
            yield 1
        self.assertTrue(isinstance([],typing.Iterable))
        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 / test_typing.py 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 / block_entity_dict.py 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

if TYPE_CHECKING:
    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:
            self._assert_val(block_entity)
            self.data[block_entity.location] = block_entity

        self._parent_chunk = weakref.ref(parent_chunk)

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

    @staticmethod
    def _check_key(key):
github bogdandm / json2python-models / json_to_models / registry.py 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):
                models2merge[model_a].add(model_b)
                models2merge[model_b].add(model_a)

        # 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 / extensions.py 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?
    ret.append(DEFAULT_PREBOOT_EXTENSIONS.keys())

    return ret
github delphix / sdb / sdb / command.py View on Github external
self.name, '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
            self.pretty_print(self.caller(objs))
        else:
            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 / identity.py View on Github external
Returns:
            Operations applying this gate to the target qubits.

        Raises:
            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
            gate.
        """
        if len(self._qid_shape) != 1:
            raise ValueError(
                'IdentityGate only supports on_each when it is a one qubit '
                'gate.')
        operations: List['cirq.Operation'] = []
        for target in targets:
            if isinstance(target, Iterable) and not isinstance(target, str):
                operations.extend(self.on_each(*target))
            elif isinstance(target, raw_types.Qid):
                operations.append(self.on(target))
            else:
                raise ValueError(
                    'Gate was called with type different than Qid. Type: {}'.
                    format(type(target)))
        return operations
github joelgrus / data-science-from-scratch / scratch / crash_course_in_python.py 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)
else:
    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 / __init__.py View on Github external
self._closed = False

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

    def _close(self):
        self._fileobj.flush()
        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:
        args: Positional arguments, passed to :class:`subprocess.Popen`
            constructor.
        stdin, stdout, stderr: Identical to the same arguments to
            :class:`subprocess.Popen`.
        kwargs: Keyword arguments, passed to :class:`subprocess.Popen`
            constructor.