3 ms·
Is there a difference between global setattr(object, v) and object.__setattr__(v)? I've seen setattr() in the wild all over but I've never encountered the dunde
by eyegor 2y ago
Is there a difference between global setattr(object, v) and object.__setattr__(v)? I've seen setattr() in the wild all over but I've never encountered the dunder one.
- notpushkin 2y agoNote that `object` here is not a placeholder variable but actually refers to the global object type (basically a superclass of pretty much every other type in Python). It allows you to bypass the classes’ __setattr__ and set the value regardless (the setattr() function can’t do that): In [1]: from dataclasses import dataclass In [2]: @dataclass(frozen=True) ...: class Foo: ...: a: int ...: In [3]: foo = Foo(5) In [4]: foo.a = 10 FrozenInstanceError: cannot assign to field 'a' In [5]: setattr(foo, "a", 10) FrozenInstanceError: cannot assign to field 'a' In [6]: object.__setattr__(foo, "a", 10) In [7]: foo.a Out[7]: 10