当前位置: 首页>>代码示例>>Python>>正文


Python MessageBuilder.fail方法代码示例

本文整理汇总了Python中mypy.messages.MessageBuilder.fail方法的典型用法代码示例。如果您正苦于以下问题:Python MessageBuilder.fail方法的具体用法?Python MessageBuilder.fail怎么用?Python MessageBuilder.fail使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mypy.messages.MessageBuilder的用法示例。


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

示例1: analyze_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_class_attribute_access(itype: Instance,
                                   name: str,
                                   context: Context,
                                   is_lvalue: bool,
                                   builtin_type: Callable[[str], Instance],
                                   msg: MessageBuilder) -> Type:
    node = itype.type.get(name)
    if not node:
        return None

    is_decorated = isinstance(node.node, Decorator)
    is_method = is_decorated or isinstance(node.node, FuncDef)
    if is_lvalue:
        if is_method:
            msg.cant_assign_to_method(context)
        if isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)

    if itype.type.is_enum and not (is_lvalue or is_decorated or is_method):
        return itype

    t = node.type
    if t:
        is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
        return add_class_tvars(t, itype.type, is_classmethod, builtin_type)

    if isinstance(node.node, TypeInfo):
        return type_object_type(cast(TypeInfo, node.node), builtin_type)

    return function_type(cast(FuncBase, node.node), builtin_type('builtins.function'))
开发者ID:narusemotoki,项目名称:mypy,代码行数:32,代码来源:checkmember.py

示例2: analyse_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyse_class_attribute_access(itype: Instance, name: str,
                                   context: Context, is_lvalue: bool,
                                   msg: MessageBuilder) -> Type:
    node = itype.type.get(name)
    if not node:
        return None

    is_decorated = isinstance(node.node, Decorator)
    is_method = is_decorated or isinstance(node.node, FuncDef)
    if is_lvalue:
        if is_method:
            msg.cant_assign_to_method(context)
        if isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)

    t = node.type
    if t:
        is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
        return add_class_tvars(t, itype.type, is_classmethod)

    if isinstance(node.node, TypeInfo):
        # TODO add second argument
        return type_object_type(cast(TypeInfo, node.node), None)

    return function_type(cast(FuncBase, node.node))
开发者ID:mvcisback,项目名称:mypy,代码行数:27,代码来源:checkmember.py

示例3: handle_partial_attribute_type

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def handle_partial_attribute_type(typ: PartialType, is_lvalue: bool, msg: MessageBuilder, context: Context) -> Type:
    if typ.type is None:
        # 'None' partial type. It has a well-defined type -- 'None'.
        # In an lvalue context we want to preserver the knowledge of
        # it being a partial type.
        if not is_lvalue:
            return NoneTyp()
        return typ
    else:
        msg.fail(messages.NEED_ANNOTATION_FOR_VAR, context)
        return AnyType()
开发者ID:JdeH,项目名称:Transcrypt,代码行数:13,代码来源:checkmember.py

示例4: analyze_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_class_attribute_access(itype: Instance,
                                   name: str,
                                   context: Context,
                                   is_lvalue: bool,
                                   builtin_type: Callable[[str], Instance],
                                   not_ready_callback: Callable[[str, Context], None],
                                   msg: MessageBuilder,
                                   original_type: Type) -> Type:
    """original_type is the type of E in the expression E.var"""
    node = itype.type.get(name)
    if not node:
        if itype.type.fallback_to_any:
            return AnyType()
        return None

    is_decorated = isinstance(node.node, Decorator)
    is_method = is_decorated or isinstance(node.node, FuncDef)
    if is_lvalue:
        if is_method:
            msg.cant_assign_to_method(context)
        if isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)

    if itype.type.is_enum and not (is_lvalue or is_decorated or is_method):
        return itype

    t = node.type
    if t:
        if isinstance(t, PartialType):
            return handle_partial_attribute_type(t, is_lvalue, msg, node.node)
        is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
        return add_class_tvars(t, itype, is_classmethod, builtin_type, original_type)
    elif isinstance(node.node, Var):
        not_ready_callback(name, context)
        return AnyType()

    if isinstance(node.node, TypeVarExpr):
        return TypeVarType(node.tvar_def, node.tvar_def.line, node.tvar_def.column)

    if isinstance(node.node, TypeInfo):
        return type_object_type(node.node, builtin_type)

    if isinstance(node.node, MypyFile):
        # Reference to a module object.
        return builtin_type('builtins.module')

    if is_decorated:
        # TODO: Return type of decorated function. This is quick hack to work around #998.
        return AnyType()
    else:
        return function_type(cast(FuncBase, node.node), builtin_type('builtins.function'))
开发者ID:rowillia,项目名称:mypy,代码行数:53,代码来源:checkmember.py

示例5: analyse_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyse_class_attribute_access(itype: Instance, name: str,
                                   context: Context, is_lvalue: bool,
                                   msg: MessageBuilder) -> Type:
    node = itype.type.get(name)
    if node:
        if is_lvalue and isinstance(node.node, FuncDef):
            msg.fail(messages.CANNOT_ASSIGN_TO_METHOD, context)
        if is_lvalue and isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)
        t = node.type
        if t:
            return add_class_tvars(t, itype.type)
        elif isinstance(node.node, TypeInfo):
            # TODO add second argument
            return type_object_type(cast(TypeInfo, node.node), None)
        else:
            return function_type(cast(FuncBase, node.node))
    else:
        return None
开发者ID:bogdan-kulynych,项目名称:mypy,代码行数:21,代码来源:checkmember.py

示例6: analyze_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_class_attribute_access(
    itype: Instance,
    name: str,
    context: Context,
    is_lvalue: bool,
    builtin_type: Callable[[str], Instance],
    not_ready_callback: Callable[[str, Context], None],
    msg: MessageBuilder,
) -> Type:
    node = itype.type.get(name)
    if not node:
        if itype.type.fallback_to_any:
            return AnyType()
        return None

    is_decorated = isinstance(node.node, Decorator)
    is_method = is_decorated or isinstance(node.node, FuncDef)
    if is_lvalue:
        if is_method:
            msg.cant_assign_to_method(context)
        if isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)

    if itype.type.is_enum and not (is_lvalue or is_decorated or is_method):
        return itype

    t = node.type
    if t:
        is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
        return add_class_tvars(t, itype.type, is_classmethod, builtin_type)
    elif isinstance(node.node, Var):
        not_ready_callback(name, context)
        return AnyType()

    if isinstance(node.node, TypeInfo):
        return type_object_type(cast(TypeInfo, node.node), builtin_type)

    if is_decorated:
        # TODO: Return type of decorated function. This is quick hack to work around #998.
        return AnyType()
    else:
        return function_type(cast(FuncBase, node.node), builtin_type("builtins.function"))
开发者ID:Carreau,项目名称:mypy,代码行数:44,代码来源:checkmember.py

示例7: analyze_class_attribute_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_class_attribute_access(itype: Instance,
                                   name: str,
                                   context: Context,
                                   is_lvalue: bool,
                                   builtin_type: Callable[[str], Instance],
                                   not_ready_callback: Callable[[str, Context], None],
                                   msg: MessageBuilder,
                                   original_type: Type) -> Optional[Type]:
    """original_type is the type of E in the expression E.var"""
    node = itype.type.get(name)
    if not node:
        if itype.type.fallback_to_any:
            return AnyType(TypeOfAny.special_form)
        return None

    is_decorated = isinstance(node.node, Decorator)
    is_method = is_decorated or isinstance(node.node, FuncDef)
    if is_lvalue:
        if is_method:
            msg.cant_assign_to_method(context)
        if isinstance(node.node, TypeInfo):
            msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context)

    if itype.type.is_enum and not (is_lvalue or is_decorated or is_method):
        return itype

    t = node.type
    if t:
        if isinstance(t, PartialType):
            symnode = node.node
            assert symnode is not None
            return handle_partial_attribute_type(t, is_lvalue, msg, symnode)
        if not is_method and (isinstance(t, TypeVarType) or get_type_vars(t)):
            msg.fail(messages.GENERIC_INSTANCE_VAR_CLASS_ACCESS, context)
        is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class
        return add_class_tvars(t, itype, is_classmethod, builtin_type, original_type)
    elif isinstance(node.node, Var):
        not_ready_callback(name, context)
        return AnyType(TypeOfAny.special_form)

    if isinstance(node.node, TypeVarExpr):
        msg.fail('Type variable "{}.{}" cannot be used as an expression'.format(
                 itype.type.name(), name), context)
        return AnyType(TypeOfAny.from_error)

    if isinstance(node.node, TypeInfo):
        return type_object_type(node.node, builtin_type)

    if isinstance(node.node, MypyFile):
        # Reference to a module object.
        return builtin_type('types.ModuleType')

    if is_decorated:
        # TODO: Return type of decorated function. This is quick hack to work around #998.
        return AnyType(TypeOfAny.special_form)
    else:
        return function_type(cast(FuncBase, node.node), builtin_type('builtins.function'))
开发者ID:greatmazinger,项目名称:mypy,代码行数:59,代码来源:checkmember.py

示例8: analyze_member_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
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,代码行数:103,代码来源:checkmember.py

示例9: analyze_descriptor_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_descriptor_access(instance_type: Type,
                              descriptor_type: Type,
                              builtin_type: Callable[[str], Instance],
                              msg: MessageBuilder,
                              context: Context, *,
                              chk: 'mypy.checker.TypeChecker') -> Type:
    """Type check descriptor access.

    Arguments:
        instance_type: The type of the instance on which the descriptor
            attribute is being accessed (the type of ``a`` in ``a.f`` when
            ``f`` is a descriptor).
        descriptor_type: The type of the descriptor attribute being accessed
            (the type of ``f`` in ``a.f`` when ``f`` is a descriptor).
        context: The node defining the context of this inference.
    Return:
        The return type of the appropriate ``__get__`` overload for the descriptor.
    """
    if isinstance(descriptor_type, UnionType):
        # Map the access over union types
        return UnionType.make_simplified_union([
            analyze_descriptor_access(instance_type, typ, builtin_type,
                                      msg, context, chk=chk)
            for typ in descriptor_type.items
        ])
    elif not isinstance(descriptor_type, Instance):
        return descriptor_type

    if not descriptor_type.type.has_readable_member('__get__'):
        return descriptor_type

    dunder_get = descriptor_type.type.get_method('__get__')

    if dunder_get is None:
        msg.fail(message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(descriptor_type), context)
        return AnyType(TypeOfAny.from_error)

    function = function_type(dunder_get, builtin_type('builtins.function'))
    bound_method = bind_self(function, descriptor_type)
    typ = map_instance_to_supertype(descriptor_type, dunder_get.info)
    dunder_get_type = expand_type_by_instance(bound_method, typ)

    if isinstance(instance_type, FunctionLike) and instance_type.is_type_obj():
        owner_type = instance_type.items()[0].ret_type
        instance_type = NoneTyp()
    elif isinstance(instance_type, TypeType):
        owner_type = instance_type.item
        instance_type = NoneTyp()
    else:
        owner_type = instance_type

    _, inferred_dunder_get_type = chk.expr_checker.check_call(
        dunder_get_type,
        [TempNode(instance_type), TempNode(TypeType.make_normalized(owner_type))],
        [ARG_POS, ARG_POS], context)

    if isinstance(inferred_dunder_get_type, AnyType):
        # check_call failed, and will have reported an error
        return inferred_dunder_get_type

    if not isinstance(inferred_dunder_get_type, CallableType):
        msg.fail(message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(descriptor_type), context)
        return AnyType(TypeOfAny.from_error)

    return inferred_dunder_get_type.ret_type
开发者ID:Michael0x2a,项目名称:mypy,代码行数:67,代码来源:checkmember.py

示例10: analyze_member_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
def analyze_member_access(name: str, typ: Type, node: Context, is_lvalue: bool,
                          is_super: bool,
                          builtin_type: Callable[[str], Instance],
                          not_ready_callback: Callable[[str, Context], None],
                          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 method.is_property:
                assert isinstance(method, OverloadedFuncDef)
                method = cast(OverloadedFuncDef, method)
                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)
    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 = [analyze_member_access(name, subtype, node, is_lvalue,
                                         is_super, builtin_type, not_ready_callback, 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 analyze_member_access(name, typ.fallback, node, is_lvalue,
                                     is_super, builtin_type, not_ready_callback, msg)
    elif isinstance(typ, FunctionLike) and typ.is_type_obj():
        # Class attribute.
        # TODO super?
        ret_type = typ.items()[0].ret_type
        if isinstance(ret_type, TupleType):
            ret_type = ret_type.fallback
        if isinstance(ret_type, Instance):
            result = analyze_class_attribute_access(ret_type, name, node, is_lvalue,
                                                    builtin_type, not_ready_callback, msg)
            if result:
                return result
            # Look up from the 'type' type.
            return analyze_member_access(name, typ.fallback, node, is_lvalue, is_super,
                                         builtin_type, not_ready_callback, msg,
                                         report_type=report_type)
        else:
            assert False, 'Unexpected type {}'.format(repr(ret_type))
    elif isinstance(typ, FunctionLike):
        # Look up from the 'function' type.
        return analyze_member_access(name, typ.fallback, node, is_lvalue, is_super,
                                     builtin_type, not_ready_callback, msg,
                                     report_type=report_type)
    elif isinstance(typ, TypeVarType):
        return analyze_member_access(name, typ.upper_bound, node, is_lvalue, is_super,
                                     builtin_type, not_ready_callback, msg,
                                     report_type=report_type)
    elif isinstance(typ, DeletedType):
        msg.deleted_as_rvalue(typ, node)
        return AnyType()
    return msg.has_no_attr(report_type, name, node)
开发者ID:ChaiYuanUMN,项目名称:mypy,代码行数:99,代码来源:checkmember.py

示例11: analyze_member_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
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, *,
                          original_type: Type,
                          chk: 'mypy.checker.TypeChecker',
                          override_info: Optional[TypeInfo] = None) -> Type:
    """Return the type of attribute `name` of typ.

    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)

    original_type is the most precise inferred or declared type of the base object
    that we have available. typ is generally a supertype of original_type.
    When looking for an attribute of typ, we may perform recursive calls targeting
    the fallback type, for example.
    original_type is always the type used in the initial call.
    """
    # TODO: this and following functions share some logic with subtypes.find_member,
    # consider refactoring.
    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(TypeOfAny.from_error)

        # The base object has an instance type.

        info = typ.type
        if override_info:
            info = override_info

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

        # 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, node, is_lvalue, msg,
                                   original_type, not_ready_callback, chk=chk)
            if is_lvalue:
                msg.cant_assign_to_method(node)
            signature = function_type(method, 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, 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, node,
                                             is_lvalue, is_super, builtin_type,
                                             not_ready_callback, msg,
                                             original_type=original_type, chk=chk)
    elif isinstance(typ, AnyType):
        # The base object has dynamic type.
        return AnyType(TypeOfAny.from_another_any, source_any=typ)
    elif isinstance(typ, NoneTyp):
        if chk.should_suppress_optional_error([typ]):
            return AnyType(TypeOfAny.from_error)
        # 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,
                                     original_type=original_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,
                                         original_type=original_type, chk=chk)
                   for subtype in typ.relevant_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 analyze_member_access(name, typ.fallback, node, is_lvalue, is_super,
                                     is_operator, builtin_type, not_ready_callback, msg,
                                     original_type=original_type, chk=chk)
    elif isinstance(typ, TypedDictType):
        # Actually look up from the fallback instance type.
#.........这里部分代码省略.........
开发者ID:sixolet,项目名称:mypy,代码行数:103,代码来源:checkmember.py

示例12: analyse_member_access

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
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,代码行数:74,代码来源:checkmember.py

示例13: TypeChecker

# 需要导入模块: from mypy.messages import MessageBuilder [as 别名]
# 或者: from mypy.messages.MessageBuilder import fail [as 别名]
class TypeChecker(NodeVisitor):
    """Mypy type checker.

    Type check mypy source files that have been semantically analysed.
    """
    
    errors = None          # Error message reporting
    symtable = None   # Symbol table for the whole program
    msg = None     # Utility for generating messages
    type_map = None  # Types of type checked nodes
    expr_checker = None
    
    stack = None # Stack of local variable definitions
                # None separates nested functions
    return_types = None  # Stack of function return types
    type_context = None  # Type context for type inference
    dynamic_funcs = None # Flags; true for dynamically typed functions
    
    globals = None
    class_tvars = None
    locals = None
    modules = None
    
    def __init__(self, errors, modules):
        """Construct a type checker.

        Use errors to report type check errors. Assume symtable has been
        populated by the semantic analyzer.
        """
        self.expr_checker
        self.errors = errors
        self.modules = modules
        self.msg = MessageBuilder(errors)
        self.type_map = {}
        self.expr_checker = mypy.checkexpr.ExpressionChecker(self, self.msg)
        self.stack = [None]
        self.return_types = []
        self.type_context = []
        self.dynamic_funcs = []
    
    def visit_file(self, file_node, path):  
        """Type check a mypy file with the given path."""
        self.errors.set_file(path)
        self.globals = file_node.names
        self.locals = None
        self.class_tvars = None
        
        for d in file_node.defs:
            self.accept(d)
    
    def accept(self, node, type_context=None):
        """Type check a node in the given type context."""
        self.type_context.append(type_context)
        typ = node.accept(self)
        self.type_context.pop()
        self.store_type(node, typ)
        if self.is_dynamic_function():
            return Any()
        else:
            return typ
    
    #
    # Definitions
    #
    
    def visit_var_def(self, defn):
        """Type check a variable definition.

        It can be of any kind: local, member or global.
        """
        # Type check initializer.
        if defn.init:
            # There is an initializer.
            if defn.items[0].type:
                # Explicit types.
                if len(defn.items) == 1:
                    self.check_single_assignment(defn.items[0].type, None,
                                                 defn.init, defn.init)
                else:
                    # Multiple assignment.
                    lvt = []
                    for v in defn.items:
                        lvt.append(v.type)
                    self.check_multi_assignment(
                        lvt, [None] * len(lvt),
                        defn.init, defn.init)
            else:
                init_type = self.accept(defn.init)
                if defn.kind == LDEF and not defn.is_top_level:
                    # Infer local variable type if there is an initializer
                    # except if the# definition is at the top level (outside a
                    # function).
                    self.infer_local_variable_type(defn.items, init_type, defn)
        else:
            # No initializer
            if (defn.kind == LDEF and not defn.items[0].type and
                    not defn.is_top_level and not self.is_dynamic_function()):
                self.fail(messages.NEED_ANNOTATION_FOR_VAR, defn)
    
    def infer_local_variable_type(self, x, y, z):
#.........这里部分代码省略.........
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:103,代码来源:checker.py


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