Search code examples
pythonoverridingmagic-methods

How to override a magic method for the current script without a class?


How to override a magic method for the current script?

def __setattr__(name, value):
    __dict__[name] = value
    print("asd")
    if name == 'b':
        print(__dict__[name])


if __name__ == '__main__':
    a = 3
    b = 4
    b = 5

In above, for example, I expect assignments to b to call __setattr__ but they don't. What am I missing?


Solution

  • __setattr__ only applies to assignments of the form a.b = c, which translates to type(a).__setattr__(b, c). Simple name assignments are a fundamental operation of the language itself, not implemented by any magic method.

    You are just defining a module level function named __setattr__, not a magic method of any particular class.