[Python-ideas] Simple class initialization

Adam Matan adam at matan.name
Sat Apr 16 23:10:29 CEST 2011


I think autoassign is a suitable name for this functionality.
I would like to see this as a PEP.
Adam

On Sat, Apr 16, 2011 at 10:58 PM, Arnaud Delobelle <arnodel at gmail.com>wrote:

>
> On 16 Apr 2011, at 12:50, Adam Matan wrote:
>
> > 0. Abstract
> > ===========
> >
> > A class initialization often begins with a long list of explicit variable
> > declaration statements at the __init__() method. This repetitively copies
> > arguments into local data attributes.
> > This article suggests some semi-automatic techniques to shorten and
> clarify
> > this code section. Comments and responses are highly appreciated.
>
> Following a discussion on c.l.python, I posted a recipe on ActiveState a
> while ago that attempted to deal with this issue:
>
>
> http://code.activestate.com/recipes/551763-automatic-attribute-assignment/
>
> From the docstring:
>
>    """
>    autoassign(function) -> method
>    autoassign(*argnames) -> decorator
>    autoassign(exclude=argnames) -> decorator
>
>    allow a method to assign (some of) its arguments as attributes of
>    'self' automatically.  E.g.
>
>    >>> class Foo(object):
>    ...     @autoassign
>    ...     def __init__(self, foo, bar): pass
>    ...
>    >>> breakfast = Foo('spam', 'eggs')
>    >>> breakfast.foo, breakfast.bar
>    ('spam', 'eggs')
>
>    To restrict autoassignment to 'bar' and 'baz', write:
>
>        @autoassign('bar', 'baz')
>        def method(self, foo, bar, baz): ...
>
>    To prevent 'foo' and 'baz' from being autoassigned, use:
>
>        @autoassign(exclude=('foo', 'baz'))
>        def method(self, foo, bar, baz): ...
>    """
>
> --
> Arnaud
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110417/87186e15/attachment.html>


More information about the Python-ideas mailing list