Skip to content

Commit bd6ae1f

Browse files
committed
Make error message mention specific class
This commit modifies the error message to try and report the specific name of the invalid class whenever possible.
1 parent 1adc40c commit bd6ae1f

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

mypy/semanal.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,11 @@ def analyze_base_classes(self, defn: ClassDef) -> None:
770770
base_types.append(base)
771771
elif isinstance(base, AnyType):
772772
if self.options.disallow_subclassing_any:
773-
self.fail("Class cannot subclass value of type 'Any'", base_expr)
773+
if isinstance(base_expr, RefExpr):
774+
msg = "Class cannot subclass '{}' (has type 'Any')".format(base_expr.name)
775+
else:
776+
msg = "Class cannot subclass value of type 'Any'"
777+
self.fail(msg, base_expr)
774778
info.fallback_to_any = True
775779
else:
776780
self.fail('Invalid base class', base_expr)

test-data/unit/check-flags.test

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ main:2: error: Function is missing a type annotation
4141
# flags: --disallow-subclassing-any
4242
from typing import Any
4343
FakeClass = None # type: Any
44-
class Foo(FakeClass): pass # E: Class cannot subclass value of type 'Any'
44+
class Foo(FakeClass): pass # E: Class cannot subclass 'FakeClass' (has type 'Any')
4545
[out]
4646

4747
[case testSubclassingAnyMultipleBaseClasses]
4848
# flags: --disallow-subclassing-any
4949
from typing import Any
5050
FakeClass = None # type: Any
5151
class ActualClass: pass
52-
class Foo(ActualClass, FakeClass): pass # E: Class cannot subclass value of type 'Any'
52+
class Foo(ActualClass, FakeClass): pass # E: Class cannot subclass 'FakeClass' (has type 'Any')
5353
[out]
5454

5555
[case testSubclassingAnySilentImports]
@@ -64,4 +64,18 @@ class Foo(BaseClass): pass
6464
class BaseClass: pass
6565

6666
[out]
67-
tmp/main.py:2: error: Class cannot subclass value of type 'Any'
67+
tmp/main.py:2: error: Class cannot subclass 'BaseClass' (has type 'Any')
68+
69+
[case testSubclassingAnySilentImports2]
70+
# flags: --disallow-subclassing-any --silent-imports
71+
# cmd: mypy -m main
72+
73+
[file main.py]
74+
import ignored_module
75+
class Foo(ignored_module.BaseClass): pass
76+
77+
[file ignored_module.py]
78+
class BaseClass: pass
79+
80+
[out]
81+
tmp/main.py:2: error: Class cannot subclass 'BaseClass' (has type 'Any')

0 commit comments

Comments
 (0)