Skip to content

Merge namespace package portions for from X import A, B - #11898

Open
Megh Parikh (meghprkh) wants to merge 2 commits into
microsoft:mainfrom
meghprkh:namespace-from-import-merge
Open

Megh Parikh (meghprkh) wants to merge 2 commits into
microsoft:mainfrom
meghprkh:namespace-from-import-merge

Conversation

@meghprkh

@meghprkh Megh Parikh (meghprkh) commented Oct 20, 2026 •

Copy link
Copy Markdown

Related: #7494, #9165, #10056

Problem

When a PEP 420 namespace package is split across several search paths
(extraPaths, editable installs, site-packages), pyright reports
"B" is unknown import symbol for:

from ns import A, B  # A in one portion, B in another

Python accepts this, and pyright accepts the same imports on separate lines.
Import sorters such as isort/ruff merge those lines back together, so the
separate-line workaround doesn't stick.

Cause

_resolveBestAbsoluteImport already resolves the import against every search
path, but _pickBestImport keeps only one result, and so only one portion's
implicit imports (submodules). _isNamespacePackageResolved accepts a portion
if it provides any requested symbol, so the first portion containing A wins
and B is lost.

Change

While walking the search paths, collect results that are namespace portions
(found, namespace, no __init__.py(i) in the final directory, not a stub
package). If the best result is one of them, return a copy whose implicit
imports are the union of all portions' implicit imports. When several portions
provide the same submodule, the earliest one wins, matching runtime order.

  • No additional file system access: every portion is already resolved today.
  • No binder or checker changes: implicit imports are looked up per name and
    each entry carries its own URI.
  • Regular packages and stub packages are never merged.

Tests

New cases in importResolver.test.ts:

  • symbols split across two portions resolve to their own files
  • the earliest portion wins for a shared submodule
  • ...even when a later portion is the one picked
  • nothing is merged into a regular package

Performance

No extra file system access. Absolute import results are cached per module
name, so a merged result also avoids repeated full resolutions: a cached
single-portion result that lacks the next requested symbol is currently
re-resolved against every search path.

Synthetic project: one namespace package split across 40 extraPaths roots
(25 modules each), 200 user files (median of 5 runs, same commit with and
without this change):

Imports in each user file Before After
5 separate from ns import m 1.85s (resolve 0.95s) 0.94s (resolve 0.08s)
one from ns import m1, …, m5 0.96s, 788 errors 0.91s, 0 errors
from ns import * 1.97s, 852 files parsed 2.17s, 1222 files parsed

from ns import * passes an empty symbol set, which keeps all implicit imports,
so it now pulls in the submodules of every portion rather than one. This was
already the behaviour for a single portion.

It also makes resolution independent of import order. Today the first file to
resolve from ns import ... decides which portion is cached for ns, so a
subpackage installed in two search paths can be loaded from either depending on
which file imported it. With this change every file gets the same copy.

A from-import of several submodules of a namespace package split across
search paths (e.g. "from ns import a, b" with a and b in different
portions) only kept the implicit imports of one portion, so the other
symbols were reported as unknown import symbols.

Merge the implicit imports of all namespace portions found during
resolution, with the earliest portion winning for a shared submodule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@bschnurr

Copy link
Copy Markdown
Member

On pinned main (d95fe63b), three namespace-portion regression tests failed: the split from import and both earlier-portion precedence cases. All three passed with 91f07fb9 integrated. The regular-package shadowing control passed on both revisions. This verifies the changed behavior without treating the unchanged control as a regression test.

@heejaechang

Heejae Chang (heejaechang) commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 4be4b4e4 — verdict: red

Automated CLI checks compared this change with its base revision.
19 focused check(s) completed.

Needs review: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

direct.py

from typing import assert_type, assert_never
reveal_type(0)
from outer.ns.a import f
assert_type(f(), str)
f().upper()

def exhaustive(x: int | str) -> None:
    if isinstance(x, int): assert_type(x, int)
    elif isinstance(x, str): assert_type(x, str)
    else: assert_never(x)

invalid.py

reveal_type(0)
from outer.ns import b
from outer.ns import a
a.f(1)

p1/outer/ns/a/__init__.py

def f(value: object = "ok") -> object:
    if isinstance(value, str):
        return value
    raise TypeError("expected a string")

p2/outer/ns/a/__init__.pyi

def f(value: str = ...) -> str: ...

p2/outer/ns/b.py

def g() -> int: return 1

pyrightconfig.json

{
  "include": [
    "valid.py",
    "invalid.py",
    "direct.py"
  ],
  "extraPaths": [
    "p1",
    "p2"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

valid.py

from typing import assert_type, assert_never
reveal_type(0)
from outer.ns import b
from outer.ns import a
assert_type(a.f(), str)
a.f().upper()

def exhaustive(x: int | str) -> None:
    if isinstance(x, int): assert_type(x, int)
    elif isinstance(x, str): assert_type(x, str)
    else: assert_never(x)

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base e80c920278f15973001d1a33414b0a7cafdc5ed2

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "direct.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[1]\" cannot be assigned to parameter \"value\" of type \"str\" in function \"f\"\n  \"Literal[1]\" is not assignable to \"str\"",
      "range": {
        "start": [
          3,
          4
        ],
        "end": [
          3,
          5
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 4be4b4e45156295ff2b8ee891b1fbde4eb1cac71

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "direct.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"object\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          5,
          6
        ],
        "end": [
          5,
          11
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"object\"",
      "range": {
        "start": [
          4,
          12
        ],
        "end": [
          4,
          17
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Additional reproduction: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Create these files in an empty directory:

direct.py

from typing import assert_type, assert_never
reveal_type(0)
from ns.a import f
assert_type(f(), str)
f().upper()

def exhaustive(x: int | str) -> None:
    if isinstance(x, int): assert_type(x, int)
    elif isinstance(x, str): assert_type(x, str)
    else: assert_never(x)

invalid.py

reveal_type(0)
from ns import b
from ns import a
a.f(1)

p1/ns/a.py

def f(value: object = "ok") -> object:
    if isinstance(value, str):
        return value
    raise TypeError("expected a string")

p2/ns/a.pyi

def f(value: str = ...) -> str: ...

p2/ns/b.py

def g() -> int: return 1

pyrightconfig.json

{
  "include": [
    "valid.py",
    "invalid.py",
    "direct.py"
  ],
  "extraPaths": [
    "p1",
    "p2"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

runtime.py

# /// script
# requires-python = ">=3.13,<3.14"
# dependencies = []
# ///
import sys
sys.dont_write_bytecode = True
from pathlib import Path
print(sys.version)
root = Path(__file__).resolve().parent
sys.path[:0] = [str(root / "p1"), str(root / "p2")]
from ns import b, a
assert a.f("hello").upper() == "HELLO"
try:
    a.f(1)
except TypeError as error:
    assert str(error) == "expected a string"
    print("invalid call raises TypeError: expected a string")
else:
    raise AssertionError("invalid call unexpectedly returned")
print("matching stub contract: str return and str-only calls confirmed")

valid.py

from typing import assert_type, assert_never
reveal_type(0)
from ns import b
from ns import a
assert_type(a.f(), str)
a.f().upper()

def exhaustive(x: int | str) -> None:
    if isinstance(x, int): assert_type(x, int)
    elif isinstance(x, str): assert_type(x, str)
    else: assert_never(x)

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base e80c920278f15973001d1a33414b0a7cafdc5ed2

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "direct.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[1]\" cannot be assigned to parameter \"value\" of type \"str\" in function \"f\"\n  \"Literal[1]\" is not assignable to \"str\"",
      "range": {
        "start": [
          3,
          4
        ],
        "end": [
          3,
          5
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 4be4b4e45156295ff2b8ee891b1fbde4eb1cac71

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "direct.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"object\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          5,
          6
        ],
        "end": [
          5,
          11
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"object\"",
      "range": {
        "start": [
          4,
          12
        ],
        "end": [
          4,
          17
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Only merge imports whose full path consists of namespace packages. Preserve the origin of merged implicit imports so typed third-party packages retain private-export diagnostics.
@meghprkh

Megh Parikh (meghprkh) commented Nov 28, 2026 •

Copy link
Copy Markdown
Author

Thanks Heejae Chang (@heejaechang) I have pushed a commit, however at this point I am fairly out of comfort with the changes being made, please let me know if this works or I will close the PR as at this point its 100% AI-ed with me just acting as a proxy (Especially since it changes an interface in packages/pyright-internal/src/analyzer/importResult.ts )

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants