How to use the mypy.nodes.NameExpr 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 / fastparse2.py View on Github external
def try_handler(self,
                    body: List[ast27.stmt],
                    handlers: List[ast27.ExceptHandler],
                    orelse: List[ast27.stmt],
                    finalbody: List[ast27.stmt],
                    lineno: int) -> TryStmt:
        vs = []  # type: List[Optional[NameExpr]]
        for item in handlers:
            if item.name is None:
                vs.append(None)
            elif isinstance(item.name, Name):
                vs.append(NameExpr(item.name.id))
            else:
                self.fail("Sorry, `except , ` is not supported",
                          item.lineno, item.col_offset)
                vs.append(None)
        types = [self.visit(h.type) for h in handlers]
        handlers_ = [self.as_required_block(h.body, h.lineno) for h in handlers]

        return TryStmt(self.as_required_block(body, lineno),
                       vs,
                       types,
                       handlers_,
                       self.as_block(orelse, lineno),
                       self.as_block(finalbody, lineno))
github seandstewart / typical / typic / mypy.py View on Github external
# NOTE: we would like the plugin generated node to dominate, but we still
    # need to keep any existing definitions so they get semantically analyzed.
    if name in info.names:
        # Get a nice unique name instead.
        r_name = get_unique_redefinition_name(name, info.names)
        info.names[r_name] = info.names[name]

    if is_classmethod or is_staticmethod:
        func.is_decorated = True
        v = Var(name, func.type)
        v.info = info
        v._fullname = func._fullname
        if is_classmethod:
            v.is_classmethod = True
            dec = Decorator(func, [NameExpr("classmethod")], v)
        else:
            v.is_staticmethod = True
            dec = Decorator(func, [NameExpr("staticmethod")], v)

        dec.line = info.line
        sym = SymbolTableNode(MDEF, dec)
    else:
        sym = SymbolTableNode(MDEF, func)
    sym.plugin_generated = True

    info.names[name] = sym
    info.defn.defs.body.append(func)
github python / mypy / mypy / plugins / attrs.py View on Github external
def _get_decorator_optional_bool_argument(
    ctx: 'mypy.plugin.ClassDefContext',
    name: str,
    default: Optional[bool] = None,
) -> Optional[bool]:
    """Return the Optional[bool] argument for the decorator.

    This handles both @decorator(...) and @decorator.
    """
    if isinstance(ctx.reason, CallExpr):
        attr_value = _get_argument(ctx.reason, name)
        if attr_value:
            if isinstance(attr_value, NameExpr):
                if attr_value.fullname == 'builtins.True':
                    return True
                if attr_value.fullname == 'builtins.False':
                    return False
                if attr_value.fullname == 'builtins.None':
                    return None
            ctx.api.fail('"{}" argument must be True or False.'.format(name), ctx.reason)
            return default
        return default
    else:
        return default
github samuelcolvin / pydantic / pydantic / mypy.py View on Github external
return None
        if lhs.name == 'extra':
            if isinstance(substmt.rvalue, StrExpr):
                forbid_extra = substmt.rvalue.value == 'forbid'
            elif isinstance(substmt.rvalue, MemberExpr):
                forbid_extra = substmt.rvalue.name == 'forbid'
            else:
                error_invalid_config_value(lhs.name, self._ctx.api, substmt)
                return None
            return ModelConfigData(forbid_extra=forbid_extra)
        if lhs.name == 'alias_generator':
            has_alias_generator = True
            if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname == 'builtins.None':
                has_alias_generator = False
            return ModelConfigData(has_alias_generator=has_alias_generator)
        if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname in ('builtins.True', 'builtins.False'):
            return ModelConfigData(**{lhs.name: substmt.rvalue.fullname == 'builtins.True'})
        error_invalid_config_value(lhs.name, self._ctx.api, substmt)
        return None
github python / mypy / mypy / transformtype.py View on Github external
def generic_accessor_wrappers(self, s: AssignmentStmt) -> List[Node]:
        """Construct wrapper class methods for attribute accessors."""
        res = []  # type: List[Node]
        assert len(s.lvalues) == 1
        assert isinstance(s.lvalues[0], NameExpr)
        assert s.type is not None
        name = cast(NameExpr, s.lvalues[0])
        for fd in [self.make_getter_wrapper(name.name, s.type),
                   self.make_setter_wrapper(name.name, s.type)]:
            res.extend(self.func_tf.generic_method_wrappers(fd))
        return res
github python / mypy / mypy / transformtype.py View on Github external
def make_dynamic_setter_wrapper(self, name: str, typ: Type) -> FuncDef:
        """Create a dynamically-typed setter wrapper for a data attribute.

        The setter will be of this form:

        . def set$name*(self: C, name; Any) -> None:
        .     self.name! = {typ name}
        """
        lvalue = MemberExpr(self_expr(), name, direct=True)
        name_expr = NameExpr(name)
        rvalue = coerce(name_expr, typ, AnyType(), self.tf.type_context())
        ret = AssignmentStmt([lvalue], rvalue)

        wrapper_name = 'set$' + name + self.tf.dynamic_suffix()
        selft = self_type(self.tf.type_context())
        sig = Callable([selft, AnyType()],
                       [nodes.ARG_POS, nodes.ARG_POS],
                       [None, None],
                       Void(), False)
        return FuncDef(wrapper_name,
                       [Var('self'), Var(name)],
                       [nodes.ARG_POS, nodes.ARG_POS],
                       [None, None],
                       Block([ret]), sig)
github typeddjango / django-stubs / mypy_django_plugin / transformers / models.py View on Github external
def get_existing_managers(self) -> List[Tuple[str, TypeInfo]]:
        managers = []
        for base in self.model_classdef.info.mro:
            for name_expr, member_expr in helpers.iter_call_assignments(base.defn):
                manager_name = name_expr.name
                callee_expr = member_expr.callee
                if isinstance(callee_expr, IndexExpr):
                    callee_expr = callee_expr.analyzed.expr
                if isinstance(callee_expr, (MemberExpr, NameExpr)) \
                        and isinstance(callee_expr.node, TypeInfo) \
                        and callee_expr.node.has_base(helpers.BASE_MANAGER_CLASS_FULLNAME):
                    managers.append((manager_name, callee_expr.node))
        return managers
github python / mypy / mypy / semanal.py View on Github external
for param_value, param_name, param_kind in zip(args, names, kinds):
            if not param_kind == ARG_NAMED:
                self.fail("Unexpected argument to TypeVar()", context)
                return None
            if param_name == 'covariant':
                if isinstance(param_value, NameExpr):
                    if param_value.name == 'True':
                        covariant = True
                    else:
                        self.fail("TypeVar 'covariant' may only be 'True'", context)
                        return None
                else:
                    self.fail("TypeVar 'covariant' may only be 'True'", context)
                    return None
            elif param_name == 'contravariant':
                if isinstance(param_value, NameExpr):
                    if param_value.name == 'True':
                        contravariant = True
                    else:
                        self.fail("TypeVar 'contravariant' may only be 'True'", context)
                        return None
                else:
                    self.fail("TypeVar 'contravariant' may only be 'True'", context)
                    return None
            elif param_name == 'bound':
                if has_values:
                    self.fail("TypeVar cannot have both values and an upper bound", context)
                    return None
                try:
                    upper_bound = self.expr_to_analyzed_type(param_value)
                except TypeTranslationError:
                    self.fail("TypeVar 'bound' must be a type", param_value)
github samuelcolvin / pydantic / pydantic / mypy.py View on Github external
# NOTE: we would like the plugin generated node to dominate, but we still
    # need to keep any existing definitions so they get semantically analyzed.
    if name in info.names:
        # Get a nice unique name instead.
        r_name = get_unique_redefinition_name(name, info.names)
        info.names[r_name] = info.names[name]

    if is_classmethod:  # or is_staticmethod:
        func.is_decorated = True
        v = Var(name, func.type)
        v.info = info
        v._fullname = func._fullname
        # if is_classmethod:
        v.is_classmethod = True
        dec = Decorator(func, [NameExpr('classmethod')], v)
        # else:
        #     v.is_staticmethod = True
        #     dec = Decorator(func, [NameExpr('staticmethod')], v)

        dec.line = info.line
        sym = SymbolTableNode(MDEF, dec)
    else:
        sym = SymbolTableNode(MDEF, func)
    sym.plugin_generated = True

    info.names[name] = sym
    info.defn.defs.body.append(func)
github python / mypy / mypy / transformtype.py View on Github external
if base.fullname() != 'builtins.object' and self.tf.is_java:
            s = SuperExpr('__init__')
            cargs = [NameExpr('__o')]  # type: List[Node]
            for n in range(num_slots(base)):
                cargs.append(NameExpr(tvar_arg_name(n + 1)))
            for n in range(num_slots(base)):
                cargs.append(NameExpr(tvar_arg_name(n + 1, BOUND_VAR)))
            c = CallExpr(s, cargs, [nodes.ARG_POS] * len(cargs))
            cdefs.append(ExpressionStmt(c))

        # Create initialization of the wrapped object.
        cdefs.append(AssignmentStmt([MemberExpr(
                                    self_expr(),
                                    self.object_member_name(info),
                                    direct=True)],
                                    NameExpr('__o')))

        # Build constructor arguments.
        args = [Var('self'), Var('__o')]
        init = [None, None]  # type: List[Node]

        for alt in [False, BOUND_VAR]:
            for n in range(nslots):
                args.append(Var(tvar_arg_name(n + 1, alt)))
                init.append(None)

        nargs = nslots * 2 + 2
        fdef = FuncDef('__init__',
                       args,
                       [nodes.ARG_POS] * nargs,
                       init,
                       Block(cdefs),