[Python-Dev] reducing self.x=x; self.y=y; self.z=z boilerplate code (original) (raw)

Ralf W. Grosse-Kunstleve rwgk at cci.lbl.gov
Sat Jul 2 05:19:10 CEST 2005


Josiah Carlson wrote:

Now, don't get me wrong, definining slots can be a pain in the tookus, but with a proper metaclass, that metaclass can define the slots attribute based on the argument list for init().

There you go.

Where? The meta-class idea sounds interesting. Could you work it out?

A syntax change is wholly unnecessary.

I wonder why everybody gets so agitated about a syntax enhancement proposal. I am not proposing a syntax change!

I know enhancing the syntax is work, but shouldn't a syntax leading to less code clutter be the higher value? IMO a long-term gain counts for much more than avoiding a one-time investment implementing a useful feature. Take, for example, the syntax enhancement supporting "import foo as bar". I could just as easily write:

import foo bar = foo del foo

"A syntax change is wholly unnecessary." Why was it important enough anyway? It was a good enhancement because it is clearly more expressive and reduces clutter.

In my experience the self.x=x; self.y=y etc. problem arises much more often than the problem solved by "import foo as bar". IMO a built-in solution is much more important in practice. Why does everybody have to reinvent the adopt_init_args/initialize wheel, or have to sheepishly type self.x=x...?

I am not wedded to the .x idea, but counter-proposals should be at least approximately as powerful as what I propose.

class grouping: def init(self, x, y, z): initialize(self, locals())

The "_x" alternative looks interesting but is problematic: it doesn't have a special meaning so far, but it is also not a syntax error. You are also not getting rid of the odd (from a learner's viewpoint) requirement to stick in "locals()".

Remember where Python comes from: it goes back to a teaching language, enabling non-geeks to write programs. "initialize(self, locals())" doesn't fit that bill, especially if you have to import initialize first. In contrast

      def __init__(self, .x, .y, .z):
                   ^^^^^^^^

almost looks like ^^^^^^ self.x

and should therefore be easy to learn and remember. I'd also be happy with

      def __init__(self, self.x, self.y, self.z):

which wouldn't be too different from unpacking tuples (and is currently a syntax error). However, remember, elegance = power/length. .x above has the same power as self.x, but is shorter, therefore more elegant. :)

Hoping-that-this-leads-to-some-consensus-for-a-built-in-solution-ly yours, Ralf



More information about the Python-Dev mailing list