Fun with AST
Provides developers with a programmatic tool to change our own code.
This repository contains a library to analyze and manipulate python code
using Abstract Systax Tress manipulation.
Using the library
See the test-fun-with-ast project for examples of using the
fun-with-ast library.
Why Fun-with-AST
- Here is
a talk
I gave in Pycon 2023. It explains the capabilities of fun-with-ast.
- It is a great learning personal development experience.
- Enables smart and complex manipulations
Examples: AST Parse vs. AST Unparse vs. fun-with-ast Source Code Preserver
The examples below show an original program that first was unparsed with
python ast module,
and then was unparsed using the fun-with-ast library. The actual code that generates
these example can be found in the test-fun-with-ast
library.
- Parse-Unparse Challenge Examples
Potential usages:
- Fun #1: Keep source to source transformations
- Fun #2: switch
else
/ if
bodies
- Fun #3: mutation testing switch
<
into <=
- Fun #4: Switch
For
to While
- Fun #5: for loop into tail recursion.
- Fun #7: Add node AND comment.
How to Contribute
- Follow the steps
in Contribute to projects.
- You can chose an existing open issue or open a new one.
- Start working ....
- Before submitting a pull request make sure tests are passing.
How to Run Tests
- In
fun-with-ast
we use pytest.
- Use your IDE to run all tests in
tests
directory.
- OR, use command line:
cd <your path to fun-with-ast fork>/fun_with_ast/tests
pytest --version
, should be at least 7.2.2
- run
pytest
- No tests should fail - some tests would be skipped / xfail.
Limitations
- The library is not yet mature.
- Determining the the of quote (i.e., ' or ") for each string is done at the module or node level.
If a node contains both
print('fun-with-ast')
and print("fun-with-ast")
only one of them will be
preserved,
the first one in the module/node. (See method guess_default_quote_for_node
, if you want to work on something
interesting)