Python typing.MutableSequence() Examples
The following are 30
code examples of typing.MutableSequence().
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: memoryfs.py From pyfilesystem2 with MIT License | 6 votes |
def __init__(self, resource_type, name): # type: (ResourceType, Text) -> None self.resource_type = resource_type self.name = name self._dir = OrderedDict() # type: typing.MutableMapping[Text, _DirEntry] self._open_files = [] # type: typing.MutableSequence[_MemoryFile] self._bytes_file = None # type: Optional[io.BytesIO] self.lock = RLock() current_time = time.time() self.created_time = current_time self.accessed_time = current_time self.modified_time = current_time if not self.is_dir: self._bytes_file = io.BytesIO()
Example #2
Source File: main.py From cwl-tes with Apache License 2.0 | 6 votes |
def set_secondary(typedef, fileobj, discovered): """ Pull over missing secondaryFiles to the job object entry. Adapted from: https://github.com/curoverse/arvados/blob/2b0b06579199967eca3d44d955ad64195d2db3c3/sdk/cwl/arvados_cwl/runner.py#L67 """ if isinstance(fileobj, MutableMapping) and fileobj.get("class") == "File": if "secondaryFiles" not in fileobj: fileobj["secondaryFiles"] = cmap( [{"location": substitute(fileobj["location"], sf["pattern"]), "class": "File"} for sf in typedef["secondaryFiles"]]) if discovered is not None: discovered[fileobj["location"]] = fileobj["secondaryFiles"] elif isinstance(fileobj, MutableSequence): for entry in fileobj: set_secondary(typedef, entry, discovered)
Example #3
Source File: messageview.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def __init__(self, parent=None): super().__init__(parent) self._messages = [] # type: typing.MutableSequence[Message] self._vbox = QVBoxLayout(self) self._vbox.setContentsMargins(0, 0, 0, 0) self._vbox.setSpacing(0) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self._clear_timer = QTimer() self._clear_timer.timeout.connect(self.clear_messages) config.instance.changed.connect(self._set_clear_timer_interval) self._last_text = None
Example #4
Source File: main.py From cwl-tes with Apache License 2.0 | 6 votes |
def find_defaults(item, operation): """ Find instances of a default field and apply the given operation. Adapted from: https://github.com/curoverse/arvados/blob/2b0b06579199967eca3d44d955ad64195d2db3c3/sdk/cwl/arvados_cwl/runner.py#L56 """ if isinstance(item, MutableSequence): for entry in item: find_defaults(entry, operation) elif isinstance(item, MutableMapping): if "default" in item: operation(item) else: for entry in itervalues(item): find_defaults(entry, operation)
Example #5
Source File: _cell.py From wikitextparser with GNU General Public License v3.0 | 6 votes |
def __init__( self, string: Union[str, MutableSequence[str]], header: bool = False, _type_to_spans: Dict[str, List[List[int]]] = None, _span: int = None, _type: int = None, _match: Match = None, _attrs_match: Match = None, ) -> None: """Initialize the object.""" super().__init__(string, _type_to_spans, _span, _type) self._header = header if _match: string = self.string self._match_cache = _match, string if _attrs_match: self._attrs_match_cache = _attrs_match, string else: self._attrs_match_cache = \ ATTRS_MATCH(_match['attrs']), string else: self._attrs_match_cache = self._match_cache = None, None
Example #6
Source File: _wikilist.py From wikitextparser with GNU General Public License v3.0 | 6 votes |
def __init__( self, string: Union[str, MutableSequence[str]], pattern: str, _match: Match = None, _type_to_spans: Dict[str, List[List[int]]] = None, _span: List[int] = None, _type: str = None, ) -> None: super().__init__(string, _type_to_spans, _span, _type) self.pattern = pattern if _match: self._match_cache = _match, self.string else: self._match_cache = fullmatch( LIST_PATTERN_FORMAT.replace( b'{pattern}', pattern.encode(), 1), self._shadow, MULTILINE, ), self.string
Example #7
Source File: cmdhistory.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def start(self, text): """Start browsing to the history. Called when the user presses the up/down key and wasn't browsing the history already. Args: text: The preset text. """ log.misc.debug("Preset text: '{}'".format(text)) if text: items = [ e for e in self.history if e.startswith(text)] # type: typing.MutableSequence[str] else: items = self.history if not items: raise HistoryEmptyError self._tmphist = usertypes.NeighborList(items) return self._tmphist.lastitem()
Example #8
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_collections_as_base(self): class M(collections.Mapping): ... self.assertIsSubclass(M, typing.Mapping) self.assertIsSubclass(M, typing.Iterable) class S(collections.MutableSequence): ... self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) class I(collections.Iterable): ... self.assertIsSubclass(I, typing.Iterable) class A(collections.Mapping, metaclass=abc.ABCMeta): ... class B: ... A.register(B) self.assertIsSubclass(B, typing.Mapping)
Example #9
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def run_tests(argv, args, kwargs): # pylint: disable=line-too-long # type: (MutableSequence[Text], Sequence[Any], MutableMapping[Text, Any]) -> None # pylint: enable=line-too-long """Executes a set of Python unit tests. Most users should call absltest.main() instead of run_tests. Please note that run_tests should be called from app.run. Calling absltest.main() would ensure that. Please note that run_tests is allowed to make changes to kwargs. Args: argv: sys.argv with the command-line flags removed from the front, i.e. the argv with which app.run() has called __main__.main. args: Positional arguments passed through to unittest.TestProgram.__init__. kwargs: Keyword arguments passed through to unittest.TestProgram.__init__. """ result = _run_and_get_tests_result( argv, args, kwargs, xml_reporter.TextAndXMLTestRunner) sys.exit(not result.wasSuccessful())
Example #10
Source File: addresses.py From IOTA_demo with MIT License | 6 votes |
def address_from_digest(digest): # type: (Digest) -> Address """ Generates an address from a private key digest. """ address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: MutableSequence[int] sponge = Kerl() sponge.absorb(digest.as_trits()) sponge.squeeze(address_trits) return Address.from_trits( trits = address_trits, key_index = digest.key_index, security_level = digest.security_level, )
Example #11
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def _setup_filtering(argv): # type: (MutableSequence[Text]) -> None """Implements the bazel test filtering protocol. The following environment variable is used in this method: TESTBRIDGE_TEST_ONLY: string, if set, is forwarded to the unittest framework to use as a test filter. Its value is split with shlex before being passed as positional arguments on argv. Args: argv: the argv to mutate in-place. """ test_filter = os.environ.get('TESTBRIDGE_TEST_ONLY') if argv is None or not test_filter: return argv[1:1] = shlex.split(test_filter)
Example #12
Source File: crop.py From starfish with MIT License | 6 votes |
def filter_tilekeys(self, tilekeys: Collection[TileKey]) -> Collection[TileKey]: """ Filters tilekeys for those that should be included in the resulting ImageStack. """ results: MutableSequence[TileKey] = list() for tilekey in tilekeys: if self._permitted_rounds is not None and tilekey.round not in self._permitted_rounds: continue if self._permitted_chs is not None and tilekey.ch not in self._permitted_chs: continue if self._permitted_zplanes is not None and tilekey.z not in self._permitted_zplanes: continue results.append(tilekey) return results
Example #13
Source File: areafilter.py From starfish with MIT License | 6 votes |
def run( self, binary_mask_collection: BinaryMaskCollection, *args, **kwargs) -> BinaryMaskCollection: matching_mask_data: MutableSequence[MaskData] = list() for ix in range(len(binary_mask_collection)): props = binary_mask_collection.mask_regionprops(ix) if self._min_area is not None and props.area < self._min_area: continue if self._max_area is not None and props.area > self._max_area: continue matching_mask_data.append(binary_mask_collection._masks[ix]) return BinaryMaskCollection( binary_mask_collection._pixel_ticks, binary_mask_collection._physical_ticks, matching_mask_data, binary_mask_collection._log, )
Example #14
Source File: launch.py From telepresence with Apache License 2.0 | 6 votes |
def __init__( self, write: typing.Callable[[str], None], do_log: bool, do_capture: bool, max_capture: int, ): self.write = write self.do_log = do_log self.do_capture = do_capture self.finished = Lock() if max_capture < 0: capture = [] # type: typing.MutableSequence[str] else: capture = deque(maxlen=max_capture) self.capture = capture # type: typing.MutableSequence[str] self.finished.acquire()
Example #15
Source File: paasta_metastatus.py From paasta with Apache License 2.0 | 6 votes |
def fill_table_rows_with_service_instance_stats( service_instance_stats: ServiceInstanceStats, resource_utilizations: Sequence[ResourceUtilization], table_rows: MutableSequence[MutableSequence[str]], ) -> None: # Calculate the max number of runnable service instances given the current resources (e.g. cpus, mem, disk) resource_free_dict = {rsrc.metric: rsrc.free for rsrc in resource_utilizations} num_service_instances_allowed = float("inf") limiting_factor = "Unknown" # service_instance_stats.keys() should be a subset of resource_free_dict for rsrc_name, rsrc_amt_wanted in service_instance_stats.items(): if rsrc_amt_wanted > 0: # type: ignore # default=0 to indicate there is none of that resource rsrc_free = resource_free_dict.get(rsrc_name, 0) if ( rsrc_free // rsrc_amt_wanted # type: ignore < num_service_instances_allowed # type: ignore ): limiting_factor = rsrc_name num_service_instances_allowed = ( rsrc_free // rsrc_amt_wanted # type: ignore ) table_rows[-1].append( "{:6} ; {}".format(int(num_service_instances_allowed), limiting_factor) )
Example #16
Source File: paasta_metastatus.py From paasta with Apache License 2.0 | 6 votes |
def utilization_table_by_grouping_from_kube( groupings: Sequence[str], threshold: float, kube_client: KubeClient, service_instance_stats: Optional[ServiceInstanceStats] = None, ) -> Tuple[Sequence[MutableSequence[str]], bool]: grouping_function = metastatus_lib.key_func_for_attribute_multi_kube(groupings) resource_info_dict_grouped = metastatus_lib.get_resource_utilization_by_grouping_kube( grouping_function, kube_client ) return utilization_table_by_grouping( groupings, grouping_function, resource_info_dict_grouped, threshold, service_instance_stats, )
Example #17
Source File: paasta_metastatus.py From paasta with Apache License 2.0 | 6 votes |
def utilization_table_by_grouping_from_mesos_state( groupings: Sequence[str], threshold: float, mesos_state: MesosState, service_instance_stats: Optional[ServiceInstanceStats] = None, ) -> Tuple[Sequence[MutableSequence[str]], bool]: grouping_function = metastatus_lib.key_func_for_attribute_multi(groupings) resource_info_dict_grouped = metastatus_lib.get_resource_utilization_by_grouping( grouping_function, mesos_state ) return utilization_table_by_grouping( groupings, grouping_function, resource_info_dict_grouped, threshold, service_instance_stats, )
Example #18
Source File: flip.py From pose-thumbnails with GNU General Public License v2.0 | 5 votes |
def pixels(values: typing.MutableSequence, width: int, height: int): """In-place flips the pixels of an image.""" start = 0 end = width for _ in range(height): values[start:end] = reversed(values[start:end]) start = end end += width
Example #19
Source File: distrib_parts.py From pytorch-lightning with Apache License 2.0 | 5 votes |
def _check_data_type(device_ids: Any) -> None: """ Checks that the device_ids argument is one of: None, Int, String or List. Raises a MisconfigurationException otherwise. Args: device_ids: gpus/tpu_cores parameter as passed to the Trainer """ if device_ids is not None and (not isinstance(device_ids, (int, str, MutableSequence)) or isinstance(device_ids, bool)): raise MisconfigurationException("Device ID's (GPU/TPU) must be int, string or sequence of ints or None.")
Example #20
Source File: simplestructs.py From CrossHair with MIT License | 5 votes |
def __init__(self, contents: MutableSequence): ''' `contents` is assumed to not have duplicate keys. ''' self.contents_ = contents
Example #21
Source File: test_typing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_mutablesequence(self): self.assertIsInstance([], typing.MutableSequence) self.assertNotIsInstance((), typing.MutableSequence)
Example #22
Source File: _argument.py From wikitextparser with GNU General Public License v3.0 | 5 votes |
def __init__( self, string: Union[str, MutableSequence[str]], _type_to_spans: Optional[Dict[str, List[List[int]]]] = None, _span: Optional[List[int]] = None, _type: Optional[Union[str, int]] = None, _parent: 'SubWikiTextWithArgs' = None, ): super().__init__(string, _type_to_spans, _span, _type) self._parent = _parent or self self._shadow_match_cache = None, None
Example #23
Source File: _comment_bold_italic.py From wikitextparser with GNU General Public License v3.0 | 5 votes |
def __init__( self, string: Union[str, MutableSequence[str]], _type_to_spans: Optional[Dict[str, List[List[int]]]] = None, _span: Optional[List[int]] = None, _type: Optional[Union[str, int]] = None, end_token: bool = True, ): """Initialize the Italic object. :param end_token: set to True if the italic object ends with a '' token False otherwise. """ super().__init__(string, _type_to_spans, _span, _type) self.end_token = end_token
Example #24
Source File: manager.py From lbry-sdk with MIT License | 5 votes |
def __init__(self, wallets: MutableSequence[Wallet] = None, ledgers: MutableMapping[Type[Ledger], Ledger] = None) -> None: self.wallets = wallets or [] self.ledgers = ledgers or {} self.running = False self.config: Optional[Config] = None
Example #25
Source File: wallet.py From lbry-sdk with MIT License | 5 votes |
def __init__(self, name: str = 'Wallet', accounts: MutableSequence['Account'] = None, storage: 'WalletStorage' = None, preferences: dict = None) -> None: self.name = name self.accounts = accounts or [] self.storage = storage or WalletStorage() self.preferences = TimestampedPreferences(preferences or {}) self.encryption_password = None self.id = self.get_id()
Example #26
Source File: misc.py From transpyle with Apache License 2.0 | 5 votes |
def flatten_sequence(sequence: t.MutableSequence[t.Any]) -> None: """Transform a given list of lists of lists (...) of lists into a flat list in-place.""" assert isinstance(sequence, collections.abc.MutableSequence), type(sequence) for i, elem in enumerate(sequence): if isinstance(elem, collections.abc.MutableSequence): flatten_sequence(elem) for value in reversed(elem): sequence.insert(i, value) del sequence[i + len(elem)]
Example #27
Source File: misc.py From transpyle with Apache License 2.0 | 5 votes |
def make_flatten_syntax(ast_module): def flatten_syntax(syntax: t.Union[ast_module.AST, t.MutableSequence[t.Any]]) -> None: """Flatten all lists of lists within the given syntax in-place.""" if isinstance(syntax, (ast_module.Module, ast_module.FunctionDef, ast_module.ClassDef, ast_module.For, ast_module.While, ast_module.If, ast_module.With, ast_module.Try, ast_module.ExceptHandler, ast_module.AsyncFunctionDef, ast_module.AsyncFor, ast_module.AsyncWith)): for node in syntax.body: flatten_syntax(node) flatten_sequence(syntax.body) return if isinstance(syntax, (ast_module.For, ast_module.While, ast_module.If, ast_module.Try, ast_module.AsyncFor)): for node in syntax.orelse: flatten_syntax(node) flatten_sequence(syntax.orelse) return if isinstance(syntax, ast_module.Try): for node in syntax.handlers: flatten_syntax(node) # flatten_sequence(syntax.handlers) # unnecessary for node in syntax.finalbody: flatten_syntax(node) flatten_sequence(syntax.finalbody) return if not isinstance(syntax, collections.abc.MutableSequence): return for node in syntax: flatten_syntax(node) flatten_sequence(syntax) return flatten_syntax
Example #28
Source File: test_typing.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_invariance(self): # Because of invariance, List[subclass of X] is not a subclass # of List[X], and ditto for MutableSequence. assert not issubclass(typing.List[Manager], typing.List[Employee]) assert not issubclass(typing.MutableSequence[Manager], typing.MutableSequence[Employee]) # It's still reflexive. assert issubclass(typing.List[Employee], typing.List[Employee]) assert issubclass(typing.MutableSequence[Employee], typing.MutableSequence[Employee])
Example #29
Source File: test_typing.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_mutablesequence(self): assert isinstance([], typing.MutableSequence) assert not isinstance((), typing.MutableSequence)
Example #30
Source File: util.py From starfish with MIT License | 5 votes |
def render_coordinates_to_rows( tile_to_physical_coordinates: Mapping[ TileIdentifier, Mapping[Coordinates, CoordinateValue]], ) -> Sequence[Mapping[str, str]]: results: MutableSequence[Mapping[str, str]] = list() for tile_identifier, physical_coordinates in tile_to_physical_coordinates.items(): rowdata: MutableMapping[str, str] = dict() for tile_coordinate_name, tile_coordinate_value in zip( TILE_COORDINATE_NAMES, dataclasses.astuple(tile_identifier) ): rowdata[tile_coordinate_name] = str(tile_coordinate_value) for coordinate_name in list(Coordinates): coordinate_value = physical_coordinates.get(coordinate_name, None) if coordinate_value is None and coordinate_name == Coordinates.Z: # Z coordinates may be legitimately missing continue if isinstance(coordinate_value, tuple): rowdata[f'{coordinate_name}_min'] = str(coordinate_value[0]) rowdata[f'{coordinate_name}_max'] = str(coordinate_value[1]) else: rowdata[f'{coordinate_name}_min'] = str(coordinate_value) results.append(rowdata) return results