• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python typing.cast函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中typing.cast函数的典型用法代码示例。如果您正苦于以下问题:Python cast函数的具体用法?Python cast怎么用?Python cast使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了cast函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _parity_interaction

def _parity_interaction(q0: ops.QubitId,
                        q1: ops.QubitId,
                        rads: float,
                        tolerance: float,
                        gate: Optional[ops.ReversibleEffect] = None):
    """Yields a ZZ interaction framed by the given operation."""
    if abs(rads) < tolerance:
        return

    h = rads * -2 / np.pi
    if gate is not None:
        g = cast(ops.Gate, gate)
        yield g.on(q0), g.on(q1)

    # If rads is ±pi/4 radians within tolerance, single full-CZ suffices.
    if _is_trivial_angle(rads, tolerance):
        yield ops.CZ.on(q0, q1)
    else:
        yield ops.CZ(q0, q1) ** (-2 * h)

    yield ops.Z(q0)**h
    yield ops.Z(q1)**h
    if gate is not None:
        g = cast(ops.Gate, gate.inverse())
        yield g.on(q0), g.on(q1)
开发者ID:google2013,项目名称:Cirq,代码行数:25,代码来源:decompositions.py


示例2: type_object_type_from_function

def type_object_type_from_function(init_or_new: FuncBase, info: TypeInfo, fallback: Instance) -> FunctionLike:
    signature = method_type_with_fallback(init_or_new, fallback)

    # The __init__ method might come from a generic superclass
    # (init_or_new.info) with type variables that do not map
    # identically to the type variables of the class being constructed
    # (info). For example
    #
    #   class A(Generic[T]): def __init__(self, x: T) -> None: pass
    #   class B(A[List[T]], Generic[T]): pass
    #
    # We need to first map B's __init__ to the type (List[T]) -> None.
    signature = cast(FunctionLike, map_type_from_supertype(signature, info, init_or_new.info))

    if init_or_new.info.fullname() == "builtins.dict":
        # Special signature!
        special_sig = "dict"
    else:
        special_sig = None

    if isinstance(signature, CallableType):
        return class_callable(signature, info, fallback, special_sig)
    else:
        # Overloaded __init__/__new__.
        items = []  # type: List[CallableType]
        for item in cast(Overloaded, signature).items():
            items.append(class_callable(item, info, fallback, special_sig))
        return Overloaded(items)
开发者ID:JdeH,项目名称:Transcrypt,代码行数:28,代码来源:checkmember.py


示例3: _load_bytes

def _load_bytes(f):  # type: (Union[IO[bytes], Text]) -> bytes
    if hasattr(f, 'read') and callable(cast(IO[bytes], f).read):
        s = cast(IO[bytes], f).read()
    else:
        with open(cast(Text, f), 'rb') as readable:
            s = readable.read()
    return s
开发者ID:harshit98,项目名称:onnx,代码行数:7,代码来源:__init__.py


示例4: format

 def format(self, typ: Type) -> str:
     """Convert a type to a relatively short string that is
     suitable for error messages. Mostly behave like format_simple
     below, but never return an empty string.
     """
     s = self.format_simple(typ)
     if s != '':
         # If format_simple returns a non-trivial result, use that.
         return s
     elif isinstance(typ, FunctionLike):
         func = cast(FunctionLike, typ)
         if func.is_type_obj():
             # The type of a type object type can be derived from the
             # return type (this always works).
             itype = cast(Instance, func.items()[0].ret_type)
             return self.format(itype)
         elif isinstance(func, Callable):
             arg_types = map(self.format, func.arg_types)
             return_type = self.format(func.ret_type)
             return 'Function[[{}] -> {}]'.format(", ".join(arg_types),
                                                 return_type)
         else:
             # Use a simple representation for function types; proper
             # function types may result in long and difficult-to-read
             # error messages.
             return 'functionlike'
     else:
         # Default case; we simply have to return something meaningful here.
         return 'object'
开发者ID:mvcisback,项目名称:mypy,代码行数:29,代码来源:messages.py


示例5: format

    def format(self, typ: Type, verbose: bool = False) -> str:
        """Convert a type to a relatively short string that is suitable for error messages.

        Mostly behave like format_simple below, but never return an empty string.
        """
        s = self.format_simple(typ)
        if s != '':
            # If format_simple returns a non-trivial result, use that.
            return s
        elif isinstance(typ, FunctionLike):
            func = cast(FunctionLike, typ)
            if func.is_type_obj():
                # The type of a type object type can be derived from the
                # return type (this always works).
                itype = cast(Instance, func.items()[0].ret_type)
                result = self.format(itype)
                if verbose:
                    # In some contexts we want to be explicit about the distinction
                    # between type X and the type of type object X.
                    result += ' (type object)'
                return result
            elif isinstance(func, CallableType):
                return_type = strip_quotes(self.format(func.ret_type))
                if func.is_ellipsis_args:
                    return 'Callable[..., {}]'.format(return_type)
                arg_types = [strip_quotes(self.format(t)) for t in func.arg_types]
                return 'Callable[[{}], {}]'.format(", ".join(arg_types), return_type)
            else:
                # Use a simple representation for function types; proper
                # function types may result in long and difficult-to-read
                # error messages.
                return 'overloaded function'
        else:
            # Default case; we simply have to return something meaningful here.
            return 'object'
开发者ID:narusemotoki,项目名称:mypy,代码行数:35,代码来源:messages.py


示例6: visit_assignment_stmt

 def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
     self.line = o.line
     if (isinstance(o.rvalue, nodes.CallExpr) and
         isinstance(cast(nodes.CallExpr, o.rvalue).analyzed,
                    nodes.TypeVarExpr)):
         # Type variable definition -- not a real assignment.
         return
     if o.type:
         self.type(o.type)
     elif self.inferred:
         for lvalue in o.lvalues:
             if isinstance(lvalue, nodes.TupleExpr):
                 items = lvalue.items
             elif isinstance(lvalue, nodes.ListExpr):
                 items = lvalue.items
             else:
                 items = [lvalue]
             for item in items:
                 if hasattr(item, 'is_def') and cast(Any, item).is_def:
                     t = self.typemap.get(item)
                     if t:
                         self.type(t)
                     else:
                         self.log('  !! No inferred type on line %d' %
                                  self.line)
                         self.record_line(self.line, TYPE_ANY)
     super().visit_assignment_stmt(o)
开发者ID:jdiglesias,项目名称:mypy,代码行数:27,代码来源:stats.py


示例7: test_getTextNameBinaryValues

    def test_getTextNameBinaryValues(self, pairs):
        # type: (Iterable[Tuple[Text, bytes]]) -> None
        """
        C{getValues} returns an iterable of L{Text} values for
        the given L{Text} header name.

        This test only inserts binary data into the header values, which
        includes invalid data if you are a sane person, but arguably
        technically valid if you read the spec because the spec is unclear
        about header encodings, so we made sure that works also, if only sort
        of.
        """
        rawHeaders = tuple(
            (headerNameAsBytes(name), value) for name, value in pairs
        )

        binaryValues = defaultdict(list)  # type: Dict[Text, List[bytes]]
        for name, value in rawHeaders:
            binaryValues[headerNameAsText(normalizeHeaderName(name))].append(
                value
            )

        for textName, values in binaryValues.items():
            cast(TestCase, self).assertEqual(
                tuple(self.getValues(rawHeaders, textName)),
                tuple(headerValueAsText(value) for value in values),
                "header name: {!r}".format(textName)
            )
开发者ID:notoriousno,项目名称:klein,代码行数:28,代码来源:test_headers.py


示例8: visit_call_expr

 def visit_call_expr(self, e: CallExpr) -> int:
     args = [] # type: List[int]
     for arg in e.args:
         args.append(self.accept(arg))
     if isinstance(e.callee, NameExpr):
         name = cast(NameExpr, e.callee)
         target = self.target_register()
         self.add(CallDirect(target, name.name, args))
     elif isinstance(e.callee, MemberExpr):
         member = cast(MemberExpr, e.callee)
         receiver = self.accept(member.expr)
         target = self.target_register()
         receiver_type = self.types[member.expr]
         assert isinstance(receiver_type, Instance) # TODO more flexible
         typeinfo = (cast(Instance, receiver_type)).type
         self.add(CallMethod(target, receiver, member.name, typeinfo, args))
     elif isinstance(e.callee, SuperExpr):
         superexpr = cast(SuperExpr, e.callee)
         target = self.target_register()
         self.add(CallMethod(target, 0,
                             superexpr.name,
                             superexpr.info.bases[0].type,
                             args, static=True))
     else:
         raise NotImplementedError('call target %s' % type(e.callee))
     return target
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:26,代码来源:icode.py


示例9: send

    def send(
            self,  # type: BaseConnection
            msg_type,  # type: MsgPackable
            *args,  # type: MsgPackable
            **kargs  # type: Union[bytes, int]
    ):  # type: (...) -> InternalMessage
        """Sends a message through its connection.

        Args:
            msg_type:  Message type, corresponds to the header in a
                           :py:class:`~py2p.base.InternalMessage` object
            *args:     A list of bytes-like objects, which correspond to the
                           packets to send to you
            **kargs:   There are two available keywords:
            id:        The ID this message should appear to be sent from
                           (default: your ID)
            time:      The time this message should appear to be sent from
                           (default: now in UTC)

        Returns:
            the :py:class:`~py2p.base.IntenalMessage` object you just sent, or
            ``None`` if the sending was unsuccessful
        """
        # Latter is returned if key not found
        id = cast(bytes, kargs.get('id', self.server.id))
        time = cast(int, kargs.get('time') or getUTC())
        # Begin real method
        msg = InternalMessage(
            msg_type, id, args, self.compression, timestamp=time)
        return self.send_InternalMessage(msg)
开发者ID:gappleto97,项目名称:p2p-project,代码行数:30,代码来源:base.py


示例10: proxies_from_env

def proxies_from_env() -> Dict[str, ProxyInfo]:
    proxy_urls = {k: URL(v) for k, v in getproxies().items()
                  if k in ('http', 'https')}
    netrc_obj = netrc_from_env()
    stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
    ret = {}
    for proto, val in stripped.items():
        proxy, auth = val
        if proxy.scheme == 'https':
            client_logger.warning(
                "HTTPS proxies %s are not supported, ignoring", proxy)
            continue
        if netrc_obj and auth is None:
            auth_from_netrc = None
            if proxy.host is not None:
                auth_from_netrc = netrc_obj.authenticators(proxy.host)
            if auth_from_netrc is not None:
                # auth_from_netrc is a (`user`, `account`, `password`) tuple,
                # `user` and `account` both can be username,
                # if `user` is None, use `account`
                *logins, password = auth_from_netrc
                login = logins[0] if logins[0] else logins[-1]
                auth = BasicAuth(cast(str, login), cast(str, password))
        ret[proto] = ProxyInfo(proxy, auth)
    return ret
开发者ID:KeepSafe,项目名称:aiohttp,代码行数:25,代码来源:helpers.py


示例11: make_class_constructor

 def make_class_constructor(self, tdef: ClassDef) -> None:
     # Do we have a non-empty __init__?
     init = cast(FuncDef, tdef.info.get_method('__init__'))
     init_argc = len(init.args) - 1
     if init.info.fullname() == 'builtins.object':
         init = None
     
     self.enter()
     if init:
         args = [] # type: List[int]
         for arg in init.args[1:]:
             args.append(self.add_local(arg))
     target = self.alloc_register()
     self.add(Construct(target, tdef.info))
     # Inititalize data attributes to default values.
     for name, node in sorted(tdef.info.names.items()):
         if isinstance(node.node, Var):
             var = cast(Var, node.node)
             temp = self.alloc_register()
             vtype = var.type
             if is_named_instance(vtype, 'builtins.int'):
                 self.add(SetRI(temp, 0))
             else:
                 self.add(SetRNone(temp))
             self.add(SetAttr(target, name, temp, tdef.info))
     if init:
         self.add(CallMethod(self.alloc_register(), target, '__init__',
                             init.info, args, static=True))
     self.add(Return(target))
     self.generated[tdef.name] = FuncIcode(init_argc, self.blocks,
                                           self.register_types)
     self.leave()
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:32,代码来源:icode.py


示例12: merged_with

 def merged_with(self, op: 'PauliStringPhasor') -> 'PauliStringPhasor':
     if not self.can_merge_with(op):
         raise ValueError('Cannot merge operations: {}, {}'.format(self, op))
     neg_sign = (1, -1)[op.pauli_string.negated ^ self.pauli_string.negated]
     half_turns = (cast(float, self.half_turns)
                   + cast(float, op.half_turns) * neg_sign)
     return PauliStringPhasor(self.pauli_string, half_turns=half_turns)
开发者ID:google2013,项目名称:Cirq,代码行数:7,代码来源:pauli_string_phasor.py


示例13: run_eden_start_with_real_daemon

def run_eden_start_with_real_daemon(
    eden_dir: pathlib.Path,
    etc_eden_dir: pathlib.Path,
    home_dir: pathlib.Path,
    systemd: bool,
) -> None:
    env = dict(os.environ)
    if systemd:
        env["EDEN_EXPERIMENTAL_SYSTEMD"] = "1"
    else:
        env.pop("EDEN_EXPERIMENTAL_SYSTEMD", None)
    command = [
        typing.cast(str, FindExe.EDEN_CLI),  # T38947910
        "--config-dir",
        str(eden_dir),
        "--etc-eden-dir",
        str(etc_eden_dir),
        "--home-dir",
        str(home_dir),
        "start",
        "--daemon-binary",
        typing.cast(str, FindExe.EDEN_DAEMON),  # T38947910
    ]
    if eden_start_needs_allow_root_option(systemd=systemd):
        command.extend(["--", "--allowRoot"])
    subprocess.check_call(command, env=env)
开发者ID:facebookexperimental,项目名称:eden,代码行数:26,代码来源:start_test.py


示例14: _non_local_part

def _non_local_part(q0: ops.QubitId,
                    q1: ops.QubitId,
                    x: float,
                    y: float,
                    z: float,
                    allow_partial_czs: bool,
                    tolerance: float = 1e-8):
    """Yields non-local operation of KAK decomposition."""

    if (allow_partial_czs or
        all(_is_trivial_angle(e, tolerance) for e in [x, y, z])):
        return [
            _parity_interaction(q0, q1, x, tolerance,
                                cast(ops.ReversibleEffect, ops.Y**-0.5)),
            _parity_interaction(q0, q1, y, tolerance,
                                cast(ops.ReversibleEffect, ops.X**0.5)),
            _parity_interaction(q0, q1, z, tolerance)
        ]

    if abs(z) >= tolerance:
        return _xx_yy_zz_interaction_via_full_czs(q0, q1, x, y, z)

    if y >= tolerance:
        return _xx_yy_interaction_via_full_czs(q0, q1, x, y)

    return _xx_interaction_via_full_czs(q0, q1, x)
开发者ID:google2013,项目名称:Cirq,代码行数:26,代码来源:decompositions.py


示例15: _sendPrintJobWaitOnWriteJobFinished

    def _sendPrintJobWaitOnWriteJobFinished(self, job: WriteFileJob) -> None:
        if self._write_job_progress_message:
            self._write_job_progress_message.hide()

        self._progress_message = Message(i18n_catalog.i18nc("@info:status", "Sending data to printer"), lifetime = 0, dismissable = False, progress = -1,
                                         title = i18n_catalog.i18nc("@info:title", "Sending Data"))
        self._progress_message.addAction("Abort", i18n_catalog.i18nc("@action:button", "Cancel"), icon = None, description = "")
        self._progress_message.actionTriggered.connect(self._progressMessageActionTriggered)
        self._progress_message.show()
        parts = []

        target_printer, preferred_format, stream = self._dummy_lambdas

        # If a specific printer was selected, it should be printed with that machine.
        if target_printer:
            target_printer = self._printer_uuid_to_unique_name_mapping[target_printer]
            parts.append(self._createFormPart("name=require_printer_name", bytes(target_printer, "utf-8"), "text/plain"))

        # Add user name to the print_job
        parts.append(self._createFormPart("name=owner", bytes(self._getUserName(), "utf-8"), "text/plain"))

        file_name = CuraApplication.getInstance().getPrintInformation().jobName + "." + preferred_format["extension"]

        output = stream.getvalue()  # Either str or bytes depending on the output mode.
        if isinstance(stream, io.StringIO):
            output = cast(str, output).encode("utf-8")
        output = cast(bytes, output)

        parts.append(self._createFormPart("name=\"file\"; filename=\"%s\"" % file_name, output))

        self._latest_reply_handler = self.postFormWithParts("print_jobs/", parts, on_finished = self._onPostPrintJobFinished, on_progress = self._onUploadPrintJobProgress)
开发者ID:rwreynolds,项目名称:Cura,代码行数:31,代码来源:ClusterUM3OutputDevice.py


示例16: handle_renegotiate

    def handle_renegotiate(self, packets):
        # type: (BaseConnection, Sequence[MsgPackable]) -> bool
        """The handler for connection renegotiations

        This is to deal with connection maintenance. For instance, it could
        be that a compression method fails to decode on the other end, and a
        node will need to renegotiate which methods it is using. Hence the
        name of the flag associated with it, "renegotiate".

        Args:
            packets:    A :py:class:`tuple` containing the packets received
                            in this message

        Returns:
            ``True`` if an action was taken, ``False`` if not
        """
        if packets[0] == flags.renegotiate:
            if packets[3] == flags.compression:
                encoded_methods = packets[4]
                respond = (self.compression != encoded_methods)
                self.compression = list(cast(Iterable[int], encoded_methods))
                self.__print__(
                    "Compression methods changed to: %s" %
                    repr(self.compression),
                    level=2)
                if respond:
                    self.send(flags.renegotiate, flags.compression,
                              cast(Tuple[int, ...],
                                   intersect(compression, self.compression)))
                return True
            elif packets[3] == flags.resend:
                self.send(*self.last_sent)
                return True
        return False
开发者ID:gappleto97,项目名称:p2p-project,代码行数:34,代码来源:base.py


示例17: process_doc

    def process_doc(self, app, doctree):
        # type: (Sphinx, nodes.document) -> None
        """Process the docinfo part of the doctree as metadata.

        Keep processing minimal -- just return what docutils says.
        """
        if len(doctree) > 0 and isinstance(doctree[0], nodes.docinfo):
            md = app.env.metadata[app.env.docname]
            for node in doctree[0]:
                # nodes are multiply inherited...
                if isinstance(node, nodes.authors):
                    authors = cast(List[nodes.author], node)
                    md['authors'] = [author.astext() for author in authors]
                elif isinstance(node, nodes.field):
                    assert len(node) == 2
                    field_name = cast(nodes.field_name, node[0])
                    field_body = cast(nodes.field_body, node[1])
                    md[field_name.astext()] = field_body.astext()
                elif isinstance(node, nodes.TextElement):
                    # other children must be TextElement
                    # see: http://docutils.sourceforge.net/docs/ref/doctree.html#bibliographic-elements  # NOQA
                    md[node.__class__.__name__] = node.astext()

            for name, value in md.items():
                if name in ('tocdepth',):
                    try:
                        value = int(value)
                    except ValueError:
                        value = 0
                    md[name] = value

            doctree.pop(0)
开发者ID:olivier-heurtier,项目名称:sphinx,代码行数:32,代码来源:metadata.py


示例18: async_step_init

    async def async_step_init(
            self, user_input: Optional[Dict[str, str]] = None) \
            -> Dict[str, Any]:
        """Handle the step of the form."""
        errors = {}

        hass_http = getattr(self.hass, 'http', None)
        if hass_http is None or not hass_http.api_password:
            return self.async_abort(
                reason='no_api_password_set'
            )

        if user_input is not None:
            try:
                cast(LegacyApiPasswordAuthProvider, self._auth_provider)\
                    .async_validate_login(user_input['password'])
            except InvalidAuthError:
                errors['base'] = 'invalid_auth'

            if not errors:
                return await self.async_finish({})

        return self.async_show_form(
            step_id='init',
            data_schema=vol.Schema({'password': str}),
            errors=errors,
        )
开发者ID:Martwall,项目名称:home-assistant,代码行数:27,代码来源:legacy_api_password.py


示例19: test_getTextName

    def test_getTextName(self, textPairs):
        # type: (Iterable[Tuple[Text, Text]]) -> None
        """
        C{getValues} returns an iterable of L{Text} values for
        the given L{Text} header name.

        This test only inserts Latin1 text into the header values, which is
        valid data.
        """
        textHeaders = tuple((name, value) for name, value in textPairs)

        textValues = defaultdict(list)  # type: Dict[Text, List[Text]]
        for name, value in textHeaders:
            textValues[normalizeHeaderName(name)].append(value)

        rawHeaders = tuple(
            (headerNameAsBytes(name), headerValueAsBytes(value))
            for name, value in textHeaders
        )

        for name, _values in textValues.items():
            cast(TestCase, self).assertEqual(
                list(self.getValues(rawHeaders, name)), _values,
                "header name: {!r}".format(name)
            )
开发者ID:notoriousno,项目名称:klein,代码行数:25,代码来源:test_headers.py


示例20: async_step_init

    async def async_step_init(
            self, user_input: Optional[Dict[str, str]] = None) \
            -> Dict[str, Any]:
        """Handle the step of the form."""
        errors = {}

        if user_input is not None:
            try:
                cast(ExampleAuthProvider, self._auth_provider)\
                    .async_validate_login(user_input['username'],
                                          user_input['password'])
            except InvalidAuthError:
                errors['base'] = 'invalid_auth'

            if not errors:
                user_input.pop('password')
                return await self.async_finish(user_input)

        schema = OrderedDict()  # type: Dict[str, type]
        schema['username'] = str
        schema['password'] = str

        return self.async_show_form(
            step_id='init',
            data_schema=vol.Schema(schema),
            errors=errors,
        )
开发者ID:EarthlingRich,项目名称:home-assistant,代码行数:27,代码来源:insecure_example.py



注:本文中的typing.cast函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python typing.get_type_hints函数代码示例发布时间:2022-05-27
下一篇:
Python currentVat.get函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap