Gmail Calendar Documents Reader Web more »
Recently Visited Groups | Help | Sign in
Google Groups Home
py3k feature proposal: field auto-assignment in constructors
There are currently too many topics in this group that display first. To make this topic appear first, remove this option from another topic.
There was an error processing your request. Please try again.
flag
  Messages 1 - 25 of 46 - Collapse all  -  Translate all to Translated (View all originals)   Newer >
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
coldpizza  
View profile  
 More options Jan 27 2008, 12:06 pm
Newsgroups: comp.lang.python
From: coldpizza <vri...@gmail.com>
Date: Sun, 27 Jan 2008 09:06:09 -0800 (PST)
Local: Sun, Jan 27 2008 12:06 pm
Subject: py3k feature proposal: field auto-assignment in constructors
There is a pattern that occurs fairly often in constructors in Python
and other OOP languages.

Let's take an example:

class Server(object):
    def __init__(self, host, port, protocol, bufsize, timeout):
        self.host = host
        self.port = port
        self.protocol = protocol
        self.bufsize = bufsize
        self.maxthreads = maxthreads
        self.timeout = timeout

Imho, in the class above the assignment to instance fields does not
contain much programming logic and therefore can be safely 'abstracted
away' by the language itself with a syntax which would look something
like this:

class Server(object):
    def __init__(self, @host, @port, @protocol, @bufsize, @timeout):
        pass

This would be equivalent to the first example above, yet it does not
obfuscate the code in any way. Or does it? It does look much cleaner
to me.

Of course, the ampersand is just an arbitrary choice and might have
bad connotations for those who read it as 'take address of' but @ has
some allusion to delegates which maybe is ok.

I am not an experienced programmer and I am not sure if this is
necessarily a good idea, so I wanted to get some feedback from more
experienced Pythonistas before submitting it elsewhere.


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
André  
View profile  
 More options Jan 27 2008, 12:46 pm
Newsgroups: comp.lang.python
From: "André" <andre.robe...@gmail.com>
Date: Sun, 27 Jan 2008 09:46:29 -0800 (PST)
Local: Sun, Jan 27 2008 12:46 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 1:06 pm, coldpizza <vri...@gmail.com> wrote:

If you search on this list, you will find that there has been *many*
proposals to remove self (which, I realize is slightly different than
what yo propose) and that the main argument can be summarized as
"Explicit is better than implicit."

Personally, I like the idea you suggest, with the modification that I
would use "." instead of "@", as in

class Server(object):
    def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
        pass

André


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Wildemar Wildenburger  
View profile  
 More options Jan 27 2008, 1:16 pm
Newsgroups: comp.lang.python
From: Wildemar Wildenburger <lasses_w...@klapptsowieso.net>
Date: Sun, 27 Jan 2008 19:16:25 +0100
Local: Sun, Jan 27 2008 1:16 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
André wrote:
> Personally, I like the idea you suggest, with the modification that I
> would use "." instead of "@", as in

> class Server(object):
>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
>         pass

I like :)

However, you can probably cook up a decorator for this (not certain, I'm
not a decorator Guru), which is not that much worse.

Still, I'd support that syntax (and the general idea.).

/W


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Diez B. Roggisch  
View profile  
 More options Jan 27 2008, 1:32 pm
Newsgroups: comp.lang.python
From: "Diez B. Roggisch" <de...@nospam.web.de>
Date: Sun, 27 Jan 2008 19:32:08 +0100
Local: Sun, Jan 27 2008 1:32 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
Wildemar Wildenburger schrieb:

> André wrote:
>> Personally, I like the idea you suggest, with the modification that I
>> would use "." instead of "@", as in

>> class Server(object):
>>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
>>         pass

> I like :)

> However, you can probably cook up a decorator for this (not certain, I'm
> not a decorator Guru), which is not that much worse.

> Still, I'd support that syntax (and the general idea.).

Just for the fun of it, I implemented a decorator:

from functools import *
from inspect import *

def autoassign(_init_):
     @wraps(_init_)
     def _autoassign(self, *args, **kwargs):
         argnames, _, _, _ = getargspec(_init_)
         for name, value in zip(argnames[1:], args):
             setattr(self, name, value)
         _init_(self, *args, **kwargs)

     return _autoassign

class Test(object):
     @autoassign
     def __init__(self, foo, bar):
         pass

t = Test(10, 20)

print t.bar

Diez


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Torsten Bronger  
View profile  
 More options Jan 27 2008, 1:41 pm
Newsgroups: comp.lang.python
From: Torsten Bronger <bron...@physik.rwth-aachen.de>
Date: Sun, 27 Jan 2008 19:41:07 +0100
Local: Sun, Jan 27 2008 1:41 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
Hallöchen!

Well, you save one or two lines per class.  Not enough in my
opinion.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bron...@jabber.org
               (See http://ime.webhop.org for further contact info.)


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Wildemar Wildenburger  
View profile  
 More options Jan 27 2008, 1:48 pm
Newsgroups: comp.lang.python
From: Wildemar Wildenburger <lasses_w...@klapptsowieso.net>
Date: Sun, 27 Jan 2008 19:48:15 +0100
Local: Sun, Jan 27 2008 1:48 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

This is neat. :) Could that maybe be extended to only assign selected
args to the instance and let others pass unchanged. So that, for instance:

@autoassign("foo", "bar")
def __init__(self, foo, bar, baz):
     super(baz)

?W


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
André  
View profile  
 More options Jan 27 2008, 2:00 pm
Newsgroups: comp.lang.python
From: "André" <andre.robe...@gmail.com>
Date: Sun, 27 Jan 2008 11:00:12 -0800 (PST)
Local: Sun, Jan 27 2008 2:00 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 2:48 pm, Wildemar Wildenburger

If one goes back to the original idea instead, the decision of using
automatic assignment should depend on the signature of the __init__
function.  Here's an implementation (using "_" instead of "." as it
would lead to a syntax error):

from functools import *
from inspect import *

def autoassign(_init_):
     @wraps(_init_)
     def _autoassign(self, *args, **kwargs):
         argnames, _, _, _ = getargspec(_init_)
         for name, value in zip(argnames[1:], args):
             if name.startswith("_"):
                 setattr(self, name[1:], value)
         _init_(self, *args, **kwargs)

     return _autoassign

class Test(object):
     @autoassign
     def __init__(self, _foo, _bar, baz):
         print 'baz =', baz

t = Test(1, 2, 3)
print t.foo
print t.bar
print t.baz

#== the output is

baz = 3
1
2
Traceback (most recent call last):
File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line
24, in exec_code
    exec code in local_dict
  File "User's code", line 23, in <module>
AttributeError: 'Test' object has no attribute 'baz'

#======
André


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Dustan  
View profile  
 More options Jan 27 2008, 6:26 pm
Newsgroups: comp.lang.python
From: Dustan <DustanGro...@gmail.com>
Date: Sun, 27 Jan 2008 15:26:19 -0800 (PST)
Local: Sun, Jan 27 2008 6:26 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 12:41 pm, Torsten Bronger <bron...@physik.rwth-aachen.de>
wrote:

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.

    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Wildemar Wildenburger  
View profile  
 More options Jan 27 2008, 6:39 pm
Newsgroups: comp.lang.python
From: Wildemar Wildenburger <lasses_w...@klapptsowieso.net>
Date: Mon, 28 Jan 2008 00:39:02 +0100
Local: Sun, Jan 27 2008 6:39 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

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 ...

/W


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Terry Reedy  
View profile  
 More options Jan 27 2008, 7:13 pm
Newsgroups: comp.lang.python
From: "Terry Reedy" <tjre...@udel.edu>
Date: Sun, 27 Jan 2008 19:13:27 -0500
Local: Sun, Jan 27 2008 7:13 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

"André" <andre.robe...@gmail.com> wrote in message

news:7dcc86da-6ed7-48ec-9a9e-ada5574ae06e@v17g2000hsa.googlegroups.com...
If one goes back to the original idea instead, the decision of using
automatic assignment should depend on the signature of the __init__
function.  Here's an implementation (using "_" instead of "." as it
would lead to a syntax error):

from functools import *
from inspect import *

def autoassign(_init_):
     @wraps(_init_)
     def _autoassign(self, *args, **kwargs):
         argnames, _, _, _ = getargspec(_init_)
         for name, value in zip(argnames[1:], args):
             if name.startswith("_"):
                 setattr(self, name[1:], value)
         _init_(self, *args, **kwargs)

     return _autoassign

class Test(object):
     @autoassign
     def __init__(self, _foo, _bar, baz):
         print 'baz =', baz

t = Test(1, 2, 3)
print t.foo
print t.bar
print t.baz

#== the output is

baz = 3
1
2
Traceback (most recent call last):
File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line
24, in exec_code
    exec code in local_dict
  File "User's code", line 23, in <module>
AttributeError: 'Test' object has no attribute 'baz'
=================================

I think this version, with this name convention, is nice enough to possibly
go in the stdlib if there were an appropriate place for it.  Not sure where
though.  If there were a classtools module....

tjr


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Ben Finney  
View profile  
 More options Jan 27 2008, 7:49 pm
Newsgroups: comp.lang.python
From: Ben Finney <bignose+hates-s...@benfinney.id.au>
Date: Mon, 28 Jan 2008 11:49:30 +1100
Local: Sun, Jan 27 2008 7:49 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

"André" <andre.robe...@gmail.com> writes:
> Personally, I like the idea you suggest, with the modification that I
> would use "." instead of "@", as in

> class Server(object):
>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
>         pass

-1.

That leading dot is too easy to miss when looking over the code.

--
 \        "Intellectual property is to the 21st century what the slave |
  `\                              trade was to the 16th." —David Mertz |
_o__)                                                                  |
Ben Finney


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steven D'Aprano  
View profile  
 More options Jan 27 2008, 8:01 pm
Newsgroups: comp.lang.python
From: Steven D'Aprano <st...@REMOVE-THIS-cybersource.com.au>
Date: Mon, 28 Jan 2008 01:01:31 -0000
Local: Sun, Jan 27 2008 8:01 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

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?

--
Steven


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Wildemar Wildenburger  
View profile  
 More options Jan 27 2008, 8:13 pm
Newsgroups: comp.lang.python
From: Wildemar Wildenburger <lasses_w...@klapptsowieso.net>
Date: Mon, 28 Jan 2008 02:13:07 +0100
Local: Sun, Jan 27 2008 8:13 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

Ben Finney wrote:
> "André" <andre.robe...@gmail.com> writes:

>> Personally, I like the idea you suggest, with the modification that I
>> would use "." instead of "@", as in

>> class Server(object):
>>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
>>         pass

> -1.

> That leading dot is too easy to miss when looking over the code.

class Server(object):
     def __init__(self, self.host, self.port,
                  self.protocol, self.bufsize, self.timeout):
         pass

?

/W


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Paul McGuire  
View profile  
 More options Jan 27 2008, 8:17 pm
Newsgroups: comp.lang.python
From: Paul McGuire <pt...@austin.rr.com>
Date: Sun, 27 Jan 2008 17:17:04 -0800 (PST)
Local: Sun, Jan 27 2008 8:17 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 6:13 pm, "Terry Reedy" <tjre...@udel.edu> wrote:

> I think this version, with this name convention, is nice enough to possibly
> go in the stdlib if there were an appropriate place for it.  Not sure where
> though.  If there were a classtools module....

> tjr

+1

I thought at one time there was to be a "decorators" module in the
stdlib for just this kind of useful item.  At minimum, you could post
this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary.

-- Paul


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
MRAB  
View profile  
 More options Jan 27 2008, 8:28 pm
Newsgroups: comp.lang.python
From: MRAB <goo...@mrabarnett.plus.com>
Date: Sun, 27 Jan 2008 17:28:33 -0800 (PST)
Local: Sun, Jan 27 2008 8:28 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 28, 1:01 am, Steven D'Aprano <st...@REMOVE-THIS-

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...


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Christian Heimes  
View profile  
 More options Jan 27 2008, 8:37 pm
Newsgroups: comp.lang.python
From: Christian Heimes <li...@cheimes.de>
Date: Mon, 28 Jan 2008 02:37:08 +0100
Local: Sun, Jan 27 2008 8:37 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

Paul McGuire wrote:
> I thought at one time there was to be a "decorators" module in the
> stdlib for just this kind of useful item.  At minimum, you could post
> this to the Python wiki at http://wiki.python.org/moin/PythonDecoratorLibrary.

Please take  the idea to the Python developer list. Several decorators
are either already implemented (e.g. the first decorator is
functools.wraps) and others are too special but some of the decorators
including auto assignment seem useful.

Christian


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steven D'Aprano  
View profile  
 More options Jan 27 2008, 8:47 pm
Newsgroups: comp.lang.python
From: Steven D'Aprano <st...@REMOVE-THIS-cybersource.com.au>
Date: Mon, 28 Jan 2008 01:47:18 -0000
Local: Sun, Jan 27 2008 8:47 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

On Sun, 27 Jan 2008 19:13:27 -0500, Terry Reedy wrote:

[snip]

> class Test(object):
>      @autoassign
>      def __init__(self, _foo, _bar, baz):
>          print 'baz =', baz

[snip]

> I think this version, with this name convention, is nice enough to
> possibly go in the stdlib if there were an appropriate place for it.
> Not sure where though.  If there were a classtools module....

-1/2

I don't like the name convention. _name already has a perfectly good
convention: it's a private name, don't mess with it. That includes in
function/method signatures. With your convention, _foo is public.

I suppose you could write __foo for a private name, and ___foo for a
*really* private name, relying on the decorator to strip one of the
underscores. But counting all those underscores is a PITA, and what
happens if you don't actually want that private name set as an instance
attribute?

As nice as this feature would be, and I vote +2 on the functionality, I
wonder whether the amount of line noise in method definitions now will be
approaching Perlish levels? We've got default values, type annotations
(in Python3), *args and **kwargs, _ private names, and now we want to add
auto-assignment.

If we do get syntax support, I vote +1 on &foo, +1/2 on @foo, -1 on .foo
and -1 on self.foo. (It's explicit, but it's long...).

--
Steven


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Arnaud Delobelle  
View profile  
 More options Jan 27 2008, 8:51 pm
Newsgroups: comp.lang.python
From: Arnaud Delobelle <arno...@googlemail.com>
Date: Sun, 27 Jan 2008 17:51:28 -0800 (PST)
Local: Sun, Jan 27 2008 8:51 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 6:32 pm, "Diez B. Roggisch" <de...@nospam.web.de> wrote:

Nice!  I've got a slight variation without magic argument names:

def autoassign(*names):
    def decorator(f):
        def decorated(self, *args, **kwargs):
            for name in names:
                setattr(self, name, kwargs.pop(name))
            return f(self, *args, **kwargs)
        return decorated
    return decorator

class Test(object):
     @autoassign('foo', 'bar')
     def __init__(self, baz):
         print 'baz =', baz

t = Test(foo=1, bar=2, baz=6)
# or Test(6, foo=1, bar=2)

print t.foo
print t.bar
print t.baz

--
Arnaud


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Arnaud Delobelle  
View profile  
 More options Jan 27 2008, 8:56 pm
Newsgroups: comp.lang.python
From: Arnaud Delobelle <arno...@googlemail.com>
Date: Sun, 27 Jan 2008 17:56:31 -0800 (PST)
Local: Sun, Jan 27 2008 8:56 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 28, 1:47 am, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:

[...]

> As nice as this feature would be, and I vote +2 on the functionality, I
> wonder whether the amount of line noise in method definitions now will be
> approaching Perlish levels? We've got default values, type annotations
> (in Python3), *args and **kwargs, _ private names, and now we want to add
> auto-assignment.

Don't forget keyword only arguments!  I find signatures too
complicated already, please let's not clutter them even more.

--
Arnaud


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
André  
View profile  
 More options Jan 27 2008, 9:02 pm
Newsgroups: comp.lang.python
From: "André" <andre.robe...@gmail.com>
Date: Sun, 27 Jan 2008 18:02:51 -0800 (PST)
Local: Sun, Jan 27 2008 9:02 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 9:47 pm, Steven D'Aprano <st...@REMOVE-THIS-

Here's a version that
1. does not require new syntax
2. does not *necessarily* override the "_" prefix convention
3. follows the "Explicit is better than implicit" convention when
being called.

(Note: I do not necessarily recommend the "self_" choice)
========
from functools import wraps
from inspect import getargspec

def autoassign(prefix):
    def _autoassign(_init_):
         @wraps(_init_)
         def __autoassign(self, *args, **kwargs):
             argnames, _, _, _ = getargspec(_init_)
             for name, value in zip(argnames[1:], args):
                 if name.startswith(prefix):
                     setattr(self, name[len(prefix):], value)
             _init_(self, *args, **kwargs)

         return __autoassign
    return _autoassign

class Test(object):
     @autoassign('self_')
     def __init__(self, self_foo, self_bar, baz):
         print 'baz =', baz

t = Test(1, 2, 3)
print t.foo
print t.bar
print t.baz # raises an exception

=============
André


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Russ P.  
View profile  
 More options Jan 27 2008, 9:50 pm
Newsgroups: comp.lang.python
From: "Russ P." <Russ.Paie...@gmail.com>
Date: Sun, 27 Jan 2008 18:50:56 -0800 (PST)
Local: Sun, Jan 27 2008 9:50 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 5:13 pm, Wildemar Wildenburger

That makes sense to me.

Come to think of it, why restrict this convention to the constructor?
Or am I just opening a can of worms?


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Paul Rubin  
View profile  
 More options Jan 27 2008, 9:57 pm
Newsgroups: comp.lang.python
From: Paul Rubin <http://phr...@NOSPAM.invalid>
Date: 27 Jan 2008 18:57:53 -0800
Local: Sun, Jan 27 2008 9:57 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

Wildemar Wildenburger <lasses_w...@klapptsowieso.net> writes:
> class Server(object):
>      def __init__(self, self.host, self.port,
>                   self.protocol, self.bufsize, self.timeout):
>          pass
> ?

That could temporarily bind those attributes but it shouldn't
persistently mutate the object.

How about:

    class Server(object):
         def __init__(self, host, port, protocol, bufsize, timeout):
            self.(host, port, protocol, bufsize, timeout) = \
                  host, port, protocol, bufsize, timeout

That's fairly explicit yet cuts down the total amount of boilerplate.


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
André  
View profile  
 More options Jan 27 2008, 10:18 pm
Newsgroups: comp.lang.python
From: "André" <andre.robe...@gmail.com>
Date: Sun, 27 Jan 2008 19:18:29 -0800 (PST)
Local: Sun, Jan 27 2008 10:18 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors
On Jan 27, 10:57 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:

Not much; you're still repeating each variable name 3 times.  I prefer
the standard way of one definition per line over this notation
myself.

André


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Ben Finney  
View profile  
 More options Jan 27 2008, 10:33 pm
Newsgroups: comp.lang.python
From: Ben Finney <bignose+hates-s...@benfinney.id.au>
Date: Mon, 28 Jan 2008 14:33:42 +1100
Local: Sun, Jan 27 2008 10:33 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

"Russ P." <Russ.Paie...@gmail.com> writes:
> On Jan 27, 5:13 pm, Wildemar Wildenburger
> <lasses_w...@klapptsowieso.net> wrote:
> > class Server(object):
> >      def __init__(self, self.host, self.port,
> >                   self.protocol, self.bufsize, self.timeout):
> >          pass

> > ?

> That makes sense to me.

Not to me. 'self' is a name that doesn't exist until *after* that
'def' statement is completed; in any other statement, that would mean
'self.foo' in the same statement would raise a NameError.

Special-casing it for a function declaration complicates the language
for little gain: the rules of what is valid when become more
complicated. Special cases aren't special enough to break the rules.

--
 \        "I took a course in speed waiting. Now I can wait an hour in |
  `\                              only ten minutes."  -- Steven Wright |
_o__)                                                                  |
Ben Finney


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Tim Chase  
View profile  
 More options Jan 27 2008, 11:30 pm
Newsgroups: comp.lang.python
From: Tim Chase <python.l...@tim.thechases.com>
Date: Sun, 27 Jan 2008 22:30:45 -0600
Local: Sun, Jan 27 2008 11:30 pm
Subject: Re: py3k feature proposal: field auto-assignment in constructors

> This is neat. :) Could that maybe be extended to only assign selected
> args to the instance and let others pass unchanged. So that, for instance:

> @autoassign("foo", "bar")
> def __init__(self, foo, bar, baz):
>      super(baz)

I've seen some folks import inspect/functools, but from my
testing, the __init__ method in question has a .func_code object
that already has the varnames in it.  However, as you suggest, a
version below allows for named defaults, and letting others go
un-defaulted.  I'm not sure about naming conventions for
class-style decorators--start with a cap, like a class should
("AutoAssign") or because it behaves like a function, use
"auto_assign", or any of a number of other variants.  Anyways...

  class auto_assign(object):
    def __init__(self, *varnames):
      self.args = set(varnames)
    def __call__(self, fn):
      autoassign = self
      def wrapper(self, *args, **kwargs):
        for argname, argvalue in zip(
            fn.func_code.co_varnames[1:],
            args):
          if argname in autoassign.args:
            setattr(self, argname, argvalue)
        for argname in autoassign.args:
          if argname in kwargs:
            setattr(self, argname, kwargs[argname])
        fn(self, *args, **kwargs)
      return wrapper

  class Foo(object):
    @auto_assign('foo', 'baz', 'fred')
    def __init__(self, foo, bar, baz, *args, **kwargs):
      pass

  f = Foo('hello', 42, 3.14, fred='wilma', barney='betty')
  try:
    print f.foo
  except AttributeError:
    print "Could not print f.foo"

  try:
    print f.bar
  except AttributeError:
    print "Could not print f.bar"

  try:
    print f.baz
  except AttributeError:
    print "Could not print f.baz"

  try:
    print f.fred
  except AttributeError:
    print "Could not print f.fred"

  try:
    print f.barney
  except AttributeError:
    print "Could not print f.barney"

-tkc


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Messages 1 - 25 of 46   Newer >
« Back to Discussions « Newer topic     Older topic »

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2009 Google