Skip to content

Commit 20b4628

Browse files
authored
Fix crash when super outside of method is called (#9173)
* Fix crash when super outside of method is called * Change error message * empty
1 parent a9c9a41 commit 20b4628

File tree

4 files changed

+21
-0
lines changed

4 files changed

+21
-0
lines changed

mypy/checkexpr.py

+4
Original file line numberDiff line numberDiff line change
@@ -3464,6 +3464,10 @@ def visit_super_expr(self, e: SuperExpr) -> Type:
34643464
self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e)
34653465
return AnyType(TypeOfAny.from_error)
34663466

3467+
if len(mro) == index + 1:
3468+
self.chk.fail(message_registry.TARGET_CLASS_HAS_NO_BASE_CLASS, e)
3469+
return AnyType(TypeOfAny.from_error)
3470+
34673471
for base in mro[index+1:]:
34683472
if e.name in base.names or base == mro[-1]:
34693473
if e.info and e.info.fallback_to_any and base == mro[-1]:

mypy/message_registry.py

+1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
SUPER_POSITIONAL_ARGS_REQUIRED = '"super" only accepts positional arguments' # type: Final
110110
SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1 = \
111111
'Argument 2 for "super" not an instance of argument 1' # type: Final
112+
TARGET_CLASS_HAS_NO_BASE_CLASS = 'Target class has no base class' # type: Final
112113
SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED = \
113114
'super() outside of a method is not supported' # type: Final
114115
SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED = \

test-data/unit/check-super.test

+14
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,20 @@ class B(A):
280280
class C:
281281
a = super().whatever # E: super() outside of a method is not supported
282282

283+
[case testSuperWithObjectClassAsFirstArgument]
284+
class A:
285+
def f(self) -> None:
286+
super(object, self).f() # E: Target class has no base class
287+
288+
[case testSuperWithTypeVarAsFirstArgument]
289+
from typing import TypeVar
290+
291+
T = TypeVar('T')
292+
293+
def f(obj: T) -> None:
294+
super(obj.__class__, obj).f() # E: Target class has no base class
295+
[builtins fixtures/__new__.pyi]
296+
283297
[case testSuperWithSingleArgument]
284298
class B:
285299
def f(self) -> None: pass

test-data/unit/fixtures/__new__.pyi

+2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ from typing import Any
55
class object:
66
def __init__(self) -> None: pass
77

8+
__class__ = object
9+
810
def __new__(cls) -> Any: pass
911

1012
class type:

0 commit comments

Comments
 (0)