Skip to content

Better error messages when using operators on super() objects #150745

@johnslavik

Description

@johnslavik

Feature or enhancement

Proposal:

When users accidentally use operators or protocols on super() (e.g. subscript, context manager, arithmetic), the error messages don't hint that they need to call the dunder method explicitly. If it is fairly cheap maintenance-wise, let's consider emitting a "Did you mean?" hint which might be immensely helpful for beginners.

Current vs desired behavior

class X:
    def d(self):
        super()[0]

X().d()
- TypeError: 'super' object is not subscriptable
+ TypeError: 'super' object is not subscriptable. Did you mean 'super().__getitem__()'?

class X:
    def d(self):
        with super():
            pass

X().d()
- TypeError: 'super' object does not support the context manager protocol (missed __exit__ method)
+ TypeError: 'super' object does not support the context manager protocol (missed __exit__ method). Did you mean 'super().__enter__()' and 'super().__exit__()'?

class X:
    def d(self):
        super() + 1

X().d()
- TypeError: unsupported operand type(s) for +: 'super' and 'int'
+ TypeError: unsupported operand type(s) for +: 'super' and 'int'. Did you mean 'super().__add__()'?
Operators / protocols to cover
Syntax Dunder(s)
super()[x] __getitem__
super()[x] = v __setitem__
del super()[x] __delitem__
super() + x __add__
super() - x __sub__
super() * x __mul__
super() @ x __matmul__
super() / x __truediv__
super() // x __floordiv__
super() % x __mod__
super() ** x __pow__
super() & x __and__
super() | x __or__
super() ^ x __xor__
super() << x __lshift__
super() >> x __rshift__
~super() __invert__
-super() __neg__
+super() __pos__
abs(super()) __abs__
len(super()) __len__
iter(super()) __iter__
next(super()) __next__
super() in x __contains__
with super(): __enter__ / __exit__
await super() __await__
async for x in super(): __aiter__ / __anext__
async with super(): __aenter__ / __aexit__
super()() __call__
bool(super()) __bool__
int(super()) __int__
float(super()) __float__

Prior discussions

Adding super() support for implicit method calls was rejected in the past:

"explicit forwarding may be slightly inconvenient to type but it does add provide clarity that
the method should be applied to the next-in-mro instead of the super object itself."

See also GH-129466, GH-143817.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

Labels

interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions