py3k feature proposal: field auto-assignment in constructors

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jan 28 04:06:17 EST 2008


On Mon, 28 Jan 2008 19:21:48 +1100, Ben Finney wrote:

> In fact, here's a variation that doesn't even need a language
> change::
> 
>     >>> class Foo(object):
>     ...     def __init__(self, spam, eggs, beans):
>     ...         self.__dict__.update(dict(
>     ...             (name, value) for (name, value) in \
>     ...             vars().items() if name in ['spam', 'beans']))
>     ...


You still need to repeat yourself twice. That's 33% better than repeating 
yourself three times, but 100% worse than repeating yourself once.

Other problems:

(1) Readability suffers greatly.

(2) Performance takes a big hit.


>>> class Parrot(object):
...     def __init__(self, name, colour, breed):
...             self.name = name
...             self.colour = colour
...             self.breed = breed
...
>>> class Parrot2(object):
...     def __init__(self, name, colour, breed):
...             self.__dict__.update(dict((name, value) for 
...             (name, value) in vars().items()
...             if name in ['name', 'colour', 'breed']))
...
>>>
>>>
>>> import timeit
>>> timeit.Timer("Parrot(1, 2, 3)", 
... "from __main__ import Parrot").repeat()
[3.3467490673065186, 2.2820541858673096, 2.2934978008270264]
>>> timeit.Timer("Parrot2(1, 2, 3)", 
... "from __main__ import Parrot2").repeat()
[13.148159027099609, 13.015455961227417, 11.936856985092163]



-- 
Steven



More information about the Python-list mailing list