Fix type checking for open builtin

Merged
DA
1mo ago
+608-7

https://github.com/pydantic/monty/issues/941

open() runs against mounted directories, but it failed type checking with unresolved-reference. update.py filters upstream builtins.pyi through ALLOWED_FUNCTIONS, and open was not on the list.
Path.open() resolved to Unknown, because the stub tree had no io module.

Changes

  • open: added to ALLOWED_FUNCTIONS, so upstream typeshed's open and Path.open signatures come through unchanged.
  • io stubs: upstream io.pyi and _io.pyi are added to COPY_FILES. io and _io are listed in VERSIONS for type checking only, like abc.
  • Exceptions: FileNotFoundError, FileExistsError, IsADirectoryError, NotADirectoryError and PermissionError are added to ALLOWED_CLASSES, so except FileNotFoundError: around open() type-checks.
  • Tests: new sections are appended to the ends of good_types.py, reveal_types.py and bad_types.py, so no existing snapshot entry moves.
    A pytest writes through a read-write mount with type checking on.
  • Docs: limitations/modules.md and docs/type-checking.md list io among the modules the type checker resolves but the runtime cannot import.

Trade-offs

Upstream's signatures accept any argument value the runtime might accept, so code that forwards encoding or buffering from a variable type-checks.
As a result, these pass type checking and then fail at runtime:

  • literal non-default buffering, errors, newline, closefd or opener, and encodings other than UTF-8
  • integer file descriptors, and 'x' or '+' modes
  • file members Monty lacks, such as iterating a file, writelines(), fileno() and readline(size)
  • import io

Follow-ups

  • A narrowed io stub, if iterating files turns out to be common.
  • These pass type checking and fail at runtime:
    • print(..., file=f);
    • json.load(f) and json.dump(obj, f);
    • e.filename and e.errno on the OSError subclasses;
    • except IOError:;
    • from typing import TextIO.

Summary by cubic

Fixes type checking for the open builtin by vendoring upstream typeshed's io stubs, so open() and Path.open() resolve with overloads for text and binary modes and invalid argument types are reported before execution.

  • Vendors io.pyi and _io.pyi from typeshed and adds open to the allowed builtins.
  • Adds the OSError subclasses open() can raise to the allowed class list, so except FileNotFoundError: type-checks.
  • Registers io and _io as stub-only modules for type checking.
  • Covers valid and invalid open/Path.open() calls, revealed file types, and a write-through run with type checking enabled.
  • Updates docs to list the additional stub-only modules that resolve during checking but raise ModuleNotFoundError at runtime.