class Works(type):
def __new__(cls, *args, **kwargs):
print([cls,args]) # outputs [<class '__main__.Works'>, ()]
return super().__new__(cls, args)
class DoesNotWork(type):
def __new__(*args, **kwargs):
print([args[0],args[:0]]) # outputs [<class '__main__.doesNotWork'>, ()]
return super().__new__(args[0], args[:0])
Works() # is fine
DoesNotWork() # gets "RuntimeError: super(): no arguments"
As far as I can see, in both cases super._new__ receives the class literal as first argument, and an empty tuple as the 2nd.
So why does one give an error and the other not?
The zero-argument form of super
requires that the method containing it have an explicit (i.e., non-varargs) first argument. This is suggested by an older version of the docs (emphasis added):
The zero argument form automatically searches the stack frame for the class (
__class__
) and the first argument.
For some reason this note was removed in later versions of the docs. (It might be worth raising a doc bug, because the docs are quite vague about how zero-argument super
works and what is required for it to work.)
See also this Python bug report (which is unresolved, and not clearly accepted as even a bug). The upshot is that zero-argument super
is magic, and that magic fails in some cases. As suggested in the bug report, if you want to accept only varargs, you'll need to use the explicit two-argument form of super
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With