本文整理汇总了Python中mypy.nodes.Var类的典型用法代码示例。如果您正苦于以下问题:Python Var类的具体用法?Python Var怎么用?Python Var使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Var类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_magic_hook
def add_magic_hook(ctx) -> None:
info = ctx.cls.info
str_type = ctx.api.named_type_or_none('builtins.str', [])
assert str_type is not None
var = Var('__magic__', str_type)
var.info = info
info.names['__magic__'] = SymbolTableNode(MDEF, var)
示例2: add_method
def add_method(funcname: str,
ret: Type,
args: List[Argument],
name: Optional[str] = None,
is_classmethod: bool = False,
is_new: bool = False,
) -> None:
if is_classmethod or is_new:
first = [Argument(Var('cls'), TypeType.make_normalized(selftype), None, ARG_POS)]
else:
first = [Argument(Var('self'), selftype, None, ARG_POS)]
args = first + args
types = [arg.type_annotation for arg in args]
items = [arg.variable.name() for arg in args]
arg_kinds = [arg.kind for arg in args]
assert None not in types
signature = CallableType(cast(List[Type], types), arg_kinds, items, ret,
function_type)
signature.variables = [tvd]
func = FuncDef(funcname, args, Block([]))
func.info = info
func.is_class = is_classmethod
func.type = set_callable_name(signature, func)
func._fullname = info.fullname() + '.' + funcname
if is_classmethod:
v = Var(funcname, func.type)
v.is_classmethod = True
v.info = info
v._fullname = func._fullname
dec = Decorator(func, [NameExpr('classmethod')], v)
info.names[funcname] = SymbolTableNode(MDEF, dec)
else:
info.names[funcname] = SymbolTableNode(MDEF, func)
示例3: visit_FunctionDef
def visit_FunctionDef(self, n: ast35.FunctionDef) -> Node:
args = self.transform_args(n.args, n.lineno)
arg_kinds = [arg.kind for arg in args]
arg_names = [arg.variable.name() for arg in args]
arg_types = None # type: List[Type]
if n.type_comment is not None:
try:
func_type_ast = ast35.parse(n.type_comment, '<func_type>', 'func_type')
except SyntaxError:
raise TypeCommentParseError(TYPE_COMMENT_SYNTAX_ERROR, n.lineno)
assert isinstance(func_type_ast, ast35.FunctionType)
# for ellipsis arg
if (len(func_type_ast.argtypes) == 1 and
isinstance(func_type_ast.argtypes[0], ast35.Ellipsis)):
arg_types = [a.type_annotation if a.type_annotation is not None else AnyType()
for a in args]
else:
arg_types = [a if a is not None else AnyType() for
a in TypeConverter(line=n.lineno).visit_list(func_type_ast.argtypes)]
return_type = TypeConverter(line=n.lineno).visit(func_type_ast.returns)
# add implicit self type
if self.in_class() and len(arg_types) < len(args):
arg_types.insert(0, AnyType())
else:
arg_types = [a.type_annotation for a in args]
return_type = TypeConverter(line=n.lineno).visit(n.returns)
if isinstance(return_type, UnboundType):
return_type.is_ret_type = True
func_type = None
if any(arg_types) or return_type:
func_type = CallableType([a if a is not None else AnyType() for a in arg_types],
arg_kinds,
arg_names,
return_type if return_type is not None else AnyType(),
None)
func_def = FuncDef(n.name,
args,
self.as_block(n.body, n.lineno),
func_type)
if func_type is not None:
func_type.definition = func_def
func_type.line = n.lineno
if n.decorator_list:
var = Var(func_def.name())
var.is_ready = False
var.set_line(n.decorator_list[0].lineno)
func_def.is_decorated = True
func_def.set_line(n.lineno + len(n.decorator_list))
func_def.body.set_line(func_def.get_line())
return Decorator(func_def, self.visit_list(n.decorator_list), var)
else:
return func_def
示例4: make_accessors
def make_accessors(self, n: Var) -> List[Node]:
if n.type:
t = n.type
else:
t = AnyType()
return [self.make_getter_wrapper(n.name(), t),
self.make_setter_wrapper(n.name(), t),
self.make_dynamic_getter_wrapper(n.name(), t),
self.make_dynamic_setter_wrapper(n.name(), t)]
示例5: analyse_member_lvalue
def analyse_member_lvalue(self, lval):
lval.accept(self)
if self.is_init_method and isinstance(lval.expr, NameExpr):
node = (lval.expr).node
if isinstance(node, Var) and (node).is_self and lval.name not in self.type.vars:
lval.is_def = True
v = Var(lval.name)
v.info = self.type
v.is_ready = False
lval.def_var = v
self.type.vars[lval.name] = v
示例6: build_enum_call_typeinfo
def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) -> TypeInfo:
base = self.api.named_type_or_none(fullname)
assert base is not None
info = self.api.basic_new_typeinfo(name, base)
info.metaclass_type = info.calculate_metaclass_type()
info.is_enum = True
for item in items:
var = Var(item)
var.info = info
var.is_property = True
var._fullname = '{}.{}'.format(self.api.qualified_name(name), item)
info.names[item] = SymbolTableNode(MDEF, var)
return info
示例7: visit_FunctionDef
def visit_FunctionDef(self, n):
args = self.transform_args(n.args, n.lineno)
arg_kinds = [arg.kind for arg in args]
arg_names = [arg.variable.name() for arg in args]
if n.type_comment is not None:
func_type_ast = typed_ast.parse(n.type_comment, '<func_type>', 'func_type')
arg_types = [a if a is not None else AnyType() for
a in TypeConverter(line=n.lineno).visit(func_type_ast.argtypes)]
return_type = TypeConverter(line=n.lineno).visit(func_type_ast.returns)
# add implicit self type
if self.in_class and len(arg_types) < len(args):
arg_types.insert(0, AnyType())
else:
arg_types = [a.type_annotation for a in args]
return_type = TypeConverter(line=n.lineno).visit(n.returns)
func_type = None
if any(arg_types) or return_type:
func_type = CallableType([a if a is not None else AnyType() for a in arg_types],
arg_kinds,
arg_names,
return_type if return_type is not None else AnyType(),
None)
func_def = FuncDef(n.name,
args,
self.as_block(n.body, n.lineno),
func_type)
if func_type is not None:
func_type.definition = func_def
if n.decorator_list:
var = Var(func_def.name())
var.is_ready = False
var.set_line(n.decorator_list[0].lineno)
func_def.is_decorated = True
func_def.set_line(n.lineno + len(n.decorator_list))
func_def.body.set_line(func_def.get_line())
return Decorator(func_def, self.visit(n.decorator_list), var)
else:
return func_def
示例8: add_field
def add_field(var: Var, is_initialized_in_class: bool = False,
is_property: bool = False) -> None:
var.info = info
var.is_initialized_in_class = is_initialized_in_class
var.is_property = is_property
var._fullname = '%s.%s' % (info.fullname(), var.name())
info.names[var.name()] = SymbolTableNode(MDEF, var)
示例9: analyse_lvalue
def analyse_lvalue(self, lval, nested=False, add_defs=False):
if isinstance(lval, NameExpr):
n = lval
nested_global = not self.locals and self.block_depth > 0 and not self.type
if (add_defs or nested_global) and n.name not in self.globals:
# Define new global name.
v = Var(n.name)
v._full_name = self.qualified_name(n.name)
v.is_ready = False # Type not inferred yet
n.node = v
n.is_def = True
n.kind = GDEF
n.full_name = v._full_name
self.globals[n.name] = SymbolTableNode(GDEF, v, self.cur_mod_id)
elif isinstance(n.node, Var) and n.is_def:
v = n.node
self.module_names[v.name()] = SymbolTableNode(GDEF, v, self.cur_mod_id)
elif self.locals and n.name not in self.locals[-1] and n.name not in self.global_decls[-1]:
# Define new local name.
v = Var(n.name)
n.node = v
n.is_def = True
n.kind = LDEF
self.add_local(v, n)
elif not self.locals and (self.type and n.name not in self.type.vars):
# Define a new attribute.
v = Var(n.name)
v.info = self.type
v.is_initialized_in_class = True
n.node = v
n.is_def = True
self.type.vars[n.name] = v
else:
# Bind to an existing name.
lval.accept(self)
elif isinstance(lval, MemberExpr):
if not add_defs:
self.analyse_member_lvalue(lval)
elif isinstance(lval, IndexExpr):
if not add_defs:
lval.accept(self)
elif isinstance(lval, ParenExpr):
self.analyse_lvalue((lval).expr, nested, add_defs)
elif (isinstance(lval, TupleExpr) or isinstance(lval, ListExpr)) and not nested:
items = (lval).items
for i in items:
self.analyse_lvalue(i, True, add_defs)
else:
self.fail("Invalid assignment target", lval)
示例10: 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()
示例11: _make_frozen
def _make_frozen(ctx: 'mypy.plugin.ClassDefContext', attributes: List[Attribute]) -> None:
"""Turn all the attributes into properties to simulate frozen classes."""
for attribute in attributes:
if attribute.name in ctx.cls.info.names:
# This variable belongs to this class so we can modify it.
node = ctx.cls.info.names[attribute.name].node
assert isinstance(node, Var)
node.is_property = True
else:
# This variable belongs to a super class so create new Var so we
# can modify it.
var = Var(attribute.name, ctx.cls.info[attribute.name].type)
var.info = ctx.cls.info
var._fullname = '%s.%s' % (ctx.cls.info.fullname(), var.name())
ctx.cls.info.names[var.name()] = SymbolTableNode(MDEF, var)
var.is_property = True
示例12: 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()
示例13: visit_var
def visit_var(self, node: Var) -> None:
node.info = self.fixup(node.info)
self.fixup_type(node.type)
super().visit_var(node)
示例14: make_init_arg
def make_init_arg(var: Var) -> Argument:
default = default_items.get(var.name(), None)
kind = ARG_POS if default is None else ARG_OPT
return Argument(var, var.type, default, kind)
示例15: visit_FunctionDef
def visit_FunctionDef(self, n: ast27.FunctionDef) -> Statement:
converter = TypeConverter(self.errors, line=n.lineno)
args, decompose_stmts = self.transform_args(n.args, n.lineno)
arg_kinds = [arg.kind for arg in args]
arg_names = [arg.variable.name() for arg in args] # type: List[Optional[str]]
arg_names = [None if argument_elide_name(name) else name for name in arg_names]
if special_function_elide_names(n.name):
arg_names = [None] * len(arg_names)
arg_types = None # type: List[Type]
if (n.decorator_list and any(is_no_type_check_decorator(d) for d in n.decorator_list)):
arg_types = [None] * len(args)
return_type = None
elif n.type_comment is not None and len(n.type_comment) > 0:
try:
func_type_ast = ast35.parse(n.type_comment, '<func_type>', 'func_type')
assert isinstance(func_type_ast, ast35.FunctionType)
# for ellipsis arg
if (len(func_type_ast.argtypes) == 1 and
isinstance(func_type_ast.argtypes[0], ast35.Ellipsis)):
arg_types = [a.type_annotation if a.type_annotation is not None else AnyType()
for a in args]
else:
# PEP 484 disallows both type annotations and type comments
if any(a.type_annotation is not None for a in args):
self.fail(messages.DUPLICATE_TYPE_SIGNATURES, n.lineno, n.col_offset)
arg_types = [a if a is not None else AnyType() for
a in converter.translate_expr_list(func_type_ast.argtypes)]
return_type = converter.visit(func_type_ast.returns)
# add implicit self type
if self.in_class() and len(arg_types) < len(args):
arg_types.insert(0, AnyType())
except SyntaxError:
self.fail(TYPE_COMMENT_SYNTAX_ERROR, n.lineno, n.col_offset)
arg_types = [AnyType()] * len(args)
return_type = AnyType()
else:
arg_types = [a.type_annotation for a in args]
return_type = converter.visit(None)
for arg, arg_type in zip(args, arg_types):
self.set_type_optional(arg_type, arg.initializer)
if isinstance(return_type, UnboundType):
return_type.is_ret_type = True
func_type = None
if any(arg_types) or return_type:
if len(arg_types) != 1 and any(isinstance(t, EllipsisType) for t in arg_types):
self.fail("Ellipses cannot accompany other argument types "
"in function type signature.", n.lineno, 0)
elif len(arg_types) > len(arg_kinds):
self.fail('Type signature has too many arguments', n.lineno, 0)
elif len(arg_types) < len(arg_kinds):
self.fail('Type signature has too few arguments', n.lineno, 0)
else:
func_type = CallableType([a if a is not None else AnyType() for a in arg_types],
arg_kinds,
arg_names,
return_type if return_type is not None else AnyType(),
None)
body = self.as_block(n.body, n.lineno)
if decompose_stmts:
body.body = decompose_stmts + body.body
func_def = FuncDef(n.name,
args,
body,
func_type)
if func_type is not None:
func_type.definition = func_def
func_type.line = n.lineno
if n.decorator_list:
var = Var(func_def.name())
var.is_ready = False
var.set_line(n.decorator_list[0].lineno)
func_def.is_decorated = True
func_def.set_line(n.lineno + len(n.decorator_list))
func_def.body.set_line(func_def.get_line())
return Decorator(func_def, self.translate_expr_list(n.decorator_list), var)
else:
return func_def