本文整理匯總了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()
示例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]))
示例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)
示例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
}
示例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
示例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
示例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 ''
示例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)
示例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
示例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))
示例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)
示例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)
示例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)
示例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
)
示例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}')