Skip to content

Commit

Permalink
Make all names and fullnames into properties (#7829)
Browse files Browse the repository at this point in the history
SymbolNode and FuncBase had name and fullname as methods while everything else has them as attributes or properties. Turn them into properties.

Fixes #7640.

This was done with `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`.
  • Loading branch information
msullivan committed Nov 13, 2019
1 parent d5fcc72 commit e97377c
Show file tree
Hide file tree
Showing 61 changed files with 578 additions and 554 deletions.
30 changes: 17 additions & 13 deletions misc/proper_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,27 @@ 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',
'mypy.types.ProperType',
'mypy.types.TypeAliasType'):
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',
'mypy.types.TypeVarType',
'mypy.types.RawExpressionType',
'mypy.types.EllipsisType',
'mypy.types.StarType',
'mypy.types.TypeList',
'mypy.types.CallableArgument',
'mypy.types.PartialType',
'mypy.types.ErasedType'):
if right.type_object().fullname in (
'mypy.types.UnboundType',
'mypy.types.TypeVarType',
'mypy.types.RawExpressionType',
'mypy.types.EllipsisType',
'mypy.types.StarType',
'mypy.types.TypeList',
'mypy.types.CallableArgument',
'mypy.types.PartialType',
'mypy.types.ErasedType'
):
# Special case: these are not valid targets for a type alias and thus safe.
# TODO: introduce a SyntheticType base to simplify this?
return True
Expand Down
4 changes: 2 additions & 2 deletions mypy/argmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions mypy/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
136 changes: 69 additions & 67 deletions mypy/checker.py

Large diffs are not rendered by default.

54 changes: 27 additions & 27 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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])
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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')):
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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)):
Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand Down
18 changes: 9 additions & 9 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand All @@ -384,15 +384,15 @@ 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),
result, mx.context, mx.chk))
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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit e97377c

Please sign in to comment.