17 Keyword arguments may be set on initialization or subsequently using __setitem__, before format. |
17 Keyword arguments may be set on initialization or subsequently using __setitem__, before format. |
18 "constant object" instances can also be inserted in the patterns. |
18 "constant object" instances can also be inserted in the patterns. |
19 """ |
19 """ |
20 self.pattern = pattern_sequence |
20 self.pattern = pattern_sequence |
21 self.arguments = keywordargs |
21 self.arguments = keywordargs |
22 from types import StringType, InstanceType |
|
23 toptypes = (StringType, InstanceType) |
|
24 for x in pattern_sequence: |
22 for x in pattern_sequence: |
25 if type(x) not in toptypes: |
23 if not isinstance(x,str) and not hasattr(x,'format'): |
26 if len(x)!=1: |
24 if len(x)!=1: |
27 raise ValueError("sequence elts must be strings or singletons containing strings: "+repr(x)) |
25 raise ValueError("sequence elts must be strings or singletons containing strings: "+ascii(x)) |
28 if type(x[0]) is not StringType: |
26 if not isinstance(x[0],str): |
29 raise ValueError("Singletons must contain strings or instances only: "+repr(x[0])) |
27 raise ValueError("Singletons must contain strings or instances only: "+ascii(x[0])) |
30 def __setitem__(self, item, value): |
28 def __setitem__(self, item, value): |
31 self.arguments[item] = value |
29 self.arguments[item] = value |
32 def __getitem__(self, item): |
30 def __getitem__(self, item): |
33 return self.arguments[item] |
31 return self.arguments[item] |
34 def format(self, document): |
32 def format(self, document): |
35 L = [] |
33 L = [] |
36 arguments = self.arguments |
34 arguments = self.arguments |
37 from types import StringType, InstanceType |
|
38 for x in self.pattern: |
35 for x in self.pattern: |
39 tx = type(x) |
36 if isinstance(x,str): |
40 if tx is StringType: |
|
41 L.append(x) |
37 L.append(x) |
42 elif tx is InstanceType: |
38 elif hasattr(x,'format'): |
43 L.append( x.format(document) ) |
39 L.append(x.format(document) ) |
44 else: |
40 else: |
45 name = x[0] |
41 name = x[0] |
46 value = arguments.get(name, None) |
42 value = arguments.get(name, None) |
47 if value is None: |
43 if value is None: |
48 raise ValueError("%s value not defined" % repr(name)) |
44 raise ValueError("%s value not defined" % ascii(name)) |
49 if type(value) is InstanceType: |
45 if isinstance(value,str): |
50 #L.append( value.format(document) ) |
46 L.append(value) |
51 L.append(format(value, document)) |
|
52 else: |
47 else: |
53 L.append( str(value) ) |
48 L.append(value.formatformat(document)) |
54 return "".join(L) |
49 return "".join(L) |
55 |
50 |
56 |
51 |