1
- import types
2
1
from ast import literal_eval
3
2
from itertools import chain
4
3
from itertools import islice
11
10
from .environment import Template
12
11
13
12
14
- def native_concat (nodes , preserve_quotes = True ):
13
+ def native_concat (nodes ):
15
14
"""Return a native Python type from the list of compiled nodes. If
16
15
the result is a single node, its value is returned. Otherwise, the
17
16
nodes are concatenated as strings. If the result can be parsed with
18
17
:func:`ast.literal_eval`, the parsed value is returned. Otherwise,
19
18
the string is returned.
20
19
21
20
:param nodes: Iterable of nodes to concatenate.
22
- :param preserve_quotes: Whether to re-wrap literal strings with
23
- quotes, to preserve quotes around expressions for later parsing.
24
- Should be ``False`` in :meth:`NativeEnvironment.render`.
25
21
"""
26
22
head = list (islice (nodes , 2 ))
27
23
@@ -31,37 +27,25 @@ def native_concat(nodes, preserve_quotes=True):
31
27
if len (head ) == 1 :
32
28
raw = head [0 ]
33
29
else :
34
- if isinstance (nodes , types .GeneratorType ):
35
- nodes = chain (head , nodes )
36
- raw = u"" .join ([text_type (v ) for v in nodes ])
30
+ raw = u"" .join ([text_type (v ) for v in chain (head , nodes )])
37
31
38
32
try :
39
- literal = literal_eval (raw )
33
+ return literal_eval (raw )
40
34
except (ValueError , SyntaxError , MemoryError ):
41
35
return raw
42
36
43
- # If literal_eval returned a string, re-wrap with the original
44
- # quote character to avoid dropping quotes between expression nodes.
45
- # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should
46
- # be ('a', 'b').
47
- if preserve_quotes and isinstance (literal , str ):
48
- return "{quote}{}{quote}" .format (literal , quote = raw [0 ])
49
-
50
- return literal
51
-
52
37
53
38
class NativeCodeGenerator (CodeGenerator ):
54
39
"""A code generator which renders Python types by not adding
55
- ``to_string()`` around output nodes, and using :func:`native_concat`
56
- to convert complex strings back to Python types if possible.
40
+ ``to_string()`` around output nodes.
57
41
"""
58
42
59
43
@staticmethod
60
44
def _default_finalize (value ):
61
45
return value
62
46
63
47
def _output_const_repr (self , group ):
64
- return repr (native_concat ( group ))
48
+ return repr (u"" . join ([ text_type ( v ) for v in group ] ))
65
49
66
50
def _output_child_to_const (self , node , frame , finalize ):
67
51
const = node .as_const (frame .eval_ctx )
@@ -100,10 +84,9 @@ def render(self, *args, **kwargs):
100
84
Otherwise, the string is returned.
101
85
"""
102
86
vars = dict (* args , ** kwargs )
87
+
103
88
try :
104
- return native_concat (
105
- self .root_render_func (self .new_context (vars )), preserve_quotes = False
106
- )
89
+ return native_concat (self .root_render_func (self .new_context (vars )))
107
90
except Exception :
108
91
return self .environment .handle_exception ()
109
92
0 commit comments