Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1]
(typename, field_names, verbose=False, rename=False)
| 3 | import sys as _sys |
| 4 | |
| 5 | def namedtuple(typename, field_names, verbose=False, rename=False): |
| 6 | """Returns a new subclass of tuple with named fields. |
| 7 | |
| 8 | >>> Point = namedtuple('Point', 'x y') |
| 9 | >>> Point.__doc__ # docstring for the new class |
| 10 | 'Point(x, y)' |
| 11 | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
| 12 | >>> p[0] + p[1] # indexable like a plain tuple |
| 13 | 33 |
| 14 | >>> x, y = p # unpack like a regular tuple |
| 15 | >>> x, y |
| 16 | (11, 22) |
| 17 | >>> p.x + p.y # fields also accessable by name |
| 18 | 33 |
| 19 | >>> d = p._asdict() # convert to a dictionary |
| 20 | >>> d['x'] |
| 21 | 11 |
| 22 | >>> Point(**d) # convert from a dictionary |
| 23 | Point(x=11, y=22) |
| 24 | >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
| 25 | Point(x=100, y=22) |
| 26 | |
| 27 | """ |
| 28 | |
| 29 | # Parse and validate the field names. Validation serves two purposes, |
| 30 | # generating informative error messages and preventing template injection attacks. |
| 31 | if isinstance(field_names, basestring): |
| 32 | field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas |
| 33 | field_names = tuple(map(str, field_names)) |
| 34 | if rename: |
| 35 | names = list(field_names) |
| 36 | seen = set() |
| 37 | for i, name in enumerate(names): |
| 38 | if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
| 39 | or not name or name[0].isdigit() or name.startswith('_') |
| 40 | or name in seen): |
| 41 | names[i] = '_%d' % i |
| 42 | seen.add(name) |
| 43 | field_names = tuple(names) |
| 44 | for name in (typename,) + field_names: |
| 45 | if not min(c.isalnum() or c=='_' for c in name): |
| 46 | raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) |
| 47 | if _iskeyword(name): |
| 48 | raise ValueError('Type names and field names cannot be a keyword: %r' % name) |
| 49 | if name[0].isdigit(): |
| 50 | raise ValueError('Type names and field names cannot start with a number: %r' % name) |
| 51 | seen_names = set() |
| 52 | for name in field_names: |
| 53 | if name.startswith('_') and not rename: |
| 54 | raise ValueError('Field names cannot start with an underscore: %r' % name) |
| 55 | if name in seen_names: |
| 56 | raise ValueError('Encountered duplicate field name: %r' % name) |
| 57 | seen_names.add(name) |
| 58 | |
| 59 | # Create and fill-in the class template |
| 60 | numfields = len(field_names) |
| 61 | argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes |
| 62 | reprtxt = ', '.join('%s=%%r' % name for name in field_names) |