Fix type checking for open builtin
Merged
DA
1mo ago+608+608+012345678901234567890123456789-7-7-0123456789
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 toALLOWED_FUNCTIONS, so upstream typeshed'sopenandPath.opensignatures come through unchanged.iostubs: upstreamio.pyiand_io.pyiare added toCOPY_FILES.ioand_ioare listed inVERSIONSfor type checking only, likeabc.- Exceptions:
FileNotFoundError,FileExistsError,IsADirectoryError,NotADirectoryErrorandPermissionErrorare added toALLOWED_CLASSES, soexcept FileNotFoundError:aroundopen()type-checks. - Tests: new sections are appended to the ends of
good_types.py,reveal_types.pyandbad_types.py, so no existing snapshot entry moves.
A pytest writes through a read-write mount with type checking on. - Docs:
limitations/modules.mdanddocs/type-checking.mdlistioamong 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,closefdoropener, and encodings other than UTF-8 - integer file descriptors, and
'x'or'+'modes - file members Monty lacks, such as iterating a file,
writelines(),fileno()andreadline(size) import io
Follow-ups
- A narrowed
iostub, if iterating files turns out to be common. - These pass type checking and fail at runtime:
print(..., file=f);json.load(f)andjson.dump(obj, f);e.filenameande.errnoon theOSErrorsubclasses;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.pyiand_io.pyifrom typeshed and addsopento the allowed builtins. - Adds the OSError subclasses
open()can raise to the allowed class list, soexcept FileNotFoundError:type-checks. - Registers
ioand_ioas 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
ModuleNotFoundErrorat runtime.