The pfst library simplifies Python source code editing through advanced AST manipulation while preserving the original formatting. Changes to functionality can be made without the hassle of dealing with syntax quirks or formatting details, enabling developers to maintain code clarity and consistency effortlessly.
Overview
The pfst module enables high-level editing of Python source code using an Abstract Syntax Tree (AST) while preserving the original formatting. It is designed for developers who need to modify Python code functionality without having to navigate through intricate details such as:
- Operator precedence and parentheses
- Indentation and line continuations
- Commas, semicolons, and tuple edge cases
- Comments and docstrings
- Syntax variations across different Python versions
This module simplifies your workflow and enhances productivity by allowing modifications without losing the original style.
Example Recipes
To explore various use cases, visit the Example Recipes.
Usage Example
To get started with pfst, simply import the module and utilize its features:
import fst # pip install pfst, import fst
ext_ast = fst.parse('if a: b = c, d # comment')
ext_ast.f.body[0].body[0].value.elts[1:1] = 'u,\nv # blah'
print(fst.unparse(ext_ast))
This will output:
if a: b = (c, u,
v, # blah
d) # comment
Robust Handling of Syntax
The module effectively manages complex syntax, ensuring the integrity of the Python code:
f = FST(r"""
if True:
@decorator1
# pre-comment
\ @ ( decorator2 )( a, ) \ # post-comment
def func(): weird; pass
""")
Native AST Support
pfst maintains compatibility with the native AST, allowing for seamless interaction:
f = FST('i = [a, b, c]')
f.targets[0] = Subscript(Name('j'), Slice(Name('x'), Name('y')))
f.value.elts[1:] = Name('d')
print(f.src)
Traversal in Syntactic Order
The module allows for easy traversal of the AST in syntactic order:
list(f.src for f in FST('call(a, x=1, *b, y=2, **c)').walk())[1:]
Explore more functionalities and examples in the provided documentation or check out the repository.
pfst is a powerful tool for developers looking to modify and manage Python source code efficiently without sacrificing formatting.
No comments yet.
Sign in to be the first to comment.