[Python-Dev] reducing self.x=x; self.y=y; self.z=z boilerplate code

Ralf W. Grosse-Kunstleve rwgk at cci.lbl.gov
Sat Jul 2 01:59:49 CEST 2005


I am happy to see that others agree we need something better
than self.x=x; self.y=y; self.z=z.

Phillip J. Eby wrote:
>    class grouping:
>        def __init__(self, x, y, z):
>            initialize(self, locals())

Been there (older code):

  http://phenix-online.org/cctbx_sources/scitbx/scitbx/python_utils/misc.py

I don't like it because

  - I do have to remember how to import adopt_init_args/initialize.

  - I also have to remember the locals() part (unpythonic
    boilerplate again).

  - I get both self.x and x. This lead to subtle bugs a few times when
    I accidentally assigned to x instead of self.x or vice versa in the
    wrong place).

  - It is sure to be less efficient than the .x support I propose.

I'd be happy if

  - adopt_init_args/initialize became a (efficiently implemented)
    Python built-in.

  - and the locals() part is not needed.

However, IMO the .x solution is still far better because I often
want to do something like this:

  class grouping:

    def __init__(self, .keep_this, .and_this, but_not_this, .but_this_again):
      pass

With the adopt_init_args/initialize solution you'd have to write:

  class grouping:

    def __init__(self, keep_this, and_this, but_not_this, but_this_again):
      initialize(self, locals(), exclude=["but_not_this"])

Unpythonic boilerplate again (the but_not_this duplication).

Cheers,
        Ralf


More information about the Python-Dev mailing list