string.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """A collection of string constants.
  2. Public module variables:
  3. whitespace -- a string containing all ASCII whitespace
  4. ascii_lowercase -- a string containing all ASCII lowercase letters
  5. ascii_uppercase -- a string containing all ASCII uppercase letters
  6. ascii_letters -- a string containing all ASCII letters
  7. digits -- a string containing all ASCII decimal digits
  8. hexdigits -- a string containing all ASCII hexadecimal digits
  9. octdigits -- a string containing all ASCII octal digits
  10. punctuation -- a string containing all ASCII punctuation characters
  11. printable -- a string containing all ASCII characters considered printable
  12. """
  13. __all__ = ["ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords",
  14. "digits", "hexdigits", "octdigits", "printable", "punctuation",
  15. "whitespace", "Formatter", "Template"]
  16. import _string
  17. # Some strings for ctype-style character classification
  18. whitespace = ' \t\n\r\v\f'
  19. ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
  20. ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  21. ascii_letters = ascii_lowercase + ascii_uppercase
  22. digits = '0123456789'
  23. hexdigits = digits + 'abcdef' + 'ABCDEF'
  24. octdigits = '01234567'
  25. punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  26. printable = digits + ascii_letters + punctuation + whitespace
  27. # Functions which aren't available as string methods.
  28. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
  29. def capwords(s, sep=None):
  30. """capwords(s [,sep]) -> string
  31. Split the argument into words using split, capitalize each
  32. word using capitalize, and join the capitalized words using
  33. join. If the optional second argument sep is absent or None,
  34. runs of whitespace characters are replaced by a single space
  35. and leading and trailing whitespace are removed, otherwise
  36. sep is used to split and join the words.
  37. """
  38. return (sep or ' ').join(x.capitalize() for x in s.split(sep))
  39. ####################################################################
  40. import re as _re
  41. from collections import ChainMap as _ChainMap
  42. class _TemplateMetaclass(type):
  43. pattern = r"""
  44. %(delim)s(?:
  45. (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
  46. (?P<named>%(id)s) | # delimiter and a Python identifier
  47. {(?P<braced>%(id)s)} | # delimiter and a braced identifier
  48. (?P<invalid>) # Other ill-formed delimiter exprs
  49. )
  50. """
  51. def __init__(cls, name, bases, dct):
  52. super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  53. if 'pattern' in dct:
  54. pattern = cls.pattern
  55. else:
  56. pattern = _TemplateMetaclass.pattern % {
  57. 'delim' : _re.escape(cls.delimiter),
  58. 'id' : cls.idpattern,
  59. }
  60. cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)
  61. class Template(metaclass=_TemplateMetaclass):
  62. """A string class for supporting $-substitutions."""
  63. delimiter = '$'
  64. idpattern = r'[_a-z][_a-z0-9]*'
  65. flags = _re.IGNORECASE
  66. def __init__(self, template):
  67. self.template = template
  68. # Search for $$, $identifier, ${identifier}, and any bare $'s
  69. def _invalid(self, mo):
  70. i = mo.start('invalid')
  71. lines = self.template[:i].splitlines(keepends=True)
  72. if not lines:
  73. colno = 1
  74. lineno = 1
  75. else:
  76. colno = i - len(''.join(lines[:-1]))
  77. lineno = len(lines)
  78. raise ValueError('Invalid placeholder in string: line %d, col %d' %
  79. (lineno, colno))
  80. def substitute(*args, **kws):
  81. if not args:
  82. raise TypeError("descriptor 'substitute' of 'Template' object "
  83. "needs an argument")
  84. self, *args = args # allow the "self" keyword be passed
  85. if len(args) > 1:
  86. raise TypeError('Too many positional arguments')
  87. if not args:
  88. mapping = kws
  89. elif kws:
  90. mapping = _ChainMap(kws, args[0])
  91. else:
  92. mapping = args[0]
  93. # Helper function for .sub()
  94. def convert(mo):
  95. # Check the most common path first.
  96. named = mo.group('named') or mo.group('braced')
  97. if named is not None:
  98. val = mapping[named]
  99. # We use this idiom instead of str() because the latter will
  100. # fail if val is a Unicode containing non-ASCII characters.
  101. return '%s' % (val,)
  102. if mo.group('escaped') is not None:
  103. return self.delimiter
  104. if mo.group('invalid') is not None:
  105. self._invalid(mo)
  106. raise ValueError('Unrecognized named group in pattern',
  107. self.pattern)
  108. return self.pattern.sub(convert, self.template)
  109. def safe_substitute(*args, **kws):
  110. if not args:
  111. raise TypeError("descriptor 'safe_substitute' of 'Template' object "
  112. "needs an argument")
  113. self, *args = args # allow the "self" keyword be passed
  114. if len(args) > 1:
  115. raise TypeError('Too many positional arguments')
  116. if not args:
  117. mapping = kws
  118. elif kws:
  119. mapping = _ChainMap(kws, args[0])
  120. else:
  121. mapping = args[0]
  122. # Helper function for .sub()
  123. def convert(mo):
  124. named = mo.group('named') or mo.group('braced')
  125. if named is not None:
  126. try:
  127. # We use this idiom instead of str() because the latter
  128. # will fail if val is a Unicode containing non-ASCII
  129. return '%s' % (mapping[named],)
  130. except KeyError:
  131. return mo.group()
  132. if mo.group('escaped') is not None:
  133. return self.delimiter
  134. if mo.group('invalid') is not None:
  135. return mo.group()
  136. raise ValueError('Unrecognized named group in pattern',
  137. self.pattern)
  138. return self.pattern.sub(convert, self.template)
  139. ########################################################################
  140. # the Formatter class
  141. # see PEP 3101 for details and purpose of this class
  142. # The hard parts are reused from the C implementation. They're exposed as "_"
  143. # prefixed methods of str.
  144. # The overall parser is implemented in _string.formatter_parser.
  145. # The field name parser is implemented in _string.formatter_field_name_split
  146. class Formatter:
  147. def format(*args, **kwargs):
  148. if not args:
  149. raise TypeError("descriptor 'format' of 'Formatter' object "
  150. "needs an argument")
  151. self, *args = args # allow the "self" keyword be passed
  152. try:
  153. format_string, *args = args # allow the "format_string" keyword be passed
  154. except ValueError:
  155. if 'format_string' in kwargs:
  156. format_string = kwargs.pop('format_string')
  157. import warnings
  158. warnings.warn("Passing 'format_string' as keyword argument is "
  159. "deprecated", DeprecationWarning, stacklevel=2)
  160. else:
  161. raise TypeError("format() missing 1 required positional "
  162. "argument: 'format_string'") from None
  163. return self.vformat(format_string, args, kwargs)
  164. def vformat(self, format_string, args, kwargs):
  165. used_args = set()
  166. result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
  167. self.check_unused_args(used_args, args, kwargs)
  168. return result
  169. def _vformat(self, format_string, args, kwargs, used_args, recursion_depth,
  170. auto_arg_index=0):
  171. if recursion_depth < 0:
  172. raise ValueError('Max string recursion exceeded')
  173. result = []
  174. for literal_text, field_name, format_spec, conversion in \
  175. self.parse(format_string):
  176. # output the literal text
  177. if literal_text:
  178. result.append(literal_text)
  179. # if there's a field, output it
  180. if field_name is not None:
  181. # this is some markup, find the object and do
  182. # the formatting
  183. # handle arg indexing when empty field_names are given.
  184. if field_name == '':
  185. if auto_arg_index is False:
  186. raise ValueError('cannot switch from manual field '
  187. 'specification to automatic field '
  188. 'numbering')
  189. field_name = str(auto_arg_index)
  190. auto_arg_index += 1
  191. elif field_name.isdigit():
  192. if auto_arg_index:
  193. raise ValueError('cannot switch from manual field '
  194. 'specification to automatic field '
  195. 'numbering')
  196. # disable auto arg incrementing, if it gets
  197. # used later on, then an exception will be raised
  198. auto_arg_index = False
  199. # given the field_name, find the object it references
  200. # and the argument it came from
  201. obj, arg_used = self.get_field(field_name, args, kwargs)
  202. used_args.add(arg_used)
  203. # do any conversion on the resulting object
  204. obj = self.convert_field(obj, conversion)
  205. # expand the format spec, if needed
  206. format_spec, auto_arg_index = self._vformat(
  207. format_spec, args, kwargs,
  208. used_args, recursion_depth-1,
  209. auto_arg_index=auto_arg_index)
  210. # format the object and append to the result
  211. result.append(self.format_field(obj, format_spec))
  212. return ''.join(result), auto_arg_index
  213. def get_value(self, key, args, kwargs):
  214. if isinstance(key, int):
  215. return args[key]
  216. else:
  217. return kwargs[key]
  218. def check_unused_args(self, used_args, args, kwargs):
  219. pass
  220. def format_field(self, value, format_spec):
  221. return format(value, format_spec)
  222. def convert_field(self, value, conversion):
  223. # do any conversion on the resulting object
  224. if conversion is None:
  225. return value
  226. elif conversion == 's':
  227. return str(value)
  228. elif conversion == 'r':
  229. return repr(value)
  230. elif conversion == 'a':
  231. return ascii(value)
  232. raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
  233. # returns an iterable that contains tuples of the form:
  234. # (literal_text, field_name, format_spec, conversion)
  235. # literal_text can be zero length
  236. # field_name can be None, in which case there's no
  237. # object to format and output
  238. # if field_name is not None, it is looked up, formatted
  239. # with format_spec and conversion and then used
  240. def parse(self, format_string):
  241. return _string.formatter_parser(format_string)
  242. # given a field_name, find the object it references.
  243. # field_name: the field being looked up, e.g. "0.name"
  244. # or "lookup[3]"
  245. # used_args: a set of which args have been used
  246. # args, kwargs: as passed in to vformat
  247. def get_field(self, field_name, args, kwargs):
  248. first, rest = _string.formatter_field_name_split(field_name)
  249. obj = self.get_value(first, args, kwargs)
  250. # loop through the rest of the field_name, doing
  251. # getattr or getitem as needed
  252. for is_attr, i in rest:
  253. if is_attr:
  254. obj = getattr(obj, i)
  255. else:
  256. obj = obj[i]
  257. return obj, first