Python typing.cast() Examples
The following are 30
code examples of typing.cast().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: webelem.py From qutebrowser with GNU General Public License v3.0 | 8 votes |
def _click_fake_event(self, click_target: usertypes.ClickTarget, button: Qt.MouseButton = Qt.LeftButton) -> None: """Send a fake click event to the element.""" pos = self._mouse_pos() log.webelem.debug("Sending fake click to {!r} at position {} with " "target {}".format(self, pos, click_target)) target_modifiers = { usertypes.ClickTarget.normal: Qt.NoModifier, usertypes.ClickTarget.window: Qt.AltModifier | Qt.ShiftModifier, usertypes.ClickTarget.tab: Qt.ControlModifier, usertypes.ClickTarget.tab_bg: Qt.ControlModifier, } if config.val.tabs.background: target_modifiers[usertypes.ClickTarget.tab] |= Qt.ShiftModifier else: target_modifiers[usertypes.ClickTarget.tab_bg] |= Qt.ShiftModifier modifiers = typing.cast(Qt.KeyboardModifiers, target_modifiers[click_target]) events = [ QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton, Qt.NoModifier), QMouseEvent(QEvent.MouseButtonPress, pos, button, button, modifiers), QMouseEvent(QEvent.MouseButtonRelease, pos, button, Qt.NoButton, modifiers), ] for evt in events: self._tab.send_event(evt) QTimer.singleShot(0, self._move_text_cursor)
Example #2
Source File: hooks.py From schemathesis with MIT License | 6 votes |
def register(self, hook: Union[str, Callable]) -> Callable: """Register a new hook. Can be used as a decorator in two forms. Without arguments for registering hooks and autodetecting their names: @schema.hooks.register def before_generate_query(strategy, context): ... With a hook name as the first argument: @schema.hooks.register("before_generate_query") def hook(strategy, context): ... """ if isinstance(hook, str): def decorator(func: Callable) -> Callable: hook_name = cast(str, hook) return self.register_hook_with_name(func, hook_name) return decorator return self.register_hook_with_name(hook, hook.__name__)
Example #3
Source File: TestRailAPIClient.py From robotframework-testrail with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: TestRailAPIClient.py From robotframework-testrail with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: dbapi.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
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
Example #6
Source File: stash.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
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']
Example #7
Source File: test_ctx.py From quart with MIT License | 6 votes |
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"/"
Example #8
Source File: stash.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
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
Example #9
Source File: identity.py From geofront with GNU Affero General Public License v3.0 | 6 votes |
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
Example #10
Source File: models.py From schemathesis with MIT License | 6 votes |
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(), )
Example #11
Source File: example_classes.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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')
Example #12
Source File: _certificate_utils.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
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
Example #13
Source File: TestRailAPIClient.py From robotframework-testrail with Apache License 2.0 | 6 votes |
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)
Example #14
Source File: factories.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
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={}, )
Example #15
Source File: TestRailAPIClient.py From robotframework-testrail with Apache License 2.0 | 6 votes |
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)
Example #16
Source File: check_typecheck.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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)
Example #17
Source File: default.py From schemathesis with MIT License | 5 votes |
def display_percentage(context: ExecutionContext, event: events.AfterExecution) -> None: """Add the current progress in % to the right side of the current line.""" padding = 1 endpoints_count = cast(int, context.endpoints_count) # is already initialized via `Initialized` event current_percentage = get_percentage(context.endpoints_processed, endpoints_count) styled = click.style(current_percentage, fg="cyan") # Total length of the message so it will fill to the right border of the terminal minus padding length = get_terminal_width() - context.current_line_length + len(styled) - len(current_percentage) - padding template = f"{{:>{length}}}" click.echo(template.format(styled))
Example #18
Source File: inspector.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, splitter: 'miscwidgets.InspectorSplitter', win_id: int, parent: QWidget = None) -> None: super().__init__(parent) self._widget = typing.cast(QWidget, None) self._layout = miscwidgets.WrapperLayout(self) self._splitter = splitter self._position = None # type: typing.Optional[Position] self._event_filter = _EventFilter(win_id, parent=self) self._child_event_filter = eventfilter.ChildEventFilter( eventfilter=self._event_filter, win_id=win_id, parent=self)
Example #19
Source File: tabwidget.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def setTabIcon(self, idx: int, icon: QIcon) -> None: """Always show tab icons for pinned tabs in some circumstances.""" tab = typing.cast(typing.Optional[browsertab.AbstractTab], self.widget(idx)) if (icon.isNull() and config.cache['tabs.favicons.show'] != 'never' and config.cache['tabs.pinned.shrink'] and not self.tabBar().vertical and tab is not None and tab.data.pinned): icon = self.style().standardIcon(QStyle.SP_FileIcon) super().setTabIcon(idx, icon)
Example #20
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab') -> None: self._widget = typing.cast(QWidget, None) self._tab = tab
Example #21
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, *, win_id: int, mode_manager: modeman.ModeManager, private: bool, parent: QWidget = None) -> None: utils.unused(mode_manager) # needed for mypy self.is_private = private self.win_id = win_id self.tab_id = next(tab_id_gen) super().__init__(parent) self.registry = objreg.ObjectRegistry() tab_registry = objreg.get('tab-registry', scope='window', window=win_id) tab_registry[self.tab_id] = self objreg.register('tab', self, registry=self.registry) self.data = TabData() self._layout = miscwidgets.WrapperLayout(self) self._widget = typing.cast(QWidget, None) self._progress = 0 self._load_status = usertypes.LoadStatus.none self._tab_event_filter = eventfilter.TabEventFilter( self, parent=self) self.backend = None # type: typing.Optional[usertypes.Backend] # If true, this tab has been requested to be removed (or is removed). self.pending_removal = False self.shutting_down.connect(functools.partial( setattr, self, 'pending_removal', True)) self.before_load_started.connect(self._on_before_load_started)
Example #22
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, mode_manager: modeman.ModeManager, tab: 'AbstractTab') -> None: self._widget = typing.cast(QWidget, None) self._tab = tab self._mode_manager = mode_manager
Example #23
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab', parent: QWidget = None) -> None: super().__init__(parent) self._widget = typing.cast(QWidget, None) self._tab = tab
Example #24
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self) -> None: self._widget = typing.cast(QWidget, None) # self._tab is set by subclasses so mypy knows its concrete type.
Example #25
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab'): self._tab = tab self._history = typing.cast( typing.Union['QWebHistory', 'QWebEngineHistory'], None)
Example #26
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab', parent: QWidget = None): super().__init__(parent) self._tab = tab self._widget = typing.cast(QWidget, None) if 'log-scroll-pos' in objects.debug_flags: self.perc_changed.connect(self._log_scroll_pos_change)
Example #27
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, mode_manager: modeman.ModeManager, parent: QWidget = None) -> None: super().__init__(parent) self._widget = typing.cast(QWidget, None) self._mode_manager = mode_manager mode_manager.entered.connect(self._on_mode_entered) mode_manager.left.connect(self._on_mode_left) # self._tab is set by subclasses so mypy knows its concrete type.
Example #28
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab', parent: QWidget = None) -> None: super().__init__(parent) self._tab = tab self._widget = typing.cast(QWidget, None) # Whether zoom was changed from the default. self._default_zoom_changed = False self._init_neighborlist() config.instance.changed.connect(self._on_config_changed) self._zoom_factor = float(config.val.zoom.default) / 100
Example #29
Source File: browsertab.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, tab: 'AbstractTab', parent: QWidget = None): super().__init__(parent) self._tab = tab self._widget = typing.cast(QWidget, None) self.text = None # type: typing.Optional[str] self.search_displayed = False
Example #30
Source File: webpage.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def _on_feature_permission_requested(self, frame, feature): """Ask the user for approval for geolocation/notifications.""" if not isinstance(frame, QWebFrame): # pragma: no cover # This makes no sense whatsoever, but someone reported this being # called with a QBuffer... log.misc.error("on_feature_permission_requested got called with " "{!r}!".format(frame)) return options = { QWebPage.Notifications: 'content.notifications', QWebPage.Geolocation: 'content.geolocation', } messages = { QWebPage.Notifications: 'show notifications', QWebPage.Geolocation: 'access your location', } yes_action = functools.partial( self.setFeaturePermission, frame, feature, QWebPage.PermissionGrantedByUser) no_action = functools.partial( self.setFeaturePermission, frame, feature, QWebPage.PermissionDeniedByUser) url = frame.url().adjusted(typing.cast(QUrl.FormattingOptions, QUrl.RemoveUserInfo | QUrl.RemovePath | QUrl.RemoveQuery | QUrl.RemoveFragment)) question = shared.feature_permission( url=url, option=options[feature], msg=messages[feature], yes_action=yes_action, no_action=no_action, abort_on=[self.shutting_down, self.loadStarted]) if question is not None: self.featurePermissionRequestCanceled.connect( # type: ignore functools.partial(self._on_feature_permission_cancelled, question, frame, feature))