open: introduce concrete return types (#4146)

* make io classes inherit from typing IO classes

This makes these classes usable if type annotations are given as "IO"
or "TextIO". In the future, we'll then be able to move open() to
return a concrete class instead (#3951).

* open: introduce concrete return types

Fixes #3951.

We use the values of the "mode" and "buffering" arguments to figure out
the concrete type open() will return at runtime. (Compare the CPython
code in https://github.com/python/cpython/blob/master/Modules/_io/_iomodule.c#L231.)
This commit is contained in:
Jelle Zijlstra
2020-05-31 15:48:12 -07:00
committed by GitHub
parent d863210335
commit adeda24fce
4 changed files with 156 additions and 25 deletions

View File

@@ -29,13 +29,22 @@ _OpenTextMode = Literal[
'x', 'x+', '+x', 'xt', 'tx', 'xt+', 'x+t', '+xt', 'tx+', 't+x', '+tx',
'U', 'rU', 'Ur', 'rtU', 'rUt', 'Urt', 'trU', 'tUr', 'Utr',
]
_OpenBinaryMode = Literal[
'rb', 'br', 'rb+', 'r+b', '+rb', 'br+', 'b+r', '+br',
'wb', 'bw', 'wb+', 'w+b', '+wb', 'bw+', 'b+w', '+bw',
'ab', 'ba', 'ab+', 'a+b', '+ab', 'ba+', 'b+a', '+ba',
'xb', 'bx', 'xb+', 'x+b', '+xb', 'bx+', 'b+x', '+bx',
_OpenBinaryModeUpdating = Literal[
'rb+', 'r+b', '+rb', 'br+', 'b+r', '+br',
'wb+', 'w+b', '+wb', 'bw+', 'b+w', '+bw',
'ab+', 'a+b', '+ab', 'ba+', 'b+a', '+ba',
'xb+', 'x+b', '+xb', 'bx+', 'b+x', '+bx',
]
_OpenBinaryModeWriting = Literal[
'wb', 'bw',
'ab', 'ba',
'xb', 'bx',
]
_OpenBinaryModeReading = Literal[
'rb', 'br',
'rbU', 'rUb', 'Urb', 'brU', 'bUr', 'Ubr',
]
_OpenBinaryMode = Union[_OpenBinaryModeUpdating, _OpenBinaryModeReading, _OpenBinaryModeWriting]
open = builtins.open