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


Python typing.Mapping方法代碼示例

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


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

示例1: from_mapping

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def from_mapping(self, mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> None:
        """Load the configuration values from a mapping.

        This allows either a mapping to be directly passed or as
        keyword arguments, for example,

        .. code-block:: python

            config = {'FOO': 'bar'}
            app.config.from_mapping(config)
            app.config.form_mapping(FOO='bar')

        Arguments:
            mapping: Optionally a mapping object.
            kwargs: Optionally a collection of keyword arguments to
                form a mapping.
        """
        mappings: Dict[str, Any] = {}
        if mapping is not None:
            mappings.update(mapping)
        mappings.update(kwargs)
        for key, value in mappings.items():
            if key.isupper():
                self[key] = value 
開發者ID:pgjones,項目名稱:quart,代碼行數:26,代碼來源:config.py

示例2: find_bad_items

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def find_bad_items(self, batch: Mapping[str, DatabaseMedia]):
        """
        a batch get failed. Now do all of its contents as individual
        gets so we can work out which ID(s) cause the failure
        """
        for item_id, media_item in batch.items():
            try:
                log.debug("BAD ID Retry on %s (%s)", item_id, media_item.relative_path)
                response = self._api.mediaItems.get.execute(mediaItemId=item_id)
                media_item_json = response.json()
                self.download_file(media_item, media_item_json)
            except RequestException as e:
                self.bad_ids.add_id(
                    str(media_item.relative_path), media_item.id, media_item.url, e
                )
                self.files_download_failed += 1
                log.error(
                    "FAILURE %d in get of %s BAD ID",
                    self.files_download_failed,
                    media_item.relative_path,
                ) 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:23,代碼來源:GooglePhotosDownload.py

示例3: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def __init__(self, fmt: str,
                 datefmt: str,
                 log_colors: typing.Mapping[str, str]) -> None:
        """Constructor.

        Args:
            fmt: The format string to use.
            datefmt: The date format to use.
            log_colors: The colors to use for logging levels.
        """
        super().__init__(fmt, datefmt)
        self._log_colors = log_colors  # type: typing.Mapping[str, str]
        self._colordict = {}  # type: typing.Mapping[str, str]
        # We could solve this nicer by using CSS, but for this simple case this
        # works.
        for color in COLORS:
            self._colordict[color] = '<font color="{}">'.format(color)
        self._colordict['reset'] = '</font>' 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:20,代碼來源:log.py

示例4: _path_info

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def _path_info() -> typing.Mapping[str, str]:
    """Get info about important path names.

    Return:
        A dictionary of descriptive to actual path names.
    """
    info = {
        'config': standarddir.config(),
        'data': standarddir.data(),
        'cache': standarddir.cache(),
        'runtime': standarddir.runtime(),
    }
    if standarddir.config() != standarddir.config(auto=True):
        info['auto config'] = standarddir.config(auto=True)
    if standarddir.data() != standarddir.data(system=True):
        info['system data'] = standarddir.data(system=True)
    return info 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:19,代碼來源:version.py

示例5: handle_event

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def handle_event(self, event: QEvent) -> bool:
        """Filter all events based on the currently set mode.

        Also calls the real keypress handler.

        Args:
            event: The KeyPress to examine.

        Return:
            True if event should be filtered, False otherwise.
        """
        handlers = {
            QEvent.KeyPress: self._handle_keypress,
            QEvent.KeyRelease: self._handle_keyrelease,
            QEvent.ShortcutOverride:
                functools.partial(self._handle_keypress, dry_run=True),
        }  # type: Mapping[QEvent.Type, Callable[[QKeyEvent], bool]]
        handler = handlers[event.type()]
        return handler(cast(QKeyEvent, event)) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:21,代碼來源:modeman.py

示例6: delete_offensive_msg

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def delete_offensive_msg(self, msg: Mapping[str, str]) -> None:
        """Delete an offensive message, and then delete it from the db."""
        try:
            channel = self.bot.get_channel(msg['channel_id'])
            if channel:
                msg_obj = await channel.fetch_message(msg['id'])
                await msg_obj.delete()
        except NotFound:
            log.info(
                f"Tried to delete message {msg['id']}, but the message can't be found "
                f"(it has been probably already deleted)."
            )
        except HTTPException as e:
            log.warning(f"Failed to delete message {msg['id']}: status {e.status}")

        await self.bot.api_client.delete(f'bot/offensive-messages/{msg["id"]}')
        log.info(f"Deleted the offensive message with id {msg['id']}.") 
開發者ID:python-discord,項目名稱:bot,代碼行數:19,代碼來源:filtering.py

示例7: get_regen_options

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def get_regen_options(config: Mapping[str, object]) -> Tuple[Type[PKey],
                                                             Optional[int]]:
    key_type = config.get('MASTER_KEY_TYPE', RSAKey)
    if not isinstance(key_type, type):
        raise RegenOptionError('MASTER_KEY_TYPE configuration must be a type, '
                               'not ' + repr(key_type))
    elif not issubclass(key_type, PKey):
        raise RegenOptionError(
            'MASTER_KEY_TYPE configuration must be a subclass of '
            '{0.__module__}.{0.__qualname__}, but {1.__module__}.'
            '{1.__qualname__} is not'.format(PKey, key_type)
        )
    bits = config['MASTER_KEY_BITS']
    if bits is not None and not isinstance(bits, int):
        raise RegenOptionError('MASTER_KEY_BITS configuration must be an '
                               'integer, not ' + repr(bits))
    return RSAKey, bits 
開發者ID:spoqa,項目名稱:geofront,代碼行數:19,代碼來源:regen.py

示例8: get_remote_set

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def get_remote_set() -> RemoteSet:
    """Get the configured remote set.

    :return: the configured remote set
    :rtype: :class:`~.remote.RemoteSet`
    :raise RuntimeError: if ``'REMOTE_SET'`` is not configured,
                         or it's not a mapping object

    """
    try:
        set_ = app.config['REMOTE_SET']
    except KeyError:
        raise RuntimeError('REMOTE_SET configuration is not present')
    if isinstance(set_, collections.abc.Mapping):
        return set_
    raise RuntimeError(
        'REMOTE_SET configuration must be an instance of {0.__module__}.'
        '{0.__qualname__}, not {1!r}'.format(collections.abc.Mapping, set_)
    ) 
開發者ID:spoqa,項目名稱:geofront,代碼行數:21,代碼來源:server.py

示例9: request_list

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [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

示例10: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def __init__(self, hero: Dict[str, Union[str, int]], enemy: Dict[str, Union[str, int]], season_id: Optional[int], archetypes: List[Archetype], people: List[Person], cards: List[Card], results: Mapping[str, Union[str, int, List[int], List[Deck]]]) -> None:
        super().__init__()
        self.results = results
        if results:
            self.results['num_decks'] = len(results['hero_deck_ids']) # type: ignore
            self.results['win_percent'] = str(round((results['wins'] / (results['wins'] + results['losses'])) * 100, 1)) if results.get('wins') else ''# type: ignore
        self.criteria = [
            {'name': 'Decks Matching…', 'prefix': 'hero_', 'choices': hero},
            {'name': '… versus …', 'prefix': 'enemy_', 'choices': enemy}
        ]
        # Set up options for dropdowns, marking the right ones as selected.
        for c in self.criteria:
            c['archetypes'] = [{'name': a.name, 'id': a.id, 'selected': str(c['choices'].get('archetype_id')) == str(a.id)} for a in archetypes] # type: ignore
            c['people'] = [{'mtgo_username': p.mtgo_username.lower(), 'id': p.id, 'selected': str(c['choices'].get('person_id')) == str(p.id)} for p in people] # type: ignore
            c['cards'] = [{'name': card.name, 'selected': c['choices'].get('card') == card.name} for card in cards] # type: ignore
        self.seasons = [{'season_id': s['num'] or '', 'name': s['name'], 'selected': str(season_id) == str(s['num'])} for s in self.all_seasons()]
        self.decks = results.get('hero_decks', []) # type: ignore
        self.show_decks = len(self.decks) > 0
        self.matches = results.get('matches', [])
        self.show_matches = False
        self.search_season_id = season_id 
開發者ID:PennyDreadfulMTG,項目名稱:Penny-Dreadful-Tools,代碼行數:23,代碼來源:matchups.py

示例11: content

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def content(cls, attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = ()) -> bytes:
    """
    Creates descriptor content with the given attributes. Mandatory fields are
    filled with dummy information unless data is supplied. This doesn't yet
    create a valid signature.

    .. versionadded:: 1.6.0

    :param attr: keyword/value mappings to be included in the descriptor
    :param exclude: mandatory keywords to exclude from the descriptor, this
      results in an invalid descriptor

    :returns: **bytes** with the content of a descriptor

    :raises:
      * **ImportError** if cryptography is unavailable and sign is True
      * **NotImplementedError** if not implemented for this descriptor type
    """

    raise NotImplementedError("The create and content methods haven't been implemented for %s" % cls.__name__) 
開發者ID:torproject,項目名稱:stem,代碼行數:22,代碼來源:__init__.py

示例12: create

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def create(cls, attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), validate: bool = True) -> 'stem.descriptor.Descriptor':
    """
    Creates a descriptor with the given attributes. Mandatory fields are filled
    with dummy information unless data is supplied. This doesn't yet create a
    valid signature.

    .. versionadded:: 1.6.0

    :param attr: keyword/value mappings to be included in the descriptor
    :param exclude: mandatory keywords to exclude from the descriptor, this
      results in an invalid descriptor
    :param validate: checks the validity of the descriptor's content if
      **True**, skips these checks otherwise

    :returns: :class:`~stem.descriptor.Descriptor` subclass

    :raises:
      * **ValueError** if the contents is malformed and validate is True
      * **ImportError** if cryptography is unavailable and sign is True
      * **NotImplementedError** if not implemented for this descriptor type
    """

    return cls(cls.content(attr, exclude), validate = validate)  # type: ignore 
開發者ID:torproject,項目名稱:stem,代碼行數:25,代碼來源:__init__.py

示例13: content

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def content(cls: Type['stem.descriptor.extrainfo_descriptor.RelayExtraInfoDescriptor'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), sign: bool = False, signing_key: Optional['stem.descriptor.SigningKey'] = None) -> bytes:
    base_header = (
      ('extra-info', '%s %s' % (_random_nickname(), _random_fingerprint())),
      ('published', _random_date()),
    )

    if sign or signing_key:
      if attr and 'router-signature' in attr:
        raise ValueError('Cannot sign the descriptor if a router-signature has been provided')

      if signing_key is None:
        signing_key = create_signing_key()

      content = _descriptor_content(attr, exclude, base_header) + b'\nrouter-signature\n'
      return _append_router_signature(content, signing_key.private)
    else:
      return _descriptor_content(attr, exclude, base_header, (
        ('router-signature', _random_crypto_blob('SIGNATURE')),
      )) 
開發者ID:torproject,項目名稱:stem,代碼行數:21,代碼來源:extrainfo_descriptor.py

示例14: content

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def content(cls: Type['stem.descriptor.networkstatus.DirectoryAuthority'], attr: Optional[Mapping[str, str]] = None, exclude: Sequence[str] = (), is_vote: bool = False) -> bytes:
    attr = {} if attr is None else dict(attr)

    # include mandatory 'vote-digest' if a consensus

    if not is_vote and not ('vote-digest' in attr or (exclude and 'vote-digest' in exclude)):
      attr['vote-digest'] = _random_fingerprint()

    content = _descriptor_content(attr, exclude, (
      ('dir-source', '%s %s no.place.com %s 9030 9090' % (_random_nickname(), _random_fingerprint(), _random_ipv4_address())),
      ('contact', 'Mike Perry <email>'),
    ))

    if is_vote:
      content += b'\n' + KeyCertificate.content()

    return content 
開發者ID:torproject,項目名稱:stem,代碼行數:19,代碼來源:networkstatus.py

示例15: _get_conf_dict_to_response

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Mapping [as 別名]
def _get_conf_dict_to_response(self, config_dict: Mapping[str, Sequence[str]], default: Any, multiple: bool) -> Dict[str, Union[str, Sequence[str]]]:
    """
    Translates a dictionary of 'config key => [value1, value2...]' into the
    return value of :func:`~stem.control.Controller.get_conf_map`, taking into
    account what the caller requested.
    """

    return_dict = {}

    for key, values in list(config_dict.items()):
      if values == []:
        # config option was unset
        if default != UNDEFINED:
          return_dict[key] = default
        else:
          return_dict[key] = [] if multiple else None
      else:
        return_dict[key] = values if multiple else values[0]

    return return_dict 
開發者ID:torproject,項目名稱:stem,代碼行數:22,代碼來源:control.py


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