1
0

_compat.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from keyword import iskeyword as _iskeyword
  2. from operator import itemgetter as _itemgetter
  3. import sys as _sys
  4. def namedtuple(typename, field_names):
  5. """Returns a new subclass of tuple with named fields.
  6. >>> Point = namedtuple('Point', 'x y')
  7. >>> Point.__doc__ # docstring for the new class
  8. 'Point(x, y)'
  9. >>> p = Point(11, y=22) # instantiate with positional args or keywords
  10. >>> p[0] + p[1] # indexable like a plain tuple
  11. 33
  12. >>> x, y = p # unpack like a regular tuple
  13. >>> x, y
  14. (11, 22)
  15. >>> p.x + p.y # fields also accessable by name
  16. 33
  17. >>> d = p._asdict() # convert to a dictionary
  18. >>> d['x']
  19. 11
  20. >>> Point(**d) # convert from a dictionary
  21. Point(x=11, y=22)
  22. >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
  23. Point(x=100, y=22)
  24. """
  25. # Parse and validate the field names. Validation serves two purposes,
  26. # generating informative error messages and preventing template injection attacks.
  27. if isinstance(field_names, basestring):
  28. field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
  29. field_names = tuple(map(str, field_names))
  30. for name in (typename,) + field_names:
  31. if not all(c.isalnum() or c=='_' for c in name):
  32. raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
  33. if _iskeyword(name):
  34. raise ValueError('Type names and field names cannot be a keyword: %r' % name)
  35. if name[0].isdigit():
  36. raise ValueError('Type names and field names cannot start with a number: %r' % name)
  37. seen_names = set()
  38. for name in field_names:
  39. if name.startswith('_'):
  40. raise ValueError('Field names cannot start with an underscore: %r' % name)
  41. if name in seen_names:
  42. raise ValueError('Encountered duplicate field name: %r' % name)
  43. seen_names.add(name)
  44. # Create and fill-in the class template
  45. numfields = len(field_names)
  46. argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
  47. reprtxt = ', '.join('%s=%%r' % name for name in field_names)
  48. dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
  49. template = '''class %(typename)s(tuple):
  50. '%(typename)s(%(argtxt)s)' \n
  51. __slots__ = () \n
  52. _fields = %(field_names)r \n
  53. def __new__(_cls, %(argtxt)s):
  54. return _tuple.__new__(_cls, (%(argtxt)s)) \n
  55. @classmethod
  56. def _make(cls, iterable, new=tuple.__new__, len=len):
  57. 'Make a new %(typename)s object from a sequence or iterable'
  58. result = new(cls, iterable)
  59. if len(result) != %(numfields)d:
  60. raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
  61. return result \n
  62. def __repr__(self):
  63. return '%(typename)s(%(reprtxt)s)' %% self \n
  64. def _asdict(t):
  65. 'Return a new dict which maps field names to their values'
  66. return {%(dicttxt)s} \n
  67. def _replace(_self, **kwds):
  68. 'Return a new %(typename)s object replacing specified fields with new values'
  69. result = _self._make(map(kwds.pop, %(field_names)r, _self))
  70. if kwds:
  71. raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
  72. return result \n
  73. def __getnewargs__(self):
  74. return tuple(self) \n\n''' % locals()
  75. for i, name in enumerate(field_names):
  76. template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
  77. # Execute the template string in a temporary namespace and
  78. # support tracing utilities by setting a value for frame.f_globals['__name__']
  79. namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
  80. _property=property, _tuple=tuple)
  81. try:
  82. exec(template, namespace)
  83. except SyntaxError:
  84. e = _sys.exc_info()[1]
  85. raise SyntaxError(e.message + ':\n' + template)
  86. result = namespace[typename]
  87. # For pickling to work, the __module__ variable needs to be set to the frame
  88. # where the named tuple is created. Bypass this step in enviroments where
  89. # sys._getframe is not defined (Jython for example).
  90. if hasattr(_sys, '_getframe'):
  91. result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
  92. return result