openrewrite / openrewrite/rewrite
Python: an import normalizer for files mixing `import m` and `from m import x`
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 3.7k
- Forks
- 570
- Avg merge
- 13h 12m
- Merged PRs (30d)
- 261
Description
- Since #8790, a template's
contextbinds its modules in the file it is spliced into. Binding is per (module, member), so a file that imports the member gets the module import added next to it:
# file: from subprocess import run
# template: template(f"subprocess.run({arg}, shell=True)", context=["import subprocess"])
from subprocess import run
import subprocess # added
out = subprocess.run('ls', shell=True)
That is correct and it runs, but the file already had what the splice needed. The pattern side is style-agnostic — pattern("json.dumps({val})", context=["import json"]) matches a file that wrote from json import dumps; dumps(x) — so matching treats the two styles as one thing and emitting does not.
Adapting the splice to the file's style is the wrong fix at the template layer. Binding is per member, so a template reading both subprocess.run and subprocess.PIPE in a file that imports only run can be collapsed for neither use or for one, and collapsing one is worse than collapsing neither. It is also not a rename: subprocess.run(...) is a MethodInvocation with a select and subprocess.PIPE a FieldAccess, so both change shape, and the resulting bare name has to be unshadowed where it lands.
A normalizer recipe is the right owner. It sees the whole file rather than one splice, so all-or-nothing coverage is decidable; it can go in both directions against a configured preference; and it reaches imports no template put there.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading issue #8790 and the import-binding behavior described here. Define the normalizer's configured preference and whole-file, all-or-nothing coverage rules for converting between import styles. Done means imports added by splices and already present in the file can be normalized without unsafe partial collapsing or shadowing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100