super in Python 3 and variadic arguments

Ned Batchelder ned at nedbatchelder.com
Wed Oct 9 12:47:13 EDT 2013


On 10/9/13 11:44 AM, Marco Buttu wrote:
> Given this class:
>
> >>> class A:
> ...     def afoo(*args):
> ...         print(args)
>
> in Python 3 we can write the following class:
>
> >>> class B(A):
> ...     def bfoo(*args):
> ...         super(B, args[0]).afoo(*args[1:])
> ...
> >>> B().bfoo(1, 2, 3)
> (<__main__.B object at 0x7f5b3bde48d0>, 1, 2, 3)
>
>
> without giving arguments to super, in this way:
>
> >>> class B(A):
> ...     def bfoo(self, *args):
> ...         super().afoo(*args)
> ...
> >>> B().bfoo(1, 2, 3)
> (<__main__.B object at 0x7f5b3bdea0d0>, 1, 2, 3)
>
> But it does not work in this case:
>
> >>> class B(A):
> ...     def bfoo(*args):
> ...         super().afoo(*args[1:])
> ...
> >>> B().bfoo(1, 2, 3)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in bfoo
> RuntimeError: super(): no arguments
>
> How come?

The no-args super() call inspects the calling environment to determine 
the class and self.  "self" is the first local name stored in 
frame.f_code.co_localsplus, but *args doesn't put "args" into that entry 
of the code object.  Basically, super() is looking for the first regular 
argument in the function.

--Ned.





More information about the Python-list mailing list