Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1 | """A collection of string constants. |
Guido van Rossum | 2003204 | 1997-12-29 19:26:28 +0000 | [diff] [blame] | 2 | |
| 3 | Public module variables: |
| 4 | |
Georg Brandl | 5076740 | 2008-11-22 08:31:09 +0000 | [diff] [blame] | 5 | whitespace -- a string containing all ASCII whitespace |
| 6 | ascii_lowercase -- a string containing all ASCII lowercase letters |
| 7 | ascii_uppercase -- a string containing all ASCII uppercase letters |
| 8 | ascii_letters -- a string containing all ASCII letters |
| 9 | digits -- a string containing all ASCII decimal digits |
| 10 | hexdigits -- a string containing all ASCII hexadecimal digits |
| 11 | octdigits -- a string containing all ASCII octal digits |
| 12 | punctuation -- a string containing all ASCII punctuation characters |
| 13 | printable -- a string containing all ASCII characters considered printable |
Guido van Rossum | 2003204 | 1997-12-29 19:26:28 +0000 | [diff] [blame] | 14 | |
| 15 | """ |
| 16 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 17 | # Some strings for ctype-style character classification |
Guido van Rossum | 8e2ec56 | 1993-07-29 09:37:38 +0000 | [diff] [blame] | 18 | whitespace = ' \t\n\r\v\f' |
Martin v. Löwis | 967f1e3 | 2007-08-14 09:23:10 +0000 | [diff] [blame] | 19 | ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' |
| 20 | ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
Fred Drake | 960fdf9 | 2001-07-20 18:38:26 +0000 | [diff] [blame] | 21 | ascii_letters = ascii_lowercase + ascii_uppercase |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 22 | digits = '0123456789' |
| 23 | hexdigits = digits + 'abcdef' + 'ABCDEF' |
| 24 | octdigits = '01234567' |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 25 | punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" |
Martin v. Löwis | 967f1e3 | 2007-08-14 09:23:10 +0000 | [diff] [blame] | 26 | printable = digits + ascii_letters + punctuation + whitespace |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 27 | |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 28 | # Functions which aren't available as string methods. |
| 29 | |
| 30 | # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 31 | def capwords(s, sep=None): |
Ezio Melotti | a40bdda | 2009-09-26 12:33:22 +0000 | [diff] [blame] | 32 | """capwords(s [,sep]) -> string |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 33 | |
| 34 | Split the argument into words using split, capitalize each |
| 35 | word using capitalize, and join the capitalized words using |
Ezio Melotti | a40bdda | 2009-09-26 12:33:22 +0000 | [diff] [blame] | 36 | join. If the optional second argument sep is absent or None, |
| 37 | runs of whitespace characters are replaced by a single space |
| 38 | and leading and trailing whitespace are removed, otherwise |
| 39 | sep is used to split and join the words. |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 40 | |
| 41 | """ |
Ezio Melotti | a40bdda | 2009-09-26 12:33:22 +0000 | [diff] [blame] | 42 | return (sep or ' ').join(x.capitalize() for x in s.split(sep)) |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 43 | |
| 44 | |
Raymond Hettinger | 0d58e2b | 2004-08-26 00:21:13 +0000 | [diff] [blame] | 45 | #################################################################### |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 46 | import re as _re |
| 47 | |
Barry Warsaw | 46b629c | 2004-09-13 14:35:04 +0000 | [diff] [blame] | 48 | class _multimap: |
| 49 | """Helper class for combining multiple mappings. |
| 50 | |
| 51 | Used by .{safe_,}substitute() to combine the mapping and keyword |
| 52 | arguments. |
| 53 | """ |
| 54 | def __init__(self, primary, secondary): |
| 55 | self._primary = primary |
| 56 | self._secondary = secondary |
| 57 | |
| 58 | def __getitem__(self, key): |
| 59 | try: |
| 60 | return self._primary[key] |
| 61 | except KeyError: |
| 62 | return self._secondary[key] |
| 63 | |
| 64 | |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 65 | class _TemplateMetaclass(type): |
| 66 | pattern = r""" |
Raymond Hettinger | 55593c3 | 2004-09-26 18:56:44 +0000 | [diff] [blame] | 67 | %(delim)s(?: |
| 68 | (?P<escaped>%(delim)s) | # Escape sequence of two delimiters |
| 69 | (?P<named>%(id)s) | # delimiter and a Python identifier |
| 70 | {(?P<braced>%(id)s)} | # delimiter and a braced identifier |
| 71 | (?P<invalid>) # Other ill-formed delimiter exprs |
| 72 | ) |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 73 | """ |
| 74 | |
| 75 | def __init__(cls, name, bases, dct): |
| 76 | super(_TemplateMetaclass, cls).__init__(name, bases, dct) |
| 77 | if 'pattern' in dct: |
| 78 | pattern = cls.pattern |
| 79 | else: |
| 80 | pattern = _TemplateMetaclass.pattern % { |
Barry Warsaw | 17cb600 | 2004-09-18 00:06:34 +0000 | [diff] [blame] | 81 | 'delim' : _re.escape(cls.delimiter), |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 82 | 'id' : cls.idpattern, |
| 83 | } |
Georg Brandl | 056cb93 | 2010-07-29 17:16:10 +0000 | [diff] [blame] | 84 | cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 85 | |
| 86 | |
Guido van Rossum | 52cc1d8 | 2007-03-18 15:41:51 +0000 | [diff] [blame] | 87 | class Template(metaclass=_TemplateMetaclass): |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 88 | """A string class for supporting $-substitutions.""" |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 89 | |
Barry Warsaw | 17cb600 | 2004-09-18 00:06:34 +0000 | [diff] [blame] | 90 | delimiter = '$' |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 91 | idpattern = r'[_a-z][_a-z0-9]*' |
Georg Brandl | 056cb93 | 2010-07-29 17:16:10 +0000 | [diff] [blame] | 92 | flags = _re.IGNORECASE |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 93 | |
| 94 | def __init__(self, template): |
| 95 | self.template = template |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 96 | |
| 97 | # Search for $$, $identifier, ${identifier}, and any bare $'s |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 98 | |
Barry Warsaw | b5c6b5b | 2004-09-13 20:52:50 +0000 | [diff] [blame] | 99 | def _invalid(self, mo): |
| 100 | i = mo.start('invalid') |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 101 | lines = self.template[:i].splitlines(True) |
| 102 | if not lines: |
| 103 | colno = 1 |
| 104 | lineno = 1 |
| 105 | else: |
| 106 | colno = i - len(''.join(lines[:-1])) |
| 107 | lineno = len(lines) |
| 108 | raise ValueError('Invalid placeholder in string: line %d, col %d' % |
| 109 | (lineno, colno)) |
| 110 | |
Barry Warsaw | b6234a9 | 2004-09-13 15:25:15 +0000 | [diff] [blame] | 111 | def substitute(self, *args, **kws): |
| 112 | if len(args) > 1: |
| 113 | raise TypeError('Too many positional arguments') |
| 114 | if not args: |
| 115 | mapping = kws |
Barry Warsaw | 46b629c | 2004-09-13 14:35:04 +0000 | [diff] [blame] | 116 | elif kws: |
Barry Warsaw | b6234a9 | 2004-09-13 15:25:15 +0000 | [diff] [blame] | 117 | mapping = _multimap(kws, args[0]) |
| 118 | else: |
| 119 | mapping = args[0] |
Barry Warsaw | 46b629c | 2004-09-13 14:35:04 +0000 | [diff] [blame] | 120 | # Helper function for .sub() |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 121 | def convert(mo): |
Barry Warsaw | b5c6b5b | 2004-09-13 20:52:50 +0000 | [diff] [blame] | 122 | # Check the most common path first. |
| 123 | named = mo.group('named') or mo.group('braced') |
| 124 | if named is not None: |
| 125 | val = mapping[named] |
| 126 | # We use this idiom instead of str() because the latter will |
| 127 | # fail if val is a Unicode containing non-ASCII characters. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 128 | return '%s' % (val,) |
Raymond Hettinger | 0d58e2b | 2004-08-26 00:21:13 +0000 | [diff] [blame] | 129 | if mo.group('escaped') is not None: |
Barry Warsaw | 17cb600 | 2004-09-18 00:06:34 +0000 | [diff] [blame] | 130 | return self.delimiter |
Barry Warsaw | b5c6b5b | 2004-09-13 20:52:50 +0000 | [diff] [blame] | 131 | if mo.group('invalid') is not None: |
| 132 | self._invalid(mo) |
Neal Norwitz | 6627a96 | 2004-10-17 16:27:18 +0000 | [diff] [blame] | 133 | raise ValueError('Unrecognized named group in pattern', |
| 134 | self.pattern) |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 135 | return self.pattern.sub(convert, self.template) |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 136 | |
Barry Warsaw | b6234a9 | 2004-09-13 15:25:15 +0000 | [diff] [blame] | 137 | def safe_substitute(self, *args, **kws): |
| 138 | if len(args) > 1: |
| 139 | raise TypeError('Too many positional arguments') |
| 140 | if not args: |
| 141 | mapping = kws |
Barry Warsaw | 46b629c | 2004-09-13 14:35:04 +0000 | [diff] [blame] | 142 | elif kws: |
Barry Warsaw | b6234a9 | 2004-09-13 15:25:15 +0000 | [diff] [blame] | 143 | mapping = _multimap(kws, args[0]) |
| 144 | else: |
| 145 | mapping = args[0] |
Barry Warsaw | 46b629c | 2004-09-13 14:35:04 +0000 | [diff] [blame] | 146 | # Helper function for .sub() |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 147 | def convert(mo): |
Florent Xicluna | eb19dce | 2010-09-18 23:34:07 +0000 | [diff] [blame] | 148 | named = mo.group('named') or mo.group('braced') |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 149 | if named is not None: |
| 150 | try: |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 151 | # We use this idiom instead of str() because the latter |
| 152 | # will fail if val is a Unicode containing non-ASCII |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 153 | return '%s' % (mapping[named],) |
Barry Warsaw | 8bee761 | 2004-08-25 02:22:30 +0000 | [diff] [blame] | 154 | except KeyError: |
Florent Xicluna | eb19dce | 2010-09-18 23:34:07 +0000 | [diff] [blame] | 155 | return mo.group() |
Barry Warsaw | b5c6b5b | 2004-09-13 20:52:50 +0000 | [diff] [blame] | 156 | if mo.group('escaped') is not None: |
Barry Warsaw | 17cb600 | 2004-09-18 00:06:34 +0000 | [diff] [blame] | 157 | return self.delimiter |
Barry Warsaw | b5c6b5b | 2004-09-13 20:52:50 +0000 | [diff] [blame] | 158 | if mo.group('invalid') is not None: |
Florent Xicluna | eb19dce | 2010-09-18 23:34:07 +0000 | [diff] [blame] | 159 | return mo.group() |
Neal Norwitz | 6627a96 | 2004-10-17 16:27:18 +0000 | [diff] [blame] | 160 | raise ValueError('Unrecognized named group in pattern', |
| 161 | self.pattern) |
Barry Warsaw | 12827c1 | 2004-09-10 03:08:08 +0000 | [diff] [blame] | 162 | return self.pattern.sub(convert, self.template) |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 163 | |
| 164 | |
| 165 | |
| 166 | ######################################################################## |
| 167 | # the Formatter class |
| 168 | # see PEP 3101 for details and purpose of this class |
| 169 | |
Benjamin Peterson | f608c61 | 2008-11-16 18:33:53 +0000 | [diff] [blame] | 170 | # The hard parts are reused from the C implementation. They're exposed as "_" |
Florent Xicluna | 7b2a771 | 2010-09-06 20:27:55 +0000 | [diff] [blame] | 171 | # prefixed methods of str. |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 172 | |
Eric Smith | e226b55 | 2007-08-27 11:28:18 +0000 | [diff] [blame] | 173 | # The overall parser is implemented in str._formatter_parser. |
| 174 | # The field name parser is implemented in str._formatter_field_name_split |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 175 | |
| 176 | class Formatter: |
| 177 | def format(self, format_string, *args, **kwargs): |
| 178 | return self.vformat(format_string, args, kwargs) |
| 179 | |
| 180 | def vformat(self, format_string, args, kwargs): |
Eric Smith | 3bcc42a | 2007-08-31 02:26:31 +0000 | [diff] [blame] | 181 | used_args = set() |
Eric Smith | 1152919 | 2007-09-04 23:04:22 +0000 | [diff] [blame] | 182 | result = self._vformat(format_string, args, kwargs, used_args, 2) |
| 183 | self.check_unused_args(used_args, args, kwargs) |
| 184 | return result |
| 185 | |
| 186 | def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): |
| 187 | if recursion_depth < 0: |
| 188 | raise ValueError('Max string recursion exceeded') |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 189 | result = [] |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 190 | for literal_text, field_name, format_spec, conversion in \ |
| 191 | self.parse(format_string): |
Eric Smith | 625cbf2 | 2007-08-29 03:22:59 +0000 | [diff] [blame] | 192 | |
| 193 | # output the literal text |
| 194 | if literal_text: |
| 195 | result.append(literal_text) |
| 196 | |
| 197 | # if there's a field, output it |
| 198 | if field_name is not None: |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 199 | # this is some markup, find the object and do |
| 200 | # the formatting |
| 201 | |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 202 | # given the field_name, find the object it references |
Eric Smith | 3bcc42a | 2007-08-31 02:26:31 +0000 | [diff] [blame] | 203 | # and the argument it came from |
Eric Smith | 9d4ba39 | 2007-09-02 15:33:26 +0000 | [diff] [blame] | 204 | obj, arg_used = self.get_field(field_name, args, kwargs) |
Eric Smith | 3bcc42a | 2007-08-31 02:26:31 +0000 | [diff] [blame] | 205 | used_args.add(arg_used) |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 206 | |
| 207 | # do any conversion on the resulting object |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 208 | obj = self.convert_field(obj, conversion) |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 209 | |
Eric Smith | 1152919 | 2007-09-04 23:04:22 +0000 | [diff] [blame] | 210 | # expand the format spec, if needed |
| 211 | format_spec = self._vformat(format_spec, args, kwargs, |
| 212 | used_args, recursion_depth-1) |
| 213 | |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 214 | # format the object and append to the result |
| 215 | result.append(self.format_field(obj, format_spec)) |
Eric Smith | 625cbf2 | 2007-08-29 03:22:59 +0000 | [diff] [blame] | 216 | |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 217 | return ''.join(result) |
| 218 | |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 219 | |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 220 | def get_value(self, key, args, kwargs): |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 221 | if isinstance(key, int): |
| 222 | return args[key] |
| 223 | else: |
| 224 | return kwargs[key] |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 225 | |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 226 | |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 227 | def check_unused_args(self, used_args, args, kwargs): |
| 228 | pass |
| 229 | |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 230 | |
Eric Smith | 8c66326 | 2007-08-25 02:26:07 +0000 | [diff] [blame] | 231 | def format_field(self, value, format_spec): |
Eric Smith | 7ade648 | 2007-08-26 22:27:13 +0000 | [diff] [blame] | 232 | return format(value, format_spec) |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 233 | |
| 234 | |
| 235 | def convert_field(self, value, conversion): |
| 236 | # do any conversion on the resulting object |
| 237 | if conversion == 'r': |
| 238 | return repr(value) |
| 239 | elif conversion == 's': |
| 240 | return str(value) |
Eric Smith | 1152919 | 2007-09-04 23:04:22 +0000 | [diff] [blame] | 241 | elif conversion is None: |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 242 | return value |
Florent Xicluna | 7b2a771 | 2010-09-06 20:27:55 +0000 | [diff] [blame] | 243 | raise ValueError("Unknown conversion specifier {0!s}".format(conversion)) |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 244 | |
| 245 | |
| 246 | # returns an iterable that contains tuples of the form: |
| 247 | # (literal_text, field_name, format_spec, conversion) |
Eric Smith | 625cbf2 | 2007-08-29 03:22:59 +0000 | [diff] [blame] | 248 | # literal_text can be zero length |
| 249 | # field_name can be None, in which case there's no |
| 250 | # object to format and output |
| 251 | # if field_name is not None, it is looked up, formatted |
| 252 | # with format_spec and conversion and then used |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 253 | def parse(self, format_string): |
| 254 | return format_string._formatter_parser() |
| 255 | |
| 256 | |
| 257 | # given a field_name, find the object it references. |
| 258 | # field_name: the field being looked up, e.g. "0.name" |
| 259 | # or "lookup[3]" |
| 260 | # used_args: a set of which args have been used |
| 261 | # args, kwargs: as passed in to vformat |
Eric Smith | 9d4ba39 | 2007-09-02 15:33:26 +0000 | [diff] [blame] | 262 | def get_field(self, field_name, args, kwargs): |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 263 | first, rest = field_name._formatter_field_name_split() |
| 264 | |
Eric Smith | 9e7c8da | 2007-08-28 11:15:20 +0000 | [diff] [blame] | 265 | obj = self.get_value(first, args, kwargs) |
| 266 | |
| 267 | # loop through the rest of the field_name, doing |
| 268 | # getattr or getitem as needed |
| 269 | for is_attr, i in rest: |
| 270 | if is_attr: |
| 271 | obj = getattr(obj, i) |
| 272 | else: |
| 273 | obj = obj[i] |
| 274 | |
Eric Smith | 3bcc42a | 2007-08-31 02:26:31 +0000 | [diff] [blame] | 275 | return obj, first |