[Python-ideas] recorarray: a mutable alternative to namedtuple

Chris Angelico rosuav at gmail.com
Sat Mar 28 03:01:30 CET 2015


On Sat, Mar 28, 2015 at 12:09 PM, Andrew Barnert
<abarnert at yahoo.com.dmarc.invalid> wrote:
>     class Person
>         def __init__(self, name: str, age: int):
>             self.name = name
>             self.age = age
>
> Of course it's trivial to wrap up that boilerplate if you're going to create 20 of these.

Here's a crazy thought: you could use functools.wraps() to abuse **kwargs.

def make_attributes(func):
    @functools.wraps(func)
    def inner(self, **args):
        self.__dict__.update(args)
        inner(self, **args)
    return inner

class Person:
    @make_attributes
    def __init__(self, *, name: str, age: int):
        pass

Thanks to wraps(), you still have your parameter names for
introspection and help() and so on. Thanks to **args, you can do bulk
operations on all the args.

It's a bit naughty (and it does preclude positional args, though a
little bit more work in the decorator could support that too), but it
would work.....

ChrisA


More information about the Python-ideas mailing list