blob: d4f9cd93554f3cc9191565c45e8e9e89cd13e06d [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
Georg Brandl66c221e2010-10-14 07:04:07 +000017import _string
18
Guido van Rossumc6360141990-10-13 19:23:40 +000019# Some strings for ctype-style character classification
Guido van Rossum8e2ec561993-07-29 09:37:38 +000020whitespace = ' \t\n\r\v\f'
Martin v. Löwis967f1e32007-08-14 09:23:10 +000021ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
22ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Fred Drake960fdf92001-07-20 18:38:26 +000023ascii_letters = ascii_lowercase + ascii_uppercase
Guido van Rossumc6360141990-10-13 19:23:40 +000024digits = '0123456789'
25hexdigits = digits + 'abcdef' + 'ABCDEF'
26octdigits = '01234567'
Tim Peters495ad3c2001-01-15 01:36:40 +000027punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
Martin v. Löwis967f1e32007-08-14 09:23:10 +000028printable = digits + ascii_letters + punctuation + whitespace
Guido van Rossumc6360141990-10-13 19:23:40 +000029
Barry Warsaw8bee7612004-08-25 02:22:30 +000030# Functions which aren't available as string methods.
31
32# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
Barry Warsaw8bee7612004-08-25 02:22:30 +000033def capwords(s, sep=None):
Ezio Melottia40bdda2009-09-26 12:33:22 +000034 """capwords(s [,sep]) -> string
Barry Warsaw8bee7612004-08-25 02:22:30 +000035
36 Split the argument into words using split, capitalize each
37 word using capitalize, and join the capitalized words using
Ezio Melottia40bdda2009-09-26 12:33:22 +000038 join. If the optional second argument sep is absent or None,
39 runs of whitespace characters are replaced by a single space
40 and leading and trailing whitespace are removed, otherwise
41 sep is used to split and join the words.
Barry Warsaw8bee7612004-08-25 02:22:30 +000042
43 """
Ezio Melottia40bdda2009-09-26 12:33:22 +000044 return (sep or ' ').join(x.capitalize() for x in s.split(sep))
Barry Warsaw8bee7612004-08-25 02:22:30 +000045
46
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000047####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +000048import re as _re
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +000049from collections import ChainMap
Barry Warsaw46b629c2004-09-13 14:35:04 +000050
Barry Warsaw12827c12004-09-10 03:08:08 +000051class _TemplateMetaclass(type):
52 pattern = r"""
Raymond Hettinger55593c32004-09-26 18:56:44 +000053 %(delim)s(?:
54 (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
55 (?P<named>%(id)s) | # delimiter and a Python identifier
56 {(?P<braced>%(id)s)} | # delimiter and a braced identifier
57 (?P<invalid>) # Other ill-formed delimiter exprs
58 )
Barry Warsaw12827c12004-09-10 03:08:08 +000059 """
60
61 def __init__(cls, name, bases, dct):
62 super(_TemplateMetaclass, cls).__init__(name, bases, dct)
63 if 'pattern' in dct:
64 pattern = cls.pattern
65 else:
66 pattern = _TemplateMetaclass.pattern % {
Barry Warsaw17cb6002004-09-18 00:06:34 +000067 'delim' : _re.escape(cls.delimiter),
Barry Warsaw12827c12004-09-10 03:08:08 +000068 'id' : cls.idpattern,
69 }
Georg Brandl056cb932010-07-29 17:16:10 +000070 cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)
Barry Warsaw12827c12004-09-10 03:08:08 +000071
72
Guido van Rossum52cc1d82007-03-18 15:41:51 +000073class Template(metaclass=_TemplateMetaclass):
Barry Warsaw8bee7612004-08-25 02:22:30 +000074 """A string class for supporting $-substitutions."""
Barry Warsaw12827c12004-09-10 03:08:08 +000075
Barry Warsaw17cb6002004-09-18 00:06:34 +000076 delimiter = '$'
Barry Warsaw12827c12004-09-10 03:08:08 +000077 idpattern = r'[_a-z][_a-z0-9]*'
Georg Brandl056cb932010-07-29 17:16:10 +000078 flags = _re.IGNORECASE
Barry Warsaw12827c12004-09-10 03:08:08 +000079
80 def __init__(self, template):
81 self.template = template
Barry Warsaw8bee7612004-08-25 02:22:30 +000082
83 # Search for $$, $identifier, ${identifier}, and any bare $'s
Barry Warsaw8bee7612004-08-25 02:22:30 +000084
Barry Warsawb5c6b5b2004-09-13 20:52:50 +000085 def _invalid(self, mo):
86 i = mo.start('invalid')
Barry Warsaw12827c12004-09-10 03:08:08 +000087 lines = self.template[:i].splitlines(True)
88 if not lines:
89 colno = 1
90 lineno = 1
91 else:
92 colno = i - len(''.join(lines[:-1]))
93 lineno = len(lines)
94 raise ValueError('Invalid placeholder in string: line %d, col %d' %
95 (lineno, colno))
96
Barry Warsawb6234a92004-09-13 15:25:15 +000097 def substitute(self, *args, **kws):
98 if len(args) > 1:
99 raise TypeError('Too many positional arguments')
100 if not args:
101 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000102 elif kws:
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +0000103 mapping = ChainMap(kws, args[0])
Barry Warsawb6234a92004-09-13 15:25:15 +0000104 else:
105 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000106 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000107 def convert(mo):
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000108 # Check the most common path first.
109 named = mo.group('named') or mo.group('braced')
110 if named is not None:
111 val = mapping[named]
112 # We use this idiom instead of str() because the latter will
113 # fail if val is a Unicode containing non-ASCII characters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114 return '%s' % (val,)
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000115 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000116 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000117 if mo.group('invalid') is not None:
118 self._invalid(mo)
Neal Norwitz6627a962004-10-17 16:27:18 +0000119 raise ValueError('Unrecognized named group in pattern',
120 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000121 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000122
Barry Warsawb6234a92004-09-13 15:25:15 +0000123 def safe_substitute(self, *args, **kws):
124 if len(args) > 1:
125 raise TypeError('Too many positional arguments')
126 if not args:
127 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000128 elif kws:
Raymond Hettinger9fe1ccf2011-02-26 01:02:51 +0000129 mapping = ChainMap(kws, args[0])
Barry Warsawb6234a92004-09-13 15:25:15 +0000130 else:
131 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000132 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000133 def convert(mo):
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000134 named = mo.group('named') or mo.group('braced')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000135 if named is not None:
136 try:
Barry Warsaw12827c12004-09-10 03:08:08 +0000137 # We use this idiom instead of str() because the latter
138 # will fail if val is a Unicode containing non-ASCII
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 return '%s' % (mapping[named],)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000140 except KeyError:
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000141 return mo.group()
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000142 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000143 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000144 if mo.group('invalid') is not None:
Florent Xiclunaeb19dce2010-09-18 23:34:07 +0000145 return mo.group()
Neal Norwitz6627a962004-10-17 16:27:18 +0000146 raise ValueError('Unrecognized named group in pattern',
147 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000148 return self.pattern.sub(convert, self.template)
Eric Smith8c663262007-08-25 02:26:07 +0000149
150
151
152########################################################################
153# the Formatter class
154# see PEP 3101 for details and purpose of this class
155
Benjamin Petersonf608c612008-11-16 18:33:53 +0000156# The hard parts are reused from the C implementation. They're exposed as "_"
Florent Xicluna7b2a7712010-09-06 20:27:55 +0000157# prefixed methods of str.
Eric Smith8c663262007-08-25 02:26:07 +0000158
Georg Brandl66c221e2010-10-14 07:04:07 +0000159# The overall parser is implemented in _string.formatter_parser.
160# The field name parser is implemented in _string.formatter_field_name_split
Eric Smith8c663262007-08-25 02:26:07 +0000161
162class Formatter:
163 def format(self, format_string, *args, **kwargs):
164 return self.vformat(format_string, args, kwargs)
165
166 def vformat(self, format_string, args, kwargs):
Eric Smith3bcc42a2007-08-31 02:26:31 +0000167 used_args = set()
Eric Smith11529192007-09-04 23:04:22 +0000168 result = self._vformat(format_string, args, kwargs, used_args, 2)
169 self.check_unused_args(used_args, args, kwargs)
170 return result
171
172 def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
173 if recursion_depth < 0:
174 raise ValueError('Max string recursion exceeded')
Eric Smith8c663262007-08-25 02:26:07 +0000175 result = []
Eric Smith9e7c8da2007-08-28 11:15:20 +0000176 for literal_text, field_name, format_spec, conversion in \
177 self.parse(format_string):
Eric Smith625cbf22007-08-29 03:22:59 +0000178
179 # output the literal text
180 if literal_text:
181 result.append(literal_text)
182
183 # if there's a field, output it
184 if field_name is not None:
Eric Smith9e7c8da2007-08-28 11:15:20 +0000185 # this is some markup, find the object and do
186 # the formatting
187
Eric Smith7ade6482007-08-26 22:27:13 +0000188 # given the field_name, find the object it references
Eric Smith3bcc42a2007-08-31 02:26:31 +0000189 # and the argument it came from
Eric Smith9d4ba392007-09-02 15:33:26 +0000190 obj, arg_used = self.get_field(field_name, args, kwargs)
Eric Smith3bcc42a2007-08-31 02:26:31 +0000191 used_args.add(arg_used)
Eric Smith7ade6482007-08-26 22:27:13 +0000192
193 # do any conversion on the resulting object
Eric Smith9e7c8da2007-08-28 11:15:20 +0000194 obj = self.convert_field(obj, conversion)
Eric Smith7ade6482007-08-26 22:27:13 +0000195
Eric Smith11529192007-09-04 23:04:22 +0000196 # expand the format spec, if needed
197 format_spec = self._vformat(format_spec, args, kwargs,
198 used_args, recursion_depth-1)
199
Eric Smith7ade6482007-08-26 22:27:13 +0000200 # format the object and append to the result
201 result.append(self.format_field(obj, format_spec))
Eric Smith625cbf22007-08-29 03:22:59 +0000202
Eric Smith8c663262007-08-25 02:26:07 +0000203 return ''.join(result)
204
Eric Smith9e7c8da2007-08-28 11:15:20 +0000205
Eric Smith8c663262007-08-25 02:26:07 +0000206 def get_value(self, key, args, kwargs):
Eric Smith7ade6482007-08-26 22:27:13 +0000207 if isinstance(key, int):
208 return args[key]
209 else:
210 return kwargs[key]
Eric Smith8c663262007-08-25 02:26:07 +0000211
Eric Smith9e7c8da2007-08-28 11:15:20 +0000212
Eric Smith8c663262007-08-25 02:26:07 +0000213 def check_unused_args(self, used_args, args, kwargs):
214 pass
215
Eric Smith9e7c8da2007-08-28 11:15:20 +0000216
Eric Smith8c663262007-08-25 02:26:07 +0000217 def format_field(self, value, format_spec):
Eric Smith7ade6482007-08-26 22:27:13 +0000218 return format(value, format_spec)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000219
220
221 def convert_field(self, value, conversion):
222 # do any conversion on the resulting object
223 if conversion == 'r':
224 return repr(value)
225 elif conversion == 's':
226 return str(value)
Eric Smith11529192007-09-04 23:04:22 +0000227 elif conversion is None:
Eric Smith9e7c8da2007-08-28 11:15:20 +0000228 return value
Florent Xicluna7b2a7712010-09-06 20:27:55 +0000229 raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
Eric Smith9e7c8da2007-08-28 11:15:20 +0000230
231
232 # returns an iterable that contains tuples of the form:
233 # (literal_text, field_name, format_spec, conversion)
Eric Smith625cbf22007-08-29 03:22:59 +0000234 # literal_text can be zero length
235 # field_name can be None, in which case there's no
236 # object to format and output
237 # if field_name is not None, it is looked up, formatted
238 # with format_spec and conversion and then used
Eric Smith9e7c8da2007-08-28 11:15:20 +0000239 def parse(self, format_string):
Georg Brandl66c221e2010-10-14 07:04:07 +0000240 return _string.formatter_parser(format_string)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000241
242
243 # given a field_name, find the object it references.
244 # field_name: the field being looked up, e.g. "0.name"
245 # or "lookup[3]"
246 # used_args: a set of which args have been used
247 # args, kwargs: as passed in to vformat
Eric Smith9d4ba392007-09-02 15:33:26 +0000248 def get_field(self, field_name, args, kwargs):
Georg Brandl66c221e2010-10-14 07:04:07 +0000249 first, rest = _string.formatter_field_name_split(field_name)
Eric Smith9e7c8da2007-08-28 11:15:20 +0000250
Eric Smith9e7c8da2007-08-28 11:15:20 +0000251 obj = self.get_value(first, args, kwargs)
252
253 # loop through the rest of the field_name, doing
254 # getattr or getitem as needed
255 for is_attr, i in rest:
256 if is_attr:
257 obj = getattr(obj, i)
258 else:
259 obj = obj[i]
260
Eric Smith3bcc42a2007-08-31 02:26:31 +0000261 return obj, first