I was just reading post How can I assign a new class attribute via __dict__ in python? and there was one comment from @bruno desthuilliers saying:
One shouldn't directly call magic methods - they are here as implementation of operators or generic functions. In this case, the idiomatic solution is to use
setattr(obj, name, value)
.
The case of setattr seems out of scope of his own comment: not an operator, not really an implementation of generic function either.
Can someone explain the comment? Why should I prefer one over the other?
In which case is it preferable to use obj.__setattr__(name, value)
?
You should always use setattr()
, the commenter is quite correct.
Not all types implement __setattr__
, for example, yet setattr()
will work correctly if the type allows the attribute to be set.
Double-underscore methods are hooks, there to enable your custom classes to implement custom behaviour. The Python APIs will use these hooks if present, to fall back to the default behaviour if the hook is missing. By bypassing the API, you are burdening yourself with having to implement the fallback in your own code.
You only ever need to call __setattr__
directly when implementing a subclass, and then preferably through the super()
call:
def Foo(Bar):
def __setattr__(self, attr, value):
# do something with attr and value
super(Foo, self).__setattr__(attr, value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With