[Python-Dev] Replacing self.dict in init (original) (raw)

Tin Tvrtković tinchester at gmail.com
Sat Mar 24 10🔞14 EDT 2018


Hi Python-dev,

I'm one of the core attrs contributors, and I'm contemplating applying an optimization to our generated __init__s. Before someone warns me python-dev is for the development of the language itself, there are two reasons I'm posting this here:

  1. it's a very low level question that I'd really like the input of the core devs on, and
  2. maybe this will find its way into dataclasses if it works out.

I've found that, if a class has more than one attribute, instead of creating an init like this:

self.a = a
self.b = b
self.c = c

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?

To make the question simpler, disregard the possibility of custom setters on the attributes.

Thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20180324/b1f97560/attachment.html>



More information about the Python-Dev mailing list