string.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  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>%(bid)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. 'bid' : cls.braceidpattern or cls.idpattern,
  60. }
  61. cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)
  62. class Template(metaclass=_TemplateMetaclass):
  63. """A string class for supporting $-substitutions."""
  64. delimiter = '$'
  65. # r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, but
  66. # without the ASCII flag. We can't add re.ASCII to flags because of
  67. # backward compatibility. So we use the ?a local flag and [a-z] pattern.
  68. # See https://bugs.python.org/issue31672
  69. idpattern = r'(?a:[_a-z][_a-z0-9]*)'
  70. braceidpattern = None
  71. flags = _re.IGNORECASE
  72. def __init__(self, template):
  73. self.template = template
  74. # Search for $$, $identifier, ${identifier}, and any bare $'s
  75. def _invalid(self, mo):
  76. i = mo.start('invalid')
  77. lines = self.template[:i].splitlines(keepends=True)
  78. if not lines:
  79. colno = 1
  80. lineno = 1
  81. else:
  82. colno = i - len(''.join(lines[:-1]))
  83. lineno = len(lines)
  84. raise ValueError('Invalid placeholder in string: line %d, col %d' %
  85. (lineno, colno))
  86. def substitute(*args, **kws):
  87. if not args:
  88. raise TypeError("descriptor 'substitute' of 'Template' object "
  89. "needs an argument")
  90. self, *args = args # allow the "self" keyword be passed
  91. if len(args) > 1:
  92. raise TypeError('Too many positional arguments')
  93. if not args:
  94. mapping = kws
  95. elif kws:
  96. mapping = _ChainMap(kws, args[0])
  97. else:
  98. mapping = args[0]
  99. # Helper function for .sub()
  100. def convert(mo):
  101. # Check the most common path first.
  102. named = mo.group('named') or mo.group('braced')
  103. if named is not None:
  104. return str(mapping[named])
  105. if mo.group('escaped') is not None:
  106. return self.delimiter
  107. if mo.group('invalid') is not None:
  108. self._invalid(mo)
  109. raise ValueError('Unrecognized named group in pattern',
  110. self.pattern)
  111. return self.pattern.sub(convert, self.template)
  112. def safe_substitute(*args, **kws):
  113. if not args:
  114. raise TypeError("descriptor 'safe_substitute' of 'Template' object "
  115. "needs an argument")
  116. self, *args = args # allow the "self" keyword be passed
  117. if len(args) > 1:
  118. raise TypeError('Too many positional arguments')
  119. if not args:
  120. mapping = kws
  121. elif kws:
  122. mapping = _ChainMap(kws, args[0])
  123. else:
  124. mapping = args[0]
  125. # Helper function for .sub()
  126. def convert(mo):
  127. named = mo.group('named') or mo.group('braced')
  128. if named is not None:
  129. try:
  130. return str(mapping[named])
  131. except KeyError:
  132. return mo.group()
  133. if mo.group('escaped') is not None:
  134. return self.delimiter
  135. if mo.group('invalid') is not None:
  136. return mo.group()
  137. raise ValueError('Unrecognized named group in pattern',
  138. self.pattern)
  139. return self.pattern.sub(convert, self.template)
  140. ########################################################################
  141. # the Formatter class
  142. # see PEP 3101 for details and purpose of this class
  143. # The hard parts are reused from the C implementation. They're exposed as "_"
  144. # prefixed methods of str.
  145. # The overall parser is implemented in _string.formatter_parser.
  146. # The field name parser is implemented in _string.formatter_field_name_split
  147. class Formatter:
  148. def format(*args, **kwargs):
  149. if not args:
  150. raise TypeError("descriptor 'format' of 'Formatter' object "
  151. "needs an argument")
  152. self, *args = args # allow the "self" keyword be passed
  153. try:
  154. format_string, *args = args # allow the "format_string" keyword be passed
  155. except ValueError:
  156. raise TypeError("format() missing 1 required positional "
  157. "argument: 'format_string'") from None
  158. return self.vformat(format_string, args, kwargs)
  159. def vformat(self, format_string, args, kwargs):
  160. used_args = set()
  161. result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
  162. self.check_unused_args(used_args, args, kwargs)
  163. return result
  164. def _vformat(self, format_string, args, kwargs, used_args, recursion_depth,
  165. auto_arg_index=0):
  166. if recursion_depth < 0:
  167. raise ValueError('Max string recursion exceeded')
  168. result = []
  169. for literal_text, field_name, format_spec, conversion in \
  170. self.parse(format_string):
  171. # output the literal text
  172. if literal_text:
  173. result.append(literal_text)
  174. # if there's a field, output it
  175. if field_name is not None:
  176. # this is some markup, find the object and do
  177. # the formatting
  178. # handle arg indexing when empty field_names are given.
  179. if field_name == '':
  180. if auto_arg_index is False:
  181. raise ValueError('cannot switch from manual field '
  182. 'specification to automatic field '
  183. 'numbering')
  184. field_name = str(auto_arg_index)
  185. auto_arg_index += 1
  186. elif field_name.isdigit():
  187. if auto_arg_index:
  188. raise ValueError('cannot switch from manual field '
  189. 'specification to automatic field '
  190. 'numbering')
  191. # disable auto arg incrementing, if it gets
  192. # used later on, then an exception will be raised
  193. auto_arg_index = False
  194. # given the field_name, find the object it references
  195. # and the argument it came from
  196. obj, arg_used = self.get_field(field_name, args, kwargs)
  197. used_args.add(arg_used)
  198. # do any conversion on the resulting object
  199. obj = self.convert_field(obj, conversion)
  200. # expand the format spec, if needed
  201. format_spec, auto_arg_index = self._vformat(
  202. format_spec, args, kwargs,
  203. used_args, recursion_depth-1,
  204. auto_arg_index=auto_arg_index)
  205. # format the object and append to the result
  206. result.append(self.format_field(obj, format_spec))
  207. return ''.join(result), auto_arg_index
  208. def get_value(self, key, args, kwargs):
  209. if isinstance(key, int):
  210. return args[key]
  211. else:
  212. return kwargs[key]
  213. def check_unused_args(self, used_args, args, kwargs):
  214. pass
  215. def format_field(self, value, format_spec):
  216. return format(value, format_spec)
  217. def convert_field(self, value, conversion):
  218. # do any conversion on the resulting object
  219. if conversion is None:
  220. return value
  221. elif conversion == 's':
  222. return str(value)
  223. elif conversion == 'r':
  224. return repr(value)
  225. elif conversion == 'a':
  226. return ascii(value)
  227. raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
  228. # returns an iterable that contains tuples of the form:
  229. # (literal_text, field_name, format_spec, conversion)
  230. # literal_text can be zero length
  231. # field_name can be None, in which case there's no
  232. # object to format and output
  233. # if field_name is not None, it is looked up, formatted
  234. # with format_spec and conversion and then used
  235. def parse(self, format_string):
  236. return _string.formatter_parser(format_string)
  237. # given a field_name, find the object it references.
  238. # field_name: the field being looked up, e.g. "0.name"
  239. # or "lookup[3]"
  240. # used_args: a set of which args have been used
  241. # args, kwargs: as passed in to vformat
  242. def get_field(self, field_name, args, kwargs):
  243. first, rest = _string.formatter_field_name_split(field_name)
  244. obj = self.get_value(first, args, kwargs)
  245. # loop through the rest of the field_name, doing
  246. # getattr or getitem as needed
  247. for is_attr, i in rest:
  248. if is_attr:
  249. obj = getattr(obj, i)
  250. else:
  251. obj = obj[i]
  252. return obj, first