home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_315 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  5.3 KB  |  109 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = [
  5.     'deque',
  6.     'defaultdict',
  7.     'namedtuple']
  8. from _abcoll import *
  9. import _abcoll
  10. __all__ += _abcoll.__all__
  11. from _collections import deque, defaultdict
  12. from operator import itemgetter as _itemgetter
  13. from keyword import iskeyword as _iskeyword
  14. import sys as _sys
  15.  
  16. def namedtuple(typename, field_names, verbose = False):
  17.     if isinstance(field_names, basestring):
  18.         field_names = field_names.replace(',', ' ').split()
  19.     
  20.     field_names = tuple(map(str, field_names))
  21.     for name in (typename,) + field_names:
  22.         if not all((lambda .0: for c in .0:
  23. if not c.isalnum():
  24. passc == '_')(name)):
  25.             raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
  26.         all((lambda .0: for c in .0:
  27. if not c.isalnum():
  28. passc == '_')(name))
  29.         if _iskeyword(name):
  30.             raise ValueError('Type names and field names cannot be a keyword: %r' % name)
  31.         _iskeyword(name)
  32.         if name[0].isdigit():
  33.             raise ValueError('Type names and field names cannot start with a number: %r' % name)
  34.         name[0].isdigit()
  35.     
  36.     seen_names = set()
  37.     for name in field_names:
  38.         if name.startswith('_'):
  39.             raise ValueError('Field names cannot start with an underscore: %r' % name)
  40.         name.startswith('_')
  41.         if name in seen_names:
  42.             raise ValueError('Encountered duplicate field name: %r' % name)
  43.         name in seen_names
  44.         seen_names.add(name)
  45.     
  46.     numfields = len(field_names)
  47.     argtxt = repr(field_names).replace("'", '')[1:-1]
  48.     reprtxt = ', '.join((lambda .0: for name in .0:
  49. '%s=%%r' % name)(field_names))
  50.     dicttxt = ', '.join((lambda .0: for pos, name in .0:
  51. '%r: t[%d]' % (name, pos))(enumerate(field_names)))
  52.     template = "class %(typename)s(tuple):\n        '%(typename)s(%(argtxt)s)' \n\n        __slots__ = () \n\n        _fields = %(field_names)r \n\n        def __new__(_cls, %(argtxt)s):\n            return _tuple.__new__(_cls, (%(argtxt)s)) \n\n        @classmethod\n        def _make(cls, iterable, new=tuple.__new__, len=len):\n            'Make a new %(typename)s object from a sequence or iterable'\n            result = new(cls, iterable)\n            if len(result) != %(numfields)d:\n                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))\n            return result \n\n        def __repr__(self):\n            return '%(typename)s(%(reprtxt)s)' %% self \n\n        def _asdict(t):\n            'Return a new dict which maps field names to their values'\n            return {%(dicttxt)s} \n\n        def _replace(_self, **kwds):\n            'Return a new %(typename)s object replacing specified fields with new values'\n            result = _self._make(map(kwds.pop, %(field_names)r, _self))\n            if kwds:\n                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())\n            return result \n\n        def __getnewargs__(self):\n            return tuple(self) \n\n" % locals()
  53.     for i, name in enumerate(field_names):
  54.         template += '        %s = _property(_itemgetter(%d))\n' % (name, i)
  55.     
  56.     if verbose:
  57.         print template
  58.     
  59.     namespace = dict(_itemgetter = _itemgetter, __name__ = 'namedtuple_%s' % typename, _property = property, _tuple = tuple)
  60.     
  61.     try:
  62.         exec template in namespace
  63.     except SyntaxError:
  64.         e = None
  65.         raise SyntaxError(e.message + ':\n' + template)
  66.  
  67.     result = namespace[typename]
  68.     if hasattr(_sys, '_getframe'):
  69.         result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
  70.     
  71.     return result
  72.  
  73. if __name__ == '__main__':
  74.     from cPickle import loads, dumps
  75.     Point = namedtuple('Point', 'x, y', True)
  76.     p = Point(x = 10, y = 20)
  77.     
  78.     class Point(namedtuple('Point', 'x y')):
  79.         __slots__ = ()
  80.         
  81.         def hypot(self):
  82.             return (self.x ** 2 + self.y ** 2) ** 0.5
  83.  
  84.         hypot = property(hypot)
  85.         
  86.         def __str__(self):
  87.             return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
  88.  
  89.  
  90.     for p in (Point(3, 4), Point(14, 5 / 7)):
  91.         print p
  92.     
  93.     
  94.     class Point(namedtuple('Point', 'x y')):
  95.         __slots__ = ()
  96.         _make = classmethod(tuple.__new__)
  97.         
  98.         def _replace(self, _map = map, **kwds):
  99.             return self._make(_map(kwds.get, ('x', 'y'), self))
  100.  
  101.  
  102.     print Point(11, 22)._replace(x = 100)
  103.     Point3D = namedtuple('Point3D', Point._fields + ('z',))
  104.     print Point3D.__doc__
  105.     import doctest
  106.     TestResults = namedtuple('TestResults', 'failed attempted')
  107.     print TestResults(*doctest.testmod())
  108.  
  109.