[Python-Dev] Replacing self.dict in init (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Sat Mar 24 23:23:55 EDT 2018
- Previous message (by thread): [Python-Dev] Replacing self.__dict__ in __init__
- Next message (by thread): [Python-Dev] Replacing self.__dict__ in __init__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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>
- Previous message (by thread): [Python-Dev] Replacing self.__dict__ in __init__
- Next message (by thread): [Python-Dev] Replacing self.__dict__ in __init__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]