4

UPDATE: please see my comment below. I don't see how the other article answers the very specific question I am asking. The closest it comes is when it says if I have an unrelated variables named super, things will work. But that a) doesn't match my situation since I do not have an unrelated variable named super, and b) doesn't explain how an unrelated super variable would cause the code to succeed, anyway. I want to know about an unrelated reference to the normal (and therefore related) super, and I want to know why/how it works.

I was looking at Why is Python 3.x's super() magic? and decided to fiddle around with the code. As I was doing so, I found that the call super_().x() in B.x() (in the code below) succeeds if the expression super is executed, but fails if it does not. At least some other references to super have the same effect - for example, I found the same results using z = super or print(id(super)).

Why does the call to B.x() succeed when this seemingly-meaningless reference to super is included?

super_ = super

class A(object):
    def x(self):
        print("Hello, world.")

class B(A):
    def x(self):
        # if this evaluation is present, the call to super_() succeeds.
        # if this evaluation is not present, the call to super_() fails.
        print(id(super))

        super_().x()

if __name__ == '__main__':
    B().x()
chris
  • 588
  • 5
  • 16
  • 5
    The first answer in the question you linked explains this behavior... – Aran-Fey Feb 08 '18 at 17:49
  • 2
    _"My patch uses an intermediate solution: it assumes you need `__class__` whenever you use a variable named 'super'. Thus, if you (globally) rename super to supper and use supper but not super, it won't work without arguments (but it will still work if you pass it either `__class__` or the actual class object); if you have an unrelated variable named super, things will work but the method will use the slightly slower call path used for cell variables."_ – Aran-Fey Feb 08 '18 at 17:50
  • How is this a duplicate? That article gives an example of how this behavior can throw an exception. My question is how adding a seemingly-unrelated line of coffee makes the exception go away. I don't see that addressed in the other article at all. If it is, I might need some additional explanation. – chris Feb 10 '18 at 18:09
  • ... unrelated line of *code... – chris Feb 10 '18 at 18:23
  • 3
    My answer there explains that using the name `super` or the name `__class__` attaches a closure cell to the function that the `super()` function needs to have access to. If you do not use either name in a method, then the cell is not created, and calling the `super()` function (via the `super_` name) fails. – Martijn Pieters Feb 10 '18 at 18:29
  • @MartijnPieters' comment has finally gotten through my thick skull. Thank you all for your patience and help. – chris Feb 11 '18 at 02:12

0 Answers0