string.py 10 KB

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