Python typing.Container() Examples

The following are 30 code examples of typing.Container(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: functions.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def given_function_called(node: Call, to_check: Container[str]) -> str:
    """
    Returns function name if it is called and contained in the container.

    >>> import ast
    >>> module = ast.parse('print(123, 456)')
    >>> given_function_called(module.body[0].value, ['print'])
    'print'

    >>> given_function_called(module.body[0].value, ['adjust'])
    ''

    """
    function_name = source.node_to_string(node.func)
    if function_name in to_check:
        return function_name
    return '' 
Example #2
Source File: _layout.py    From clifford with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bases(self, mvClass=MultiVector, grades: Optional[Container[int]] = None) -> Dict[str, MultiVector]:
        """Returns a dictionary mapping basis element names to their MultiVector
        instances, optionally for specific grades

        if you are lazy,  you might do this to populate your namespace
        with the variables of a given layout.

        >>> locals().update(layout.blades())  # doctest: +SKIP

        .. versionchanged:: 1.1.0
            This dictionary includes the scalar
        """
        return {
            name: self._basis_blade(i, mvClass)
            for i, (name, grade) in enumerate(zip(self.names, self._basis_blade_order.grades))
            if grades is None or grade in grades
        } 
Example #3
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_subclassing_register(self):

        class A(typing.Container): ...
        class B(A): ...

        class C: ...
        A.register(C)
        self.assertIsSubclass(C, A)
        self.assertNotIsSubclass(C, B)

        class D: ...
        B.register(D)
        self.assertIsSubclass(D, A)
        self.assertIsSubclass(D, B)

        class M(): ...
        collections.MutableMapping.register(M)
        self.assertIsSubclass(M, typing.Mapping) 
Example #4
Source File: data.py    From modAL with MIT License 6 votes vote down vote up
def data_vstack(blocks: Container) -> modALinput:
    """
    Stack vertically both sparse and dense arrays.

    Args:
        blocks: Sequence of modALinput objects.

    Returns:
        New sequence of vertically stacked elements.
    """
    if isinstance(blocks[0], np.ndarray):
        return np.concatenate(blocks)
    elif isinstance(blocks[0], list):
        return list(chain(blocks))
    elif sp.issparse(blocks[0]):
        return sp.vstack(blocks)
    else:
        try:
            return np.concatenate(blocks)
        except:
            raise TypeError('%s datatype is not supported' % type(blocks[0])) 
Example #5
Source File: typing_predicates.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check(self, value, namespace):
        if not self._is_possible_subclass(type(value), self._cls):
            return False  # totally the wrong type
        # now check the content of the value, if possible:
        assert type(self._cls) == tg.GenericMeta
        params = self._cls.__parameters__
        result = True  # any failing check will set it to False
        # check checkable relevant properties of all
        # relevant Generic subclasses from the typing module.
        # Fall back from specific to less specific leave the content
        # check out if there are more __parameters__ than expected:
        if (self._we_want_to_check(value, tg.Sequence)):
            return self._check_sequence(value, params, namespace)
        if (self._we_want_to_check(value, tg.Mapping)):
            return self._check_mapping(value, params, namespace)
        if (self._we_want_to_check(value, tg.Iterable)):
            return self._check_by_iterator(value, params, namespace)
        # tg.Iterator: nothing is checkable: reading would modify it
        # tg.Container: nothing is checkable: would need to guess elements
        return True  # no content checking possible 
Example #6
Source File: schemas.py    From CTFd with Apache License 2.0 6 votes vote down vote up
def sqlalchemy_to_pydantic(
    db_model: Type, *, exclude: Container[str] = []
) -> Type[BaseModel]:
    """
    Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
    """
    mapper = inspect(db_model)
    fields = {}
    for attr in mapper.attrs:
        if isinstance(attr, ColumnProperty):
            if attr.columns:
                column = attr.columns[0]
                python_type = column.type.python_type
                name = attr.key
                if name in exclude:
                    continue
                default = None
                if column.default is None and not column.nullable:
                    default = ...
                fields[name] = (python_type, default)
    pydantic_model = create_model(
        db_model.__name__, **fields  # type: ignore
    )
    return pydantic_model 
Example #7
Source File: data.py    From indosum with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 paragraphs: Sequence[Paragraph],
                 summary: Optional[Paragraph] = None,
                 category: Optional[str] = None,
                 source: Optional[str] = None,
                 source_url: Optional[str] = None,
                 id_: Optional[str] = None,
                 lower: bool = False,
                 remove_puncts: bool = False,
                 replace_digits: bool = False,
                 stopwords: Optional[Container[Word]] = None,
                 ) -> None:
        self.paragraphs = paragraphs
        self.summary = summary
        self.category = category
        self.source = source
        self.source_url = source_url
        self.id_ = id_
        self.lower = lower
        self.remove_puncts = remove_puncts
        self.replace_digits = replace_digits
        self.stopwords = stopwords

        self.preprocess() 
Example #8
Source File: taar_amodump.py    From python_mozetl with MIT License 5 votes vote down vote up
def marshal(value, name, type_def):
    serializers = {
        typing.List: list,
        typing.Dict: dict,
        str: text_type,
        text_type: text_type,
        int: int,
        float: float,
        bool: bool,
    }

    if issubclass(type_def, JSONSchema):
        obj = {}
        for attr_name, attr_type_def in list(type_def.meta.items()):
            attr_value = value.get(attr_name, Undefined)
            if attr_value is not Undefined:
                # Try marshalling the value
                obj[attr_name] = marshal(attr_value, attr_name, attr_type_def)
        return obj
    elif issubclass(type_def, typing.Container) and type_def not in [str, bytes]:
        if issubclass(type_def, typing.List):
            item_type = type_def.__args__[0]
            return [marshal(j, name, item_type) for j in value]
        elif issubclass(type_def, typing.Dict):
            if value is None:
                return None
            k_cast, v_cast = type_def.__args__
            dict_vals = [
                (marshal(k, name, k_cast), marshal(v, name, v_cast))
                for k, v in list(value.items())
            ]
            return dict(dict_vals)
    else:
        return serializers[type_def](value) 
Example #9
Source File: tokens.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def only_contains(
    tokens: Iterable[tokenize.TokenInfo],
    container: Container[int],
) -> bool:
    """Determins that only tokens from the given list are contained."""
    for token in tokens:
        if token.exact_type not in container:
            return False
    return True 
Example #10
Source File: batch_nlg_response.py    From DeepPavlov with Apache License 2.0 5 votes vote down vote up
def __init__(self, nlg_responses: Container[NLGResponseInterface]):
        self.responses: Container[NLGResponseInterface] = nlg_responses 
Example #11
Source File: base.py    From trinity with MIT License 5 votes vote down vote up
def _load_state_machines(
    sm_configuration: StateMachineConfiguration, chain_db: BaseBeaconChainDB
) -> Iterable[Tuple[Container[int], "BaseBeaconStateMachine"]]:
    sm_configuration += ((FAR_FUTURE_SLOT, None),)
    for (first_fork, second_fork) in toolz.sliding_window(2, sm_configuration):
        valid_range = range(first_fork[0], second_fork[0])
        valid_sm = first_fork[1](chain_db)
        yield (valid_range, valid_sm) 
Example #12
Source File: base.py    From trinity with MIT License 5 votes vote down vote up
def __init__(self, chaindb: BaseBeaconChainDB) -> None:
        self.chaindb = chaindb

        _validate_sm_configuration(self.sm_configuration)
        self._state_machines_by_range: Dict[
            Container[int], "BaseBeaconStateMachine"
        ] = _load_state_machines(self.sm_configuration, self.chaindb) 
Example #13
Source File: test_typing_annotations.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_KeysView_to_Sequence_not_OK():
    with expected(tc.InputParameterError("v: dict_keys\(.*3.*")):
        assert foo_KeysView_to_Sequence({b'A':11, b'B':12, 3:13}.keys()) == [b'A', b'B', 13]


############################################################################
# for Iterator and Container we cannot check the actual content 
Example #14
Source File: test_typing_annotations.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def foo_Container(c: tg.Container[tg.Sequence[str]]):
    pass 
Example #15
Source File: test_typing_annotations.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_Iterable_Iterator_Container_OK():
    """
    No extra code is needed to check Iterable, Iterator, and Container,
    because there is no suitable way to access their contents.
    """
    foo_Iterator((dt.date.today(), dt.date.today()).__iter__())
    foo_Container([["nested", "list"], ["of", "strings"]]) 
Example #16
Source File: legacy_registries.py    From kopf with MIT License 5 votes vote down vote up
def iter_handlers(
            self,
            cause: AnyCause,
            excluded: Container[handlers.HandlerId] = frozenset(),  # only for signature matching
    ) -> Iterator[AnyHandler]:
        yield from self._handlers 
Example #17
Source File: orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_item_specifier_type(
    specifier, spec_types: Container = None, separator=":"
):
    """
    Returns a tuple that splits the string int a specifier, and its specifier
    type.

    Retruns a tuple of (specifier, specifier_type). If no specifier type could
    be found in the set, returns None in place of the specifier_type.

    :param specifier: The specifier string, such as "ip:10.0.0.1".
    :param spec_types: A container whose elements are strings that will be
        recognized as specifier types.
    :param separator: Optional specifier. Defaults to ':'.
    :return: tuple
    """
    if separator in specifier:
        tokens = specifier.split(separator, 1)
        if tokens[0] in spec_types:
            specifier_type = tokens[0]
            specifier = tokens[1].strip()
        else:
            specifier_type = None
    else:
        specifier_type = None
    return specifier, specifier_type 
Example #18
Source File: bogoliubov_transform_test.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def test_bogoliubov_transform_fourier_transform(transformation_matrix,
                                                initial_state,
                                                correct_state,
                                                atol=5e-6):
    n_qubits = transformation_matrix.shape[0]
    qubits = LineQubit.range(n_qubits)
    if isinstance(initial_state, Container):
        initial_state = sum(1 << (n_qubits - 1 - i) for i in initial_state)

    circuit = cirq.Circuit(bogoliubov_transform(
        qubits, transformation_matrix, initial_state=initial_state))
    state = circuit.final_wavefunction(initial_state)

    cirq.testing.assert_allclose_up_to_global_phase(
            state, correct_state, atol=atol) 
Example #19
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def get_Generic_parameters(tp, generic_supertype=None):
    """tp must be a subclass of generic_supertype.
    Retrieves the type values from tp that correspond to parameters
    defined by generic_supertype.

    E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
    to get_Mapping_key_value(tp) except for the error message.

    generic_supertype defaults to tp.__origin__ or closest __origin__ in
    terms of util.orig_mro if the former is not available.

    Note that get_Generic_itemtype(tp) is not exactly equal to
    get_Generic_parameters(tp, typing.Container), as that method
    additionally contains treatment for typing.Tuple and typing.Iterable.
    """
    if generic_supertype is None:
        generic_supertype = _origin(tp)
    if generic_supertype is None:
        for bs in pytypes.util.orig_mro(tp):
            generic_supertype = _origin(bs)
            if not generic_supertype is None:
                break
    try:
        res = _select_Generic_superclass_parameters(tp, generic_supertype)
    except TypeError:
        res = None
    if res is None:
        raise TypeError("%s has no proper parameters defined by %s."%
                (type_str(tp), type_str(generic_supertype)))
    else:
        return tuple(res) 
Example #20
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def get_Generic_itemtype(sq, simplify=True):
    """Retrieves the item type from a PEP 484 generic or subclass of such.
    sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
    Consequently this also works with typing.List, typing.Set and typing.Dict.
    Note that for typing.Dict and mapping types in general, the key type is regarded as item type.
    For typing.Tuple all contained types are returned as a typing.Union.
    If simplify == True some effort is taken to eliminate redundancies in such a union.
    """
    if is_Tuple(sq):
        if simplify:
            itm_tps = [x for x in get_Tuple_params(sq)]
            simplify_for_Union(itm_tps)
            return Union[tuple(itm_tps)]
        else:
            return Union[get_Tuple_params(sq)]
    else:
        try:
            res = _select_Generic_superclass_parameters(sq, typing.Container)
        except TypeError:
            res = None
        if res is None:
            try:
                res = _select_Generic_superclass_parameters(sq, typing.Iterable)
            except TypeError:
                pass
        if res is None or isinstance(res[0], TypeVar):
            raise TypeError("Has no itemtype: "+type_str(sq))
        else:
            return res[0] 
Example #21
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_container(self):
        self.assertIsInstance([], typing.Container)
        self.assertNotIsInstance(42, typing.Container) 
Example #22
Source File: test_typing.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_container(self):
        assert isinstance([], typing.Container)
        assert not isinstance(42, typing.Container) 
Example #23
Source File: assertions.py    From xcube with MIT License 5 votes vote down vote up
def assert_in(value: Any, container: Container, name: str = None):
    if value not in container:
        raise ValueError(f'{name or _DEFAULT_NAME} must be one of {container}') 
Example #24
Source File: pyupgrade.py    From pyupgrade with MIT License 5 votes vote down vote up
def _is_six(self, node: ast.expr, names: Container[str]) -> bool:
        return (
            isinstance(node, ast.Name) and
            node.id in names and
            node.id in self._from_imports['six']
        ) or (
            isinstance(node, ast.Attribute) and
            isinstance(node.value, ast.Name) and
            node.value.id == 'six' and
            node.attr in names
        ) 
Example #25
Source File: utils.py    From pytorch-UNet with MIT License 5 votes vote down vote up
def chk_mkdir(*paths: Container) -> None:
    """
    Creates folders if they do not exist.

    Args:
        paths: Container of paths to be created.
    """
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path) 
Example #26
Source File: decorators.py    From bot with MIT License 5 votes vote down vote up
def in_whitelist(
    *,
    channels: Container[int] = (),
    categories: Container[int] = (),
    roles: Container[int] = (),
    redirect: Optional[int] = Channels.bot_commands,
    fail_silently: bool = False,
) -> Callable:
    """
    Check if a command was issued in a whitelisted context.

    The whitelists that can be provided are:

    - `channels`: a container with channel ids for whitelisted channels
    - `categories`: a container with category ids for whitelisted categories
    - `roles`: a container with with role ids for whitelisted roles

    If the command was invoked in a context that was not whitelisted, the member is either
    redirected to the `redirect` channel that was passed (default: #bot-commands) or simply
    told that they're not allowed to use this particular command (if `None` was passed).
    """
    def predicate(ctx: Context) -> bool:
        """Check if command was issued in a whitelisted context."""
        return in_whitelist_check(ctx, channels, categories, roles, redirect, fail_silently)

    return commands.check(predicate) 
Example #27
Source File: scheduler.py    From bot with MIT License 5 votes vote down vote up
def reschedule_infractions(self, supported_infractions: t.Container[str]) -> None:
        """Schedule expiration for previous infractions."""
        await self.bot.wait_until_guild_available()

        log.trace(f"Rescheduling infractions for {self.__class__.__name__}.")

        infractions = await self.bot.api_client.get(
            'bot/infractions',
            params={'active': 'true'}
        )
        for infraction in infractions:
            if infraction["expires_at"] is not None and infraction["type"] in supported_infractions:
                self.schedule_task(infraction["id"], infraction) 
Example #28
Source File: scheduler.py    From bot with MIT License 5 votes vote down vote up
def __init__(self, bot: Bot, supported_infractions: t.Container[str]):
        super().__init__()

        self.bot = bot
        self.bot.loop.create_task(self.reschedule_infractions(supported_infractions)) 
Example #29
Source File: many_to_one.py    From matchpy with MIT License 5 votes vote down vote up
def _get_name_for_position(position: List[int], variables: Container[str]) -> str:
        new_name = 'i{}'.format('.'.join(map(str, position)))
        if new_name in variables:
            counter = 1
            while '{}_{}'.format(new_name, counter) in variables:
                counter += 1
            new_name = '{}_{}'.format(new_name, counter)
        return new_name 
Example #30
Source File: decorators.py    From seasonalbot with MIT License 4 votes vote down vote up
def in_channel_check(*channels: int, bypass_roles: t.Container[int] = None) -> t.Callable[[Context], bool]:
    """
    Checks that the message is in a whitelisted channel or optionally has a bypass role.

    If `in_channel_override` is present, check if it contains channels
    and use them in place of the global whitelist.
    """
    def predicate(ctx: Context) -> bool:
        if not ctx.guild:
            log.debug(f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM.")
            return True
        if ctx.channel.id in channels:
            log.debug(
                f"{ctx.author} tried to call the '{ctx.command.name}' command "
                f"and the command was used in a whitelisted channel."
            )
            return True

        if bypass_roles and any(r.id in bypass_roles for r in ctx.author.roles):
            log.debug(
                f"{ctx.author} called the '{ctx.command.name}' command and "
                f"had a role to bypass the in_channel check."
            )
            return True

        if hasattr(ctx.command.callback, "in_channel_override"):
            override = ctx.command.callback.in_channel_override
            if override is None:
                log.debug(
                    f"{ctx.author} called the '{ctx.command.name}' command "
                    f"and the command was whitelisted to bypass the in_channel check."
                )
                return True
            else:
                if ctx.channel.id in override:
                    log.debug(
                        f"{ctx.author} tried to call the '{ctx.command.name}' command "
                        f"and the command was used in an overridden whitelisted channel."
                    )
                    return True

                log.debug(
                    f"{ctx.author} tried to call the '{ctx.command.name}' command. "
                    f"The overridden in_channel check failed."
                )
                channels_str = ', '.join(f"<#{c_id}>" for c_id in override)
                raise InChannelCheckFailure(
                    f"Sorry, but you may only use this command within {channels_str}."
                )

        log.debug(
            f"{ctx.author} tried to call the '{ctx.command.name}' command. "
            f"The in_channel check failed."
        )

        channels_str = ', '.join(f"<#{c_id}>" for c_id in channels)
        raise InChannelCheckFailure(
            f"Sorry, but you may only use this command within {channels_str}."
        )

    return predicate