py3k feature proposal: field auto-assignment in constructors

MRAB google at mrabarnett.plus.com
Sun Jan 27 20:28:33 EST 2008


On Jan 28, 1:01 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Mon, 28 Jan 2008 00:39:02 +0100, Wildemar Wildenburger wrote:
> > Dustan wrote:
> >>> Well, you save one or two lines per class.  Not enough in my opinion.
>
> >> Are you referring to the alternate syntax or to the decorator? Either
> >> way, you could be saving 4 or 5 or more lines, if you have enough
> >> arguments.
>
> > OK, but then again, every decent IDE should give you the tools to write
> > an automation for that. Not that I don't like the idea of
> > auto-assignment, but, you know ...
>
> You know, not everybody uses a "decent IDE", by choice or necessity, and
> even if they did, having what is essentially a macro to type for you
> doesn't solve the essential problem that you're writing the same thing
> THREE TIMES instead of once. And then you have to keep it all in sync
> through who knows how many code revisions and refactorings.
>
> class Parrot(object):  # after many revisions...
>     def __init__(self, genus, species, variety, name, age, colours,
>         wingspan, beaksize, healthstate, language, vocabulary):
>         self.wingspan = wingspan
>         self.beaksize = beaksize
>         self.name = name
>         self.age = age
>         self.binomial_name = (genus, species)
>         self.breed = variety
>         self.colour = colour
>         self.language = language
>         self.state = get_state(healthstate)
>         self.words = vocabulary
>         self.colors = colours
>
> What IDE will spot the error(s) in the above?
>
> Here's another version, assuming syntax support for auto-assignment for
> names starting with an ampersand:
>
> class Parrot(object):  # after many revisions...
>     def __init__(self, genus, species, variety, &name, &age, &colours,
>         &wingspan, &beaksize, healthstate, &language, vocabulary):
>         self.binomial_name = (genus, species)
>         self.breed = variety
>         self.state = get_state(healthstate)
>         self.words = vocabulary
>
> See how much easier it is to keep the attributes synced with the
> arguments? Don't Repeat Yourself in action.
>
> I think the biggest minus on this proposal is that it creates new syntax
> that is only meaningful in the __init__ method of a class. "Special cases
> aren't special enough to break the rules." I'd vote for it, but
> conditionally. What should this do?
>
> def foo(x, y, &z):
>     pass
>
> Create foo.z perhaps?
>
Well, if:

def __init__(self, &foo):
    pass

does:

def __init__(self, foo):
    self.foo = foo

then:

def foo(x, y, &z):
    pass

does:

def foo(x, y, &z):
    x.z = z

Don't think that's useful, though...



More information about the Python-list mailing list