PageRenderTime 1163ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/batch_submit/pymodules/python2.7/lib/python/pysam-0.7.5-py2.7-linux-x86_64.egg/pysam/namedtuple.py

https://gitlab.com/pooja043/Globus_Docker
Python | 117 lines | 114 code | 1 blank | 2 comment | 6 complexity | 4a68bc5ad706f87bf4c1502500e727ac MD5 | raw file
  1. from operator import itemgetter as _itemgetter
  2. from keyword import iskeyword as _iskeyword
  3. import sys as _sys
  4. def namedtuple(typename, field_names, verbose=False, rename=False):
  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. if rename:
  31. names = list(field_names)
  32. seen = set()
  33. for i, name in enumerate(names):
  34. if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
  35. or not name or name[0].isdigit() or name.startswith('_')
  36. or name in seen):
  37. names[i] = '_%d' % i
  38. seen.add(name)
  39. field_names = tuple(names)
  40. for name in (typename,) + field_names:
  41. if not min(c.isalnum() or c=='_' for c in name):
  42. raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
  43. if _iskeyword(name):
  44. raise ValueError('Type names and field names cannot be a keyword: %r' % name)
  45. if name[0].isdigit():
  46. raise ValueError('Type names and field names cannot start with a 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' % name)
  51. if name in seen_names:
  52. raise ValueError('Encountered duplicate field name: %r' % name)
  53. seen_names.add(name)
  54. # Create and fill-in the class template
  55. numfields = len(field_names)
  56. argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
  57. reprtxt = ', '.join('%s=%%r' % name for name in field_names)
  58. template = '''class %(typename)s(tuple):
  59. '%(typename)s(%(argtxt)s)' \n
  60. __slots__ = () \n
  61. _fields = %(field_names)r \n
  62. def __new__(_cls, %(argtxt)s):
  63. return _tuple.__new__(_cls, (%(argtxt)s)) \n
  64. @classmethod
  65. def _make(cls, iterable, new=tuple.__new__, len=len):
  66. 'Make a new %(typename)s object from a sequence or iterable'
  67. result = new(cls, iterable)
  68. if len(result) != %(numfields)d:
  69. raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
  70. return result \n
  71. def __repr__(self):
  72. return '%(typename)s(%(reprtxt)s)' %% self \n
  73. def _asdict(self):
  74. 'Return a new dict which maps field names to their values'
  75. return dict(zip(self._fields, self)) \n
  76. def _replace(_self, **kwds):
  77. 'Return a new %(typename)s object replacing specified fields with new values'
  78. result = _self._make(map(kwds.pop, %(field_names)r, _self))
  79. if kwds:
  80. raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
  81. return result \n
  82. def __getnewargs__(self):
  83. return tuple(self) \n\n''' % locals()
  84. for i, name in enumerate(field_names):
  85. template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
  86. if verbose:
  87. print template
  88. # Execute the template string in a temporary namespace
  89. namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
  90. _property=property, _tuple=tuple)
  91. try:
  92. exec template in namespace
  93. except SyntaxError, e:
  94. raise SyntaxError(e.message + ':\n' + template)
  95. result = namespace[typename]
  96. # For pickling to work, the __module__ variable needs to be set to the frame
  97. # where the named tuple is created. Bypass this step in enviroments where
  98. # sys._getframe is not defined (Jython for example) or sys._getframe is not
  99. # defined for arguments greater than 0 (IronPython).
  100. try:
  101. result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
  102. except (AttributeError, ValueError):
  103. pass
  104. return result