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


Python typing.cast方法代码示例

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


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

示例1: execute

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def execute(
        self, document: DocumentNode, *args, **kwargs,
    ) -> ExecutionResult:
        """Execute the provided document AST for on a local GraphQL Schema.
        """

        result_or_awaitable = execute(self.schema, document, *args, **kwargs)

        execution_result: ExecutionResult

        if isawaitable(result_or_awaitable):
            result_or_awaitable = cast(Awaitable[ExecutionResult], result_or_awaitable)
            execution_result = await result_or_awaitable
        else:
            result_or_awaitable = cast(ExecutionResult, result_or_awaitable)
            execution_result = result_or_awaitable

        return execution_result 
开发者ID:graphql-python,项目名称:gql,代码行数:20,代码来源:local_schema.py

示例2: perform_check

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def perform_check(self, env: env_tools.PreparedEnv, verbose: bool):
        base_path = cast(str, env.destination_directory)
        config_path = os.path.join(base_path,
                                   'dev_tools',
                                   'conf',
                                   'mypy.ini')
        files = list(env_tools.get_unhidden_ungenerated_python_files(
            base_path))

        result = shell_tools.run_cmd(
            env.bin('mypy'),
            '--config-file={}'.format(config_path),
            *files,
            out=shell_tools.TeeCapture(sys.stdout),
            raise_on_fail=False,
            log_run_to_stderr=verbose,
            abbreviate_non_option_arguments=True)

        output = cast(str, result[0])
        passed = result[2] == 0
        if passed:
            return True, 'Types look good!'
        issue_count = len([e for e in output.split('\n') if e.strip()])

        return False, '{} issues'.format(issue_count) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:27,代码来源:check_typecheck.py

示例3: optimize

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def optimize(self,
                 black_box: BlackBox,
                 initial_guess: Optional[numpy.ndarray]=None,
                 initial_guess_array: Optional[numpy.ndarray]=None
                 ) -> OptimizationResult:
        opt = numpy.inf
        opt_params = None
        for _ in range(5):
            guess = numpy.random.randn(black_box.dimension)
            val = black_box.evaluate(guess)
            if val < opt:
                opt = val
                opt_params = guess
        return OptimizationResult(
                optimal_value=opt,
                optimal_parameters=cast(numpy.ndarray, opt_params),
                num_evaluations=1,
                cost_spent=0.0,
                status=0,
                message='success') 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:22,代码来源:example_classes.py

示例4: test_copy_current_websocket_context

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def test_copy_current_websocket_context() -> None:
    app = Quart(__name__)

    @app.websocket("/")
    async def index() -> None:
        @copy_current_websocket_context
        async def within_context() -> None:
            return websocket.path

        data = await asyncio.ensure_future(within_context())
        await websocket.send(data.encode())

    test_client = app.test_client()
    async with test_client.websocket("/") as test_websocket:
        data = await test_websocket.receive()
    assert cast(bytes, data) == b"/" 
开发者ID:pgjones,项目名称:quart,代码行数:18,代码来源:test_ctx.py

示例5: get_tests

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def get_tests(self, run_id: Id, status_ids: Union[str, Sequence[int]] = None) -> JsonList:
        """Get tests from TestRail test run by run_id.

        *Args:* \n
            _run_id_ - ID of the test run;\n
            _status_ids_ - list of the required test statuses.

        *Returns:* \n
            Tests information in json format.
        """
        uri = 'get_tests/{run_id}'.format(run_id=run_id)
        if status_ids:
            status_ids = ','.join(str(status_id) for status_id in status_ids)
        params = {
            'status_id': status_ids
        }
        response = self._send_get(uri=uri, headers=DEFAULT_TESTRAIL_HEADERS, params=params)
        return cast(JsonList, response) 
开发者ID:peterservice-rnd,项目名称:robotframework-testrail,代码行数:20,代码来源:TestRailAPIClient.py

示例6: get_results_for_case

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def get_results_for_case(self, run_id: Id, case_id: Id, limit: int = None) -> JsonList:
        """Get results for case by run_id and case_id.

        *Args:* \n
            _run_id_ - ID of the test run;\n
            _case_id_ - ID of the test case;\n
            _limit_ - limit of case results.

        *Returns:* \n
            Cases results in json format.
        """
        uri = 'get_results_for_case/{run_id}/{case_id}'.format(run_id=run_id, case_id=case_id)
        params = {
            'limit': limit
        }
        response = self._send_get(uri=uri, headers=DEFAULT_TESTRAIL_HEADERS, params=params)
        return cast(JsonList, response) 
开发者ID:peterservice-rnd,项目名称:robotframework-testrail,代码行数:19,代码来源:TestRailAPIClient.py

示例7: add_section

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def add_section(self, project_id: Id, name: str, suite_id: Id = None, parent_id: Id = None,
                    description: str = None) -> JsonDict:
        """Creates a new section.

        *Args:* \n
            _project_id_ - ID of the project;\n
            _name_ - name of the section;\n
            _suite_id_ - ID of the test suite(ignored if the project is operating in single suite mode);\n
            _parent_id_ - ID of the parent section (to build section hierarchies);\n
            _description_ - description of the section.

        *Returns:* \n
            New section information.
        """
        uri = 'add_section/{project_id}'.format(project_id=project_id)
        data: Dict[str, Union[int, str]] = {'name': name}
        if suite_id is not None:
            data['suite_id'] = suite_id
        if parent_id is not None:
            data['parent_id'] = parent_id
        if description is not None:
            data['description'] = description

        response = self._send_post(uri=uri, data=data)
        return cast(JsonDict, response) 
开发者ID:peterservice-rnd,项目名称:robotframework-testrail,代码行数:27,代码来源:TestRailAPIClient.py

示例8: get_cases

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def get_cases(self, project_id: Id, suite_id: Id = None, section_id: Id = None) -> JsonList:
        """Returns a list of test cases for a test suite or specific section in a test suite.

        *Args:* \n
            _project_id_ - ID of the project;\n
            _suite_id_ - ID of the test suite (optional if the project is operating in single suite mode);\n
            _section_id_ - ID of the section (optional).

        *Returns:* \n
            Information about test cases in section.
        """
        uri = 'get_cases/{project_id}'.format(project_id=project_id)
        params = {'project_id': project_id}
        if suite_id is not None:
            params['suite_id'] = suite_id
        if section_id is not None:
            params['section_id'] = section_id

        response = self._send_get(uri=uri, headers=DEFAULT_TESTRAIL_HEADERS, params=params)
        return cast(JsonList, response) 
开发者ID:peterservice-rnd,项目名称:robotframework-testrail,代码行数:22,代码来源:TestRailAPIClient.py

示例9: create

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def create(
        server_info: ServerConnectivityInfo = ServerConnectivityInfoFactory.create(),
        scan_commands_results: Optional[ScanCommandResultsDict] = None,
        scan_commands_errors: Optional[ScanCommandErrorsDict] = None,
    ) -> ServerScanResult:
        final_results: ScanCommandResultsDict = (
            scan_commands_results
            if scan_commands_results
            else {ScanCommand.TLS_COMPRESSION: CompressionScanResult(supports_compression=True)}
        )
        final_errors: ScanCommandErrorsDict = scan_commands_errors if scan_commands_errors else {}
        scan_commands: Set[ScanCommandType] = set()
        for scan_cmd in final_results.keys():
            typed_scan_cmd = cast(ScanCommandType, scan_cmd)
            scan_commands.add(typed_scan_cmd)
        for scan_cmd in final_errors.keys():
            scan_commands.add(scan_cmd)

        return ServerScanResult(
            scan_commands_results=final_results,
            scan_commands_errors=final_errors,
            server_info=server_info,
            scan_commands=scan_commands,
            scan_commands_extra_arguments={},
        ) 
开发者ID:nabla-c0d3,项目名称:sslyze,代码行数:27,代码来源:factories.py

示例10: extract_dns_subject_alternative_names

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def extract_dns_subject_alternative_names(certificate: x509.Certificate) -> List[str]:
    """Retrieve all the DNS entries of the Subject Alternative Name extension.
    """
    subj_alt_names: List[str] = []
    try:
        san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
        san_ext_value = cast(x509.SubjectAlternativeName, san_ext.value)
        subj_alt_names = san_ext_value.get_values_for_type(DNSName)
    except ExtensionNotFound:
        pass
    except DuplicateExtension:
        # Fix for https://github.com/nabla-c0d3/sslyze/issues/420
        # Not sure how browsers behave in this case but having a duplicate extension makes the certificate invalid
        # so we just return no SANs (likely to make hostname validation fail, which is fine)
        pass

    return subj_alt_names 
开发者ID:nabla-c0d3,项目名称:sslyze,代码行数:19,代码来源:_certificate_utils.py

示例11: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def __init__(self,
                 team_type: Type['Team'],
                 identifier: Union[Hashable, str, int],  # workaround mypy bug
                 access_token=None) -> None:
        if not isinstance(team_type, type):
            raise TypeError('team_type must be a type, not ' + repr(team_type))
        from .team import Team  # noqa: F811
        if not issubclass(team_type, Team):
            raise TypeError('team_type must be a subclass of {0.__module__}.'
                            '{0.__qualname__}'.format(Team))
        elif not callable(getattr(identifier, '__hash__')):
            raise TypeError('identifier must be hashable, not ' +
                            repr(identifier))
        self.team_type = cast(Type[Team], team_type)
        self.identifier = identifier  # type: Union[Hashable, str, int]
        self.access_token = access_token 
开发者ID:spoqa,项目名称:geofront,代码行数:18,代码来源:identity.py

示例12: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def __init__(self, db_module: types.ModuleType, *args, **kwargs) -> None:
        if not callable(getattr(db_module, 'connect', None)):
            module_name = db_module.__name__
            raise TypeError('db_module must be DB-API 2.0 compliant, but {} '
                            'lacks connect() function'.format(module_name))
        elif not isinstance(getattr(db_module, 'IntegrityError', None),
                            type):
            raise TypeError('db_module must be DB-API 2.0 compliant, but {} '
                            'lacks IntegrityError'.format(module_name))
        integrity_error = db_module.IntegrityError  # type: ignore
        if not issubclass(integrity_error, Exception):
            raise TypeError(
                'db_module must be DB-API 2.0 compliant, but {}.'
                'IntegrityError is not an exception class'.format(module_name)
            )
        self.db_module = db_module
        self.integrity_error = cast(Type[Exception], integrity_error)
        self.connection_args = args
        self.connection_kwargs = kwargs 
开发者ID:spoqa,项目名称:geofront,代码行数:21,代码来源:dbapi.py

示例13: request_list

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def request_list(
        self, identity: Identity
    ) -> Iterator[Sequence[Mapping[str, object]]]:
        team = self.team
        if not (isinstance(team, identity.team_type) and
                cast(str, identity.identifier).startswith(team.server_url)):
            return
        start = 0
        while True:
            response = self.request(
                identity,
                'GET',
                self.LIST_URL.format(self.team, start)
            )
            assert response.code == 200
            payload = json.load(io.TextIOWrapper(response, encoding='utf-8'))
            response.close()
            yield from payload['values']
            if payload['isLastPage']:
                break
            start = payload['nextPageStart'] 
开发者ID:spoqa,项目名称:geofront,代码行数:23,代码来源:stash.py

示例14: register

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def register(self, identity: Identity, public_key: PKey) -> None:
        team = self.team
        if not (isinstance(team, identity.team_type) and
                cast(str, identity.identifier).startswith(team.server_url)):
            return
        data = json.dumps({
            'text': format_openssh_pubkey(public_key)
        })
        try:
            self.request(
                identity, 'POST', self.REGISTER_URL.format(self.team), data,
                headers={'Content-Type': 'application/json'}
            )
        except urllib.error.HTTPError as e:
            if e.code == 409:
                errors = json.loads(e.read().decode('utf-8'))['errors']
                raise DuplicatePublicKeyError(errors[0]['message'])
            raise 
开发者ID:spoqa,项目名称:geofront,代码行数:20,代码来源:stash.py

示例15: from_prepared_request

# 需要导入模块: import typing [as 别名]
# 或者: from typing import cast [as 别名]
def from_prepared_request(cls, prepared: requests.PreparedRequest) -> "Request":
        """A prepared request version is already stored in `requests.Response`."""
        body = prepared.body or b""

        if isinstance(body, str):
            # can be a string for `application/x-www-form-urlencoded`
            body = body.encode("utf-8")

        # these values have `str` type at this point
        uri = cast(str, prepared.url)
        method = cast(str, prepared.method)
        return cls(
            uri=uri,
            method=method,
            headers={key: [value] for (key, value) in prepared.headers.items()},
            body=base64.b64encode(body).decode(),
        ) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:19,代码来源:models.py


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