4

I have two almost identical implementations of the __new__ method for a class.

However, in one case, there is an error message.

In the other case, it works fine.

class Klass1():
    # causes RuntimeError: super(): no arguments
    def __new__(*args):
        obj = super().__new__(args[0])
        return obj

class Klass2():
    # This code here works just fine   
    def __new__(cls, *args):
        obj = super().__new__(cls)
        return obj

instance1 = Klass1()
instance2 = Klass2()

Why would it matter whether we write cls or args[0]?

What is causing the RuntimeError exception to be raised?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • 6
    The zero-argument form of `super` requires a tiny bit of compiler magic which is, apparently, broken by a function declaration that doesn't have at least one explicit parameter. – chepner Mar 15 '23 at 21:06
  • 3
    BTW, that magic is quoted in an answer over at https://stackoverflow.com/a/13128705/14122 (albeit an older version from Python 3.3) – Charles Duffy Mar 15 '23 at 21:06
  • 2
    `super` does not have default parameter values in the usual sense (e.g., `def super(x=3, y=5): ...`, because the values used are determined when `super` is *called*, not when `super` is defined. (Also, `super` is a type, not a function, but the idea is the same.) – chepner Mar 15 '23 at 21:07

0 Answers0