OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 # |
| 3 # $Id: _compat.py 1142 2011-10-05 18:45:49Z g.rodola $ |
| 4 # |
| 5 # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. |
| 6 # Use of this source code is governed by a BSD-style license that can be |
| 7 # found in the LICENSE file. |
| 8 |
| 9 """Module which provides compatibility with older Python versions.""" |
| 10 |
| 11 __all__ = ["namedtuple", "property"] |
| 12 |
| 13 from operator import itemgetter as _itemgetter |
| 14 from keyword import iskeyword as _iskeyword |
| 15 import sys as _sys |
| 16 import __builtin__ |
| 17 |
| 18 try: |
| 19 from collections import namedtuple |
| 20 except ImportError: |
| 21 def namedtuple(typename, field_names, verbose=False, rename=False): |
| 22 """A collections.namedtuple implementation written in Python |
| 23 to support Python versions < 2.6. |
| 24 |
| 25 Taken from: http://code.activestate.com/recipes/500261/ |
| 26 """ |
| 27 # Parse and validate the field names. Validation serves two |
| 28 # purposes, generating informative error messages and preventing |
| 29 # template injection attacks. |
| 30 if isinstance(field_names, basestring): |
| 31 # names separated by whitespace and/or commas |
| 32 field_names = field_names.replace(',', ' ').split() |
| 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(n
ame) |
| 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 '
\ |
| 47 'alphanumeric characters and underscores: %r' |
| 48 % name) |
| 49 if _iskeyword(name): |
| 50 raise ValueError('Type names and field names cannot be a keyword
: %r' \ |
| 51 % name) |
| 52 if name[0].isdigit(): |
| 53 raise ValueError('Type names and field names cannot start with a
' \ |
| 54 'number: %r' % name) |
| 55 seen_names = set() |
| 56 for name in field_names: |
| 57 if name.startswith('_') and not rename: |
| 58 raise ValueError('Field names cannot start with an underscore: %
r' |
| 59 % name) |
| 60 if name in seen_names: |
| 61 raise ValueError('Encountered duplicate field name: %r' % name) |
| 62 seen_names.add(name) |
| 63 |
| 64 # Create and fill-in the class template |
| 65 numfields = len(field_names) |
| 66 # tuple repr without parens or quotes |
| 67 argtxt = repr(field_names).replace("'", "")[1:-1] |
| 68 reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
| 69 template = '''class %(typename)s(tuple): |
| 70 '%(typename)s(%(argtxt)s)' \n |
| 71 __slots__ = () \n |
| 72 _fields = %(field_names)r \n |
| 73 def __new__(_cls, %(argtxt)s): |
| 74 return _tuple.__new__(_cls, (%(argtxt)s)) \n |
| 75 @classmethod |
| 76 def _make(cls, iterable, new=tuple.__new__, len=len): |
| 77 'Make a new %(typename)s object from a sequence or iterable' |
| 78 result = new(cls, iterable) |
| 79 if len(result) != %(numfields)d: |
| 80 raise TypeError('Expected %(numfields)d arguments, got %%d' %% l
en(result)) |
| 81 return result \n |
| 82 def __repr__(self): |
| 83 return '%(typename)s(%(reprtxt)s)' %% self \n |
| 84 def _asdict(self): |
| 85 'Return a new dict which maps field names to their values' |
| 86 return dict(zip(self._fields, self)) \n |
| 87 def _replace(_self, **kwds): |
| 88 'Return a new %(typename)s object replacing specified fields with ne
w values' |
| 89 result = _self._make(map(kwds.pop, %(field_names)r, _self)) |
| 90 if kwds: |
| 91 raise ValueError('Got unexpected field names: %%r' %% kwds.keys(
)) |
| 92 return result \n |
| 93 def __getnewargs__(self): |
| 94 return tuple(self) \n\n''' % locals() |
| 95 for i, name in enumerate(field_names): |
| 96 template += ' %s = _property(_itemgetter(%d))\n' % (name, i) |
| 97 if verbose: |
| 98 print template |
| 99 |
| 100 # Execute the template string in a temporary namespace |
| 101 namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typ
ename, |
| 102 _property=property, _tuple=tuple) |
| 103 try: |
| 104 exec template in namespace |
| 105 except SyntaxError, e: |
| 106 raise SyntaxError(e.message + ':\n' + template) |
| 107 result = namespace[typename] |
| 108 |
| 109 # For pickling to work, the __module__ variable needs to be set |
| 110 # to the frame where the named tuple is created. Bypass this |
| 111 # step in enviroments where sys._getframe is not defined (Jython |
| 112 # for example) or sys._getframe is not defined for arguments |
| 113 # greater than 0 (IronPython). |
| 114 try: |
| 115 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__m
ain__') |
| 116 except (AttributeError, ValueError): |
| 117 pass |
| 118 |
| 119 return result |
| 120 |
| 121 |
| 122 # dirty hack to support property.setter on python < 2.6 |
| 123 property = property |
| 124 |
| 125 if not hasattr(property, "setter"): |
| 126 |
| 127 class property(property): |
| 128 |
| 129 def __init__(self, fget, *args, **kwargs): |
| 130 self.__doc__ = fget.__doc__ |
| 131 super(property, self).__init__(fget, *args, **kwargs) |
| 132 |
| 133 def setter(self, fset): |
| 134 cls_ns = _sys._getframe(1).f_locals |
| 135 for k, v in cls_ns.iteritems(): |
| 136 if v == self: |
| 137 propname = k |
| 138 break |
| 139 cls_ns[propname] = property(self.fget, fset, |
| 140 self.fdel, self.__doc__) |
| 141 return cls_ns[propname] |
| 142 |
| 143 def deleter(self, fdel): |
| 144 cls_ns = _sys._getframe(1).f_locals |
| 145 for k, v in cls_ns.iteritems(): |
| 146 if v == self: |
| 147 propname = k |
| 148 break |
| 149 cls_ns[propname] = property(self.fget, self.fset, |
| 150 fdel, self.__doc__) |
| 151 return cls_ns[propname] |
| 152 |
| 153 __builtin__.property = property |
| 154 |
OLD | NEW |