本文整理匯總了Python中typing.Generator方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Generator方法的具體用法?Python typing.Generator怎麽用?Python typing.Generator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Generator方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: subscribe
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def subscribe(
self, document: DocumentNode, *args, **kwargs
) -> Generator[Dict, None, None]:
"""Execute a GraphQL subscription with a python generator.
We need an async transport for this functionality.
"""
async_generator = self.subscribe_async(document, *args, **kwargs)
loop = asyncio.get_event_loop()
assert not loop.is_running(), (
"Cannot run client.subscribe if an asyncio loop is running."
" Use subscribe_async instead."
)
try:
while True:
result = loop.run_until_complete(async_generator.__anext__())
yield result
except StopAsyncIteration:
pass
示例2: run_sync_iterable
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def run_sync_iterable(iterable: Generator[Any, None, None]) -> AsyncGenerator[Any, None]:
async def _gen_wrapper() -> AsyncGenerator[Any, None]:
# Wrap the generator such that each iteration runs
# in the executor. Then rationalise the raised
# errors so that it ends.
def _inner() -> Any:
# https://bugs.python.org/issue26221
# StopIteration errors are swallowed by the
# run_in_exector method
try:
return next(iterable)
except StopIteration:
raise StopAsyncIteration()
loop = asyncio.get_running_loop()
while True:
try:
yield await loop.run_in_executor(None, copy_context().run, _inner)
except StopAsyncIteration:
return
return _gen_wrapper()
示例3: _app
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def _app() -> Quart:
app = Quart(__name__)
@app.route("/", methods=["GET", "POST"])
def index() -> ResponseReturnValue:
return request.method
@app.route("/gen")
def gen() -> ResponseReturnValue:
def _gen() -> Generator[bytes, None, None]:
yield b"%d" % threading.current_thread().ident
for _ in range(2):
yield b"b"
return _gen(), 200
return app
示例4: subtitles
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def subtitles(self, comments: Comments) -> Generator[Tuple[str, Comment], None, None]:
"""
Subtitle generator
:param comments: Comments to turn into subtitles
:return: Generator with subtitles and subtitle data
"""
for index, comment in enumerate(comments):
# Stat and stop timestamps. Add a millisecond for timedelta to include millisecond digits
start = datetime.timedelta(seconds=comment.content_offset_seconds)
stop: datetime.timedelta = start + datetime.timedelta(milliseconds=self.format_dictionary['duration'])
# Format message
message: str = Pipe(self.format_dictionary['comments']).comment(comment.data)
# Subtitle variables
# Subtract the last three milliseconds form timestamp (required by SRT)
subtitle: dict = {
'index': index + 1,
'start': SRT.format_timestamp(start),
'stop': SRT.format_timestamp(stop),
'message': message
}
yield '{index}\n{start} --> {stop}\n{message}\n'.format_map(SafeDict(subtitle)), comment
示例5: use
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def use(self, format_name: str) -> Tuple[Generator[Tuple[str, Comment], None, None], str]:
"""
Use format
:param format_name:
:return: tuple(Line, comment), output
"""
if format_name not in Settings().config['formats']:
print('Invalid format name')
exit(1)
if format_name == 'srt':
return SRT(self.video).use()
elif format_name == 'ssa':
return SSA(self.video).use()
else:
return Custom(self.video, format_name).use()
示例6: all_pages
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def all_pages(self, page: Paging) -> Generator[Paging, None, None]:
"""
Retrieve all pages of a paging.
Request and yield new (next) pages until the end of the paging.
The paging that was given as an argument is yielded as the first result.
Parameters
----------
page
paging object
Returns
-------
Generator
all pages within a paging
"""
if self.is_async:
return self._async_all_pages(page)
else:
return self._sync_all_pages(page)
示例7: all_items
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def all_items(
self,
page: Paging
) -> Generator[Model, None, None]:
"""
Retrieve all items from all pages of a paging.
Request and yield new (next) items until the end of the paging.
The items in the paging that was given as an argument are yielded first.
Parameters
----------
page
paging object
Returns
-------
Generator
all items within a paging
"""
if self.is_async:
return self._async_all_items(page)
else:
return self._sync_all_items(page)
示例8: _serialize_openapi3
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def _serialize_openapi3(definitions: DefinitionList) -> Generator[Optional[Callable], None, None]:
"""Different collection styles for Open API 3.0."""
for definition in definitions:
name = definition["name"]
if "content" in definition:
# https://swagger.io/docs/specification/describing-parameters/#schema-vs-content
options = iter(definition["content"].keys())
media_type = next(options, None)
if media_type == "application/json":
yield to_json(name)
else:
# Simple serialization
style = definition.get("style")
explode = definition.get("explode")
type_ = definition.get("schema", {}).get("type")
if definition["in"] == "path":
yield from _serialize_path_openapi3(name, type_, style, explode)
elif definition["in"] == "query":
yield from _serialize_query_openapi3(name, type_, style, explode)
elif definition["in"] == "header":
yield from _serialize_header_openapi3(name, type_, explode)
elif definition["in"] == "cookie":
yield from _serialize_cookie_openapi3(name, type_, explode)
示例9: _serialize_query_openapi3
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def _serialize_query_openapi3(
name: str, type_: str, style: Optional[str], explode: Optional[bool]
) -> Generator[Optional[Callable], None, None]:
if type_ == "object":
if style == "deepObject":
yield deep_object(name)
if style is None or style == "form":
if explode is False:
yield comma_delimited_object(name)
if explode is True:
yield extracted_object(name)
elif type_ == "array" and explode is False:
if style == "pipeDelimited":
yield delimited(name, delimiter="|")
if style == "spaceDelimited":
yield delimited(name, delimiter=" ")
if style is None or style == "form": # "form" is the default style
yield delimited(name, delimiter=",")
示例10: _parse
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def _parse(expr: str) -> Generator[nodes.Node, None, None]:
tokens = lexer.tokenize(expr)
brackets_stack: List[str] = []
for token in tokens:
if token.is_string:
yield nodes.String(token.value)
elif token.is_variable:
yield from _parse_variable(tokens, token, expr)
elif token.is_left_bracket:
if brackets_stack:
raise RuntimeExpressionError("Nested embedded expressions are not allowed")
brackets_stack.append("{")
elif token.is_right_bracket:
if not brackets_stack:
raise RuntimeExpressionError("Unmatched bracket")
brackets_stack.pop()
if brackets_stack:
raise RuntimeExpressionError("Unmatched bracket")
示例11: execute
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def execute(self) -> Generator[events.ExecutionEvent, None, None]:
"""Common logic for all runners."""
results = TestResultSet()
initialized = events.Initialized.from_schema(schema=self.schema)
yield initialized
for event in self._execute(results):
if (
self.exit_first
and isinstance(event, events.AfterExecution)
and event.status in (Status.error, Status.failure)
):
break
yield event
yield events.Finished.from_results(results=results, running_time=time.monotonic() - initialized.start_time)
示例12: _run_tests
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def _run_tests( # pylint: disable=too-many-arguments
self,
maker: Callable,
template: Callable,
settings: hypothesis.settings,
seed: Optional[int],
recursion_level: int = 0,
**kwargs: Any,
) -> Generator[events.ExecutionEvent, None, None]:
"""Run tests and recursively run additional tests."""
if recursion_level > self.stateful_recursion_limit:
return
for endpoint, test in maker(template, settings, seed):
feedback = Feedback(self.stateful, endpoint)
for event in run_test(endpoint, test, feedback=feedback, recursion_level=recursion_level, **kwargs):
yield event
if isinstance(event, events.Interrupted):
return
# Additional tests, generated via the `feedback` instance
yield from self._run_tests(
feedback.get_stateful_tests, template, settings, seed, recursion_level=recursion_level + 1, **kwargs
)
示例13: extract_mustache
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def extract_mustache(fileobj: Any, keywords: List[str], comment_tags: List[str], options: Dict[str, str]) -> Generator:
"""Extract messages from mustache files.
:param fileobj: the file-like object the messages should be extracted
from
:param keywords: a list of keywords (i.e. function names) that should
be recognized as translation functions
:param comment_tags: a list of translator tags to search for and
include in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)``
tuples
:rtype: ``iterator``
"""
source = fileobj.read().decode(options.get('encoding', 'utf-8'))
tree = template.insert_gettext_nodes(pystache.parse(source))
for node in tree._parse_tree:
if isinstance(node, template._GettextNode):
yield 1, None, node.key, []
示例14: config
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def config(): # type: () -> Generator[ApplicationConfig]
config = ApplicationConfig()
config.set_catch_exceptions(False)
config.set_terminate_after_run(False)
config.set_io_factory(
lambda app, args, input_stream, output_stream, error_stream: IO(
Input(input_stream), Output(output_stream), Output(error_stream)
)
)
yield config
示例15: process
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Generator [as 別名]
def process(self, sample: Sample, ops=List['BaseOperation']) -> Generator[Sample, None, None]:
"""Complete a processing step in the pipeline and run the next one.
:param sample: The sample to be processed
:param ops: The next operations to run
:return: A generator yielding samples
The process function is expected to first transform the sample and then to call
the next BaseOperation, yielding the resulting sample as a return value.
"""
raise NotImplementedError