本文整理汇总了Python中collections.abc.Generator方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Generator方法的具体用法?Python abc.Generator怎么用?Python abc.Generator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Generator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def __init__(self, methodName: str = "runTest") -> None:
super(AsyncTestCase, self).__init__(methodName)
self.__stopped = False
self.__running = False
self.__failure = None # type: Optional[_ExcInfoTuple]
self.__stop_args = None # type: Any
self.__timeout = None # type: Optional[object]
# It's easy to forget the @gen_test decorator, but if you do
# the test will silently be ignored because nothing will consume
# the generator. Replace the test method with a wrapper that will
# make sure it's not an undecorated generator.
setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))
# Not used in this class itself, but used by @gen_test
self._test_generator = None # type: Optional[Union[Generator, Coroutine]]
示例2: map_add_data
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def map_add_data(_map, data, *args, **kwargs):
if any(isinstance(data, c) for c in (Airspace, Flight, Traffic)):
layer = data.kepler()
return _old_add_data(_map, layer, *args, **kwargs)
if any(isinstance(data, c) for c in (list, Generator)):
layer = dict(
type="FeatureCollection", features=[elt.kepler() for elt in data]
)
return _old_add_data(_map, layer, *args, **kwargs)
# convenient for airports, navaids, etc.
if hasattr(data, "data"):
data = data.data
return _old_add_data(_map, data, *args, **kwargs)
示例3: parse_module_post_hook
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def parse_module_post_hook(self, module, tokens: abc.Generator):
"""This function is meant to be overridden by subclasses
that may want to perform some extra processing if
'normal' parse_module() operations fail to complete.
See OmniParser for an example.
This function shall return a two-tuple, with the first item
being the *module* (altered by processing or unaltered), and
the second item being a boolean that will signal whether
the tokens should continue to be parsed to accumulate more
elements into the returned *module*, or whether the
*module* is in a good state and should be returned by
parse_module().
If the operations within this function are unsuccessful,
it should raise an exception (any exception descended from
Exception), which will result in the operation of parse_module()
as if it were not overridden.
"""
raise Exception
示例4: parse_around_equals
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def parse_around_equals(self, tokens: abc.Generator) -> None:
"""Parses white space and comments on either side
of an equals sign.
*tokens* is expected to be a *generator iterator* which
provides ``pvl.token`` objects.
This is shared functionality for Begin Aggregation Statements
and Assignment Statements. It basically covers parsing
anything that has a syntax diagram like this:
<WSC>* '=' <WSC>*
"""
if not self.parse_WSC_until('=', tokens):
try:
t = next(tokens)
tokens.send(t)
raise ValueError(f'Expecting "=", got: {t}')
except StopIteration:
raise ParseError('Expecting "=", but ran out of tokens.')
self.parse_WSC_until(None, tokens)
return
示例5: parse_WSC_until
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def parse_WSC_until(self, token: str, tokens: abc.Generator) -> bool:
"""Consumes objects from *tokens*, if the object's *.is_WSC()*
function returns *True*, it will continue until *token* is
encountered and will return *True*. If it encounters an object
that does not meet these conditions, it will 'return' that
object to *tokens* and will return *False*.
*tokens* is expected to be a *generator iterator* which
provides ``pvl.token`` objects.
"""
for t in tokens:
if t == token:
return True
elif t.is_WSC():
# If there's a comment, could parse here.
pass
else:
tokens.send(t)
return False
示例6: parse_set
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def parse_set(self, tokens: abc.Generator) -> set:
"""Parses a PVL Set.
<Set> ::= "{" <WSC>*
[ <Value> <WSC>* ( "," <WSC>* <Value> <WSC>* )* ]
"}"
Returns the decoded <Set> as a Python ``frozenset``. The PVL
specification doesn't seem to indicate that a PVL Set
has distinct values (like a Python ``set``), only that the
ordering of the values is unimportant. For now, we will
implement PVL Sets as Python ``frozenset`` objects.
They are returned as ``frozenset`` objects because PVL Sets
can contain as their elements other PVL Sets, but since Python
``set`` objects are non-hashable, they cannot be members of a set,
however, ``frozenset`` objects can.
"""
return frozenset(self._parse_set_seq(self.grammar.set_delimiters,
tokens))
示例7: parse_value_post_hook
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def parse_value_post_hook(self, tokens: abc.Generator):
"""Overrides the parent function to allow for more
permissive parsing.
If the next token is a reserved word or delimiter,
then it is returned to the *tokens* and an
EmptyValueAtLine object is returned as the value.
"""
t = next(tokens)
# print(f't: {t}')
truecase_reserved = [x.casefold() for x in
self.grammar.reserved_keywords]
trucase_delim = [x.casefold() for x in
self.grammar.delimiters]
if t.casefold() in (truecase_reserved + trucase_delim):
# print(f'kw: {kw}')
# if kw.casefold() == t.casefold():
# print('match')
tokens.send(t)
return self._empty_value(t.pos)
else:
raise ValueError
示例8: test_returns_windowed_data_lazily
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def test_returns_windowed_data_lazily(self):
from collections.abc import Generator
result = lineflow.window(self.data, self.window_size, lazy=True)
self.assertIsInstance(result, Generator)
for x, y in zip(result, self.expected):
self.assertTupleEqual(x, y)
示例9: __init__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def __init__(
self,
indent_step=4,
indent_char=' ',
repr_strings=False,
simple_cutoff=10,
width=120,
yield_from_generators=True,
):
self._indent_step = indent_step
self._c = indent_char
self._repr_strings = repr_strings
self._repr_generators = not yield_from_generators
self._simple_cutoff = simple_cutoff
self._width = width
self._type_lookup = [
(dict, self._format_dict),
((str, bytes), self._format_str_bytes),
(tuple, self._format_tuples),
((list, set, frozenset), self._format_list_like),
(Generator, self._format_generators),
]
示例10: _format
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def _format(self, value: 'Any', indent_current: int, indent_first: bool):
if indent_first:
self._stream.write(indent_current * self._c)
try:
pretty_func = getattr(value, '__pretty__')
except AttributeError:
pass
else:
# `pretty_func.__class__.__name__ == 'method'` should only be true for bound methods,
# `hasattr(pretty_func, '__self__')` is more canonical but weirdly is true for unbound cython functions
from unittest.mock import _Call as MockCall
if pretty_func.__class__.__name__ == 'method' and not isinstance(value, MockCall):
try:
gen = pretty_func(fmt=fmt, skip_exc=SkipPretty)
self._render_pretty(gen, indent_current)
except SkipPretty:
pass
else:
return
value_repr = repr(value)
if len(value_repr) <= self._simple_cutoff and not isinstance(value, Generator):
self._stream.write(value_repr)
else:
indent_new = indent_current + self._indent_step
for t, func in self._type_lookup:
if isinstance(value, t):
func(value, value_repr, indent_current, indent_new)
return
# very blunt check for things that look like dictionaries but do not necessarily inherit from Mapping
# e.g. asyncpg Records
# HELP: are there any other checks we should include here?
if hasattr(value, '__getitem__') and hasattr(value, 'items') and callable(value.items):
self._format_dict(value, value_repr, indent_current, indent_new)
return
self._format_raw(value, value_repr, indent_current, indent_new)
示例11: _format_generators
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def _format_generators(self, value: Generator, value_repr: str, indent_current: int, indent_new: int):
if self._repr_generators:
self._stream.write(value_repr)
else:
self._stream.write('(\n')
for v in value:
self._format(v, indent_new, True)
self._stream.write(',\n')
self._stream.write(indent_current * self._c + ')')
示例12: __init__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def __init__(
self,
gen: "Generator[_Yieldable, Any, _T]",
result_future: "Future[_T]",
first_yielded: _Yieldable,
) -> None:
self.gen = gen
self.result_future = result_future
self.future = _null_future # type: Union[None, Future]
self.running = False
self.finished = False
self.io_loop = IOLoop.current()
if self.handle_yield(first_yielded):
gen = result_future = first_yielded = None # type: ignore
self.run()
示例13: __call__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def __call__(self, *args: Any, **kwargs: Any) -> None:
result = self.orig_method(*args, **kwargs)
if isinstance(result, Generator) or inspect.iscoroutine(result):
raise TypeError(
"Generator and coroutine test methods should be"
" decorated with tornado.testing.gen_test"
)
elif result is not None:
raise ValueError("Return value from test method ignored: %r" % result)
示例14: gen_test
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def gen_test(
*, timeout: float = None
) -> Callable[[Callable[..., Union[Generator, "Coroutine"]]], Callable[..., None]]:
pass
示例15: __new__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Generator [as 别名]
def __new__(cls, *args, **kwds):
if _geqv(cls, Dict):
raise TypeError("Type Dict cannot be instantiated; "
"use dict() instead")
return dict.__new__(cls, *args, **kwds)
# Determine what base class to use for Generator.