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

Python maptype.map_instance_to_supertype函数代码示例

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

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



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

示例1: map_type_from_supertype

def map_type_from_supertype(typ: Type, sub_info: TypeInfo, super_info: TypeInfo) -> Type:
    """Map type variables in a type defined in a supertype context to be valid
    in the subtype context. Assume that the result is unique; if more than
    one type is possible, return one of the alternatives.

    For example, assume

    . class D(Generic[S]) ...
    . class C(D[E[T]], Generic[T]) ...

    Now S in the context of D would be mapped to E[T] in the context of C.
    """
    # Create the type of self in subtype, of form t[a1, ...].
    inst_type = self_type(sub_info)
    if isinstance(inst_type, TupleType):
        inst_type = inst_type.fallback
    # Map the type of self to supertype. This gets us a description of the
    # supertype type variables in terms of subtype variables, i.e. t[t1, ...]
    # so that any type variables in tN are to be interpreted in subtype
    # context.
    inst_type = map_instance_to_supertype(inst_type, super_info)
    # Finally expand the type variables in type with those in the previously
    # constructed type. Note that both type and inst_type may have type
    # variables, but in type they are interpreted in supertype context while
    # in inst_type they are interpreted in subtype context. This works even if
    # the names of type variables in supertype and subtype overlap.
    return expand_type_by_instance(typ, inst_type)
开发者ID:JdeH,项目名称:Transcrypt,代码行数:27,代码来源:checkmember.py


示例2: is_proper_subtype

def is_proper_subtype(t: Type, s: Type) -> bool:
    """Check if t is a proper subtype of s?

    For proper subtypes, there's no need to rely on compatibility due to
    Any types. Any instance type t is also a proper subtype of t.
    """
    # FIX tuple types
    if isinstance(t, Instance):
        if isinstance(s, Instance):
            if not t.type.has_base(s.type.fullname()):
                return False

            def check_argument(left: Type, right: Type, variance: int) -> bool:
                if variance == COVARIANT:
                    return is_proper_subtype(left, right)
                elif variance == CONTRAVARIANT:
                    return is_proper_subtype(right, left)
                else:
                    return sametypes.is_same_type(left, right)

            # Map left type to corresponding right instances.
            t = map_instance_to_supertype(t, s.type)

            return all(check_argument(ta, ra, tvar.variance) for ta, ra, tvar in
                       zip(t.args, s.args, s.type.defn.type_vars))
        return False
    else:
        return sametypes.is_same_type(t, s)
开发者ID:alexandrul,项目名称:mypy,代码行数:28,代码来源:subtypes.py


示例3: visit_instance

 def visit_instance(self, left: Instance) -> bool:
     if left.type.fallback_to_any:
         return True
     right = self.right
     if isinstance(right, TupleType) and right.fallback.type.is_enum:
         return is_subtype(left, right.fallback)
     if isinstance(right, Instance):
         if right.type.is_cached_subtype_check(left, right):
             return True
         # NOTE: left.type.mro may be None in quick mode if there
         # was an error somewhere.
         if left.type.mro is not None:
             for base in left.type.mro:
                 # TODO: Also pass recursively ignore_declared_variance
                 if base._promote and is_subtype(
                         base._promote, self.right, self.check_type_parameter,
                         ignore_pos_arg_names=self.ignore_pos_arg_names):
                     right.type.record_subtype_cache_entry(left, right)
                     return True
         rname = right.type.fullname()
         # Always try a nominal check if possible,
         # there might be errors that a user wants to silence *once*.
         if ((left.type.has_base(rname) or rname == 'builtins.object') and
                 not self.ignore_declared_variance):
             # Map left type to corresponding right instances.
             t = map_instance_to_supertype(left, right.type)
             nominal = all(self.check_type_parameter(lefta, righta, tvar.variance)
                           for lefta, righta, tvar in
                           zip(t.args, right.args, right.type.defn.type_vars))
             if nominal:
                 right.type.record_subtype_cache_entry(left, right)
             return nominal
         if right.type.is_protocol and is_protocol_implementation(left, right):
             return True
         return False
     if isinstance(right, TypeType):
         item = right.item
         if isinstance(item, TupleType):
             item = item.fallback
         if is_named_instance(left, 'builtins.type'):
             return is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right)
         if left.type.is_metaclass():
             if isinstance(item, AnyType):
                 return True
             if isinstance(item, Instance):
                 # Special-case enum since we don't have better way of expressing it
                 if (is_named_instance(left, 'enum.EnumMeta')
                         and is_named_instance(item, 'enum.Enum')):
                     return True
                 return is_named_instance(item, 'builtins.object')
     if isinstance(right, CallableType):
         # Special case: Instance can be a subtype of Callable.
         call = find_member('__call__', left, left)
         if call:
             return is_subtype(call, right)
         return False
     else:
         return False
开发者ID:greatmazinger,项目名称:mypy,代码行数:58,代码来源:subtypes.py


示例4: analyse_member_var_access

def analyse_member_var_access(name: str, itype: Instance, info: TypeInfo,
                              node: Context, is_lvalue: bool, is_super: bool,
                              msg: MessageBuilder,
                              report_type: Type = None) -> Type:
    """Analyse attribute access that does not target a method.

    This is logically part of analyse_member_access and the arguments are
    similar.
    """
    # It was not a method. Try looking up a variable.
    v = lookup_member_var_or_accessor(info, name, is_lvalue)

    vv = v
    if isinstance(vv, Decorator):
        # The associated Var node of a decorator contains the type.
        v = vv.var

    if isinstance(v, Var):
        # Found a member variable.
        var = v
        itype = map_instance_to_supertype(itype, var.info)
        if var.type:
            t = expand_type_by_instance(var.type, itype)
            if var.is_initialized_in_class and isinstance(t, FunctionLike):
                if is_lvalue:
                    if var.is_property:
                        msg.read_only_property(name, info, node)
                    else:
                        msg.cant_assign_to_method(node)

                if not var.is_staticmethod:
                    # Class-level function objects and classmethods become bound
                    # methods: the former to the instance, the latter to the
                    # class.
                    functype = cast(FunctionLike, t)
                    check_method_type(functype, itype, node, msg)
                    signature = method_type(functype)
                    if var.is_property:
                        # A property cannot have an overloaded type => the cast
                        # is fine.
                        return cast(Callable, signature).ret_type
                    else:
                        return signature
            return t
        else:
            if not var.is_ready:
                msg.cannot_determine_type(var.name(), node)
            # Implicit 'Any' type.
            return AnyType()
    elif isinstance(v, FuncDef):
        assert False, "Did not expect a function"

    # Could not find the member.
    if is_super:
        msg.undefined_in_superclass(name, node)
        return AnyType()
    else:
        return msg.has_no_attr(report_type or itype, name, node)
开发者ID:kivipe,项目名称:mypy,代码行数:58,代码来源:checkmember.py


示例5: visit_instance

 def visit_instance(self, template: Instance) -> List[Constraint]:
     actual = self.actual
     res = []  # type: List[Constraint]
     if isinstance(actual, Instance):
         instance = actual
         if (self.direction == SUBTYPE_OF and
                 template.type.has_base(instance.type.fullname())):
             mapped = map_instance_to_supertype(template, instance.type)
             for i in range(len(instance.args)):
                 # The constraints for generic type parameters are
                 # invariant. Include constraints from both directions
                 # to achieve the effect.
                 res.extend(infer_constraints(
                     mapped.args[i], instance.args[i], self.direction))
                 res.extend(infer_constraints(
                     mapped.args[i], instance.args[i], neg_op(self.direction)))
             return res
         elif (self.direction == SUPERTYPE_OF and
                 instance.type.has_base(template.type.fullname())):
             mapped = map_instance_to_supertype(instance, template.type)
             for j in range(len(template.args)):
                 # The constraints for generic type parameters are
                 # invariant.
                 res.extend(infer_constraints(
                     template.args[j], mapped.args[j], self.direction))
                 res.extend(infer_constraints(
                     template.args[j], mapped.args[j], neg_op(self.direction)))
             return res
     if isinstance(actual, AnyType):
         # IDEA: Include both ways, i.e. add negation as well?
         return self.infer_against_any(template.args)
     if (isinstance(actual, TupleType) and
         (is_named_instance(template, 'typing.Iterable') or
          is_named_instance(template, 'typing.Container') or
          is_named_instance(template, 'typing.Sequence') or
          is_named_instance(template, 'typing.Reversible'))
             and self.direction == SUPERTYPE_OF):
         for item in actual.items:
             cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
             res.extend(cb)
         return res
     else:
         return []
开发者ID:alexandrul,项目名称:mypy,代码行数:43,代码来源:constraints.py


示例6: _find_simplecdata_base_arg

def _find_simplecdata_base_arg(tp: Instance, api: 'mypy.plugin.CheckerPluginInterface'
                               ) -> Optional[Type]:
    """Try to find a parametrized _SimpleCData in tp's bases and return its single type argument.

    None is returned if _SimpleCData appears nowhere in tp's (direct or indirect) bases.
    """
    if tp.type.has_base('ctypes._SimpleCData'):
        simplecdata_base = map_instance_to_supertype(tp,
            api.named_generic_type('ctypes._SimpleCData', [AnyType(TypeOfAny.special_form)]).type)
        assert len(simplecdata_base.args) == 1, '_SimpleCData takes exactly one type argument'
        return simplecdata_base.args[0]
    return None
开发者ID:Michael0x2a,项目名称:mypy,代码行数:12,代码来源:ctypes.py


示例7: analyze_member_var_access

def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
                              node: Context, is_lvalue: bool, is_super: bool,
                              builtin_type: Callable[[str], Instance],
                              not_ready_callback: Callable[[str, Context], None],
                              msg: MessageBuilder,
                              original_type: Type,
                              chk: 'mypy.checker.TypeChecker' = None) -> Type:
    """Analyse attribute access that does not target a method.

    This is logically part of analyze_member_access and the arguments are similar.

    original_type is the type of E in the expression E.var
    """
    # It was not a method. Try looking up a variable.
    v = lookup_member_var_or_accessor(info, name, is_lvalue)

    vv = v
    if isinstance(vv, Decorator):
        # The associated Var node of a decorator contains the type.
        v = vv.var

    if isinstance(v, Var):
        return analyze_var(name, v, itype, info, node, is_lvalue, msg,
                           original_type, not_ready_callback)
    elif isinstance(v, FuncDef):
        assert False, "Did not expect a function"
    elif not v and name not in ['__getattr__', '__setattr__', '__getattribute__']:
        if not is_lvalue:
            for method_name in ('__getattribute__', '__getattr__'):
                method = info.get_method(method_name)
                # __getattribute__ is defined on builtins.object and returns Any, so without
                # the guard this search will always find object.__getattribute__ and conclude
                # that the attribute exists
                if method and method.info.fullname() != 'builtins.object':
                    function = function_type(method, builtin_type('builtins.function'))
                    bound_method = bind_self(function, original_type)
                    typ = map_instance_to_supertype(itype, method.info)
                    getattr_type = expand_type_by_instance(bound_method, typ)
                    if isinstance(getattr_type, CallableType):
                        return getattr_type.ret_type

    if itype.type.fallback_to_any:
        return AnyType()

    # Could not find the member.
    if is_super:
        msg.undefined_in_superclass(name, node)
        return AnyType()
    else:
        if chk and chk.should_suppress_optional_error([itype]):
            return AnyType()
        return msg.has_no_attr(original_type, name, node)
开发者ID:alexandrul,项目名称:mypy,代码行数:52,代码来源:checkmember.py


示例8: analyze_member_var_access

def analyze_member_var_access(
    name: str,
    itype: Instance,
    info: TypeInfo,
    node: Context,
    is_lvalue: bool,
    is_super: bool,
    builtin_type: Callable[[str], Instance],
    not_ready_callback: Callable[[str, Context], None],
    msg: MessageBuilder,
    report_type: Type = None,
    chk: "mypy.checker.TypeChecker" = None,
) -> Type:
    """Analyse attribute access that does not target a method.

    This is logically part of analyze_member_access and the arguments are
    similar.
    """
    # It was not a method. Try looking up a variable.
    v = lookup_member_var_or_accessor(info, name, is_lvalue)

    vv = v
    if isinstance(vv, Decorator):
        # The associated Var node of a decorator contains the type.
        v = vv.var
    if isinstance(v, Var):
        return analyze_var(name, v, itype, info, node, is_lvalue, msg, not_ready_callback)
    elif isinstance(v, FuncDef):
        assert False, "Did not expect a function"
    elif not v and name not in ["__getattr__", "__setattr__"]:
        if not is_lvalue:
            method = info.get_method("__getattr__")
            if method:
                typ = map_instance_to_supertype(itype, method.info)
                getattr_type = expand_type_by_instance(
                    method_type_with_fallback(method, builtin_type("builtins.function")), typ
                )
                if isinstance(getattr_type, CallableType):
                    return getattr_type.ret_type

    if itype.type.fallback_to_any:
        return AnyType()

    # Could not find the member.
    if is_super:
        msg.undefined_in_superclass(name, node)
        return AnyType()
    else:
        if chk and chk.should_suppress_optional_error([itype]):
            return AnyType()
        return msg.has_no_attr(report_type or itype, name, node)
开发者ID:JdeH,项目名称:Transcrypt,代码行数:51,代码来源:checkmember.py


示例9: analyze_var

def analyze_var(
    name: str,
    var: Var,
    itype: Instance,
    info: TypeInfo,
    node: Context,
    is_lvalue: bool,
    msg: MessageBuilder,
    not_ready_callback: Callable[[str, Context], None],
) -> Type:
    """Analyze access to an attribute via a Var node.

    This is conceptually part of analyze_member_access and the arguments are similar.
    """
    # Found a member variable.
    itype = map_instance_to_supertype(itype, var.info)
    typ = var.type
    if typ:
        if isinstance(typ, PartialType):
            return handle_partial_attribute_type(typ, is_lvalue, msg, var)
        t = expand_type_by_instance(typ, itype)
        if is_lvalue and var.is_property and not var.is_settable_property:
            # TODO allow setting attributes in subclass (although it is probably an error)
            msg.read_only_property(name, info, node)
        if var.is_initialized_in_class and isinstance(t, FunctionLike):
            if is_lvalue:
                if var.is_property:
                    if not var.is_settable_property:
                        msg.read_only_property(name, info, node)
                else:
                    msg.cant_assign_to_method(node)

            if not var.is_staticmethod:
                # Class-level function objects and classmethods become bound
                # methods: the former to the instance, the latter to the
                # class.
                functype = t
                check_method_type(functype, itype, var.is_classmethod, node, msg)
                signature = method_type(functype)
                if var.is_property:
                    # A property cannot have an overloaded type => the cast
                    # is fine.
                    return cast(CallableType, signature).ret_type
                else:
                    return signature
        return t
    else:
        if not var.is_ready:
            not_ready_callback(var.name(), node)
        # Implicit 'Any' type.
        return AnyType()
开发者ID:JdeH,项目名称:Transcrypt,代码行数:51,代码来源:checkmember.py


示例10: join_instances_via_supertype

def join_instances_via_supertype(t: Instance, s: Instance) -> Type:
    # Give preference to joins via duck typing relationship, so that
    # join(int, float) == float, for example.
    if t.type._promote and is_subtype(t.type._promote, s):
        return join_types(t.type._promote, s)
    elif s.type._promote and is_subtype(s.type._promote, t):
        return join_types(t, s.type._promote)
    res = s
    mapped = map_instance_to_supertype(t, t.type.bases[0].type)
    join = join_instances(mapped, res)
    # If the join failed, fail. This is a defensive measure (this might
    # never happen).
    if isinstance(join, ErrorType):
        return join
    # Now the result must be an Instance, so the cast below cannot fail.
    res = cast(Instance, join)
    return res
开发者ID:FaithBradley200,项目名称:mypy,代码行数:17,代码来源:join.py


示例11: analyze_instance_member_access

def analyze_instance_member_access(name: str,
                                   typ: Instance,
                                   mx: MemberContext,
                                   override_info: Optional[TypeInfo]) -> Type:
    if name == '__init__' and not mx.is_super:
        # Accessing __init__ in statically typed code would compromise
        # type safety unless used via super().
        mx.msg.fail(message_registry.CANNOT_ACCESS_INIT, mx.context)
        return AnyType(TypeOfAny.from_error)

    # The base object has an instance type.

    info = typ.type
    if override_info:
        info = override_info

    if (state.find_occurrences and
            info.name() == state.find_occurrences[0] and
            name == state.find_occurrences[1]):
        mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context)

    # Look up the member. First look up the method dictionary.
    method = info.get_method(name)
    if method:
        if method.is_property:
            assert isinstance(method, OverloadedFuncDef)
            first_item = cast(Decorator, method.items[0])
            return analyze_var(name, first_item.var, typ, info, mx)
        if mx.is_lvalue:
            mx.msg.cant_assign_to_method(mx.context)
        signature = function_type(method, mx.builtin_type('builtins.function'))
        signature = freshen_function_type_vars(signature)
        if name == '__new__':
            # __new__ is special and behaves like a static method -- don't strip
            # the first argument.
            pass
        else:
            signature = bind_self(signature, mx.original_type)
        typ = map_instance_to_supertype(typ, method.info)
        member_type = expand_type_by_instance(signature, typ)
        freeze_type_vars(member_type)
        return member_type
    else:
        # Not a method.
        return analyze_member_var_access(name, typ, info, mx)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:45,代码来源:checkmember.py


示例12: visit_instance

    def visit_instance(self, left: Instance) -> bool:
        right = self.right
        if isinstance(right, Instance):
            if left.type._promote and is_subtype(left.type._promote, self.right, self.check_type_parameter):
                return True
            rname = right.type.fullname()
            if not left.type.has_base(rname) and rname != "builtins.object":
                return False

            # Map left type to corresponding right instances.
            t = map_instance_to_supertype(left, right.type)

            return all(
                self.check_type_parameter(lefta, righta, tvar.variance)
                for lefta, righta, tvar in zip(t.args, right.args, right.type.defn.type_vars)
            )
        else:
            return False
开发者ID:nierob,项目名称:mypy,代码行数:18,代码来源:subtypes.py


示例13: join_instances_via_supertype

def join_instances_via_supertype(t: Instance, s: Instance) -> Type:
    # Give preference to joins via duck typing relationship, so that
    # join(int, float) == float, for example.
    if t.type._promote and is_subtype(t.type._promote, s):
        return join_types(t.type._promote, s)
    elif s.type._promote and is_subtype(s.type._promote, t):
        return join_types(t, s.type._promote)
    # Compute the "best" supertype of t when joined with s.
    # The definition of "best" may evolve; for now it is the one with
    # the longest MRO.  Ties are broken by using the earlier base.
    best = None  # type: Type
    for base in t.type.bases:
        mapped = map_instance_to_supertype(t, base.type)
        res = join_instances(mapped, s)
        if best is None or is_better(res, best):
            best = res
    assert best is not None
    return best
开发者ID:ChaiYuanUMN,项目名称:mypy,代码行数:18,代码来源:join.py


示例14: visit_instance

    def visit_instance(self, left: Instance) -> bool:
        right = self.right
        if isinstance(right, Instance):
            if left.type._promote and is_subtype(left.type._promote,
                                                 self.right):
                return True
            rname = right.type.fullname()
            if not left.type.has_base(rname) and rname != 'builtins.object':
                return False

            # Map left type to corresponding right instances.
            t = map_instance_to_supertype(left, right.type)
            if not is_immutable(right):
                result = all(is_equivalent(ta, ra) for (ta, ra) in
                             zip(t.args, right.args))
            else:
                result = all(is_subtype(ta, ra) for (ta, ra) in
                             zip(t.args, right.args))
            return result
        else:
            return False
开发者ID:noisecapella,项目名称:mypy,代码行数:21,代码来源:subtypes.py


示例15: is_proper_subtype

def is_proper_subtype(t: Type, s: Type) -> bool:
    """Check if t is a proper subtype of s?

    For proper subtypes, there's no need to rely on compatibility due to
    Any types. Any instance type t is also a proper subtype of t.
    """
    # FIX tuple types
    if isinstance(t, Instance):
        if isinstance(s, Instance):
            if not t.type.has_base(s.type.fullname()):
                return False
            t = map_instance_to_supertype(t, s.type)
            if not is_immutable(s):
                return all(sametypes.is_same_type(ta, ra) for (ta, ra) in
                           zip(t.args, s.args))
            else:
                return all(is_proper_subtype(ta, ra) for (ta, ra) in
                           zip(t.args, s.args))
        return False
    else:
        return sametypes.is_same_type(t, s)
开发者ID:noisecapella,项目名称:mypy,代码行数:21,代码来源:subtypes.py


示例16: analyze_var

def analyze_var(
    name: str, var: Var, itype: Instance, info: TypeInfo, node: Context, is_lvalue: bool, msg: MessageBuilder
) -> Type:
    """Analyze access to an attribute via a Var node.

    This is conceptually part of analyze_member_access and the arguments are similar.
    """
    # Found a member variable.
    itype = map_instance_to_supertype(itype, var.info)
    if var.type:
        t = expand_type_by_instance(var.type, itype)
        if var.is_initialized_in_class and isinstance(t, FunctionLike):
            if is_lvalue:
                if var.is_property:
                    if not var.is_settable_property:
                        msg.read_only_property(name, info, node)
                else:
                    msg.cant_assign_to_method(node)

            if not var.is_staticmethod:
                # Class-level function objects and classmethods become bound
                # methods: the former to the instance, the latter to the
                # class.
                functype = cast(FunctionLike, t)
                check_method_type(functype, itype, node, msg)
                signature = method_type(functype)
                if var.is_property:
                    # A property cannot have an overloaded type => the cast
                    # is fine.
                    return cast(CallableType, signature).ret_type
                else:
                    return signature
        return t
    else:
        if not var.is_ready:
            msg.cannot_determine_type(var.name(), node)
        # Implicit 'Any' type.
        return AnyType()
开发者ID:jdiglesias,项目名称:mypy,代码行数:38,代码来源:checkmember.py


示例17: visit_instance

    def visit_instance(self, left: Instance) -> bool:
        if left.type.fallback_to_any:
            return True
        right = self.right
        if isinstance(right, TupleType) and right.fallback.type.is_enum:
            return is_subtype(left, right.fallback)
        if isinstance(right, Instance):
            if left.type._promote and is_subtype(
                    left.type._promote, self.right, self.check_type_parameter,
                    ignore_pos_arg_names=self.ignore_pos_arg_names):
                return True
            rname = right.type.fullname()
            if not left.type.has_base(rname) and rname != 'builtins.object':
                return False

            # Map left type to corresponding right instances.
            t = map_instance_to_supertype(left, right.type)

            return all(self.check_type_parameter(lefta, righta, tvar.variance)
                       for lefta, righta, tvar in
                       zip(t.args, right.args, right.type.defn.type_vars))
        else:
            return False
开发者ID:alexandrul,项目名称:mypy,代码行数:23,代码来源:subtypes.py


示例18: find_node_type

def find_node_type(node: Union[Var, FuncBase], itype: Instance, subtype: Type) -> Type:
    """Find type of a variable or method 'node' (maybe also a decorated method).
    Apply type arguments from 'itype', and bind 'self' to 'subtype'.
    """
    from mypy.checkmember import bind_self
    if isinstance(node, FuncBase):
        typ = function_type(node,
                            fallback=Instance(itype.type.mro[-1], []))  # type: Optional[Type]
    else:
        typ = node.type
    if typ is None:
        return AnyType(TypeOfAny.from_error)
    # We don't need to bind 'self' for static methods, since there is no 'self'.
    if isinstance(node, FuncBase) or isinstance(typ, FunctionLike) and not node.is_staticmethod:
        assert isinstance(typ, FunctionLike)
        signature = bind_self(typ, subtype)
        if node.is_property:
            assert isinstance(signature, CallableType)
            typ = signature.ret_type
        else:
            typ = signature
    itype = map_instance_to_supertype(itype, node.info)
    typ = expand_type_by_instance(typ, itype)
    return typ
开发者ID:greatmazinger,项目名称:mypy,代码行数:24,代码来源:subtypes.py


示例19: analyse_member_access

def analyse_member_access(name: str, typ: Type, node: Context, is_lvalue: bool,
                          is_super: bool,
                          builtin_type: Function[[str], Instance],
                          msg: MessageBuilder, override_info: TypeInfo = None,
                          report_type: Type = None) -> Type:
    """Analyse attribute access.

    This is a general operation that supports various different variations:

      1. lvalue or non-lvalue access (i.e. setter or getter access)
      2. supertype access (when using super(); is_super == True and
         override_info should refer to the supertype)
    """
    report_type = report_type or typ
    if isinstance(typ, Instance):
        if name == '__init__' and not is_super:
            # Accessing __init__ in statically typed code would compromise
            # type safety unless used via super().
            msg.fail(messages.CANNOT_ACCESS_INIT, node)
            return AnyType()

        # The base object has an instance type.

        info = typ.type
        if override_info:
            info = override_info

        # Look up the member. First look up the method dictionary.
        method = info.get_method(name)
        if method:
            if is_lvalue:
                msg.cant_assign_to_method(node)
            typ = map_instance_to_supertype(typ, method.info)
            return expand_type_by_instance(
                method_type(method, builtin_type('builtins.function')), typ)
        else:
            # Not a method.
            return analyse_member_var_access(name, typ, info, node,
                                             is_lvalue, is_super, msg,
                                             report_type=report_type)
    elif isinstance(typ, AnyType):
        # The base object has dynamic type.
        return AnyType()
    elif isinstance(typ, UnionType):
        # The base object has dynamic type.
        msg.disable_type_names += 1
        results = [analyse_member_access(name, subtype, node, is_lvalue,
                                         is_super, builtin_type, msg)
                   for subtype in typ.items]
        msg.disable_type_names -= 1
        return UnionType.make_simplified_union(results)
    elif isinstance(typ, TupleType):
        # Actually look up from the fallback instance type.
        return analyse_member_access(name, typ.fallback, node, is_lvalue,
                                     is_super, builtin_type, msg)
    elif (isinstance(typ, FunctionLike) and
          cast(FunctionLike, typ).is_type_obj()):
        # Class attribute.
        # TODO super?
        sig = cast(FunctionLike, typ)
        itype = cast(Instance, sig.items()[0].ret_type)
        result = analyse_class_attribute_access(itype, name, node, is_lvalue, builtin_type, msg)
        if result:
            return result
        # Look up from the 'type' type.
        return analyse_member_access(name, sig.fallback, node, is_lvalue, is_super,
                                     builtin_type, msg, report_type=report_type)
    elif isinstance(typ, FunctionLike):
        # Look up from the 'function' type.
        return analyse_member_access(name, typ.fallback, node, is_lvalue, is_super,
                                     builtin_type, msg, report_type=report_type)
    return msg.has_no_attr(report_type, name, node)
开发者ID:kivipe,项目名称:mypy,代码行数:72,代码来源:checkmember.py


示例20: analyze_member_access

def analyze_member_access(
    name: str,
    typ: Type,
    node: Context,
    is_lvalue: bool,
    is_super: bool,
    is_operator: bool,
    builtin_type: Callable[[str], Instance],
    not_ready_callback: Callable[[str, Context], None],
    msg: MessageBuilder,
    override_info: TypeInfo = None,
    report_type: Type = None,
    chk: "mypy.checker.TypeChecker" = None,
) -> Type:
    """Analyse attribute access.

    This is a general operation that supports various different variations:

      1. lvalue or non-lvalue access (i.e. setter or getter access)
      2. supertype access (when using super(); is_super == True and
         override_info should refer to the supertype)
    """
    report_type = report_type or typ
    if isinstance(typ, Instance):
        if name == "__init__" and not is_super:
            # Accessing __init__ in statically typed code would compromise
            # type safety unless used via super().
            msg.fail(messages.CANNOT_ACCESS_INIT, node)
            return AnyType()

        # The base object has an instance type.

        info = typ.type
        if override_info:
            info = override_info

        # Look up the member. First look up the method dictionary.
        method = info.get_method(name)
        if method:
            if method.is_property:
                assert isinstance(method, OverloadedFuncDef)
                return analyze_var(name, method.items[0].var, typ, info, node, is_lvalue, msg, not_ready_callback)
            if is_lvalue:
                msg.cant_assign_to_method(node)
            typ = map_instance_to_supertype(typ, method.info)
            if name == "__new__":
                # __new__ is special and behaves like a static method -- don't strip
                # the first argument.
                signature = function_type(method, builtin_type("builtins.function"))
            else:
                signature = method_type_with_fallback(method, builtin_type("builtins.function"))
            return expand_type_by_instance(signature, typ)
        else:
            # Not a method.
            return analyze_member_var_access(
                name,
                typ,
                info,
                node,
                is_lvalue,
                is_super,
                builtin_type,
                not_ready_callback,
                msg,
                report_type=report_type,
                chk=chk,
            )
    elif isinstance(typ, AnyType):
        # The base object has dynamic type.
        return AnyType()
    elif isinstance(typ, NoneTyp):
        if chk and chk.should_suppress_optional_error([typ]):
            return AnyType()
        # The only attribute NoneType has are those it inherits from object
        return analyze_member_access(
            name,
            builtin_type("builtins.object"),
            node,
            is_lvalue,
            is_super,
            is_operator,
            builtin_type,
            not_ready_callback,
            msg,
            report_type=report_type,
            chk=chk,
        )
    elif isinstance(typ, UnionType):
        # The base object has dynamic type.
        msg.disable_type_names += 1
        results = [
            analyze_member_access(
                name, subtype, node, is_lvalue, is_super, is_operator, builtin_type, not_ready_callback, msg, chk=chk
            )
            for subtype in typ.items
        ]
        msg.disable_type_names -= 1
        return UnionType.make_simplified_union(results)
    elif isinstance(typ, TupleType):
        # Actually look up from the fallback instance type.
#.........这里部分代码省略.........
开发者ID:JdeH,项目名称:Transcrypt,代码行数:101,代码来源:checkmember.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python messages.MessageBuilder类代码示例发布时间:2022-05-27
下一篇:
Python expandtype.expand_type_by_instance函数代码示例发布时间: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