[Python-Dev] Replacing self.__dict__ in __init__
Raymond Hettinger
raymond.hettinger at gmail.com
Sat Mar 24 12:20:22 EDT 2018
> On Mar 24, 2018, at 7:18 AM, Tin Tvrtković <tinchester at gmail.com> wrote:
>
> it's faster to do this:
>
> self.__dict__ = {'a': a, 'b': b, 'c': c}
>
> i.e. to replace the instance dictionary altogether. On PyPy, their core devs inform me this is a bad idea because the instance dictionary is special there, so we won't be doing this on PyPy.
>
> But is it safe to do on CPython?
This should work. I've seen it done in other production tools without any ill effect.
The dict can be replaced during __init__() and still get benefits of key-sharing. That benefit is lost only when the instance dict keys are modified downstream from __init__(). So, from a dict size point of view, your optimization is fine.
Still, you should look at whether this would affect static type checkers, lint tools, and other tooling.
Raymond
More information about the Python-Dev
mailing list