def create_format_spec_node(node: ast.Call, value: ast.Name, format_spec: str) -> ast.FormattedValue: formatted_value_node = ast.FormattedValue(lineno=node.lineno, col_offset=node.col_offset, parent=node.parent) specifications: Optional[ast.JoinedStr] if format_spec: specifications = ast.JoinedStr(lineno=node.lineno, col_offset=node.col_offset, parent=node.parent,) specifications.postinit(values=[ast.Const(format_spec.replace(":", ""))]) else: specifications = None formatted_value_node.postinit(value=ast.Name(value.name), format_spec=specifications) return formatted_value_node
def format_to_fstring_transform(node): f_string_node = astroid.JoinedStr( lineno=node.lineno, col_offset=node.col_offset, parent=node.parent, ) formatted_value_node = astroid.FormattedValue( lineno=node.lineno, col_offset=node.col_offset, parent=node.parent, ) formatted_value_node.postinit(value=node.args[0]) # Removes the {} since it will be represented as # formatted_value_node string = astroid.Const(node.func.expr.value.replace('{}', '')) print node f_string_node.postinit(values=[string, formatted_value_node]) node.keywords = "a" return astroid.Const(node.func.expr.value.replace('{}', ''))
def transform(self, node: ast.Call) -> ast.JoinedStr: f_string_node = ast.JoinedStr( lineno=node.lineno, col_offset=node.col_offset, parent=node.parent, ) constants: List[str] = re.split("{[^{]*}", node.func.expr.value) specs = re.findall("(?<={)[^{]*(?=})", node.func.expr.value) values = [] for i, const in enumerate(constants): values.append(ast.Const(const)) if i != len(constants) - 1: formatted_node = create_format_spec_node( node, node.args[i], specs[i]) values.append(formatted_node) f_string_node.postinit(values=values) return f_string_node