[Python-ideas] Syntax for making stuct / record / namedtuples
Arnaud Delobelle
arnodel at googlemail.com
Wed Oct 21 19:19:57 CEST 2009
On 21 Oct 2009, at 16:56, Bruce Leban wrote:
> Reading your code I have no idea what these lines mean
>
>
> autoassign(function) -> method
> autoassign(*argnames) -> decorator
> autoassign(exclude=argnames) -> decorator
>
> Reading the code, what I *think* this does
>
> """Decorator that assigns all function parameters to attributes of
> the class.
> You can specify a list of parameters to process or a list of
> parameters to exclude.
> Given another function, does something complicated that belongs in
> another recipe.
> """
>
I don't understand that last sentence.
> I'm only half-joking. It's not obvious what that function parameter
> does and you don't give any examples of it's use.
I give two examples. One in the docstring (first example), the other
one in the tests below the definition of the decorator (class Test2).
> Just reading the code with unrelated assignments grouped together
> was confusing enough -- definitely not my coding style.
Sorry I confused you :)
>
> More importantly not at all clear why this is better than
>
> self.__dict__.update(locals())
>
It's not a very nice construct. And it doesn't work as is:
>>> class Foo(object):
... def __init__(self, a, b, c):
... self.__dict__.update(locals())
...
>>> foo=Foo(1, 2, 3)
>>> foo.self
<__main__.Foo object at 0x10048c790>
Probably not what was intended... So you can write something like:
>>> class Foo(object):
... def __init__(self, a, b, c):
... self.__dict__.update(((n, v) for (n, v) in locals
().items() if n!='self'))
...
>>> foo=Foo(1, 2, 3)
>>> foo.self
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'self'
But that reads even worse.
Also, it's a bit more versatile.
--
Arnaud
More information about the Python-ideas
mailing list