Kaydet (Commit) cbab5949 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Cleanup docs for NamedTuple.

üst cce8df2f
...@@ -360,9 +360,12 @@ Setting the :attr:`default_factory` to :class:`set` makes the ...@@ -360,9 +360,12 @@ Setting the :attr:`default_factory` to :class:`set` makes the
.. _named-tuple-factory: .. _named-tuple-factory:
:func:`NamedTuple` datatype factory function :func:`NamedTuple` factory function
-------------------------------------------- -----------------------------------
Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code. They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.
.. function:: NamedTuple(typename, fieldnames, [verbose]) .. function:: NamedTuple(typename, fieldnames, [verbose])
...@@ -372,94 +375,90 @@ Setting the :attr:`default_factory` to :class:`set` makes the ...@@ -372,94 +375,90 @@ Setting the :attr:`default_factory` to :class:`set` makes the
helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
method which lists the tuple contents in a ``name=value`` format. method which lists the tuple contents in a ``name=value`` format.
The *fieldnames* are specified in a single string with each fieldname separated by
a space and/or comma. Any valid Python identifier may be used for a field name.
If *verbose* is true, the *NamedTuple* call will print the class definition.
*NamedTuple* instances do not have per-instance dictionaries, so they are
lightweight, requiring no more memory than regular tuples.
.. versionadded:: 2.6 .. versionadded:: 2.6
The *fieldnames* are specified in a single string and are separated by spaces Example::
and/or commas. Any valid Python identifier may be used for a field name.
>>> Point = NamedTuple('Point', 'x y', True)
Example:: class Point(tuple):
'Point(x, y)'
>>> Point = NamedTuple('Point', 'x y') __slots__ = ()
>>> Point.__doc__ # docstring for the new datatype __fields__ = ('x', 'y')
'Point(x, y)' def __new__(cls, x, y):
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments return tuple.__new__(cls, (x, y))
>>> p[0] + p[1] # works just like the tuple (11, 22) def __repr__(self):
33 return 'Point(x=%r, y=%r)' % self
>>> x, y = p # unpacks just like a tuple def __replace__(self, field, value):
>>> x, y 'Return a new Point object replacing one field with a new value'
(11, 22) return Point(**dict(zip(('x', 'y'), self) + [(field, value)]))
>>> p.x + p.y # fields also accessable by name x = property(itemgetter(0))
33 y = property(itemgetter(1))
>>> p # readable __repr__ with name=value style
Point(x=11, y=22) >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the regular tuple (11, 22)
The use cases are the same as those for tuples. The named factories assign 33
meaning to each tuple position and allow for more readable, self-documenting >>> x, y = p # unpack like a regular tuple
code. Named tuples can also be used to assign field names to tuples returned >>> x, y
by the :mod:`csv` or :mod:`sqlite3` modules. For example:: (11, 22)
>>> p.x + p.y # fields also accessable by name
from itertools import starmap 33
import csv >>> p # readable __repr__ with a name=value style
EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') Point(x=11, y=22)
for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
print record Named tuples are especially useful for assigning field names to result tuples returned
by the :mod:`csv` or :mod:`sqlite3` modules::
To cast an individual record stored as :class:`list`, :class:`tuple`, or some
other iterable type, use the star-operator [#]_ to unpack the values:: from itertools import starmap
import csv
>>> Color = NamedTuple('Color', 'name code') EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade')
>>> m = dict(red=1, green=2, blue=3) for emp in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
>>> print Color(*m.popitem()) print emp.name, emp.title
Color(name='blue', code=3)
When casting a single record to a *NamedTuple*, use the star-operator [#]_ to unpack
If *verbose* is true, the *NamedTuple* call will print the class definition:: the values::
>>> Point = NamedTuple('Point', 'x y', verbose=True) >>> t = [11, 22]
class Point(tuple): >>> Point(*t) # the star-operator unpacks any iterable object
'Point(x, y)' Point(x=11, y=22)
__slots__ = ()
__fields__ = ('x', 'y')
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
def __repr__(self):
return 'Point(x=%r, y=%r)' % self
def __replace__(self, field, value):
'Return a new Point object replacing one field with a new value'
return Point(**dict(zip(('x', 'y'), self) + [(field, value)]))
x = property(itemgetter(0))
y = property(itemgetter(1))
In addition to the methods inherited from tuples, named tuples support In addition to the methods inherited from tuples, named tuples support
an additonal method and an informational read-only attribute. an additonal method and an informational read-only attribute.
.. method:: somenamedtuple.replace(field, value) .. method:: somenamedtuple.replace(field, value)
Return a new instance of the named tuple with *field* replaced with *value*. Return a new instance of the named tuple replacing the named *field* with a new *value*::
Examples:: >>> p = Point(x=11, y=22)
>>> p = Point(x=11, y=22)
>>> p.__replace__('x', 33) >>> p.__replace__('x', 33)
Point(x=33, y=22) Point(x=33, y=22)
>>> for recordnum, record in inventory: >>> for recordnum, record in inventory:
... inventory[recordnum] = record.replace('total', record.price * record.quantity) ... inventory[recordnum] = record.replace('total', record.price * record.quantity)
.. attribute:: somenamedtuple.__fields__ .. attribute:: somenamedtuple.__fields__
Return a tuple of strings listing the field names. This is useful for introspection, Return a tuple of strings listing the field names. This is useful for introspection,
for converting a named tuple instance to a dictionary, and for creating new named tuple for converting a named tuple instance to a dictionary, and for combining named tuple
types from existing types. types to create new named tuple types::
Examples:: >>> p.__fields__ # view the field names
('x', 'y')
>>> dict(zip(p.__fields__, p)) # make a dictionary from a named tuple instance >>> dict(zip(p.__fields__, p)) # convert to a dictionary
{'y': 20, 'x': 10} {'y': 22, 'x': 11}
>>> ColorPoint = NamedTuple('ColorPoint', ' '.join(Point.__fields__) + ' color') >>> Color = NamedTuple('Color', 'red green blue')
>>> ColorPoint(10, 20, 'red') >>> pixel_fields = ' '.join(Point.__fields__ + Color.__fields__) # combine fields
ColorPoint(x=10, y=20, color='red') >>> Pixel = NamedTuple('Pixel', pixel_fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)'
.. rubric:: Footnotes .. rubric:: Footnotes
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment