[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)

Joao S. O. Bueno jsbueno at python.org.br
Thu Mar 10 05:51:19 CET 2011


On Wed, Mar 9, 2011 at 9:29 PM, Guido van Rossum <guido at python.org> wrote:
> On Wed, Mar 9, 2011 at 6:12 PM, MRAB <python at mrabarnett.plus.com> wrote:
>>    def foo = CharField(size=10, nullable=False)
>
> Eek, it would be really easy to misread that.
>
> But as long as we're trying to reuse 'def', I think a decorator using
> introspection could make this form work:
>
> @CharField
> def foo(size=10, nullable=False): "docstring goes here"
>
> Not that I seriously recommend this. :-)

Though it would be easy to do for most cases, with nothing new needed:

from collections import namedtuple

class MetaAssignmentDecorator(type):
    def __call__(cls, func):
        parameters = dict(zip(func.__code__.co_varnames, func.__defaults__))
        return type.__call__(cls, func.__name__, **parameters)

class NamedTuple(metaclass=MetaAssignmentDecorator):
    def __new__(cls, name, values):
        return namedtuple(name, values)

# Allows for

@NamedTuple
def Point(values="x y"): pass

p = Point(127, 87)
>>> print (p.x)
87


>
> --
> --Guido van Rossum (python.org/~guido)
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list