[Python-ideas] Ordered storage of keyword arguments

Steven D'Aprano steve at pearwood.info
Sat Oct 30 11:58:23 CEST 2010


spir wrote:

> (**) I miss "free objects" in python for this reason -- people often use dicts instead. I'd like to be able to write: "return (color:c, position:p)", where the defined object is instance of Object directly, or maybe of Individual, meaning Object with a __dict__.
> class Individual:
>     def __init__ (self, **slots):
>         self.__dict__ = slots
>     def __repr__(self):
>         return "(%s)" % \
>             ' '.join("%s:%s" %(k,v) for (k,v) in self.__dict__.items())
> print Individual(a=135, d=100)  # (a:135 d:100)
> If only we had a literal notation for that :-) No more need of classes for singletons.


We almost do.

 >>> from collections import namedtuple as nt
 >>> nt("Individual", "a d")(a=135, d=100)
Individual(a=135, d=100)


Short enough to write in-line. Or you could do this:

 >>> Individual = nt("Individual", "a d")
 >>> Individual(99, 42)
Individual(a=99, d=42)


It shouldn't be hard to write a function similar to namedtuple that 
didn't require a declaration before hand, but picked up the field names 
from the keyword-only arguments given:

 >>> from collections import record  # say
 >>> record(a=23, b=42)
record(a=23, b=24)


I leave that as an exercise to the readers :)




-- 
Steven



More information about the Python-ideas mailing list