def transform(self, node: ast.Call) -> ast.Call: new_call = ast.Call(parent=node.parent) new_name = ast.Name(self.new_name, parent=new_call.parent) new_call.postinit(func=new_name, args=node.args, keywords=node.keywords) return new_call
def transform(self, node: ast.Assign) -> ast.Assign: new_assign = ast.Assign(parent=node.parent) value = ast.Call(parent=new_assign) iterator = node.value.generators[0].iter iterator.parent = value value.postinit( func=ast.Name(name="map", parent=value), args=[ast.Name(node.value.elt.func.name, parent=value), iterator]) targets = node.targets for target in targets: target.parent = new_assign new_assign.postinit(targets=node.targets, value=value) return new_assign
def convert_f_string_to_format_string(src: str) -> str: """ Convert a single f-string (passed as its source token) to a .format() call (as a source token). """ node = astroid.extract_node(src) # An f-string alternates between two kinds of nodes: string Const nodes and # FormattedValue nodes that hold the formatting bits format_string_parts = [] format_args = [] for child in node.get_children(): if isinstance(child, astroid.Const): format_string_parts.append(child.value) elif isinstance(child, astroid.FormattedValue): format_string_parts.append( "{{{c}{f}}}".format( c=CONVERSIONS[child.conversion], f=f":{child.format_spec.values[0].value}" if child.format_spec is not None else "", ) ) # We can pick the format value nodes right out of the string # and place them in the args; no need to introspect what they # actually are! format_args.append(child.value) format_string_node = astroid.Const("".join(format_string_parts)) format_call = astroid.Call(lineno=node.lineno, col_offset=node.col_offset) # The Call's func is a method looked up on the format string format_attr = astroid.Attribute(attrname="format", lineno=node.lineno, parent=format_call) format_attr.postinit(expr=format_string_node) # The Call's arguments are the format arguments extracted from the f-string format_call.postinit(func=format_attr, args=format_args, keywords=[]) return format_call.as_string()