[Python-Dev] Replacing self.__dict__ in __init__
Nick Coghlan
ncoghlan at gmail.com
Sat Mar 24 23:23:55 EDT 2018
On 25 March 2018 at 00:18, Tin Tvrtković <tinchester at gmail.com> wrote:
> But is it safe to do on CPython?
>
That depends on what you mean by "safe" :)
It won't crash, but it will lose any existing entries that a metaclass,
subclass, or __new__ method implementation might have added to the instance
dictionary before calling the __init__ method. That can be OK in a tightly
controlled application specific class hierarchy, but it would be
questionable in a general purpose utility library that may be combined with
arbitrary other types.
As Kirill suggests, `self.__dict__.update(new_attrs)` is likely to be
faster than repeated assignment statements, without the potentially odd
interactions with other instance initialisation code.
It should also be explicitly safe to do in the case of "type(self) is
__class__ and not self.__dict__", which would let you speed up the common
case of direct instantiation, while falling back to the update based
approach when combined with other classes at runtime.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180325/c3004008/attachment.html>
More information about the Python-Dev
mailing list