How to use the typing.cast function in typing

To help you get started, we’ve selected a few typing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Mirantis / disk_perf_test_tool / wally / hw_info.py View on Github external
for slot_node in mem_node.find("node[@class='memory']"):
                        slot_sz = slot_node.find('size')
                        if slot_sz is not None:
                            assert slot_sz.attrib['units'] == 'bytes'
                            res.ram_size += int(slot_sz.text)
                else:
                    assert mem_sz.attrib['units'] == 'bytes'
                    res.ram_size += int(mem_sz.text)
        except Exception:
            pass

    for net in core.findall(".//node[@class='network']"):
        try:
            link = net.find("configuration/setting[@id='link']")
            if link.attrib['value'] == 'yes':
                name = cast(str, net.find("logicalname").text)
                speed_node = net.find("configuration/setting[@id='speed']")

                if speed_node is None:
                    speed = None
                else:
                    speed = int(speed_node.attrib['value'])

                dup_node = net.find("configuration/setting[@id='duplex']")
                if dup_node is None:
                    dup = None
                else:
                    dup = cast(str, dup_node.attrib['value']).lower() == 'yes'

                ips = []  # type: List[str]
                res.net_info[name] = (speed, dup, ips)
        except Exception:
github Ultimaker / Cura / plugins / Toolbox / src / Toolbox.py View on Github external
def startDownload(self, url: str) -> None:
        Logger.log("i", "Attempting to download & install package from %s.", url)
        url = QUrl(url)
        self._download_request = QNetworkRequest(url)
        if hasattr(QNetworkRequest, "FollowRedirectsAttribute"):
            # Patch for Qt 5.6-5.8
            cast(QNetworkRequest, self._download_request).setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        if hasattr(QNetworkRequest, "RedirectPolicyAttribute"):
            # Patch for Qt 5.9+
            cast(QNetworkRequest, self._download_request).setAttribute(QNetworkRequest.RedirectPolicyAttribute, True)
        for header_name, header_value in self._request_headers:
            cast(QNetworkRequest, self._download_request).setRawHeader(header_name, header_value)
        self._download_reply = cast(QNetworkAccessManager, self._network_manager).get(self._download_request)
        self.setDownloadProgress(0)
        self.setIsDownloading(True)
        cast(QNetworkReply, self._download_reply).downloadProgress.connect(self._onDownloadProgress)
github common-workflow-language / schema_salad / schema_salad / schema.py View on Github external
for field in ("type", "items", "values", "fields"):
            if field in items:
                items[field] = make_valid_avro(
                    items[field], alltypes, found, union=True
                )
        if "symbols" in items:
            items["symbols"] = [avro_name(sym) for sym in items["symbols"]]
        return items
    if isinstance(items, MutableSequence):
        ret = []
        for i in items:
            ret.append(make_valid_avro(i, alltypes, found, union=union))
        return ret
    if union and isinstance(items, str):
        if items in alltypes and avro_name(items) not in found:
            return cast(
                Dict[str, str],
                make_valid_avro(alltypes[items], alltypes, found, union=union),
            )
        items = avro_name(items)
    return items
github dotnet / performance / src / benchmarks / gc / src / analysis / clr.py View on Github external
def StackSourceSample(self) -> Type[AbstractStackSourceSample]:
        return cast(Type[AbstractStackSourceSample], self._stacks.StackSourceSample)
github dkmstr / openuds / server / src / uds / models / user_service.py View on Github external
def recoverValue(self, name: str) -> str:
        """
        Recovers a value from custom storage

        Args:
            name: Name of values to recover

        Returns:
            Stored value, None if no value was stored
        """
        val = self.getProperty(name)

        # To transition between old stor at storage table and new properties table
        # If value is found on property, use it, else, try to recover it from storage
        if val is None:
            val = typing.cast(str, self.getEnvironment().storage.get(name))
        return val
github oilshell / oil / asdl / format.py View on Github external
tag = node.tag_()
  if tag == hnode_e.Leaf:
    node = cast(hnode__Leaf, UP_node)
    f.PushColor(node.color)
    f.write(qsn.maybe_encode(node.s))
    f.PopColor()

  elif tag == hnode_e.External:
    node = cast(hnode__External, UP_node)

    f.PushColor(color_e.External)
    f.write(repr(node.obj))
    f.PopColor()

  elif tag == hnode_e.Array:
    node = cast(hnode__Array, UP_node)

    # Can we fit the WHOLE array on the line?
    f.write('[')
    for i, item in enumerate(node.children):
      if i != 0:
        f.write(' ')
      if not _TrySingleLine(item, f, max_chars):
        return False
    f.write(']')

  elif tag == hnode_e.Record:
    node = cast(hnode__Record, UP_node)

    return _TrySingleLineObj(node, f, max_chars)

  else:
github qutebrowser / qutebrowser / qutebrowser / config / config.py View on Github external
from qutebrowser.utils import utils, log, jinja, urlmatch
from qutebrowser.misc import objects
from qutebrowser.keyinput import keyutils

MYPY = False
if MYPY:
    # pylint: disable=unused-import,useless-suppression
    from typing import Tuple, MutableMapping
    from qutebrowser.config import configcache, configfiles
    from qutebrowser.misc import savemanager

# An easy way to access the config from other code via config.val.foo
val = typing.cast('ConfigContainer', None)
instance = typing.cast('Config', None)
key_instance = typing.cast('KeyConfig', None)
cache = typing.cast('configcache.ConfigCache', None)

# Keeping track of all change filters to validate them later.
change_filters = []

# Sentinel
UNSET = object()


class change_filter:  # noqa: N801,N806 pylint: disable=invalid-name

    """Decorator to filter calls based on a config section/option matching.

    This could also be a function, but as a class (with a "wrong" name) it's
    much cleaner to implement.

    Attributes:
github jdidion / atropos / atropos / io / formatters.py View on Github external
def create_row(_tags: Union[str, dict]):
            if isinstance(_tags, dict):
                tags_str = "\t".join(f"{key}:{val}" for key, val in _tags.items())
            else:
                tags_str = cast(str, _tags)
            return f"@{header_type}\t{tags_str}"
github dnanexus / IndexTools / indextools / intervals.py View on Github external
Examples:
            # End-inclusivity: a Interval is not end-inclusive, so an
            # interval whose end position is the same as the start position of
            # a second interval does *not* overlap that interval:
            i1 = Interval('chr1', 50, 100)
            i2 = Interval('chr1', 100, 200)
            cmp = i1.compare(i2)  # => (0, -1, 0, 0)
        """
        diff = 0
        overlap = 0

        if isinstance(other.contig, int):
            other_contig = cast(int, other.contig)
        else:
            other_contig = cast(str, other.contig)
        contig = self.contig
        if contig < other_contig:
            contig_cmp = -1
        elif contig > other_contig:
            contig_cmp = 1
        else:
            contig_cmp = 0

        if self.start >= other.end:
            diff = (self.start + 1) - other.end
        elif self.end <= other.start:
            diff = self.end - (other.start + 1)
        elif self.start >= other.start:
            overlap = min(self.end, other.end) - self.start
        else:
            overlap = other.start - self.end
github MagicStack / py-pgproto / types.py View on Github external
def __new__(cls, high: typing.Sequence[float],
                low: typing.Sequence[float]) -> 'Box':
        return super().__new__(cls,
                               typing.cast(typing.Any, (Point(*high),
                                                        Point(*low))))