basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

Code action to add import has incorrect text when the whole module is already imported

Open injust opened this issue 5 months ago • 2 comments

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:

  1. Put the cursor over the randrange error
  2. Run the from random import randrange code 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.

injust avatar Nov 08 '25 22:11 injust

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

DetachHead avatar Nov 09 '25 06:11 DetachHead

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 foo and from foo import bar for the same module. For example, randrange() is self-explanatory in what it does, choices() is unclear and should be instead written as random.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.

injust avatar Nov 09 '25 07:11 injust