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