OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 # |
| 3 # $Id: compat.py 712 2010-10-20 15:25:57Z g.rodola $ |
| 4 # |
| 5 |
| 6 """Module which provides compatibility with older Python versions.""" |
| 7 |
| 8 from operator import itemgetter as _itemgetter |
| 9 from keyword import iskeyword as _iskeyword |
| 10 import sys as _sys |
| 11 |
| 12 |
| 13 def namedtuple(typename, field_names, verbose=False, rename=False): |
| 14 """A collections.namedtuple implementation written in Python |
| 15 to support Python versions < 2.6. |
| 16 |
| 17 Taken from: http://code.activestate.com/recipes/500261/ |
| 18 """ |
| 19 # Parse and validate the field names. Validation serves two |
| 20 # purposes, generating informative error messages and preventing |
| 21 # template injection attacks. |
| 22 if isinstance(field_names, basestring): |
| 23 # names separated by whitespace and/or commas |
| 24 field_names = field_names.replace(',', ' ').split() |
| 25 field_names = tuple(map(str, field_names)) |
| 26 if rename: |
| 27 names = list(field_names) |
| 28 seen = set() |
| 29 for i, name in enumerate(names): |
| 30 if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
| 31 or not name or name[0].isdigit() or name.startswith('_') |
| 32 or name in seen): |
| 33 names[i] = '_%d' % i |
| 34 seen.add(name) |
| 35 field_names = tuple(names) |
| 36 for name in (typename,) + field_names: |
| 37 if not min(c.isalnum() or c=='_' for c in name): |
| 38 raise ValueError('Type names and field names can only contain ' \ |
| 39 'alphanumeric characters and underscores: %r' |
| 40 % name) |
| 41 if _iskeyword(name): |
| 42 raise ValueError('Type names and field names cannot be a keyword: %r
' \ |
| 43 % name) |
| 44 if name[0].isdigit(): |
| 45 raise ValueError('Type names and field names cannot start with a ' \ |
| 46 'number: %r' % name) |
| 47 seen_names = set() |
| 48 for name in field_names: |
| 49 if name.startswith('_') and not rename: |
| 50 raise ValueError('Field names cannot start with an underscore: %r' |
| 51 % name) |
| 52 if name in seen_names: |
| 53 raise ValueError('Encountered duplicate field name: %r' % name) |
| 54 seen_names.add(name) |
| 55 |
| 56 # Create and fill-in the class template |
| 57 numfields = len(field_names) |
| 58 # tuple repr without parens or quotes |
| 59 argtxt = repr(field_names).replace("'", "")[1:-1] |
| 60 reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
| 61 template = '''class %(typename)s(tuple): |
| 62 '%(typename)s(%(argtxt)s)' \n |
| 63 __slots__ = () \n |
| 64 _fields = %(field_names)r \n |
| 65 def __new__(_cls, %(argtxt)s): |
| 66 return _tuple.__new__(_cls, (%(argtxt)s)) \n |
| 67 @classmethod |
| 68 def _make(cls, iterable, new=tuple.__new__, len=len): |
| 69 'Make a new %(typename)s object from a sequence or iterable' |
| 70 result = new(cls, iterable) |
| 71 if len(result) != %(numfields)d: |
| 72 raise TypeError('Expected %(numfields)d arguments, got %%d' %% l
en(result)) |
| 73 return result \n |
| 74 def __repr__(self): |
| 75 return '%(typename)s(%(reprtxt)s)' %% self \n |
| 76 def _asdict(self): |
| 77 'Return a new dict which maps field names to their values' |
| 78 return dict(zip(self._fields, self)) \n |
| 79 def _replace(_self, **kwds): |
| 80 'Return a new %(typename)s object replacing specified fields with ne
w values' |
| 81 result = _self._make(map(kwds.pop, %(field_names)r, _self)) |
| 82 if kwds: |
| 83 raise ValueError('Got unexpected field names: %%r' %% kwds.keys(
)) |
| 84 return result \n |
| 85 def __getnewargs__(self): |
| 86 return tuple(self) \n\n''' % locals() |
| 87 for i, name in enumerate(field_names): |
| 88 template += ' %s = _property(_itemgetter(%d))\n' % (name, i) |
| 89 if verbose: |
| 90 print template |
| 91 |
| 92 # Execute the template string in a temporary namespace |
| 93 namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typenam
e, |
| 94 _property=property, _tuple=tuple) |
| 95 try: |
| 96 exec template in namespace |
| 97 except SyntaxError, e: |
| 98 raise SyntaxError(e.message + ':\n' + template) |
| 99 result = namespace[typename] |
| 100 |
| 101 # For pickling to work, the __module__ variable needs to be set |
| 102 # to the frame where the named tuple is created. Bypass this |
| 103 # step in enviroments where sys._getframe is not defined (Jython |
| 104 # for example) or sys._getframe is not defined for arguments |
| 105 # greater than 0 (IronPython). |
| 106 try: |
| 107 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main_
_') |
| 108 except (AttributeError, ValueError): |
| 109 pass |
| 110 |
| 111 return result |
OLD | NEW |