satwikkansal / wtfpython

What the f*ck Python? 😱
Do What The F*ck You Want To Public License
35.51k stars 2.65k forks source link

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

Open david-shiko opened 1 year ago

david-shiko commented 1 year ago

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