當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.MutableMapping方法代碼示例

本文整理匯總了Python中typing.MutableMapping方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.MutableMapping方法的具體用法?Python typing.MutableMapping怎麽用?Python typing.MutableMapping使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.MutableMapping方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: replace_variables

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def replace_variables(win_id, arglist):
    """Utility function to replace variables like {url} in a list of args."""
    tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                window=win_id)
    values = {}  # type: typing.MutableMapping[str, str]
    args = []

    def repl_cb(matchobj):
        """Return replacement for given match."""
        var = matchobj.group("var")
        if var not in values:
            values[var] = VARIABLE_REPLACEMENTS[var](tabbed_browser)
        return values[var]

    try:
        for arg in arglist:
            # using re.sub with callback function replaces all variables in a
            # single pass and avoids expansion of nested variables (e.g.
            # "{url}" from clipboard is not expanded)
            args.append(VARIABLE_REPLACEMENT_PATTERN.sub(repl_cb, arg))
    except utils.ClipboardError as e:
        raise cmdutils.CommandError(e)
    return args 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:25,代碼來源:runners.py

示例2: _get_many_using_multiprocessing

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def _get_many_using_multiprocessing(self, async_results) -> Mapping[str, EventBufferValueType]:
        num_process = min(len(async_results), self._sync_parallelism)

        with Pool(processes=num_process) as sync_pool:
            chunksize = max(1, math.floor(math.ceil(1.0 * len(async_results) / self._sync_parallelism)))

            task_id_to_states_and_info = sync_pool.map(
                fetch_celery_task_state,
                async_results,
                chunksize=chunksize)

            states_and_info_by_task_id: MutableMapping[str, EventBufferValueType] = {}
            for task_id, state_or_exception, info in task_id_to_states_and_info:
                if isinstance(state_or_exception, ExceptionWithTraceback):
                    self.log.error(  # pylint: disable=logging-not-lazy
                        CELERY_FETCH_ERR_MSG_HEADER + ":%s\n%s\n",
                        state_or_exception.exception, state_or_exception.traceback
                    )
                else:
                    states_and_info_by_task_id[task_id] = state_or_exception, info
        return states_and_info_by_task_id 
開發者ID:apache,項目名稱:airflow,代碼行數:23,代碼來源:celery_executor.py

示例3: _get_set_clear

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def _get_set_clear(
    mapping: MutableMapping[K, V],
    key: K,
    default_factory: Callable[[], V],
    *,
    clear: bool = False
) -> V:
    try:
        out = mapping[key]
    except KeyError:
        mapping[key] = out = default_factory()

    if clear:
        out.clear()

    return out 
開發者ID:TotallyNotRobots,項目名稱:CloudBot,代碼行數:18,代碼來源:server_info.py

示例4: test_subclassing

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def test_subclassing(self):

        class MMA(typing.MutableMapping):
            pass

        with self.assertRaises(TypeError):  # It's abstract
            MMA()

        class MMC(MMA):
            def __len__(self):
                return 0

        assert len(MMC()) == 0

        class MMB(typing.MutableMapping[KT, VT]):
            def __len__(self):
                return 0

        assert len(MMB()) == 0
        assert len(MMB[str, str]()) == 0
        assert len(MMB[KT, VT]()) == 0 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_typing.py

示例5: build_smartstack_location_dict

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def build_smartstack_location_dict(
    location: str,
    matched_backends_and_tasks: List[
        Tuple[
            Optional[HaproxyBackend],
            Optional[Union[marathon_tools.MarathonTask, V1Pod]],
        ]
    ],
    should_return_individual_backends: bool = False,
) -> MutableMapping[str, Any]:
    running_backends_count = 0
    backends = []
    for backend, task in matched_backends_and_tasks:
        if backend is None:
            continue
        if backend_is_up(backend):
            running_backends_count += 1
        if should_return_individual_backends:
            backends.append(build_smartstack_backend_dict(backend, task))

    return {
        "name": location,
        "running_backends_count": running_backends_count,
        "backends": backends,
    } 
開發者ID:Yelp,項目名稱:paasta,代碼行數:27,代碼來源:smartstack_tools.py

示例6: _build_smartstack_location_dict_for_backends

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def _build_smartstack_location_dict_for_backends(
    synapse_host: str,
    registration: str,
    tasks: Sequence[MarathonTask],
    location: str,
    should_return_individual_backends: bool,
) -> MutableMapping[str, Any]:
    sorted_smartstack_backends = sorted(
        smartstack_tools.get_backends(
            registration,
            synapse_host=synapse_host,
            synapse_port=settings.system_paasta_config.get_synapse_port(),
            synapse_haproxy_url_format=settings.system_paasta_config.get_synapse_haproxy_url_format(),
        ),
        key=lambda backend: backend["status"],
        reverse=True,  # put 'UP' backends above 'MAINT' backends
    )
    matched_smartstack_backends_and_tasks = smartstack_tools.match_backends_and_tasks(
        sorted_smartstack_backends, tasks
    )
    return smartstack_tools.build_smartstack_location_dict(
        location,
        matched_smartstack_backends_and_tasks,
        should_return_individual_backends,
    ) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:27,代碼來源:instance.py

示例7: get_mesos_non_running_task_dict

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def get_mesos_non_running_task_dict(
    task: Task, num_tail_lines: int
) -> MutableMapping[str, Any]:
    if num_tail_lines > 0:
        tail_lines = await get_tail_lines_for_mesos_task(
            task, get_short_task_id, num_tail_lines
        )
    else:
        tail_lines = {}

    task_dict = {
        "id": get_short_task_id(task["id"]),
        "hostname": await results_or_unknown(get_short_hostname_from_task(task)),
        "state": task["state"],
        "tail_lines": tail_lines,
    }

    task_start_time = get_first_status_timestamp(task)
    if task_start_time is not None:
        task_dict["deployed_timestamp"] = task_start_time

    return task_dict 
開發者ID:Yelp,項目名稱:paasta,代碼行數:24,代碼來源:instance.py

示例8: get_language_strings

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def get_language_strings(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> LanguageStringsDto:
        locale = query["locale"] if "locale" in query else query["platform"].default_locale

        url = "https://ddragon.leagueoflegends.com/cdn/{version}/data/{locale}/language.json".format(
            version=query["version"],
            locale=locale
        )
        try:
            body = json.loads(self._client.get(url)[0])
        except HTTPError as e:
            raise NotFoundError(str(e)) from e

        body["region"] = query["platform"].region.value
        body["locale"] = locale
        return LanguageStringsDto(body)

    #########
    # Runes #
    ######### 
開發者ID:meraki-analytics,項目名稱:cassiopeia,代碼行數:21,代碼來源:ddragon.py

示例9: get_profile_icon

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def get_profile_icon(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> ProfileIconDataDto:
        locale = query["locale"] if "locale" in query else query["platform"].default_locale

        url = "https://ddragon.leagueoflegends.com/cdn/{version}/data/{locale}/profileicon.json".format(
            version=query["version"],
            locale=locale
        )
        try:
            body = json.loads(self._client.get(url)[0])
        except HTTPError as e:
            raise NotFoundError(str(e)) from e

        body["region"] = query["platform"].region.value
        body["locale"] = locale
        body["version"] = query["version"]
        for pi in body["data"].values():
            pi["region"] = body["region"]
            pi["version"] = body["version"]
            pi["locale"] = locale
        return ProfileIconDataDto(body) 
開發者ID:meraki-analytics,項目名稱:cassiopeia,代碼行數:22,代碼來源:ddragon.py

示例10: get_champion_all_rates

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def get_champion_all_rates(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> ChampionAllRatesDto:
        try:
            return self._cache[ChampionRatesDto]
        except KeyError:
            pass
        url = "http://cdn.merakianalytics.com/riot/lol/resources/latest/en-US/championrates.json"
        try:
            body = self._client.get(url)[0]
            body = json.decode(body)
            body["data"] = {int(k): v for k, v in body["data"].items()}
        except HTTPError as e:
            raise NotFoundError(str(e)) from e

        result = ChampionAllRatesDto(**body)
        self._cache[ChampionRatesDto] = result
        return result 
開發者ID:meraki-analytics,項目名稱:cassiopeia,代碼行數:18,代碼來源:merakianalyticscdn.py

示例11: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def __init__(self, uuid: str, value: Optional[Sequence[int]],
                 flags: Sequence[str]):
        self.uuid = uuid
        self.value = value
        self.flags = flags
        self.descriptors: MutableMapping[str, GATTDescriptor] = dict() 
開發者ID:scipag,項目名稱:btle-sniffer,代碼行數:8,代碼來源:device.py

示例12: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def __init__(self, parent=None):
        super().__init__(parent)
        self._cleaned_up = False
        self._filepath = None
        self._proc = None
        self._env = {}  # type: typing.MutableMapping[str, str]
        self._text_stored = False
        self._html_stored = False
        self._args = ()  # type: typing.Tuple[typing.Any, ...]
        self._kwargs = {} 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:12,代碼來源:userscripts.py

示例13: _get_call_args

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def _get_call_args(self, win_id):
        """Get arguments for a function call.

        Args:
            win_id: The window id this command should be executed in.

        Return:
            An (args, kwargs) tuple.
        """
        args = []  # type: typing.Any
        kwargs = {}  # type: typing.MutableMapping[str, typing.Any]
        signature = inspect.signature(self.handler)

        for i, param in enumerate(signature.parameters.values()):
            if self._handle_special_call_arg(pos=i, param=param,
                                             win_id=win_id, args=args,
                                             kwargs=kwargs):
                continue

            value = self._get_param_value(param)
            if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
                args.append(value)
            elif param.kind == inspect.Parameter.VAR_POSITIONAL:
                if value is not None:
                    args += value
            elif param.kind == inspect.Parameter.KEYWORD_ONLY:
                kwargs[param.name] = value
            else:
                raise TypeError("{}: Invalid parameter type {} for argument "
                                "'{}'!".format(
                                    self.name, param.kind, param.name))
        return args, kwargs 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:34,代碼來源:command.py

示例14: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def __init__(self) -> None:
        super().__init__()
        self._partial_objs = {
        }  # type: typing.MutableMapping[_IndexType, typing.Callable[[], None]]
        self.command_only = []  # type: typing.MutableSequence[str] 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:7,代碼來源:objreg.py

示例15: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import MutableMapping [as 別名]
def __init__(self, parent=None):
        """Initialize and read quickmarks."""
        super().__init__(parent)

        self.marks = collections.OrderedDict(
        )  # type: typing.MutableMapping[str, str]

        self._init_lineparser()
        for line in self._lineparser:
            if not line.strip() or line.startswith('#'):
                # Ignore empty or whitespace-only lines and comments.
                continue
            self._parse_line(line)
        self._init_savemanager(objreg.get('save-manager')) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:16,代碼來源:urlmarks.py


注:本文中的typing.MutableMapping方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。