From 2718ca998ad3e38ea150dc2a1d03d534c3976870 Mon Sep 17 00:00:00 2001 From: "Michael J. Sullivan" Date: Wed, 13 Nov 2019 12:47:52 -0800 Subject: [PATCH] Fix all calls to name and fullname functions `sed -i -e 's/\.name()/.name/g' -e 's/\.fullname()/.fullname/g' mypy/*.py mypy/*/*.py mypyc/*.py mypyc/*/*.py misc/proper_plugin.py test-data/unit/plugins/*.py` --- misc/proper_plugin.py | 6 +- mypy/argmap.py | 4 +- mypy/build.py | 4 +- mypy/checker.py | 132 +++++++++--------- mypy/checkexpr.py | 54 ++++---- mypy/checkmember.py | 18 +-- mypy/checkstrformat.py | 4 +- mypy/constraints.py | 4 +- mypy/fastparse.py | 10 +- mypy/fastparse2.py | 8 +- mypy/fixup.py | 4 +- mypy/indirection.py | 2 +- mypy/join.py | 6 +- mypy/meet.py | 20 +-- mypy/messages.py | 68 +++++----- mypy/mro.py | 4 +- mypy/nodes.py | 38 +++--- mypy/plugin.py | 2 +- mypy/plugins/attrs.py | 16 +-- mypy/plugins/common.py | 4 +- mypy/plugins/ctypes.py | 10 +- mypy/plugins/dataclasses.py | 14 +- mypy/plugins/enums.py | 2 +- mypy/renaming.py | 4 +- mypy/report.py | 12 +- mypy/scope.py | 10 +- mypy/semanal.py | 100 +++++++------- mypy/semanal_classprop.py | 6 +- mypy/semanal_enum.py | 2 +- mypy/semanal_infer.py | 2 +- mypy/semanal_main.py | 2 +- mypy/semanal_namedtuple.py | 14 +- mypy/semanal_pass1.py | 2 +- mypy/semanal_shared.py | 12 +- mypy/semanal_typeargs.py | 14 +- mypy/server/astdiff.py | 12 +- mypy/server/astmerge.py | 8 +- mypy/server/deps.py | 74 +++++----- mypy/server/mergecheck.py | 8 +- mypy/server/update.py | 24 ++-- mypy/stats.py | 4 +- mypy/strconv.py | 12 +- mypy/stubgen.py | 18 +-- mypy/subtypes.py | 14 +- mypy/suggestions.py | 16 +-- mypy/test/testmerge.py | 4 +- mypy/test/visitors.py | 2 +- mypy/treetransform.py | 8 +- mypy/tvar_scope.py | 4 +- mypy/typeanal.py | 22 +-- mypy/typeops.py | 14 +- mypy/types.py | 24 ++-- mypy/typestate.py | 14 +- mypyc/emitmodule.py | 8 +- mypyc/genops.py | 156 +++++++++++----------- mypyc/ops.py | 2 +- test-data/unit/plugins/class_callable.py | 4 +- test-data/unit/plugins/depshook.py | 2 +- test-data/unit/plugins/dyn_class.py | 2 +- test-data/unit/plugins/method_sig_hook.py | 2 +- test-data/unit/plugins/union_method.py | 4 +- 61 files changed, 538 insertions(+), 538 deletions(-) diff --git a/misc/proper_plugin.py b/misc/proper_plugin.py index d133cf300a87..9759c94bcbb9 100644 --- a/misc/proper_plugin.py +++ b/misc/proper_plugin.py @@ -48,15 +48,15 @@ def isinstance_proper_hook(ctx: FunctionContext) -> Type: def is_special_target(right: ProperType) -> bool: """Whitelist some special cases for use in isinstance() with improper types.""" if isinstance(right, CallableType) and right.is_type_obj(): - if right.type_object().fullname() == 'builtins.tuple': + if right.type_object().fullname == 'builtins.tuple': # Used with Union[Type, Tuple[Type, ...]]. return True - if right.type_object().fullname() in ('mypy.types.Type', + if right.type_object().fullname in ('mypy.types.Type', 'mypy.types.ProperType', 'mypy.types.TypeAliasType'): # Special case: things like assert isinstance(typ, ProperType) are always OK. return True - if right.type_object().fullname() in ('mypy.types.UnboundType', + if right.type_object().fullname in ('mypy.types.UnboundType', 'mypy.types.TypeVarType', 'mypy.types.RawExpressionType', 'mypy.types.EllipsisType', diff --git a/mypy/argmap.py b/mypy/argmap.py index 62c312e78a83..324ccaf833d5 100644 --- a/mypy/argmap.py +++ b/mypy/argmap.py @@ -158,7 +158,7 @@ def expand_actual_type(self, actual_type = get_proper_type(actual_type) if actual_kind == nodes.ARG_STAR: if isinstance(actual_type, Instance): - if actual_type.type.fullname() == 'builtins.list': + if actual_type.type.fullname == 'builtins.list': # List *arg. return actual_type.args[0] elif actual_type.args: @@ -187,7 +187,7 @@ def expand_actual_type(self, self.kwargs_used.add(formal_name) return actual_type.items[formal_name] elif (isinstance(actual_type, Instance) - and (actual_type.type.fullname() == 'builtins.dict')): + and (actual_type.type.fullname == 'builtins.dict')): # Dict **arg. # TODO: Handle arbitrary Mapping return actual_type.args[1] diff --git a/mypy/build.py b/mypy/build.py index 89f2f368332a..f68aabe5e440 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -676,7 +676,7 @@ def all_imported_modules_in_file(self, def correct_rel_imp(imp: Union[ImportFrom, ImportAll]) -> str: """Function to correct for relative imports.""" - file_id = file.fullname() + file_id = file.fullname rel = imp.relative if rel == 0: return imp.id @@ -687,7 +687,7 @@ def correct_rel_imp(imp: Union[ImportFrom, ImportAll]) -> str: new_id = file_id + "." + imp.id if imp.id else file_id if not new_id: - self.errors.set_file(file.path, file.name()) + self.errors.set_file(file.path, file.name) self.errors.report(imp.line, 0, "No parent module -- cannot perform relative import", blocker=True) diff --git a/mypy/checker.py b/mypy/checker.py index 226a341995eb..fb74b93dcb54 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -284,8 +284,8 @@ def check_first_pass(self) -> None: """ self.recurse_into_functions = True with state.strict_optional_set(self.options.strict_optional): - self.errors.set_file(self.path, self.tree.fullname(), scope=self.tscope) - self.tscope.enter_file(self.tree.fullname()) + self.errors.set_file(self.path, self.tree.fullname, scope=self.tscope) + self.tscope.enter_file(self.tree.fullname) with self.enter_partial_types(): with self.binder.top_frame_context(): for d in self.tree.defs: @@ -321,8 +321,8 @@ def check_second_pass(self, with state.strict_optional_set(self.options.strict_optional): if not todo and not self.deferred_nodes: return False - self.errors.set_file(self.path, self.tree.fullname(), scope=self.tscope) - self.tscope.enter_file(self.tree.fullname()) + self.errors.set_file(self.path, self.tree.fullname, scope=self.tscope) + self.tscope.enter_file(self.tree.fullname) self.pass_num += 1 if not todo: todo = self.deferred_nodes @@ -335,7 +335,7 @@ def check_second_pass(self, continue # This is useful for debugging: # print("XXX in pass %d, class %s, function %s" % - # (self.pass_num, type_name, node.fullname() or node.name())) + # (self.pass_num, type_name, node.fullname or node.name)) done.add(node) with self.tscope.class_scope(active_typeinfo) if active_typeinfo else nothing(): with self.scope.push_class(active_typeinfo) if active_typeinfo else nothing(): @@ -445,7 +445,7 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: self.visit_decorator(cast(Decorator, defn.items[0])) for fdef in defn.items: assert isinstance(fdef, Decorator) - self.check_func_item(fdef.func, name=fdef.func.name()) + self.check_func_item(fdef.func, name=fdef.func.name) if fdef.func.is_abstract: num_abstract += 1 if num_abstract not in (0, len(defn.items)): @@ -480,7 +480,7 @@ def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None: assert isinstance(inner_type, CallableType) impl_type = inner_type - is_descriptor_get = defn.info and defn.name() == "__get__" + is_descriptor_get = defn.info and defn.name == "__get__" for i, item in enumerate(defn.items): # TODO overloads involving decorators assert isinstance(item, Decorator) @@ -613,7 +613,7 @@ def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool: gt = self.named_generic_type('typing.Generator', [any_type, any_type, any_type]) if is_subtype(gt, typ): return True - return isinstance(typ, Instance) and typ.type.fullname() == 'typing.AwaitableGenerator' + return isinstance(typ, Instance) and typ.type.fullname == 'typing.AwaitableGenerator' def is_async_generator_return_type(self, typ: Type) -> bool: """Is `typ` a valid type for an async generator? @@ -642,7 +642,7 @@ def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Typ elif not isinstance(return_type, Instance): # Same as above, but written as a separate branch so the typechecker can understand. return AnyType(TypeOfAny.from_error) - elif return_type.type.fullname() == 'typing.Awaitable': + elif return_type.type.fullname == 'typing.Awaitable': # Awaitable: ty is Any. return AnyType(TypeOfAny.special_form) elif return_type.args: @@ -671,14 +671,14 @@ def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> T elif not isinstance(return_type, Instance): # Same as above, but written as a separate branch so the typechecker can understand. return AnyType(TypeOfAny.from_error) - elif return_type.type.fullname() == 'typing.Awaitable': + elif return_type.type.fullname == 'typing.Awaitable': # Awaitable, AwaitableGenerator: tc is Any. return AnyType(TypeOfAny.special_form) - elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator') + elif (return_type.type.fullname in ('typing.Generator', 'typing.AwaitableGenerator') and len(return_type.args) >= 3): # Generator: tc is args[1]. return return_type.args[1] - elif return_type.type.fullname() == 'typing.AsyncGenerator' and len(return_type.args) >= 2: + elif return_type.type.fullname == 'typing.AsyncGenerator' and len(return_type.args) >= 2: return return_type.args[1] else: # `return_type` is a supertype of Generator, so callers won't be able to send it @@ -706,10 +706,10 @@ def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Ty elif not isinstance(return_type, Instance): # Same as above, but written as a separate branch so the typechecker can understand. return AnyType(TypeOfAny.from_error) - elif return_type.type.fullname() == 'typing.Awaitable' and len(return_type.args) == 1: + elif return_type.type.fullname == 'typing.Awaitable' and len(return_type.args) == 1: # Awaitable: tr is args[0]. return return_type.args[0] - elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator') + elif (return_type.type.fullname in ('typing.Generator', 'typing.AwaitableGenerator') and len(return_type.args) >= 3): # AwaitableGenerator, Generator: tr is args[2]. return return_type.args[2] @@ -725,7 +725,7 @@ def visit_func_def(self, defn: FuncDef) -> None: def _visit_func_def(self, defn: FuncDef) -> None: """Type check a function definition.""" - self.check_func_item(defn, name=defn.name()) + self.check_func_item(defn, name=defn.name) if defn.info: if not defn.is_dynamic() and not defn.is_overload and not defn.is_decorated: # If the definition is the implementation for an @@ -820,14 +820,14 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) if isinstance(item, FuncDef): fdef = item # Check if __init__ has an invalid, non-None return type. - if (fdef.info and fdef.name() in ('__init__', '__init_subclass__') and + if (fdef.info and fdef.name in ('__init__', '__init_subclass__') and not isinstance(get_proper_type(typ.ret_type), NoneType) and not self.dynamic_funcs[-1]): - self.fail(message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name()), + self.fail(message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item) # Check validity of __new__ signature - if fdef.info and fdef.name() == '__new__': + if fdef.info and fdef.name == '__new__': self.check___new___signature(fdef, typ) self.check_for_missing_annotations(fdef) @@ -838,7 +838,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) self.msg.unimported_type_becomes_any("Return type", ret_type, fdef) for idx, arg_type in enumerate(fdef.type.arg_types): if has_any_from_unimported_type(arg_type): - prefix = "Argument {} to \"{}\"".format(idx + 1, fdef.name()) + prefix = "Argument {} to \"{}\"".format(idx + 1, fdef.name) self.msg.unimported_type_becomes_any(prefix, arg_type, fdef) check_for_explicit_any(fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef) @@ -871,7 +871,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) orig_ret_type = get_proper_type(typ.ret_type) if (self.options.python_version[0] == 2 and isinstance(orig_ret_type, Instance) and - orig_ret_type.type.fullname() == 'typing.Generator'): + orig_ret_type.type.fullname == 'typing.Generator'): if not isinstance(get_proper_type(orig_ret_type.args[2]), (NoneType, AnyType)): self.fail(message_registry.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ) @@ -906,7 +906,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) if (isinstance(defn, FuncDef) and ref_type is not None and i == 0 and not defn.is_static and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]): - isclass = defn.is_class or defn.name() in ('__new__', '__init_subclass__') + isclass = defn.is_class or defn.name in ('__new__', '__init_subclass__') if isclass: ref_type = mypy.types.TypeType.make_normalized(ref_type) erased = get_proper_type(erase_to_bound(arg_type)) @@ -939,7 +939,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) # TODO: check recursively for inner type variables if ( arg_type.variance == COVARIANT and - defn.name() not in ('__init__', '__new__') + defn.name not in ('__init__', '__new__') ): ctx = arg_type # type: Context if ctx.line < 0: @@ -1005,7 +1005,7 @@ def check_default_args(self, item: FuncItem, body_is_trivial: bool) -> None: continue if body_is_trivial and isinstance(arg.initializer, EllipsisExpr): continue - name = arg.variable.name() + name = arg.variable.name msg = 'Incompatible default for ' if name.startswith('__tuple_arg_'): msg += "tuple argument {}".format(name[12:]) @@ -1175,7 +1175,7 @@ def check_reverse_op_method(self, defn: FuncItem, if isinstance(ret_type, AnyType): return if isinstance(ret_type, Instance): - if ret_type.type.fullname() == 'builtins.object': + if ret_type.type.fullname == 'builtins.object': return if reverse_type.arg_kinds[0] == ARG_STAR: reverse_type = reverse_type.copy_modified(arg_types=[reverse_type.arg_types[0]] * 2, @@ -1324,7 +1324,7 @@ def check_inplace_operator_method(self, defn: FuncBase) -> None: They cannot arbitrarily overlap with __add__. """ - method = defn.name() + method = defn.name if method not in nodes.inplace_operator_methods: return typ = bind_self(self.function_type(defn)) @@ -1430,12 +1430,12 @@ def check_method_or_accessor_override_for_base(self, defn: Union[FuncDef, superclass nodes is not ready. """ if base: - name = defn.name() + name = defn.name base_attr = base.names.get(name) if base_attr: # First, check if we override a final (always an error, even with Any types). if is_final_node(base_attr.node): - self.msg.cant_override_final(name, base.name(), defn) + self.msg.cant_override_final(name, base.name, defn) # Second, final can't override anything writeable independently of types. if defn.is_final: self.check_no_writable(name, base_attr.node, defn) @@ -1522,9 +1522,9 @@ def check_method_override_for_base_with_name( # TODO overloaded signatures self.check_override(typ, original, - defn.name(), + defn.name, name, - base.name(), + base.name, original_class_or_static, override_class_or_static, context) @@ -1537,7 +1537,7 @@ def check_method_override_for_base_with_name( pass else: self.msg.signature_incompatible_with_supertype( - defn.name(), name, base.name(), context) + defn.name, name, base.name, context) return False def bind_and_map_method(self, sym: SymbolTableNode, typ: FunctionLike, @@ -1629,7 +1629,7 @@ def check_override(self, override: FunctionLike, original: FunctionLike, override_ids = override.type_var_ids() type_name = None if isinstance(override.definition, FuncDef): - type_name = override.definition.info.name() + type_name = override.definition.info.name def erase_override(t: Type) -> Type: return erase_typevars(t, ids_to_erase=override_ids) @@ -1710,7 +1710,7 @@ def visit_class_def(self, defn: ClassDef) -> None: typ = defn.info for base in typ.mro[1:]: if base.is_final: - self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name()), defn) + self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn) with self.tscope.class_scope(defn.info), self.enter_partial_types(is_class=True): old_binder = self.binder self.binder = ConditionalTypeBinder() @@ -1766,7 +1766,7 @@ def check_init_subclass(self, defn: ClassDef) -> None: Child.__init_subclass__ is never called. """ if (defn.info.metaclass_type and - defn.info.metaclass_type.type.fullname() not in ('builtins.type', 'abc.ABCMeta')): + defn.info.metaclass_type.type.fullname not in ('builtins.type', 'abc.ABCMeta')): # We can't safely check situations when both __init_subclass__ and a custom # metaclass are present. return @@ -1910,14 +1910,14 @@ class C(B, A[int]): ... # this is unsafe because... ok = is_subtype(first_type, cast(CallableType, second_type).ret_type) else: if first_type is None: - self.msg.cannot_determine_type_in_base(name, base1.name(), ctx) + self.msg.cannot_determine_type_in_base(name, base1.name, ctx) if second_type is None: - self.msg.cannot_determine_type_in_base(name, base2.name(), ctx) + self.msg.cannot_determine_type_in_base(name, base2.name, ctx) ok = True # Final attributes can never be overridden, but can override # non-final read-only attributes. if is_final_node(second.node): - self.msg.cant_override_final(name, base2.name(), ctx) + self.msg.cant_override_final(name, base2.name, ctx) if is_final_node(first.node): self.check_no_writable(name, second.node, ctx) # __slots__ is special and the type can vary across class hierarchy. @@ -2046,7 +2046,7 @@ def check_assignment(self, lvalue: Lvalue, rvalue: Expression, infer_lvalue_type # If we're assigning to __getattr__ or similar methods, check that the signature is # valid. if isinstance(lvalue, NameExpr) and lvalue.node: - name = lvalue.node.name() + name = lvalue.node.name if name in ('__setattr__', '__getattribute__', '__getattr__'): # If an explicit type is given, use that. if lvalue_type: @@ -2150,7 +2150,7 @@ def check_compatibility_all_supers(self, lvalue: RefExpr, lvalue_type: Optional[ len(lvalue_node.info.bases) > 0): for base in lvalue_node.info.mro[1:]: - tnode = base.names.get(lvalue_node.name()) + tnode = base.names.get(lvalue_node.name) if tnode is not None: if not self.check_compatibility_classvar_super(lvalue_node, base, @@ -2174,10 +2174,10 @@ def check_compatibility_all_supers(self, lvalue: RefExpr, lvalue_type: Optional[ # anything other than 3 elements. The exception to this rule # is __slots__, where it is allowed for any child class to # redefine it. - if lvalue_node.name() == "__slots__" and base.fullname() != "builtins.object": + if lvalue_node.name == "__slots__" and base.fullname != "builtins.object": continue - if is_private(lvalue_node.name()): + if is_private(lvalue_node.name): continue base_type, base_node = self.lvalue_type_from_base(lvalue_node, base) @@ -2252,7 +2252,7 @@ def check_compatibility_super(self, lvalue: RefExpr, lvalue_type: Optional[Type] return self.check_subtype(compare_type, base_type, rvalue, message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, 'expression has type', - 'base class "%s" defined the type as' % base.name(), + 'base class "%s" defined the type as' % base.name, code=codes.ASSIGNMENT) return True @@ -2260,7 +2260,7 @@ def lvalue_type_from_base(self, expr_node: Var, base: TypeInfo) -> Tuple[Optional[Type], Optional[Node]]: """For a NameExpr that is part of a class, walk all base classes and try to find the first class that defines a Type for the same name.""" - expr_name = expr_node.name() + expr_name = expr_node.name base_var = base.names.get(expr_name) if base_var: @@ -2302,10 +2302,10 @@ def check_compatibility_classvar_super(self, node: Var, if not isinstance(base_node, Var): return True if node.is_classvar and not base_node.is_classvar: - self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name()), node) + self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name), node) return False elif not node.is_classvar and base_node.is_classvar: - self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name()), node) + self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name), node) return False return True @@ -2327,10 +2327,10 @@ def check_compatibility_final_super(self, node: Var, # if we are overriding a final method with variable. # Other override attempts will be flagged as assignment to constant # in `check_final()`. - self.msg.cant_override_final(node.name(), base.name(), node) + self.msg.cant_override_final(node.name, base.name, node) return False if node.is_final: - self.check_no_writable(node.name(), base_node, node) + self.check_no_writable(node.name, base_node, node) return True def check_no_writable(self, name: str, base_node: Optional[Node], ctx: Context) -> None: @@ -2396,7 +2396,7 @@ def check_final(self, self.msg.final_without_value(s) for lv in lvs: if isinstance(lv, RefExpr) and isinstance(lv.node, Var): - name = lv.node.name() + name = lv.node.name cls = self.scope.active_class() if cls is not None: # Theses additional checks exist to give more error messages @@ -2773,7 +2773,7 @@ def infer_partial_type(self, name: Var, lvalue: Lvalue, init_type: Type) -> bool if isinstance(init_type, NoneType): partial_type = PartialType(None, name, [init_type]) elif isinstance(init_type, Instance): - fullname = init_type.type.fullname() + fullname = init_type.type.fullname if (isinstance(lvalue, (NameExpr, MemberExpr)) and (fullname == 'builtins.list' or fullname == 'builtins.set' or @@ -2969,7 +2969,7 @@ def try_infer_partial_type_from_indexed_assignment( partial_types = self.find_partial_types(var) if partial_types is None: return - typename = type_type.fullname() + typename = type_type.fullname if typename == 'builtins.dict': # TODO: Don't infer things twice. key_type = self.expr_checker.accept(lvalue.index) @@ -3035,7 +3035,7 @@ def check_return_stmt(self, s: ReturnStmt) -> None: if (self.options.warn_return_any and not self.current_node_deferred and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type) - and not (defn.name() in BINARY_MAGIC_METHODS and + and not (defn.name in BINARY_MAGIC_METHODS and is_literal_not_implemented(s.expr))): self.msg.incorrectly_returning_any(return_type, s) return @@ -3394,7 +3394,7 @@ def visit_decorator(self, e: Decorator) -> None: if self.recurse_into_functions: with self.tscope.function_scope(e.func): - self.check_func_item(e.func, name=e.func.name()) + self.check_func_item(e.func, name=e.func.name) # Process decorators from the inside out to determine decorated signature, which # may be different from the declared signature. @@ -3421,7 +3421,7 @@ def visit_decorator(self, e: Decorator) -> None: if e.func.info and not e.func.is_dynamic(): self.check_method_override(e) - if e.func.info and e.func.name() in ('__init__', '__new__'): + if e.func.info and e.func.name in ('__init__', '__new__'): if e.type and not isinstance(get_proper_type(e.type), (FunctionLike, AnyType)): self.fail(message_registry.BAD_CONSTRUCTOR_TYPE, e) @@ -3432,11 +3432,11 @@ def check_for_untyped_decorator(self, if (self.options.disallow_untyped_decorators and is_typed_callable(func.type) and is_untyped_decorator(dec_type)): - self.msg.typed_function_untyped_decorator(func.name(), dec_expr) + self.msg.typed_function_untyped_decorator(func.name, dec_expr) def check_incompatible_property_override(self, e: Decorator) -> None: if not e.var.is_settable_property and e.func.info: - name = e.func.name() + name = e.func.name for base in e.func.info.mro[1:]: base_attr = base.names.get(name) if not base_attr: @@ -3468,7 +3468,7 @@ def visit_with_stmt(self, s: WithStmt) -> None: if (is_literal_type(exit_ret_type, "builtins.bool", True) or (isinstance(exit_ret_type, Instance) - and exit_ret_type.type.fullname() == 'builtins.bool' + and exit_ret_type.type.fullname == 'builtins.bool' and state.strict_optional)): # Note: if strict-optional is disabled, this bool instance # could actually be an Optional[bool]. @@ -3544,7 +3544,7 @@ def intersect_instance_callable(self, typ: Instance, callable_type: CallableType # have a valid fullname and a corresponding entry in a symbol table. We generate # a unique name inside the symbol table of the current module. cur_module = cast(MypyFile, self.scope.stack[0]) - gen_name = gen_unique_name("".format(typ.type.name()), + gen_name = gen_unique_name("".format(typ.type.name), cur_module.names) # Build the fake ClassDef and TypeInfo together. @@ -3555,8 +3555,8 @@ def intersect_instance_callable(self, typ: Instance, callable_type: CallableType # is_protocol, protocol_members, is_abstract short_name = format_type_bare(typ) cdef = ClassDef(short_name, Block([])) - cdef.fullname = cur_module.fullname() + '.' + gen_name - info = TypeInfo(SymbolTable(), cdef, cur_module.fullname()) + cdef.fullname = cur_module.fullname + '.' + gen_name + info = TypeInfo(SymbolTable(), cdef, cur_module.fullname) cdef.info = info info.bases = [typ] calculate_mro(info) @@ -3748,7 +3748,7 @@ def find_isinstance_check_helper(self, node: Expression) -> Tuple[TypeMap, TypeM elif isinstance(vartype, TypeType): vartype = vartype.item elif (isinstance(vartype, Instance) and - vartype.type.fullname() == 'builtins.type'): + vartype.type.fullname == 'builtins.type'): vartype = self.named_type('builtins.object') else: # Any other object whose type we don't know precisely @@ -3788,7 +3788,7 @@ def find_isinstance_check_helper(self, node: Expression) -> Tuple[TypeMap, TypeM # a union of singleton types. if isinstance(other_type, LiteralType) and other_type.is_enum_literal(): - fallback_name = other_type.fallback.type.fullname() + fallback_name = other_type.fallback.type.fullname var_type = try_expanding_enum_to_union(var_type, fallback_name) target_type = [TypeRange(other_type, is_upper_bound=False)] @@ -3818,7 +3818,7 @@ def find_isinstance_check_helper(self, node: Expression) -> Tuple[TypeMap, TypeM right_type = get_proper_type(builtin_item_type(type_map[node.operands[1]])) right_ok = right_type and (not is_optional(right_type) and (not isinstance(right_type, Instance) or - right_type.type.fullname() != 'builtins.object')) + right_type.type.fullname != 'builtins.object')) if (right_type and right_ok and is_optional(left_type) and literal(expr) == LITERAL_TYPE and not is_literal_none(expr) and is_overlapping_erased_types(left_type, right_type)): @@ -4266,7 +4266,7 @@ def handle_partial_var_type( self.options.python_version) else: # Defer the node -- we might get a better type in the outer scope - self.handle_cannot_determine_type(node.name(), context) + self.handle_cannot_determine_type(node.name, context) return self.fixup_partial_type(typ) def fixup_partial_type(self, typ: Type) -> Type: @@ -4287,7 +4287,7 @@ def fixup_partial_type(self, typ: Type) -> Type: def is_defined_in_base_class(self, var: Var) -> bool: if var.info: for base in var.info.mro[1:]: - if base.get(var.name()) is not None: + if base.get(var.name) is not None: return True if var.info.fallback_to_any: return True @@ -4455,7 +4455,7 @@ def builtin_item_type(tp: Type) -> Optional[Type]: tp = get_proper_type(tp) if isinstance(tp, Instance): - if tp.type.fullname() in ['builtins.list', 'builtins.tuple', 'builtins.dict', + if tp.type.fullname in ['builtins.list', 'builtins.tuple', 'builtins.dict', 'builtins.set', 'builtins.frozenset']: if not tp.args: # TODO: fix tuple in lib-stub/builtins.pyi (it should be generic). @@ -4469,7 +4469,7 @@ def builtin_item_type(tp: Type) -> Optional[Type]: # TypedDict always has non-optional string keys. Find the key type from the Mapping # base class. for base in tp.fallback.type.mro: - if base.fullname() == 'typing.Mapping': + if base.fullname == 'typing.Mapping': return map_instance_to_supertype(tp.fallback, base).args[0] assert False, 'No Mapping base class found for TypedDict fallback' return None @@ -4568,7 +4568,7 @@ def get_isinstance_type(expr: Expression, # Type[A] means "any type that is a subtype of A" rather than "precisely type A" # we indicate this by setting is_upper_bound flag types.append(TypeRange(typ.item, is_upper_bound=True)) - elif isinstance(typ, Instance) and typ.type.fullname() == 'builtins.type': + elif isinstance(typ, Instance) and typ.type.fullname == 'builtins.type': object_type = Instance(typ.type.mro[-1], []) types.append(TypeRange(object_type, is_upper_bound=True)) elif isinstance(typ, AnyType): diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index ef6ff42ddc8a..07ca3aaa7bc1 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -230,7 +230,7 @@ def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: or lvalue) else: if isinstance(node, PlaceholderNode): - assert False, 'PlaceholderNode %r leaked to checker' % node.fullname() + assert False, 'PlaceholderNode %r leaked to checker' % node.fullname # Unknown reference; use any type implicitly to avoid # generating extra type errors. result = AnyType(TypeOfAny.from_error) @@ -243,12 +243,12 @@ def analyze_var_ref(self, var: Var, context: Context) -> Type: if isinstance(var_type, Instance): if self.is_literal_context() and var_type.last_known_value is not None: return var_type.last_known_value - if var.name() in {'True', 'False'}: - return self.infer_literal_expr_type(var.name() == 'True', 'builtins.bool') + if var.name in {'True', 'False'}: + return self.infer_literal_expr_type(var.name == 'True', 'builtins.bool') return var.type else: if not var.is_ready and self.chk.in_checked_function(): - self.chk.handle_cannot_determine_type(var.name(), context) + self.chk.handle_cannot_determine_type(var.name, context) # Implicit 'Any' type. return AnyType(TypeOfAny.special_form) @@ -328,7 +328,7 @@ def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) -> if isinstance(e.callee.node, TypeAlias): target = get_proper_type(e.callee.node.target) if isinstance(target, Instance): - fullname = target.type.fullname() + fullname = target.type.fullname # * Call to a method on object that has a full name (see # method_fullname() for details on supported objects); # get_method_hook() and get_method_signature_hook() will @@ -386,12 +386,12 @@ def method_fullname(self, object_type: Type, method_name: str) -> Optional[str]: type_name = None if isinstance(object_type, Instance): - type_name = object_type.type.fullname() + type_name = object_type.type.fullname elif isinstance(object_type, (TypedDictType, LiteralType)): info = object_type.fallback.type.get_containing_type_info(method_name) - type_name = info.fullname() if info is not None else None + type_name = info.fullname if info is not None else None elif isinstance(object_type, TupleType): - type_name = tuple_fallback(object_type).type.fullname() + type_name = tuple_fallback(object_type).type.fullname if type_name is not None: return '{}.{}'.format(type_name, method_name) @@ -558,7 +558,7 @@ def try_infer_partial_type(self, e: CallExpr) -> None: partial_type.type is None): # A partial None type -> can't infer anything. return - typename = partial_type.type.fullname() + typename = partial_type.type.fullname methodname = e.callee.name # Sometimes we can infer a full type for a partial List, Dict or Set type. # TODO: Don't infer argument expression twice. @@ -575,7 +575,7 @@ def try_infer_partial_type(self, e: CallExpr) -> None: and e.arg_kinds == [ARG_POS]): arg_type = get_proper_type(self.accept(e.args[0])) if isinstance(arg_type, Instance): - arg_typename = arg_type.type.fullname() + arg_typename = arg_type.type.fullname if arg_typename in self.container_args[typename][methodname]: full_item_types = [ make_simplified_union([item_type, prev_type]) @@ -801,7 +801,7 @@ def check_call(self, is_super=False, is_operator=True, msg=self.msg, original_type=callee, chk=self.chk, in_literal_context=self.is_literal_context()) - callable_name = callee.type.fullname() + ".__call__" + callable_name = callee.type.fullname + ".__call__" # Apply method signature hook, if one exists call_function = self.transform_callee_type( callable_name, call_function, args, arg_kinds, context, arg_names, callee) @@ -840,7 +840,7 @@ def check_callable_call(self, callable_name = callee.name ret_type = get_proper_type(callee.ret_type) if callee.is_type_obj() and isinstance(ret_type, Instance): - callable_name = ret_type.type.fullname() + callable_name = ret_type.type.fullname if (isinstance(callable_node, RefExpr) and callable_node.fullname in ('enum.Enum', 'enum.IntEnum', 'enum.Flag', 'enum.IntFlag')): @@ -853,13 +853,13 @@ def check_callable_call(self, and not callee.type_object().fallback_to_any): type = callee.type_object() self.msg.cannot_instantiate_abstract_class( - callee.type_object().name(), type.abstract_attributes, + callee.type_object().name, type.abstract_attributes, context) elif (callee.is_type_obj() and callee.type_object().is_protocol # Exception for Type[...] and not callee.from_type_type): self.chk.fail(message_registry.CANNOT_INSTANTIATE_PROTOCOL - .format(callee.type_object().name()), context) + .format(callee.type_object().name), context) formal_to_actual = map_actuals_to_formals( arg_kinds, arg_names, @@ -935,7 +935,7 @@ def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type: return callee # We support Type of namedtuples but not of tuples in general if (isinstance(item, TupleType) - and tuple_fallback(item).type.fullname() != 'builtins.tuple'): + and tuple_fallback(item).type.fullname != 'builtins.tuple'): return self.analyze_type_type_callee(tuple_fallback(item), context) self.msg.unsupported_type_type(item, context) @@ -2180,8 +2180,8 @@ def dangerous_comparison(self, left: Type, right: Type, return False if isinstance(left, Instance) and isinstance(right, Instance): # Special case some builtin implementations of AbstractSet. - if (left.type.fullname() in OVERLAPPING_TYPES_WHITELIST and - right.type.fullname() in OVERLAPPING_TYPES_WHITELIST): + if (left.type.fullname in OVERLAPPING_TYPES_WHITELIST and + right.type.fullname in OVERLAPPING_TYPES_WHITELIST): abstract_set = self.chk.lookup_typeinfo('typing.AbstractSet') left = map_instance_to_supertype(left, abstract_set) right = map_instance_to_supertype(right, abstract_set) @@ -2334,7 +2334,7 @@ def lookup_definer(typ: Instance, attr_name: str) -> Optional[str]: """ for cls in typ.type.mro: if cls.names.get(attr_name): - return cls.fullname() + return cls.fullname return None left_type = get_proper_type(left_type) @@ -2899,7 +2899,7 @@ def visit_reveal_expr(self, expr: RevealExpr) -> Type: # calculated at semantic analysis time. Use it to pull out the # corresponding subset of variables in self.chk.type_map names_to_types = { - var_node.name(): var_node.type for var_node in expr.local_nodes + var_node.name: var_node.type for var_node in expr.local_nodes } if expr.local_nodes is not None else {} self.msg.reveal_locals(names_to_types, expr) @@ -2988,7 +2988,7 @@ class LongName(Generic[T]): ... return self.apply_type_arguments_to_callable(tp, item.args, ctx) elif (isinstance(item, TupleType) and # Tuple[str, int]() fails at runtime, only named tuples and subclasses work. - tuple_fallback(item).type.fullname() != 'builtins.tuple'): + tuple_fallback(item).type.fullname != 'builtins.tuple'): return type_object_type(tuple_fallback(item).type, self.named_type) elif isinstance(item, AnyType): return AnyType(TypeOfAny.from_another_any, source_any=item) @@ -3793,7 +3793,7 @@ def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = Fals # Determine the type of the entire yield from expression. iter_type = get_proper_type(iter_type) if (isinstance(iter_type, Instance) and - iter_type.type.fullname() == 'typing.Generator'): + iter_type.type.fullname == 'typing.Generator'): expr_type = self.chk.get_generator_return_type(iter_type, False) else: # Non-Generators don't return anything from `yield from` expressions. @@ -3906,7 +3906,7 @@ def visit_any(self, t: AnyType) -> bool: def has_coroutine_decorator(t: Type) -> bool: """Whether t came from a function decorated with `@coroutine`.""" t = get_proper_type(t) - return isinstance(t, Instance) and t.type.fullname() == 'typing.AwaitableGenerator' + return isinstance(t, Instance) and t.type.fullname == 'typing.AwaitableGenerator' def is_async_def(t: Type) -> bool: @@ -3925,10 +3925,10 @@ def is_async_def(t: Type) -> bool: # decorations.) t = get_proper_type(t) if (isinstance(t, Instance) - and t.type.fullname() == 'typing.AwaitableGenerator' + and t.type.fullname == 'typing.AwaitableGenerator' and len(t.args) >= 4): t = get_proper_type(t.args[3]) - return isinstance(t, Instance) and t.type.fullname() == 'typing.Coroutine' + return isinstance(t, Instance) and t.type.fullname == 'typing.Coroutine' def is_non_empty_tuple(t: Type) -> bool: @@ -4025,7 +4025,7 @@ def arg_approximate_similarity(actual: Type, formal: Type) -> bool: def is_typetype_like(typ: ProperType) -> bool: return (isinstance(typ, TypeType) or (isinstance(typ, FunctionLike) and typ.is_type_obj()) - or (isinstance(typ, Instance) and typ.type.fullname() == "builtins.type")) + or (isinstance(typ, Instance) and typ.type.fullname == "builtins.type")) if isinstance(formal, CallableType): if isinstance(actual, (CallableType, Overloaded, TypeType)): @@ -4205,7 +4205,7 @@ def custom_equality_method(typ: Type) -> bool: method = typ.type.get('__eq__') if method and isinstance(method.node, (SYMBOL_FUNCBASE_TYPES, Decorator, Var)): if method.node.info: - return not method.node.info.fullname().startswith('builtins.') + return not method.node.info.fullname.startswith('builtins.') return False if isinstance(typ, UnionType): return any(custom_equality_method(t) for t in typ.items) @@ -4230,7 +4230,7 @@ def has_bytes_component(typ: Type, py2: bool = False) -> bool: byte_types = {'builtins.bytes', 'builtins.bytearray'} if isinstance(typ, UnionType): return any(has_bytes_component(t) for t in typ.items) - if isinstance(typ, Instance) and typ.type.fullname() in byte_types: + if isinstance(typ, Instance) and typ.type.fullname in byte_types: return True return False diff --git a/mypy/checkmember.py b/mypy/checkmember.py index 7d867404cc7e..a3a086402ad5 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -180,7 +180,7 @@ def analyze_instance_member_access(name: str, info = override_info if (state.find_occurrences and - info.name() == state.find_occurrences[0] and + info.name == state.find_occurrences[0] and name == state.find_occurrences[1]): mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context) @@ -375,7 +375,7 @@ def analyze_member_var_access(name: str, # __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': + if method and method.info.fullname != 'builtins.object': function = function_type(method, mx.builtin_type('builtins.function')) bound_method = bind_self(function, mx.self_type) typ = map_instance_to_supertype(itype, method.info) @@ -384,7 +384,7 @@ def analyze_member_var_access(name: str, result = getattr_type.ret_type # Call the attribute hook before returning. - fullname = '{}.{}'.format(method.info.fullname(), name) + fullname = '{}.{}'.format(method.info.fullname, name) hook = mx.chk.plugin.get_attribute_hook(fullname) if hook: result = hook(AttributeContext(get_proper_type(mx.original_type), @@ -392,7 +392,7 @@ def analyze_member_var_access(name: str, return result else: setattr_meth = info.get_method('__setattr__') - if setattr_meth and setattr_meth.info.fullname() != 'builtins.object': + if setattr_meth and setattr_meth.info.fullname != 'builtins.object': setattr_func = function_type(setattr_meth, mx.builtin_type('builtins.function')) bound_type = bind_self(setattr_func, mx.self_type) typ = map_instance_to_supertype(itype, setattr_meth.info) @@ -566,10 +566,10 @@ def analyze_var(name: str, result = signature else: if not var.is_ready: - mx.not_ready_callback(var.name(), mx.context) + mx.not_ready_callback(var.name, mx.context) # Implicit 'Any' type. result = AnyType(TypeOfAny.special_form) - fullname = '{}.{}'.format(var.info.fullname(), name) + fullname = '{}.{}'.format(var.info.fullname, name) hook = mx.chk.plugin.get_attribute_hook(fullname) if result and not mx.is_lvalue and not implicit: result = analyze_descriptor_access(mx.original_type, result, mx.builtin_type, @@ -682,7 +682,7 @@ def analyze_class_attribute_access(itype: Instance, # can't be accessed on the class object. if node.implicit and isinstance(node.node, Var) and node.node.is_final: mx.msg.fail(message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR - .format(node.node.name()), mx.context) + .format(node.node.name), mx.context) # An assignment to final attribute on class object is also always an error, # independently of types. @@ -757,7 +757,7 @@ def analyze_class_attribute_access(itype: Instance, if isinstance(node.node, TypeVarExpr): mx.msg.fail(message_registry.CANNOT_USE_TYPEVAR_AS_EXPRESSION.format( - info.name(), name), mx.context) + info.name, name), mx.context) return AnyType(TypeOfAny.from_error) if isinstance(node.node, TypeInfo): @@ -878,7 +878,7 @@ def type_object_type(info: TypeInfo, builtin_type: Callable[[str], Instance]) -> method = new_method.node is_new = True else: - if init_method.node.info.fullname() == 'builtins.object': + if init_method.node.info.fullname == 'builtins.object': # Both are defined by object. But if we've got a bogus # base class, we can't know for sure, so check for that. if info.fallback_to_any: diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py index 08be7f86a2c1..6f7647d98846 100644 --- a/mypy/checkstrformat.py +++ b/mypy/checkstrformat.py @@ -656,7 +656,7 @@ def check_simple_str_interpolation(self, specifiers: List[ConversionSpecifier], rep_types = rhs_type.items elif isinstance(rhs_type, AnyType): return - elif isinstance(rhs_type, Instance) and rhs_type.type.fullname() == 'builtins.tuple': + elif isinstance(rhs_type, Instance) and rhs_type.type.fullname == 'builtins.tuple': # Assume that an arbitrary-length tuple has the right number of items. rep_types = [rhs_type.args[0]] * len(checkers) elif isinstance(rhs_type, UnionType): @@ -974,7 +974,7 @@ def custom_special_method(typ: Type, name: str, method = typ.type.get(name) if method and isinstance(method.node, (SYMBOL_FUNCBASE_TYPES, Decorator, Var)): if method.node.info: - return not method.node.info.fullname().startswith('builtins.') + return not method.node.info.fullname.startswith('builtins.') return False if isinstance(typ, UnionType): if check_all: diff --git a/mypy/constraints.py b/mypy/constraints.py index 91e602f87ef6..1f380f0ebf2e 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -329,7 +329,7 @@ def visit_instance(self, template: Instance) -> List[Constraint]: # We always try nominal inference if possible, # it is much faster than the structural one. if (self.direction == SUBTYPE_OF and - template.type.has_base(instance.type.fullname())): + template.type.has_base(instance.type.fullname)): mapped = map_instance_to_supertype(template, instance.type) tvars = mapped.type.defn.type_vars for i in range(len(instance.args)): @@ -343,7 +343,7 @@ def visit_instance(self, template: Instance) -> List[Constraint]: 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())): + instance.type.has_base(template.type.fullname)): mapped = map_instance_to_supertype(instance, template.type) tvars = template.type.defn.type_vars for j in range(len(template.args)): diff --git a/mypy/fastparse.py b/mypy/fastparse.py index 6e6e90bd4d07..402853bec113 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -431,7 +431,7 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: for stmt in stmts: if (current_overload_name is not None and isinstance(stmt, (Decorator, FuncDef)) - and stmt.name() == current_overload_name): + and stmt.name == current_overload_name): current_overload.append(stmt) else: if len(current_overload) == 1: @@ -441,7 +441,7 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: if isinstance(stmt, Decorator): current_overload = [stmt] - current_overload_name = stmt.name() + current_overload_name = stmt.name else: current_overload = [] current_overload_name = None @@ -509,7 +509,7 @@ def do_func_def(self, n: Union[ast3.FunctionDef, ast3.AsyncFunctionDef], posonlyargs = [arg.arg for arg in getattr(n.args, "posonlyargs", [])] arg_kinds = [arg.kind for arg in args] - arg_names = [arg.variable.name() for arg in args] # type: List[Optional[str]] + arg_names = [arg.variable.name for arg in args] # type: List[Optional[str]] arg_names = [None if argument_elide_name(name) or name in posonlyargs else name for name in arg_names] if special_function_elide_names(n.name): @@ -610,7 +610,7 @@ def do_func_def(self, n: Union[ast3.FunctionDef, ast3.AsyncFunctionDef], # existing "# type: ignore" comments working: end_lineno = n.decorator_list[0].lineno + len(n.decorator_list) - var = Var(func_def.name()) + var = Var(func_def.name) var.is_ready = False var.set_line(lineno) @@ -676,7 +676,7 @@ def transform_args(self, new_args.append(self.make_argument(args.kwarg, None, ARG_STAR2, no_type_check)) names.append(args.kwarg) - check_arg_names([arg.variable.name() for arg in new_args], names, self.fail_arg) + check_arg_names([arg.variable.name for arg in new_args], names, self.fail_arg) return new_args diff --git a/mypy/fastparse2.py b/mypy/fastparse2.py index b8cbef904a12..f34319a67b2d 100644 --- a/mypy/fastparse2.py +++ b/mypy/fastparse2.py @@ -303,7 +303,7 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: for stmt in stmts: if (current_overload_name is not None and isinstance(stmt, (Decorator, FuncDef)) - and stmt.name() == current_overload_name): + and stmt.name == current_overload_name): current_overload.append(stmt) else: if len(current_overload) == 1: @@ -313,7 +313,7 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: if isinstance(stmt, Decorator): current_overload = [stmt] - current_overload_name = stmt.name() + current_overload_name = stmt.name else: current_overload = [] current_overload_name = None @@ -369,7 +369,7 @@ def visit_FunctionDef(self, n: ast27.FunctionDef) -> Statement: args, decompose_stmts = self.transform_args(n.args, lineno) arg_kinds = [arg.kind for arg in args] - arg_names = [arg.variable.name() for arg in args] # type: List[Optional[str]] + 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) @@ -449,7 +449,7 @@ def visit_FunctionDef(self, n: ast27.FunctionDef) -> Statement: func_type.line = lineno if n.decorator_list: - var = Var(func_def.name()) + var = Var(func_def.name) var.is_ready = False var.set_line(n.decorator_list[0].lineno) diff --git a/mypy/fixup.py b/mypy/fixup.py index 73458c59e619..e3555b9ba7f3 100644 --- a/mypy/fixup.py +++ b/mypy/fixup.py @@ -266,7 +266,7 @@ def lookup_qualified_typeinfo(modules: Dict[str, MypyFile], name: str, # Looks like a missing TypeInfo during an initial daemon load, put something there assert allow_missing, "Should never get here in normal mode," \ " got {}:{} instead of TypeInfo".format(type(node).__name__, - node.fullname() if node + node.fullname if node else '') return missing_info(modules) @@ -280,7 +280,7 @@ def lookup_qualified_alias(modules: Dict[str, MypyFile], name: str, # Looks like a missing TypeAlias during an initial daemon load, put something there assert allow_missing, "Should never get here in normal mode," \ " got {}:{} instead of TypeAlias".format(type(node).__name__, - node.fullname() if node + node.fullname if node else '') return missing_alias() diff --git a/mypy/indirection.py b/mypy/indirection.py index bae9be4cb750..307628c2abc5 100644 --- a/mypy/indirection.py +++ b/mypy/indirection.py @@ -79,7 +79,7 @@ def visit_instance(self, t: types.Instance) -> Set[str]: def visit_callable_type(self, t: types.CallableType) -> Set[str]: out = self._visit(t.arg_types) | self._visit(t.ret_type) if t.definition is not None: - out.update(extract_module_names(t.definition.fullname())) + out.update(extract_module_names(t.definition.fullname)) return out def visit_overloaded(self, t: types.Overloaded) -> Set[str]: diff --git a/mypy/join.py b/mypy/join.py index 7472c2dead93..5f1d292d65e2 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -302,7 +302,7 @@ def visit_partial_type(self, t: PartialType) -> ProperType: def visit_type_type(self, t: TypeType) -> ProperType: if isinstance(self.s, TypeType): return TypeType.make_normalized(self.join(t.item, self.s.item), line=t.line) - elif isinstance(self.s, Instance) and self.s.type.fullname() == 'builtins.type': + elif isinstance(self.s, Instance) and self.s.type.fullname == 'builtins.type': return self.s else: return self.default(self.s) @@ -406,7 +406,7 @@ def join_similar_callables(t: CallableType, s: CallableType) -> CallableType: # TODO in combine_similar_callables also applies here (names and kinds) # The fallback type can be either 'function' or 'type'. The result should have 'type' as # fallback only if both operands have it as 'type'. - if t.fallback.type.fullname() != 'builtins.type': + if t.fallback.type.fullname != 'builtins.type': fallback = t.fallback else: fallback = s.fallback @@ -424,7 +424,7 @@ def combine_similar_callables(t: CallableType, s: CallableType) -> CallableType: # TODO kinds and argument names # The fallback type can be either 'function' or 'type'. The result should have 'type' as # fallback only if both operands have it as 'type'. - if t.fallback.type.fullname() != 'builtins.type': + if t.fallback.type.fullname != 'builtins.type': fallback = t.fallback else: fallback = s.fallback diff --git a/mypy/meet.py b/mypy/meet.py index 59e94a24596f..6e9c68d29529 100644 --- a/mypy/meet.py +++ b/mypy/meet.py @@ -78,7 +78,7 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type: return meet_types(declared, narrowed) elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance): # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). - if (narrowed.type.fullname() == 'builtins.dict' and + if (narrowed.type.fullname == 'builtins.dict' and all(isinstance(t, AnyType) for t in get_proper_types(narrowed.args))): return declared return meet_types(declared, narrowed) @@ -317,9 +317,9 @@ def _type_object_overlap(left: Type, right: Type) -> bool: return True # Two unrelated types cannot be partially overlapping: they're disjoint. - if left.type.has_base(right.type.fullname()): + if left.type.has_base(right.type.fullname): left = map_instance_to_supertype(left, right.type) - elif right.type.has_base(left.type.fullname()): + elif right.type.has_base(left.type.fullname): right = map_instance_to_supertype(right, left.type) else: return False @@ -409,7 +409,7 @@ def are_tuples_overlapping(left: Type, right: Type, *, def adjust_tuple(left: ProperType, r: ProperType) -> Optional[TupleType]: """Find out if `left` is a Tuple[A, ...], and adjust its length to `right`""" - if isinstance(left, Instance) and left.type.fullname() == 'builtins.tuple': + if isinstance(left, Instance) and left.type.fullname == 'builtins.tuple': n = r.length() if isinstance(r, TupleType) else 1 return TupleType([left.args[0]] * n, left) return None @@ -418,7 +418,7 @@ def adjust_tuple(left: ProperType, r: ProperType) -> Optional[TupleType]: def is_tuple(typ: Type) -> bool: typ = get_proper_type(typ) return (isinstance(typ, TupleType) - or (isinstance(typ, Instance) and typ.type.fullname() == 'builtins.tuple')) + or (isinstance(typ, Instance) and typ.type.fullname == 'builtins.tuple')) class TypeMeetVisitor(TypeVisitor[ProperType]): @@ -453,7 +453,7 @@ def visit_union_type(self, t: UnionType) -> ProperType: def visit_none_type(self, t: NoneType) -> ProperType: if state.strict_optional: if isinstance(self.s, NoneType) or (isinstance(self.s, Instance) and - self.s.type.fullname() == 'builtins.object'): + self.s.type.fullname == 'builtins.object'): return t else: return UninhabitedType() @@ -577,7 +577,7 @@ def visit_tuple_type(self, t: TupleType) -> ProperType: return TupleType(items, tuple_fallback(t)) elif isinstance(self.s, Instance): # meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>]. - if self.s.type.fullname() == 'builtins.tuple' and self.s.args: + if self.s.type.fullname == 'builtins.tuple' and self.s.args: return t.copy_modified(items=[meet_types(it, self.s.args[0]) for it in t.items]) elif is_proper_subtype(t, self.s): # A named tuple that inherits from a normal class @@ -626,7 +626,7 @@ def visit_type_type(self, t: TypeType) -> ProperType: if not isinstance(typ, NoneType): typ = TypeType.make_normalized(typ, line=t.line) return typ - elif isinstance(self.s, Instance) and self.s.type.fullname() == 'builtins.type': + elif isinstance(self.s, Instance) and self.s.type.fullname == 'builtins.type': return t elif isinstance(self.s, CallableType): return self.meet(t, self.s) @@ -657,7 +657,7 @@ def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType: # TODO in combine_similar_callables also applies here (names and kinds) # The fallback type can be either 'function' or 'type'. The result should have 'function' as # fallback only if both operands have it as 'function'. - if t.fallback.type.fullname() != 'builtins.function': + if t.fallback.type.fullname != 'builtins.function': fallback = t.fallback else: fallback = s.fallback @@ -739,7 +739,7 @@ def typed_dict_mapping_overlap(left: Type, right: Type, assert isinstance(right, TypedDictType) typed, other = right, left - mapping = next(base for base in other.type.mro if base.fullname() == 'typing.Mapping') + mapping = next(base for base in other.type.mro if base.fullname == 'typing.Mapping') other = map_instance_to_supertype(other, mapping) key_type, value_type = get_proper_types(other.args) diff --git a/mypy/messages.py b/mypy/messages.py index 29b99352cfec..6fe7afedd03a 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -226,7 +226,7 @@ def has_no_attr(self, original_type: Type, typ: Type, member: str, context: Cont self.fail('Unsupported target for indexed assignment', context, code=codes.INDEX) elif member == '__call__': if isinstance(original_type, Instance) and \ - (original_type.type.fullname() == 'builtins.function'): + (original_type.type.fullname == 'builtins.function'): # "'function' not callable" is a confusing error message. # Explain that the problem is that the type of the function is not known. self.fail('Cannot call function of unknown type', context, code=codes.OPERATOR) @@ -862,7 +862,7 @@ def base_class_definitions_incompatible(self, name: str, base1: TypeInfo, context: Context) -> None: self.fail('Definition of "{}" in base class "{}" is incompatible ' 'with definition in base class "{}"'.format( - name, base1.name(), base2.name()), context) + name, base1.name, base2.name), context) def cant_assign_to_method(self, context: Context) -> None: self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, @@ -895,7 +895,7 @@ def final_without_value(self, ctx: Context) -> None: def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: self.fail('Property "{}" defined in "{}" is read-only'.format( - name, type.name()), context) + name, type.name), context) def incompatible_typevar_value(self, callee: CallableType, @@ -958,7 +958,7 @@ def operator_method_signatures_overlap( forward_method: str, context: Context) -> None: self.fail('Signatures of "{}" of "{}" and "{}" of {} ' 'are unsafely overlapping'.format( - reverse_method, reverse_class.name(), + reverse_method, reverse_class.name, forward_method, format_type(forward_class)), context) @@ -1012,23 +1012,23 @@ def need_annotation_for_var(self, node: SymbolNode, context: Context, has_variable_annotations = not python_version or python_version >= (3, 6) # Only gives hint if it's a variable declaration and the partial type is a builtin type if (python_version and isinstance(node, Var) and isinstance(node.type, PartialType) and - node.type.type and node.type.type.fullname() in reverse_builtin_aliases): - alias = reverse_builtin_aliases[node.type.type.fullname()] + node.type.type and node.type.type.fullname in reverse_builtin_aliases): + alias = reverse_builtin_aliases[node.type.type.fullname] alias = alias.split('.')[-1] type_dec = '' if alias == 'Dict': type_dec = '{}, {}'.format(type_dec, type_dec) if has_variable_annotations: - hint = ' (hint: "{}: {}[{}] = ...")'.format(node.name(), alias, type_dec) + hint = ' (hint: "{}: {}[{}] = ...")'.format(node.name, alias, type_dec) else: - hint = ' (hint: "{} = ... # type: {}[{}]")'.format(node.name(), alias, type_dec) + hint = ' (hint: "{} = ... # type: {}[{}]")'.format(node.name, alias, type_dec) if has_variable_annotations: needed = 'annotation' else: needed = 'comment' - self.fail("Need type {} for '{}'{}".format(needed, unmangle(node.name()), hint), context, + self.fail("Need type {} for '{}'{}".format(needed, unmangle(node.name), hint), context, code=codes.VAR_ANNOTATED) def explicit_any(self, ctx: Context) -> None: @@ -1175,7 +1175,7 @@ def report_non_method_protocol(self, tp: TypeInfo, members: List[str], if len(members) < 3: attrs = ', '.join(members) self.note('Protocol "{}" has non-method member(s): {}' - .format(tp.name(), attrs), context) + .format(tp.name, attrs), context) def note_call(self, subtype: Type, @@ -1236,7 +1236,7 @@ def report_protocol_problems(self, exclusions = {TypedDictType: ['typing.Mapping'], TupleType: ['typing.Iterable', 'typing.Sequence'], Instance: []} # type: Dict[type, List[str]] - if supertype.type.fullname() in exclusions[type(subtype)]: + if supertype.type.fullname in exclusions[type(subtype)]: return if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)): # We don't want to add notes for failed inference (e.g. Iterable[]). @@ -1257,7 +1257,7 @@ def report_protocol_problems(self, if (missing and len(missing) < len(supertype.type.protocol_members) and len(missing) <= MAX_ITEMS): self.note("'{}' is missing following '{}' protocol member{}:" - .format(subtype.type.name(), supertype.type.name(), plural_s(missing)), + .format(subtype.type.name, supertype.type.name, plural_s(missing)), context, code=code) self.note(', '.join(missing), context, offset=OFFSET, code=code) @@ -1304,22 +1304,22 @@ def report_protocol_problems(self, for name, subflags, superflags in conflict_flags[:MAX_ITEMS]: if IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags: self.note('Protocol member {}.{} expected instance variable,' - ' got class variable'.format(supertype.type.name(), name), + ' got class variable'.format(supertype.type.name, name), context, code=code) if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: self.note('Protocol member {}.{} expected class variable,' - ' got instance variable'.format(supertype.type.name(), name), + ' got instance variable'.format(supertype.type.name, name), context, code=code) if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: self.note('Protocol member {}.{} expected settable variable,' - ' got read-only attribute'.format(supertype.type.name(), name), + ' got read-only attribute'.format(supertype.type.name, name), context, code=code) if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: self.note('Protocol member {}.{} expected class or static method' - .format(supertype.type.name(), name), + .format(supertype.type.name, name), context, code=code) self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=code) @@ -1418,22 +1418,22 @@ def format(typ: Type) -> str: if isinstance(typ, Instance): itype = typ # Get the short name of the type. - if itype.type.fullname() in ('types.ModuleType', + if itype.type.fullname in ('types.ModuleType', '_importlib_modulespec.ModuleType'): # Make some common error messages simpler and tidier. return 'Module' - if verbosity >= 2 or (fullnames and itype.type.fullname() in fullnames): - base_str = itype.type.fullname() + if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames): + base_str = itype.type.fullname else: - base_str = itype.type.name() + base_str = itype.type.name if itype.args == []: # No type arguments, just return the type name return base_str - elif itype.type.fullname() == 'builtins.tuple': + elif itype.type.fullname == 'builtins.tuple': item_type_str = format(itype.args[0]) return 'Tuple[{}, ...]'.format(item_type_str) - elif itype.type.fullname() in reverse_builtin_aliases: - alias = reverse_builtin_aliases[itype.type.fullname()] + elif itype.type.fullname in reverse_builtin_aliases: + alias = reverse_builtin_aliases[itype.type.fullname] alias = alias.split('.')[-1] items = [format(arg) for arg in itype.args] return '{}[{}]'.format(alias, ', '.join(items)) @@ -1453,7 +1453,7 @@ def format(typ: Type) -> str: return typ.name elif isinstance(typ, TupleType): # Prefer the name of the fallback class (if not tuple), as it's more informative. - if typ.partial_fallback.type.fullname() != 'builtins.tuple': + if typ.partial_fallback.type.fullname != 'builtins.tuple': return format(typ.partial_fallback) items = [] for t in typ.items: @@ -1584,7 +1584,7 @@ def find_type_overlaps(*types: Type) -> Set[str]: d = {} # type: Dict[str, Set[str]] for type in types: for inst in collect_all_instances(type): - d.setdefault(inst.type.name(), set()).add(inst.type.fullname()) + d.setdefault(inst.type.name, set()).add(inst.type.fullname) overlaps = set() # type: Set[str] for fullnames in d.values(): @@ -1674,14 +1674,14 @@ def [T <: int] f(self, x: int, y: T) -> None s += ' = ...' # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list - if isinstance(tp.definition, FuncDef) and tp.definition.name() is not None: + if isinstance(tp.definition, FuncDef) and tp.definition.name is not None: definition_args = tp.definition.arg_names if definition_args and tp.arg_names != definition_args \ and len(definition_args) > 0: if s: s = ', ' + s s = definition_args[0] + s - s = '{}({})'.format(tp.definition.name(), s) + s = '{}({})'.format(tp.definition.name, s) elif tp.name: first_arg = tp.def_extras.get('first_arg') if first_arg: @@ -1698,7 +1698,7 @@ def [T <: int] f(self, x: int, y: T) -> None for tvar in tp.variables: upper_bound = get_proper_type(tvar.upper_bound) if (isinstance(upper_bound, Instance) and - upper_bound.type.fullname() != 'builtins.object'): + upper_bound.type.fullname != 'builtins.object'): tvars.append('{} <: {}'.format(tvar.name, format_type_bare(upper_bound))) elif tvar.values: tvars.append('{} in ({})' @@ -1844,7 +1844,7 @@ def for_function(callee: CallableType) -> str: def find_defining_module(modules: Dict[str, MypyFile], typ: CallableType) -> Optional[MypyFile]: if not typ.definition: return None - fullname = typ.definition.fullname() + fullname = typ.definition.fullname if fullname is not None and '.' in fullname: for i in range(fullname.count('.')): module_name = fullname.rsplit('.', i + 1)[0] @@ -1887,13 +1887,13 @@ def append_invariance_notes(notes: List[str], arg_type: Instance, """Explain that the type is invariant and give notes for how to solve the issue.""" invariant_type = '' covariant_suggestion = '' - if (arg_type.type.fullname() == 'builtins.list' and - expected_type.type.fullname() == 'builtins.list' and + if (arg_type.type.fullname == 'builtins.list' and + expected_type.type.fullname == 'builtins.list' and is_subtype(arg_type.args[0], expected_type.args[0])): invariant_type = 'List' covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' - elif (arg_type.type.fullname() == 'builtins.dict' and - expected_type.type.fullname() == 'builtins.dict' and + elif (arg_type.type.fullname == 'builtins.dict' and + expected_type.type.fullname == 'builtins.dict' and is_same_type(arg_type.args[0], expected_type.args[0]) and is_subtype(arg_type.args[1], expected_type.args[1])): invariant_type = 'Dict' @@ -1922,7 +1922,7 @@ def make_inferred_type_note(context: Context, supertype = get_proper_type(supertype) if (isinstance(subtype, Instance) and isinstance(supertype, Instance) and - subtype.type.fullname() == supertype.type.fullname() and + subtype.type.fullname == supertype.type.fullname and subtype.args and supertype.args and isinstance(context, ReturnStmt) and diff --git a/mypy/mro.py b/mypy/mro.py index 7cda9c623836..59c53996e628 100644 --- a/mypy/mro.py +++ b/mypy/mro.py @@ -28,7 +28,7 @@ def linearize_hierarchy(info: TypeInfo, if info.mro: return info.mro bases = info.direct_base_classes() - if (not bases and info.fullname() != 'builtins.object' and + if (not bases and info.fullname != 'builtins.object' and obj_type is not None): # Second pass in import cycle, add a dummy `object` base class, # otherwise MRO calculation may spuriously fail. @@ -36,7 +36,7 @@ def linearize_hierarchy(info: TypeInfo, bases = [obj_type().type] lin_bases = [] for base in bases: - assert base is not None, "Cannot linearize bases for %s %s" % (info.fullname(), bases) + assert base is not None, "Cannot linearize bases for %s %s" % (info.fullname, bases) lin_bases.append(linearize_hierarchy(base, obj_type)) lin_bases.append(bases) return [info] + merge(lin_bases) diff --git a/mypy/nodes.py b/mypy/nodes.py index 57107bad6af1..58709590492f 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -280,7 +280,7 @@ def local_definitions(self) -> Iterator[Definition]: This doesn't include imported definitions. """ - return local_definitions(self.names, self.fullname()) + return local_definitions(self.names, self.fullname) @property def name(self) -> str: @@ -505,11 +505,11 @@ def __init__(self, items: List['OverloadPart']) -> None: @property def name(self) -> str: if self.items: - return self.items[0].name() + return self.items[0].name else: # This may happen for malformed overload assert self.impl is not None - return self.impl.name() + return self.impl.name def accept(self, visitor: StatementVisitor[T]) -> T: return visitor.visit_overloaded_func_def(self) @@ -603,7 +603,7 @@ def __init__(self, typ: 'Optional[mypy.types.FunctionLike]' = None) -> None: super().__init__() self.arguments = arguments - self.arg_names = [arg.variable.name() for arg in self.arguments] + self.arg_names = [arg.variable.name for arg in self.arguments] self.arg_kinds = [arg.kind for arg in self.arguments] # type: List[int] self.max_pos = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT) self.body = body @@ -744,11 +744,11 @@ def __init__(self, func: FuncDef, decorators: List[Expression], @property def name(self) -> str: - return self.func.name() + return self.func.name @property def fullname(self) -> Bogus[str]: - return self.func.fullname() + return self.func.fullname @property def is_final(self) -> bool: @@ -2449,7 +2449,7 @@ def __getitem__(self, name: str) -> 'SymbolTableNode': raise KeyError(name) def __repr__(self) -> str: - return '' % self.fullname() + return '' % self.fullname def __bool__(self) -> bool: # We defined this here instead of just overriding it in @@ -2486,7 +2486,7 @@ def calculate_metaclass_type(self) -> 'Optional[mypy.types.Instance]': return None def is_metaclass(self) -> bool: - return (self.has_base('builtins.type') or self.fullname() == 'abc.ABCMeta' or + return (self.has_base('builtins.type') or self.fullname == 'abc.ABCMeta' or self.fallback_to_any) def has_base(self, fullname: str) -> bool: @@ -2495,7 +2495,7 @@ def has_base(self, fullname: str) -> bool: This can be either via extension or via implementation. """ for cls in self.mro: - if cls.fullname() == fullname: + if cls.fullname == fullname: return True return False @@ -2530,7 +2530,7 @@ def type_str(typ: 'mypy.types.Type') -> str: if self.bases: base = 'Bases({})'.format(', '.join(type_str(base) for base in self.bases)) - mro = 'Mro({})'.format(', '.join(item.fullname() + str_conv.format_id(item) + mro = 'Mro({})'.format(', '.join(item.fullname + str_conv.format_id(item) for item in self.mro)) names = [] for name in sorted(self.names): @@ -2540,7 +2540,7 @@ def type_str(typ: 'mypy.types.Type') -> str: description += ' ({})'.format(type_str(node.type)) names.append(description) items = [ - 'Name({})'.format(self.fullname()), + 'Name({})'.format(self.fullname), base, mro, ('Names', names), @@ -2558,13 +2558,13 @@ def serialize(self) -> JsonDict: # NOTE: This is where all ClassDefs originate, so there shouldn't be duplicates. data = {'.class': 'TypeInfo', 'module_name': self.module_name, - 'fullname': self.fullname(), - 'names': self.names.serialize(self.fullname()), + 'fullname': self.fullname, + 'names': self.names.serialize(self.fullname), 'defn': self.defn.serialize(), 'abstract_attributes': self.abstract_attributes, 'type_vars': self.type_vars, 'bases': [b.serialize() for b in self.bases], - 'mro': [c.fullname() for c in self.mro], + 'mro': [c.fullname for c in self.mro], '_promote': None if self._promote is None else self._promote.serialize(), 'declared_metaclass': (None if self.declared_metaclass is None else self.declared_metaclass.serialize()), @@ -2954,7 +2954,7 @@ def __init__(self, @property def fullname(self) -> Optional[str]: if self.node is not None: - return self.node.fullname() + return self.node.fullname else: return None @@ -2980,7 +2980,7 @@ def copy(self) -> 'SymbolTableNode': def __str__(self) -> str: s = '{}/{}'.format(node_kinds[self.kind], short_type(self.node)) if isinstance(self.node, SymbolNode): - s += ' ({})'.format(self.node.fullname()) + s += ' ({})'.format(self.node.fullname) # Include declared type of variables and functions. if self.type is not None: s += ' : {}'.format(self.type) @@ -3005,11 +3005,11 @@ def serialize(self, prefix: str, name: str) -> JsonDict: if self.plugin_generated: data['plugin_generated'] = True if isinstance(self.node, MypyFile): - data['cross_ref'] = self.node.fullname() + data['cross_ref'] = self.node.fullname else: assert self.node is not None, '%s:%s' % (prefix, name) if prefix is not None: - fullname = self.node.fullname() + fullname = self.node.fullname if (fullname is not None and '.' in fullname and fullname != prefix + '.' + name and not (isinstance(self.node, Var) @@ -3194,7 +3194,7 @@ def local_definitions(names: SymbolTable, shortname = name.split('-redef')[0] fullname = name_prefix + '.' + shortname node = symnode.node - if node and node.fullname() == fullname: + if node and node.fullname == fullname: yield fullname, symnode, info if isinstance(node, TypeInfo): yield from local_definitions(node.names, fullname, node) diff --git a/mypy/plugin.py b/mypy/plugin.py index 6a2d40cc219b..3482fabe72e4 100644 --- a/mypy/plugin.py +++ b/mypy/plugin.py @@ -593,7 +593,7 @@ def get_attribute_hook(self, fullname: str """Adjust type of a class attribute. This method is called with attribute full name using the class where the attribute was - defined (or Var.info.fullname() for generated attributes). + defined (or Var.info.fullname for generated attributes). For classes without __getattr__ or __getattribute__, this hook is only called for names of fields/properties (but not methods) that exist in the instance MRO. diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 50a505eade44..540905839992 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -346,7 +346,7 @@ def _analyze_class(ctx: 'mypy.plugin.ClassDefContext', for super_info in ctx.cls.info.mro[1:-1]: if 'attrs' in super_info.metadata: # Each class depends on the set of attributes in its attrs ancestors. - ctx.api.add_plugin_dependency(make_wildcard_trigger(super_info.fullname())) + ctx.api.add_plugin_dependency(make_wildcard_trigger(super_info.fullname)) for data in super_info.metadata['attrs']['attributes']: # Only add an attribute if it hasn't been defined before. This @@ -538,12 +538,12 @@ def _parse_converter(ctx: 'mypy.plugin.ClassDefContext', if (isinstance(converter.node, FuncDef) and converter.node.type and isinstance(converter.node.type, FunctionLike)): - return Converter(converter.node.fullname()) + return Converter(converter.node.fullname) elif (isinstance(converter.node, OverloadedFuncDef) and is_valid_overloaded_converter(converter.node)): - return Converter(converter.node.fullname()) + return Converter(converter.node.fullname) elif isinstance(converter.node, TypeInfo): - return Converter(converter.node.fullname()) + return Converter(converter.node.fullname) if (isinstance(converter, CallExpr) and isinstance(converter.callee, RefExpr) @@ -606,10 +606,10 @@ def _add_order(ctx: 'mypy.plugin.ClassDefContext', adder: 'MethodAdder') -> None # AT = TypeVar('AT') # def __lt__(self: AT, other: AT) -> bool # This way comparisons with subclasses will work correctly. - tvd = TypeVarDef(SELF_TVAR_NAME, ctx.cls.info.fullname() + '.' + SELF_TVAR_NAME, + tvd = TypeVarDef(SELF_TVAR_NAME, ctx.cls.info.fullname + '.' + SELF_TVAR_NAME, -1, [], object_type) tvd_type = TypeVarType(tvd) - self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, ctx.cls.info.fullname() + '.' + SELF_TVAR_NAME, + self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, ctx.cls.info.fullname + '.' + SELF_TVAR_NAME, [], object_type) ctx.cls.info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) @@ -631,8 +631,8 @@ def _make_frozen(ctx: 'mypy.plugin.ClassDefContext', attributes: List[Attribute] # 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._fullname = '%s.%s' % (ctx.cls.info.fullname, var.name) + ctx.cls.info.names[var.name] = SymbolTableNode(MDEF, var) var.is_property = True diff --git a/mypy/plugins/common.py b/mypy/plugins/common.py index 64c86af146c8..6f2f5845cbeb 100644 --- a/mypy/plugins/common.py +++ b/mypy/plugins/common.py @@ -106,7 +106,7 @@ def add_method( for arg in args: assert arg.type_annotation, 'All arguments must be fully typed.' arg_types.append(arg.type_annotation) - arg_names.append(arg.variable.name()) + arg_names.append(arg.variable.name) arg_kinds.append(arg.kind) signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) @@ -116,7 +116,7 @@ def add_method( func = FuncDef(name, args, Block([PassStmt()])) func.info = info func.type = set_callable_name(signature, func) - func._fullname = info.fullname() + '.' + name + func._fullname = info.fullname + '.' + name func.line = info.line # NOTE: we would like the plugin generated node to dominate, but we still diff --git a/mypy/plugins/ctypes.py b/mypy/plugins/ctypes.py index 88fb2f04769e..d2b69e423d4b 100644 --- a/mypy/plugins/ctypes.py +++ b/mypy/plugins/ctypes.py @@ -94,7 +94,7 @@ def _autounboxed_cdata(tp: Type) -> ProperType: return make_simplified_union([_autounboxed_cdata(t) for t in tp.items]) elif isinstance(tp, Instance): for base in tp.type.bases: - if base.type.fullname() == 'ctypes._SimpleCData': + if base.type.fullname == 'ctypes._SimpleCData': # If tp has _SimpleCData as a direct base class, # the auto-unboxed type is the single type argument of the _SimpleCData type. assert len(base.args) == 1 @@ -108,7 +108,7 @@ def _get_array_element_type(tp: Type) -> Optional[ProperType]: """Get the element type of the Array type tp, or None if not specified.""" tp = get_proper_type(tp) if isinstance(tp, Instance): - assert tp.type.fullname() == 'ctypes.Array' + assert tp.type.fullname == 'ctypes.Array' if len(tp.args) == 1: return get_proper_type(tp.args[0]) return None @@ -198,9 +198,9 @@ def array_value_callback(ctx: 'mypy.plugin.AttributeContext') -> Type: for tp in union_items(et): if isinstance(tp, AnyType): types.append(AnyType(TypeOfAny.from_another_any, source_any=tp)) - elif isinstance(tp, Instance) and tp.type.fullname() == 'ctypes.c_char': + elif isinstance(tp, Instance) and tp.type.fullname == 'ctypes.c_char': types.append(_get_bytes_type(ctx.api)) - elif isinstance(tp, Instance) and tp.type.fullname() == 'ctypes.c_wchar': + elif isinstance(tp, Instance) and tp.type.fullname == 'ctypes.c_wchar': types.append(_get_text_type(ctx.api)) else: ctx.api.msg.fail( @@ -218,7 +218,7 @@ def array_raw_callback(ctx: 'mypy.plugin.AttributeContext') -> Type: types = [] # type: List[Type] for tp in union_items(et): if (isinstance(tp, AnyType) - or isinstance(tp, Instance) and tp.type.fullname() == 'ctypes.c_char'): + or isinstance(tp, Instance) and tp.type.fullname == 'ctypes.c_char'): types.append(_get_bytes_type(ctx.api)) else: ctx.api.msg.fail( diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index d4a43c617e29..ed3a0f4c997f 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -114,7 +114,7 @@ def transform(self) -> None: decorator_arguments['order']): # Type variable for self types in generated methods. obj_type = ctx.api.named_type('__builtins__.object') - self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname() + '.' + SELF_TVAR_NAME, + self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, [], obj_type) info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) @@ -125,7 +125,7 @@ def transform(self) -> None: # the same type as self (covariant). Note the # "self_type" parameter to add_method. obj_type = ctx.api.named_type('__builtins__.object') - cmp_tvar_def = TypeVarDef(SELF_TVAR_NAME, info.fullname() + '.' + SELF_TVAR_NAME, + cmp_tvar_def = TypeVarDef(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, -1, [], obj_type) cmp_other_type = TypeVarType(cmp_tvar_def) cmp_return_type = ctx.api.named_type('__builtins__.bool') @@ -148,7 +148,7 @@ def transform(self) -> None: # Like for __eq__ and __ne__, we want "other" to match # the self type. obj_type = ctx.api.named_type('__builtins__.object') - order_tvar_def = TypeVarDef(SELF_TVAR_NAME, info.fullname() + '.' + SELF_TVAR_NAME, + order_tvar_def = TypeVarDef(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, -1, [], obj_type) order_other_type = TypeVarType(order_tvar_def) order_return_type = ctx.api.named_type('__builtins__.bool') @@ -247,7 +247,7 @@ def collect_attributes(self) -> Optional[List[DataclassAttribute]]: is_init_var = False node_type = get_proper_type(node.type) if (isinstance(node_type, Instance) and - node_type.type.fullname() == 'dataclasses.InitVar'): + node_type.type.fullname == 'dataclasses.InitVar'): is_init_var = True node.type = node_type.args[0] @@ -297,7 +297,7 @@ def collect_attributes(self) -> Optional[List[DataclassAttribute]]: super_attrs = [] # Each class depends on the set of attributes in its dataclass ancestors. - ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname())) + ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname)) for data in info.metadata['dataclass']['attributes']: name = data['name'] # type: str @@ -363,8 +363,8 @@ def _freeze(self, attributes: List[DataclassAttribute]) -> None: var = attr.to_var(info) var.info = info var.is_property = True - var._fullname = info.fullname() + '.' + var.name() - info.names[var.name()] = SymbolTableNode(MDEF, var) + var._fullname = info.fullname + '.' + var.name + info.names[var.name] = SymbolTableNode(MDEF, var) def dataclass_class_maker_callback(ctx: ClassDefContext) -> None: diff --git a/mypy/plugins/enums.py b/mypy/plugins/enums.py index e842fed1f32f..81aa29afcb11 100644 --- a/mypy/plugins/enums.py +++ b/mypy/plugins/enums.py @@ -92,7 +92,7 @@ class SomeEnum: # TODO: Consider using the return type of `Enum._generate_next_value_` here? return ctx.default_attr_type - if isinstance(underlying_type, Instance) and underlying_type.type.fullname() == 'enum.auto': + if isinstance(underlying_type, Instance) and underlying_type.type.fullname == 'enum.auto': # TODO: Deduce the correct inferred type when the user uses 'enum.auto'. # We should use the same strategy we end up picking up above. return ctx.default_attr_type diff --git a/mypy/renaming.py b/mypy/renaming.py index abb7e2648b24..93d8addf54fb 100644 --- a/mypy/renaming.py +++ b/mypy/renaming.py @@ -92,11 +92,11 @@ def visit_func_def(self, fdef: FuncDef) -> None: self.enter_block() for arg in fdef.arguments: - name = arg.variable.name() + name = arg.variable.name # 'self' can't be redefined since it's special as it allows definition of # attributes. 'cls' can't be used to define attributes so we can ignore it. can_be_redefined = name != 'self' # TODO: Proper check - self.record_assignment(arg.variable.name(), can_be_redefined) + self.record_assignment(arg.variable.name, can_be_redefined) self.handle_arg(name) for stmt in fdef.body.body: diff --git a/mypy/report.py b/mypy/report.py index 2e80e854698b..d4da7d10dbcf 100644 --- a/mypy/report.py +++ b/mypy/report.py @@ -201,19 +201,19 @@ def on_file(self, type_map: Dict[Expression, Type], options: Options) -> None: visitor = stats.StatisticsVisitor(inferred=True, - filename=tree.fullname(), + filename=tree.fullname, modules=modules, typemap=type_map, all_nodes=True, visit_untyped_defs=False) tree.accept(visitor) - self.any_types_counter[tree.fullname()] = visitor.type_of_any_counter + self.any_types_counter[tree.fullname] = visitor.type_of_any_counter num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED) # count each line of dead code as one expression of type "Any" num_any = visitor.num_any_exprs + num_unanalyzed_lines num_total = visitor.num_imprecise_exprs + visitor.num_precise_exprs + num_any if num_total > 0: - self.counts[tree.fullname()] = (num_any, num_total) + self.counts[tree.fullname] = (num_any, num_total) def on_finish(self) -> None: self._report_any_exprs() @@ -464,7 +464,7 @@ def on_file(self, return visitor = stats.StatisticsVisitor(inferred=True, - filename=tree.fullname(), + filename=tree.fullname, modules=modules, typemap=type_map, all_nodes=True) @@ -586,7 +586,7 @@ def on_file(self, options: Options) -> None: path = os.path.relpath(tree.path) visitor = stats.StatisticsVisitor(inferred=True, - filename=tree.fullname(), + filename=tree.fullname, modules=modules, typemap=type_map, all_nodes=True) @@ -818,7 +818,7 @@ def on_file(self, return visitor = stats.StatisticsVisitor(inferred=True, - filename=tree.fullname(), + filename=tree.fullname, modules=modules, typemap=type_map, all_nodes=True) diff --git a/mypy/scope.py b/mypy/scope.py index e5e0b2dc21be..22608ef3a0fe 100644 --- a/mypy/scope.py +++ b/mypy/scope.py @@ -30,7 +30,7 @@ def current_target(self) -> str: """Return the current target (non-class; for a class return enclosing module).""" assert self.module if self.function: - fullname = self.function.fullname() + fullname = self.function.fullname return fullname or '' return self.module @@ -38,18 +38,18 @@ def current_full_target(self) -> str: """Return the current target (may be a class).""" assert self.module if self.function: - return self.function.fullname() + return self.function.fullname if self.classes: - return self.classes[-1].fullname() + return self.classes[-1].fullname return self.module def current_type_name(self) -> Optional[str]: """Return the current type's short name if it exists""" - return self.classes[-1].name() if self.classes else None + return self.classes[-1].name if self.classes else None def current_function_name(self) -> Optional[str]: """Return the current function's short name if it exists""" - return self.function.name() if self.function else None + return self.function.name if self.function else None def enter_file(self, prefix: str) -> None: self.module = prefix diff --git a/mypy/semanal.py b/mypy/semanal.py index 18e45d684f64..18adce2a9600 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -300,9 +300,9 @@ def prepare_file(self, file_node: MypyFile) -> None: if 'builtins' in self.modules: file_node.names['__builtins__'] = SymbolTableNode(GDEF, self.modules['builtins']) - if file_node.fullname() == 'builtins': + if file_node.fullname == 'builtins': self.prepare_builtins_namespace(file_node) - if file_node.fullname() == 'typing': + if file_node.fullname == 'typing': self.prepare_typing_namespace(file_node) def prepare_typing_namespace(self, file_node: MypyFile) -> None: @@ -387,7 +387,7 @@ def refresh_top_level(self, file_node: MypyFile) -> None: self.add_implicit_module_attrs(file_node) for d in file_node.defs: self.accept(d) - if file_node.fullname() == 'typing': + if file_node.fullname == 'typing': self.add_builtin_aliases(file_node) self.adjust_public_exports() self.export_map[self.cur_mod_id] = self.all_exports @@ -431,7 +431,7 @@ def add_builtin_aliases(self, tree: MypyFile) -> None: corresponding nodes on the fly. We explicitly mark these aliases as normalized, so that a user can write `typing.List[int]`. """ - assert tree.fullname() == 'typing' + assert tree.fullname == 'typing' for alias, target_name in type_aliases.items(): if type_aliases_target_versions[alias] > self.options.python_version: # This alias is not available on this Python version. @@ -491,9 +491,9 @@ def file_context(self, """ scope = self.scope self.options = options - self.errors.set_file(file_node.path, file_node.fullname(), scope=scope) + self.errors.set_file(file_node.path, file_node.fullname, scope=scope) self.cur_mod_node = file_node - self.cur_mod_id = file_node.fullname() + self.cur_mod_id = file_node.fullname scope.enter_file(self.cur_mod_id) self.is_stub_file = file_node.path.lower().endswith('.pyi') self._is_typeshed_stub_file = self.errors.is_typeshed_file(file_node.path) @@ -540,7 +540,7 @@ def visit_func_def(self, defn: FuncDef) -> None: # Set full names even for those definitions that aren't added # to a symbol table. For example, for overload items. - defn._fullname = self.qualified_name(defn.name()) + defn._fullname = self.qualified_name(defn.name) # We don't add module top-level functions to symbol tables # when we analyze their bodies in the second phase on analysis, @@ -568,7 +568,7 @@ def analyze_func_def(self, defn: FuncDef) -> None: # Method definition assert self.type is not None defn.info = self.type - if defn.type is not None and defn.name() in ('__init__', '__init_subclass__'): + if defn.type is not None and defn.name in ('__init__', '__init_subclass__'): assert isinstance(defn.type, CallableType) if isinstance(get_proper_type(defn.type.ret_type), AnyType): defn.type = defn.type.copy_modified(ret_type=NoneType()) @@ -616,7 +616,7 @@ def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None: # Only non-static methods are special. functype = func.type if not func.is_static: - if func.name() in ['__init_subclass__', '__class_getitem__']: + if func.name in ['__init_subclass__', '__class_getitem__']: func.is_class = True if not func.arguments: self.fail('Method must have at least one argument', func) @@ -624,7 +624,7 @@ def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None: self_type = get_proper_type(functype.arg_types[0]) if isinstance(self_type, AnyType): leading_type = fill_typevars(info) # type: Type - if func.is_class or func.name() == '__new__': + if func.is_class or func.name == '__new__': leading_type = self.class_type(leading_type) func.type = replace_implicit_first_type(functype, leading_type) @@ -675,7 +675,7 @@ def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: # with a @property with a setter or a deleter, and for a classic # @overload. - defn._fullname = self.qualified_name(defn.name()) + defn._fullname = self.qualified_name(defn.name) # TODO: avoid modifying items. defn.items = defn.unanalyzed_items.copy() @@ -785,9 +785,9 @@ def handle_missing_overload_decorators(self, "must come last", defn.items[idx]) else: for idx in non_overload_indexes[1:]: - self.name_already_defined(defn.name(), defn.items[idx], defn.items[0]) + self.name_already_defined(defn.name, defn.items[idx], defn.items[0]) if defn.impl: - self.name_already_defined(defn.name(), defn.impl, defn.items[0]) + self.name_already_defined(defn.name, defn.impl, defn.items[0]) # Remove the non-overloads for idx in reversed(non_overload_indexes): del defn.items[idx] @@ -883,8 +883,8 @@ def add_function_to_symbol_table(self, func: Union[FuncDef, OverloadedFuncDef]) if self.is_class_scope(): assert self.type is not None func.info = self.type - func._fullname = self.qualified_name(func.name()) - self.add_symbol(func.name(), func, func) + func._fullname = self.qualified_name(func.name) + self.add_symbol(func.name, func, func) def analyze_arg_initializers(self, defn: FuncItem) -> None: with self.tvar_scope_frame(self.tvar_scope.method_frame()): @@ -946,8 +946,8 @@ def visit_decorator(self, dec: Decorator) -> None: dec.decorators = dec.original_decorators.copy() dec.func.is_conditional = self.block_depth[-1] > 0 if not dec.is_overload: - self.add_symbol(dec.name(), dec, dec) - dec.func._fullname = self.qualified_name(dec.name()) + self.add_symbol(dec.name, dec, dec) + dec.func._fullname = self.qualified_name(dec.name) for d in dec.decorators: d.accept(self) removed = [] # type: List[int] @@ -1241,7 +1241,7 @@ class Foo(Bar, Generic[T]): ... if isinstance(base, UnboundType): sym = self.lookup_qualified(base.name, base) if sym is not None and sym.node is not None: - if (sym.node.fullname() in ('typing.Protocol', + if (sym.node.fullname in ('typing.Protocol', 'typing_extensions.Protocol') and i not in removed): # also remove bare 'Protocol' bases @@ -1287,10 +1287,10 @@ def analyze_class_typevar_declaration(self, base: Type) -> Optional[Tuple[TypeVa sym = self.lookup_qualified(unbound.name, unbound) if sym is None or sym.node is None: return None - if (sym.node.fullname() == 'typing.Generic' or - sym.node.fullname() == 'typing.Protocol' and base.args or - sym.node.fullname() == 'typing_extensions.Protocol' and base.args): - is_proto = sym.node.fullname() != 'typing.Generic' + if (sym.node.fullname == 'typing.Generic' or + sym.node.fullname == 'typing.Protocol' and base.args or + sym.node.fullname == 'typing_extensions.Protocol' and base.args): + is_proto = sym.node.fullname != 'typing.Generic' tvars = [] # type: TypeVarList for arg in unbound.args: tag = self.track_incomplete_refs() @@ -1299,7 +1299,7 @@ def analyze_class_typevar_declaration(self, base: Type) -> Optional[Tuple[TypeVa tvars.append(tvar) elif not self.found_incomplete_ref(tag): self.fail('Free type variable expected in %s[...]' % - sym.node.name(), base) + sym.node.name, base) return tvars, is_proto return None @@ -1350,7 +1350,7 @@ def prepare_class_def(self, defn: ClassDef, info: Optional[TypeInfo] = None) -> if not self.is_func_scope(): info._fullname = self.qualified_name(defn.name) else: - info._fullname = info.name() + info._fullname = info.name self.add_symbol(defn.name, defn.info, defn) if self.is_nested_within_func_scope(): # We need to preserve local classes, let's store them @@ -1513,7 +1513,7 @@ def configure_tuple_base_class(self, defn.analyzed.line = defn.line defn.analyzed.column = defn.column - if base.partial_fallback.type.fullname() == 'builtins.tuple': + if base.partial_fallback.type.fullname == 'builtins.tuple': # Fallback can only be safely calculated after semantic analysis, since base # classes may be incomplete. Postpone the calculation. self.schedule_patch(PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(base)) @@ -1604,13 +1604,13 @@ def verify_base_classes(self, defn: ClassDef) -> bool: self.fail('Cycle in inheritance hierarchy', defn, blocker=True) # Clear bases to forcefully get rid of the cycle. info.bases = [] - if baseinfo.fullname() == 'builtins.bool': + if baseinfo.fullname == 'builtins.bool': self.fail("'%s' is not a valid base class" % - baseinfo.name(), defn, blocker=True) + baseinfo.name, defn, blocker=True) return False dup = find_duplicate(info.direct_base_classes()) if dup: - self.fail('Duplicate base class "%s"' % dup.name(), defn, blocker=True) + self.fail('Duplicate base class "%s"' % dup.name, defn, blocker=True) return False return True @@ -1666,7 +1666,7 @@ def analyze_metaclass(self, defn: ClassDef) -> None: defn.info.metaclass_type = defn.info.calculate_metaclass_type() if any(info.is_protocol for info in defn.info.mro): if (not defn.info.metaclass_type or - defn.info.metaclass_type.type.fullname() == 'builtins.type'): + defn.info.metaclass_type.type.fullname == 'builtins.type'): # All protocols and their subclasses have ABCMeta metaclass by default. # TODO: add a metaclass conflict check if there is another metaclass. abc_meta = self.named_type_or_none('abc.ABCMeta', []) @@ -1878,7 +1878,7 @@ def visit_import_all(self, i: ImportAll) -> None: if node.module_public and (not name.startswith('_') or '__all__' in m.names): if isinstance(node.node, MypyFile): # Star import of submodule from a package, add it as a dependency. - self.imports.add(node.node.fullname()) + self.imports.add(node.node.fullname) existing_symbol = self.lookup_current_scope(name) if existing_symbol and not isinstance(node.node, PlaceholderNode): # Import can redefine a variable. They get special treatment. @@ -1992,7 +1992,7 @@ def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool: for node in s.rvalue, lvalue: node.node = sym.node node.kind = GDEF - node.fullname = sym.node.fullname() + node.fullname = sym.node.fullname return True def should_wait_rhs(self, rv: Expression) -> bool: @@ -2103,8 +2103,8 @@ def is_none_alias(self, node: Expression) -> bool: isinstance(node.args[0], NameExpr)): call = self.lookup_qualified(node.callee.name, node.callee) arg = self.lookup_qualified(node.args[0].name, node.args[0]) - if (call is not None and call.node and call.node.fullname() == 'builtins.type' and - arg is not None and arg.node and arg.node.fullname() == 'builtins.None'): + if (call is not None and call.node and call.node.fullname == 'builtins.type' and + arg is not None and arg.node and arg.node.fullname == 'builtins.None'): return True return False @@ -2254,7 +2254,7 @@ def check_final_implicit_def(self, s: AssignmentStmt) -> None: return else: assert self.function_stack - if self.function_stack[-1].name() != '__init__': + if self.function_stack[-1].name != '__init__': self.fail("Can only declare a final attribute in class body or __init__", s) s.is_final_def = False return @@ -2281,7 +2281,7 @@ def store_final_status(self, s: AssignmentStmt) -> None: if cur_node and isinstance(cur_node.node, Var) and cur_node.node.is_final: assert self.function_stack top_function = self.function_stack[-1] - if (top_function.name() == '__init__' and + if (top_function.name == '__init__' and cur_node.node.final_unset_in_class and not cur_node.node.final_set_in_init and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs)): @@ -2401,7 +2401,7 @@ def analyze_alias(self, rvalue: Expression, typ, depends_on = res found_type_vars = typ.accept(TypeVariableQuery(self.lookup_qualified, self.tvar_scope)) alias_tvars = [name for (name, node) in found_type_vars] - qualified_tvars = [node.fullname() for (name, node) in found_type_vars] + qualified_tvars = [node.fullname for (name, node) in found_type_vars] else: alias_tvars = [] depends_on = set() @@ -3063,7 +3063,7 @@ def is_classvar(self, typ: Type) -> bool: sym = self.lookup_qualified(typ.name, typ) if not sym or not sym.node: return False - return sym.node.fullname() == 'typing.ClassVar' + return sym.node.fullname == 'typing.ClassVar' def is_final_type(self, typ: Optional[Type]) -> bool: if not isinstance(typ, UnboundType): @@ -3071,7 +3071,7 @@ def is_final_type(self, typ: Optional[Type]) -> bool: sym = self.lookup_qualified(typ.name, typ) if not sym or not sym.node: return False - return sym.node.fullname() in ('typing.Final', + return sym.node.fullname in ('typing.Final', 'typing_extensions.Final') def fail_invalid_classvar(self, context: Context) -> None: @@ -3599,7 +3599,7 @@ def visit_member_expr(self, expr: MemberExpr) -> None: # check for self.bar or cls.bar in method/classmethod func_def = self.function_stack[-1] if not func_def.is_static and isinstance(func_def.type, CallableType): - formal_arg = func_def.type.argument_by_name(base.node.name()) + formal_arg = func_def.type.argument_by_name(base.node.name) if formal_arg and formal_arg.pos == 0: type_info = self.type elif isinstance(base.node, TypeAlias) and base.node.no_args: @@ -3669,7 +3669,7 @@ def analyze_type_application(self, expr: IndexExpr) -> None: alias = base.node target = get_proper_type(alias.target) if isinstance(target, Instance): - name = target.type.fullname() + name = target.type.fullname if (alias.no_args and # this avoids bogus errors for already reported aliases name in nongen_builtins and not alias.normalized): self.fail(no_subscript_builtin_alias(name, propose_alt=False), expr) @@ -3915,7 +3915,7 @@ class C: assert self.statement # we are at class scope return (node is None or node.line < self.statement.line - or not self.is_defined_in_current_module(node.fullname()) + or not self.is_defined_in_current_module(node.fullname) or isinstance(node, TypeInfo) or (isinstance(node, PlaceholderNode) and node.becomes_typeinfo)) @@ -3949,7 +3949,7 @@ def lookup_qualified(self, name: str, ctx: Context, nextsym = node.get(part) elif isinstance(node, MypyFile): nextsym = self.get_module_symbol(node, part) - namespace = node.fullname() + namespace = node.fullname elif isinstance(node, PlaceholderNode): return sym else: @@ -3982,7 +3982,7 @@ def get_module_symbol(self, node: MypyFile, name: str) -> Optional[SymbolTableNo Return None if no matching symbol could be bound. """ - module = node.fullname() + module = node.fullname names = node.names sym = names.get(name) if not sym: @@ -4017,7 +4017,7 @@ def implicit_symbol(self, sym: SymbolTableNode, name: str, parts: List[str], if sym.node is None: basename = None else: - basename = sym.node.fullname() + basename = sym.node.fullname if basename is None: fullname = name else: @@ -4297,7 +4297,7 @@ def add_module_symbol(self, def add_local(self, node: Union[Var, FuncDef, OverloadedFuncDef], context: Context) -> None: """Add local variable or function.""" assert self.is_func_scope() - name = node.name() + name = node.name node._fullname = name self.add_symbol(name, node, context) @@ -4336,7 +4336,7 @@ def add_unknown_imported_symbol(self, # definition, but this name may point to nothing. var._fullname = target_name elif self.type: - var._fullname = self.type.fullname() + "." + name + var._fullname = self.type.fullname + "." + name var.info = self.type else: var._fullname = self.qualified_name(name) @@ -4581,7 +4581,7 @@ def already_defined(self, # Therefore its line number is always 1, which is not useful for this # error message. extra_msg = ' (by an import)' - elif node and node.line != -1 and self.is_local_name(node.fullname()): + elif node and node.line != -1 and self.is_local_name(node.fullname): # TODO: Using previous symbol node may give wrong line. We should use # the line number where the binding was established instead. extra_msg = ' on line {}'.format(node.line) @@ -4824,7 +4824,7 @@ def refers_to_fullname(node: Expression, fullname: str) -> bool: return True if isinstance(node.node, TypeAlias): target = get_proper_type(node.node.target) - if isinstance(target, Instance) and target.type.fullname() == fullname: + if isinstance(target, Instance) and target.type.fullname == fullname: return True return False @@ -4853,7 +4853,7 @@ def remove_imported_names_from_symtable(names: SymbolTable, for name, node in names.items(): if node.node is None: continue - fullname = node.node.fullname() + fullname = node.node.fullname prefix = fullname[:fullname.rfind('.')] if prefix != module: removed.append(name) @@ -4914,7 +4914,7 @@ def is_same_var_from_getattr(n1: Optional[SymbolNode], n2: Optional[SymbolNode]) and n1.from_module_getattr and isinstance(n2, Var) and n2.from_module_getattr - and n1.fullname() == n2.fullname()) + and n1.fullname == n2.fullname) def dummy_context() -> Context: diff --git a/mypy/semanal_classprop.py b/mypy/semanal_classprop.py index c9772276d7d8..7052a1197d04 100644 --- a/mypy/semanal_classprop.py +++ b/mypy/semanal_classprop.py @@ -97,7 +97,7 @@ def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: E # implement some methods. typ.abstract_attributes = sorted(abstract) if is_stub_file: - if typ.declared_metaclass and typ.declared_metaclass.type.fullname() == 'abc.ABCMeta': + if typ.declared_metaclass and typ.declared_metaclass.type.fullname == 'abc.ABCMeta': return if typ.is_protocol: return @@ -106,7 +106,7 @@ def report(message: str, severity: str) -> None: errors.report(typ.line, typ.column, message, severity=severity) attrs = ", ".join('"{}"'.format(attr) for attr in sorted(abstract)) - report("Class {} has abstract attributes {}".format(typ.fullname(), attrs), 'error') + report("Class {} has abstract attributes {}".format(typ.fullname, attrs), 'error') report("If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass", 'note') @@ -115,7 +115,7 @@ def check_protocol_status(info: TypeInfo, errors: Errors) -> None: """Check that all classes in MRO of a protocol are protocols""" if info.is_protocol: for type in info.bases: - if not type.type.is_protocol and type.type.fullname() != 'builtins.object': + if not type.type.is_protocol and type.type.fullname != 'builtins.object': def report(message: str, severity: str) -> None: errors.report(info.line, info.column, message, severity=severity) report('All bases of a protocol must be protocols', 'error') diff --git a/mypy/semanal_enum.py b/mypy/semanal_enum.py index c8d163f1385b..d373a887abfa 100644 --- a/mypy/semanal_enum.py +++ b/mypy/semanal_enum.py @@ -89,7 +89,7 @@ def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) - var = Var(item) var.info = info var.is_property = True - var._fullname = '{}.{}'.format(info.fullname(), item) + var._fullname = '{}.{}'.format(info.fullname, item) info.names[item] = SymbolTableNode(MDEF, var) return info diff --git a/mypy/semanal_infer.py b/mypy/semanal_infer.py index 622ba275da3e..a869cdf29112 100644 --- a/mypy/semanal_infer.py +++ b/mypy/semanal_infer.py @@ -31,7 +31,7 @@ def infer_decorator_signature_if_simple(dec: Decorator, [None], AnyType(TypeOfAny.special_form), analyzer.named_type('__builtins__.function'), - name=dec.var.name()) + name=dec.var.name) elif isinstance(dec.func.type, CallableType): dec.var.type = dec.func.type return diff --git a/mypy/semanal_main.py b/mypy/semanal_main.py index 513f420e4e25..a12b6cadeb69 100644 --- a/mypy/semanal_main.py +++ b/mypy/semanal_main.py @@ -126,7 +126,7 @@ def semantic_analysis_for_targets( # Already done above. continue process_top_level_function(analyzer, state, state.id, - n.node.fullname(), n.node, n.active_typeinfo, patches) + n.node.fullname, n.node, n.active_typeinfo, patches) apply_semantic_analyzer_patches(patches) check_type_arguments_in_targets(nodes, state, state.manager.errors) diff --git a/mypy/semanal_namedtuple.py b/mypy/semanal_namedtuple.py index da65f6f063d2..af71c9d234d4 100644 --- a/mypy/semanal_namedtuple.py +++ b/mypy/semanal_namedtuple.py @@ -384,8 +384,8 @@ def add_field(var: Var, is_initialized_in_class: bool = False, 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) + var._fullname = '%s.%s' % (info.fullname, var.name) + info.names[var.name] = SymbolTableNode(MDEF, var) fields = [Var(item, typ) for item, typ in zip(items, types)] for var in fields: @@ -404,7 +404,7 @@ def add_field(var: Var, is_initialized_in_class: bool = False, add_field(Var('__annotations__', ordereddictype), is_initialized_in_class=True) add_field(Var('__doc__', strtype), is_initialized_in_class=True) - tvd = TypeVarDef(SELF_TVAR_NAME, info.fullname() + '.' + SELF_TVAR_NAME, + tvd = TypeVarDef(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, -1, [], info.tuple_type) selftype = TypeVarType(tvd) @@ -421,7 +421,7 @@ def add_method(funcname: str, args = first + args types = [arg.type_annotation for arg in args] - items = [arg.variable.name() 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, @@ -431,7 +431,7 @@ def add_method(funcname: str, func.info = info func.is_class = is_classmethod func.type = set_callable_name(signature, func) - func._fullname = info.fullname() + '.' + funcname + func._fullname = info.fullname + '.' + funcname func.line = line if is_classmethod: v = Var(funcname, func.type) @@ -451,7 +451,7 @@ def add_method(funcname: str, args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars]) def make_init_arg(var: Var) -> Argument: - default = default_items.get(var.name(), None) + default = default_items.get(var.name, None) kind = ARG_POS if default is None else ARG_OPT return Argument(var, var.type, default, kind) @@ -465,7 +465,7 @@ def make_init_arg(var: Var) -> Argument: Argument(Var('new'), special_form_any, EllipsisExpr(), ARG_NAMED_OPT), Argument(Var('len'), special_form_any, EllipsisExpr(), ARG_NAMED_OPT)]) - self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname() + '.' + SELF_TVAR_NAME, + self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, [], info.tuple_type) info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) return info diff --git a/mypy/semanal_pass1.py b/mypy/semanal_pass1.py index 76d2e852381d..0296788e3990 100644 --- a/mypy/semanal_pass1.py +++ b/mypy/semanal_pass1.py @@ -63,7 +63,7 @@ def visit_func_def(self, node: FuncDef) -> None: file_node = self.cur_mod_node if (self.is_global_scope and file_node.is_stub - and node.name() == '__getattr__' + and node.name == '__getattr__' and file_node.is_package_init_file()): # __init__.pyi with __getattr__ means that any submodules are assumed # to exist, even if there is no stub. Note that we can't verify that the diff --git a/mypy/semanal_shared.py b/mypy/semanal_shared.py index 1063ed8fae70..c800dcb95d14 100644 --- a/mypy/semanal_shared.py +++ b/mypy/semanal_shared.py @@ -170,7 +170,7 @@ def create_indirect_imported_name(file_node: MypyFile, These entries act as indirect references. """ target_module, ok = correct_relative_import( - file_node.fullname(), + file_node.fullname, relative, module, file_node.is_package_init_file()) @@ -186,15 +186,15 @@ def set_callable_name(sig: Type, fdef: FuncDef) -> ProperType: sig = get_proper_type(sig) if isinstance(sig, FunctionLike): if fdef.info: - if fdef.info.fullname() in TPDICT_FB_NAMES: + if fdef.info.fullname in TPDICT_FB_NAMES: # Avoid exposing the internal _TypedDict name. class_name = 'TypedDict' else: - class_name = fdef.info.name() + class_name = fdef.info.name return sig.with_name( - '{} of {}'.format(fdef.name(), class_name)) + '{} of {}'.format(fdef.name, class_name)) else: - return sig.with_name(fdef.name()) + return sig.with_name(fdef.name) else: return sig @@ -214,5 +214,5 @@ def calculate_tuple_fallback(typ: TupleType) -> None: we don't prevent their existence). """ fallback = typ.partial_fallback - assert fallback.type.fullname() == 'builtins.tuple' + assert fallback.type.fullname == 'builtins.tuple' fallback.args[0] = join.join_type_list(list(typ.items)) diff --git a/mypy/semanal_typeargs.py b/mypy/semanal_typeargs.py index eceb5664d0e9..5ea77f4025d6 100644 --- a/mypy/semanal_typeargs.py +++ b/mypy/semanal_typeargs.py @@ -29,8 +29,8 @@ def __init__(self, errors: Errors, options: Options, is_typeshed_file: bool) -> self.recurse_into_functions = True def visit_mypy_file(self, o: MypyFile) -> None: - self.errors.set_file(o.path, o.fullname(), scope=self.scope) - self.scope.enter_file(o.fullname()) + self.errors.set_file(o.path, o.fullname, scope=self.scope) + self.scope.enter_file(o.fullname) super().visit_mypy_file(o) self.scope.leave() @@ -59,7 +59,7 @@ def visit_instance(self, t: Instance) -> None: if not arg_values: self.fail('Type variable "{}" not valid as type ' 'argument value for "{}"'.format( - arg.name, info.name()), t, code=codes.TYPE_VAR) + arg.name, info.name), t, code=codes.TYPE_VAR) continue else: arg_values = [arg] @@ -67,7 +67,7 @@ def visit_instance(self, t: Instance) -> None: if not is_subtype(arg, tvar.upper_bound): self.fail('Type argument "{}" of "{}" must be ' 'a subtype of "{}"'.format( - arg, info.name(), tvar.upper_bound), t, code=codes.TYPE_VAR) + arg, info.name, tvar.upper_bound), t, code=codes.TYPE_VAR) super().visit_instance(t) def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: str, @@ -78,10 +78,10 @@ def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: s for value in valids)): if len(actuals) > 1 or not isinstance(actual, Instance): self.fail('Invalid type argument value for "{}"'.format( - type.name()), context, code=codes.TYPE_VAR) + type.name), context, code=codes.TYPE_VAR) else: - class_name = '"{}"'.format(type.name()) - actual_type_name = '"{}"'.format(actual.type.name()) + class_name = '"{}"'.format(type.name) + actual_type_name = '"{}"'.format(actual.type.name) self.fail( message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format( arg_name, class_name, actual_type_name), diff --git a/mypy/server/astdiff.py b/mypy/server/astdiff.py index fdb6a273c131..9893092882b5 100644 --- a/mypy/server/astdiff.py +++ b/mypy/server/astdiff.py @@ -132,7 +132,7 @@ def snapshot_symbol_table(name_prefix: str, table: SymbolTable) -> Dict[str, Sna for name, symbol in table.items(): node = symbol.node # TODO: cross_ref? - fullname = node.fullname() if node else None + fullname = node.fullname if node else None common = (fullname, symbol.kind, symbol.module_public) if isinstance(node, MypyFile): # This is a cross-reference to another module. @@ -153,7 +153,7 @@ def snapshot_symbol_table(name_prefix: str, table: SymbolTable) -> Dict[str, Sna snapshot_optional_type(node.target)) else: assert symbol.kind != UNBOUND_IMPORTED - if node and get_prefix(node.fullname()) != name_prefix: + if node and get_prefix(node.fullname) != name_prefix: # This is a cross-reference to a node defined in another module. result[name] = ('CrossRef', common) else: @@ -204,7 +204,7 @@ def snapshot_definition(node: Optional[SymbolNode], snapshot_optional_type(node.metaclass_type), snapshot_optional_type(node.tuple_type), snapshot_optional_type(node.typeddict_type), - [base.fullname() for base in node.mro], + [base.fullname for base in node.mro], # Note that the structure of type variables is a part of the external interface, # since creating instances might fail, for example: # T = TypeVar('T', bound=int) @@ -216,7 +216,7 @@ def snapshot_definition(node: Optional[SymbolNode], tuple(snapshot_type(TypeVarType(tdef)) for tdef in node.defn.type_vars), [snapshot_type(base) for base in node.bases], snapshot_optional_type(node._promote)) - prefix = node.fullname() + prefix = node.fullname symbol_table = snapshot_symbol_table(prefix, node.names) # Special dependency for abstract attribute handling. symbol_table['(abstract)'] = ('Abstract', tuple(sorted(node.abstract_attributes))) @@ -292,7 +292,7 @@ def visit_deleted_type(self, typ: DeletedType) -> SnapshotItem: def visit_instance(self, typ: Instance) -> SnapshotItem: return ('Instance', - encode_optional_str(typ.type.fullname()), + encode_optional_str(typ.type.fullname), snapshot_types(typ.args), ('None',) if typ.last_known_value is None else snapshot_type(typ.last_known_value)) @@ -348,7 +348,7 @@ def visit_type_type(self, typ: TypeType) -> SnapshotItem: def visit_type_alias_type(self, typ: TypeAliasType) -> SnapshotItem: assert typ.alias is not None - return ('TypeAliasType', typ.alias.fullname(), snapshot_types(typ.args)) + return ('TypeAliasType', typ.alias.fullname, snapshot_types(typ.args)) def snapshot_untyped_signature(func: Union[OverloadedFuncDef, FuncItem]) -> Tuple[object, ...]: diff --git a/mypy/server/astmerge.py b/mypy/server/astmerge.py index 5080905d1eaf..5d00acee8c42 100644 --- a/mypy/server/astmerge.py +++ b/mypy/server/astmerge.py @@ -77,11 +77,11 @@ def merge_asts(old: MypyFile, old_symbols: SymbolTable, will be the new symbol table. 'new' and 'old_symbols' will no longer be valid. """ - assert new.fullname() == old.fullname() + assert new.fullname == old.fullname # Find the mapping from new to old node identities for all nodes # whose identities should be preserved. replacement_map = replacement_map_from_symbol_table( - old_symbols, new_symbols, prefix=old.fullname()) + old_symbols, new_symbols, prefix=old.fullname) # Also replace references to the new MypyFile node. replacement_map[new] = old # Perform replacements to everywhere within the new AST (not including symbol @@ -106,11 +106,11 @@ def replacement_map_from_symbol_table( replacements = {} # type: Dict[SymbolNode, SymbolNode] for name, node in old.items(): if (name in new and (node.kind == MDEF - or node.node and get_prefix(node.node.fullname()) == prefix)): + or node.node and get_prefix(node.node.fullname) == prefix)): new_node = new[name] if (type(new_node.node) == type(node.node) # noqa and new_node.node and node.node and - new_node.node.fullname() == node.node.fullname() and + new_node.node.fullname == node.node.fullname and new_node.kind == node.kind): replacements[new_node.node] = node.node if isinstance(node.node, TypeInfo) and isinstance(new_node.node, TypeInfo): diff --git a/mypy/server/deps.py b/mypy/server/deps.py index 295b1bca266c..9e1f7bd2c6d2 100644 --- a/mypy/server/deps.py +++ b/mypy/server/deps.py @@ -168,7 +168,7 @@ def __init__(self, self.options = options def visit_mypy_file(self, o: MypyFile) -> None: - self.scope.enter_file(o.fullname()) + self.scope.enter_file(o.fullname) self.is_package_init_file = o.is_package_init_file() self.add_type_alias_deps(self.scope.current_target()) for trigger, targets in o.plugin_deps.items(): @@ -191,8 +191,8 @@ def visit_func_def(self, o: FuncDef) -> None: for base in non_trivial_bases(o.info): # Base class __init__/__new__ doesn't generate a logical # dependency since the override can be incompatible. - if not self.use_logical_deps() or o.name() not in ('__init__', '__new__'): - self.add_dependency(make_trigger(base.fullname() + '.' + o.name())) + if not self.use_logical_deps() or o.name not in ('__init__', '__new__'): + self.add_dependency(make_trigger(base.fullname + '.' + o.name)) self.add_type_alias_deps(self.scope.current_target()) super().visit_func_def(o) variants = set(o.expanded) - {o} @@ -207,7 +207,7 @@ def visit_decorator(self, o: Decorator) -> None: # Also if any decorator is nested, it is not externally visible, so we don't need to # generate dependency. if not o.func.is_overload and self.scope.current_function_name() is None: - self.add_dependency(make_trigger(o.func.fullname())) + self.add_dependency(make_trigger(o.func.fullname)) else: # Add logical dependencies from decorators to the function. For example, # if we have @@ -223,7 +223,7 @@ def visit_decorator(self, o: Decorator) -> None: d.callee.fullname is not None): tname = d.callee.fullname if tname is not None: - self.add_dependency(make_trigger(tname), make_trigger(o.func.fullname())) + self.add_dependency(make_trigger(tname), make_trigger(o.func.fullname)) super().visit_decorator(o) def visit_class_def(self, o: ClassDef) -> None: @@ -268,7 +268,7 @@ def process_type_info(self, info: TypeInfo) -> None: # # In this example we add -> , to invalidate Sub if # a new member is added to Super. - self.add_dependency(make_wildcard_trigger(base_info.fullname()), + self.add_dependency(make_wildcard_trigger(base_info.fullname), target=make_trigger(target)) # More protocol dependencies are collected in TypeState._snapshot_protocol_deps # after a full run or update is finished. @@ -278,12 +278,12 @@ def process_type_info(self, info: TypeInfo) -> None: if isinstance(node.node, Var): # Recheck Liskov if needed, self definitions are checked in the defining method if node.node.is_initialized_in_class and has_user_bases(info): - self.add_dependency(make_trigger(info.fullname() + '.' + name)) + self.add_dependency(make_trigger(info.fullname + '.' + name)) for base_info in non_trivial_bases(info): # If the type of an attribute changes in a base class, we make references # to the attribute in the subclass stale. - self.add_dependency(make_trigger(base_info.fullname() + '.' + name), - target=make_trigger(info.fullname() + '.' + name)) + self.add_dependency(make_trigger(base_info.fullname + '.' + name), + target=make_trigger(info.fullname + '.' + name)) for base_info in non_trivial_bases(info): for name, node in base_info.names.items(): if self.use_logical_deps(): @@ -302,24 +302,24 @@ def process_type_info(self, info: TypeInfo) -> None: # logical depedency. if name in ('__init__', '__new__'): continue - self.add_dependency(make_trigger(base_info.fullname() + '.' + name), - target=make_trigger(info.fullname() + '.' + name)) + self.add_dependency(make_trigger(base_info.fullname + '.' + name), + target=make_trigger(info.fullname + '.' + name)) if not self.use_logical_deps(): # These dependencies are only useful for propagating changes -- # they aren't logical dependencies since __init__ and __new__ can be # overridden with a different signature. - self.add_dependency(make_trigger(base_info.fullname() + '.__init__'), - target=make_trigger(info.fullname() + '.__init__')) - self.add_dependency(make_trigger(base_info.fullname() + '.__new__'), - target=make_trigger(info.fullname() + '.__new__')) + self.add_dependency(make_trigger(base_info.fullname + '.__init__'), + target=make_trigger(info.fullname + '.__init__')) + self.add_dependency(make_trigger(base_info.fullname + '.__new__'), + target=make_trigger(info.fullname + '.__new__')) # If the set of abstract attributes change, this may invalidate class # instantiation, or change the generated error message, since Python checks # class abstract status when creating an instance. - self.add_dependency(make_trigger(base_info.fullname() + '.(abstract)'), - target=make_trigger(info.fullname() + '.__init__')) + self.add_dependency(make_trigger(base_info.fullname + '.(abstract)'), + target=make_trigger(info.fullname + '.__init__')) # If the base class abstract attributes change, subclass abstract # attributes need to be recalculated. - self.add_dependency(make_trigger(base_info.fullname() + '.(abstract)')) + self.add_dependency(make_trigger(base_info.fullname + '.(abstract)')) def visit_import(self, o: Import) -> None: for id, as_id in o.ids: @@ -355,15 +355,15 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None: if isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypeVarExpr): analyzed = rvalue.analyzed self.add_type_dependencies(analyzed.upper_bound, - target=make_trigger(analyzed.fullname())) + target=make_trigger(analyzed.fullname)) for val in analyzed.values: - self.add_type_dependencies(val, target=make_trigger(analyzed.fullname())) + self.add_type_dependencies(val, target=make_trigger(analyzed.fullname)) # We need to re-analyze the definition if bound or value is deleted. super().visit_call_expr(rvalue) elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, NamedTupleExpr): # Depend on types of named tuple items. info = rvalue.analyzed.info - prefix = '%s.%s' % (self.scope.current_full_target(), info.name()) + prefix = '%s.%s' % (self.scope.current_full_target(), info.name) for name, symnode in info.names.items(): if not name.startswith('_') and isinstance(symnode.node, Var): typ = symnode.node.type @@ -376,7 +376,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None: # Depend on the underlying typeddict type info = rvalue.analyzed.info assert info.typeddict_type is not None - prefix = '%s.%s' % (self.scope.current_full_target(), info.name()) + prefix = '%s.%s' % (self.scope.current_full_target(), info.name) self.add_type_dependencies(info.typeddict_type, target=make_trigger(prefix)) elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, EnumCallExpr): # Enum values are currently not checked, but for future we add the deps on them @@ -389,7 +389,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None: assert isinstance(lvalue, NameExpr) typ = get_proper_type(self.type_map.get(lvalue)) if isinstance(typ, FunctionLike) and typ.is_type_obj(): - class_name = typ.type_object().fullname() + class_name = typ.type_object().fullname self.add_dependency(make_trigger(class_name + '.__init__')) self.add_dependency(make_trigger(class_name + '.__new__')) if isinstance(rvalue, IndexExpr) and isinstance(rvalue.analyzed, TypeAliasExpr): @@ -421,7 +421,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None: # use actual __init__ as a dependency source init = rvalue.callee.node.get('__init__') if init and isinstance(init.node, FuncBase): - fname = init.node.fullname() + fname = init.node.fullname else: fname = rvalue.callee.fullname if fname is None: @@ -453,7 +453,7 @@ def process_lvalue(self, lvalue: Expression) -> None: info = node.info if info and has_user_bases(info): # Recheck Liskov for self definitions - self.add_dependency(make_trigger(info.fullname() + '.' + lvalue.name)) + self.add_dependency(make_trigger(info.fullname + '.' + lvalue.name)) if lvalue.kind is None: # Reference to a non-module attribute if lvalue.expr not in self.type_map: @@ -568,7 +568,7 @@ def process_global_ref_expr(self, o: RefExpr) -> None: # class attribute references, etc., if performance is a problem. typ = get_proper_type(self.type_map.get(o)) if isinstance(typ, FunctionLike) and typ.is_type_obj(): - class_name = typ.type_object().fullname() + class_name = typ.type_object().fullname self.add_dependency(make_trigger(class_name + '.__init__')) self.add_dependency(make_trigger(class_name + '.__new__')) @@ -586,7 +586,7 @@ def visit_name_expr(self, o: NameExpr) -> None: def visit_member_expr(self, e: MemberExpr) -> None: if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, TypeInfo): # Special case class attribute so that we don't depend on "__init__". - self.add_dependency(make_trigger(e.expr.node.fullname())) + self.add_dependency(make_trigger(e.expr.node.fullname)) else: super().visit_member_expr(e) if e.kind is not None: @@ -600,7 +600,7 @@ def visit_member_expr(self, e: MemberExpr) -> None: return if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, MypyFile): # Special case: reference to a missing module attribute. - self.add_dependency(make_trigger(e.expr.node.fullname() + '.' + e.name)) + self.add_dependency(make_trigger(e.expr.node.fullname + '.' + e.name)) return typ = get_proper_type(self.type_map[e.expr]) self.add_attribute_dependency(typ, e.name) @@ -649,7 +649,7 @@ def visit_super_expr(self, e: SuperExpr) -> None: if e.info is not None: name = e.name for base in non_trivial_bases(e.info): - self.add_dependency(make_trigger(base.fullname() + '.' + name)) + self.add_dependency(make_trigger(base.fullname + '.' + name)) if name in base.names: # No need to depend on further base classes, since we found # the target. This is safe since if the target gets @@ -735,7 +735,7 @@ def add_operator_method_dependency_for_type(self, typ: ProperType, method: str) if isinstance(typ, TupleType): typ = typ.partial_fallback if isinstance(typ, Instance): - trigger = make_trigger(typ.type.fullname() + '.' + method) + trigger = make_trigger(typ.type.fullname + '.' + method) self.add_dependency(trigger) elif isinstance(typ, UnionType): for item in typ.items: @@ -817,10 +817,10 @@ def attribute_triggers(self, typ: Type, name: str) -> List[str]: if isinstance(typ, TupleType): typ = typ.partial_fallback if isinstance(typ, Instance): - member = '%s.%s' % (typ.type.fullname(), name) + member = '%s.%s' % (typ.type.fullname, name) return [make_trigger(member)] elif isinstance(typ, FunctionLike) and typ.is_type_obj(): - member = '%s.%s' % (typ.type_object().fullname(), name) + member = '%s.%s' % (typ.type_object().fullname, name) triggers = [make_trigger(member)] triggers.extend(self.attribute_triggers(typ.fallback, name)) return triggers @@ -833,7 +833,7 @@ def attribute_triggers(self, typ: Type, name: str) -> List[str]: triggers = self.attribute_triggers(typ.item, name) if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None: triggers.append(make_trigger('%s.%s' % - (typ.item.type.metaclass_type.type.fullname(), + (typ.item.type.metaclass_type.type.fullname, name))) return triggers else: @@ -870,7 +870,7 @@ def get_type_triggers(self, typ: Type) -> List[str]: return get_type_triggers(typ, self.use_logical_deps) def visit_instance(self, typ: Instance) -> List[str]: - trigger = make_trigger(typ.type.fullname()) + trigger = make_trigger(typ.type.fullname) triggers = [trigger] for arg in typ.args: triggers.extend(self.get_type_triggers(arg)) @@ -880,7 +880,7 @@ def visit_instance(self, typ: Instance) -> List[str]: def visit_type_alias_type(self, typ: TypeAliasType) -> List[str]: assert typ.alias is not None - trigger = make_trigger(typ.alias.fullname()) + trigger = make_trigger(typ.alias.fullname) triggers = [trigger] for arg in typ.args: triggers.extend(self.get_type_triggers(arg)) @@ -976,7 +976,7 @@ def merge_dependencies(new_deps: Dict[str, Set[str]], def non_trivial_bases(info: TypeInfo) -> List[TypeInfo]: return [base for base in info.mro[1:] - if base.fullname() != 'builtins.object'] + if base.fullname != 'builtins.object'] def has_user_bases(info: TypeInfo) -> bool: @@ -994,7 +994,7 @@ def dump_all_dependencies(modules: Dict[str, MypyFile], # print('processing', id) if id in ('builtins', 'typing') or '/typeshed/' in node.path: continue - assert id == node.fullname() + assert id == node.fullname deps = get_dependencies(node, type_map, python_version, options) for trigger, targets in deps.items(): all_deps.setdefault(trigger, set()).update(targets) diff --git a/mypy/server/mergecheck.py b/mypy/server/mergecheck.py index a636e2d3e936..dcb820bbffc1 100644 --- a/mypy/server/mergecheck.py +++ b/mypy/server/mergecheck.py @@ -21,7 +21,7 @@ def check_consistency(o: object) -> None: m = {} # type: Dict[str, SymbolNode] for sym in syms: - fn = sym.fullname() + fn = sym.fullname # Skip None names, since they are ambiguous. # TODO: Everything should have a proper full name? if fn is None: @@ -33,7 +33,7 @@ def check_consistency(o: object) -> None: continue if fn not in m: - m[sym.fullname()] = sym + m[sym.fullname] = sym continue # We have trouble and need to decide what to do about it. @@ -58,7 +58,7 @@ def check_consistency(o: object) -> None: print('---') print(id(sym2), sym2) - assert sym.fullname() not in m + assert sym.fullname not in m def path_to_str(path: List[Tuple[object, object]]) -> str: @@ -69,7 +69,7 @@ def path_to_str(path: List[Tuple[object, object]]) -> str: result += '[%s]' % repr(attr) else: if isinstance(obj, Var): - result += '.%s(%s:%s)' % (attr, t, obj.name()) + result += '.%s(%s:%s)' % (attr, t, obj.name) elif t in ('BuildManager', 'FineGrainedBuildManager'): # Omit class name for some classes that aren't part of a class # hierarchy since there isn't much ambiguity. diff --git a/mypy/server/update.py b/mypy/server/update.py index b0a8fc2092b6..2e256e9d7f3c 100644 --- a/mypy/server/update.py +++ b/mypy/server/update.py @@ -889,9 +889,9 @@ def reprocess_nodes(manager: BuildManager, return set() file_node = manager.modules[module_id] - old_symbols = find_symbol_tables_recursive(file_node.fullname(), file_node.names) + old_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names) old_symbols = {name: names.copy() for name, names in old_symbols.items()} - old_symbols_snapshot = snapshot_symbol_table(file_node.fullname(), file_node.names) + old_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names) def key(node: FineGrainedDeferredNode) -> int: # Unlike modules which are sorted by name within SCC, @@ -922,13 +922,13 @@ def key(node: FineGrainedDeferredNode) -> int: # Strip semantic analysis information. saved_attrs = {} # type: SavedAttributes for deferred in nodes: - processed_targets.append(deferred.node.fullname()) + processed_targets.append(deferred.node.fullname) strip_target(deferred.node, saved_attrs) semantic_analysis_for_targets(graph[module_id], nodes, graph, saved_attrs) # Merge symbol tables to preserve identities of AST nodes. The file node will remain # the same, but other nodes may have been recreated with different identities, such as # NamedTuples defined using assignment statements. - new_symbols = find_symbol_tables_recursive(file_node.fullname(), file_node.names) + new_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names) for name in old_symbols: if name in new_symbols: merge_asts(file_node, old_symbols[name], file_node, new_symbols[name]) @@ -948,9 +948,9 @@ def key(node: FineGrainedDeferredNode) -> int: if manager.options.export_types: manager.all_types.update(graph[module_id].type_map()) - new_symbols_snapshot = snapshot_symbol_table(file_node.fullname(), file_node.names) + new_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names) # Check if any attribute types were changed and need to be propagated further. - changed = compare_symbol_table_snapshots(file_node.fullname(), + changed = compare_symbol_table_snapshots(file_node.fullname, old_symbols_snapshot, new_symbols_snapshot) new_triggered = {make_trigger(name) for name in changed} @@ -979,7 +979,7 @@ def find_symbol_tables_recursive(prefix: str, symbols: SymbolTable) -> Dict[str, result = {} result[prefix] = symbols for name, node in symbols.items(): - if isinstance(node.node, TypeInfo) and node.node.fullname().startswith(prefix + '.'): + if isinstance(node.node, TypeInfo) and node.node.fullname.startswith(prefix + '.'): more = find_symbol_tables_recursive(prefix + '.' + name, node.node.names) result.update(more) return result @@ -1049,7 +1049,7 @@ def not_found() -> None: # typically a module top-level, since we don't support processing class # bodies as separate entitites for simplicity. assert file is not None - if node.fullname() != target: + if node.fullname != target: # This is a reference to a different TypeInfo, likely due to a stale dependency. # Processing them would spell trouble -- for example, we could be refreshing # a deserialized TypeInfo with missing attributes. @@ -1075,7 +1075,7 @@ def not_found() -> None: # changed to another type and we have a stale dependency pointing to it. not_found() return [], None - if node.fullname() != target: + if node.fullname != target: # Stale reference points to something unexpected. We shouldn't process since the # context will be wrong and it could be a partially initialized deserialized node. not_found() @@ -1099,12 +1099,12 @@ def target_from_node(module: str, module (for example, if it's actually defined in another module). """ if isinstance(node, MypyFile): - if module != node.fullname(): + if module != node.fullname: # Actually a reference to another module -- likely a stale dependency. return None return module else: # OverloadedFuncDef or FuncDef if node.info: - return '%s.%s' % (node.info.fullname(), node.name()) + return '%s.%s' % (node.info.fullname, node.name) else: - return '%s.%s' % (module, node.name()) + return '%s.%s' % (module, node.name) diff --git a/mypy/stats.py b/mypy/stats.py index 43dde75d185a..d277852c60ef 100644 --- a/mypy/stats.py +++ b/mypy/stats.py @@ -85,7 +85,7 @@ def __init__(self, def visit_mypy_file(self, o: MypyFile) -> None: self.cur_mod_node = o - self.cur_mod_id = o.fullname() + self.cur_mod_id = o.fullname super().visit_mypy_file(o) def visit_import_from(self, imp: ImportFrom) -> None: @@ -395,7 +395,7 @@ def dump_type_stats(tree: MypyFile, return print(path) visitor = StatisticsVisitor(inferred, - filename=tree.fullname(), + filename=tree.fullname, modules=modules, typemap=typemap) tree.accept(visitor) diff --git a/mypy/strconv.py b/mypy/strconv.py index 7f10d355ff09..533bf4f390ba 100644 --- a/mypy/strconv.py +++ b/mypy/strconv.py @@ -126,7 +126,7 @@ def visit_import_all(self, o: 'mypy.nodes.ImportAll') -> str: def visit_func_def(self, o: 'mypy.nodes.FuncDef') -> str: a = self.func_helper(o) - a.insert(0, o.name()) + a.insert(0, o.name) arg_kinds = {arg.kind for arg in o.arguments} if len(arg_kinds & {mypy.nodes.ARG_NAMED, mypy.nodes.ARG_NAMED_OPT}) > 0: a.insert(1, 'MaxPos({})'.format(o.max_pos)) @@ -159,7 +159,7 @@ def visit_class_def(self, o: 'mypy.nodes.ClassDef') -> str: if o.base_type_exprs: if o.info and o.info.bases: if (len(o.info.bases) != 1 - or o.info.bases[0].type.fullname() != 'builtins.object'): + or o.info.bases[0].type.fullname != 'builtins.object'): a.insert(1, ('BaseType', o.info.bases)) else: a.insert(1, ('BaseTypeExpr', o.base_type_exprs)) @@ -183,7 +183,7 @@ def visit_var(self, o: 'mypy.nodes.Var') -> str: # compatible with old test case descriptions that assume this. if o.line < 0: lst = ':nil' - return 'Var' + lst + '(' + o.name() + ')' + return 'Var' + lst + '(' + o.name + ')' def visit_global_decl(self, o: 'mypy.nodes.GlobalDecl') -> str: return self.dump([o.names], o) @@ -472,15 +472,15 @@ def visit_type_alias_expr(self, o: 'mypy.nodes.TypeAliasExpr') -> str: def visit_namedtuple_expr(self, o: 'mypy.nodes.NamedTupleExpr') -> str: return 'NamedTupleExpr:{}({}, {})'.format(o.line, - o.info.name(), + o.info.name, o.info.tuple_type) def visit_enum_call_expr(self, o: 'mypy.nodes.EnumCallExpr') -> str: - return 'EnumCallExpr:{}({}, {})'.format(o.line, o.info.name(), o.items) + return 'EnumCallExpr:{}({}, {})'.format(o.line, o.info.name, o.items) def visit_typeddict_expr(self, o: 'mypy.nodes.TypedDictExpr') -> str: return 'TypedDictExpr:{}({})'.format(o.line, - o.info.name()) + o.info.name) def visit__promote_expr(self, o: 'mypy.nodes.PromoteExpr') -> str: return 'PromoteExpr:{}({})'.format(o.line, o.type) diff --git a/mypy/stubgen.py b/mypy/stubgen.py index a901b4d153f9..5fb4807a8013 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -376,11 +376,11 @@ def visit_mypy_file(self, o: MypyFile) -> None: self.add('# %s\n' % name) def visit_func_def(self, o: FuncDef, is_abstract: bool = False) -> None: - if self.is_private_name(o.name()): + if self.is_private_name(o.name): return - if self.is_not_in_all(o.name()): + if self.is_not_in_all(o.name): return - if self.is_recorded_name(o.name()): + if self.is_recorded_name(o.name): return if not self._indent and self._state not in (EMPTY, FUNC) and not o.is_awaitable_coroutine: self.add('\n') @@ -394,13 +394,13 @@ def visit_func_def(self, o: FuncDef, is_abstract: bool = False) -> None: for s in self._decorators: self.add(s) self.clear_decorators() - self.add("%s%sdef %s(" % (self._indent, 'async ' if o.is_coroutine else '', o.name())) - self.record_name(o.name()) + self.add("%s%sdef %s(" % (self._indent, 'async ' if o.is_coroutine else '', o.name)) + self.record_name(o.name) args = [] # type: List[str] for i, arg_ in enumerate(o.arguments): var = arg_.variable kind = arg_.kind - name = var.name() + name = var.name annotated_type = (o.unanalyzed_type.arg_types[i] if isinstance(o.unanalyzed_type, CallableType) else None) # I think the name check is incorrect: there are libraries which @@ -442,7 +442,7 @@ def visit_func_def(self, o: FuncDef, is_abstract: bool = False) -> None: # Always assume abstract methods return Any unless explicitly annotated. retname = 'Any' self.add_typing_import("Any") - elif o.name() == '__init__' or not has_return_statement(o) and not is_abstract: + elif o.name == '__init__' or not has_return_statement(o) and not is_abstract: retname = 'None' retfield = '' if retname is not None: @@ -453,7 +453,7 @@ def visit_func_def(self, o: FuncDef, is_abstract: bool = False) -> None: self._state = FUNC def visit_decorator(self, o: Decorator) -> None: - if self.is_private_name(o.func.name()): + if self.is_private_name(o.func.name): return is_abstract = False for decorator in o.original_decorators: @@ -641,7 +641,7 @@ def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool: # Also add function and module aliases. return ((top_level and isinstance(expr.node, (FuncDef, Decorator, MypyFile)) or isinstance(expr.node, TypeInfo)) and - not self.is_private_member(expr.node.fullname())) + not self.is_private_member(expr.node.fullname)) elif (isinstance(expr, IndexExpr) and isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name)): if isinstance(expr.index, TupleExpr): diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 1c5862471656..e14cdb451d87 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -240,7 +240,7 @@ def visit_instance(self, left: Instance) -> bool: if base._promote and self._is_subtype(base._promote, self.right): TypeState.record_subtype_cache_entry(self._subtype_kind, left, right) return True - rname = right.type.fullname() + 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 @@ -463,7 +463,7 @@ def visit_type_type(self, left: TypeType) -> bool: # This is unsound, we don't check the __init__ signature. return self._is_subtype(left.item, right.ret_type) if isinstance(right, Instance): - if right.type.fullname() in ['builtins.object', 'builtins.type']: + if right.type.fullname in ['builtins.object', 'builtins.type']: return True item = left.item if isinstance(item, TypeVarType): @@ -606,7 +606,7 @@ def find_member(name: str, # many false negatives, then this could be prohibited for # structural subtyping. method = info.get_method(method_name) - if method and method.info.fullname() != 'builtins.object': + if method and method.info.fullname != 'builtins.object': getattr_type = get_proper_type(find_node_type(method, itype, subtype)) if isinstance(getattr_type, CallableType): return getattr_type.ret_type @@ -1106,7 +1106,7 @@ def covers_at_runtime(item: Type, supertype: Type, ignore_promotions: bool) -> b return True if isinstance(item, TypedDictType) and isinstance(supertype, Instance): # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). - if supertype.type.fullname() == 'builtins.dict': + if supertype.type.fullname == 'builtins.dict': return True # TODO: Add more special cases. return False @@ -1209,7 +1209,7 @@ def visit_instance(self, left: Instance) -> bool: TypeState.record_subtype_cache_entry(self._subtype_kind, left, right) return True - if left.type.has_base(right.type.fullname()): + if left.type.has_base(right.type.fullname): def check_argument(leftarg: Type, rightarg: Type, variance: int) -> bool: if variance == COVARIANT: return self._is_proper_subtype(leftarg, rightarg) @@ -1328,13 +1328,13 @@ def visit_type_type(self, left: TypeType) -> bool: # This is also unsound because of __init__. return right.is_type_obj() and self._is_proper_subtype(left.item, right.ret_type) if isinstance(right, Instance): - if right.type.fullname() == 'builtins.type': + if right.type.fullname == 'builtins.type': # TODO: Strictly speaking, the type builtins.type is considered equivalent to # Type[Any]. However, this would break the is_proper_subtype check in # conditional_type_map for cases like isinstance(x, type) when the type # of x is Type[int]. It's unclear what's the right way to address this. return True - if right.type.fullname() == 'builtins.object': + if right.type.fullname == 'builtins.object': return True item = left.item if isinstance(item, TypeVarType): diff --git a/mypy/suggestions.py b/mypy/suggestions.py index 44d15d2edd1e..b1bf248f1e1d 100644 --- a/mypy/suggestions.py +++ b/mypy/suggestions.py @@ -369,7 +369,7 @@ def get_callsites(self, func: FuncDef) -> Tuple[List[Callsite], List[str]]: """Find all call sites of a function.""" new_type = self.get_starting_type(func) - collector_plugin = SuggestionPlugin(func.fullname()) + collector_plugin = SuggestionPlugin(func.fullname) self.plugin._plugins.insert(0, collector_plugin) try: @@ -486,7 +486,7 @@ def find_node(self, key: str) -> Tuple[str, str, FuncDef]: raise SuggestionFailure('Line number must be a number. Got {}'.format(line)) line_number = int(line) modname, node = self.find_node_by_file_and_line(file, line_number) - tail = node.fullname()[len(modname) + 1:] # add one to account for '.' + tail = node.fullname[len(modname) + 1:] # add one to account for '.' else: target = split_target(self.fgmanager.graph, key) if not target: @@ -605,7 +605,7 @@ def try_type(self, func: FuncDef, typ: ProperType) -> List[str]: func.type = None func.unanalyzed_type = typ try: - res = self.fgmanager.trigger(func.fullname()) + res = self.fgmanager.trigger(func.fullname) # if res: # print('===', typ) # print('\n'.join(res)) @@ -696,7 +696,7 @@ def score_type(self, t: Type, arg_pos: bool) -> int: return 10 if isinstance(t, CallableType) and (has_any_type(t) or is_tricky_callable(t)): return 10 - if self.try_text and isinstance(t, Instance) and t.type.fullname() == 'builtins.str': + if self.try_text and isinstance(t, Instance) and t.type.fullname == 'builtins.str': return 1 return 0 @@ -757,7 +757,7 @@ def __init__(self, module: Optional[str], graph: Graph) -> None: self.graph = graph def visit_instance(self, t: Instance) -> str: - s = t.type.fullname() or t.type.name() or None + s = t.type.fullname or t.type.name or None if s is None: return '' if s in reverse_builtin_aliases: @@ -791,7 +791,7 @@ def visit_instance(self, t: Instance) -> str: def visit_tuple_type(self, t: TupleType) -> str: if t.partial_fallback and t.partial_fallback.type: - fallback_name = t.partial_fallback.type.fullname() + fallback_name = t.partial_fallback.type.fullname if fallback_name != 'builtins.tuple': return t.partial_fallback.accept(self) s = self.list_str(t.items) @@ -827,12 +827,12 @@ def __init__(self, builtin_type: Callable[[str], Instance]) -> None: def visit_type_alias_type(self, t: TypeAliasType) -> Type: exp_t = get_proper_type(t) - if isinstance(exp_t, Instance) and exp_t.type.fullname() == 'builtins.str': + if isinstance(exp_t, Instance) and exp_t.type.fullname == 'builtins.str': return self.text_type return t.copy_modified(args=[a.accept(self) for a in t.args]) def visit_instance(self, t: Instance) -> Type: - if t.type.fullname() == 'builtins.str': + if t.type.fullname == 'builtins.str': return self.text_type else: return super().visit_instance(t) diff --git a/mypy/test/testmerge.py b/mypy/test/testmerge.py index b3818f9e77ef..c9f04c2abef6 100644 --- a/mypy/test/testmerge.py +++ b/mypy/test/testmerge.py @@ -181,7 +181,7 @@ def format_symbol_table_node(self, node: SymbolTableNode) -> str: else: s = '? ({})'.format(type(node.node)) if (isinstance(node.node, Var) and node.node.type and - not node.node.fullname().startswith('typing.')): + not node.node.fullname.startswith('typing.')): typestr = self.format_type(node.node.type) s += '({})'.format(typestr) return s @@ -203,7 +203,7 @@ def dump_typeinfos_recursive(self, names: SymbolTable) -> List[str]: return a def dump_typeinfo(self, info: TypeInfo) -> List[str]: - if info.fullname() == 'enum.Enum': + if info.fullname == 'enum.Enum': # Avoid noise return [] s = info.dump(str_conv=self.str_conv, diff --git a/mypy/test/visitors.py b/mypy/test/visitors.py index 9051886bbc55..2ba4ab52d135 100644 --- a/mypy/test/visitors.py +++ b/mypy/test/visitors.py @@ -24,7 +24,7 @@ def __init__(self) -> None: self.is_typing = False def visit_mypy_file(self, f: MypyFile) -> None: - self.is_typing = f.fullname() == 'typing' or f.fullname() == 'builtins' + self.is_typing = f.fullname == 'typing' or f.fullname == 'builtins' super().visit_mypy_file(f) def visit_assignment_stmt(self, s: AssignmentStmt) -> None: diff --git a/mypy/treetransform.py b/mypy/treetransform.py index 43fe7ae87fe8..09d1edd4220d 100644 --- a/mypy/treetransform.py +++ b/mypy/treetransform.py @@ -104,7 +104,7 @@ def visit_func_def(self, node: FuncDef) -> FuncDef: for stmt in node.body.body: stmt.accept(init) - new = FuncDef(node.name(), + new = FuncDef(node.name, [self.copy_argument(arg) for arg in node.arguments], self.block(node.body), cast(Optional[FunctionLike], self.optional_type(node.type))) @@ -200,7 +200,7 @@ def visit_var(self, node: Var) -> Var: # Note that a Var must be transformed to a Var. if node in self.var_map: return self.var_map[node] - new = Var(node.name(), self.optional_type(node.type)) + new = Var(node.name, self.optional_type(node.type)) new.line = node.line new._fullname = node._fullname new.info = node.info @@ -492,7 +492,7 @@ def visit_backquote_expr(self, node: BackquoteExpr) -> BackquoteExpr: return BackquoteExpr(self.expr(node.expr)) def visit_type_var_expr(self, node: TypeVarExpr) -> TypeVarExpr: - return TypeVarExpr(node.name(), node.fullname(), + return TypeVarExpr(node.name, node.fullname, self.types(node.values), self.type(node.upper_bound), variance=node.variance) @@ -615,5 +615,5 @@ def visit_func_def(self, node: FuncDef) -> None: if node not in self.transformer.func_placeholder_map: # Haven't seen this FuncDef before, so create a placeholder node. self.transformer.func_placeholder_map[node] = FuncDef( - node.name(), node.arguments, node.body, None) + node.name, node.arguments, node.body, None) super().visit_func_def(node) diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py index 639c89da80d6..7d5dce18fc66 100644 --- a/mypy/tvar_scope.py +++ b/mypy/tvar_scope.py @@ -60,14 +60,14 @@ def bind_new(self, name: str, tvar_expr: TypeVarExpr) -> TypeVarDef: self.func_id -= 1 i = self.func_id tvar_def = TypeVarDef(name, - tvar_expr.fullname(), + tvar_expr.fullname, i, values=tvar_expr.values, upper_bound=tvar_expr.upper_bound, variance=tvar_expr.variance, line=tvar_expr.line, column=tvar_expr.column) - self.scope[tvar_expr.fullname()] = tvar_def + self.scope[tvar_expr.fullname] = tvar_def return tvar_def def bind_existing(self, tvar_def: TypeVarDef) -> None: diff --git a/mypy/typeanal.py b/mypy/typeanal.py index e455f80dc12e..ce6b06119a70 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -177,7 +177,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) self.api.defer() else: self.api.record_incomplete_ref() - return PlaceholderType(node.fullname(), self.anal_array(t.args), t.line) + return PlaceholderType(node.fullname, self.anal_array(t.args), t.line) else: if self.api.final_iteration: self.cannot_resolve_type(t) @@ -189,7 +189,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) if node is None: self.fail('Internal error (node is None, kind={})'.format(sym.kind), t) return AnyType(TypeOfAny.special_form) - fullname = node.fullname() + fullname = node.fullname hook = self.plugin.get_type_analyze_hook(fullname) if hook is not None: return hook(AnalyzeTypeContext(t, t, self)) @@ -333,7 +333,7 @@ def analyze_type_with_type_info(self, info: TypeInfo, args: List[Type], ctx: Con This handles simple cases like 'int', 'modname.UserClass[str]', etc. """ - if len(args) > 0 and info.fullname() == 'builtins.tuple': + if len(args) > 0 and info.fullname == 'builtins.tuple': fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line) return TupleType(self.anal_array(args), fallback, ctx.line) # Analyze arguments and (usually) construct Instance type. The @@ -378,7 +378,7 @@ def analyze_unbound_type_without_type_info(self, t: UnboundType, sym: SymbolTabl name = sym.fullname if name is None: assert sym.node is not None - name = sym.node.name() + name = sym.node.name # Option 1: # Something with an Any type -- make it an alias for Any in a type # context. This is slightly problematic as it allows using the type 'Any' @@ -407,8 +407,8 @@ def analyze_unbound_type_without_type_info(self, t: UnboundType, sym: SymbolTabl # `def foo(x: Color.RED) -> None: ...`, we can remove that # check entirely. if isinstance(sym.node, Var) and sym.node.info and sym.node.info.is_enum: - value = sym.node.name() - base_enum_short_name = sym.node.info.name() + value = sym.node.name + base_enum_short_name = sym.node.info.name if not defining_literal: msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format( base_enum_short_name, value) @@ -830,10 +830,10 @@ def bind_function_type_variables(self, if not self.is_defined_type_var(name, defn)] defs = [] # type: List[TypeVarDef] for name, tvar in typevars: - if not self.tvar_scope.allow_binding(tvar.fullname()): + if not self.tvar_scope.allow_binding(tvar.fullname): self.fail("Type variable '{}' is bound by an outer class".format(name), defn) self.tvar_scope.bind_new(name, tvar) - binding = self.tvar_scope.get_binding(tvar.fullname()) + binding = self.tvar_scope.get_binding(tvar.fullname) assert binding is not None defs.append(binding) @@ -950,7 +950,7 @@ def fix_instance(t: Instance, fail: MsgCallback, note: MsgCallback, if use_generic_error: fullname = None # type: Optional[str] else: - fullname = t.type.fullname() + fullname = t.type.fullname any_type = get_omitted_any(disallow_any, fail, note, t, fullname, unexpanded_type) t.args = [any_type] * len(t.type.type_vars) return @@ -965,7 +965,7 @@ def fix_instance(t: Instance, fail: MsgCallback, note: MsgCallback, if act == '0': act = 'none' fail('"{}" expects {}, but {} given'.format( - t.type.name(), s, act), t, code=codes.TYPE_ARG) + t.type.name, s, act), t, code=codes.TYPE_ARG) # Construct the correct number of type arguments, as # otherwise the type checker may crash as it expects # things to be right. @@ -1013,7 +1013,7 @@ def expand_type_alias(target: Type, alias_tvars: List[str], args: List[Type], typ = replace_alias_tvars(target, alias_tvars, args, ctx.line, ctx.column) # type: Type # HACK: Implement FlexibleAlias[T, typ] by expanding it to typ here. if (isinstance(typ, Instance) # type: ignore - and typ.type.fullname() == 'mypy_extensions.FlexibleAlias'): + and typ.type.fullname == 'mypy_extensions.FlexibleAlias'): typ = typ.args[-1] return typ diff --git a/mypy/typeops.py b/mypy/typeops.py index 763e70c643ab..1b2f20cf1759 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -39,7 +39,7 @@ def tuple_fallback(typ: TupleType) -> Instance: from mypy.join import join_type_list info = typ.partial_fallback.type - if info.fullname() != 'builtins.tuple': + if info.fullname != 'builtins.tuple': return typ.partial_fallback return Instance(info, [join_type_list(typ.items)]) @@ -94,7 +94,7 @@ def type_object_type_from_function(signature: FunctionLike, signature = cast(FunctionLike, map_type_from_supertype(signature, info, def_info)) special_sig = None # type: Optional[str] - if def_info.fullname() == 'builtins.dict': + if def_info.fullname == 'builtins.dict': # Special signature! special_sig = 'dict' @@ -136,7 +136,7 @@ def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance, callable_type = init_type.copy_modified( ret_type=ret_type, fallback=type_type, name=None, variables=variables, special_sig=special_sig) - c = callable_type.with_name(info.name()) + c = callable_type.with_name(info.name) return c @@ -468,7 +468,7 @@ def callable_type(fdef: FuncItem, fallback: Instance, # TODO: somewhat unfortunate duplication with prepare_method_signature in semanal if fdef.info and not fdef.is_static and fdef.arg_names: self_type = fill_typevars(fdef.info) # type: Type - if fdef.is_class or fdef.name() == '__new__': + if fdef.is_class or fdef.name == '__new__': self_type = TypeType.make_normalized(self_type) args = [self_type] + [AnyType(TypeOfAny.unannotated)] * (len(fdef.arg_names)-1) else: @@ -480,7 +480,7 @@ def callable_type(fdef: FuncItem, fallback: Instance, [None if argument_elide_name(n) else n for n in fdef.arg_names], ret_type or AnyType(TypeOfAny.unannotated), fallback, - name=fdef.name(), + name=fdef.name, line=fdef.line, column=fdef.column, implicit=True, @@ -550,7 +550,7 @@ def try_getting_literals_from_type(typ: Type, literals = [] # type: List[T] for lit in get_proper_types(possible_literals): - if isinstance(lit, LiteralType) and lit.fallback.type.fullname() == target_fullname: + if isinstance(lit, LiteralType) and lit.fallback.type.fullname == target_fullname: val = lit.value if isinstance(val, target_literal_type): literals.append(val) @@ -615,7 +615,7 @@ class Status(Enum): if isinstance(typ, UnionType): items = [try_expanding_enum_to_union(item, target_fullname) for item in typ.items] return make_simplified_union(items) - elif isinstance(typ, Instance) and typ.type.is_enum and typ.type.fullname() == target_fullname: + elif isinstance(typ, Instance) and typ.type.is_enum and typ.type.fullname == target_fullname: new_items = [] for name, symbol in typ.type.names.items(): if not isinstance(symbol.node, Var): diff --git a/mypy/types.py b/mypy/types.py index b2c689f537e2..b426b5721566 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -235,7 +235,7 @@ def __eq__(self, other: object) -> bool: def serialize(self) -> JsonDict: assert self.alias is not None data = {'.class': 'TypeAliasType', - 'type_ref': self.alias.fullname(), + 'type_ref': self.alias.fullname, 'args': [arg.serialize() for arg in self.args]} # type: JsonDict return data @@ -794,7 +794,7 @@ def __eq__(self, other: object) -> bool: def serialize(self) -> Union[JsonDict, str]: assert self.type is not None - type_ref = self.type.fullname() + type_ref = self.type.fullname if not self.args and not self.last_known_value: return type_ref data = {'.class': 'Instance', @@ -1437,7 +1437,7 @@ def deserialize(cls, data: JsonDict) -> 'TypedDictType': Instance.deserialize(data['fallback'])) def is_anonymous(self) -> bool: - return self.fallback.type.fullname() in TPDICT_FB_NAMES + return self.fallback.type.fullname in TPDICT_FB_NAMES def as_anonymous(self) -> 'TypedDictType': if self.is_anonymous(): @@ -1606,7 +1606,7 @@ def value_repr(self) -> str: where the value is a string, byte string, a unicode string, or an enum. """ raw = repr(self.value) - fallback_name = self.fallback.type.fullname() + fallback_name = self.fallback.type.fullname # If this is backed by an enum, if self.is_enum_literal(): @@ -1972,7 +1972,7 @@ def visit_deleted_type(self, t: DeletedType) -> str: return "".format(t.source) def visit_instance(self, t: Instance) -> str: - s = t.type.fullname() or t.type.name() or '' + s = t.type.fullname or t.type.name or '' if t.erased: s += '*' if t.args != []: @@ -2041,7 +2041,7 @@ def visit_overloaded(self, t: Overloaded) -> str: def visit_tuple_type(self, t: TupleType) -> str: s = self.list_str(t.items) if t.partial_fallback and t.partial_fallback.type: - fallback_name = t.partial_fallback.type.fullname() + fallback_name = t.partial_fallback.type.fullname if fallback_name != 'builtins.tuple': return 'Tuple[{}, fallback={}]'.format(s, t.partial_fallback.accept(self)) return 'Tuple[{}]'.format(s) @@ -2057,8 +2057,8 @@ def item_str(name: str, typ: str) -> str: for name, typ in t.items.items()) + '}' prefix = '' if t.fallback and t.fallback.type: - if t.fallback.type.fullname() not in TPDICT_FB_NAMES: - prefix = repr(t.fallback.type.fullname()) + ', ' + if t.fallback.type.fullname not in TPDICT_FB_NAMES: + prefix = repr(t.fallback.type.fullname) + ', ' return 'TypedDict({}{})'.format(prefix, s) def visit_raw_expression_type(self, t: RawExpressionType) -> str: @@ -2079,7 +2079,7 @@ def visit_partial_type(self, t: PartialType) -> str: if t.type is None: return '' else: - return ''.format(t.type.name(), + return ''.format(t.type.name, ', '.join(['?'] * len(t.type.type_vars))) def visit_ellipsis_type(self, t: EllipsisType) -> str: @@ -2093,7 +2093,7 @@ def visit_placeholder_type(self, t: PlaceholderType) -> str: def visit_type_alias_type(self, t: TypeAliasType) -> str: if t.alias is not None: - return ''.format(t.alias.fullname()) + return ''.format(t.alias.fullname) return '' def list_str(self, a: Iterable[Type]) -> str: @@ -2140,7 +2140,7 @@ def strip_type(typ: Type) -> ProperType: def is_named_instance(t: Type, fullname: str) -> bool: t = get_proper_type(t) - return isinstance(t, Instance) and t.type.fullname() == fullname + return isinstance(t, Instance) and t.type.fullname == fullname TP = TypeVar('TP', bound=Type) @@ -2255,7 +2255,7 @@ def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue typ = typ.last_known_value if not isinstance(typ, LiteralType): return False - if typ.fallback.type.fullname() != fallback_fullname: + if typ.fallback.type.fullname != fallback_fullname: return False return typ.value == value diff --git a/mypy/typestate.py b/mypy/typestate.py index 87dba5cbf601..39eca3e318ef 100644 --- a/mypy/typestate.py +++ b/mypy/typestate.py @@ -152,9 +152,9 @@ def record_protocol_subtype_check(left_type: TypeInfo, right_type: TypeInfo) -> assert right_type.is_protocol TypeState._rechecked_types.add(left_type) TypeState._attempted_protocols.setdefault( - left_type.fullname(), set()).add(right_type.fullname()) + left_type.fullname, set()).add(right_type.fullname) TypeState._checked_against_members.setdefault( - left_type.fullname(), + left_type.fullname, set()).update(right_type.protocol_members) @staticmethod @@ -189,18 +189,18 @@ def __iter__(self) -> Iterator[int]: """ deps = {} # type: Dict[str, Set[str]] for info in TypeState._rechecked_types: - for attr in TypeState._checked_against_members[info.fullname()]: + for attr in TypeState._checked_against_members[info.fullname]: # The need for full MRO here is subtle, during an update, base classes of # a concrete class may not be reprocessed, so not all -> deps # are added. for base_info in info.mro[:-1]: - trigger = make_trigger('%s.%s' % (base_info.fullname(), attr)) + trigger = make_trigger('%s.%s' % (base_info.fullname, attr)) if 'typing' in trigger or 'builtins' in trigger: # TODO: avoid everything from typeshed continue - deps.setdefault(trigger, set()).add(make_trigger(info.fullname())) - for proto in TypeState._attempted_protocols[info.fullname()]: - trigger = make_trigger(info.fullname()) + deps.setdefault(trigger, set()).add(make_trigger(info.fullname)) + for proto in TypeState._attempted_protocols[info.fullname]: + trigger = make_trigger(info.fullname) if 'typing' in trigger or 'builtins' in trigger: continue # If any class that was checked against a protocol changes, diff --git a/mypyc/emitmodule.py b/mypyc/emitmodule.py index 7da48780a90e..f1fdf0b5f833 100644 --- a/mypyc/emitmodule.py +++ b/mypyc/emitmodule.py @@ -151,7 +151,7 @@ def report_config_data( def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]: # Report dependency on modules in the module's group - return [(10, id, -1) for id in self.group_map.get(file.fullname(), (None, []))[1]] + return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]] def parse_and_typecheck( @@ -196,7 +196,7 @@ def compile_scc_to_ir( """ if compiler_options.verbose: - print("Compiling {}".format(", ".join(x.name() for x in scc))) + print("Compiling {}".format(", ".join(x.name for x in scc))) # Generate basic IR, with missing exception and refcount handling. modules = genops.build_ir( @@ -359,8 +359,8 @@ def load_scc_from_cache( Arguments and return are as compile_scc_to_ir. """ cache_data = { - k.fullname(): json.loads( - result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname()])) + k.fullname: json.loads( + result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname])) )['ir'] for k in scc } modules = deserialize_modules(cache_data, ctx) diff --git a/mypyc/genops.py b/mypyc/genops.py index 5547897d164a..070ed9d0fd1e 100644 --- a/mypyc/genops.py +++ b/mypyc/genops.py @@ -132,7 +132,7 @@ def build_type_map(mapper: 'Mapper', # Collect all class mappings so that we can bind arbitrary class name # references even if there are import cycles. for module, cdef in classes: - class_ir = ClassIR(cdef.name, module.fullname(), is_trait(cdef), + class_ir = ClassIR(cdef.name, module.fullname, is_trait(cdef), is_abstract=cdef.info.is_abstract) # If global optimizations are disabled, turn of tracking of class children if not options.global_opts: @@ -146,16 +146,16 @@ def build_type_map(mapper: 'Mapper', for module, cdef in classes: with catch_errors(module.path, cdef.line): if mapper.type_to_ir[cdef.info].is_ext_class: - prepare_class_def(module.path, module.fullname(), cdef, errors, mapper) + prepare_class_def(module.path, module.fullname, cdef, errors, mapper) else: - prepare_non_ext_class_def(module.path, module.fullname(), cdef, errors, mapper) + prepare_non_ext_class_def(module.path, module.fullname, cdef, errors, mapper) # Collect all the functions also. We collect from the symbol table # so that we can easily pick out the right copy of a function that # is conditionally defined. for module in modules: for func in get_module_func_defs(module): - prepare_func_def(module.fullname(), None, func, mapper) + prepare_func_def(module.fullname, None, func, mapper) # TODO: what else? @@ -170,7 +170,7 @@ def load_type_map(mapper: 'Mapper', for module in modules: for func in get_module_func_defs(module): - mapper.func_to_decl[func] = deser_ctx.functions[func.fullname()].decl + mapper.func_to_decl[func] = deser_ctx.functions[func.fullname].decl @strict_optional_dec # Turn on strict optional for any type manipulations we do @@ -195,17 +195,17 @@ def build_ir(modules: List[MypyFile], # Second pass. builder = IRBuilder( - module.fullname(), types, graph, errors, mapper, pbv, options + module.fullname, types, graph, errors, mapper, pbv, options ) builder.visit_mypy_file(module) module_ir = ModuleIR( - module.fullname(), + module.fullname, list(builder.imports), builder.functions, builder.classes, builder.final_names ) - result[module.fullname()] = module_ir + result[module.fullname] = module_ir class_irs.extend(builder.classes) # Compute vtables. @@ -244,7 +244,7 @@ def is_extension_class(cdef: ClassDef) -> bool: if any(not is_trait_decorator(d) and not is_dataclass_decorator(d) for d in cdef.decorators): return False - elif (cdef.info.metaclass_type and cdef.info.metaclass_type.type.fullname() not in ( + elif (cdef.info.metaclass_type and cdef.info.metaclass_type.type.fullname not in ( 'abc.ABCMeta', 'typing.TypingMeta', 'typing.GenericMeta')): return False return True @@ -299,7 +299,7 @@ def get_module_func_defs(module: MypyFile) -> Iterable[FuncDef]: # aliases. The best way to do this seems to be by # checking that the fullname matches. if (isinstance(node.node, (FuncDef, Decorator, OverloadedFuncDef)) - and node.fullname == module.fullname() + '.' + name): + and node.fullname == module.fullname + '.' + name): yield get_func_def(node.node) @@ -412,24 +412,24 @@ def type_to_rtype(self, typ: Optional[Type]) -> RType: typ = get_proper_type(typ) if isinstance(typ, Instance): - if typ.type.fullname() == 'builtins.int': + if typ.type.fullname == 'builtins.int': return int_rprimitive - elif typ.type.fullname() == 'builtins.float': + elif typ.type.fullname == 'builtins.float': return float_rprimitive - elif typ.type.fullname() == 'builtins.str': + elif typ.type.fullname == 'builtins.str': return str_rprimitive - elif typ.type.fullname() == 'builtins.bool': + elif typ.type.fullname == 'builtins.bool': return bool_rprimitive - elif typ.type.fullname() == 'builtins.list': + elif typ.type.fullname == 'builtins.list': return list_rprimitive # Dict subclasses are at least somewhat common and we # specifically support them, so make sure that dict operations # get optimized on them. - elif any(cls.fullname() == 'builtins.dict' for cls in typ.type.mro): + elif any(cls.fullname == 'builtins.dict' for cls in typ.type.mro): return dict_rprimitive - elif typ.type.fullname() == 'builtins.set': + elif typ.type.fullname == 'builtins.set': return set_rprimitive - elif typ.type.fullname() == 'builtins.tuple': + elif typ.type.fullname == 'builtins.tuple': return tuple_rprimitive # Varying-length tuple elif typ.type in self.type_to_ir: return RInstance(self.type_to_ir[typ.type]) @@ -438,7 +438,7 @@ def type_to_rtype(self, typ: Optional[Type]) -> RType: elif isinstance(typ, TupleType): # Use our unboxed tuples for raw tuples but fall back to # being boxed for NamedTuple. - if typ.partial_fallback.type.fullname() == 'builtins.tuple': + if typ.partial_fallback.type.fullname == 'builtins.tuple': return RTuple([self.type_to_rtype(t) for t in typ.items]) else: return tuple_rprimitive @@ -492,13 +492,13 @@ def fdef_to_sig(self, fdef: FuncDef) -> FuncSignature: arg_types = [object_rprimitive for arg in fdef.arguments] ret = object_rprimitive - args = [RuntimeArg(arg.variable.name(), arg_type, arg.kind) + args = [RuntimeArg(arg.variable.name, arg_type, arg.kind) for arg, arg_type in zip(fdef.arguments, arg_types)] # We force certain dunder methods to return objects to support letting them # return NotImplemented. It also avoids some pointless boxing and unboxing, # since tp_richcompare needs an object anyways. - if fdef.name() in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'): + if fdef.name in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'): ret = object_rprimitive return FuncSignature(args, ret) @@ -523,7 +523,7 @@ def prepare_func_def(module_name: str, class_name: Optional[str], fdef: FuncDef, mapper: Mapper) -> FuncDecl: kind = FUNC_STATICMETHOD if fdef.is_static else ( FUNC_CLASSMETHOD if fdef.is_class else FUNC_NORMAL) - decl = FuncDecl(fdef.name(), class_name, module_name, mapper.fdef_to_sig(fdef), kind) + decl = FuncDecl(fdef.name, class_name, module_name, mapper.fdef_to_sig(fdef), kind) mapper.func_to_decl[fdef] = decl return decl @@ -531,25 +531,25 @@ def prepare_func_def(module_name: str, class_name: Optional[str], def prepare_method_def(ir: ClassIR, module_name: str, cdef: ClassDef, mapper: Mapper, node: Union[FuncDef, Decorator]) -> None: if isinstance(node, FuncDef): - ir.method_decls[node.name()] = prepare_func_def(module_name, cdef.name, node, mapper) + ir.method_decls[node.name] = prepare_func_def(module_name, cdef.name, node, mapper) elif isinstance(node, Decorator): # TODO: do something about abstract methods here. Currently, they are handled just like # normal methods. decl = prepare_func_def(module_name, cdef.name, node.func, mapper) if not node.decorators: - ir.method_decls[node.name()] = decl + ir.method_decls[node.name] = decl elif isinstance(node.decorators[0], MemberExpr) and node.decorators[0].name == 'setter': # Make property setter name different than getter name so there are no # name clashes when generating C code, and property lookup at the IR level # works correctly. decl.name = PROPSET_PREFIX + decl.name decl.is_prop_setter = True - ir.method_decls[PROPSET_PREFIX + node.name()] = decl + ir.method_decls[PROPSET_PREFIX + node.name] = decl if node.func.is_property: assert node.func.type decl.is_prop_getter = True - ir.property_types[node.name()] = decl.sig.ret_type + ir.property_types[node.name] = decl.sig.ret_type def is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool: @@ -609,12 +609,12 @@ def prepare_class_def(path: str, module_name: str, cdef: ClassDef, for cls in info.mro: # Special case exceptions and dicts # XXX: How do we handle *other* things?? - if cls.fullname() == 'builtins.BaseException': + if cls.fullname == 'builtins.BaseException': ir.builtin_base = 'PyBaseExceptionObject' - elif cls.fullname() == 'builtins.dict': + elif cls.fullname == 'builtins.dict': ir.builtin_base = 'PyDictObject' - elif cls.fullname().startswith('builtins.'): - if not can_subclass_builtin(cls.fullname()): + elif cls.fullname.startswith('builtins.'): + if not can_subclass_builtin(cls.fullname): # Note that if we try to subclass a C extension class that # isn't in builtins, bad things will happen and we won't # catch it here! But this should catch a lot of the most @@ -636,7 +636,7 @@ def prepare_class_def(path: str, module_name: str, cdef: ClassDef, # **kwargs so it can call tp_init. if ((defining_ir is None or not defining_ir.is_ext_class or cdef.info['__init__'].plugin_generated) - and init_node.info.fullname() != 'builtins.object'): + and init_node.info.fullname != 'builtins.object'): init_sig = FuncSignature( [init_sig.args[0], RuntimeArg("args", tuple_rprimitive, ARG_STAR), @@ -658,7 +658,7 @@ def prepare_class_def(path: str, module_name: str, cdef: ClassDef, base_mro = [] for cls in info.mro: if cls not in mapper.type_to_ir: - if cls.fullname() != 'builtins.object': + if cls.fullname != 'builtins.object': ir.inherits_python = True continue base_ir = mapper.type_to_ir[cls] @@ -1119,13 +1119,13 @@ def __init__(self, self.imports = OrderedDict() # type: OrderedDict[str, None] def visit_mypy_file(self, mypyfile: MypyFile) -> None: - if mypyfile.fullname() in ('typing', 'abc'): + if mypyfile.fullname in ('typing', 'abc'): # These module are special; their contents are currently all # built-in primitives. return self.module_path = mypyfile.path - self.module_name = mypyfile.fullname() + self.module_name = mypyfile.fullname classes = [node for node in mypyfile.defs if isinstance(node, ClassDef)] @@ -1153,14 +1153,14 @@ def visit_mypy_file(self, mypyfile: MypyFile) -> None: def handle_ext_method(self, cdef: ClassDef, fdef: FuncDef) -> None: # Perform the function of visit_method for methods inside extension classes. - name = fdef.name() + name = fdef.name class_ir = self.mapper.type_to_ir[cdef.info] func_ir, func_reg = self.gen_func_item(fdef, name, self.mapper.fdef_to_sig(fdef), cdef) self.functions.append(func_ir) if self.is_decorated(fdef): # Obtain the the function name in order to construct the name of the helper function. - _, _, name = fdef.fullname().rpartition('.') + _, _, name = fdef.fullname.rpartition('.') helper_name = decorator_helper_name(name) # Read the PyTypeObject representing the class, get the callable object # representing the non-decorated method @@ -1213,7 +1213,7 @@ def handle_ext_method(self, cdef: ClassDef, fdef: FuncDef) -> None: def handle_non_ext_method( self, non_ext: NonExtClassInfo, cdef: ClassDef, fdef: FuncDef) -> None: # Perform the function of visit_method for methods inside non-extension classes. - name = fdef.name() + name = fdef.name func_ir, func_reg = self.gen_func_item(fdef, name, self.mapper.fdef_to_sig(fdef), cdef) assert func_reg is not None self.functions.append(func_ir) @@ -1375,7 +1375,7 @@ def populate_non_ext_bases(self, cdef: ClassDef) -> Value: ir = self.mapper.type_to_ir[cdef.info] bases = [] for cls in cdef.info.mro[1:]: - if cls.fullname() == 'builtins.object': + if cls.fullname == 'builtins.object': continue # Add the current class to the base classes list of concrete subclasses if cls in self.mapper.type_to_ir: @@ -1383,7 +1383,7 @@ def populate_non_ext_bases(self, cdef: ClassDef) -> Value: if base_ir.children is not None: base_ir.children.append(ir) - base = self.load_global_str(cls.name(), cdef.line) + base = self.load_global_str(cls.name, cdef.line) bases.append(base) return self.primitive_op(new_tuple_op, bases, cdef.line) @@ -1415,7 +1415,7 @@ def add_non_ext_class_attr(self, non_ext: NonExtClassInfo, lvalue: NameExpr, self.add_to_non_ext_dict(non_ext, lvalue.name, rvalue, stmt.line) # We cache enum attributes to speed up enum attribute lookup since they # are final. - if cdef.info.bases and cdef.info.bases[0].type.fullname() == 'enum.Enum': + if cdef.info.bases and cdef.info.bases[0].type.fullname == 'enum.Enum': attr_to_cache.append(lvalue) def setup_non_ext_dict(self, cdef: ClassDef, bases: Value) -> Value: @@ -1543,7 +1543,7 @@ def visit_class_def(self, cdef: ClassDef) -> None: # Ignore plugin generated methods (since they have no # bodies to compile and will need to have the bodies # provided by some other mechanism.) - if cdef.info.names[stmt.name()].plugin_generated: + if cdef.info.names[stmt.name].plugin_generated: continue with self.catch_errors(stmt.line): self.visit_method(cdef, non_ext, get_func_def(stmt)) @@ -1874,11 +1874,11 @@ def calculate_arg_defaults(self, value = self.coerce(self.accept(arg.initializer), env.lookup(arg.variable).type, arg.line) if not fn_info.is_nested: - name = fitem.fullname() + '.' + arg.variable.name() + name = fitem.fullname + '.' + arg.variable.name self.add(InitStatic(value, name, self.module_name)) else: assert func_reg is not None - self.add(SetAttr(func_reg, arg.variable.name(), value, arg.line)) + self.add(SetAttr(func_reg, arg.variable.name, value, arg.line)) def gen_arg_defaults(self) -> None: """Generate blocks for arguments that have default values. @@ -1901,11 +1901,11 @@ def get_default() -> Value: # Because gen_arg_defaults runs before calculate_arg_defaults, we # add the static/attribute to final_names/the class here. elif not self.fn_info.is_nested: - name = fitem.fullname() + '.' + arg.variable.name() + name = fitem.fullname + '.' + arg.variable.name self.final_names.append((name, target.type)) return self.add(LoadStatic(target.type, name, self.module_name)) else: - name = arg.variable.name() + name = arg.variable.name self.fn_info.callable_class.ir.attributes[name] = target.type return self.add( GetAttr(self.fn_info.callable_class.self_reg, name, arg.line)) @@ -2019,7 +2019,7 @@ def c() -> None: if self.fn_info.fitem in self.free_variables: # Sort the variables to keep things deterministic - for var in sorted(self.free_variables[self.fn_info.fitem], key=lambda x: x.name()): + for var in sorted(self.free_variables[self.fn_info.fitem], key=lambda x: x.name): if isinstance(var, Var): rtype = self.type_to_rtype(var.type) self.add_var_to_env_class(var, rtype, env_for_func, reassign=False) @@ -2081,10 +2081,10 @@ def gen_func_ir(self, class_name = None if cdef is None else cdef.name func_decl = FuncDecl(fn_info.name, class_name, self.module_name, sig) func_ir = FuncIR(func_decl, blocks, env, fn_info.fitem.line, - traceback_name=fn_info.fitem.name()) + traceback_name=fn_info.fitem.name) else: func_ir = FuncIR(self.mapper.func_to_decl[fn_info.fitem], blocks, env, - fn_info.fitem.line, traceback_name=fn_info.fitem.name()) + fn_info.fitem.line, traceback_name=fn_info.fitem.name) return (func_ir, func_reg) def load_decorated_func(self, fdef: FuncDef, orig_func_reg: Value) -> Value: @@ -2114,7 +2114,7 @@ def maybe_add_implicit_return(self) -> None: self.add_implicit_unreachable() def visit_func_def(self, fdef: FuncDef) -> None: - func_ir, func_reg = self.gen_func_item(fdef, fdef.name(), self.mapper.fdef_to_sig(fdef)) + func_ir, func_reg = self.gen_func_item(fdef, fdef.name, self.mapper.fdef_to_sig(fdef)) # If the function that was visited was a nested function, then either look it up in our # current environment or define it if it was not already defined. @@ -2876,8 +2876,8 @@ def is_native_module(self, module: str) -> bool: def is_native_ref_expr(self, expr: RefExpr) -> bool: if expr.node is None: return False - if '.' in expr.node.fullname(): - return self.is_native_module(expr.node.fullname().rpartition('.')[0]) + if '.' in expr.node.fullname: + return self.is_native_module(expr.node.fullname.rpartition('.')[0]) return True def is_native_module_ref_expr(self, expr: RefExpr) -> bool: @@ -2909,17 +2909,17 @@ def get_final_ref(self, expr: MemberExpr) -> Optional[Tuple[str, Var, bool]]: sym = expr.expr.node.get(expr.name) if sym and isinstance(sym.node, Var): # Enum attribute are treated as final since they are added to the global cache - expr_fullname = expr.expr.node.bases[0].type.fullname() + expr_fullname = expr.expr.node.bases[0].type.fullname is_final = sym.node.is_final or expr_fullname == 'enum.Enum' if is_final: final_var = sym.node - fullname = '{}.{}'.format(sym.node.info.fullname(), final_var.name()) + fullname = '{}.{}'.format(sym.node.info.fullname, final_var.name) native = self.is_native_module(expr.expr.node.module_name) elif self.is_module_member_expr(expr): # a module attribute if isinstance(expr.node, Var) and expr.node.is_final: final_var = expr.node - fullname = expr.node.fullname() + fullname = expr.node.fullname native = self.is_native_ref_expr(expr) if final_var is not None: return fullname, final_var, native @@ -2947,7 +2947,7 @@ def emit_load_final(self, final_var: Var, fullname: str, def visit_name_expr(self, expr: NameExpr) -> Value: assert expr.node, "RefExpr not resolved" - fullname = expr.node.fullname() + fullname = expr.node.fullname if fullname in name_ref_ops: # Use special access op for this particular name. desc = name_ref_ops[fullname] @@ -2961,8 +2961,8 @@ def visit_name_expr(self, expr: NameExpr) -> Value: if value is not None: return value - if isinstance(expr.node, MypyFile) and expr.node.fullname() in self.imports: - return self.load_module(expr.node.fullname()) + if isinstance(expr.node, MypyFile) and expr.node.fullname in self.imports: + return self.load_module(expr.node.fullname) # If the expression is locally defined, then read the result from the corresponding # assignment target and return it. Otherwise if the expression is a global, load it from @@ -2976,7 +2976,7 @@ def visit_name_expr(self, expr: NameExpr) -> Value: and expr.node.is_inferred): self.error( "Local variable '{}' has inferred type None; add an annotation".format( - expr.node.name()), + expr.node.name), expr.node.line) # TODO: Behavior currently only defined for Var and FuncDef node types. @@ -2992,13 +2992,13 @@ def visit_member_expr(self, expr: MemberExpr) -> Value: final = self.get_final_ref(expr) if final is not None: fullname, final_var, native = final - value = self.emit_load_final(final_var, fullname, final_var.name(), native, + value = self.emit_load_final(final_var, fullname, final_var.name, native, self.types[expr], expr.line) if value is not None: return value - if isinstance(expr.node, MypyFile) and expr.node.fullname() in self.imports: - return self.load_module(expr.node.fullname()) + if isinstance(expr.node, MypyFile) and expr.node.fullname in self.imports: + return self.load_module(expr.node.fullname) obj = self.accept(expr.expr) return self.get_attr(obj, expr.name, self.node_type(expr), expr.line) @@ -3283,7 +3283,7 @@ def translate_method_call(self, expr: CallExpr, callee: MemberExpr) -> Value: arg_kinds, arg_names = expr.arg_kinds[:], expr.arg_names[:] # Add the class argument for class methods in extension classes if decl.kind == FUNC_CLASSMETHOD and ir.is_ext_class: - args.append(self.load_native_type_object(callee.expr.node.fullname())) + args.append(self.load_native_type_object(callee.expr.node.fullname)) arg_kinds.insert(0, ARG_POS) arg_names.insert(0, None) args += [self.accept(arg) for arg in expr.args] @@ -4023,7 +4023,7 @@ def visit_lambda_expr(self, expr: LambdaExpr) -> Value: for arg, arg_type in zip(expr.arguments, typ.arg_types): arg.variable.type = arg_type runtime_args.append( - RuntimeArg(arg.variable.name(), self.type_to_rtype(arg_type), arg.kind)) + RuntimeArg(arg.variable.name, self.type_to_rtype(arg_type), arg.kind)) ret_type = self.type_to_rtype(typ.ret_type) fsig = FuncSignature(runtime_args, ret_type) @@ -4163,7 +4163,7 @@ def loop_contents( handle_loop(loop_params) def visit_decorator(self, dec: Decorator) -> None: - func_ir, func_reg = self.gen_func_item(dec.func, dec.func.name(), + func_ir, func_reg = self.gen_func_item(dec.func, dec.func.name, self.mapper.fdef_to_sig(dec.func)) if dec.func in self.nested_fitems: @@ -4173,7 +4173,7 @@ def visit_decorator(self, dec: Decorator) -> None: func_reg = decorated_func else: # Obtain the the function name in order to construct the name of the helper function. - name = dec.func.fullname().split('.')[-1] + name = dec.func.fullname.split('.')[-1] helper_name = decorator_helper_name(name) # Load the callable object representing the non-decorated function, and decorate it. @@ -4183,7 +4183,7 @@ def visit_decorator(self, dec: Decorator) -> None: # Set the callable object representing the decorated function as a global. self.primitive_op(dict_set_item_op, [self.load_globals_dict(), - self.load_static_unicode(dec.func.name()), decorated_func], + self.load_static_unicode(dec.func.name), decorated_func], decorated_func.line) self.functions.append(func_ir) @@ -4219,7 +4219,7 @@ def visit_super_expr(self, o: SuperExpr) -> Value: args = [self.accept(arg) for arg in o.call.args] else: assert o.info is not None - typ = self.load_native_type_object(o.info.fullname()) + typ = self.load_native_type_object(o.info.fullname) ir = self.mapper.type_to_ir[o.info] iter_env = iter(self.environment.indexes) vself = next(iter_env) # grab first argument @@ -4776,8 +4776,8 @@ def load_outer_env(self, base: Value, outer_env: Environment) -> Value: assert isinstance(env.type, RInstance), '{} must be of type RInstance'.format(env) for symbol, target in outer_env.symtable.items(): - env.type.class_ir.attributes[symbol.name()] = target.type - symbol_target = AssignmentTargetAttr(env, symbol.name()) + env.type.class_ir.attributes[symbol.name] = target.type + symbol_target = AssignmentTargetAttr(env, symbol.name) self.environment.add_target(symbol, symbol_target) return env @@ -4829,14 +4829,14 @@ def add_var_to_env_class(self, reassign: bool = False) -> AssignmentTarget: # First, define the variable name as an attribute of the environment class, and then # construct a target for that attribute. - self.fn_info.env_class.attributes[var.name()] = rtype - attr_target = AssignmentTargetAttr(base.curr_env_reg, var.name()) + self.fn_info.env_class.attributes[var.name] = rtype + attr_target = AssignmentTargetAttr(base.curr_env_reg, var.name) if reassign: # Read the local definition of the variable, and set the corresponding attribute of # the environment class' variable to be that value. reg = self.read(self.environment.lookup(var), self.fn_info.fitem.line) - self.add(SetAttr(base.curr_env_reg, var.name(), reg, self.fn_info.fitem.line)) + self.add(SetAttr(base.curr_env_reg, var.name, reg, self.fn_info.fitem.line)) # Override the local definition of the variable to instead point at the variable in # the environment class. @@ -4850,7 +4850,7 @@ def setup_func_for_recursive_call(self, fdef: FuncDef, base: ImplicitClass) -> N """ # First, set the attribute of the environment class so that GetAttr can be called on it. prev_env = self.fn_infos[-2].env_class - prev_env.attributes[fdef.name()] = self.type_to_rtype(fdef.type) + prev_env.attributes[fdef.name] = self.type_to_rtype(fdef.type) if isinstance(base, GeneratorClass): # If we are dealing with a generator class, then we need to first get the register @@ -4862,7 +4862,7 @@ def setup_func_for_recursive_call(self, fdef: FuncDef, base: ImplicitClass) -> N # Obtain the instance of the callable class representing the FuncDef, and add it to the # current environment. - val = self.add(GetAttr(prev_env_reg, fdef.name(), -1)) + val = self.add(GetAttr(prev_env_reg, fdef.name, -1)) target = self.environment.add_local_reg(fdef, object_rprimitive) self.assign(target, val, -1) @@ -4987,7 +4987,7 @@ def add_call_to_callable_class(self, sig = FuncSignature((RuntimeArg(SELF_NAME, object_rprimitive),) + sig.args, sig.ret_type) call_fn_decl = FuncDecl('__call__', fn_info.callable_class.ir.name, self.module_name, sig) call_fn_ir = FuncIR(call_fn_decl, blocks, env, - fn_info.fitem.line, traceback_name=fn_info.fitem.name()) + fn_info.fitem.line, traceback_name=fn_info.fitem.name) fn_info.callable_class.ir.methods['__call__'] = call_fn_ir return call_fn_ir @@ -5137,7 +5137,7 @@ def add_helper_to_generator_class(self, helper_fn_decl = FuncDecl('__mypyc_generator_helper__', fn_info.generator_class.ir.name, self.module_name, sig) helper_fn_ir = FuncIR(helper_fn_decl, blocks, env, - fn_info.fitem.line, traceback_name=fn_info.fitem.name()) + fn_info.fitem.line, traceback_name=fn_info.fitem.name) fn_info.generator_class.ir.methods['__mypyc_generator_helper__'] = helper_fn_ir self.functions.append(helper_fn_ir) return helper_fn_decl @@ -5342,7 +5342,7 @@ def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister: def is_builtin_ref_expr(self, expr: RefExpr) -> bool: assert expr.node, "RefExpr not resolved" - return '.' in expr.node.fullname() and expr.node.fullname().split('.')[0] == 'builtins' + return '.' in expr.node.fullname and expr.node.fullname.split('.')[0] == 'builtins' def load_global(self, expr: NameExpr) -> Value: """Loads a Python-level global. @@ -5353,7 +5353,7 @@ def load_global(self, expr: NameExpr) -> Value: # If the global is from 'builtins', turn it into a module attr load instead if self.is_builtin_ref_expr(expr): assert expr.node, "RefExpr not resolved" - return self.load_module_attr_by_fullname(expr.node.fullname(), expr.line) + return self.load_module_attr_by_fullname(expr.node.fullname, expr.line) if (self.is_native_module_ref_expr(expr) and isinstance(expr.node, TypeInfo) and not self.is_synthetic_type(expr.node)): assert expr.fullname is not None diff --git a/mypyc/ops.py b/mypyc/ops.py index f0444779f580..caab7b5b1ad7 100644 --- a/mypyc/ops.py +++ b/mypyc/ops.py @@ -522,7 +522,7 @@ def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> 'Re assert isinstance(symbol, SymbolNode) reg = Register(typ, symbol.line, is_arg=is_arg) self.symtable[symbol] = AssignmentTargetRegister(reg) - self.add(reg, symbol.name()) + self.add(reg, symbol.name) return reg def add_local_reg(self, symbol: SymbolNode, diff --git a/test-data/unit/plugins/class_callable.py b/test-data/unit/plugins/class_callable.py index 278286f7e0f8..07f75ec80ac1 100644 --- a/test-data/unit/plugins/class_callable.py +++ b/test-data/unit/plugins/class_callable.py @@ -10,12 +10,12 @@ def get_function_hook(self, fullname): def attr_hook(ctx): assert isinstance(ctx.default_return_type, Instance) - if ctx.default_return_type.type.fullname() == 'mod.Attr': + if ctx.default_return_type.type.fullname == 'mod.Attr': attr_base = ctx.default_return_type else: attr_base = None for base in ctx.default_return_type.type.bases: - if base.type.fullname() == 'mod.Attr': + if base.type.fullname == 'mod.Attr': attr_base = base break assert attr_base is not None diff --git a/test-data/unit/plugins/depshook.py b/test-data/unit/plugins/depshook.py index 99a6fd14dc02..037e2861e4dc 100644 --- a/test-data/unit/plugins/depshook.py +++ b/test-data/unit/plugins/depshook.py @@ -6,7 +6,7 @@ class DepsPlugin(Plugin): def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]: - if file.fullname() == '__main__': + if file.fullname == '__main__': return [(10, 'err', -1)] return [] diff --git a/test-data/unit/plugins/dyn_class.py b/test-data/unit/plugins/dyn_class.py index a1785c65d6c4..266284a21de3 100644 --- a/test-data/unit/plugins/dyn_class.py +++ b/test-data/unit/plugins/dyn_class.py @@ -34,7 +34,7 @@ def replace_col_hook(ctx): for sym in info.names.values(): node = sym.node if isinstance(node, Var) and isinstance(node.type, Instance): - if node.type.type.fullname() == 'mod.Column': + if node.type.type.fullname == 'mod.Column': new_sym = ctx.api.lookup_fully_qualified_or_none('mod.Instr') if new_sym: new_info = new_sym.node diff --git a/test-data/unit/plugins/method_sig_hook.py b/test-data/unit/plugins/method_sig_hook.py index 57a4da56087a..25c2842e6620 100644 --- a/test-data/unit/plugins/method_sig_hook.py +++ b/test-data/unit/plugins/method_sig_hook.py @@ -13,7 +13,7 @@ def get_method_signature_hook(self, fullname): def _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type: if isinstance(typ, Instance): - if typ.type.fullname() == 'builtins.str': + if typ.type.fullname == 'builtins.str': return api.named_generic_type('builtins.int', []) elif typ.args: return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args]) diff --git a/test-data/unit/plugins/union_method.py b/test-data/unit/plugins/union_method.py index 28b9611ab9b0..a7621553f6ad 100644 --- a/test-data/unit/plugins/union_method.py +++ b/test-data/unit/plugins/union_method.py @@ -18,7 +18,7 @@ def get_method_hook(self, fullname): def _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type: if isinstance(typ, Instance): - if typ.type.fullname() == 'builtins.str': + if typ.type.fullname == 'builtins.str': return api.named_generic_type('builtins.int', []) elif typ.args: return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args]) @@ -27,7 +27,7 @@ def _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type: def _float_to_int(api: CheckerPluginInterface, typ: Type) -> Type: if isinstance(typ, Instance): - if typ.type.fullname() == 'builtins.float': + if typ.type.fullname == 'builtins.float': return api.named_generic_type('builtins.int', []) elif typ.args: return typ.copy_modified(args=[_float_to_int(api, t) for t in typ.args])