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


Python typing.Generator方法代码示例

本文整理汇总了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 
开发者ID:graphql-python,项目名称:gql,代码行数:26,代码来源:client.py

示例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() 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:utils.py

示例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 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:test_sync.py

示例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 
开发者ID:PetterKraabol,项目名称:Twitch-Chat-Downloader,代码行数:26,代码来源:srt.py

示例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() 
开发者ID:PetterKraabol,项目名称:Twitch-Chat-Downloader,代码行数:18,代码来源:formatter.py

示例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) 
开发者ID:felix-hilden,项目名称:tekore,代码行数:23,代码来源:paging.py

示例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) 
开发者ID:felix-hilden,项目名称:tekore,代码行数:26,代码来源:paging.py

示例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) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:25,代码来源:serialization.py

示例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=",") 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:20,代码来源:serialization.py

示例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") 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:20,代码来源:parser.py

示例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) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:19,代码来源:core.py

示例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
            ) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:24,代码来源:core.py

示例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, [] 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:21,代码来源:generate_translations.py

示例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 
开发者ID:sdispater,项目名称:clikit,代码行数:13,代码来源:test_console_aplication.py

示例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 
开发者ID:mme,项目名称:vergeml,代码行数:14,代码来源:operation.py


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