wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

New snippet. "super" is true "super" and not restricted by the rules of python

Open david-shiko opened this issue 2 years ago • 0 comments

We are all used to using:

class Foo:
    pass

class Bar(Foo):
    def __init__(self):
        super().__init__()

But once, during coding, I just wondered, how does super know about the Bar parent class at all? Does str().__some_method__ also know about the Bar class around?

Check this class

class SuperMystery:
    def nothing_special(self):
        print('__class__' in locals())  # False 

    def surprise(self):
        super  # senseless expression, do nothing  
        print('__class__' in locals())  # True 

    @staticmethod
    def even_more():  # Just as function, no reference to an instance/class
        super  # Just a word, senseless expression , do nothing
        print('__class__' in locals())  # True 
        
super_mystery = SuperMystery()
super_mystery.nothing_special()
super_mystery.surprise()
super_mystery.even_more()

Curious? It's just a Python hack that violates regular rules!

Explanation: When the Python compiler meets super in the method, it will insert some special attributes into the method and its namespace. super will fool the compiler into creating a __class__ cell, even if it's senseless and does nothing.

See: https://stackoverflow.com/a/45522873/11277611 Docs about super https://docs.python.org/3/library/functions.html#super

david-shiko avatar Jan 09 '23 12:01 david-shiko