[Python-ideas] Docstrings for namedtuple
Terry Reedy
tjreedy at udel.edu
Sun Dec 16 21:05:36 CET 2012
On 12/16/2012 8:22 AM, Eli Bendersky wrote:
> This may be a good time to say that personally I always disliked
> namedtuple's creation syntax. It is unpleasant in two respects:
>
> 1. You have to repeat the name
> 2. You have to specify the fields in a space-separated string
>
> I wish there was an alternative of something like:
>
> @namedtuple
> class Point:
> x = 0
> y = 0
Pretty easy, once one figures out metaclass basics.
import collections as co
class ntmeta():
def __prepare__(name, bases, **kwds):
return co.OrderedDict()
def __new__(cls, name, bases, namespace):
print(namespace) # shows why filter is needed
return co.namedtuple(name,
filter(lambda s: s[0] != '_', namespace))
class Point(metaclass=ntmeta):
x = 0
y = 0
p = Point(1,2)
print(p)
#
OrderedDict([('__module__', '__main__'), ('__qualname__', 'Point'),
('x', 0), ('y', 0)])
Point(x=1, y=2)
To use the filtered namespace values as defaults (Antoine's suggestion),
first replace namedtuple() with its body.
Then modify the header of generated name.__new__. For Point, change
def __new__(_cls, x, y):
#to
def __new__(_cls, x=0, y=0):
Also change the newclass docstring. For Point, change
'Point(x, y)'
to
'Point(x=0, y=0)'
--
Terry Jan Reedy
More information about the Python-ideas
mailing list