Code action to add import has incorrect text when the whole module is already imported
Description
A Python code action that should add an import instead changes the usage.
Note how randrange is not imported here:
import random
foo = random.choices([1, 2, 3])
bar = randrange(2, 4)
Steps to reproduce:
- Put the cursor over the
randrangeerror - Run the
from random import randrangecode action
Expected Behavior: A from random import randrange import is added
Actual Behavior: The usage is changed to random.randrange
I originally reported this at https://github.com/zed-industries/zed/issues/41855, but it looks like a basedpyright issue.
i prefer the current behavior. if i already have an import of the whole random module in the current file, i don't want to add other imports from the same module when i can just access them from the random namespace directly. (i actually opened an issue on ruff not too long ago to warn against doing exactly this: https://github.com/astral-sh/ruff/issues/20544)
the text on the code action is definitely incorrect here though and should be updated
That makes sense, but for context, I will also add what I originally posted over at https://github.com/zed-industries/zed/issues/41855:
There is definitely a valid use case for combining
import fooandfrom foo import barfor the same module. For example,randrange()is self-explanatory in what it does,choices()is unclear and should be instead written asrandom.choices().
Of course, this is an edge case, and if a Ruff rule was added for this, it's a simple ignore.
the text on the code action is definitely incorrect here though and should be updated
I'm happy with this fix though.