google-pasta
google-pasta is an AST-based Python refactoring library (version 0.2.0). It aims to enable robust Python source code refactoring through Abstract Syntax Tree (AST) modifications, useful for tasks like renaming modules, rewriting import statements, enforcing code style, or safely migrating code between APIs. The library is currently marked as 'Pre-Alpha' on PyPI and has a slow release cadence, with the last update in March 2020.
Warnings
- gotcha The library operates under the assumption that the Python version for which the code is written is the same as the Python version running `pasta`. This is due to its reliance on the built-in `ast.parse` module, which can have version-specific behaviors.
- gotcha Changing indentation levels of code blocks is not directly supported, which can limit certain refactoring operations like extracting methods.
- gotcha Some Python features, such as the `global` keyword, are not fully supported, which can lead to incorrect transformations or parsing errors.
- gotcha The project's PyPI status is '2 - Pre-Alpha', indicating it is still experimental and not considered stable or production-ready by its maintainers.
- gotcha Development is slow or stalled. The last PyPI release (0.2.0) was in March 2020, and the last reported code push activity was around late 2020. Open issues exist for modern Python syntax (e.g., f-strings parsing failures, Python 3.10 support), suggesting potential compatibility problems with newer Python versions.
Install
-
pip install google-pasta
Imports
- parse
import pasta src = 'def foo(): pass' ast = pasta.parse(src)
- dump
import pasta src = 'def foo(): pass' ast = pasta.parse(src) reconstructed_src = pasta.dump(ast)
Quickstart
import pasta
# Original source code string
original_code = """
def greet(name):
print(f"Hello, {name}!")
greet("World")
"""
# Parse the source code into an AST
ast_tree = pasta.parse(original_code)
# (Optional) Modify the AST here, for example, renaming a function
# For simplicity, we're just parsing and dumping to demonstrate symmetry
# Dump the AST back into source code
reconstructed_code = pasta.dump(ast_tree)
# Verify symmetry (as per pasta's design goals)
assert original_code == reconstructed_code
print("Original Code:\n" + original_code)
print("Reconstructed Code:\n" + reconstructed_code)
print(f"Code matches after parse and dump: {original_code == reconstructed_code}")