pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Import resolution incorrectly falls back to relative package

Open Walnut356 opened this issue 1 month ago • 5 comments

Describe the Bug

This is without a pyrefly.toml file. Adding one "resolves" the issue w.r.t. this minimal example (though that's not always an option) due to the inferred root directory afaict. In the non-minimal example that I made this example from, adding a pyrefly.toml doesn' fix things, and it doesn't seem like fiddling with the config options helps either? It seems to prefer the definitely invalid self-package-import over the (possibly invalid) external import

Assuming you have the following package b with inner package b.a:

├── b
│   ├── a
│   │   ├── code.py
│   │   └── __init__.py
│   └── __init__.py

and the contents of code.py are:

from a import A

print(A())

And a cannot be found anywhere else, Pyrefly assumes a is b.a. This assumption is incorrect and differs from Python's actual behavior. To access b.a, the import would need to be from ..a import A.

Because pyrefly behaves the way it does, it will offer suggestions from b.a and won't report an error. When trying to run a file that depends on b, it will (if a is actually undiscoverable) hit an import error. If a is discoverable, it will almost certainly error out or behave unexpectedly due to the runtime import not matching the suggestions pyrefly was providing.

In this circumstance, a "did you mean..." lint + a "can't find this package" error is preferable. I don't think there's a case where a package can internally refer to itself. Even without a pyrefly.toml, it seems pretty obvious what the package structure is just from the directory tree, so the a in the current directory shouldn't be valid to import from any file within ./a/.

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Walnut356 avatar Oct 31 '26 07:10 Walnut356

#claim

Sano007 avatar Nov 03 '26 08:11 Sano007

@Sano007 you've claimed this issue — it's now assigned to you. Thanks for picking it up! 🎉

github-actions[bot] avatar Nov 03 '26 08:11 github-actions[bot]

Thanks for the clear example, I can reproduce this. With no config file, Pyrefly also searches the folders above your file, so it finds imports that fail when you actually run the script. Adding a pyproject.toml or pyrefly.toml at the project root fixes it in your minimal example. You mentioned a pyrefly.toml didn't help in your real project, could you share that config?

shahhamdihassan avatar Nov 03 '26 18:11 shahhamdihassan

#unclaim

Sano007 avatar Nov 14 '26 07:11 Sano007

@Sano007 you've been unassigned from this issue. Thanks for letting us know! 👋

github-actions[bot] avatar Nov 14 '26 07:11 github-actions[bot]