Google Groups Home
Help | Sign in
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   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
coldpizza  
View profile
 More options Jan 27, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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