py3k feature proposal: field auto-assignment in constructors

Paddy paddy3118 at googlemail.com
Mon Jan 28 02:13:14 EST 2008


On Jan 27, 5:06 pm, coldpizza <vri... at gmail.com> wrote:
> 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.

Is it not possible to write a function that queries its call stack
when run to find the name of all arguments and locals() of the level
above so you could write:

class test(object):
  def __init__(self, x, y):
    arg2inst()

and automatically assign self.x=x; self.y=y ?

It could be extended so that...

class test(object):
  def __init__(self, x, y):
    arg2inst("x")

... then only assigns x.


Has anyone seen something like this in the cookbook?

- Paddy.



More information about the Python-list mailing list