Skip to content

fix priority of namespace vs non-namespace packages #1749

@carljm

Description

@carljm

Consider a directory structure like this:

path-one/
   mod/
      sub1.py
path-two/
   mod/
      __init__.py
      sub2.py

Where path-one and path-two are both import-search-path entries, in that order (e.g. PYTHONPATH=path-one:path-two" should make this happen both for ty and at runtime).

At runtime, a non-namespace package anywhere on the search path takes precedence over a namespace package. This means that with the above setup, import mod.sub1 fails. Despite being first on the search path, path-one/mod is never considered as a candidate for the mod package, because path-two/mod/__init__.py exists.

Given import mod in the above scenario, we do prefer path-two/mod/__init__.py over the path-one/mod namespace package. But we wrongly allow import mod.sub1 to succeed, resolving to the path-one namespace package.

In this particular case, that might seem harmless, but it can cause us to import the wrong thing in some scenarios, and it can lead to some very odd inconsistencies with relative imports, documented in import/workspaces.md. Allowing imports of modules in the "should be ignored" namespace package to just fail would allow our "desperate resolution" to kick in (for imports within that "should be ignored" namespace package) and actually give more consistent behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    importsModule resolution, site-packages discovery, import-related diagnostics

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions