99
1010from templatelib import Interpolation , Template
1111
12+ from . import pairs
1213from .fstring import convert
1314
1415
@@ -23,24 +24,22 @@ class Formatter:
2324 def __init__ (self , template : Template ):
2425 """Construct a formatter for the provided template."""
2526 # Ensure that all interpolations are strings.
26- for arg in template .args :
27- if isinstance (arg , Interpolation ):
28- if not isinstance (arg .value , str ):
29- raise ValueError (f"Non-string interpolation: { arg .value } " )
27+ for i , _ in pairs (template ):
28+ if i is not None and not isinstance (i .value , str ):
29+ raise ValueError (f"Non-string interpolation: { i .value } " )
3030 self .template = template
3131
3232 def format (self , ** kwargs ) -> str :
3333 """Render the t-string using the given values."""
3434 parts = []
35- for t_arg in self .template .args :
36- if isinstance (t_arg , str ):
37- parts .append (t_arg )
38- else :
39- assert isinstance (t_arg .value , str )
40- value = kwargs [t_arg .value ]
41- value = convert (value , t_arg .conv )
42- value = format (value , t_arg .format_spec )
35+ for i , s in pairs (self .template ):
36+ if i is not None :
37+ assert isinstance (i .value , str )
38+ value = kwargs [i .value ]
39+ value = convert (value , i .conv )
40+ value = format (value , i .format_spec )
4341 parts .append (value )
42+ parts .append (s )
4443 return "" .join (parts )
4544
4645
@@ -55,24 +54,20 @@ class Binder:
5554 def __init__ (self , template : Template ):
5655 """Construct a binder for the provided template."""
5756 # Ensure that all interpolations are strings.
58- for arg in template .args :
59- if isinstance (arg , Interpolation ):
60- if not isinstance (arg .value , str ):
61- raise ValueError (f"Non-string interpolation: { arg .value } " )
57+ for i , _ in pairs (template ):
58+ if i is not None and not isinstance (i .value , str ):
59+ raise ValueError (f"Non-string interpolation: { i .value } " )
6260 self .template = template
6361
6462 def bind (self , ** kwargs ) -> Template :
6563 """Bind values to the template."""
6664 args = []
67- for t_arg in self .template .args :
68- if isinstance (t_arg , str ):
69- args .append (t_arg )
70- else :
71- assert isinstance (t_arg .value , str )
72- value = kwargs [t_arg .value ]
73- expr = repr (t_arg .value )[1 :- 1 ] # remove quotes from original expression
74- interpolation = Interpolation (
75- value , expr , t_arg .conv , t_arg .format_spec
76- )
65+ for i , s in pairs (self .template ):
66+ if i is not None :
67+ assert isinstance (i .value , str )
68+ value = kwargs [i .value ]
69+ expr = repr (i .value )[1 :- 1 ] # remove quotes from original expression
70+ interpolation = Interpolation (value , expr , i .conv , i .format_spec )
7771 args .append (interpolation )
72+ args .append (s )
7873 return Template (* args )
0 commit comments