Replaces placeholders in a Python template. AST Name and Tuple nodes always receive the context that inferred from the template. However, when replacing more complex nodes (that can potentially contain Name children), then the caller is responsible for setting the appropriate context. Ar
(template, **replacements)
| 231 | |
| 232 | |
| 233 | def replace(template, **replacements): |
| 234 | """Replaces placeholders in a Python template. |
| 235 | |
| 236 | AST Name and Tuple nodes always receive the context that inferred from |
| 237 | the template. However, when replacing more complex nodes (that can potentially |
| 238 | contain Name children), then the caller is responsible for setting the |
| 239 | appropriate context. |
| 240 | |
| 241 | Args: |
| 242 | template: A string representing Python code. Any symbol name can be used |
| 243 | that appears in the template code can be used as placeholder. |
| 244 | **replacements: A mapping from placeholder names to (lists of) AST nodes |
| 245 | that these placeholders will be replaced by. String values are also |
| 246 | supported as a shorthand for AST Name nodes with the respective ID. |
| 247 | |
| 248 | Returns: |
| 249 | An AST node or list of AST nodes with the replacements made. If the |
| 250 | template was a function, a list will be returned. If the template was a |
| 251 | node, the same node will be returned. If the template was a string, an |
| 252 | AST node will be returned (a `Module` node in the case of a multi-line |
| 253 | string, an `Expr` node otherwise). |
| 254 | |
| 255 | Raises: |
| 256 | ValueError: if the arguments are incorrect. |
| 257 | """ |
| 258 | if not isinstance(template, str): |
| 259 | raise ValueError('Expected string template, got %s' % type(template)) |
| 260 | for k in replacements: |
| 261 | replacements[k] = _convert_to_ast(replacements[k]) |
| 262 | template_str = parser.STANDARD_PREAMBLE + textwrap.dedent(template) |
| 263 | nodes = parser.parse_str( |
| 264 | template_str, |
| 265 | preamble_len=parser.STANDARD_PREAMBLE_LEN, |
| 266 | single_node=False) |
| 267 | results = [] |
| 268 | for node in nodes: |
| 269 | node = ReplaceTransformer(replacements).visit(node) |
| 270 | if isinstance(node, (list, tuple)): |
| 271 | results.extend(node) |
| 272 | else: |
| 273 | results.append(node) |
| 274 | results = [qual_names.resolve(r) for r in results] |
| 275 | return results |
| 276 | |
| 277 | |
| 278 | def replace_as_expression(template, **replacements): |