Skip to content

Commit 1ba56b4

Browse files
authored
[ty] Fix relative imports in stub packages (#18132)
1 parent e677cab commit 1ba56b4

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

crates/ty_python_semantic/resources/mdtest/import/stub_packages.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,5 @@ class YamlLoader: ...
311311
```py
312312
import yaml
313313

314-
# TODO: This should not be an error
315-
yaml.YamlLoader # error: [unresolved-attribute] "Type `<module 'yaml'>` has no attribute `YamlLoader`"
314+
reveal_type(yaml.YamlLoader) # revealed: <class 'YamlLoader'>
316315
```

crates/ty_python_semantic/src/module_resolver/path.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use std::fmt;
44
use std::sync::Arc;
55

66
use camino::{Utf8Path, Utf8PathBuf};
7-
87
use ruff_db::files::{File, FileError, system_path_to_file, vendored_path_to_file};
98
use ruff_db::system::{System, SystemPath, SystemPathBuf};
109
use ruff_db::vendored::{VendoredPath, VendoredPathBuf};
@@ -189,7 +188,18 @@ impl ModulePath {
189188
stdlib_path_to_module_name(relative_path)
190189
} else {
191190
let parent = relative_path.parent()?;
192-
let parent_components = parent.components().map(|component| component.as_str());
191+
let parent_components = parent.components().enumerate().map(|(index, component)| {
192+
let component = component.as_str();
193+
194+
// For stub packages, strip the `-stubs` suffix from the first component
195+
// because it isn't a valid module name part AND the module name is the name without the `-stubs`.
196+
if index == 0 {
197+
component.strip_suffix("-stubs").unwrap_or(component)
198+
} else {
199+
component
200+
}
201+
});
202+
193203
let skip_final_part =
194204
relative_path.ends_with("__init__.py") || relative_path.ends_with("__init__.pyi");
195205
if skip_final_part {

0 commit comments

Comments
 (0)