(original) (raw)
On 25 March 2018 at 00:18, Tin Tvrtković <tinchester@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@gmail.com | Brisbane, Australia