Skip to content

Commit 5fdd707

Browse files
committed
Update DEP2 by chosing a different solution
1 parent 3f09116 commit 5fdd707

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

enhancement_proposals/dep_2.md

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,53 @@ Various strategies exist, how it could be removed:
2424
so that the statement could once again be converted to AST to check its validity.
2525
- nothing could be remembered - on removal surrounding expression could be detected and validated.
2626

27-
### Solution for incomplete imports
28-
Memorise the places of an original AST expression and evaluate its validity after applied changes.
29-
If the statement is no longer valid and it is import expression - remove it all together.
3027

31-
The chosen approach will be easiest to implement and efficient.
28+
## Chosen solution
29+
AST node can be modified and rendered back as valid code.
30+
AST node should have methods BEFORE and AFTER handling its child nodes.
3231

32+
Compare original code chunk with cleaned up one and remember parts to remove during AST parsing.
3333

34+
After walking a node:
35+
If node is only partially unused:
36+
Modify the node, which is being walked.
37+
Render the node.
38+
Find the diff between original and modified nodes.
39+
Save the unused parts: so that those get removed during rendering.
40+
41+
During removal part no fixes should be applied, only removable code parts should be provided (no AST adjustmnets to make them valid).
42+
Currently implemented adjustments for import, context manager, pass for empty code blocks should be removed from the writing to file part.
43+
44+
This examples demonstrates, how AST nodes can be fixed:
45+
```
46+
import ast
47+
48+
49+
def print_ast(node: ast.AST) -> None:
50+
print(ast.dump(node, indent=4)) # type: ignore
51+
52+
53+
nodes = ast.parse("""
54+
from labas import (
55+
foo as spam,
56+
bar
57+
)
58+
""")
59+
60+
# Apply code clean-up rules:
61+
nodes.body[0].names.pop()
62+
nodes.body[0].names.pop()
63+
64+
# Show nodes after clean-up
65+
print("Fixed and cleaned up code, which can get merged")
66+
print_ast(nodes)
67+
68+
# Show code after clean-up
69+
print("Fixed and cleaned up code, which can get merged")
70+
print(ast.unparse(nodes))
71+
```
72+
73+
## Examples of code adjustments
3474
### Empty code block
3575
Another case is when all expressions are being removed from a block, e.g.
3676

0 commit comments

Comments
 (0)