8000 Add more details for "Invalid type" errors by ilevkivskyi · Pull Request #7166 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Add more details for "Invalid type" errors #7166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 8, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Tweak some error messages
  • Loading branch information
ilevkivskyi committed Jul 6, 2019
commit 1a704cb6ffdddad871a5b9473771293ecf078f3f
30 changes: 26 additions & 4 deletions mypy/newsemanal/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1348,6 +1348,18 @@ def make_empty_type_info(self, defn: ClassDef) -> TypeInfo:
info.set_line(defn)
return info

def get_name_repr_of_expr(self, expr: Expression) -> Optional[str]:
"""Try finding a short simplified textual representation of a base class expression."""
if isinstance(expr, NameExpr):
return expr.name
if isinstance(expr, MemberExpr):
return get_member_expr_fullname(expr)
if isinstance(expr, IndexExpr):
return self.get_name_repr_of_expr(expr.base)
if isinstance(expr, CallExpr):
return self.get_name_repr_of_expr(expr.callee)
return None

def analyze_base_classes(
self,
base_type_exprs: List[Expression]) -> Optional[Tuple[List[Tuple[Type, Expression]],
Expand All @@ -1371,7 +1383,13 @@ def analyze_base_classes(
try:
base = self.expr_to_analyzed_type(base_expr, allow_placeholder=True)
except TypeTranslationError:
self.fail('Invalid base class', base_expr)
msg = 'Invalid base class'
name = self.get_name_repr_of_expr(base_expr)
if name:
msg += ' "{}"'.format(name)
if isinstance(base_expr, CallExpr):
msg += ': Unsupported dynamic base class'
self.fail(msg, base_expr)
is_error = True
continue
if base is None:
Expand Down Expand Up @@ -1409,7 +1427,11 @@ def configure_base_classes(self,
self.fail(msg, base_expr)
info.fallback_to_any = True
else:
self.fail('Invalid base class', base_expr)
msg = 'Invalid base class'
name = self.get_name_repr_of_expr(base_expr)
if name:
msg += ' "{}"'.format(name)
self.fail(msg, base_expr)
info.fallback_to_any = True
if self.options.disallow_any_unimported and has_any_from_unimported_type(base):
if isinstance(base_expr, (NameExpr, MemberExpr)):
Expand All @@ -1421,7 +1443,7 @@ def configure_base_classes(self,
context=base_expr)

# Add 'object' as implicit base if there is no other base class.
if (not base_types and defn.fullname != 'builtins.object'):
if not base_types and defn.fullname != 'builtins.object':
base_types.append(self.object_type())

info.bases = base_types
Expand Down Expand Up @@ -3186,7 +3208,7 @@ def visit_with_stmt(self, s: WithStmt) -> None:
actual_targets = [t for t in s.target if t is not None]
if len(actual_targets) == 0:
# We have a type for no targets
self.fail('Invalid type comment', s)
self.fail('Invalid type comment: `with` statement has no targets', s)
elif len(actual_targets) == 1:
# We have one target and one type
types = [s.unanalyzed_type]
Expand Down
20 changes: 15 additions & 5 deletions mypy/newsemanal/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
TypeInfo, Context, SymbolTableNode, Var, Expression,
nongen_builtins, check_arg_names, check_arg_kinds, ARG_POS, ARG_NAMED,
ARG_OPT, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, TypeVarExpr,
TypeAlias, PlaceholderNode
TypeAlias, PlaceholderNode, SYMBOL_FUNCBASE_TYPES, Decorator, MypyFile
)
from mypy.typetraverser import TypeTraverserVisitor
from mypy.tvar_scope import TypeVarScope
Expand Down Expand Up @@ -72,7 +72,7 @@ def analyze_type_alias(node: Expression,
try:
type = expr_to_unanalyzed_type(node)
except TypeTranslationError:
api.fail('Invalid type alias', node)
api.fail('Invalid type alias: cannot interpret right hand side as a type', node)
return None
analyzer = TypeAnalyser(api, tvar_scope, plugin, options, is_typeshed_stub,
allow_unnormalized=allow_unnormalized, defining_alias=True,
Expand Down Expand Up @@ -401,7 +401,17 @@ def analyze_unbound_type_without_type_info(self, t: UnboundType, sym: SymbolTabl
# None of the above options worked. We parse the args (if there are any)
# to make sure there are no remaining semanal-only types, then give up.
t = t.copy_modified(args=self.anal_array(t.args))
self.fail('Invalid type "{}"'.format(name), t)
if isinstance(sym.node, Var):
reason = 'Cannot use variable as type' # TODO: add link to alias docs, see #3494
elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)):
reason = 'Cannot use function as type, use Callable[...] or a protocol instead'
elif isinstance(sym.node, MypyFile):
reason = 'Module cannot be used as type' # TODO: suggest a protocol when supported
elif unbound_tvar:
reason = 'Can only use bound type variables as type'
else:
reason = 'Cannot interpret reference as a type'
self.fail('Invalid type "{}": {}'.format(name, reason), t)

# TODO: Would it be better to always return Any instead of UnboundType
# in case of an error? On one hand, UnboundType has a name so error messages
Expand All @@ -422,11 +432,11 @@ def visit_deleted_type(self, t: DeletedType) -> Type:
return t

def visit_type_list(self, t: TypeList) -> Type:
self.fail('Invalid type', t)
self.fail('Invalid type AAAA', t)
return AnyType(TypeOfAny.from_error)

def visit_callable_argument(self, t: CallableArgument) -> Type:
self.fail('Invalid type', t)
self.fail('Invalid type BBBB', t)
return AnyType(TypeOfAny.from_error)

def visit_instance(self, t: Instance) -> Type:
Expand Down
0