当前位置: 首页>>代码示例>>Python>>正文


Python typing.Container方法代码示例

本文整理汇总了Python中typing.Container方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Container方法的具体用法?Python typing.Container怎么用?Python typing.Container使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.Container方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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() 
开发者ID:kata-ai,项目名称:indosum,代码行数:26,代码来源:data.py

示例2: data_vstack

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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])) 
开发者ID:modAL-python,项目名称:modAL,代码行数:23,代码来源:data.py

示例3: test_subclassing_register

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:20,代码来源:test_typing.py

示例4: bases

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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
        } 
开发者ID:pygae,项目名称:clifford,代码行数:19,代码来源:_layout.py

示例5: sqlalchemy_to_pydantic

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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 
开发者ID:CTFd,项目名称:CTFd,代码行数:26,代码来源:schemas.py

示例6: check

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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 
开发者ID:prechelt,项目名称:typecheck-decorator,代码行数:22,代码来源:typing_predicates.py

示例7: given_function_called

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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 '' 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:19,代码来源:functions.py

示例8: test_bogoliubov_transform_fourier_transform

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:17,代码来源:bogoliubov_transform_test.py

示例9: _get_name_for_position

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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 
开发者ID:HPAC,项目名称:matchpy,代码行数:10,代码来源:many_to_one.py

示例10: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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)) 
开发者ID:python-discord,项目名称:bot,代码行数:7,代码来源:scheduler.py

示例11: reschedule_infractions

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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) 
开发者ID:python-discord,项目名称:bot,代码行数:15,代码来源:scheduler.py

示例12: in_whitelist

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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) 
开发者ID:python-discord,项目名称:bot,代码行数:28,代码来源:decorators.py

示例13: chk_mkdir

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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) 
开发者ID:cosmic-cortex,项目名称:pytorch-UNet,代码行数:12,代码来源:utils.py

示例14: _is_six

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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
        ) 
开发者ID:asottile,项目名称:pyupgrade,代码行数:13,代码来源:pyupgrade.py

示例15: assert_in

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Container [as 别名]
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}') 
开发者ID:dcs4cop,项目名称:xcube,代码行数:5,代码来源:assertions.py


注:本文中的typing.Container方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。