[ty] Prefer unqualified imports over qualified imports

It seems like this is perhaps a better default:
https://github.com/astral-sh/ty/issues/1274#issuecomment-3352233790

For me personally, I think I'd prefer the qualified
variant. But I can easily see this changing based on
the specific scenario. I think the thing that pushes
me toward prioritizing the unqualified variant is that
the user could have typed the qualified variant themselves,
but they didn't. So we should perhaps prioritize the
form they typed, which is unqualified.
This commit is contained in:
Andrew Gallant 2025-12-12 10:04:05 -05:00 committed by Andrew Gallant
parent 43d983ecae
commit 0589700ca1
2 changed files with 15 additions and 6 deletions

View File

@ -6717,8 +6717,8 @@ TypedDi<CURSOR>
assert_snapshot!( assert_snapshot!(
builder.imports().build().snapshot(), builder.imports().build().snapshot(),
@r" @r"
typing.TypedDict :: <no import edit> TypedDict :: , TypedDict
typing.is_typeddict :: <no import edit> is_typeddict :: , is_typeddict
_FilterConfigurationTypedDict :: from logging.config import _FilterConfigurationTypedDict _FilterConfigurationTypedDict :: from logging.config import _FilterConfigurationTypedDict
_FormatterConfigurationTypedDict :: from logging.config import _FormatterConfigurationTypedDict _FormatterConfigurationTypedDict :: from logging.config import _FormatterConfigurationTypedDict

View File

@ -745,8 +745,17 @@ impl ImportResponseKind<'_> {
fn priority(&self) -> usize { fn priority(&self) -> usize {
match *self { match *self {
ImportResponseKind::Unqualified { .. } => 0, ImportResponseKind::Unqualified { .. } => 0,
ImportResponseKind::Qualified { .. } => 1, ImportResponseKind::Partial(_) => 1,
ImportResponseKind::Partial(_) => 2, // N.B. When given the choice between adding a
// name to an existing `from ... import ...`
// statement and using an existing `import ...`
// in a qualified manner, we currently choose
// the former. Originally we preferred qualification,
// but there is some evidence that this violates
// expectations.
//
// Ref: https://github.com/astral-sh/ty/issues/1274#issuecomment-3352233790
ImportResponseKind::Qualified { .. } => 2,
} }
} }
} }
@ -1332,9 +1341,9 @@ import collections
); );
assert_snapshot!( assert_snapshot!(
test.import("collections", "defaultdict"), @r" test.import("collections", "defaultdict"), @r"
from collections import OrderedDict from collections import OrderedDict, defaultdict
import collections import collections
collections.defaultdict defaultdict
"); ");
} }