blob: 89287c4c0adecb5781b50b13b4a0127d81e725b0 [file] [log] [blame]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001"""A collection of string constants.
Guido van Rossum20032041997-12-29 19:26:28 +00002
3Public module variables:
4
Georg Brandl50767402008-11-22 08:31:09 +00005whitespace -- a string containing all ASCII whitespace
6ascii_lowercase -- a string containing all ASCII lowercase letters
7ascii_uppercase -- a string containing all ASCII uppercase letters
8ascii_letters -- a string containing all ASCII letters
9digits -- a string containing all ASCII decimal digits
10hexdigits -- a string containing all ASCII hexadecimal digits
11octdigits -- a string containing all ASCII octal digits
12punctuation -- a string containing all ASCII punctuation characters
13printable -- a string containing all ASCII characters considered printable
Guido van Rossum20032041997-12-29 19:26:28 +000014
15"""
16
Zachary Warec17a0b82016-06-04 14:35:05 -050017__all__ = ["ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords",
18 "digits", "hexdigits", "octdigits", "printable", "punctuation",
19 "whitespace", "Formatter", "Template"]
20
Georg Brandl66c221e2010-10-14 07:04:07 +000021import _string
22
Guido van Rossumc6360141990-10-13 19:23:40 +000023# Some strings for ctype-style character classification
Guido van Rossum8e2ec561993-07-29 09:37:38 +000024whitespace = ' \t\n\r\v\f'
Martin v. Löwis967f1e32007-08-14 09:23:10 +000025ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
26ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Fred Drake960fdf92001-07-20 18:38:26 +000027ascii_letters = ascii_lowercase + ascii_uppercase
Guido van Rossumc6360141990-10-13 19:23:40 +000028digits = '0123456789'
29hexdigits = digits + 'abcdef' + 'ABCDEF'
30octdigits = '01234567'
Tim Peters495ad3c2001-01-15 01:36:40 +000031punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
Martin v. Löwis967f1e32007-08-14 09:23:10 +000032printable = digits + ascii_letters + punctuation + whitespace
Guido van Rossumc6360141990-10-13 19:23:40 +000033
Barry Warsaw8bee7612004-08-25 02:22:30 +000034# Functions which aren't available as string methods.
35
36# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
Barry Warsaw8bee7612004-08-25 02:22:30 +000037def capwords(s, sep=None):
Ezio Melottia40bdda2009-09-26 12:33:22 +000038 """capwords(s [,sep]) -> string
Barry Warsaw8bee7612004-08-25 02:22:30 +000039
40 Split the argument into words using split, capitalize each
41 word using capitalize, and join the capitalized words using
Ezio Melottia40bdda2009-09-26 12:33:22 +000042 join. If the optional second argument sep is absent or None,
43 runs of whitespace characters are replaced by a single space
44 and leading and trailing whitespace are removed, otherwise
45 sep is used to split and join the words.
Barry Warsaw8bee7612004-08-25 02:22:30 +000046
47 """
Ezio Melottia40bdda2009-09-26 12:33:22 +000048 return (sep or ' ').join(x.capitalize() for x in s.split(sep))
Barry Warsaw8bee7612004-08-25 02:22:30 +000049
50
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000051####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +000052import re as _re
Zachary Warec17a0b82016-06-04 14:35:05 -050053from collections import ChainMap as _ChainMap
Barry Warsaw46b629c2004-09-13 14:35:04 +000054
Barry Warsaw12827c12004-09-10 03:08:08 +000055class _TemplateMetaclass(type):
56 pattern = r"""
Raymond Hettinger55593c32004-09-26 18:56:44 +000057 %(delim)s(?:
58 (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
59 (?P<named>%(id)s) | # delimiter and a Python identifier
60 {(?P<braced>%(id)s)} | # delimiter and a braced identifier
61 (?P<invalid>) # Other ill-formed delimiter exprs
62 )
Barry Warsaw12827c12004-09-10 03:08:08 +000063 """
64
65 def __init__(cls, name, bases, dct):
66 super(_TemplateMetaclass, cls).__init__(name, bases, dct)
67 if 'pattern' in dct:
68 pattern = cls.pattern
69 else:
70 pattern = _TemplateMetaclass.pattern % {
Barry Warsaw17cb6002004-09-18 00:06:34 +000071 'delim' : _re.escape(cls.delimiter),
Barry Warsaw12827c12004-09-10 03:08:08 +000072 'id' : cls.idpattern,
73 }
Georg Brandl056cb932010-07-29 17:16:10 +000074 cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)
Barry Warsaw12827c12004-09-10 03:08:08 +000075
76
Guido van Rossum52cc1d82007-03-18 15:41:51 +000077class Template(metaclass=_TemplateMetaclass):
Barry Warsaw8bee7612004-08-25 02:22:30 +000078 """A string class for supporting $-substitutions."""
Barry Warsaw12827c12004-09-10 03:08:08 +000079
Barry Warsaw17cb6002004-09-18 00:06:34 +000080 delimiter = '$'
Barry Warsaw12827c12004-09-10 03:08:08 +000081 idpattern = r'[_a-z][_a-z0-9]*'
Georg Brandl056cb932010-07-29 17:16:10 +000082 flags = _re.IGNORECASE
Barry Warsaw12827c12004-09-10 03:08:08 +000083
84 def __init__(self, template):
85 self.template = template
Barry Warsaw8bee7612004-08-25 02:22:30 +000086
87 # Search for $$, $identifier, ${identifier}, and any bare $'s
Barry Warsaw8bee7612004-08-25 02:22:30 +000088
Barry Warsawb5c6b5b2004-09-13 20:52:50 +000089 def _invalid(self, mo):
90 i = mo.start('invalid')
Ezio Melottid8b509b2011-09-28 17:37:55 +030091 lines = self.template[:i].splitlines(keepends=True)
Barry Warsaw12827c12004-09-10 03:08:08 +000092 if not lines:
93 colno = 1
94 lineno = 1
95 else:
96 colno = i - len(''.join(lines[:-1]))
97 lineno = len(lines)
98 raise ValueError('Invalid placeholder in string: line %d, col %d' %
99 (lineno, colno))
100
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200101 def substitute(*args, **kws):
102 if not args:
103 raise TypeError("descriptor 'substitute' of 'Template' object "
104 "needs an argument")
105 self, *args = args # allow the "self" keyword be passed
Barry Warsawb6234a92004-09-13 15:25:15 +0000106 if len(args) > 1:
107 raise TypeError('Too many positional arguments')
108 if not args:
109 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000110 elif kws:
Zachary Warec17a0b82016-06-04 14:35:05 -0500111 mapping = _ChainMap(kws, args[0])
Barry Warsawb6234a92004-09-13 15:25:15 +0000112 else:
113 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000114 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000115 def convert(mo):
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000116 # Check the most common path first.
117 named = mo.group('named') or mo.group('braced')
118 if named is not None:
Yury Selivanov7aa53412015-05-30 10:57:56 -0400119 val = mapping[named]
120 # We use this idiom instead of str() because the latter will
121 # fail if val is a Unicode containing non-ASCII characters.
122 return '%s' % (val,)
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000123 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000124 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000125 if mo.group('invalid') is not None:
126 self._invalid(mo)
Neal Norwitz6627a962004-10-17 16:27:18 +0000127 raise ValueError('Unrecognized named group in pattern',
128 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000129 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000130
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200131 def safe_substitute(*args, **kws):
132 if not args:
133 raise TypeError("descriptor 'safe_substitute' of 'Template' object "
134 "needs an argument")
135 self, *args = args # allow the "self" keyword be passed
Barry Warsawb6234a92004-09-13 15:25:15 +0000136 if len(args) > 1:
137 raise TypeError('Too many positional arguments')
138 if not args:
139 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000140 elif kws:
Zachary Warec17a0b82016-06-04 14:35:05 -0500141 mapping = _ChainMap(kws, args[0])
Barry Warsawb6234a92004-09-13 15:25:15 +0000142 else:
143 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000144 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000145 def convert(mo):
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000146 named = mo.group('named') or mo.group('braced')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000147 if named is not None:
148 try:
Yury Selivanov7aa53412015-05-30 10:57:56 -0400149 # We use this idiom instead of str() because the latter
150 # will fail if val is a Unicode containing non-ASCII
151 return '%s' % (mapping[named],)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000152 except KeyError:
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000153 return mo.group()
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000154 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000155 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000156 if mo.group('invalid') is not None:
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000157 return mo.group()
Neal Norwitz6627a962004-10-17 16:27:18 +0000158 raise ValueError('Unrecognized named group in pattern',
159 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000160 return self.pattern.sub(convert, self.template)
Eric Smith8c663262007-08-25 02:26:07 +0000161
162
163
164########################################################################
165# the Formatter class
166# see PEP 3101 for details and purpose of this class
167
Benjamin Petersonf608c612008-11-16 18:33:53 +0000168# The hard parts are reused from the C implementation. They're exposed as "_"
Florent Xicluna7b2a7712010-09-06 20:27:55 +0000169# prefixed methods of str.
Eric Smith8c663262007-08-25 02:26:07 +0000170
Georg Brandl66c221e2010-10-14 07:04:07 +0000171# The overall parser is implemented in _string.formatter_parser.
172# The field name parser is implemented in _string.formatter_field_name_split
Eric Smith8c663262007-08-25 02:26:07 +0000173
174class Formatter:
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200175 def format(*args, **kwargs):
176 if not args:
177 raise TypeError("descriptor 'format' of 'Formatter' object "
178 "needs an argument")
179 self, *args = args # allow the "self" keyword be passed
180 try:
181 format_string, *args = args # allow the "format_string" keyword be passed
182 except ValueError:
183 if 'format_string' in kwargs:
184 format_string = kwargs.pop('format_string')
Serhiy Storchakab876df42015-03-24 22:30:46 +0200185 import warnings
186 warnings.warn("Passing 'format_string' as keyword argument is "
187 "deprecated", DeprecationWarning, stacklevel=2)
Serhiy Storchaka8ffe9172015-03-24 22:28:43 +0200188 else:
189 raise TypeError("format() missing 1 required positional "
190 "argument: 'format_string'") from None
Eric Smith8c663262007-08-25 02:26:07 +0000191 return self.vformat(format_string, args, kwargs)
192
193 def vformat(self, format_string, args, kwargs):
Eric Smith3bcc42a2007-08-31 02:26:31 +0000194 used_args = set()
Eric V. Smith85976b12015-09-29 10:27:38 -0400195 result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
Eric Smith11529192007-09-04 23:04:22 +0000196 self.check_unused_args(used_args, args, kwargs)
197 return result
198
Eric V. Smith7ce90742014-04-14 16:43:50 -0400199 def _vformat(self, format_string, args, kwargs, used_args, recursion_depth,
200 auto_arg_index=0):
Eric Smith11529192007-09-04 23:04:22 +0000201 if recursion_depth < 0:
202 raise ValueError('Max string recursion exceeded')
Eric Smith8c663262007-08-25 02:26:07 +0000203 result = []
Eric Smith9e7c8da2007-08-28 11:15:20 +0000204 for literal_text, field_name, format_spec, conversion in \
205 self.parse(format_string):
Eric Smith625cbf22007-08-29 03:22:59 +0000206
207 # output the literal text
208 if literal_text:
209 result.append(literal_text)
210
211 # if there's a field, output it
212 if field_name is not None:
Eric Smith9e7c8da2007-08-28 11:15:20 +0000213 # this is some markup, find the object and do
214 # the formatting
215
Eric V. Smith7ce90742014-04-14 16:43:50 -0400216 # handle arg indexing when empty field_names are given.
217 if field_name == '':
218 if auto_arg_index is False:
219 raise ValueError('cannot switch from manual field '
220 'specification to automatic field '
221 'numbering')
222 field_name = str(auto_arg_index)
223 auto_arg_index += 1
224 elif field_name.isdigit():
225 if auto_arg_index:
226 raise ValueError('cannot switch from manual field '
227 'specification to automatic field '
228 'numbering')
229 # disable auto arg incrementing, if it gets
230 # used later on, then an exception will be raised
231 auto_arg_index = False
232
Eric Smith7ade6482007-08-26 22:27:13 +0000233 # given the field_name, find the object it references
Eric Smith3bcc42a2007-08-31 02:26:31 +0000234 # and the argument it came from
Eric Smith9d4ba392007-09-02 15:33:26 +0000235 obj, arg_used = self.get_field(field_name, args, kwargs)
Eric Smith3bcc42a2007-08-31 02:26:31 +0000236 used_args.add(arg_used)
Eric Smith7ade6482007-08-26 22:27:13 +0000237
238 # do any conversion on the resulting object
Eric Smith9e7c8da2007-08-28 11:15:20 +0000239 obj = self.convert_field(obj, conversion)
Eric Smith7ade6482007-08-26 22:27:13 +0000240
Eric Smith11529192007-09-04 23:04:22 +0000241 # expand the format spec, if needed
Eric V. Smith85976b12015-09-29 10:27:38 -0400242 format_spec, auto_arg_index = self._vformat(
243 format_spec, args, kwargs,
244 used_args, recursion_depth-1,
245 auto_arg_index=auto_arg_index)
Eric Smith11529192007-09-04 23:04:22 +0000246
Eric Smith7ade6482007-08-26 22:27:13 +0000247 # format the object and append to the result
248 result.append(self.format_field(obj, format_spec))
Eric Smith625cbf22007-08-29 03:22:59 +0000249
Eric V. Smith85976b12015-09-29 10:27:38 -0400250 return ''.join(result), auto_arg_index
Eric Smith8c663262007-08-25 02:26:07 +0000251
Eric Smith9e7c8da2007-08-28 11:15:20 +0000252
Eric Smith8c663262007-08-25 02:26:07 +0000253 def get_value(self, key, args, kwargs):
Eric Smith7ade6482007-08-26 22:27:13 +0000254 if isinstance(key, int):
255 return args[key]
256 else:
257 return kwargs[key]
Eric Smith8c663262007-08-25 02:26:07 +0000258
Eric Smith9e7c8da2007-08-28 11:15:20 +0000259
Eric Smith8c663262007-08-25 02:26:07 +0000260 def check_unused_args(self, used_args, args, kwargs):
261 pass
262
Eric Smith9e7c8da2007-08-28 11:15:20 +0000263
Eric Smith8c663262007-08-25 02:26:07 +0000264 def format_field(self, value, format_spec):
Eric Smith7ade6482007-08-26 22:27:13 +0000265 return format(value, format_spec)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000266
267
268 def convert_field(self, value, conversion):
269 # do any conversion on the resulting object
R David Murraye56bf972012-08-19 17:26:34 -0400270 if conversion is None:
271 return value
Eric Smith9e7c8da2007-08-28 11:15:20 +0000272 elif conversion == 's':
273 return str(value)
R David Murraye56bf972012-08-19 17:26:34 -0400274 elif conversion == 'r':
275 return repr(value)
276 elif conversion == 'a':
277 return ascii(value)
Florent Xicluna7b2a7712010-09-06 20:27:55 +0000278 raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
Eric Smith9e7c8da2007-08-28 11:15:20 +0000279
280
281 # returns an iterable that contains tuples of the form:
282 # (literal_text, field_name, format_spec, conversion)
Eric Smith625cbf22007-08-29 03:22:59 +0000283 # literal_text can be zero length
284 # field_name can be None, in which case there's no
285 # object to format and output
286 # if field_name is not None, it is looked up, formatted
287 # with format_spec and conversion and then used
Eric Smith9e7c8da2007-08-28 11:15:20 +0000288 def parse(self, format_string):
Georg Brandl66c221e2010-10-14 07:04:07 +0000289 return _string.formatter_parser(format_string)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000290
291
292 # given a field_name, find the object it references.
293 # field_name: the field being looked up, e.g. "0.name"
294 # or "lookup[3]"
295 # used_args: a set of which args have been used
296 # args, kwargs: as passed in to vformat
Eric Smith9d4ba392007-09-02 15:33:26 +0000297 def get_field(self, field_name, args, kwargs):
Georg Brandl66c221e2010-10-14 07:04:07 +0000298 first, rest = _string.formatter_field_name_split(field_name)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000299
Eric Smith9e7c8da2007-08-28 11:15:20 +0000300 obj = self.get_value(first, args, kwargs)
301
302 # loop through the rest of the field_name, doing
303 # getattr or getitem as needed
304 for is_attr, i in rest:
305 if is_attr:
306 obj = getattr(obj, i)
307 else:
308 obj = obj[i]
309
Eric Smith3bcc42a2007-08-31 02:26:31 +0000310 return obj, first