No project description provided
Project description
ast-comments
A Python extension to the built-in ast module that preserves comments in the Abstract Syntax Tree.
This library finds comments in source code and includes them as nodes in the parsed AST.
Installation
pip install ast-comments
Usage
Usage is identical to the standard ast module:
>>> from ast_comments import *
>>> tree = parse("hello = 'hello' # comment to hello")
The parsed tree is an instance of the original ast.Module object.
The only difference is that there is a new type of tree node: Comment.
>>> tree
<_ast.Module object at 0x7ffba52322e0>
>>> tree.body
[<ast.Assign object at 0x10a01d5b0>, <ast_comments.Comment object at 0x10a09e0a0>]
>>> tree.body[1].value
'# comment to hello'
>>> dump(tree)
"Module(body=[Assign(targets=[Name(id='hello', ctx=Store())], value=Constant(value='hello')), Comment(value='# comment to hello', inline=True)], type_ignores=[])"
If you have Python 3.9 or above, you can also unparse the tree object with its comments preserved:
>>> print(unparse(tree))
hello = 'hello' # comment to hello
Note: Python's compile() function cannot be used directly on the parsed tree output. The included pre_compile_fixer() function can be used to prepare the tree for compilation by stripping comment nodes when needed.
Additional examples can be found in the test files: test_parse.py and test_unparse.py.
Contributing
Contributions are welcome! Please feel free to open an issue or create a pull request.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ast_comments-1.3.0.tar.gz.
File metadata
- Download URL: ast_comments-1.3.0.tar.gz
- Upload date:
- Size: 5.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.10.19 Darwin/25.2.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
45f0113ecff4156a98255c1b87cc6e15b9cee185c3f037c714cf27d3225ed7c3
|
|
| MD5 |
161e11607e52aeca1227d2c0f928b3c6
|
|
| BLAKE2b-256 |
eae89bb599fd6162644d31fe0f87e0e2903d92cd434e4327d9cc2eaa904f6777
|
File details
Details for the file ast_comments-1.3.0-py3-none-any.whl.
File metadata
- Download URL: ast_comments-1.3.0-py3-none-any.whl
- Upload date:
- Size: 5.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.10.19 Darwin/25.2.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1b53fbf7fa89af1ac6222fea0a752328f2d6c35de565e045ad74a16c9441209d
|
|
| MD5 |
43ab25250b49ab46075f5cdb823ccfa4
|
|
| BLAKE2b-256 |
8a38e30499bf1b346e372b780f9161131bb230ce1a63b36662b0acabed3b3219
|