I finally got back to this. Short version: most of the remaining problem was on our side, not in the type checkers 🙈
Upstream status:
So why did pyright and ty still infer UPath for UPath("b/k", protocol="s3")? Two reasons:
- The overload return types were written as
_uimpl.cloud.S3Path via import upath.implementations as _uimpl. upath/implementations/__init__.py doesn't import its submodules, so pyright resolved the return type to Unknown ("cloud" is not a known attribute of module), and ty warned about a possibly-missing submodule. An Unknown return from __new__ falls back to the class itself, which is UPath. mypy is more lenient here, so we never noticed.
- ty uses the return type of our annotated metaclass
__call__(cls: type[T], ...) -> T and stops there. pyright and pyrefly continue with __new__.
#591 fixes both. It imports the implementation classes directly (like upath.registry already does) and hides _UPathMeta.__call__ from type checkers (no runtime change). Results with mypy 2.4.1 / 1.19.1, pyright 1.1.414, ty 0.0.99 and pyrefly 1.4.1:
from upath import UPath
from upath.implementations.cloud import S3Path
from upath.registry import get_upath_class
UPath("s3://bucket/key") # UPath everywhere (URIs can't be parsed statically)
UPath("bucket/key", protocol="s3") # S3Path: mypy, pyrefly | now also pyright, ty
UPath("bucket/key", protocol="s3", **opts) # S3Path: same as above
UPath("bucket/key", protocol="s3", anon="x") # error only in pyright (it checks S3Path.__init__)
S3Path("s3://bucket/key", anon=True) # S3Path + storage options checked everywhere*
get_upath_class("s3")("bucket/key", anon=True) # S3Path + storage options checked everywhere*
* ty checks option types, but by design it accepts unknown keys for (open) TypedDicts, see astral-sh/ty#4212.
Making pyright check __init__ through the narrowed type also uncovered three wrong protocol literals in our __init__ stubs (TarPath said "zip", SFTPPath didn't accept "ssh", WebdavPath didn't accept "webdav"). Those are fixed in the PR too.
To stop this from silently regressing again, the PR adds a small nox -s type-narrowing CI job. It runs mypy, pyright and ty on an assert_type file covering all literal protocols. On current main that file produces 32 errors each in pyright and ty.
Two known limitations:
- Only pyright validates storage options passed through
UPath(..., protocol=...). To get autocompletion and checks for storage options in every checker, use the implementation class or get_upath_class(...) as described above.
- The overloads are inherited by subclasses, so
S3Path("b/k", protocol="gcs") (which raises at runtime) is now inferred as GCSPath by pyright/ty instead of being flagged. If that becomes a problem, we can add a TYPE_CHECKING-only __new__ to the implementation classes.
I'll close this once the PR is released.