Python: an import normalizer for files mixing `import m` and `from m import x`

Open
#8,791 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
42/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Active
Tech stack
java
Domain
devtools

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.

Description

enhancement python
  • Since #8790, a template's context binds 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.

Dominant language
Java
Stars
3.9k
Forks
599
Avg merge
9h 38m
Merged PRs (30d)
557

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from openrewrite/rewrite

All issues in openrewrite/rewrite

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.