How to use the mypy.nodes function in mypy

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

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

github python / mypy / mypy / plugins / ctypes.py View on Github external
def array_constructor_callback(ctx: 'mypy.plugin.FunctionContext') -> Type:
    """Callback to provide an accurate signature for the ctypes.Array constructor."""
    # Extract the element type from the constructor's return type, i. e. the type of the array
    # being constructed.
    et = _get_array_element_type(ctx.default_return_type)
    if et is not None:
        allowed = _autoconvertible_to_cdata(et, ctx.api)
        assert len(ctx.arg_types) == 1, \
            "The stub of the ctypes.Array constructor should have a single vararg parameter"
        for arg_num, (arg_kind, arg_type) in enumerate(zip(ctx.arg_kinds[0], ctx.arg_types[0]), 1):
            if arg_kind == nodes.ARG_POS and not is_subtype(arg_type, allowed):
                ctx.api.msg.fail(
                    'Array constructor argument {} of type {}'
                    ' is not convertible to the array element type {}'
                    .format(arg_num, format_type(arg_type), format_type(et)), ctx.context)
            elif arg_kind == nodes.ARG_STAR:
                ty = ctx.api.named_generic_type("typing.Iterable", [allowed])
                if not is_subtype(arg_type, ty):
                    it = ctx.api.named_generic_type("typing.Iterable", [et])
                    ctx.api.msg.fail(
                        'Array constructor argument {} of type {}'
                        ' is not convertible to the array element type {}'
                        .format(arg_num, format_type(arg_type), format_type(it)), ctx.context)

    return ctx.default_return_type
github python / mypy / mypy / checkexpr.py View on Github external
Type]) -> List[List[int]]:
    """Calculate mapping between actual (caller) args and formals.

    The result contains a list of caller argument indexes mapping to each
    callee argument index, indexed by callee index.

    The caller_arg_type argument should evaluate to the type of the actual
    argument type with the given index.
    """
    ncallee = len(callee_kinds)
    map = [[] for i in range(ncallee)]  # type: List[List[int]]
    j = 0
    for i, kind in enumerate(caller_kinds):
        if kind == nodes.ARG_POS:
            if j < ncallee:
                if callee_kinds[j] in [nodes.ARG_POS, nodes.ARG_OPT,
                                       nodes.ARG_NAMED, nodes.ARG_NAMED_OPT]:
                    map[j].append(i)
                    j += 1
                elif callee_kinds[j] == nodes.ARG_STAR:
                    map[j].append(i)
        elif kind == nodes.ARG_STAR:
            # We need to know the actual type to map varargs.
            argt = caller_arg_type(i)
            if isinstance(argt, TupleType):
                # A tuple actual maps to a fixed number of formals.
                for _ in range(len(argt.items)):
                    if j < ncallee:
                        if callee_kinds[j] != nodes.ARG_STAR2:
                            map[j].append(i)
                        else:
                            break
github python / mypy / mypy / transformtype.py View on Github external
def name_expr(self, name: str) -> NameExpr:
        nexpr = NameExpr(name)
        nexpr.kind = nodes.LDEF
        node = self.names[name]
        nexpr.node = node
        self.type_map[nexpr] = node.type
        return nexpr
github python / mypy / mypy / checkexpr.py View on Github external
if isinstance(e.callee, NameExpr) and isinstance(e.callee.node, TypeInfo) and \
                e.callee.node.typeddict_type is not None:
            return self.check_typeddict_call(e.callee.node.typeddict_type,
                                             e.arg_kinds, e.arg_names, e.args, e)
        if isinstance(e.callee, NameExpr) and e.callee.name in ('isinstance', 'issubclass'):
            for typ in mypy.checker.flatten(e.args[1]):
                if isinstance(typ, NameExpr):
                    try:
                        node = self.chk.lookup_qualified(typ.name)
                    except KeyError:
                        # Undefined names should already be reported in semantic analysis.
                        node = None
                if (isinstance(typ, IndexExpr)
                        and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr))
                        # node.kind == TYPE_ALIAS only for aliases like It = Iterable[int].
                        or isinstance(typ, NameExpr) and node and node.kind == nodes.TYPE_ALIAS):
                    self.msg.type_arguments_not_allowed(e)
        self.try_infer_partial_type(e)
        callee_type = self.accept(e.callee, always_allow_any=True)
        if (self.chk.options.disallow_untyped_calls and
                self.chk.in_checked_function() and
                isinstance(callee_type, CallableType)
                and callee_type.implicit):
            return self.msg.untyped_function_call(callee_type, e)
        # Figure out the full name of the callee for plugin loopup.
        object_type = None
        if not isinstance(e.callee, RefExpr):
            fullname = None
        else:
            fullname = e.callee.fullname
            if (fullname is None
                    and isinstance(e.callee, MemberExpr)
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / _mypy-master-0.4.7 / mypy / checkexpr.py View on Github external
def check_generator_or_comprehension(self, gen: GeneratorExpr,
                                         type_name: str,
                                         id_for_messages: str) -> Type:
        """Type check a generator expression or a list comprehension."""
        with self.chk.binder.frame_context(can_skip=True, fall_through=0):
            self.check_for_comp(gen)

            # Infer the type of the list comprehension by using a synthetic generic
            # callable type.
            tvdef = TypeVarDef('T', -1, [], self.chk.object_type())
            tv = TypeVarType(tvdef)
            constructor = CallableType(
                [tv],
                [nodes.ARG_POS],
                [None],
                self.chk.named_generic_type(type_name, [tv]),
                self.chk.named_type('builtins.function'),
                name=id_for_messages,
                variables=[tvdef])
            return self.check_call(constructor,
                                [gen.left_expr], [nodes.ARG_POS], gen)[0]
github python / mypy / mypy / stats.py View on Github external
def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
        self.line = o.line
        if (isinstance(o.rvalue, nodes.CallExpr) and
                isinstance(o.rvalue.analyzed, nodes.TypeVarExpr)):
            # Type variable definition -- not a real assignment.
            return
        if o.type:
            self.type(o.type)
        elif self.inferred and not self.all_nodes:
            # if self.all_nodes is set, lvalues will be visited later
            for lvalue in o.lvalues:
                if isinstance(lvalue, nodes.TupleExpr):
                    items = lvalue.items
                else:
                    items = [lvalue]
                for item in items:
                    if isinstance(item, RefExpr) and item.is_inferred_def:
                        if self.typemap is not None:
                            self.type(self.typemap.get(item))
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / strconv.py View on Github external
def pretty_name(self, name, kind, fullname, is_def):
        n = name
        if is_def:
            n += '*'
        if kind == mypy.nodes.GDEF or (fullname != name and
                                       fullname is not None):
            # Append fully qualified name for global references.
            n += ' [{}]'.format(fullname)
        elif kind == mypy.nodes.LDEF:
            # Add tag to signify a local reference.
            n += ' [l]'
        elif kind == mypy.nodes.MDEF:
            # Add tag to signify a member reference.
            n += ' [m]'
        return n
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / _mypy-master-0.4.7 / mypy / checkexpr.py View on Github external
def get_reverse_op_method(self, method: str) -> str:
        if method == '__div__' and self.chk.options.python_version[0] == 2:
            return '__rdiv__'
        else:
            return nodes.reverse_op_methods[method]
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / strconv.py View on Github external
def pretty_name(self, name, kind, fullname, is_def):
        n = name
        if is_def:
            n += '*'
        if kind == mypy.nodes.GDEF or (fullname != name and
                                       fullname is not None):
            # Append fully qualified name for global references.
            n += ' [{}]'.format(fullname)
        elif kind == mypy.nodes.LDEF:
            # Add tag to signify a local reference.
            n += ' [l]'
        elif kind == mypy.nodes.MDEF:
            # Add tag to signify a member reference.
            n += ' [m]'
        return n
github python / mypy / mypy / icode.py View on Github external
def visit_mypy_file(self, mfile: MypyFile) -> int:
        if mfile.fullname() in ('typing', 'abc'):
            # These module are special; their contents are currently all
            # built-in primitives.
            return -1

        self.enter()

        # Initialize non-int global variables.
        for name in sorted(mfile.names):
            node = mfile.names[name].node
            if (isinstance(node, Var) and
                    name not in nodes.implicit_module_attrs):
                v = cast(Var, node)
                if (not is_named_instance(v.type, 'builtins.int')
                        and v.fullname() != 'typing.Undefined'):
                    tmp = self.alloc_register()
                    self.add(SetRNone(tmp))
                    self.add(SetGR(v.fullname(), tmp))

        for d in mfile.defs:
            d.accept(self)
        self.add_implicit_return()
        self.generated['__init'] = FuncIcode(0, self.blocks,
                                             self.register_types)
        # TODO leave?
        return -1