diff --git a/mypy/fastparse.py b/mypy/fastparse.py index b250095c74a8..15b86d71b3d2 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -660,7 +660,7 @@ def transform_args(self, ) -> List[Argument]: new_args = [] names = [] # type: List[ast3.arg] - args_args = getattr(args, "posonlyargs", []) + args.args + args_args = getattr(args, "posonlyargs", cast(List[ast3.arg], [])) + args.args args_defaults = args.defaults num_no_defaults = len(args_args) - len(args_defaults) # positional arguments without defaults diff --git a/mypy/typeshed/stdlib/@python2/Queue.pyi b/mypy/typeshed/stdlib/@python2/Queue.pyi index 98dda8722864..5297a4b76034 100644 --- a/mypy/typeshed/stdlib/@python2/Queue.pyi +++ b/mypy/typeshed/stdlib/@python2/Queue.pyi @@ -1,4 +1,3 @@ -from collections import deque from typing import Any, Deque, Generic, Optional, TypeVar _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/@python2/SocketServer.pyi b/mypy/typeshed/stdlib/@python2/SocketServer.pyi index b8a2c14ee5e2..ca6a31a0f2e1 100644 --- a/mypy/typeshed/stdlib/@python2/SocketServer.pyi +++ b/mypy/typeshed/stdlib/@python2/SocketServer.pyi @@ -1,7 +1,6 @@ import sys -import types from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Text, Tuple, Type, Union +from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Text, Tuple, Union class BaseServer: address_family: int diff --git a/mypy/typeshed/stdlib/@python2/UserString.pyi b/mypy/typeshed/stdlib/@python2/UserString.pyi index 33de4873992b..74ab34f6ac69 100644 --- a/mypy/typeshed/stdlib/@python2/UserString.pyi +++ b/mypy/typeshed/stdlib/@python2/UserString.pyi @@ -1,4 +1,3 @@ -import collections from typing import Any, Iterable, List, MutableSequence, Optional, Sequence, Text, Tuple, TypeVar, Union, overload _UST = TypeVar("_UST", bound=UserString) diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index 4eb5424d8da7..b7b68bbb7844 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -861,7 +861,12 @@ def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: .. @overload def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -def getattr(__o: Any, name: Text, __default: Any = ...) -> Any: ... +@overload +def getattr(__o: Any, name: Text) -> Any: ... +@overload +def getattr(__o: Any, name: Text, __default: None) -> Optional[Any]: ... +@overload +def getattr(__o: Any, name: Text, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/__future__.pyi b/mypy/typeshed/stdlib/@python2/__future__.pyi new file mode 100644 index 000000000000..8f5ff06ac080 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/__future__.pyi @@ -0,0 +1,17 @@ +import sys +from typing import List + +class _Feature: + def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... + def getOptionalRelease(self) -> sys._version_info: ... + def getMandatoryRelease(self) -> sys._version_info: ... + compiler_flag: int + +absolute_import: _Feature +division: _Feature +generators: _Feature +nested_scopes: _Feature +print_function: _Feature +unicode_literals: _Feature +with_statement: _Feature +all_feature_names: List[str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/__main__.pyi b/mypy/typeshed/stdlib/@python2/__main__.pyi new file mode 100644 index 000000000000..e27843e53382 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/__main__.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/_bisect.pyi b/mypy/typeshed/stdlib/@python2/_bisect.pyi new file mode 100644 index 000000000000..1e909c2a77d3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_bisect.pyi @@ -0,0 +1,8 @@ +from typing import MutableSequence, Optional, Sequence, TypeVar + +_T = TypeVar("_T") + +def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: Optional[int] = ...) -> int: ... +def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: Optional[int] = ...) -> int: ... +def insort_left(a: MutableSequence[_T], x: _T, lo: int = ..., hi: Optional[int] = ...) -> None: ... +def insort_right(a: MutableSequence[_T], x: _T, lo: int = ..., hi: Optional[int] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_codecs.pyi b/mypy/typeshed/stdlib/@python2/_codecs.pyi new file mode 100644 index 000000000000..70f7da857f5a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_codecs.pyi @@ -0,0 +1,66 @@ +import codecs +import sys +from typing import Any, Callable, Dict, Optional, Text, Tuple, Union + +# For convenience: +_Handler = Callable[[Exception], Tuple[Text, int]] +_String = Union[bytes, str] +_Errors = Union[str, Text, None] +_Decodable = Union[bytes, Text] +_Encodable = Union[bytes, Text] + +# This type is not exposed; it is defined in unicodeobject.c +class _EncodingMap(object): + def size(self) -> int: ... + +_MapT = Union[Dict[int, int], _EncodingMap] + +def register(__search_function: Callable[[str], Any]) -> None: ... +def register_error(__errors: Union[str, Text], __handler: _Handler) -> None: ... +def lookup(__encoding: Union[str, Text]) -> codecs.CodecInfo: ... +def lookup_error(__name: Union[str, Text]) -> _Handler: ... +def decode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... +def encode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... +def charmap_build(__map: Text) -> _MapT: ... +def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... +def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: Optional[_MapT] = ...) -> Tuple[Text, int]: ... +def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: Optional[_MapT] = ...) -> Tuple[bytes, int]: ... +def escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[str, int]: ... +def escape_encode(__data: bytes, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... +def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... +def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... +def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... +def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +def utf_16_ex_decode( + __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... +) -> Tuple[Text, int, int]: ... +def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +def utf_32_ex_decode( + __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... +) -> Tuple[Text, int, int]: ... +def utf_32_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_32_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_7_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_7_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_8_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... +def utf_8_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... + +if sys.platform == "win32": + def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... + def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/_csv.pyi b/mypy/typeshed/stdlib/@python2/_csv.pyi new file mode 100644 index 000000000000..e194cc625889 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_csv.pyi @@ -0,0 +1,42 @@ +from typing import Any, Iterable, Iterator, List, Optional, Protocol, Sequence, Text, Type, Union + +QUOTE_ALL: int +QUOTE_MINIMAL: int +QUOTE_NONE: int +QUOTE_NONNUMERIC: int + +class Error(Exception): ... + +class Dialect: + delimiter: str + quotechar: Optional[str] + escapechar: Optional[str] + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: int + strict: int + def __init__(self) -> None: ... + +_DialectLike = Union[str, Dialect, Type[Dialect]] + +class _reader(Iterator[List[str]]): + dialect: Dialect + line_num: int + def next(self) -> List[str]: ... + +class _writer: + dialect: Dialect + def writerow(self, row: Sequence[Any]) -> Any: ... + def writerows(self, rows: Iterable[Sequence[Any]]) -> None: ... + +class _Writer(Protocol): + def write(self, s: str) -> Any: ... + +def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... +def reader(csvfile: Iterable[Text], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... +def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... +def unregister_dialect(name: str) -> None: ... +def get_dialect(name: str) -> Dialect: ... +def list_dialects() -> List[str]: ... +def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/_curses.pyi b/mypy/typeshed/stdlib/@python2/_curses.pyi new file mode 100644 index 000000000000..d6c286e37d13 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_curses.pyi @@ -0,0 +1,511 @@ +from typing import IO, Any, BinaryIO, Optional, Tuple, Union, overload + +_chtype = Union[str, bytes, int] + +# ACS codes are only initialized after initscr is called +ACS_BBSS: int +ACS_BLOCK: int +ACS_BOARD: int +ACS_BSBS: int +ACS_BSSB: int +ACS_BSSS: int +ACS_BTEE: int +ACS_BULLET: int +ACS_CKBOARD: int +ACS_DARROW: int +ACS_DEGREE: int +ACS_DIAMOND: int +ACS_GEQUAL: int +ACS_HLINE: int +ACS_LANTERN: int +ACS_LARROW: int +ACS_LEQUAL: int +ACS_LLCORNER: int +ACS_LRCORNER: int +ACS_LTEE: int +ACS_NEQUAL: int +ACS_PI: int +ACS_PLMINUS: int +ACS_PLUS: int +ACS_RARROW: int +ACS_RTEE: int +ACS_S1: int +ACS_S3: int +ACS_S7: int +ACS_S9: int +ACS_SBBS: int +ACS_SBSB: int +ACS_SBSS: int +ACS_SSBB: int +ACS_SSBS: int +ACS_SSSB: int +ACS_SSSS: int +ACS_STERLING: int +ACS_TTEE: int +ACS_UARROW: int +ACS_ULCORNER: int +ACS_URCORNER: int +ACS_VLINE: int +ALL_MOUSE_EVENTS: int +A_ALTCHARSET: int +A_ATTRIBUTES: int +A_BLINK: int +A_BOLD: int +A_CHARTEXT: int +A_COLOR: int +A_DIM: int +A_HORIZONTAL: int +A_INVIS: int +A_LEFT: int +A_LOW: int +A_NORMAL: int +A_PROTECT: int +A_REVERSE: int +A_RIGHT: int +A_STANDOUT: int +A_TOP: int +A_UNDERLINE: int +A_VERTICAL: int +BUTTON1_CLICKED: int +BUTTON1_DOUBLE_CLICKED: int +BUTTON1_PRESSED: int +BUTTON1_RELEASED: int +BUTTON1_TRIPLE_CLICKED: int +BUTTON2_CLICKED: int +BUTTON2_DOUBLE_CLICKED: int +BUTTON2_PRESSED: int +BUTTON2_RELEASED: int +BUTTON2_TRIPLE_CLICKED: int +BUTTON3_CLICKED: int +BUTTON3_DOUBLE_CLICKED: int +BUTTON3_PRESSED: int +BUTTON3_RELEASED: int +BUTTON3_TRIPLE_CLICKED: int +BUTTON4_CLICKED: int +BUTTON4_DOUBLE_CLICKED: int +BUTTON4_PRESSED: int +BUTTON4_RELEASED: int +BUTTON4_TRIPLE_CLICKED: int +BUTTON_ALT: int +BUTTON_CTRL: int +BUTTON_SHIFT: int +COLOR_BLACK: int +COLOR_BLUE: int +COLOR_CYAN: int +COLOR_GREEN: int +COLOR_MAGENTA: int +COLOR_RED: int +COLOR_WHITE: int +COLOR_YELLOW: int +ERR: int +KEY_A1: int +KEY_A3: int +KEY_B2: int +KEY_BACKSPACE: int +KEY_BEG: int +KEY_BREAK: int +KEY_BTAB: int +KEY_C1: int +KEY_C3: int +KEY_CANCEL: int +KEY_CATAB: int +KEY_CLEAR: int +KEY_CLOSE: int +KEY_COMMAND: int +KEY_COPY: int +KEY_CREATE: int +KEY_CTAB: int +KEY_DC: int +KEY_DL: int +KEY_DOWN: int +KEY_EIC: int +KEY_END: int +KEY_ENTER: int +KEY_EOL: int +KEY_EOS: int +KEY_EXIT: int +KEY_F0: int +KEY_F1: int +KEY_F10: int +KEY_F11: int +KEY_F12: int +KEY_F13: int +KEY_F14: int +KEY_F15: int +KEY_F16: int +KEY_F17: int +KEY_F18: int +KEY_F19: int +KEY_F2: int +KEY_F20: int +KEY_F21: int +KEY_F22: int +KEY_F23: int +KEY_F24: int +KEY_F25: int +KEY_F26: int +KEY_F27: int +KEY_F28: int +KEY_F29: int +KEY_F3: int +KEY_F30: int +KEY_F31: int +KEY_F32: int +KEY_F33: int +KEY_F34: int +KEY_F35: int +KEY_F36: int +KEY_F37: int +KEY_F38: int +KEY_F39: int +KEY_F4: int +KEY_F40: int +KEY_F41: int +KEY_F42: int +KEY_F43: int +KEY_F44: int +KEY_F45: int +KEY_F46: int +KEY_F47: int +KEY_F48: int +KEY_F49: int +KEY_F5: int +KEY_F50: int +KEY_F51: int +KEY_F52: int +KEY_F53: int +KEY_F54: int +KEY_F55: int +KEY_F56: int +KEY_F57: int +KEY_F58: int +KEY_F59: int +KEY_F6: int +KEY_F60: int +KEY_F61: int +KEY_F62: int +KEY_F63: int +KEY_F7: int +KEY_F8: int +KEY_F9: int +KEY_FIND: int +KEY_HELP: int +KEY_HOME: int +KEY_IC: int +KEY_IL: int +KEY_LEFT: int +KEY_LL: int +KEY_MARK: int +KEY_MAX: int +KEY_MESSAGE: int +KEY_MIN: int +KEY_MOUSE: int +KEY_MOVE: int +KEY_NEXT: int +KEY_NPAGE: int +KEY_OPEN: int +KEY_OPTIONS: int +KEY_PPAGE: int +KEY_PREVIOUS: int +KEY_PRINT: int +KEY_REDO: int +KEY_REFERENCE: int +KEY_REFRESH: int +KEY_REPLACE: int +KEY_RESET: int +KEY_RESIZE: int +KEY_RESTART: int +KEY_RESUME: int +KEY_RIGHT: int +KEY_SAVE: int +KEY_SBEG: int +KEY_SCANCEL: int +KEY_SCOMMAND: int +KEY_SCOPY: int +KEY_SCREATE: int +KEY_SDC: int +KEY_SDL: int +KEY_SELECT: int +KEY_SEND: int +KEY_SEOL: int +KEY_SEXIT: int +KEY_SF: int +KEY_SFIND: int +KEY_SHELP: int +KEY_SHOME: int +KEY_SIC: int +KEY_SLEFT: int +KEY_SMESSAGE: int +KEY_SMOVE: int +KEY_SNEXT: int +KEY_SOPTIONS: int +KEY_SPREVIOUS: int +KEY_SPRINT: int +KEY_SR: int +KEY_SREDO: int +KEY_SREPLACE: int +KEY_SRESET: int +KEY_SRIGHT: int +KEY_SRSUME: int +KEY_SSAVE: int +KEY_SSUSPEND: int +KEY_STAB: int +KEY_SUNDO: int +KEY_SUSPEND: int +KEY_UNDO: int +KEY_UP: int +OK: int +REPORT_MOUSE_POSITION: int +_C_API: Any +version: bytes + +def baudrate() -> int: ... +def beep() -> None: ... +def can_change_color() -> bool: ... +def cbreak(__flag: bool = ...) -> None: ... +def color_content(__color_number: int) -> Tuple[int, int, int]: ... + +# Changed in Python 3.8.8 and 3.9.2 +def color_pair(__color_number: int) -> int: ... +def curs_set(__visibility: int) -> int: ... +def def_prog_mode() -> None: ... +def def_shell_mode() -> None: ... +def delay_output(__ms: int) -> None: ... +def doupdate() -> None: ... +def echo(__flag: bool = ...) -> None: ... +def endwin() -> None: ... +def erasechar() -> bytes: ... +def filter() -> None: ... +def flash() -> None: ... +def flushinp() -> None: ... +def getmouse() -> Tuple[int, int, int, int, int]: ... +def getsyx() -> Tuple[int, int]: ... +def getwin(__file: BinaryIO) -> _CursesWindow: ... +def halfdelay(__tenths: int) -> None: ... +def has_colors() -> bool: ... +def has_ic() -> bool: ... +def has_il() -> bool: ... +def has_key(__key: int) -> bool: ... +def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... +def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... +def initscr() -> _CursesWindow: ... +def intrflush(__flag: bool) -> None: ... +def is_term_resized(__nlines: int, __ncols: int) -> bool: ... +def isendwin() -> bool: ... +def keyname(__key: int) -> bytes: ... +def killchar() -> bytes: ... +def longname() -> bytes: ... +def meta(__yes: bool) -> None: ... +def mouseinterval(__interval: int) -> None: ... +def mousemask(__newmask: int) -> Tuple[int, int]: ... +def napms(__ms: int) -> int: ... +def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... +def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... +def nl(__flag: bool = ...) -> None: ... +def nocbreak() -> None: ... +def noecho() -> None: ... +def nonl() -> None: ... +def noqiflush() -> None: ... +def noraw() -> None: ... +def pair_content(__pair_number: int) -> Tuple[int, int]: ... +def pair_number(__attr: int) -> int: ... +def putp(__string: bytes) -> None: ... +def qiflush(__flag: bool = ...) -> None: ... +def raw(__flag: bool = ...) -> None: ... +def reset_prog_mode() -> None: ... +def reset_shell_mode() -> None: ... +def resetty() -> None: ... +def resize_term(__nlines: int, __ncols: int) -> None: ... +def resizeterm(__nlines: int, __ncols: int) -> None: ... +def savetty() -> None: ... +def setsyx(__y: int, __x: int) -> None: ... +def setupterm(term: Optional[str] = ..., fd: int = ...) -> None: ... +def start_color() -> None: ... +def termattrs() -> int: ... +def termname() -> bytes: ... +def tigetflag(__capname: str) -> int: ... +def tigetnum(__capname: str) -> int: ... +def tigetstr(__capname: str) -> bytes: ... +def tparm( + __str: bytes, + __i1: int = ..., + __i2: int = ..., + __i3: int = ..., + __i4: int = ..., + __i5: int = ..., + __i6: int = ..., + __i7: int = ..., + __i8: int = ..., + __i9: int = ..., +) -> bytes: ... +def typeahead(__fd: int) -> None: ... +def unctrl(__ch: _chtype) -> bytes: ... +def ungetch(__ch: _chtype) -> None: ... +def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... +def use_default_colors() -> None: ... +def use_env(__flag: bool) -> None: ... + +class error(Exception): ... + +class _CursesWindow: + @overload + def addch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addstr(self, str: str, attr: int = ...) -> None: ... + @overload + def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + def attroff(self, __attr: int) -> None: ... + def attron(self, __attr: int) -> None: ... + def attrset(self, __attr: int) -> None: ... + def bkgd(self, __ch: _chtype, __attr: int = ...) -> None: ... + def bkgdset(self, __ch: _chtype, __attr: int = ...) -> None: ... + def border( + self, + ls: _chtype = ..., + rs: _chtype = ..., + ts: _chtype = ..., + bs: _chtype = ..., + tl: _chtype = ..., + tr: _chtype = ..., + bl: _chtype = ..., + br: _chtype = ..., + ) -> None: ... + @overload + def box(self) -> None: ... + @overload + def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... + @overload + def chgat(self, attr: int) -> None: ... + @overload + def chgat(self, num: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + def clear(self) -> None: ... + def clearok(self, yes: int) -> None: ... + def clrtobot(self) -> None: ... + def clrtoeol(self) -> None: ... + def cursyncup(self) -> None: ... + @overload + def delch(self) -> None: ... + @overload + def delch(self, y: int, x: int) -> None: ... + def deleteln(self) -> None: ... + @overload + def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... + def enclose(self, __y: int, __x: int) -> bool: ... + def erase(self) -> None: ... + def getbegyx(self) -> Tuple[int, int]: ... + def getbkgd(self) -> Tuple[int, int]: ... + @overload + def getch(self) -> int: ... + @overload + def getch(self, y: int, x: int) -> int: ... + @overload + def getkey(self) -> str: ... + @overload + def getkey(self, y: int, x: int) -> str: ... + def getmaxyx(self) -> Tuple[int, int]: ... + def getparyx(self) -> Tuple[int, int]: ... + @overload + def getstr(self) -> _chtype: ... + @overload + def getstr(self, n: int) -> _chtype: ... + @overload + def getstr(self, y: int, x: int) -> _chtype: ... + @overload + def getstr(self, y: int, x: int, n: int) -> _chtype: ... + def getyx(self) -> Tuple[int, int]: ... + @overload + def hline(self, ch: _chtype, n: int) -> None: ... + @overload + def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... + def idcok(self, flag: bool) -> None: ... + def idlok(self, yes: bool) -> None: ... + def immedok(self, flag: bool) -> None: ... + @overload + def inch(self) -> _chtype: ... + @overload + def inch(self, y: int, x: int) -> _chtype: ... + @overload + def insch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + def insdelln(self, nlines: int) -> None: ... + def insertln(self) -> None: ... + @overload + def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insstr(self, str: str, attr: int = ...) -> None: ... + @overload + def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + @overload + def instr(self, n: int = ...) -> _chtype: ... + @overload + def instr(self, y: int, x: int, n: int = ...) -> _chtype: ... + def is_linetouched(self, __line: int) -> bool: ... + def is_wintouched(self) -> bool: ... + def keypad(self, yes: bool) -> None: ... + def leaveok(self, yes: bool) -> None: ... + def move(self, new_y: int, new_x: int) -> None: ... + def mvderwin(self, y: int, x: int) -> None: ... + def mvwin(self, new_y: int, new_x: int) -> None: ... + def nodelay(self, yes: bool) -> None: ... + def notimeout(self, yes: bool) -> None: ... + def noutrefresh(self) -> None: ... + @overload + def overlay(self, destwin: _CursesWindow) -> None: ... + @overload + def overlay( + self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + @overload + def overwrite(self, destwin: _CursesWindow) -> None: ... + @overload + def overwrite( + self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + def putwin(self, __file: IO[Any]) -> None: ... + def redrawln(self, __beg: int, __num: int) -> None: ... + def redrawwin(self) -> None: ... + @overload + def refresh(self) -> None: ... + @overload + def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + def resize(self, nlines: int, ncols: int) -> None: ... + def scroll(self, lines: int = ...) -> None: ... + def scrollok(self, flag: bool) -> None: ... + def setscrreg(self, __top: int, __bottom: int) -> None: ... + def standend(self) -> None: ... + def standout(self) -> None: ... + @overload + def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def syncdown(self) -> None: ... + def syncok(self, flag: bool) -> None: ... + def syncup(self) -> None: ... + def timeout(self, delay: int) -> None: ... + def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... + def touchwin(self) -> None: ... + def untouchwin(self) -> None: ... + @overload + def vline(self, ch: _chtype, n: int) -> None: ... + @overload + def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi new file mode 100644 index 000000000000..bab2acdc84cd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi @@ -0,0 +1,109 @@ +from types import FrameType, TracebackType +from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar, Union + +# TODO recursive type +_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] + +_PF = Callable[[FrameType, str, Any], None] +_T = TypeVar("_T") + +__all__: List[str] + +def active_count() -> int: ... +def activeCount() -> int: ... +def current_thread() -> Thread: ... +def currentThread() -> Thread: ... +def enumerate() -> List[Thread]: ... +def settrace(func: _TF) -> None: ... +def setprofile(func: Optional[_PF]) -> None: ... +def stack_size(size: int = ...) -> int: ... + +class ThreadError(Exception): ... + +class local(object): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class Thread: + name: str + ident: Optional[int] + daemon: bool + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: Optional[Mapping[Text, Any]] = ..., + ) -> None: ... + def start(self) -> None: ... + def run(self) -> None: ... + def join(self, timeout: Optional[float] = ...) -> None: ... + def getName(self) -> str: ... + def setName(self, name: Text) -> None: ... + def is_alive(self) -> bool: ... + def isAlive(self) -> bool: ... + def isDaemon(self) -> bool: ... + def setDaemon(self, daemonic: bool) -> None: ... + +class _DummyThread(Thread): ... + +class Lock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + +class _RLock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + +RLock = _RLock + +class Condition: + def __init__(self, lock: Union[Lock, _RLock, None] = ...) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + def notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + def notifyAll(self) -> None: ... + +class Semaphore: + def __init__(self, value: int = ...) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def __enter__(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + +class BoundedSemaphore(Semaphore): ... + +class Event: + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + def isSet(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + +class Timer(Thread): + def __init__( + self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... + ) -> None: ... + def cancel(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_functools.pyi b/mypy/typeshed/stdlib/@python2/_functools.pyi index 697abb78272a..e68398238f9b 100644 --- a/mypy/typeshed/stdlib/@python2/_functools.pyi +++ b/mypy/typeshed/stdlib/@python2/_functools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Optional, Tuple, TypeVar, overload +from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") diff --git a/mypy/typeshed/stdlib/@python2/_heapq.pyi b/mypy/typeshed/stdlib/@python2/_heapq.pyi new file mode 100644 index 000000000000..f02fc470df14 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_heapq.pyi @@ -0,0 +1,11 @@ +from typing import Any, Callable, Iterable, List, Optional, TypeVar + +_T = TypeVar("_T") + +def heapify(__heap: List[Any]) -> None: ... +def heappop(__heap: List[_T]) -> _T: ... +def heappush(__heap: List[_T], __item: _T) -> None: ... +def heappushpop(__heap: List[_T], __item: _T) -> _T: ... +def heapreplace(__heap: List[_T], __item: _T) -> _T: ... +def nlargest(__n: int, __iterable: Iterable[_T], __key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... +def nsmallest(__n: int, __iterable: Iterable[_T], __key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/_hotshot.pyi b/mypy/typeshed/stdlib/@python2/_hotshot.pyi index 46c365f4b60b..b048f6fb83d5 100644 --- a/mypy/typeshed/stdlib/@python2/_hotshot.pyi +++ b/mypy/typeshed/stdlib/@python2/_hotshot.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, Generic, List, Tuple +from typing import Any, Tuple def coverage(a: str) -> Any: ... def logreader(a: str) -> LogReaderType: ... diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi index b88f3de0fae3..4eafef332985 100644 --- a/mypy/typeshed/stdlib/@python2/_io.pyi +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -1,6 +1,5 @@ from mmap import mmap -from types import TracebackType -from typing import IO, Any, AnyStr, BinaryIO, Iterable, Iterator, List, Optional, Text, TextIO, Tuple, Type, TypeVar, Union +from typing import IO, Any, BinaryIO, Iterable, List, Optional, Text, TextIO, Tuple, Type, TypeVar, Union _bytearray_like = Union[bytearray, mmap] diff --git a/mypy/typeshed/stdlib/@python2/_json.pyi b/mypy/typeshed/stdlib/@python2/_json.pyi index 1c8e0409feaf..a9868b3e60fd 100644 --- a/mypy/typeshed/stdlib/@python2/_json.pyi +++ b/mypy/typeshed/stdlib/@python2/_json.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, Generic, List, Tuple +from typing import Any, Tuple def encode_basestring_ascii(*args, **kwargs) -> str: ... def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/_markupbase.pyi b/mypy/typeshed/stdlib/@python2/_markupbase.pyi new file mode 100644 index 000000000000..d8bc79f34e8c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_markupbase.pyi @@ -0,0 +1,8 @@ +from typing import Tuple + +class ParserBase: + def __init__(self) -> None: ... + def error(self, message: str) -> None: ... + def reset(self) -> None: ... + def getpos(self) -> Tuple[int, int]: ... + def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_msi.pyi b/mypy/typeshed/stdlib/@python2/_msi.pyi new file mode 100644 index 000000000000..a8f9c60bbadd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_msi.pyi @@ -0,0 +1,49 @@ +import sys +from typing import List, Optional, Union + +if sys.platform == "win32": + + # Actual typename View, not exposed by the implementation + class _View: + def Execute(self, params: Optional[_Record] = ...) -> None: ... + def GetColumnInfo(self, kind: int) -> _Record: ... + def Fetch(self) -> _Record: ... + def Modify(self, mode: int, record: _Record) -> None: ... + def Close(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + # Actual typename Summary, not exposed by the implementation + class _Summary: + def GetProperty(self, propid: int) -> Optional[Union[str, bytes]]: ... + def GetPropertyCount(self) -> int: ... + def SetProperty(self, propid: int, value: Union[str, bytes]) -> None: ... + def Persist(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + # Actual typename Database, not exposed by the implementation + class _Database: + def OpenView(self, sql: str) -> _View: ... + def Commit(self) -> None: ... + def GetSummaryInformation(self, updateCount: int) -> _Summary: ... + def Close(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + # Actual typename Record, not exposed by the implementation + class _Record: + def GetFieldCount(self) -> int: ... + def GetInteger(self, field: int) -> int: ... + def GetString(self, field: int) -> str: ... + def SetString(self, field: int, str: str) -> None: ... + def SetStream(self, field: int, stream: str) -> None: ... + def SetInteger(self, field: int, int: int) -> None: ... + def ClearData(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + def UuidCreate() -> str: ... + def FCICreate(cabname: str, files: List[str]) -> None: ... + def OpenDatabase(name: str, flags: int) -> _Database: ... + def CreateRecord(count: int) -> _Record: ... diff --git a/mypy/typeshed/stdlib/@python2/_osx_support.pyi b/mypy/typeshed/stdlib/@python2/_osx_support.pyi new file mode 100644 index 000000000000..5d67d996b30a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_osx_support.pyi @@ -0,0 +1,33 @@ +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +__all__: List[str] + +_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented +_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented +_INITPRE: str # undocumented + +def _find_executable(executable: str, path: Optional[str] = ...) -> Optional[str]: ... # undocumented +def _read_output(commandstring: str) -> Optional[str]: ... # undocumented +def _find_build_tool(toolname: str) -> str: ... # undocumented + +_SYSTEM_VERSION: Optional[str] # undocumented + +def _get_system_version() -> str: ... # undocumented +def _remove_original_values(_config_vars: Dict[str, str]) -> None: ... # undocumented +def _save_modified_value(_config_vars: Dict[str, str], cv: str, newvalue: str) -> None: ... # undocumented +def _supports_universal_builds() -> bool: ... # undocumented +def _find_appropriate_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented +def _remove_universal_flags(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented +def _remove_unsupported_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented +def _override_all_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented +def _check_for_unavailable_sdk(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented +def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> List[str]: ... +def customize_config_vars(_config_vars: Dict[str, str]) -> Dict[str, str]: ... +def customize_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... +def get_platform_osx( + _config_vars: Dict[str, str], osname: _T, release: _K, machine: _V +) -> Tuple[Union[str, _T], Union[str, _K], Union[str, _V]]: ... diff --git a/mypy/typeshed/stdlib/@python2/_random.pyi b/mypy/typeshed/stdlib/@python2/_random.pyi new file mode 100644 index 000000000000..7c2dd61af49f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_random.pyi @@ -0,0 +1,13 @@ +from typing import Tuple + +# Actually Tuple[(int,) * 625] +_State = Tuple[int, ...] + +class Random(object): + def __init__(self, seed: object = ...) -> None: ... + def seed(self, __n: object = ...) -> None: ... + def getstate(self) -> _State: ... + def setstate(self, __state: _State) -> None: ... + def random(self) -> float: ... + def getrandbits(self, __k: int) -> int: ... + def jumpahead(self, i: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_thread.pyi b/mypy/typeshed/stdlib/@python2/_thread.pyi new file mode 100644 index 000000000000..46a6c7741024 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_thread.pyi @@ -0,0 +1,26 @@ +from types import TracebackType +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple, Type + +error = RuntimeError + +def _count() -> int: ... + +_dangling: Any + +class LockType: + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + def __enter__(self) -> bool: ... + def __exit__( + self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> int: ... +def interrupt_main() -> None: ... +def exit() -> NoReturn: ... +def allocate_lock() -> LockType: ... +def get_ident() -> int: ... +def stack_size(size: int = ...) -> int: ... + +TIMEOUT_MAX: float diff --git a/mypy/typeshed/stdlib/@python2/_tkinter.pyi b/mypy/typeshed/stdlib/@python2/_tkinter.pyi new file mode 100644 index 000000000000..378b04202c4f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_tkinter.pyi @@ -0,0 +1,95 @@ +from typing import Any +from typing_extensions import Literal + +# _tkinter is meant to be only used internally by tkinter, but some tkinter +# functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl +# object that hasn't been converted to a string. +# +# There are not many ways to get Tcl_Objs from tkinter, and I'm not sure if the +# only existing ways are supposed to return Tcl_Objs as opposed to returning +# strings. Here's one of these things that return Tcl_Objs: +# +# >>> import tkinter +# >>> text = tkinter.Text() +# >>> text.tag_add('foo', '1.0', 'end') +# >>> text.tag_ranges('foo') +# (, ) +class Tcl_Obj: + string: str # str(tclobj) returns this + typename: str + +class TclError(Exception): ... + +# This class allows running Tcl code. Tkinter uses it internally a lot, and +# it's often handy to drop a piece of Tcl code into a tkinter program. Example: +# +# >>> import tkinter, _tkinter +# >>> tkapp = tkinter.Tk().tk +# >>> isinstance(tkapp, _tkinter.TkappType) +# True +# >>> tkapp.call('set', 'foo', (1,2,3)) +# (1, 2, 3) +# >>> tkapp.eval('return $foo') +# '1 2 3' +# >>> +# +# call args can be pretty much anything. Also, call(some_tuple) is same as call(*some_tuple). +# +# eval always returns str because _tkinter_tkapp_eval_impl in _tkinter.c calls +# Tkapp_UnicodeResult, and it returns a string when it succeeds. +class TkappType: + # Please keep in sync with tkinter.Tk + def call(self, __command: Any, *args: Any) -> Any: ... + def eval(self, __script: str) -> str: ... + adderrorinfo: Any + createcommand: Any + createfilehandler: Any + createtimerhandler: Any + deletecommand: Any + deletefilehandler: Any + dooneevent: Any + evalfile: Any + exprboolean: Any + exprdouble: Any + exprlong: Any + exprstring: Any + getboolean: Any + getdouble: Any + getint: Any + getvar: Any + globalgetvar: Any + globalsetvar: Any + globalunsetvar: Any + interpaddr: Any + loadtk: Any + mainloop: Any + quit: Any + record: Any + setvar: Any + split: Any + splitlist: Any + unsetvar: Any + wantobjects: Any + willdispatch: Any + +# These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS +ALL_EVENTS: Literal[-3] +FILE_EVENTS: Literal[8] +IDLE_EVENTS: Literal[32] +TIMER_EVENTS: Literal[16] +WINDOW_EVENTS: Literal[4] + +DONT_WAIT: Literal[2] +EXCEPTION: Literal[8] +READABLE: Literal[2] +WRITABLE: Literal[4] + +TCL_VERSION: str +TK_VERSION: str + +# TODO: figure out what these are (with e.g. help()) and get rid of Any +TkttType: Any +_flatten: Any +create: Any +getbusywaitinterval: Any +setbusywaitinterval: Any diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi new file mode 100644 index 000000000000..9548a2497943 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi @@ -0,0 +1,158 @@ +# Utility types for typeshed + +# This module contains various common types to be used by typeshed. The +# module and its types do not exist at runtime. You can use this module +# outside of typeshed, but no API stability guarantees are made. To use +# it in implementation (.py) files, the following construct must be used: +# +# from typing import TYPE_CHECKING +# if TYPE_CHECKING: +# from _typeshed import ... +# +# If on Python versions < 3.10 and "from __future__ import annotations" +# is not used, types from this module must be quoted. + +import array +import mmap +from typing import Any, Container, Iterable, Protocol, Text, Tuple, TypeVar, Union +from typing_extensions import Literal, final + +_KT = TypeVar("_KT") +_KT_co = TypeVar("_KT_co", covariant=True) +_KT_contra = TypeVar("_KT_contra", contravariant=True) +_VT = TypeVar("_VT") +_VT_co = TypeVar("_VT_co", covariant=True) +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) + +class IdentityFunction(Protocol): + def __call__(self, __x: _T) -> _T: ... + +class SupportsLessThan(Protocol): + def __lt__(self, __other: Any) -> bool: ... + +SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 + +class SupportsDivMod(Protocol[_T_contra, _T_co]): + def __divmod__(self, __other: _T_contra) -> _T_co: ... + +class SupportsRDivMod(Protocol[_T_contra, _T_co]): + def __rdivmod__(self, __other: _T_contra) -> _T_co: ... + +# Mapping-like protocols + +class SupportsItems(Protocol[_KT_co, _VT_co]): + # We want dictionaries to support this on Python 2. + def items(self) -> Iterable[Tuple[_KT_co, _VT_co]]: ... + +class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): + def keys(self) -> Iterable[_KT]: ... + def __getitem__(self, __k: _KT) -> _VT_co: ... + +class SupportsGetItem(Container[_KT_contra], Protocol[_KT_contra, _VT_co]): + def __getitem__(self, __k: _KT_contra) -> _VT_co: ... + +class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): + def __setitem__(self, __k: _KT_contra, __v: _VT) -> None: ... + def __delitem__(self, __v: _KT_contra) -> None: ... + +# These aliases can be used in places where a PathLike object can be used +# instead of a string in Python 3. +StrPath = Text +BytesPath = str +StrOrBytesPath = Text +AnyPath = StrOrBytesPath # obsolete, will be removed soon + +OpenTextModeUpdating = Literal[ + "r+", + "+r", + "rt+", + "r+t", + "+rt", + "tr+", + "t+r", + "+tr", + "w+", + "+w", + "wt+", + "w+t", + "+wt", + "tw+", + "t+w", + "+tw", + "a+", + "+a", + "at+", + "a+t", + "+at", + "ta+", + "t+a", + "+ta", + "x+", + "+x", + "xt+", + "x+t", + "+xt", + "tx+", + "t+x", + "+tx", +] +OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] +OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] +OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] +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] + +class HasFileno(Protocol): + def fileno(self) -> int: ... + +FileDescriptor = int +FileDescriptorLike = Union[int, HasFileno] + +class SupportsRead(Protocol[_T_co]): + def read(self, __length: int = ...) -> _T_co: ... + +class SupportsReadline(Protocol[_T_co]): + def readline(self, __length: int = ...) -> _T_co: ... + +class SupportsNoArgReadline(Protocol[_T_co]): + def readline(self) -> _T_co: ... + +class SupportsWrite(Protocol[_T_contra]): + def write(self, __s: _T_contra) -> Any: ... + +ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] +WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] + +# Used by type checkers for checks involving None (does not exist at runtime) +@final +class NoneType: + def __bool__(self) -> Literal[False]: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi new file mode 100644 index 000000000000..bafaf7bc5f66 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi @@ -0,0 +1,35 @@ +# Types to support PEP 3333 (WSGI) +# +# This module doesn't exist at runtime and neither do the types defined in this +# file. They are provided for type checking purposes. + +from sys import _OptExcInfo +from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Text, Tuple + +class StartResponse(Protocol): + def __call__( + self, status: str, headers: List[Tuple[str, str]], exc_info: Optional[_OptExcInfo] = ... + ) -> Callable[[bytes], Any]: ... + +WSGIEnvironment = Dict[Text, Any] +WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] + +# WSGI input streams per PEP 3333 +class InputStream(Protocol): + def read(self, size: int = ...) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def __iter__(self) -> Iterable[bytes]: ... + +# WSGI error streams per PEP 3333 +class ErrorStream(Protocol): + def flush(self) -> None: ... + def write(self, s: str) -> None: ... + def writelines(self, seq: List[str]) -> None: ... + +class _Readable(Protocol): + def read(self, size: int = ...) -> bytes: ... + +# Optional file wrapper in wsgi.file_wrapper +class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ...) -> Iterable[bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi new file mode 100644 index 000000000000..7ad28aef1b75 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi @@ -0,0 +1,10 @@ +# Stub-only types. This module does not exist at runtime. + +from typing import Any, Optional +from typing_extensions import Protocol + +# As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects +class DOMImplementation(Protocol): + def hasFeature(self, feature: str, version: Optional[str]) -> bool: ... + def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Optional[Any]) -> Any: ... + def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/_warnings.pyi b/mypy/typeshed/stdlib/@python2/_warnings.pyi new file mode 100644 index 000000000000..d16637e6814c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_warnings.pyi @@ -0,0 +1,31 @@ +from typing import Any, Dict, List, Optional, Tuple, Type, Union, overload + +default_action: str +once_registry: Dict[Any, Any] + +filters: List[Tuple[Any, ...]] + +@overload +def warn(message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ...) -> None: ... +@overload +def warn(message: Warning, category: Any = ..., stacklevel: int = ...) -> None: ... +@overload +def warn_explicit( + message: str, + category: Type[Warning], + filename: str, + lineno: int, + module: Optional[str] = ..., + registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., + module_globals: Optional[Dict[str, Any]] = ..., +) -> None: ... +@overload +def warn_explicit( + message: Warning, + category: Any, + filename: str, + lineno: int, + module: Optional[str] = ..., + registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., + module_globals: Optional[Dict[str, Any]] = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakref.pyi b/mypy/typeshed/stdlib/@python2/_weakref.pyi new file mode 100644 index 000000000000..e8882b6f18b8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_weakref.pyi @@ -0,0 +1,26 @@ +from typing import Any, Callable, Generic, List, Optional, TypeVar, overload + +_C = TypeVar("_C", bound=Callable[..., Any]) +_T = TypeVar("_T") + +class CallableProxyType(Generic[_C]): # "weakcallableproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ProxyType(Generic[_T]): # "weakproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ReferenceType(Generic[_T]): + def __init__(self, o: _T, callback: Optional[Callable[[ReferenceType[_T]], Any]] = ...) -> None: ... + def __call__(self) -> Optional[_T]: ... + def __hash__(self) -> int: ... + +ref = ReferenceType + +def getweakrefcount(__object: Any) -> int: ... +def getweakrefs(object: Any) -> List[Any]: ... +@overload +def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType[_C]: ... + +# Return CallableProxyType if object is callable, ProxyType otherwise +@overload +def proxy(object: _T, callback: Optional[Callable[[_T], Any]] = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakrefset.pyi b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi new file mode 100644 index 000000000000..99fa3e31166a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi @@ -0,0 +1,41 @@ +from typing import Any, Generic, Iterable, Iterator, MutableSet, Optional, TypeVar, Union + +_S = TypeVar("_S") +_T = TypeVar("_T") +_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) + +class WeakSet(MutableSet[_T], Generic[_T]): + def __init__(self, data: Optional[Iterable[_T]] = ...) -> None: ... + def add(self, item: _T) -> None: ... + def clear(self) -> None: ... + def discard(self, item: _T) -> None: ... + def copy(self: _SelfT) -> _SelfT: ... + def pop(self) -> _T: ... + def remove(self, item: _T) -> None: ... + def update(self, other: Iterable[_T]) -> None: ... + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __ior__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def difference_update(self, other: Iterable[_T]) -> None: ... + def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def intersection_update(self, other: Iterable[_T]) -> None: ... + def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def issubset(self, other: Iterable[_T]) -> bool: ... + def __le__(self, other: Iterable[_T]) -> bool: ... + def __lt__(self, other: Iterable[_T]) -> bool: ... + def issuperset(self, other: Iterable[_T]) -> bool: ... + def __ge__(self, other: Iterable[_T]) -> bool: ... + def __gt__(self, other: Iterable[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def __xor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... + def __ixor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def union(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def __or__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def isdisjoint(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_winreg.pyi b/mypy/typeshed/stdlib/@python2/_winreg.pyi index f12186cb3d9a..8e729f68720e 100644 --- a/mypy/typeshed/stdlib/@python2/_winreg.pyi +++ b/mypy/typeshed/stdlib/@python2/_winreg.pyi @@ -1,4 +1,3 @@ -import sys from types import TracebackType from typing import Any, Optional, Tuple, Type, Union diff --git a/mypy/typeshed/stdlib/@python2/aifc.pyi b/mypy/typeshed/stdlib/@python2/aifc.pyi new file mode 100644 index 000000000000..4349b11c1f1c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/aifc.pyi @@ -0,0 +1,74 @@ +from typing import IO, Any, List, NamedTuple, Optional, Text, Tuple, Union, overload +from typing_extensions import Literal + +class Error(Exception): ... + +class _aifc_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: bytes + compname: bytes + +_File = Union[Text, IO[bytes]] +_Marker = Tuple[int, int, bytes] + +class Aifc_read: + def __init__(self, f: _File) -> None: ... + def initfp(self, file: IO[bytes]) -> None: ... + def getfp(self) -> IO[bytes]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> bytes: ... + def getcompname(self) -> bytes: ... + def getparams(self) -> _aifc_params: ... + def getmarkers(self) -> Optional[List[_Marker]]: ... + def getmark(self, id: int) -> _Marker: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes: ... + +class Aifc_write: + def __init__(self, f: _File) -> None: ... + def __del__(self) -> None: ... + def initfp(self, file: IO[bytes]) -> None: ... + def aiff(self) -> None: ... + def aifc(self) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: int) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: bytes, compname: bytes) -> None: ... + def getcomptype(self) -> bytes: ... + def getcompname(self) -> bytes: ... + def setparams(self, params: Tuple[int, int, int, int, bytes, bytes]) -> None: ... + def getparams(self) -> _aifc_params: ... + def setmark(self, id: int, pos: int, name: bytes) -> None: ... + def getmark(self, id: int) -> _Marker: ... + def getmarkers(self) -> Optional[List[_Marker]]: ... + def tell(self) -> int: ... + def writeframesraw(self, data: Any) -> None: ... # Actual type for data is Buffer Protocol + def writeframes(self, data: Any) -> None: ... + def close(self) -> None: ... + +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... +@overload +def open(f: _File, mode: Optional[str] = ...) -> Any: ... +@overload +def openfp(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... +@overload +def openfp(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... +@overload +def openfp(f: _File, mode: Optional[str] = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/antigravity.pyi b/mypy/typeshed/stdlib/@python2/antigravity.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/argparse.pyi b/mypy/typeshed/stdlib/@python2/argparse.pyi new file mode 100644 index 000000000000..a3b5528c4a31 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/argparse.pyi @@ -0,0 +1,383 @@ +from typing import ( + IO, + Any, + Callable, + Dict, + Generator, + Iterable, + List, + NoReturn, + Optional, + Pattern, + Protocol, + Sequence, + Text, + Tuple, + Type, + TypeVar, + Union, + overload, +) + +_T = TypeVar("_T") +_ActionT = TypeVar("_ActionT", bound=Action) +_N = TypeVar("_N") + +_Text = Union[str, unicode] + +ONE_OR_MORE: str +OPTIONAL: str +PARSER: str +REMAINDER: str +SUPPRESS: str +ZERO_OR_MORE: str +_UNRECOGNIZED_ARGS_ATTR: str # undocumented + +class ArgumentError(Exception): + argument_name: Optional[str] + message: str + def __init__(self, argument: Optional[Action], message: str) -> None: ... + +# undocumented +class _AttributeHolder: + def _get_kwargs(self) -> List[Tuple[str, Any]]: ... + def _get_args(self) -> List[Any]: ... + +# undocumented +class _ActionsContainer: + description: Optional[_Text] + prefix_chars: _Text + argument_default: Any + conflict_handler: _Text + + _registries: Dict[_Text, Dict[Any, Any]] + _actions: List[Action] + _option_string_actions: Dict[_Text, Action] + _action_groups: List[_ArgumentGroup] + _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] + _defaults: Dict[str, Any] + _negative_number_matcher: Pattern[str] + _has_negative_number_optionals: List[bool] + def __init__( + self, description: Optional[Text], prefix_chars: Text, argument_default: Any, conflict_handler: Text + ) -> None: ... + def register(self, registry_name: Text, value: Any, object: Any) -> None: ... + def _registry_get(self, registry_name: Text, value: Any, default: Any = ...) -> Any: ... + def set_defaults(self, **kwargs: Any) -> None: ... + def get_default(self, dest: Text) -> Any: ... + def add_argument( + self, + *name_or_flags: Text, + action: Union[Text, Type[Action]] = ..., + nargs: Union[int, Text] = ..., + const: Any = ..., + default: Any = ..., + type: Union[Callable[[Text], _T], Callable[[str], _T], FileType] = ..., + choices: Iterable[_T] = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + dest: Optional[Text] = ..., + version: Text = ..., + **kwargs: Any, + ) -> Action: ... + def add_argument_group(self, *args: Any, **kwargs: Any) -> _ArgumentGroup: ... + def add_mutually_exclusive_group(self, **kwargs: Any) -> _MutuallyExclusiveGroup: ... + def _add_action(self, action: _ActionT) -> _ActionT: ... + def _remove_action(self, action: Action) -> None: ... + def _add_container_actions(self, container: _ActionsContainer) -> None: ... + def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> Dict[str, Any]: ... + def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... + def _pop_action_class(self, kwargs: Any, default: Optional[Type[Action]] = ...) -> Type[Action]: ... + def _get_handler(self) -> Callable[[Action, Iterable[Tuple[Text, Action]]], Any]: ... + def _check_conflict(self, action: Action) -> None: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> NoReturn: ... + def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> None: ... + +class _FormatterClass(Protocol): + def __call__(self, prog: str) -> HelpFormatter: ... + +class ArgumentParser(_AttributeHolder, _ActionsContainer): + prog: _Text + usage: Optional[_Text] + epilog: Optional[_Text] + formatter_class: _FormatterClass + fromfile_prefix_chars: Optional[_Text] + add_help: bool + + # undocumented + _positionals: _ArgumentGroup + _optionals: _ArgumentGroup + _subparsers: Optional[_ArgumentGroup] + def __init__( + self, + prog: Optional[Text] = ..., + usage: Optional[Text] = ..., + description: Optional[Text] = ..., + epilog: Optional[Text] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: Text = ..., + fromfile_prefix_chars: Optional[Text] = ..., + argument_default: Any = ..., + conflict_handler: Text = ..., + add_help: bool = ..., + ) -> None: ... + # The type-ignores in these overloads should be temporary. See: + # https://github.com/python/typeshed/pull/2643#issuecomment-442280277 + @overload + def parse_args(self, args: Optional[Sequence[Text]] = ...) -> Namespace: ... + @overload + def parse_args(self, args: Optional[Sequence[Text]], namespace: None) -> Namespace: ... # type: ignore + @overload + def parse_args(self, args: Optional[Sequence[Text]], namespace: _N) -> _N: ... + @overload + def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore + @overload + def parse_args(self, *, namespace: _N) -> _N: ... + def add_subparsers( + self, + *, + title: Text = ..., + description: Optional[Text] = ..., + prog: Text = ..., + parser_class: Type[ArgumentParser] = ..., + action: Type[Action] = ..., + option_string: Text = ..., + dest: Optional[Text] = ..., + help: Optional[Text] = ..., + metavar: Optional[Text] = ..., + ) -> _SubParsersAction: ... + def print_usage(self, file: Optional[IO[str]] = ...) -> None: ... + def print_help(self, file: Optional[IO[str]] = ...) -> None: ... + def format_usage(self) -> str: ... + def format_help(self) -> str: ... + def parse_known_args( + self, args: Optional[Sequence[Text]] = ..., namespace: Optional[Namespace] = ... + ) -> Tuple[Namespace, List[str]]: ... + def convert_arg_line_to_args(self, arg_line: Text) -> List[str]: ... + def exit(self, status: int = ..., message: Optional[Text] = ...) -> NoReturn: ... + def error(self, message: Text) -> NoReturn: ... + # undocumented + def _get_optional_actions(self) -> List[Action]: ... + def _get_positional_actions(self) -> List[Action]: ... + def _parse_known_args(self, arg_strings: List[Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... + def _read_args_from_files(self, arg_strings: List[Text]) -> List[Text]: ... + def _match_argument(self, action: Action, arg_strings_pattern: Text) -> int: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> List[int]: ... + def _parse_optional(self, arg_string: Text) -> Optional[Tuple[Optional[Action], Text, Optional[Text]]]: ... + def _get_option_tuples(self, option_string: Text) -> List[Tuple[Action, Text, Optional[Text]]]: ... + def _get_nargs_pattern(self, action: Action) -> _Text: ... + def _get_values(self, action: Action, arg_strings: List[Text]) -> Any: ... + def _get_value(self, action: Action, arg_string: Text) -> Any: ... + def _check_value(self, action: Action, value: Any) -> None: ... + def _get_formatter(self) -> HelpFormatter: ... + def _print_message(self, message: str, file: Optional[IO[str]] = ...) -> None: ... + +class HelpFormatter: + # undocumented + _prog: _Text + _indent_increment: int + _max_help_position: int + _width: int + _current_indent: int + _level: int + _action_max_length: int + _root_section: Any + _current_section: Any + _whitespace_matcher: Pattern[str] + _long_break_matcher: Pattern[str] + _Section: Type[Any] # Nested class + def __init__( + self, prog: Text, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ... + ) -> None: ... + def _indent(self) -> None: ... + def _dedent(self) -> None: ... + def _add_item(self, func: Callable[..., _Text], args: Iterable[Any]) -> None: ... + def start_section(self, heading: Optional[Text]) -> None: ... + def end_section(self) -> None: ... + def add_text(self, text: Optional[Text]) -> None: ... + def add_usage( + self, usage: Optional[Text], actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[Text] = ... + ) -> None: ... + def add_argument(self, action: Action) -> None: ... + def add_arguments(self, actions: Iterable[Action]) -> None: ... + def format_help(self) -> _Text: ... + def _join_parts(self, part_strings: Iterable[Text]) -> _Text: ... + def _format_usage( + self, usage: Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[Text] + ) -> _Text: ... + def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> _Text: ... + def _format_text(self, text: Text) -> _Text: ... + def _format_action(self, action: Action) -> _Text: ... + def _format_action_invocation(self, action: Action) -> _Text: ... + def _metavar_formatter(self, action: Action, default_metavar: Text) -> Callable[[int], Tuple[_Text, ...]]: ... + def _format_args(self, action: Action, default_metavar: Text) -> _Text: ... + def _expand_help(self, action: Action) -> _Text: ... + def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... + def _split_lines(self, text: Text, width: int) -> List[_Text]: ... + def _fill_text(self, text: Text, width: int, indent: Text) -> _Text: ... + def _get_help_string(self, action: Action) -> Optional[_Text]: ... + def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... + def _get_default_metavar_for_positional(self, action: Action) -> _Text: ... + +class RawDescriptionHelpFormatter(HelpFormatter): ... +class RawTextHelpFormatter(RawDescriptionHelpFormatter): ... +class ArgumentDefaultsHelpFormatter(HelpFormatter): ... + +class Action(_AttributeHolder): + option_strings: Sequence[_Text] + dest: _Text + nargs: Optional[Union[int, _Text]] + const: Any + default: Any + type: Union[Callable[[str], Any], FileType, None] + choices: Optional[Iterable[Any]] + required: bool + help: Optional[_Text] + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] + def __init__( + self, + option_strings: Sequence[Text], + dest: Text, + nargs: Optional[Union[int, Text]] = ..., + const: Optional[_T] = ..., + default: Union[_T, str, None] = ..., + type: Optional[Union[Callable[[Text], _T], Callable[[str], _T], FileType]] = ..., + choices: Optional[Iterable[_T]] = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + ) -> None: ... + def __call__( + self, + parser: ArgumentParser, + namespace: Namespace, + values: Union[Text, Sequence[Any], None], + option_string: Optional[Text] = ..., + ) -> None: ... + +class Namespace(_AttributeHolder): + def __init__(self, **kwargs: Any) -> None: ... + def __getattr__(self, name: Text) -> Any: ... + def __setattr__(self, name: Text, value: Any) -> None: ... + def __contains__(self, key: str) -> bool: ... + +class FileType: + # undocumented + _mode: _Text + _bufsize: int + def __init__(self, mode: Text = ..., bufsize: Optional[int] = ...) -> None: ... + def __call__(self, string: Text) -> IO[Any]: ... + +# undocumented +class _ArgumentGroup(_ActionsContainer): + title: Optional[_Text] + _group_actions: List[Action] + def __init__( + self, container: _ActionsContainer, title: Optional[Text] = ..., description: Optional[Text] = ..., **kwargs: Any + ) -> None: ... + +# undocumented +class _MutuallyExclusiveGroup(_ArgumentGroup): + required: bool + _container: _ActionsContainer + def __init__(self, container: _ActionsContainer, required: bool = ...) -> None: ... + +# undocumented +class _StoreAction(Action): ... + +# undocumented +class _StoreConstAction(Action): + def __init__( + self, + option_strings: Sequence[Text], + dest: Text, + const: Any, + default: Any = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + ) -> None: ... + +# undocumented +class _StoreTrueAction(_StoreConstAction): + def __init__( + self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Optional[Text] = ... + ) -> None: ... + +# undocumented +class _StoreFalseAction(_StoreConstAction): + def __init__( + self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Optional[Text] = ... + ) -> None: ... + +# undocumented +class _AppendAction(Action): ... + +# undocumented +class _AppendConstAction(Action): + def __init__( + self, + option_strings: Sequence[Text], + dest: Text, + const: Any, + default: Any = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + ) -> None: ... + +# undocumented +class _CountAction(Action): + def __init__( + self, option_strings: Sequence[Text], dest: Text, default: Any = ..., required: bool = ..., help: Optional[Text] = ... + ) -> None: ... + +# undocumented +class _HelpAction(Action): + def __init__( + self, option_strings: Sequence[Text], dest: Text = ..., default: Text = ..., help: Optional[Text] = ... + ) -> None: ... + +# undocumented +class _VersionAction(Action): + version: Optional[_Text] + def __init__( + self, + option_strings: Sequence[Text], + version: Optional[Text] = ..., + dest: Text = ..., + default: Text = ..., + help: Text = ..., + ) -> None: ... + +# undocumented +class _SubParsersAction(Action): + _ChoicesPseudoAction: Type[Any] # nested class + _prog_prefix: _Text + _parser_class: Type[ArgumentParser] + _name_parser_map: Dict[_Text, ArgumentParser] + choices: Dict[_Text, ArgumentParser] + _choices_actions: List[Action] + def __init__( + self, + option_strings: Sequence[Text], + prog: Text, + parser_class: Type[ArgumentParser], + dest: Text = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + ) -> None: ... + # TODO: Type keyword args properly. + def add_parser(self, name: Text, **kwargs: Any) -> ArgumentParser: ... + def _get_subactions(self) -> List[Action]: ... + +# undocumented +class ArgumentTypeError(Exception): ... + +# undocumented +def _ensure_value(namespace: Namespace, name: Text, value: Any) -> Any: ... + +# undocumented +def _get_action_name(argument: Optional[Action]) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/array.pyi b/mypy/typeshed/stdlib/@python2/array.pyi new file mode 100644 index 000000000000..a93742f85412 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/array.pyi @@ -0,0 +1,65 @@ +from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Text, Tuple, TypeVar, Union, overload +from typing_extensions import Literal + +_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] +_FloatTypeCode = Literal["f", "d"] +_UnicodeTypeCode = Literal["u"] +_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] + +_T = TypeVar("_T", int, float, Text) + +class array(MutableSequence[_T], Generic[_T]): + typecode: _TypeCode + itemsize: int + @overload + def __init__(self: array[int], typecode: _IntTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + @overload + def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + @overload + def __init__(self: array[Text], typecode: _UnicodeTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + @overload + def __init__(self, typecode: str, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + def append(self, __v: _T) -> None: ... + def buffer_info(self) -> Tuple[int, int]: ... + def byteswap(self) -> None: ... + def count(self, __v: Any) -> int: ... + def extend(self, __bb: Iterable[_T]) -> None: ... + def fromfile(self, __f: BinaryIO, __n: int) -> None: ... + def fromlist(self, __list: List[_T]) -> None: ... + def fromunicode(self, __ustr: str) -> None: ... + def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence + def insert(self, __i: int, __v: _T) -> None: ... + def pop(self, __i: int = ...) -> _T: ... + def read(self, f: BinaryIO, n: int) -> None: ... + def remove(self, __v: Any) -> None: ... + def reverse(self) -> None: ... + def tofile(self, __f: BinaryIO) -> None: ... + def tolist(self) -> List[_T]: ... + def tounicode(self) -> str: ... + def write(self, f: BinaryIO) -> None: ... + def fromstring(self, __buffer: bytes) -> None: ... + def tostring(self) -> bytes: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> array[_T]: ... + @overload # type: ignore # Overrides MutableSequence + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: array[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self, x: array[_T]) -> array[_T]: ... + def __ge__(self, other: array[_T]) -> bool: ... + def __gt__(self, other: array[_T]) -> bool: ... + def __iadd__(self, x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence + def __imul__(self, n: int) -> array[_T]: ... + def __le__(self, other: array[_T]) -> bool: ... + def __lt__(self, other: array[_T]) -> bool: ... + def __mul__(self, n: int) -> array[_T]: ... + def __rmul__(self, n: int) -> array[_T]: ... + def __delslice__(self, i: int, j: int) -> None: ... + def __getslice__(self, i: int, j: int) -> array[_T]: ... + def __setslice__(self, i: int, j: int, y: array[_T]) -> None: ... + +ArrayType = array diff --git a/mypy/typeshed/stdlib/@python2/asynchat.pyi b/mypy/typeshed/stdlib/@python2/asynchat.pyi new file mode 100644 index 000000000000..464eb42bad52 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/asynchat.pyi @@ -0,0 +1,37 @@ +import asyncore +import socket +from abc import abstractmethod +from typing import Optional, Sequence, Tuple, Union + +class simple_producer: + def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... + def more(self) -> bytes: ... + +class async_chat(asyncore.dispatcher): + ac_in_buffer_size: int + ac_out_buffer_size: int + def __init__(self, sock: Optional[socket.socket] = ..., map: Optional[asyncore._maptype] = ...) -> None: ... + @abstractmethod + def collect_incoming_data(self, data: bytes) -> None: ... + @abstractmethod + def found_terminator(self) -> None: ... + def set_terminator(self, term: Union[bytes, int, None]) -> None: ... + def get_terminator(self) -> Union[bytes, int, None]: ... + def handle_read(self) -> None: ... + def handle_write(self) -> None: ... + def handle_close(self) -> None: ... + def push(self, data: bytes) -> None: ... + def push_with_producer(self, producer: simple_producer) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def close_when_done(self) -> None: ... + def initiate_send(self) -> None: ... + def discard_buffers(self) -> None: ... + +class fifo: + def __init__(self, list: Sequence[Union[bytes, simple_producer]] = ...) -> None: ... + def __len__(self) -> int: ... + def is_empty(self) -> bool: ... + def first(self) -> bytes: ... + def push(self, data: Union[bytes, simple_producer]) -> None: ... + def pop(self) -> Tuple[int, bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/asyncore.pyi b/mypy/typeshed/stdlib/@python2/asyncore.pyi new file mode 100644 index 000000000000..be551a040cc1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/asyncore.pyi @@ -0,0 +1,118 @@ +import sys +from _typeshed import FileDescriptorLike +from socket import SocketType +from typing import Any, Dict, Optional, Tuple, Union, overload + +# cyclic dependence with asynchat +_maptype = Dict[int, Any] + +socket_map: _maptype = ... # Undocumented + +class ExitNow(Exception): ... + +def read(obj: Any) -> None: ... +def write(obj: Any) -> None: ... +def readwrite(obj: Any, flags: int) -> None: ... +def poll(timeout: float = ..., map: Optional[_maptype] = ...) -> None: ... +def poll2(timeout: float = ..., map: Optional[_maptype] = ...) -> None: ... + +poll3 = poll2 + +def loop(timeout: float = ..., use_poll: bool = ..., map: Optional[_maptype] = ..., count: Optional[int] = ...) -> None: ... + +# Not really subclass of socket.socket; it's only delegation. +# It is not covariant to it. +class dispatcher: + + debug: bool + connected: bool + accepting: bool + connecting: bool + closing: bool + ignore_log_types: frozenset[str] + socket: Optional[SocketType] + def __init__(self, sock: Optional[SocketType] = ..., map: Optional[_maptype] = ...) -> None: ... + def add_channel(self, map: Optional[_maptype] = ...) -> None: ... + def del_channel(self, map: Optional[_maptype] = ...) -> None: ... + def create_socket(self, family: int = ..., type: int = ...) -> None: ... + def set_socket(self, sock: SocketType, map: Optional[_maptype] = ...) -> None: ... + def set_reuse_addr(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def listen(self, num: int) -> None: ... + def bind(self, addr: Union[Tuple[Any, ...], str]) -> None: ... + def connect(self, address: Union[Tuple[Any, ...], str]) -> None: ... + def accept(self) -> Optional[Tuple[SocketType, Any]]: ... + def send(self, data: bytes) -> int: ... + def recv(self, buffer_size: int) -> bytes: ... + def close(self) -> None: ... + def log(self, message: Any) -> None: ... + def log_info(self, message: Any, type: str = ...) -> None: ... + def handle_read_event(self) -> None: ... + def handle_connect_event(self) -> None: ... + def handle_write_event(self) -> None: ... + def handle_expt_event(self) -> None: ... + def handle_error(self) -> None: ... + def handle_expt(self) -> None: ... + def handle_read(self) -> None: ... + def handle_write(self) -> None: ... + def handle_connect(self) -> None: ... + def handle_accept(self) -> None: ... + def handle_close(self) -> None: ... + # Historically, some methods were "imported" from `self.socket` by + # means of `__getattr__`. This was long deprecated, and as of Python + # 3.5 has been removed; simply call the relevant methods directly on + # self.socket if necessary. + def detach(self) -> int: ... + def fileno(self) -> int: ... + # return value is an address + def getpeername(self) -> Any: ... + def getsockname(self) -> Any: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + def gettimeout(self) -> float: ... + def ioctl(self, control: object, option: Tuple[int, int, int]) -> None: ... + # TODO the return value may be BinaryIO or TextIO, depending on mode + def makefile( + self, mode: str = ..., buffering: int = ..., encoding: str = ..., errors: str = ..., newline: str = ... + ) -> Any: ... + # return type is an address + def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ... + def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... + def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... + def sendall(self, data: bytes, flags: int = ...) -> None: ... + def sendto(self, data: bytes, address: Union[Tuple[str, int], str], flags: int = ...) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: Union[float, None]) -> None: ... + def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... + def shutdown(self, how: int) -> None: ... + +class dispatcher_with_send(dispatcher): + def __init__(self, sock: SocketType = ..., map: Optional[_maptype] = ...) -> None: ... + def initiate_send(self) -> None: ... + def handle_write(self) -> None: ... + # incompatible signature: + # def send(self, data: bytes) -> Optional[int]: ... + +def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ... +def close_all(map: Optional[_maptype] = ..., ignore_all: bool = ...) -> None: ... + +if sys.platform != "win32": + class file_wrapper: + fd: int + def __init__(self, fd: int) -> None: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + def read(self, bufsize: int, flags: int = ...) -> bytes: ... + def write(self, data: bytes, flags: int = ...) -> int: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + class file_dispatcher(dispatcher): + def __init__(self, fd: FileDescriptorLike, map: Optional[_maptype] = ...) -> None: ... + def set_file(self, fd: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/audioop.pyi b/mypy/typeshed/stdlib/@python2/audioop.pyi new file mode 100644 index 000000000000..606f4b9f5f7e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/audioop.pyi @@ -0,0 +1,42 @@ +from typing import Optional, Tuple + +AdpcmState = Tuple[int, int] +RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] + +class error(Exception): ... + +def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... +def adpcm2lin(__fragment: bytes, __width: int, __state: Optional[AdpcmState]) -> Tuple[bytes, AdpcmState]: ... +def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... +def avg(__fragment: bytes, __width: int) -> int: ... +def avgpp(__fragment: bytes, __width: int) -> int: ... +def bias(__fragment: bytes, __width: int, __bias: int) -> bytes: ... +def byteswap(__fragment: bytes, __width: int) -> bytes: ... +def cross(__fragment: bytes, __width: int) -> int: ... +def findfactor(__fragment: bytes, __reference: bytes) -> float: ... +def findfit(__fragment: bytes, __reference: bytes) -> Tuple[int, float]: ... +def findmax(__fragment: bytes, __length: int) -> int: ... +def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... +def lin2adpcm(__fragment: bytes, __width: int, __state: Optional[AdpcmState]) -> Tuple[bytes, AdpcmState]: ... +def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... +def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... +def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... +def max(__fragment: bytes, __width: int) -> int: ... +def maxpp(__fragment: bytes, __width: int) -> int: ... +def minmax(__fragment: bytes, __width: int) -> Tuple[int, int]: ... +def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... +def ratecv( + __fragment: bytes, + __width: int, + __nchannels: int, + __inrate: int, + __outrate: int, + __state: Optional[RatecvState], + __weightA: int = ..., + __weightB: int = ..., +) -> Tuple[bytes, RatecvState]: ... +def reverse(__fragment: bytes, __width: int) -> bytes: ... +def rms(__fragment: bytes, __width: int) -> int: ... +def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... +def tostereo(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... +def ulaw2lin(__fragment: bytes, __width: int) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/base64.pyi b/mypy/typeshed/stdlib/@python2/base64.pyi new file mode 100644 index 000000000000..05c3ec319f38 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/base64.pyi @@ -0,0 +1,19 @@ +from typing import IO, Optional, Union + +_encodable = Union[bytes, unicode] +_decodable = Union[bytes, unicode] + +def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... +def b64decode(s: _decodable, altchars: Optional[bytes] = ..., validate: bool = ...) -> bytes: ... +def standard_b64encode(s: _encodable) -> bytes: ... +def standard_b64decode(s: _decodable) -> bytes: ... +def urlsafe_b64encode(s: _encodable) -> bytes: ... +def urlsafe_b64decode(s: _decodable) -> bytes: ... +def b32encode(s: _encodable) -> bytes: ... +def b32decode(s: _decodable, casefold: bool = ..., map01: Optional[bytes] = ...) -> bytes: ... +def b16encode(s: _encodable) -> bytes: ... +def b16decode(s: _decodable, casefold: bool = ...) -> bytes: ... +def decode(input: IO[bytes], output: IO[bytes]) -> None: ... +def encode(input: IO[bytes], output: IO[bytes]) -> None: ... +def encodestring(s: bytes) -> bytes: ... +def decodestring(s: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/bdb.pyi b/mypy/typeshed/stdlib/@python2/bdb.pyi new file mode 100644 index 000000000000..9d76b3afde22 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/bdb.pyi @@ -0,0 +1,98 @@ +from types import CodeType, FrameType, TracebackType +from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, SupportsInt, Tuple, Type, TypeVar, Union + +_T = TypeVar("_T") +_TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type +_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] + +GENERATOR_AND_COROUTINE_FLAGS: int = ... + +class BdbQuit(Exception): ... + +class Bdb: + + skip: Optional[Set[str]] + breaks: Dict[str, List[int]] + fncache: Dict[str, str] + frame_returning: Optional[FrameType] + botframe: Optional[FrameType] + quitting: bool + stopframe: Optional[FrameType] + returnframe: Optional[FrameType] + stoplineno: int + def __init__(self, skip: Optional[Iterable[str]] = ...) -> None: ... + def canonic(self, filename: str) -> str: ... + def reset(self) -> None: ... + def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> _TraceDispatch: ... + def dispatch_line(self, frame: FrameType) -> _TraceDispatch: ... + def dispatch_call(self, frame: FrameType, arg: None) -> _TraceDispatch: ... + def dispatch_return(self, frame: FrameType, arg: Any) -> _TraceDispatch: ... + def dispatch_exception(self, frame: FrameType, arg: _ExcInfo) -> _TraceDispatch: ... + def is_skipped_module(self, module_name: str) -> bool: ... + def stop_here(self, frame: FrameType) -> bool: ... + def break_here(self, frame: FrameType) -> bool: ... + def do_clear(self, arg: Any) -> Optional[bool]: ... + def break_anywhere(self, frame: FrameType) -> bool: ... + def user_call(self, frame: FrameType, argument_list: None) -> None: ... + def user_line(self, frame: FrameType) -> None: ... + def user_return(self, frame: FrameType, return_value: Any) -> None: ... + def user_exception(self, frame: FrameType, exc_info: _ExcInfo) -> None: ... + def set_until(self, frame: FrameType, lineno: Optional[int] = ...) -> None: ... + def set_step(self) -> None: ... + def set_next(self, frame: FrameType) -> None: ... + def set_return(self, frame: FrameType) -> None: ... + def set_trace(self, frame: Optional[FrameType] = ...) -> None: ... + def set_continue(self) -> None: ... + def set_quit(self) -> None: ... + def set_break( + self, filename: str, lineno: int, temporary: bool = ..., cond: Optional[str] = ..., funcname: Optional[str] = ... + ) -> None: ... + def clear_break(self, filename: str, lineno: int) -> None: ... + def clear_bpbynumber(self, arg: SupportsInt) -> None: ... + def clear_all_file_breaks(self, filename: str) -> None: ... + def clear_all_breaks(self) -> None: ... + def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... + def get_break(self, filename: str, lineno: int) -> bool: ... + def get_breaks(self, filename: str, lineno: int) -> List[Breakpoint]: ... + def get_file_breaks(self, filename: str) -> List[Breakpoint]: ... + def get_all_breaks(self) -> List[Breakpoint]: ... + def get_stack(self, f: Optional[FrameType], t: Optional[TracebackType]) -> Tuple[List[Tuple[FrameType, int]], int]: ... + def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... + def run( + self, cmd: Union[str, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ... + ) -> None: ... + def runeval(self, expr: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> None: ... + def runctx( + self, cmd: Union[str, CodeType], globals: Optional[Dict[str, Any]], locals: Optional[Mapping[str, Any]] + ) -> None: ... + def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> Optional[_T]: ... + +class Breakpoint: + + next: int = ... + bplist: Dict[Tuple[str, int], List[Breakpoint]] = ... + bpbynumber: List[Optional[Breakpoint]] = ... + + funcname: Optional[str] + func_first_executable_line: Optional[int] + file: str + line: int + temporary: bool + cond: Optional[str] + enabled: bool + ignore: int + hits: int + number: int + def __init__( + self, file: str, line: int, temporary: bool = ..., cond: Optional[str] = ..., funcname: Optional[str] = ... + ) -> None: ... + def deleteMe(self) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def bpprint(self, out: Optional[IO[str]] = ...) -> None: ... + def bpformat(self) -> str: ... + def __str__(self) -> str: ... + +def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... +def effective(file: str, line: int, frame: FrameType) -> Union[Tuple[Breakpoint, bool], Tuple[None, None]]: ... +def set_trace() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/binascii.pyi b/mypy/typeshed/stdlib/@python2/binascii.pyi new file mode 100644 index 000000000000..b8da269c95a8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/binascii.pyi @@ -0,0 +1,25 @@ +from typing import Text + +# Python 2 accepts unicode ascii pretty much everywhere. +_Bytes = Text +_Ascii = Text + +def a2b_uu(__data: _Ascii) -> bytes: ... +def b2a_uu(__data: _Bytes) -> bytes: ... +def a2b_base64(__data: _Ascii) -> bytes: ... +def b2a_base64(__data: _Bytes) -> bytes: ... +def a2b_qp(data: _Ascii, header: bool = ...) -> bytes: ... +def b2a_qp(data: _Bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... +def a2b_hqx(__data: _Ascii) -> bytes: ... +def rledecode_hqx(__data: _Bytes) -> bytes: ... +def rlecode_hqx(__data: _Bytes) -> bytes: ... +def b2a_hqx(__data: _Bytes) -> bytes: ... +def crc_hqx(__data: _Bytes, __crc: int) -> int: ... +def crc32(__data: _Bytes, __crc: int = ...) -> int: ... +def b2a_hex(__data: _Bytes) -> bytes: ... +def hexlify(__data: _Bytes) -> bytes: ... +def a2b_hex(__hexstr: _Ascii) -> bytes: ... +def unhexlify(__hexstr: _Ascii) -> bytes: ... + +class Error(ValueError): ... +class Incomplete(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/binhex.pyi b/mypy/typeshed/stdlib/@python2/binhex.pyi new file mode 100644 index 000000000000..02d094faf923 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/binhex.pyi @@ -0,0 +1,42 @@ +from typing import IO, Any, Tuple, Union + +class Error(Exception): ... + +REASONABLY_LARGE: int +LINELEN: int +RUNCHAR: bytes + +class FInfo: + def __init__(self) -> None: ... + Type: str + Creator: str + Flags: int + +_FileInfoTuple = Tuple[str, FInfo, int, int] +_FileHandleUnion = Union[str, IO[bytes]] + +def getfileinfo(name: str) -> _FileInfoTuple: ... + +class openrsrc: + def __init__(self, *args: Any) -> None: ... + def read(self, *args: Any) -> bytes: ... + def write(self, *args: Any) -> None: ... + def close(self) -> None: ... + +class BinHex: + def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ... + def write(self, data: bytes) -> None: ... + def close_data(self) -> None: ... + def write_rsrc(self, data: bytes) -> None: ... + def close(self) -> None: ... + +def binhex(inp: str, out: str) -> None: ... + +class HexBin: + def __init__(self, ifp: _FileHandleUnion) -> None: ... + def read(self, *n: int) -> bytes: ... + def close_data(self) -> None: ... + def read_rsrc(self, *n: int) -> bytes: ... + def close(self) -> None: ... + +def hexbin(inp: str, out: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/bisect.pyi b/mypy/typeshed/stdlib/@python2/bisect.pyi new file mode 100644 index 000000000000..60dfc48d69bd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/bisect.pyi @@ -0,0 +1,4 @@ +from _bisect import * + +bisect = bisect_right +insort = insort_right diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index 4eb5424d8da7..b7b68bbb7844 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -861,7 +861,12 @@ def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: .. @overload def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -def getattr(__o: Any, name: Text, __default: Any = ...) -> Any: ... +@overload +def getattr(__o: Any, name: Text) -> Any: ... +@overload +def getattr(__o: Any, name: Text, __default: None) -> Optional[Any]: ... +@overload +def getattr(__o: Any, name: Text, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/bz2.pyi b/mypy/typeshed/stdlib/@python2/bz2.pyi new file mode 100644 index 000000000000..d3c0baded59a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/bz2.pyi @@ -0,0 +1,34 @@ +import io +from _typeshed import ReadableBuffer, WriteableBuffer +from typing import IO, Any, Iterable, List, Optional, Text, TypeVar, Union +from typing_extensions import SupportsIndex + +_PathOrFile = Union[Text, IO[bytes]] +_T = TypeVar("_T") + +def compress(data: bytes, compresslevel: int = ...) -> bytes: ... +def decompress(data: bytes) -> bytes: ... + +class BZ2File(io.BufferedIOBase, IO[bytes]): + def __enter__(self: _T) -> _T: ... + def __init__( + self, filename: _PathOrFile, mode: str = ..., buffering: Optional[Any] = ..., compresslevel: int = ... + ) -> None: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore + def readinto(self, b: WriteableBuffer) -> int: ... + def readlines(self, size: SupportsIndex = ...) -> List[bytes]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def write(self, data: ReadableBuffer) -> int: ... + def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... + +class BZ2Compressor(object): + def __init__(self, compresslevel: int = ...) -> None: ... + def compress(self, __data: bytes) -> bytes: ... + def flush(self) -> bytes: ... + +class BZ2Decompressor(object): + def decompress(self, data: bytes) -> bytes: ... + @property + def unused_data(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/cProfile.pyi b/mypy/typeshed/stdlib/@python2/cProfile.pyi new file mode 100644 index 000000000000..0cc2e94986fc --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cProfile.pyi @@ -0,0 +1,28 @@ +from types import CodeType +from typing import Any, Callable, Dict, Optional, Text, Tuple, TypeVar, Union + +def run(statement: str, filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... +def runctx( + statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: Optional[str] = ..., sort: Union[str, int] = ... +) -> None: ... + +_SelfT = TypeVar("_SelfT", bound=Profile) +_T = TypeVar("_T") +_Label = Tuple[str, int, str] + +class Profile: + stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented + def __init__( + self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ... + ) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def print_stats(self, sort: Union[str, int] = ...) -> None: ... + def dump_stats(self, file: Text) -> None: ... + def create_stats(self) -> None: ... + def snapshot_stats(self) -> None: ... + def run(self: _SelfT, cmd: str) -> _SelfT: ... + def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + +def label(code: Union[str, CodeType]) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/cStringIO.pyi b/mypy/typeshed/stdlib/@python2/cStringIO.pyi index 603ce3f2403f..8518625fc1df 100644 --- a/mypy/typeshed/stdlib/@python2/cStringIO.pyi +++ b/mypy/typeshed/stdlib/@python2/cStringIO.pyi @@ -1,5 +1,4 @@ from abc import ABCMeta -from types import TracebackType from typing import IO, Iterable, Iterator, List, Optional, Union, overload # This class isn't actually abstract, but you can't instantiate it diff --git a/mypy/typeshed/stdlib/@python2/calendar.pyi b/mypy/typeshed/stdlib/@python2/calendar.pyi new file mode 100644 index 000000000000..1a8cb1657f1b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/calendar.pyi @@ -0,0 +1,105 @@ +import datetime +from time import struct_time +from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union + +_LocaleType = Tuple[Optional[str], Optional[str]] + +class IllegalMonthError(ValueError): + def __init__(self, month: int) -> None: ... + def __str__(self) -> str: ... + +class IllegalWeekdayError(ValueError): + def __init__(self, weekday: int) -> None: ... + def __str__(self) -> str: ... + +def isleap(year: int) -> bool: ... +def leapdays(y1: int, y2: int) -> int: ... +def weekday(year: int, month: int, day: int) -> int: ... +def monthrange(year: int, month: int) -> Tuple[int, int]: ... + +class Calendar: + firstweekday: int + def __init__(self, firstweekday: int = ...) -> None: ... + def getfirstweekday(self) -> int: ... + def setfirstweekday(self, firstweekday: int) -> None: ... + def iterweekdays(self) -> Iterable[int]: ... + def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... + def itermonthdays2(self, year: int, month: int) -> Iterable[Tuple[int, int]]: ... + def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... + def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ... + def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ... + def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ... + def yeardatescalendar(self, year: int, width: int = ...) -> List[List[int]]: ... + def yeardays2calendar(self, year: int, width: int = ...) -> List[List[Tuple[int, int]]]: ... + def yeardayscalendar(self, year: int, width: int = ...) -> List[List[int]]: ... + +class TextCalendar(Calendar): + def prweek(self, theweek: int, width: int) -> None: ... + def formatday(self, day: int, weekday: int, width: int) -> str: ... + def formatweek(self, theweek: int, width: int) -> str: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatweekheader(self, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... + def prmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... + def formatmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... + def formatyear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... + def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... + +def firstweekday() -> int: ... +def monthcalendar(year: int, month: int) -> List[List[int]]: ... +def prweek(theweek: int, width: int) -> None: ... +def week(theweek: int, width: int) -> str: ... +def weekheader(width: int) -> str: ... +def prmonth(theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... +def month(theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... +def calendar(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... +def prcal(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... + +class HTMLCalendar(Calendar): + def formatday(self, day: int, weekday: int) -> str: ... + def formatweek(self, theweek: int) -> str: ... + def formatweekday(self, day: int) -> str: ... + def formatweekheader(self) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + def formatyear(self, theyear: int, width: int = ...) -> str: ... + def formatyearpage(self, theyear: int, width: int = ..., css: Optional[str] = ..., encoding: Optional[str] = ...) -> str: ... + +class TimeEncoding: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> _LocaleType: ... + def __exit__(self, *args: Any) -> None: ... + +class LocaleTextCalendar(TextCalendar): + def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... + +class LocaleHTMLCalendar(HTMLCalendar): + def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ... + def formatweekday(self, day: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + +c: TextCalendar + +def setfirstweekday(firstweekday: int) -> None: ... +def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... +def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... +def timegm(tuple: Union[Tuple[int, ...], struct_time]) -> int: ... + +# Data attributes +day_name: Sequence[str] +day_abbr: Sequence[str] +month_name: Sequence[str] +month_abbr: Sequence[str] + +# Below constants are not in docs or __all__, but enough people have used them +# they are now effectively public. + +MONDAY: int +TUESDAY: int +WEDNESDAY: int +THURSDAY: int +FRIDAY: int +SATURDAY: int +SUNDAY: int diff --git a/mypy/typeshed/stdlib/@python2/cgitb.pyi b/mypy/typeshed/stdlib/@python2/cgitb.pyi new file mode 100644 index 000000000000..017840dc472c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cgitb.pyi @@ -0,0 +1,32 @@ +from types import FrameType, TracebackType +from typing import IO, Any, Callable, Dict, List, Optional, Text, Tuple, Type + +_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +def reset() -> str: ... # undocumented +def small(text: str) -> str: ... # undocumented +def strong(text: str) -> str: ... # undocumented +def grey(text: str) -> str: ... # undocumented +def lookup(name: str, frame: FrameType, locals: Dict[str, Any]) -> Tuple[Optional[str], Any]: ... # undocumented +def scanvars( + reader: Callable[[], bytes], frame: FrameType, locals: Dict[str, Any] +) -> List[Tuple[str, Optional[str], Any]]: ... # undocumented +def html(einfo: _ExcInfo, context: int = ...) -> str: ... +def text(einfo: _ExcInfo, context: int = ...) -> str: ... + +class Hook: # undocumented + def __init__( + self, + display: int = ..., + logdir: Optional[Text] = ..., + context: int = ..., + file: Optional[IO[str]] = ..., + format: str = ..., + ) -> None: ... + def __call__( + self, etype: Optional[Type[BaseException]], evalue: Optional[BaseException], etb: Optional[TracebackType] + ) -> None: ... + def handle(self, info: Optional[_ExcInfo] = ...) -> None: ... + +def handler(info: Optional[_ExcInfo] = ...) -> None: ... +def enable(display: int = ..., logdir: Optional[Text] = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/chunk.pyi b/mypy/typeshed/stdlib/@python2/chunk.pyi new file mode 100644 index 000000000000..50ff267c5436 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/chunk.pyi @@ -0,0 +1,20 @@ +from typing import IO + +class Chunk: + closed: bool + align: bool + file: IO[bytes] + chunkname: bytes + chunksize: int + size_read: int + offset: int + seekable: bool + def __init__(self, file: IO[bytes], align: bool = ..., bigendian: bool = ..., inclheader: bool = ...) -> None: ... + def getname(self) -> bytes: ... + def getsize(self) -> int: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, whence: int = ...) -> None: ... + def tell(self) -> int: ... + def read(self, size: int = ...) -> bytes: ... + def skip(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cmath.pyi b/mypy/typeshed/stdlib/@python2/cmath.pyi new file mode 100644 index 000000000000..1e19687b4885 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cmath.pyi @@ -0,0 +1,27 @@ +from typing import SupportsComplex, SupportsFloat, Tuple, Union + +e: float +pi: float +_C = Union[SupportsFloat, SupportsComplex, complex] + +def acos(__z: _C) -> complex: ... +def acosh(__z: _C) -> complex: ... +def asin(__z: _C) -> complex: ... +def asinh(__z: _C) -> complex: ... +def atan(__z: _C) -> complex: ... +def atanh(__z: _C) -> complex: ... +def cos(__z: _C) -> complex: ... +def cosh(__z: _C) -> complex: ... +def exp(__z: _C) -> complex: ... +def isinf(__z: _C) -> bool: ... +def isnan(__z: _C) -> bool: ... +def log(__x: _C, __y_obj: _C = ...) -> complex: ... +def log10(__z: _C) -> complex: ... +def phase(__z: _C) -> float: ... +def polar(__z: _C) -> Tuple[float, float]: ... +def rect(__r: float, __phi: float) -> complex: ... +def sin(__z: _C) -> complex: ... +def sinh(__z: _C) -> complex: ... +def sqrt(__z: _C) -> complex: ... +def tan(__z: _C) -> complex: ... +def tanh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/@python2/cmd.pyi b/mypy/typeshed/stdlib/@python2/cmd.pyi new file mode 100644 index 000000000000..0b7a7f704a9b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cmd.pyi @@ -0,0 +1,39 @@ +from typing import IO, Any, Callable, List, Optional, Tuple + +class Cmd: + prompt: str + identchars: str + ruler: str + lastcmd: str + intro: Optional[Any] + doc_leader: str + doc_header: str + misc_header: str + undoc_header: str + nohelp: str + use_rawinput: bool + stdin: IO[str] + stdout: IO[str] + cmdqueue: List[str] + completekey: str + def __init__(self, completekey: str = ..., stdin: Optional[IO[str]] = ..., stdout: Optional[IO[str]] = ...) -> None: ... + old_completer: Optional[Callable[[str, int], Optional[str]]] + def cmdloop(self, intro: Optional[Any] = ...) -> None: ... + def precmd(self, line: str) -> str: ... + def postcmd(self, stop: bool, line: str) -> bool: ... + def preloop(self) -> None: ... + def postloop(self) -> None: ... + def parseline(self, line: str) -> Tuple[Optional[str], Optional[str], str]: ... + def onecmd(self, line: str) -> bool: ... + def emptyline(self) -> bool: ... + def default(self, line: str) -> bool: ... + def completedefault(self, *ignored: Any) -> List[str]: ... + def completenames(self, text: str, *ignored: Any) -> List[str]: ... + completion_matches: Optional[List[str]] + def complete(self, text: str, state: int) -> Optional[List[str]]: ... + def get_names(self) -> List[str]: ... + # Only the first element of args matters. + def complete_help(self, *args: Any) -> List[str]: ... + def do_help(self, arg: str) -> Optional[bool]: ... + def print_topics(self, header: str, cmds: Optional[List[str]], cmdlen: Any, maxcol: int) -> None: ... + def columnize(self, list: Optional[List[str]], displaywidth: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/code.pyi b/mypy/typeshed/stdlib/@python2/code.pyi new file mode 100644 index 000000000000..ea882c9de68e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/code.pyi @@ -0,0 +1,22 @@ +from types import CodeType +from typing import Any, Callable, Mapping, Optional + +class InteractiveInterpreter: + def __init__(self, locals: Optional[Mapping[str, Any]] = ...) -> None: ... + def runsource(self, source: str, filename: str = ..., symbol: str = ...) -> bool: ... + def runcode(self, code: CodeType) -> None: ... + def showsyntaxerror(self, filename: Optional[str] = ...) -> None: ... + def showtraceback(self) -> None: ... + def write(self, data: str) -> None: ... + +class InteractiveConsole(InteractiveInterpreter): + def __init__(self, locals: Optional[Mapping[str, Any]] = ..., filename: str = ...) -> None: ... + def interact(self, banner: Optional[str] = ...) -> None: ... + def push(self, line: str) -> bool: ... + def resetbuffer(self) -> None: ... + def raw_input(self, prompt: str = ...) -> str: ... + +def interact( + banner: Optional[str] = ..., readfunc: Optional[Callable[[str], str]] = ..., local: Optional[Mapping[str, Any]] = ... +) -> None: ... +def compile_command(source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... diff --git a/mypy/typeshed/stdlib/@python2/codecs.pyi b/mypy/typeshed/stdlib/@python2/codecs.pyi new file mode 100644 index 000000000000..8bacab771b0d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/codecs.pyi @@ -0,0 +1,297 @@ +import types +from abc import abstractmethod +from typing import ( + IO, + Any, + BinaryIO, + Callable, + Generator, + Iterable, + Iterator, + List, + Optional, + Protocol, + Text, + TextIO, + Tuple, + Type, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal + +# TODO: this only satisfies the most common interface, where +# bytes (py2 str) is the raw form and str (py2 unicode) is the cooked form. +# In the long run, both should become template parameters maybe? +# There *are* bytes->bytes and str->str encodings in the standard library. +# They are much more common in Python 2 than in Python 3. + +_Decoded = Text +_Encoded = bytes + +class _Encoder(Protocol): + def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode + +class _Decoder(Protocol): + def __call__(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... # signature of Codec().decode + +class _StreamReader(Protocol): + def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamReader: ... + +class _StreamWriter(Protocol): + def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamWriter: ... + +class _IncrementalEncoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalEncoder: ... + +class _IncrementalDecoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalDecoder: ... + +# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 +# mypy and pytype disagree about where the type ignore can and cannot go, so alias the long type +_BytesToBytesEncodingT = Literal[ + "base64", + "base_64", + "base64_codec", + "bz2", + "bz2_codec", + "hex", + "hex_codec", + "quopri", + "quotedprintable", + "quoted_printable", + "quopri_codec", + "uu", + "uu_codec", + "zip", + "zlib", + "zlib_codec", +] + +@overload +def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... +@overload +def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore +@overload +def encode(obj: _Decoded, encoding: str = ..., errors: str = ...) -> _Encoded: ... +@overload +def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore +@overload +def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> Text: ... +@overload +def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: ... +def lookup(__encoding: str) -> CodecInfo: ... +def utf_16_be_decode( + __data: _Encoded, __errors: Optional[str] = ..., __final: bool = ... +) -> Tuple[_Decoded, int]: ... # undocumented +def utf_16_be_encode(__str: _Decoded, __errors: Optional[str] = ...) -> Tuple[_Encoded, int]: ... # undocumented + +class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __new__( + cls, + encode: _Encoder, + decode: _Decoder, + streamreader: Optional[_StreamReader] = ..., + streamwriter: Optional[_StreamWriter] = ..., + incrementalencoder: Optional[_IncrementalEncoder] = ..., + incrementaldecoder: Optional[_IncrementalDecoder] = ..., + name: Optional[str] = ..., + *, + _is_text_encoding: Optional[bool] = ..., + ) -> CodecInfo: ... + +def getencoder(encoding: str) -> _Encoder: ... +def getdecoder(encoding: str) -> _Decoder: ... +def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... +def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... +def getreader(encoding: str) -> _StreamReader: ... +def getwriter(encoding: str) -> _StreamWriter: ... +def register(__search_function: Callable[[str], Optional[CodecInfo]]) -> None: ... +def open( + filename: str, mode: str = ..., encoding: Optional[str] = ..., errors: str = ..., buffering: int = ... +) -> StreamReaderWriter: ... +def EncodedFile( + file: IO[_Encoded], data_encoding: str, file_encoding: Optional[str] = ..., errors: str = ... +) -> StreamRecoder: ... +def iterencode(iterator: Iterable[_Decoded], encoding: str, errors: str = ...) -> Generator[_Encoded, None, None]: ... +def iterdecode(iterator: Iterable[_Encoded], encoding: str, errors: str = ...) -> Generator[_Decoded, None, None]: ... + +BOM: bytes +BOM_BE: bytes +BOM_LE: bytes +BOM_UTF8: bytes +BOM_UTF16: bytes +BOM_UTF16_BE: bytes +BOM_UTF16_LE: bytes +BOM_UTF32: bytes +BOM_UTF32_BE: bytes +BOM_UTF32_LE: bytes + +# It is expected that different actions be taken depending on which of the +# three subclasses of `UnicodeError` is actually ...ed. However, the Union +# is still needed for at least one of the cases. +def register_error(__errors: str, __handler: Callable[[UnicodeError], Tuple[Union[str, bytes], int]]) -> None: ... +def lookup_error(__name: str) -> Callable[[UnicodeError], Tuple[Union[str, bytes], int]]: ... +def strict_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def replace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def ignore_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def backslashreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... + +class Codec: + # These are sort of @abstractmethod but sort of not. + # The StreamReader and StreamWriter subclasses only implement one. + def encode(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... + def decode(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... + +class IncrementalEncoder: + errors: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... + def reset(self) -> None: ... + # documentation says int but str is needed for the subclass. + def getstate(self) -> Union[int, _Decoded]: ... + def setstate(self, state: Union[int, _Decoded]) -> None: ... + +class IncrementalDecoder: + errors: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... + def reset(self) -> None: ... + def getstate(self) -> Tuple[_Encoded, int]: ... + def setstate(self, state: Tuple[_Encoded, int]) -> None: ... + +# These are not documented but used in encodings/*.py implementations. +class BufferedIncrementalEncoder(IncrementalEncoder): + buffer: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def _buffer_encode(self, input: _Decoded, errors: str, final: bool) -> _Encoded: ... + def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... + +class BufferedIncrementalDecoder(IncrementalDecoder): + buffer: bytes + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... + def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... + +_SW = TypeVar("_SW", bound=StreamWriter) + +# TODO: it is not possible to specify the requirement that all other +# attributes and methods are passed-through from the stream. +class StreamWriter(Codec): + errors: str + def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... + def write(self, object: _Decoded) -> None: ... + def writelines(self, list: Iterable[_Decoded]) -> None: ... + def reset(self) -> None: ... + def __enter__(self: _SW) -> _SW: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... + +_SR = TypeVar("_SR", bound=StreamReader) + +class StreamReader(Codec): + errors: str + def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... + def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... + def readline(self, size: Optional[int] = ..., keepends: bool = ...) -> _Decoded: ... + def readlines(self, sizehint: Optional[int] = ..., keepends: bool = ...) -> List[_Decoded]: ... + def reset(self) -> None: ... + def __enter__(self: _SR) -> _SR: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + def __iter__(self) -> Iterator[_Decoded]: ... + def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... + +_T = TypeVar("_T", bound=StreamReaderWriter) + +# Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing +# and delegates attributes to the underlying binary stream with __getattr__. +class StreamReaderWriter(TextIO): + def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... + def read(self, size: int = ...) -> _Decoded: ... + def readline(self, size: Optional[int] = ...) -> _Decoded: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[_Decoded]: ... + def next(self) -> Text: ... + def __iter__(self: _T) -> _T: ... + # This actually returns None, but that's incompatible with the supertype + def write(self, data: _Decoded) -> int: ... + def writelines(self, list: Iterable[_Decoded]) -> None: ... + def reset(self) -> None: ... + # Same as write() + def seek(self, offset: int, whence: int = ...) -> int: ... + def __enter__(self: _T) -> _T: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + # These methods don't actually exist directly, but they are needed to satisfy the TextIO + # interface. At runtime, they are delegated through __getattr__. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... + +_SRT = TypeVar("_SRT", bound=StreamRecoder) + +class StreamRecoder(BinaryIO): + def __init__( + self, + stream: IO[_Encoded], + encode: _Encoder, + decode: _Decoder, + Reader: _StreamReader, + Writer: _StreamWriter, + errors: str = ..., + ) -> None: ... + def read(self, size: int = ...) -> bytes: ... + def readline(self, size: Optional[int] = ...) -> bytes: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[bytes]: ... + def next(self) -> bytes: ... + def __iter__(self: _SRT) -> _SRT: ... + def write(self, data: bytes) -> int: ... + def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None + def reset(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self: _SRT) -> _SRT: ... + def __exit__( + self, type: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO + # interface. At runtime, they are delegated through __getattr__. + def seek(self, offset: int, whence: int = ...) -> int: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/codeop.pyi b/mypy/typeshed/stdlib/@python2/codeop.pyi new file mode 100644 index 000000000000..f3d6c2819ec6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/codeop.pyi @@ -0,0 +1,14 @@ +from types import CodeType +from typing import Optional + +def compile_command(source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... + +class Compile: + flags: int + def __init__(self) -> None: ... + def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... + +class CommandCompiler: + compiler: Compile + def __init__(self) -> None: ... + def __call__(self, source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... diff --git a/mypy/typeshed/stdlib/@python2/colorsys.pyi b/mypy/typeshed/stdlib/@python2/colorsys.pyi new file mode 100644 index 000000000000..8db2e2c9ab3a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/colorsys.pyi @@ -0,0 +1,13 @@ +from typing import Tuple + +def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def yiq_to_rgb(y: float, i: float, q: float) -> Tuple[float, float, float]: ... +def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ... +def rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: ... + +# TODO undocumented +ONE_SIXTH: float +ONE_THIRD: float +TWO_THIRD: float diff --git a/mypy/typeshed/stdlib/@python2/compileall.pyi b/mypy/typeshed/stdlib/@python2/compileall.pyi index 59680fd7926d..5ae1d6f7f7c1 100644 --- a/mypy/typeshed/stdlib/@python2/compileall.pyi +++ b/mypy/typeshed/stdlib/@python2/compileall.pyi @@ -1,16 +1,15 @@ -from _typeshed import AnyPath -from typing import Any, Optional, Pattern +from typing import Any, Optional, Pattern, Text # rx can be any object with a 'search' method; once we have Protocols we can change the type def compile_dir( - dir: AnyPath, + dir: Text, maxlevels: int = ..., - ddir: Optional[AnyPath] = ..., + ddir: Optional[Text] = ..., force: bool = ..., rx: Optional[Pattern[Any]] = ..., quiet: int = ..., ) -> int: ... def compile_file( - fullname: AnyPath, ddir: Optional[AnyPath] = ..., force: bool = ..., rx: Optional[Pattern[Any]] = ..., quiet: int = ... + fullname: Text, ddir: Optional[Text] = ..., force: bool = ..., rx: Optional[Pattern[Any]] = ..., quiet: int = ... ) -> int: ... def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/contextlib.pyi b/mypy/typeshed/stdlib/@python2/contextlib.pyi new file mode 100644 index 000000000000..6aabf5a16e47 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/contextlib.pyi @@ -0,0 +1,25 @@ +from types import TracebackType +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Type, TypeVar +from typing_extensions import Protocol + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) +_F = TypeVar("_F", bound=Callable[..., Any]) + +_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] +_CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) + +class GeneratorContextManager(ContextManager[_T_co]): + def __call__(self, func: _F) -> _F: ... + +def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... +def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... + +class _SupportsClose(Protocol): + def close(self) -> None: ... + +_SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) + +class closing(ContextManager[_SupportsCloseT]): + def __init__(self, thing: _SupportsCloseT) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/copy.pyi b/mypy/typeshed/stdlib/@python2/copy.pyi new file mode 100644 index 000000000000..b51c79c66c6a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/copy.pyi @@ -0,0 +1,14 @@ +from typing import Any, Dict, Optional, TypeVar + +_T = TypeVar("_T") + +# None in CPython but non-None in Jython +PyStringMap: Any + +# Note: memo and _nil are internal kwargs. +def deepcopy(x: _T, memo: Optional[Dict[int, Any]] = ..., _nil: Any = ...) -> _T: ... +def copy(x: _T) -> _T: ... + +class Error(Exception): ... + +error = Error diff --git a/mypy/typeshed/stdlib/@python2/copyreg.pyi b/mypy/typeshed/stdlib/@python2/copyreg.pyi new file mode 100644 index 000000000000..ea07ba410b6d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/copyreg.pyi @@ -0,0 +1,16 @@ +from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union + +_TypeT = TypeVar("_TypeT", bound=type) +_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] + +__all__: List[str] + +def pickle( + ob_type: _TypeT, + pickle_function: Callable[[_TypeT], Union[str, _Reduce[_TypeT]]], + constructor_ob: Optional[Callable[[_Reduce[_TypeT]], _TypeT]] = ..., +) -> None: ... +def constructor(object: Callable[[_Reduce[_TypeT]], _TypeT]) -> None: ... +def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ... +def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... +def clear_extension_cache() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/crypt.pyi b/mypy/typeshed/stdlib/@python2/crypt.pyi new file mode 100644 index 000000000000..c4036dbe7a5a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/crypt.pyi @@ -0,0 +1 @@ +def crypt(word: str, salt: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/csv.pyi b/mypy/typeshed/stdlib/@python2/csv.pyi new file mode 100644 index 000000000000..944c04065ae0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/csv.pyi @@ -0,0 +1,103 @@ +from _csv import ( + QUOTE_ALL as QUOTE_ALL, + QUOTE_MINIMAL as QUOTE_MINIMAL, + QUOTE_NONE as QUOTE_NONE, + QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, + Dialect as Dialect, + Error as Error, + _DialectLike, + _reader, + _writer, + field_size_limit as field_size_limit, + get_dialect as get_dialect, + list_dialects as list_dialects, + reader as reader, + register_dialect as register_dialect, + unregister_dialect as unregister_dialect, + writer as writer, +) +from typing import ( + Any, + Dict as _DictReadMapping, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Text, + Type, + TypeVar, + overload, +) + +_T = TypeVar("_T") + +class excel(Dialect): + delimiter: str + quotechar: str + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: int + +class excel_tab(excel): + delimiter: str + +class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): + fieldnames: Optional[Sequence[_T]] + restkey: Optional[str] + restval: Optional[str] + reader: _reader + dialect: _DialectLike + line_num: int + @overload + def __init__( + self, + f: Iterable[Text], + fieldnames: Sequence[_T], + restkey: Optional[str] = ..., + restval: Optional[str] = ..., + dialect: _DialectLike = ..., + *args: Any, + **kwds: Any, + ) -> None: ... + @overload + def __init__( + self: DictReader[str], + f: Iterable[Text], + fieldnames: Optional[Sequence[str]] = ..., + restkey: Optional[str] = ..., + restval: Optional[str] = ..., + dialect: _DialectLike = ..., + *args: Any, + **kwds: Any, + ) -> None: ... + def __iter__(self) -> DictReader[_T]: ... + def next(self) -> _DictReadMapping[_T, str]: ... + +class DictWriter(Generic[_T]): + fieldnames: Sequence[_T] + restval: Optional[Any] + extrasaction: str + writer: _writer + def __init__( + self, + f: Any, + fieldnames: Sequence[_T], + restval: Optional[Any] = ..., + extrasaction: str = ..., + dialect: _DialectLike = ..., + *args: Any, + **kwds: Any, + ) -> None: ... + def writeheader(self) -> None: ... + def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... + def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... + +class Sniffer(object): + preferred: List[str] + def __init__(self) -> None: ... + def sniff(self, sample: str, delimiters: Optional[str] = ...) -> Type[Dialect]: ... + def has_header(self, sample: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi new file mode 100644 index 000000000000..4adaa3975a82 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi @@ -0,0 +1,293 @@ +import sys +from array import array +from typing import ( + Any, + Callable, + ClassVar, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Text, + Tuple, + Type, + TypeVar, + Union as _UnionT, + overload, +) + +_T = TypeVar("_T") +_DLLT = TypeVar("_DLLT", bound=CDLL) +_CT = TypeVar("_CT", bound=_CData) + +RTLD_GLOBAL: int = ... +RTLD_LOCAL: int = ... +DEFAULT_MODE: int = ... + +class CDLL(object): + _func_flags_: ClassVar[int] = ... + _func_restype_: ClassVar[_CData] = ... + _name: str = ... + _handle: int = ... + _FuncPtr: Type[_FuncPointer] = ... + def __init__( + self, name: Optional[str], mode: int = ..., handle: Optional[int] = ..., use_errno: bool = ..., use_last_error: bool = ... + ) -> None: ... + def __getattr__(self, name: str) -> _NamedFuncPointer: ... + def __getitem__(self, name: str) -> _NamedFuncPointer: ... + +if sys.platform == "win32": + class OleDLL(CDLL): ... + class WinDLL(CDLL): ... + +class PyDLL(CDLL): ... + +class LibraryLoader(Generic[_DLLT]): + def __init__(self, dlltype: Type[_DLLT]) -> None: ... + def __getattr__(self, name: str) -> _DLLT: ... + def __getitem__(self, name: str) -> _DLLT: ... + def LoadLibrary(self, name: str) -> _DLLT: ... + +cdll: LibraryLoader[CDLL] = ... +if sys.platform == "win32": + windll: LibraryLoader[WinDLL] = ... + oledll: LibraryLoader[OleDLL] = ... +pydll: LibraryLoader[PyDLL] = ... +pythonapi: PyDLL = ... + +# Anything that implements the read-write buffer interface. +# The buffer interface is defined purely on the C level, so we cannot define a normal Protocol +# for it. Instead we have to list the most common stdlib buffer classes in a Union. +_WritableBuffer = _UnionT[bytearray, memoryview, array[Any], _CData] +# Same as _WritableBuffer, but also includes read-only buffer types (like bytes). +_ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] + +class _CDataMeta(type): + # By default mypy complains about the following two methods, because strictly speaking cls + # might not be a Type[_CT]. However this can never actually happen, because the only class that + # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. + def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore + def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore + +class _CData(metaclass=_CDataMeta): + _b_base: int = ... + _b_needsfree_: bool = ... + _objects: Optional[Mapping[Any, int]] = ... + @classmethod + def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ... + @classmethod + def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ... + @classmethod + def from_address(cls: Type[_CT], address: int) -> _CT: ... + @classmethod + def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + @classmethod + def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + +class _CanCastTo(_CData): ... +class _PointerLike(_CanCastTo): ... + +_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] +_PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] + +class _FuncPointer(_PointerLike, _CData): + restype: _UnionT[Type[_CData], Callable[[int], Any], None] = ... + argtypes: Sequence[Type[_CData]] = ... + errcheck: _ECT = ... + @overload + def __init__(self, address: int) -> None: ... + @overload + def __init__(self, callable: Callable[..., Any]) -> None: ... + @overload + def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... + @overload + def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class _NamedFuncPointer(_FuncPointer): + __name__: str + +class ArgumentError(Exception): ... + +def CFUNCTYPE( + restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... +) -> Type[_FuncPointer]: ... + +if sys.platform == "win32": + def WINFUNCTYPE( + restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... + ) -> Type[_FuncPointer]: ... + +def PYFUNCTYPE(restype: Optional[Type[_CData]], *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... + +class _CArgObject: ... + +# Any type that can be implicitly converted to c_void_p when passed as a C function argument. +# (bytes is not included here, see below.) +_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] +# Same as above, but including types known to be read-only (i. e. bytes). +# This distinction is not strictly necessary (ctypes doesn't differentiate between const +# and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) +# when memmove(buf, b'foo', 4) was intended. +_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] + +def addressof(obj: _CData) -> int: ... +def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... + +_CastT = TypeVar("_CastT", bound=_CanCastTo) + +def cast(obj: _UnionT[_CData, _CArgObject, int], typ: Type[_CastT]) -> _CastT: ... +def create_string_buffer(init: _UnionT[int, bytes], size: Optional[int] = ...) -> Array[c_char]: ... + +c_buffer = create_string_buffer + +def create_unicode_buffer(init: _UnionT[int, Text], size: Optional[int] = ...) -> Array[c_wchar]: ... + +if sys.platform == "win32": + def DllCanUnloadNow() -> int: ... + def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented + def FormatError(code: int) -> str: ... + def GetLastError() -> int: ... + +def get_errno() -> int: ... + +if sys.platform == "win32": + def get_last_error() -> int: ... + +def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... +def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... +def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... + +# The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like +# ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, +# it can be instantiated directly (to mimic the behavior of the real pointer function). +class pointer(Generic[_CT], _PointerLike, _CData): + _type_: ClassVar[Type[_CT]] = ... + contents: _CT = ... + def __init__(self, arg: _CT = ...) -> None: ... + @overload + def __getitem__(self, i: int) -> _CT: ... + @overload + def __getitem__(self, s: slice) -> List[_CT]: ... + @overload + def __setitem__(self, i: int, o: _CT) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... + +def resize(obj: _CData, size: int) -> None: ... +def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... +def set_errno(value: int) -> int: ... + +if sys.platform == "win32": + def set_last_error(value: int) -> int: ... + +def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... + +if sys.platform == "win32": + def WinError(code: Optional[int] = ..., descr: Optional[str] = ...) -> OSError: ... + +def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ... + +class _SimpleCData(Generic[_T], _CData): + value: _T = ... + def __init__(self, value: _T = ...) -> None: ... + +class c_byte(_SimpleCData[int]): ... + +class c_char(_SimpleCData[bytes]): + def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ... + +class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): + def __init__(self, value: Optional[_UnionT[int, bytes]] = ...) -> None: ... + +class c_double(_SimpleCData[float]): ... +class c_longdouble(_SimpleCData[float]): ... +class c_float(_SimpleCData[float]): ... +class c_int(_SimpleCData[int]): ... +class c_int8(_SimpleCData[int]): ... +class c_int16(_SimpleCData[int]): ... +class c_int32(_SimpleCData[int]): ... +class c_int64(_SimpleCData[int]): ... +class c_long(_SimpleCData[int]): ... +class c_longlong(_SimpleCData[int]): ... +class c_short(_SimpleCData[int]): ... +class c_size_t(_SimpleCData[int]): ... +class c_ssize_t(_SimpleCData[int]): ... +class c_ubyte(_SimpleCData[int]): ... +class c_uint(_SimpleCData[int]): ... +class c_uint8(_SimpleCData[int]): ... +class c_uint16(_SimpleCData[int]): ... +class c_uint32(_SimpleCData[int]): ... +class c_uint64(_SimpleCData[int]): ... +class c_ulong(_SimpleCData[int]): ... +class c_ulonglong(_SimpleCData[int]): ... +class c_ushort(_SimpleCData[int]): ... +class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... +class c_wchar(_SimpleCData[Text]): ... + +class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): + def __init__(self, value: Optional[_UnionT[int, Text]] = ...) -> None: ... + +class c_bool(_SimpleCData[bool]): + def __init__(self, value: bool = ...) -> None: ... + +if sys.platform == "win32": + class HRESULT(_SimpleCData[int]): ... # TODO undocumented + +class py_object(_CanCastTo, _SimpleCData[_T]): ... + +class _CField: + offset: int = ... + size: int = ... + +class _StructUnionMeta(_CDataMeta): + _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ... + _pack_: int = ... + _anonymous_: Sequence[str] = ... + def __getattr__(self, name: str) -> _CField: ... + +class _StructUnionBase(_CData, metaclass=_StructUnionMeta): + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class Union(_StructUnionBase): ... +class Structure(_StructUnionBase): ... +class BigEndianStructure(Structure): ... +class LittleEndianStructure(Structure): ... + +class Array(Generic[_CT], _CData): + _length_: ClassVar[int] = ... + _type_: ClassVar[Type[_CT]] = ... + raw: bytes = ... # Note: only available if _CT == c_char + value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise + # TODO These methods cannot be annotated correctly at the moment. + # All of these "Any"s stand for the array's element type, but it's not possible to use _CT + # here, because of a special feature of ctypes. + # By default, when accessing an element of an Array[_CT], the returned object has type _CT. + # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object + # and converts it to the corresponding Python primitive. For example, when accessing an element + # of an Array[c_int], a Python int object is returned, not a c_int. + # This behavior does *not* apply to subclasses of "simple types". + # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns + # a MyInt, not an int. + # This special behavior is not easy to model in a stub, so for now all places where + # the array element type would belong are annotated with Any instead. + def __init__(self, *args: Any) -> None: ... + @overload + def __getitem__(self, i: int) -> Any: ... + @overload + def __getitem__(self, s: slice) -> List[Any]: ... + @overload + def __setitem__(self, i: int, o: Any) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ... + def __iter__(self) -> Iterator[Any]: ... + # Can't inherit from Sized because the metaclass conflict between + # Sized and _CData prevents using _CDataMeta. + def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/util.pyi b/mypy/typeshed/stdlib/@python2/ctypes/util.pyi new file mode 100644 index 000000000000..20914c70a05c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ctypes/util.pyi @@ -0,0 +1,7 @@ +import sys +from typing import Optional + +def find_library(name: str) -> Optional[str]: ... + +if sys.platform == "win32": + def find_msvcrt() -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/@python2/ctypes/wintypes.pyi new file mode 100644 index 000000000000..c178a9bdf936 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ctypes/wintypes.pyi @@ -0,0 +1,234 @@ +from ctypes import ( + Array, + Structure, + _SimpleCData, + c_byte, + c_char, + c_char_p, + c_double, + c_float, + c_int, + c_long, + c_longlong, + c_short, + c_uint, + c_ulong, + c_ulonglong, + c_ushort, + c_void_p, + c_wchar, + c_wchar_p, + pointer, +) + +BYTE = c_byte +WORD = c_ushort +DWORD = c_ulong +CHAR = c_char +WCHAR = c_wchar +UINT = c_uint +INT = c_int +DOUBLE = c_double +FLOAT = c_float +BOOLEAN = BYTE +BOOL = c_long + +class VARIANT_BOOL(_SimpleCData[bool]): ... + +ULONG = c_ulong +LONG = c_long +USHORT = c_ushort +SHORT = c_short +LARGE_INTEGER = c_longlong +_LARGE_INTEGER = c_longlong +ULARGE_INTEGER = c_ulonglong +_ULARGE_INTEGER = c_ulonglong + +OLESTR = c_wchar_p +LPOLESTR = c_wchar_p +LPCOLESTR = c_wchar_p +LPWSTR = c_wchar_p +LPCWSTR = c_wchar_p +LPSTR = c_char_p +LPCSTR = c_char_p +LPVOID = c_void_p +LPCVOID = c_void_p + +# These two types are pointer-sized unsigned and signed ints, respectively. +# At runtime, they are either c_[u]long or c_[u]longlong, depending on the host's pointer size +# (they are not really separate classes). +class WPARAM(_SimpleCData[int]): ... +class LPARAM(_SimpleCData[int]): ... + +ATOM = WORD +LANGID = WORD +COLORREF = DWORD +LGRPID = DWORD +LCTYPE = DWORD +LCID = DWORD + +HANDLE = c_void_p +HACCEL = HANDLE +HBITMAP = HANDLE +HBRUSH = HANDLE +HCOLORSPACE = HANDLE +HDC = HANDLE +HDESK = HANDLE +HDWP = HANDLE +HENHMETAFILE = HANDLE +HFONT = HANDLE +HGDIOBJ = HANDLE +HGLOBAL = HANDLE +HHOOK = HANDLE +HICON = HANDLE +HINSTANCE = HANDLE +HKEY = HANDLE +HKL = HANDLE +HLOCAL = HANDLE +HMENU = HANDLE +HMETAFILE = HANDLE +HMODULE = HANDLE +HMONITOR = HANDLE +HPALETTE = HANDLE +HPEN = HANDLE +HRGN = HANDLE +HRSRC = HANDLE +HSTR = HANDLE +HTASK = HANDLE +HWINSTA = HANDLE +HWND = HANDLE +SC_HANDLE = HANDLE +SERVICE_STATUS_HANDLE = HANDLE + +class RECT(Structure): + left: LONG + top: LONG + right: LONG + bottom: LONG + +RECTL = RECT +_RECTL = RECT +tagRECT = RECT + +class _SMALL_RECT(Structure): + Left: SHORT + Top: SHORT + Right: SHORT + Bottom: SHORT + +SMALL_RECT = _SMALL_RECT + +class _COORD(Structure): + X: SHORT + Y: SHORT + +class POINT(Structure): + x: LONG + y: LONG + +POINTL = POINT +_POINTL = POINT +tagPOINT = POINT + +class SIZE(Structure): + cx: LONG + cy: LONG + +SIZEL = SIZE +tagSIZE = SIZE + +def RGB(red: int, green: int, blue: int) -> int: ... + +class FILETIME(Structure): + dwLowDateTime: DWORD + dwHighDateTime: DWORD + +_FILETIME = FILETIME + +class MSG(Structure): + hWnd: HWND + message: UINT + wParam: WPARAM + lParam: LPARAM + time: DWORD + pt: POINT + +tagMSG = MSG +MAX_PATH: int + +class WIN32_FIND_DATAA(Structure): + dwFileAttributes: DWORD + ftCreationTime: FILETIME + ftLastAccessTime: FILETIME + ftLastWriteTime: FILETIME + nFileSizeHigh: DWORD + nFileSizeLow: DWORD + dwReserved0: DWORD + dwReserved1: DWORD + cFileName: Array[CHAR] + cAlternateFileName: Array[CHAR] + +class WIN32_FIND_DATAW(Structure): + dwFileAttributes: DWORD + ftCreationTime: FILETIME + ftLastAccessTime: FILETIME + ftLastWriteTime: FILETIME + nFileSizeHigh: DWORD + nFileSizeLow: DWORD + dwReserved0: DWORD + dwReserved1: DWORD + cFileName: Array[WCHAR] + cAlternateFileName: Array[WCHAR] + +# These pointer type definitions use pointer[...] instead of POINTER(...), to allow them +# to be used in type annotations. +PBOOL = pointer[BOOL] +LPBOOL = pointer[BOOL] +PBOOLEAN = pointer[BOOLEAN] +PBYTE = pointer[BYTE] +LPBYTE = pointer[BYTE] +PCHAR = pointer[CHAR] +LPCOLORREF = pointer[COLORREF] +PDWORD = pointer[DWORD] +LPDWORD = pointer[DWORD] +PFILETIME = pointer[FILETIME] +LPFILETIME = pointer[FILETIME] +PFLOAT = pointer[FLOAT] +PHANDLE = pointer[HANDLE] +LPHANDLE = pointer[HANDLE] +PHKEY = pointer[HKEY] +LPHKL = pointer[HKL] +PINT = pointer[INT] +LPINT = pointer[INT] +PLARGE_INTEGER = pointer[LARGE_INTEGER] +PLCID = pointer[LCID] +PLONG = pointer[LONG] +LPLONG = pointer[LONG] +PMSG = pointer[MSG] +LPMSG = pointer[MSG] +PPOINT = pointer[POINT] +LPPOINT = pointer[POINT] +PPOINTL = pointer[POINTL] +PRECT = pointer[RECT] +LPRECT = pointer[RECT] +PRECTL = pointer[RECTL] +LPRECTL = pointer[RECTL] +LPSC_HANDLE = pointer[SC_HANDLE] +PSHORT = pointer[SHORT] +PSIZE = pointer[SIZE] +LPSIZE = pointer[SIZE] +PSIZEL = pointer[SIZEL] +LPSIZEL = pointer[SIZEL] +PSMALL_RECT = pointer[SMALL_RECT] +PUINT = pointer[UINT] +LPUINT = pointer[UINT] +PULARGE_INTEGER = pointer[ULARGE_INTEGER] +PULONG = pointer[ULONG] +PUSHORT = pointer[USHORT] +PWCHAR = pointer[WCHAR] +PWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] +LPWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] +PWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] +LPWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] +PWORD = pointer[WORD] +LPWORD = pointer[WORD] diff --git a/mypy/typeshed/stdlib/@python2/curses/__init__.pyi b/mypy/typeshed/stdlib/@python2/curses/__init__.pyi new file mode 100644 index 000000000000..73e84fba3763 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/curses/__init__.pyi @@ -0,0 +1,15 @@ +from _curses import * # noqa: F403 +from _curses import _CursesWindow as _CursesWindow +from typing import Any, Callable, TypeVar + +_T = TypeVar("_T") + +# available after calling `curses.initscr()` +LINES: int +COLS: int + +# available after calling `curses.start_color()` +COLORS: int +COLOR_PAIRS: int + +def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/curses/ascii.pyi b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi new file mode 100644 index 000000000000..10bab853adcf --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi @@ -0,0 +1,62 @@ +from typing import List, TypeVar, Union + +_CharT = TypeVar("_CharT", str, int) + +NUL: int +SOH: int +STX: int +ETX: int +EOT: int +ENQ: int +ACK: int +BEL: int +BS: int +TAB: int +HT: int +LF: int +NL: int +VT: int +FF: int +CR: int +SO: int +SI: int +DLE: int +DC1: int +DC2: int +DC3: int +DC4: int +NAK: int +SYN: int +ETB: int +CAN: int +EM: int +SUB: int +ESC: int +FS: int +GS: int +RS: int +US: int +SP: int +DEL: int + +controlnames: List[int] + +def isalnum(c: Union[str, int]) -> bool: ... +def isalpha(c: Union[str, int]) -> bool: ... +def isascii(c: Union[str, int]) -> bool: ... +def isblank(c: Union[str, int]) -> bool: ... +def iscntrl(c: Union[str, int]) -> bool: ... +def isdigit(c: Union[str, int]) -> bool: ... +def isgraph(c: Union[str, int]) -> bool: ... +def islower(c: Union[str, int]) -> bool: ... +def isprint(c: Union[str, int]) -> bool: ... +def ispunct(c: Union[str, int]) -> bool: ... +def isspace(c: Union[str, int]) -> bool: ... +def isupper(c: Union[str, int]) -> bool: ... +def isxdigit(c: Union[str, int]) -> bool: ... +def isctrl(c: Union[str, int]) -> bool: ... +def ismeta(c: Union[str, int]) -> bool: ... +def ascii(c: _CharT) -> _CharT: ... +def ctrl(c: _CharT) -> _CharT: ... +def alt(c: _CharT) -> _CharT: ... +def unctrl(c: Union[str, int]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/curses/panel.pyi b/mypy/typeshed/stdlib/@python2/curses/panel.pyi new file mode 100644 index 000000000000..138e4a9f727e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/curses/panel.pyi @@ -0,0 +1,20 @@ +from _curses import _CursesWindow + +class _Curses_Panel: # type is (note the space in the class name) + def above(self) -> _Curses_Panel: ... + def below(self) -> _Curses_Panel: ... + def bottom(self) -> None: ... + def hidden(self) -> bool: ... + def hide(self) -> None: ... + def move(self, y: int, x: int) -> None: ... + def replace(self, win: _CursesWindow) -> None: ... + def set_userptr(self, obj: object) -> None: ... + def show(self) -> None: ... + def top(self) -> None: ... + def userptr(self) -> object: ... + def window(self) -> _CursesWindow: ... + +def bottom_panel() -> _Curses_Panel: ... +def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... +def top_panel() -> _Curses_Panel: ... +def update_panels() -> _Curses_Panel: ... diff --git a/mypy/typeshed/stdlib/@python2/curses/textpad.pyi b/mypy/typeshed/stdlib/@python2/curses/textpad.pyi new file mode 100644 index 000000000000..d2b5766fda26 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/curses/textpad.pyi @@ -0,0 +1,11 @@ +from _curses import _CursesWindow +from typing import Callable, Optional, Union + +def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... + +class Textbox: + stripspaces: bool + def __init__(self, win: _CursesWindow, insert_mode: bool = ...) -> None: ... + def edit(self, validate: Optional[Callable[[int], int]] = ...) -> str: ... + def do_command(self, ch: Union[str, int]) -> None: ... + def gather(self) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/datetime.pyi b/mypy/typeshed/stdlib/@python2/datetime.pyi new file mode 100644 index 000000000000..d1b0d6437825 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/datetime.pyi @@ -0,0 +1,231 @@ +from time import struct_time +from typing import AnyStr, ClassVar, Optional, SupportsAbs, Tuple, Type, TypeVar, Union, overload + +_S = TypeVar("_S") + +_Text = Union[str, unicode] + +MINYEAR: int +MAXYEAR: int + +class tzinfo: + def tzname(self, dt: Optional[datetime]) -> Optional[str]: ... + def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ... + def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ... + def fromutc(self, dt: datetime) -> datetime: ... + +_tzinfo = tzinfo + +class date: + min: ClassVar[date] + max: ClassVar[date] + resolution: ClassVar[timedelta] + def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + @classmethod + def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + @classmethod + def today(cls: Type[_S]) -> _S: ... + @classmethod + def fromordinal(cls: Type[_S], n: int) -> _S: ... + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + def ctime(self) -> str: ... + def strftime(self, fmt: _Text) -> str: ... + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def isoformat(self) -> str: ... + def timetuple(self) -> struct_time: ... + def toordinal(self) -> int: ... + def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... + def __le__(self, other: date) -> bool: ... + def __lt__(self, other: date) -> bool: ... + def __ge__(self, other: date) -> bool: ... + def __gt__(self, other: date) -> bool: ... + def __add__(self, other: timedelta) -> date: ... + def __radd__(self, other: timedelta) -> date: ... + @overload + def __sub__(self, other: timedelta) -> date: ... + @overload + def __sub__(self, other: date) -> timedelta: ... + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def isocalendar(self) -> Tuple[int, int, int]: ... + +class time: + min: ClassVar[time] + max: ClassVar[time] + resolution: ClassVar[timedelta] + def __new__( + cls: Type[_S], + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + ) -> _S: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> Optional[_tzinfo]: ... + def __le__(self, other: time) -> bool: ... + def __lt__(self, other: time) -> bool: ... + def __ge__(self, other: time) -> bool: ... + def __gt__(self, other: time) -> bool: ... + def __hash__(self) -> int: ... + def isoformat(self) -> str: ... + def strftime(self, fmt: _Text) -> str: ... + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def utcoffset(self) -> Optional[timedelta]: ... + def tzname(self) -> Optional[str]: ... + def dst(self) -> Optional[timedelta]: ... + def replace( + self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ... + ) -> time: ... + +_date = date +_time = time + +class timedelta(SupportsAbs[timedelta]): + min: ClassVar[timedelta] + max: ClassVar[timedelta] + resolution: ClassVar[timedelta] + def __new__( + cls: Type[_S], + days: float = ..., + seconds: float = ..., + microseconds: float = ..., + milliseconds: float = ..., + minutes: float = ..., + hours: float = ..., + weeks: float = ..., + ) -> _S: ... + @property + def days(self) -> int: ... + @property + def seconds(self) -> int: ... + @property + def microseconds(self) -> int: ... + def total_seconds(self) -> float: ... + def __add__(self, other: timedelta) -> timedelta: ... + def __radd__(self, other: timedelta) -> timedelta: ... + def __sub__(self, other: timedelta) -> timedelta: ... + def __rsub__(self, other: timedelta) -> timedelta: ... + def __neg__(self) -> timedelta: ... + def __pos__(self) -> timedelta: ... + def __abs__(self) -> timedelta: ... + def __mul__(self, other: float) -> timedelta: ... + def __rmul__(self, other: float) -> timedelta: ... + @overload + def __floordiv__(self, other: timedelta) -> int: ... + @overload + def __floordiv__(self, other: int) -> timedelta: ... + @overload + def __div__(self, other: timedelta) -> float: ... + @overload + def __div__(self, other: float) -> timedelta: ... + def __le__(self, other: timedelta) -> bool: ... + def __lt__(self, other: timedelta) -> bool: ... + def __ge__(self, other: timedelta) -> bool: ... + def __gt__(self, other: timedelta) -> bool: ... + def __hash__(self) -> int: ... + +class datetime(date): + min: ClassVar[datetime] + max: ClassVar[datetime] + resolution: ClassVar[timedelta] + def __new__( + cls: Type[_S], + year: int, + month: int, + day: int, + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + ) -> _S: ... + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> Optional[_tzinfo]: ... + @classmethod + def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... + @classmethod + def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... + @classmethod + def today(cls: Type[_S]) -> _S: ... + @classmethod + def fromordinal(cls: Type[_S], n: int) -> _S: ... + @overload + @classmethod + def now(cls: Type[_S], tz: None = ...) -> _S: ... + @overload + @classmethod + def now(cls, tz: _tzinfo) -> datetime: ... + @classmethod + def utcnow(cls: Type[_S]) -> _S: ... + @classmethod + def combine(cls, date: _date, time: _time) -> datetime: ... + def strftime(self, fmt: _Text) -> str: ... + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def toordinal(self) -> int: ... + def timetuple(self) -> struct_time: ... + def utctimetuple(self) -> struct_time: ... + def date(self) -> _date: ... + def time(self) -> _time: ... + def timetz(self) -> _time: ... + def replace( + self, + year: int = ..., + month: int = ..., + day: int = ..., + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + ) -> datetime: ... + def astimezone(self, tz: _tzinfo) -> datetime: ... + def ctime(self) -> str: ... + def isoformat(self, sep: str = ...) -> str: ... + @classmethod + def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... + def utcoffset(self) -> Optional[timedelta]: ... + def tzname(self) -> Optional[str]: ... + def dst(self) -> Optional[timedelta]: ... + def __le__(self, other: datetime) -> bool: ... # type: ignore + def __lt__(self, other: datetime) -> bool: ... # type: ignore + def __ge__(self, other: datetime) -> bool: ... # type: ignore + def __gt__(self, other: datetime) -> bool: ... # type: ignore + def __add__(self, other: timedelta) -> datetime: ... + def __radd__(self, other: timedelta) -> datetime: ... + @overload # type: ignore + def __sub__(self, other: datetime) -> timedelta: ... + @overload + def __sub__(self, other: timedelta) -> datetime: ... + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def isocalendar(self) -> Tuple[int, int, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi new file mode 100644 index 000000000000..edce1ea02861 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi @@ -0,0 +1,26 @@ +from types import TracebackType +from typing import Iterator, MutableMapping, Optional, Tuple, Type, Union +from typing_extensions import Literal + +_KeyType = Union[str, bytes] +_ValueType = Union[str, bytes] + +class _Database(MutableMapping[_KeyType, bytes]): + def close(self) -> None: ... + def __getitem__(self, key: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def __del__(self) -> None: ... + def __enter__(self) -> _Database: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + +class _error(Exception): ... + +error = Tuple[Type[_error], Type[OSError]] + +def whichdb(filename: str) -> str: ... +def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi new file mode 100644 index 000000000000..0b8ee50a79b7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi @@ -0,0 +1,25 @@ +from types import TracebackType +from typing import Iterator, MutableMapping, Optional, Type, Union + +_KeyType = Union[str, bytes] +_ValueType = Union[str, bytes] + +error = OSError + +class _Database(MutableMapping[_KeyType, bytes]): + def __init__(self, filebasename: str, mode: str, flag: str = ...) -> None: ... + def sync(self) -> None: ... + def iterkeys(self) -> Iterator[bytes]: ... # undocumented + def close(self) -> None: ... + def __getitem__(self, key: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def __del__(self) -> None: ... + def __enter__(self) -> _Database: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + +def open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi new file mode 100644 index 000000000000..8f13a2988488 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi @@ -0,0 +1,35 @@ +from types import TracebackType +from typing import List, Optional, Type, TypeVar, Union, overload + +_T = TypeVar("_T") +_KeyType = Union[str, bytes] +_ValueType = Union[str, bytes] + +class error(OSError): ... + +# Actual typename gdbm, not exposed by the implementation +class _gdbm: + def firstkey(self) -> Optional[bytes]: ... + def nextkey(self, key: _KeyType) -> Optional[bytes]: ... + def reorganize(self) -> None: ... + def sync(self) -> None: ... + def close(self) -> None: ... + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __len__(self) -> int: ... + def __enter__(self) -> _gdbm: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + @overload + def get(self, k: _KeyType) -> Optional[bytes]: ... + @overload + def get(self, k: _KeyType, default: Union[bytes, _T]) -> Union[bytes, _T]: ... + def keys(self) -> List[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + +def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi new file mode 100644 index 000000000000..020131543e13 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi @@ -0,0 +1,34 @@ +from types import TracebackType +from typing import List, Optional, Type, TypeVar, Union, overload + +_T = TypeVar("_T") +_KeyType = Union[str, bytes] +_ValueType = Union[str, bytes] + +class error(OSError): ... + +library: str = ... + +# Actual typename dbm, not exposed by the implementation +class _dbm: + def close(self) -> None: ... + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __len__(self) -> int: ... + def __del__(self) -> None: ... + def __enter__(self) -> _dbm: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + @overload + def get(self, k: _KeyType) -> Optional[bytes]: ... + @overload + def get(self, k: _KeyType, default: Union[bytes, _T]) -> Union[bytes, _T]: ... + def keys(self) -> List[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore + __init__: None # type: ignore + +def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/@python2/decimal.pyi b/mypy/typeshed/stdlib/@python2/decimal.pyi new file mode 100644 index 000000000000..bee33d9c7af0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/decimal.pyi @@ -0,0 +1,246 @@ +from types import TracebackType +from typing import Any, Container, Dict, List, NamedTuple, Optional, Sequence, Text, Tuple, Type, TypeVar, Union + +_Decimal = Union[Decimal, int] +_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] +_ComparableNum = Union[Decimal, float] +_DecimalT = TypeVar("_DecimalT", bound=Decimal) + +class DecimalTuple(NamedTuple): + sign: int + digits: Tuple[int, ...] + exponent: int + +ROUND_DOWN: str +ROUND_HALF_UP: str +ROUND_HALF_EVEN: str +ROUND_CEILING: str +ROUND_FLOOR: str +ROUND_UP: str +ROUND_HALF_DOWN: str +ROUND_05UP: str + +class DecimalException(ArithmeticError): + def handle(self, context: Context, *args: Any) -> Optional[Decimal]: ... + +class Clamped(DecimalException): ... +class InvalidOperation(DecimalException): ... +class ConversionSyntax(InvalidOperation): ... +class DivisionByZero(DecimalException, ZeroDivisionError): ... +class DivisionImpossible(InvalidOperation): ... +class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... +class Inexact(DecimalException): ... +class InvalidContext(InvalidOperation): ... +class Rounded(DecimalException): ... +class Subnormal(DecimalException): ... +class Overflow(Inexact, Rounded): ... +class Underflow(Inexact, Rounded, Subnormal): ... + +def setcontext(__context: Context) -> None: ... +def getcontext() -> Context: ... +def localcontext(ctx: Optional[Context] = ...) -> _ContextManager: ... + +class Decimal(object): + def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Optional[Context] = ...) -> _DecimalT: ... + @classmethod + def from_float(cls, __f: float) -> Decimal: ... + def __nonzero__(self) -> bool: ... + def __div__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rdiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __ne__(self, other: object, context: Optional[Context] = ...) -> bool: ... + def compare(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __hash__(self) -> int: ... + def as_tuple(self) -> DecimalTuple: ... + def to_eng_string(self, context: Optional[Context] = ...) -> str: ... + def __abs__(self, round: bool = ..., context: Optional[Context] = ...) -> Decimal: ... + def __add__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __divmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... + def __eq__(self, other: object, context: Optional[Context] = ...) -> bool: ... + def __floordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __ge__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __gt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __le__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __lt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __mod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __mul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __neg__(self, context: Optional[Context] = ...) -> Decimal: ... + def __pos__(self, context: Optional[Context] = ...) -> Decimal: ... + def __pow__(self, other: _Decimal, modulo: Optional[_Decimal] = ..., context: Optional[Context] = ...) -> Decimal: ... + def __radd__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rdivmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rmul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rsub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rtruediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __str__(self, eng: bool = ..., context: Optional[Context] = ...) -> str: ... + def __sub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __truediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def remainder_near(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __trunc__(self) -> int: ... + @property + def real(self) -> Decimal: ... + @property + def imag(self) -> Decimal: ... + def conjugate(self) -> Decimal: ... + def __complex__(self) -> complex: ... + def __long__(self) -> long: ... + def fma(self, other: _Decimal, third: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rpow__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def normalize(self, context: Optional[Context] = ...) -> Decimal: ... + def quantize( + self, exp: _Decimal, rounding: Optional[str] = ..., context: Optional[Context] = ..., watchexp: bool = ... + ) -> Decimal: ... + def same_quantum(self, other: _Decimal) -> bool: ... + def to_integral_exact(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def to_integral_value(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def to_integral(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def sqrt(self, context: Optional[Context] = ...) -> Decimal: ... + def max(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def min(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def adjusted(self) -> int: ... + def canonical(self, context: Optional[Context] = ...) -> Decimal: ... + def compare_signal(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def compare_total(self, other: _Decimal) -> Decimal: ... + def compare_total_mag(self, other: _Decimal) -> Decimal: ... + def copy_abs(self) -> Decimal: ... + def copy_negate(self) -> Decimal: ... + def copy_sign(self, other: _Decimal) -> Decimal: ... + def exp(self, context: Optional[Context] = ...) -> Decimal: ... + def is_canonical(self) -> bool: ... + def is_finite(self) -> bool: ... + def is_infinite(self) -> bool: ... + def is_nan(self) -> bool: ... + def is_normal(self, context: Optional[Context] = ...) -> bool: ... + def is_qnan(self) -> bool: ... + def is_signed(self) -> bool: ... + def is_snan(self) -> bool: ... + def is_subnormal(self, context: Optional[Context] = ...) -> bool: ... + def is_zero(self) -> bool: ... + def ln(self, context: Optional[Context] = ...) -> Decimal: ... + def log10(self, context: Optional[Context] = ...) -> Decimal: ... + def logb(self, context: Optional[Context] = ...) -> Decimal: ... + def logical_and(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def logical_invert(self, context: Optional[Context] = ...) -> Decimal: ... + def logical_or(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def logical_xor(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def max_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def min_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def next_minus(self, context: Optional[Context] = ...) -> Decimal: ... + def next_plus(self, context: Optional[Context] = ...) -> Decimal: ... + def next_toward(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def number_class(self, context: Optional[Context] = ...) -> str: ... + def radix(self) -> Decimal: ... + def rotate(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def scaleb(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def shift(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __reduce__(self) -> Tuple[Type[Decimal], Tuple[str]]: ... + def __copy__(self) -> Decimal: ... + def __deepcopy__(self, memo: Any) -> Decimal: ... + def __format__(self, specifier: str, context: Optional[Context] = ...) -> str: ... + +class _ContextManager(object): + new_context: Context + saved_context: Context + def __init__(self, new_context: Context) -> None: ... + def __enter__(self) -> Context: ... + def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... + +_TrapType = Type[DecimalException] + +class Context(object): + prec: int + rounding: str + Emin: int + Emax: int + capitals: int + _clamp: int + traps: Dict[_TrapType, bool] + flags: Dict[_TrapType, bool] + def __init__( + self, + prec: Optional[int] = ..., + rounding: Optional[str] = ..., + traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + Emin: Optional[int] = ..., + Emax: Optional[int] = ..., + capitals: Optional[int] = ..., + _clamp: Optional[int] = ..., + _ignored_flags: Optional[List[_TrapType]] = ..., + ) -> None: ... + def clear_flags(self) -> None: ... + def copy(self) -> Context: ... + def __copy__(self) -> Context: ... + __hash__: Any = ... + def Etiny(self) -> int: ... + def Etop(self) -> int: ... + def create_decimal(self, __num: _DecimalNew = ...) -> Decimal: ... + def create_decimal_from_float(self, __f: float) -> Decimal: ... + def abs(self, __x: _Decimal) -> Decimal: ... + def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def canonical(self, __x: Decimal) -> Decimal: ... + def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def copy_abs(self, __x: _Decimal) -> Decimal: ... + def copy_decimal(self, __x: _Decimal) -> Decimal: ... + def copy_negate(self, __x: _Decimal) -> Decimal: ... + def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divmod(self, __x: _Decimal, __y: _Decimal) -> Tuple[Decimal, Decimal]: ... + def exp(self, __x: _Decimal) -> Decimal: ... + def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... + def is_canonical(self, __x: _Decimal) -> bool: ... + def is_finite(self, __x: _Decimal) -> bool: ... + def is_infinite(self, __x: _Decimal) -> bool: ... + def is_nan(self, __x: _Decimal) -> bool: ... + def is_normal(self, __x: _Decimal) -> bool: ... + def is_qnan(self, __x: _Decimal) -> bool: ... + def is_signed(self, __x: _Decimal) -> bool: ... + def is_snan(self, __x: _Decimal) -> bool: ... + def is_subnormal(self, __x: _Decimal) -> bool: ... + def is_zero(self, __x: _Decimal) -> bool: ... + def ln(self, __x: _Decimal) -> Decimal: ... + def log10(self, __x: _Decimal) -> Decimal: ... + def logb(self, __x: _Decimal) -> Decimal: ... + def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def logical_invert(self, __x: _Decimal) -> Decimal: ... + def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def minus(self, __x: _Decimal) -> Decimal: ... + def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def next_minus(self, __x: _Decimal) -> Decimal: ... + def next_plus(self, __x: _Decimal) -> Decimal: ... + def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def normalize(self, __x: _Decimal) -> Decimal: ... + def number_class(self, __x: _Decimal) -> str: ... + def plus(self, __x: _Decimal) -> Decimal: ... + def power(self, a: _Decimal, b: _Decimal, modulo: Optional[_Decimal] = ...) -> Decimal: ... + def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def radix(self) -> Decimal: ... + def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... + def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def sqrt(self, __x: _Decimal) -> Decimal: ... + def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def to_eng_string(self, __x: _Decimal) -> str: ... + def to_sci_string(self, __x: _Decimal) -> str: ... + def to_integral_exact(self, __x: _Decimal) -> Decimal: ... + def to_integral_value(self, __x: _Decimal) -> Decimal: ... + def to_integral(self, __x: _Decimal) -> Decimal: ... + +DefaultContext: Context +BasicContext: Context +ExtendedContext: Context diff --git a/mypy/typeshed/stdlib/@python2/difflib.pyi b/mypy/typeshed/stdlib/@python2/difflib.pyi new file mode 100644 index 000000000000..02dbbb64433c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/difflib.pyi @@ -0,0 +1,113 @@ +from typing import ( + Any, + AnyStr, + Callable, + Generic, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Sequence, + Text, + Tuple, + TypeVar, + Union, + overload, +) + +_T = TypeVar("_T") + +# Aliases can't point to type vars, so we need to redeclare AnyStr +_StrType = TypeVar("_StrType", Text, bytes) + +_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] + +class Match(NamedTuple): + a: int + b: int + size: int + +class SequenceMatcher(Generic[_T]): + def __init__( + self, isjunk: Optional[Callable[[_T], bool]] = ..., a: Sequence[_T] = ..., b: Sequence[_T] = ..., autojunk: bool = ... + ) -> None: ... + def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... + def set_seq1(self, a: Sequence[_T]) -> None: ... + def set_seq2(self, b: Sequence[_T]) -> None: ... + def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... + def get_matching_blocks(self) -> List[Match]: ... + def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ... + def get_grouped_opcodes(self, n: int = ...) -> Iterable[List[Tuple[str, int, int, int, int]]]: ... + def ratio(self) -> float: ... + def quick_ratio(self) -> float: ... + def real_quick_ratio(self) -> float: ... + +# mypy thinks the signatures of the overloads overlap, but the types still work fine +@overload +def get_close_matches( # type: ignore + word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... +) -> List[AnyStr]: ... +@overload +def get_close_matches( + word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... +) -> List[Sequence[_T]]: ... + +class Differ: + def __init__(self, linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ...) -> None: ... + def compare(self, a: Sequence[_StrType], b: Sequence[_StrType]) -> Iterator[_StrType]: ... + +def IS_LINE_JUNK(line: _StrType, pat: Any = ...) -> bool: ... # pat is undocumented +def IS_CHARACTER_JUNK(ch: _StrType, ws: _StrType = ...) -> bool: ... # ws is undocumented +def unified_diff( + a: Sequence[_StrType], + b: Sequence[_StrType], + fromfile: _StrType = ..., + tofile: _StrType = ..., + fromfiledate: _StrType = ..., + tofiledate: _StrType = ..., + n: int = ..., + lineterm: _StrType = ..., +) -> Iterator[_StrType]: ... +def context_diff( + a: Sequence[_StrType], + b: Sequence[_StrType], + fromfile: _StrType = ..., + tofile: _StrType = ..., + fromfiledate: _StrType = ..., + tofiledate: _StrType = ..., + n: int = ..., + lineterm: _StrType = ..., +) -> Iterator[_StrType]: ... +def ndiff( + a: Sequence[_StrType], b: Sequence[_StrType], linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ... +) -> Iterator[_StrType]: ... + +class HtmlDiff(object): + def __init__( + self, + tabsize: int = ..., + wrapcolumn: Optional[int] = ..., + linejunk: Optional[_JunkCallback] = ..., + charjunk: Optional[_JunkCallback] = ..., + ) -> None: ... + def make_file( + self, + fromlines: Sequence[_StrType], + tolines: Sequence[_StrType], + fromdesc: _StrType = ..., + todesc: _StrType = ..., + context: bool = ..., + numlines: int = ..., + ) -> _StrType: ... + def make_table( + self, + fromlines: Sequence[_StrType], + tolines: Sequence[_StrType], + fromdesc: _StrType = ..., + todesc: _StrType = ..., + context: bool = ..., + numlines: int = ..., + ) -> _StrType: ... + +def restore(delta: Iterable[_StrType], which: int) -> Iterator[_StrType]: ... diff --git a/mypy/typeshed/stdlib/@python2/dis.pyi b/mypy/typeshed/stdlib/@python2/dis.pyi new file mode 100644 index 000000000000..1d6537667a60 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dis.pyi @@ -0,0 +1,30 @@ +import types +from opcode import ( + EXTENDED_ARG as EXTENDED_ARG, + HAVE_ARGUMENT as HAVE_ARGUMENT, + cmp_op as cmp_op, + hascompare as hascompare, + hasconst as hasconst, + hasfree as hasfree, + hasjabs as hasjabs, + hasjrel as hasjrel, + haslocal as haslocal, + hasname as hasname, + opmap as opmap, + opname as opname, +) +from typing import Any, Callable, Dict, Iterator, List, Tuple, Union + +# Strictly this should not have to include Callable, but mypy doesn't use FunctionType +# for functions (python/mypy#3171) +_have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] +_have_code_or_string = Union[_have_code, str, bytes] + +COMPILER_FLAG_NAMES: Dict[int, str] + +def findlabels(code: _have_code) -> List[int]: ... +def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... +def dis(x: _have_code_or_string = ...) -> None: ... +def distb(tb: types.TracebackType = ...) -> None: ... +def disassemble(co: _have_code, lasti: int = ...) -> None: ... +def disco(co: _have_code, lasti: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/doctest.pyi b/mypy/typeshed/stdlib/@python2/doctest.pyi new file mode 100644 index 000000000000..b9e0ab392374 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/doctest.pyi @@ -0,0 +1,216 @@ +import types +import unittest +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union + +class TestResults(NamedTuple): + failed: int + attempted: int + +OPTIONFLAGS_BY_NAME: Dict[str, int] + +def register_optionflag(name: str) -> int: ... + +DONT_ACCEPT_TRUE_FOR_1: int +DONT_ACCEPT_BLANKLINE: int +NORMALIZE_WHITESPACE: int +ELLIPSIS: int +SKIP: int +IGNORE_EXCEPTION_DETAIL: int + +COMPARISON_FLAGS: int + +REPORT_UDIFF: int +REPORT_CDIFF: int +REPORT_NDIFF: int +REPORT_ONLY_FIRST_FAILURE: int +REPORTING_FLAGS: int + +BLANKLINE_MARKER: str +ELLIPSIS_MARKER: str + +class Example: + source: str + want: str + exc_msg: Optional[str] + lineno: int + indent: int + options: Dict[int, bool] + def __init__( + self, + source: str, + want: str, + exc_msg: Optional[str] = ..., + lineno: int = ..., + indent: int = ..., + options: Optional[Dict[int, bool]] = ..., + ) -> None: ... + def __hash__(self) -> int: ... + +class DocTest: + examples: List[Example] + globs: Dict[str, Any] + name: str + filename: Optional[str] + lineno: Optional[int] + docstring: Optional[str] + def __init__( + self, + examples: List[Example], + globs: Dict[str, Any], + name: str, + filename: Optional[str], + lineno: Optional[int], + docstring: Optional[str], + ) -> None: ... + def __hash__(self) -> int: ... + def __lt__(self, other: DocTest) -> bool: ... + +class DocTestParser: + def parse(self, string: str, name: str = ...) -> List[Union[str, Example]]: ... + def get_doctest( + self, string: str, globs: Dict[str, Any], name: str, filename: Optional[str], lineno: Optional[int] + ) -> DocTest: ... + def get_examples(self, string: str, name: str = ...) -> List[Example]: ... + +class DocTestFinder: + def __init__( + self, verbose: bool = ..., parser: DocTestParser = ..., recurse: bool = ..., exclude_empty: bool = ... + ) -> None: ... + def find( + self, + obj: object, + name: Optional[str] = ..., + module: Union[None, bool, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., + extraglobs: Optional[Dict[str, Any]] = ..., + ) -> List[DocTest]: ... + +_Out = Callable[[str], Any] +_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] + +class DocTestRunner: + DIVIDER: str + optionflags: int + original_optionflags: int + tries: int + failures: int + test: DocTest + def __init__(self, checker: Optional[OutputChecker] = ..., verbose: Optional[bool] = ..., optionflags: int = ...) -> None: ... + def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... + def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + def run( + self, test: DocTest, compileflags: Optional[int] = ..., out: Optional[_Out] = ..., clear_globs: bool = ... + ) -> TestResults: ... + def summarize(self, verbose: Optional[bool] = ...) -> TestResults: ... + def merge(self, other: DocTestRunner) -> None: ... + +class OutputChecker: + def check_output(self, want: str, got: str, optionflags: int) -> bool: ... + def output_difference(self, example: Example, got: str, optionflags: int) -> str: ... + +class DocTestFailure(Exception): + test: DocTest + example: Example + got: str + def __init__(self, test: DocTest, example: Example, got: str) -> None: ... + +class UnexpectedException(Exception): + test: DocTest + example: Example + exc_info: _ExcInfo + def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + +class DebugRunner(DocTestRunner): ... + +master: Optional[DocTestRunner] + +def testmod( + m: Optional[types.ModuleType] = ..., + name: Optional[str] = ..., + globs: Optional[Dict[str, Any]] = ..., + verbose: Optional[bool] = ..., + report: bool = ..., + optionflags: int = ..., + extraglobs: Optional[Dict[str, Any]] = ..., + raise_on_error: bool = ..., + exclude_empty: bool = ..., +) -> TestResults: ... +def testfile( + filename: str, + module_relative: bool = ..., + name: Optional[str] = ..., + package: Union[None, str, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., + verbose: Optional[bool] = ..., + report: bool = ..., + optionflags: int = ..., + extraglobs: Optional[Dict[str, Any]] = ..., + raise_on_error: bool = ..., + parser: DocTestParser = ..., + encoding: Optional[str] = ..., +) -> TestResults: ... +def run_docstring_examples( + f: object, + globs: Dict[str, Any], + verbose: bool = ..., + name: str = ..., + compileflags: Optional[int] = ..., + optionflags: int = ..., +) -> None: ... +def set_unittest_reportflags(flags: int) -> int: ... + +class DocTestCase(unittest.TestCase): + def __init__( + self, + test: DocTest, + optionflags: int = ..., + setUp: Optional[Callable[[DocTest], Any]] = ..., + tearDown: Optional[Callable[[DocTest], Any]] = ..., + checker: Optional[OutputChecker] = ..., + ) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + def runTest(self) -> None: ... + def format_failure(self, err: str) -> str: ... + def debug(self) -> None: ... + def id(self) -> str: ... + def __hash__(self) -> int: ... + def shortDescription(self) -> str: ... + +class SkipDocTestCase(DocTestCase): + def __init__(self, module: types.ModuleType) -> None: ... + def setUp(self) -> None: ... + def test_skip(self) -> None: ... + def shortDescription(self) -> str: ... + +_DocTestSuite = unittest.TestSuite + +def DocTestSuite( + module: Union[None, str, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., + extraglobs: Optional[Dict[str, Any]] = ..., + test_finder: Optional[DocTestFinder] = ..., + **options: Any, +) -> _DocTestSuite: ... + +class DocFileCase(DocTestCase): + def id(self) -> str: ... + def format_failure(self, err: str) -> str: ... + +def DocFileTest( + path: str, + module_relative: bool = ..., + package: Union[None, str, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., + parser: DocTestParser = ..., + encoding: Optional[str] = ..., + **options: Any, +) -> DocFileCase: ... +def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... +def script_from_examples(s: str) -> str: ... +def testsource(module: Union[None, str, types.ModuleType], name: str) -> str: ... +def debug_src(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ... +def debug_script(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ... +def debug(module: Union[None, str, types.ModuleType], name: str, pm: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dummy_threading.pyi b/mypy/typeshed/stdlib/@python2/dummy_threading.pyi new file mode 100644 index 000000000000..757cb8d4bd4c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dummy_threading.pyi @@ -0,0 +1,2 @@ +from _dummy_threading import * +from _dummy_threading import __all__ as __all__ diff --git a/mypy/typeshed/stdlib/@python2/email/__init__.pyi b/mypy/typeshed/stdlib/@python2/email/__init__.pyi index 384d9567f7b0..83d9895cab4d 100644 --- a/mypy/typeshed/stdlib/@python2/email/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/email/__init__.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, AnyStr +from typing import IO, AnyStr def message_from_string(s: AnyStr, *args, **kwargs): ... def message_from_bytes(s: str, *args, **kwargs): ... diff --git a/mypy/typeshed/stdlib/@python2/ensurepip/__init__.pyi b/mypy/typeshed/stdlib/@python2/ensurepip/__init__.pyi new file mode 100644 index 000000000000..8a22ef546436 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ensurepip/__init__.pyi @@ -0,0 +1,11 @@ +from typing import Optional + +def version() -> str: ... +def bootstrap( + root: Optional[str] = ..., + upgrade: bool = ..., + user: bool = ..., + altinstall: bool = ..., + default_pip: bool = ..., + verbosity: int = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/errno.pyi b/mypy/typeshed/stdlib/@python2/errno.pyi new file mode 100644 index 000000000000..b053604fc33a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/errno.pyi @@ -0,0 +1,137 @@ +from typing import Mapping + +errorcode: Mapping[int, str] + +EPERM: int +ENOENT: int +ESRCH: int +EINTR: int +EIO: int +ENXIO: int +E2BIG: int +ENOEXEC: int +EBADF: int +ECHILD: int +EAGAIN: int +ENOMEM: int +EACCES: int +EFAULT: int +ENOTBLK: int +EBUSY: int +EEXIST: int +EXDEV: int +ENODEV: int +ENOTDIR: int +EISDIR: int +EINVAL: int +ENFILE: int +EMFILE: int +ENOTTY: int +ETXTBSY: int +EFBIG: int +ENOSPC: int +ESPIPE: int +EROFS: int +EMLINK: int +EPIPE: int +EDOM: int +ERANGE: int +EDEADLCK: int +ENAMETOOLONG: int +ENOLCK: int +ENOSYS: int +ENOTEMPTY: int +ELOOP: int +EWOULDBLOCK: int +ENOMSG: int +EIDRM: int +ECHRNG: int +EL2NSYNC: int +EL3HLT: int +EL3RST: int +ELNRNG: int +EUNATCH: int +ENOCSI: int +EL2HLT: int +EBADE: int +EBADR: int +EXFULL: int +ENOANO: int +EBADRQC: int +EBADSLT: int +EDEADLOCK: int +EBFONT: int +ENOSTR: int +ENODATA: int +ETIME: int +ENOSR: int +ENONET: int +ENOPKG: int +EREMOTE: int +ENOLINK: int +EADV: int +ESRMNT: int +ECOMM: int +EPROTO: int +EMULTIHOP: int +EDOTDOT: int +EBADMSG: int +EOVERFLOW: int +ENOTUNIQ: int +EBADFD: int +EREMCHG: int +ELIBACC: int +ELIBBAD: int +ELIBSCN: int +ELIBMAX: int +ELIBEXEC: int +EILSEQ: int +ERESTART: int +ESTRPIPE: int +EUSERS: int +ENOTSOCK: int +EDESTADDRREQ: int +EMSGSIZE: int +EPROTOTYPE: int +ENOPROTOOPT: int +EPROTONOSUPPORT: int +ESOCKTNOSUPPORT: int +ENOTSUP: int +EOPNOTSUPP: int +EPFNOSUPPORT: int +EAFNOSUPPORT: int +EADDRINUSE: int +EADDRNOTAVAIL: int +ENETDOWN: int +ENETUNREACH: int +ENETRESET: int +ECONNABORTED: int +ECONNRESET: int +ENOBUFS: int +EISCONN: int +ENOTCONN: int +ESHUTDOWN: int +ETOOMANYREFS: int +ETIMEDOUT: int +ECONNREFUSED: int +EHOSTDOWN: int +EHOSTUNREACH: int +EALREADY: int +EINPROGRESS: int +ESTALE: int +EUCLEAN: int +ENOTNAM: int +ENAVAIL: int +EISNAM: int +EREMOTEIO: int +EDQUOT: int +ECANCELED: int # undocumented +EKEYEXPIRED: int # undocumented +EKEYREJECTED: int # undocumented +EKEYREVOKED: int # undocumented +EMEDIUMTYPE: int # undocumented +ENOKEY: int # undocumented +ENOMEDIUM: int # undocumented +ENOTRECOVERABLE: int # undocumented +EOWNERDEAD: int # undocumented +ERFKILL: int # undocumented diff --git a/mypy/typeshed/stdlib/@python2/filecmp.pyi b/mypy/typeshed/stdlib/@python2/filecmp.pyi new file mode 100644 index 000000000000..73fe39580c55 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/filecmp.pyi @@ -0,0 +1,40 @@ +from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Text, Tuple, Union + +DEFAULT_IGNORES: List[str] + +def cmp(f1: Union[bytes, Text], f2: Union[bytes, Text], shallow: Union[int, bool] = ...) -> bool: ... +def cmpfiles( + a: AnyStr, b: AnyStr, common: Iterable[AnyStr], shallow: Union[int, bool] = ... +) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... + +class dircmp(Generic[AnyStr]): + def __init__( + self, a: AnyStr, b: AnyStr, ignore: Optional[Sequence[AnyStr]] = ..., hide: Optional[Sequence[AnyStr]] = ... + ) -> None: ... + left: AnyStr + right: AnyStr + hide: Sequence[AnyStr] + ignore: Sequence[AnyStr] + # These properties are created at runtime by __getattr__ + subdirs: Dict[AnyStr, dircmp[AnyStr]] + same_files: List[AnyStr] + diff_files: List[AnyStr] + funny_files: List[AnyStr] + common_dirs: List[AnyStr] + common_files: List[AnyStr] + common_funny: List[AnyStr] + common: List[AnyStr] + left_only: List[AnyStr] + right_only: List[AnyStr] + left_list: List[AnyStr] + right_list: List[AnyStr] + def report(self) -> None: ... + def report_partial_closure(self) -> None: ... + def report_full_closure(self) -> None: ... + methodmap: Dict[str, Callable[[], None]] + def phase0(self) -> None: ... + def phase1(self) -> None: ... + def phase2(self) -> None: ... + def phase3(self) -> None: ... + def phase4(self) -> None: ... + def phase4_closure(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/fileinput.pyi b/mypy/typeshed/stdlib/@python2/fileinput.pyi new file mode 100644 index 000000000000..1e1f8dace600 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/fileinput.pyi @@ -0,0 +1,45 @@ +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Text, Union + +def input( + files: Union[Text, Iterable[Text], None] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[Text, str], IO[AnyStr]] = ..., +) -> FileInput[AnyStr]: ... +def close() -> None: ... +def nextfile() -> None: ... +def filename() -> str: ... +def lineno() -> int: ... +def filelineno() -> int: ... +def fileno() -> int: ... +def isfirstline() -> bool: ... +def isstdin() -> bool: ... + +class FileInput(Iterable[AnyStr], Generic[AnyStr]): + def __init__( + self, + files: Union[None, Text, Iterable[Text]] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[Text, str], IO[AnyStr]] = ..., + ) -> None: ... + def __del__(self) -> None: ... + def close(self) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __next__(self) -> AnyStr: ... + def __getitem__(self, i: int) -> AnyStr: ... + def nextfile(self) -> None: ... + def readline(self) -> AnyStr: ... + def filename(self) -> str: ... + def lineno(self) -> int: ... + def filelineno(self) -> int: ... + def fileno(self) -> int: ... + def isfirstline(self) -> bool: ... + def isstdin(self) -> bool: ... + +def hook_compressed(filename: Text, mode: str) -> IO[Any]: ... +def hook_encoded(encoding: str) -> Callable[[Text, str], IO[Any]]: ... diff --git a/mypy/typeshed/stdlib/@python2/formatter.pyi b/mypy/typeshed/stdlib/@python2/formatter.pyi new file mode 100644 index 000000000000..31c45592a215 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/formatter.pyi @@ -0,0 +1,103 @@ +from typing import IO, Any, Iterable, List, Optional, Tuple + +AS_IS: None +_FontType = Tuple[str, bool, bool, bool] +_StylesType = Tuple[Any, ...] + +class NullFormatter: + writer: Optional[NullWriter] + def __init__(self, writer: Optional[NullWriter] = ...) -> None: ... + def end_paragraph(self, blankline: int) -> None: ... + def add_line_break(self) -> None: ... + def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... + def add_label_data(self, format: str, counter: int, blankline: Optional[int] = ...) -> None: ... + def add_flowing_data(self, data: str) -> None: ... + def add_literal_data(self, data: str) -> None: ... + def flush_softspace(self) -> None: ... + def push_alignment(self, align: Optional[str]) -> None: ... + def pop_alignment(self) -> None: ... + def push_font(self, x: _FontType) -> None: ... + def pop_font(self) -> None: ... + def push_margin(self, margin: int) -> None: ... + def pop_margin(self) -> None: ... + def set_spacing(self, spacing: Optional[str]) -> None: ... + def push_style(self, *styles: _StylesType) -> None: ... + def pop_style(self, n: int = ...) -> None: ... + def assert_line_data(self, flag: int = ...) -> None: ... + +class AbstractFormatter: + writer: NullWriter + align: Optional[str] + align_stack: List[Optional[str]] + font_stack: List[_FontType] + margin_stack: List[int] + spacing: Optional[str] + style_stack: Any + nospace: int + softspace: int + para_end: int + parskip: int + hard_break: int + have_label: int + def __init__(self, writer: NullWriter) -> None: ... + def end_paragraph(self, blankline: int) -> None: ... + def add_line_break(self) -> None: ... + def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... + def add_label_data(self, format: str, counter: int, blankline: Optional[int] = ...) -> None: ... + def format_counter(self, format: Iterable[str], counter: int) -> str: ... + def format_letter(self, case: str, counter: int) -> str: ... + def format_roman(self, case: str, counter: int) -> str: ... + def add_flowing_data(self, data: str) -> None: ... + def add_literal_data(self, data: str) -> None: ... + def flush_softspace(self) -> None: ... + def push_alignment(self, align: Optional[str]) -> None: ... + def pop_alignment(self) -> None: ... + def push_font(self, font: _FontType) -> None: ... + def pop_font(self) -> None: ... + def push_margin(self, margin: int) -> None: ... + def pop_margin(self) -> None: ... + def set_spacing(self, spacing: Optional[str]) -> None: ... + def push_style(self, *styles: _StylesType) -> None: ... + def pop_style(self, n: int = ...) -> None: ... + def assert_line_data(self, flag: int = ...) -> None: ... + +class NullWriter: + def __init__(self) -> None: ... + def flush(self) -> None: ... + def new_alignment(self, align: Optional[str]) -> None: ... + def new_font(self, font: _FontType) -> None: ... + def new_margin(self, margin: int, level: int) -> None: ... + def new_spacing(self, spacing: Optional[str]) -> None: ... + def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... + def send_label_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + def send_literal_data(self, data: str) -> None: ... + +class AbstractWriter(NullWriter): + def new_alignment(self, align: Optional[str]) -> None: ... + def new_font(self, font: _FontType) -> None: ... + def new_margin(self, margin: int, level: int) -> None: ... + def new_spacing(self, spacing: Optional[str]) -> None: ... + def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... + def send_label_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + def send_literal_data(self, data: str) -> None: ... + +class DumbWriter(NullWriter): + file: IO[str] + maxcol: int + def __init__(self, file: Optional[IO[str]] = ..., maxcol: int = ...) -> None: ... + def reset(self) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... + def send_literal_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + +def test(file: Optional[str] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/fractions.pyi b/mypy/typeshed/stdlib/@python2/fractions.pyi new file mode 100644 index 000000000000..bb60014b398e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/fractions.pyi @@ -0,0 +1,149 @@ +from decimal import Decimal +from numbers import Integral, Rational, Real +from typing import Optional, Tuple, Type, TypeVar, Union, overload +from typing_extensions import Literal + +_ComparableNum = Union[int, float, Decimal, Real] +_T = TypeVar("_T") + +@overload +def gcd(a: int, b: int) -> int: ... +@overload +def gcd(a: Integral, b: int) -> Integral: ... +@overload +def gcd(a: int, b: Integral) -> Integral: ... +@overload +def gcd(a: Integral, b: Integral) -> Integral: ... + +class Fraction(Rational): + @overload + def __new__( + cls: Type[_T], + numerator: Union[int, Rational] = ..., + denominator: Optional[Union[int, Rational]] = ..., + *, + _normalize: bool = ..., + ) -> _T: ... + @overload + def __new__(cls: Type[_T], __value: Union[float, Decimal, str], *, _normalize: bool = ...) -> _T: ... + @classmethod + def from_float(cls, f: float) -> Fraction: ... + @classmethod + def from_decimal(cls, dec: Decimal) -> Fraction: ... + def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + @overload + def __add__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __add__(self, other: float) -> float: ... + @overload + def __add__(self, other: complex) -> complex: ... + @overload + def __radd__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __radd__(self, other: float) -> float: ... + @overload + def __radd__(self, other: complex) -> complex: ... + @overload + def __sub__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __sub__(self, other: float) -> float: ... + @overload + def __sub__(self, other: complex) -> complex: ... + @overload + def __rsub__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __rsub__(self, other: float) -> float: ... + @overload + def __rsub__(self, other: complex) -> complex: ... + @overload + def __mul__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __mul__(self, other: float) -> float: ... + @overload + def __mul__(self, other: complex) -> complex: ... + @overload + def __rmul__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __rmul__(self, other: float) -> float: ... + @overload + def __rmul__(self, other: complex) -> complex: ... + @overload + def __truediv__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __truediv__(self, other: float) -> float: ... + @overload + def __truediv__(self, other: complex) -> complex: ... + @overload + def __rtruediv__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __rtruediv__(self, other: float) -> float: ... + @overload + def __rtruediv__(self, other: complex) -> complex: ... + @overload + def __div__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __div__(self, other: float) -> float: ... + @overload + def __div__(self, other: complex) -> complex: ... + @overload + def __rdiv__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __rdiv__(self, other: float) -> float: ... + @overload + def __rdiv__(self, other: complex) -> complex: ... + @overload + def __floordiv__(self, other: Union[int, Fraction]) -> int: ... + @overload + def __floordiv__(self, other: float) -> float: ... + @overload + def __rfloordiv__(self, other: Union[int, Fraction]) -> int: ... + @overload + def __rfloordiv__(self, other: float) -> float: ... + @overload + def __mod__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __mod__(self, other: float) -> float: ... + @overload + def __rmod__(self, other: Union[int, Fraction]) -> Fraction: ... + @overload + def __rmod__(self, other: float) -> float: ... + @overload + def __divmod__(self, other: Union[int, Fraction]) -> Tuple[int, Fraction]: ... + @overload + def __divmod__(self, other: float) -> Tuple[float, Fraction]: ... + @overload + def __rdivmod__(self, other: Union[int, Fraction]) -> Tuple[int, Fraction]: ... + @overload + def __rdivmod__(self, other: float) -> Tuple[float, Fraction]: ... + @overload + def __pow__(self, other: int) -> Fraction: ... + @overload + def __pow__(self, other: Union[float, Fraction]) -> float: ... + @overload + def __pow__(self, other: complex) -> complex: ... + @overload + def __rpow__(self, other: Union[int, float, Fraction]) -> float: ... + @overload + def __rpow__(self, other: complex) -> complex: ... + def __pos__(self) -> Fraction: ... + def __neg__(self) -> Fraction: ... + def __abs__(self) -> Fraction: ... + def __trunc__(self) -> int: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: _ComparableNum) -> bool: ... + def __gt__(self, other: _ComparableNum) -> bool: ... + def __le__(self, other: _ComparableNum) -> bool: ... + def __ge__(self, other: _ComparableNum) -> bool: ... + def __nonzero__(self) -> bool: ... + # Not actually defined within fractions.py, but provides more useful + # overrides + @property + def real(self) -> Fraction: ... + @property + def imag(self) -> Literal[0]: ... + def conjugate(self) -> Fraction: ... diff --git a/mypy/typeshed/stdlib/@python2/ftplib.pyi b/mypy/typeshed/stdlib/@python2/ftplib.pyi new file mode 100644 index 000000000000..bdb975fbc21e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ftplib.pyi @@ -0,0 +1,128 @@ +from _typeshed import SupportsRead, SupportsReadline +from socket import socket +from ssl import SSLContext +from typing import Any, BinaryIO, Callable, List, Optional, Text, Tuple, Type, TypeVar, Union +from typing_extensions import Literal + +_T = TypeVar("_T") +_IntOrStr = Union[int, Text] + +MSG_OOB: int +FTP_PORT: int +MAXLINE: int +CRLF: str + +class Error(Exception): ... +class error_reply(Error): ... +class error_temp(Error): ... +class error_perm(Error): ... +class error_proto(Error): ... + +all_errors: Tuple[Type[Exception], ...] + +class FTP: + debugging: int + + # Note: This is technically the type that's passed in as the host argument. But to make it easier in Python 2 we + # accept Text but return str. + host: str + + port: int + maxline: int + sock: Optional[socket] + welcome: Optional[str] + passiveserver: int + timeout: int + af: int + lastresp: str + + file: Optional[BinaryIO] + def __init__( + self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., timeout: float = ... + ) -> None: ... + def connect(self, host: Text = ..., port: int = ..., timeout: float = ...) -> str: ... + def getwelcome(self) -> str: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def set_pasv(self, val: Union[bool, int]) -> None: ... + def sanitize(self, s: Text) -> str: ... + def putline(self, line: Text) -> None: ... + def putcmd(self, line: Text) -> None: ... + def getline(self) -> str: ... + def getmultiline(self) -> str: ... + def getresp(self) -> str: ... + def voidresp(self) -> str: ... + def abort(self) -> str: ... + def sendcmd(self, cmd: Text) -> str: ... + def voidcmd(self, cmd: Text) -> str: ... + def sendport(self, host: Text, port: int) -> str: ... + def sendeprt(self, host: Text, port: int) -> str: ... + def makeport(self) -> socket: ... + def makepasv(self) -> Tuple[str, int]: ... + def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ...) -> str: ... + # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. + def ntransfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> Tuple[socket, int]: ... + def transfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> socket: ... + def retrbinary( + self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: Optional[_IntOrStr] = ... + ) -> str: ... + def storbinary( + self, + cmd: Text, + fp: SupportsRead[bytes], + blocksize: int = ..., + callback: Optional[Callable[[bytes], Any]] = ..., + rest: Optional[_IntOrStr] = ..., + ) -> str: ... + def retrlines(self, cmd: Text, callback: Optional[Callable[[str], Any]] = ...) -> str: ... + def storlines(self, cmd: Text, fp: SupportsReadline[bytes], callback: Optional[Callable[[bytes], Any]] = ...) -> str: ... + def acct(self, password: Text) -> str: ... + def nlst(self, *args: Text) -> List[str]: ... + # Technically only the last arg can be a Callable but ... + def dir(self, *args: Union[str, Callable[[str], None]]) -> None: ... + def rename(self, fromname: Text, toname: Text) -> str: ... + def delete(self, filename: Text) -> str: ... + def cwd(self, dirname: Text) -> str: ... + def size(self, filename: Text) -> Optional[int]: ... + def mkd(self, dirname: Text) -> str: ... + def rmd(self, dirname: Text) -> str: ... + def pwd(self) -> str: ... + def quit(self) -> str: ... + def close(self) -> None: ... + +class FTP_TLS(FTP): + def __init__( + self, + host: Text = ..., + user: Text = ..., + passwd: Text = ..., + acct: Text = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + context: Optional[SSLContext] = ..., + timeout: float = ..., + source_address: Optional[Tuple[str, int]] = ..., + ) -> None: ... + ssl_version: int + keyfile: Optional[str] + certfile: Optional[str] + context: SSLContext + def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ..., secure: bool = ...) -> str: ... + def auth(self) -> str: ... + def prot_p(self) -> str: ... + def prot_c(self) -> str: ... + +class Netrc: + def __init__(self, filename: Optional[Text] = ...) -> None: ... + def get_hosts(self) -> List[str]: ... + def get_account(self, host: Text) -> Tuple[Optional[str], Optional[str], Optional[str]]: ... + def get_macros(self) -> List[str]: ... + def get_macro(self, macro: Text) -> Tuple[str, ...]: ... + +def parse150(resp: str) -> Optional[int]: ... # undocumented +def parse227(resp: str) -> Tuple[str, int]: ... # undocumented +def parse229(resp: str, peer: Any) -> Tuple[str, int]: ... # undocumented +def parse257(resp: str) -> str: ... # undocumented +def ftpcp( + source: FTP, sourcename: str, target: FTP, targetname: str = ..., type: Literal["A", "I"] = ... +) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/functools.pyi b/mypy/typeshed/stdlib/@python2/functools.pyi index 8b82177b6f6b..dd873708fea4 100644 --- a/mypy/typeshed/stdlib/@python2/functools.pyi +++ b/mypy/typeshed/stdlib/@python2/functools.pyi @@ -1,5 +1,4 @@ -from abc import ABCMeta, abstractmethod -from typing import Any, Callable, Dict, Generic, Iterable, Optional, Sequence, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Dict, Generic, Iterable, Sequence, Tuple, Type, TypeVar, overload _AnyCallable = Callable[..., Any] diff --git a/mypy/typeshed/stdlib/@python2/genericpath.pyi b/mypy/typeshed/stdlib/@python2/genericpath.pyi new file mode 100644 index 000000000000..f1d3538cd1a4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/genericpath.pyi @@ -0,0 +1,25 @@ +from _typeshed import SupportsLessThanT +from typing import List, Sequence, Text, Tuple, Union, overload +from typing_extensions import Literal + +# All overloads can return empty string. Ideally, Literal[""] would be a valid +# Iterable[T], so that Union[List[T], Literal[""]] could be used as a return +# type. But because this only works when T is str, we need Sequence[T] instead. +@overload +def commonprefix(m: Sequence[str]) -> Union[str, Literal[""]]: ... # type: ignore +@overload +def commonprefix(m: Sequence[Text]) -> Text: ... # type: ignore +@overload +def commonprefix(m: Sequence[List[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... +@overload +def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... +def exists(path: Text) -> bool: ... +def getsize(filename: Text) -> int: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(filename: Text) -> float: ... +def getmtime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/grp.pyi b/mypy/typeshed/stdlib/@python2/grp.pyi new file mode 100644 index 000000000000..8447f21736bb --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/grp.pyi @@ -0,0 +1,11 @@ +from typing import List, NamedTuple, Optional + +class struct_group(NamedTuple): + gr_name: str + gr_passwd: Optional[str] + gr_gid: int + gr_mem: List[str] + +def getgrall() -> List[struct_group]: ... +def getgrgid(id: int) -> struct_group: ... +def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/typeshed/stdlib/@python2/heapq.pyi b/mypy/typeshed/stdlib/@python2/heapq.pyi index d6da32d767d3..8bdb3d23b9ba 100644 --- a/mypy/typeshed/stdlib/@python2/heapq.pyi +++ b/mypy/typeshed/stdlib/@python2/heapq.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsLessThan -from typing import Any, Callable, Iterable, List, Optional, Protocol, TypeVar +from typing import Callable, Iterable, List, Optional, TypeVar _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/@python2/hmac.pyi b/mypy/typeshed/stdlib/@python2/hmac.pyi new file mode 100644 index 000000000000..7550163b6707 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/hmac.pyi @@ -0,0 +1,23 @@ +from _typeshed import ReadableBuffer +from types import ModuleType +from typing import Any, AnyStr, Callable, Optional, Union, overload + +# TODO more precise type for object of hashlib +_Hash = Any +_DigestMod = Union[str, Callable[[], _Hash], ModuleType] + +digest_size: None + +def new(key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: Optional[_DigestMod] = ...) -> HMAC: ... + +class HMAC: + def __init__(self, key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: _DigestMod = ...) -> None: ... + def update(self, msg: ReadableBuffer) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def copy(self) -> HMAC: ... + +@overload +def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... +@overload +def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/httplib.pyi b/mypy/typeshed/stdlib/@python2/httplib.pyi index 59dc658f79ef..6901dfc0f695 100644 --- a/mypy/typeshed/stdlib/@python2/httplib.pyi +++ b/mypy/typeshed/stdlib/@python2/httplib.pyi @@ -1,5 +1,4 @@ import mimetools -import ssl from typing import Any, Dict, Optional, Protocol class HTTPMessage(mimetools.Message): diff --git a/mypy/typeshed/stdlib/@python2/imaplib.pyi b/mypy/typeshed/stdlib/@python2/imaplib.pyi new file mode 100644 index 000000000000..73063629295a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/imaplib.pyi @@ -0,0 +1,130 @@ +import subprocess +import time +from socket import socket as _socket +from ssl import SSLSocket +from typing import IO, Any, Callable, Dict, List, Optional, Pattern, Text, Tuple, Type, Union +from typing_extensions import Literal + +# TODO: Commands should use their actual return types, not this type alias. +# E.g. Tuple[Literal["OK"], List[bytes]] +_CommandResults = Tuple[str, List[Any]] + +_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] + +class IMAP4: + error: Type[Exception] = ... + abort: Type[Exception] = ... + readonly: Type[Exception] = ... + mustquote: Pattern[Text] = ... + debug: int = ... + state: str = ... + literal: Optional[Text] = ... + tagged_commands: Dict[bytes, Optional[List[bytes]]] + untagged_responses: Dict[str, List[Union[bytes, Tuple[bytes, bytes]]]] + continuation_response: str = ... + is_readonly: bool = ... + tagnum: int = ... + tagpre: str = ... + tagre: Pattern[Text] = ... + welcome: bytes = ... + capabilities: Tuple[str] = ... + PROTOCOL_VERSION: str = ... + def __init__(self, host: str = ..., port: int = ...) -> None: ... + def open(self, host: str = ..., port: int = ...) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: Union[IO[Text], IO[bytes]] = ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def recent(self) -> _CommandResults: ... + def response(self, code: str) -> _CommandResults: ... + def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... + def authenticate(self, mechanism: str, authobject: Callable[[bytes], Optional[bytes]]) -> Tuple[str, str]: ... + def capability(self) -> _CommandResults: ... + def check(self) -> _CommandResults: ... + def close(self) -> _CommandResults: ... + def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: ... + def create(self, mailbox: str) -> _CommandResults: ... + def delete(self, mailbox: str) -> _CommandResults: ... + def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... + def expunge(self) -> _CommandResults: ... + def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... + def getacl(self, mailbox: str) -> _CommandResults: ... + def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... + def getquota(self, root: str) -> _CommandResults: ... + def getquotaroot(self, mailbox: str) -> _CommandResults: ... + def list(self, directory: str = ..., pattern: str = ...) -> Tuple[str, _AnyResponseData]: ... + def login(self, user: str, password: str) -> Tuple[Literal["OK"], List[bytes]]: ... + def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... + def logout(self) -> Tuple[str, _AnyResponseData]: ... + def lsub(self, directory: str = ..., pattern: str = ...) -> _CommandResults: ... + def myrights(self, mailbox: str) -> _CommandResults: ... + def namespace(self) -> _CommandResults: ... + def noop(self) -> Tuple[str, List[bytes]]: ... + def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ... + def proxyauth(self, user: str) -> _CommandResults: ... + def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... + def search(self, charset: Optional[str], *criteria: str) -> _CommandResults: ... + def select(self, mailbox: str = ..., readonly: bool = ...) -> Tuple[str, List[Optional[bytes]]]: ... + def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... + def setannotation(self, *args: str) -> _CommandResults: ... + def setquota(self, root: str, limits: str) -> _CommandResults: ... + def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... + def status(self, mailbox: str, names: str) -> _CommandResults: ... + def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... + def subscribe(self, mailbox: str) -> _CommandResults: ... + def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... + def uid(self, command: str, *args: str) -> _CommandResults: ... + def unsubscribe(self, mailbox: str) -> _CommandResults: ... + def xatom(self, name: str, *args: str) -> _CommandResults: ... + def print_log(self) -> None: ... + +class IMAP4_SSL(IMAP4): + keyfile: str = ... + certfile: str = ... + def __init__(self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ...) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + sslobj: SSLSocket = ... + file: IO[Any] = ... + def open(self, host: str = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def ssl(self) -> SSLSocket: ... + +class IMAP4_stream(IMAP4): + command: str = ... + def __init__(self, command: str) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: IO[Any] = ... + process: subprocess.Popen[bytes] = ... + writefile: IO[Any] = ... + readfile: IO[Any] = ... + def open(self, host: Optional[str] = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + +class _Authenticator: + mech: Callable[[bytes], bytes] = ... + def __init__(self, mechinst: Callable[[bytes], bytes]) -> None: ... + def process(self, data: str) -> str: ... + def encode(self, inp: bytes) -> str: ... + def decode(self, inp: str) -> bytes: ... + +def Internaldate2tuple(resp: str) -> time.struct_time: ... +def Int2AP(num: int) -> str: ... +def ParseFlags(resp: str) -> Tuple[str]: ... +def Time2Internaldate(date_time: Union[float, time.struct_time, str]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/imghdr.pyi b/mypy/typeshed/stdlib/@python2/imghdr.pyi new file mode 100644 index 000000000000..4a6c3f39eb27 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/imghdr.pyi @@ -0,0 +1,15 @@ +from typing import Any, BinaryIO, Callable, List, Optional, Protocol, Text, Union, overload + +class _ReadableBinary(Protocol): + def tell(self) -> int: ... + def read(self, size: int) -> bytes: ... + def seek(self, offset: int) -> Any: ... + +_File = Union[Text, _ReadableBinary] + +@overload +def what(file: _File, h: None = ...) -> Optional[str]: ... +@overload +def what(file: Any, h: bytes) -> Optional[str]: ... + +tests: List[Callable[[bytes, Optional[BinaryIO]], Optional[str]]] diff --git a/mypy/typeshed/stdlib/@python2/itertools.pyi b/mypy/typeshed/stdlib/@python2/itertools.pyi index addb4104419f..63c38980ce79 100644 --- a/mypy/typeshed/stdlib/@python2/itertools.pyi +++ b/mypy/typeshed/stdlib/@python2/itertools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Generic, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") diff --git a/mypy/typeshed/stdlib/@python2/keyword.pyi b/mypy/typeshed/stdlib/@python2/keyword.pyi new file mode 100644 index 000000000000..e84ea1c919ec --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/keyword.pyi @@ -0,0 +1,5 @@ +from typing import Sequence, Text + +def iskeyword(s: Text) -> bool: ... + +kwlist: Sequence[str] diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/__init__.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/__init__.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/driver.pyi new file mode 100644 index 000000000000..841b0e4b1cb3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/driver.pyi @@ -0,0 +1,20 @@ +from _typeshed import StrPath +from lib2to3.pgen2.grammar import Grammar +from lib2to3.pytree import _NL, _Convert +from logging import Logger +from typing import IO, Any, Iterable, Optional, Text + +class Driver: + grammar: Grammar + logger: Logger + convert: _Convert + def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ..., logger: Optional[Logger] = ...) -> None: ... + def parse_tokens(self, tokens: Iterable[Any], debug: bool = ...) -> _NL: ... + def parse_stream_raw(self, stream: IO[Text], debug: bool = ...) -> _NL: ... + def parse_stream(self, stream: IO[Text], debug: bool = ...) -> _NL: ... + def parse_file(self, filename: StrPath, encoding: Optional[Text] = ..., debug: bool = ...) -> _NL: ... + def parse_string(self, text: Text, debug: bool = ...) -> _NL: ... + +def load_grammar( + gt: Text = ..., gp: Optional[Text] = ..., save: bool = ..., force: bool = ..., logger: Optional[Logger] = ... +) -> Grammar: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi new file mode 100644 index 000000000000..6ec97ce849d2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi @@ -0,0 +1,26 @@ +from _typeshed import StrPath +from typing import Dict, List, Optional, Text, Tuple, TypeVar + +_P = TypeVar("_P") +_Label = Tuple[int, Optional[Text]] +_DFA = List[List[Tuple[int, int]]] +_DFAS = Tuple[_DFA, Dict[int, int]] + +class Grammar: + symbol2number: Dict[Text, int] + number2symbol: Dict[int, Text] + states: List[_DFA] + dfas: Dict[int, _DFAS] + labels: List[_Label] + keywords: Dict[Text, int] + tokens: Dict[int, int] + symbol2label: Dict[Text, int] + start: int + def __init__(self) -> None: ... + def dump(self, filename: StrPath) -> None: ... + def load(self, filename: StrPath) -> None: ... + def copy(self: _P) -> _P: ... + def report(self) -> None: ... + +opmap_raw: Text +opmap: Dict[Text, Text] diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi new file mode 100644 index 000000000000..160d6fd76f76 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi @@ -0,0 +1,7 @@ +from typing import Dict, Match, Text + +simple_escapes: Dict[Text, Text] + +def escape(m: Match[str]) -> Text: ... +def evalString(s: Text) -> Text: ... +def test() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi new file mode 100644 index 000000000000..b7018cba9c1d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi @@ -0,0 +1,26 @@ +from lib2to3.pgen2.grammar import _DFAS, Grammar +from lib2to3.pytree import _NL, _Convert, _RawNode +from typing import Any, List, Optional, Sequence, Set, Text, Tuple + +_Context = Sequence[Any] + +class ParseError(Exception): + msg: Text + type: int + value: Optional[Text] + context: _Context + def __init__(self, msg: Text, type: int, value: Optional[Text], context: _Context) -> None: ... + +class Parser: + grammar: Grammar + convert: _Convert + stack: List[Tuple[_DFAS, int, _RawNode]] + rootnode: Optional[_NL] + used_names: Set[Text] + def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ...) -> None: ... + def setup(self, start: Optional[int] = ...) -> None: ... + def addtoken(self, type: int, value: Optional[Text], context: _Context) -> bool: ... + def classify(self, type: int, value: Optional[Text], context: _Context) -> int: ... + def shift(self, type: int, value: Optional[Text], newstate: int, context: _Context) -> None: ... + def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ... + def pop(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi new file mode 100644 index 000000000000..7920262f4f04 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi @@ -0,0 +1,46 @@ +from _typeshed import StrPath +from lib2to3.pgen2 import grammar +from lib2to3.pgen2.tokenize import _TokenInfo +from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Optional, Text, Tuple + +class PgenGrammar(grammar.Grammar): ... + +class ParserGenerator: + filename: StrPath + stream: IO[Text] + generator: Iterator[_TokenInfo] + first: Dict[Text, Dict[Text, int]] + def __init__(self, filename: StrPath, stream: Optional[IO[Text]] = ...) -> None: ... + def make_grammar(self) -> PgenGrammar: ... + def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... + def make_label(self, c: PgenGrammar, label: Text) -> int: ... + def addfirstsets(self) -> None: ... + def calcfirst(self, name: Text) -> None: ... + def parse(self) -> Tuple[Dict[Text, List[DFAState]], Text]: ... + def make_dfa(self, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def dump_dfa(self, name: Text, dfa: Iterable[DFAState]) -> None: ... + def simplify_dfa(self, dfa: List[DFAState]) -> None: ... + def parse_rhs(self) -> Tuple[NFAState, NFAState]: ... + def parse_alt(self) -> Tuple[NFAState, NFAState]: ... + def parse_item(self) -> Tuple[NFAState, NFAState]: ... + def parse_atom(self) -> Tuple[NFAState, NFAState]: ... + def expect(self, type: int, value: Optional[Any] = ...) -> Text: ... + def gettoken(self) -> None: ... + def raise_error(self, msg: str, *args: Any) -> NoReturn: ... + +class NFAState: + arcs: List[Tuple[Optional[Text], NFAState]] + def __init__(self) -> None: ... + def addarc(self, next: NFAState, label: Optional[Text] = ...) -> None: ... + +class DFAState: + nfaset: Dict[NFAState, Any] + isfinal: bool + arcs: Dict[Text, DFAState] + def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... + def addarc(self, next: DFAState, label: Text) -> None: ... + def unifystate(self, old: DFAState, new: DFAState) -> None: ... + def __eq__(self, other: Any) -> bool: ... + +def generate_grammar(filename: StrPath = ...) -> PgenGrammar: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi new file mode 100644 index 000000000000..3f4e41d49bd5 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi @@ -0,0 +1,63 @@ +from typing import Dict, Text + +ENDMARKER: int +NAME: int +NUMBER: int +STRING: int +NEWLINE: int +INDENT: int +DEDENT: int +LPAR: int +RPAR: int +LSQB: int +RSQB: int +COLON: int +COMMA: int +SEMI: int +PLUS: int +MINUS: int +STAR: int +SLASH: int +VBAR: int +AMPER: int +LESS: int +GREATER: int +EQUAL: int +DOT: int +PERCENT: int +BACKQUOTE: int +LBRACE: int +RBRACE: int +EQEQUAL: int +NOTEQUAL: int +LESSEQUAL: int +GREATEREQUAL: int +TILDE: int +CIRCUMFLEX: int +LEFTSHIFT: int +RIGHTSHIFT: int +DOUBLESTAR: int +PLUSEQUAL: int +MINEQUAL: int +STAREQUAL: int +SLASHEQUAL: int +PERCENTEQUAL: int +AMPEREQUAL: int +VBAREQUAL: int +CIRCUMFLEXEQUAL: int +LEFTSHIFTEQUAL: int +RIGHTSHIFTEQUAL: int +DOUBLESTAREQUAL: int +DOUBLESLASH: int +DOUBLESLASHEQUAL: int +OP: int +COMMENT: int +NL: int +ERRORTOKEN: int +N_TOKENS: int +NT_OFFSET: int +tok_name: Dict[int, Text] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi new file mode 100644 index 000000000000..477341c1a54e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi @@ -0,0 +1,23 @@ +from lib2to3.pgen2.token import * # noqa +from typing import Callable, Iterable, Iterator, List, Text, Tuple + +_Coord = Tuple[int, int] +_TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] +_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] + +class TokenError(Exception): ... +class StopTokenizing(Exception): ... + +def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... + +class Untokenizer: + tokens: List[Text] + prev_row: int + prev_col: int + def __init__(self) -> None: ... + def add_whitespace(self, start: _Coord) -> None: ... + def untokenize(self, iterable: Iterable[_TokenInfo]) -> Text: ... + def compat(self, token: Tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... + +def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... +def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pygram.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pygram.pyi new file mode 100644 index 000000000000..bf96a55c41b3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pygram.pyi @@ -0,0 +1,113 @@ +from lib2to3.pgen2.grammar import Grammar + +class Symbols: + def __init__(self, grammar: Grammar) -> None: ... + +class python_symbols(Symbols): + and_expr: int + and_test: int + annassign: int + arglist: int + argument: int + arith_expr: int + assert_stmt: int + async_funcdef: int + async_stmt: int + atom: int + augassign: int + break_stmt: int + classdef: int + comp_for: int + comp_if: int + comp_iter: int + comp_op: int + comparison: int + compound_stmt: int + continue_stmt: int + decorated: int + decorator: int + decorators: int + del_stmt: int + dictsetmaker: int + dotted_as_name: int + dotted_as_names: int + dotted_name: int + encoding_decl: int + eval_input: int + except_clause: int + exec_stmt: int + expr: int + expr_stmt: int + exprlist: int + factor: int + file_input: int + flow_stmt: int + for_stmt: int + funcdef: int + global_stmt: int + if_stmt: int + import_as_name: int + import_as_names: int + import_from: int + import_name: int + import_stmt: int + lambdef: int + listmaker: int + not_test: int + old_lambdef: int + old_test: int + or_test: int + parameters: int + pass_stmt: int + power: int + print_stmt: int + raise_stmt: int + return_stmt: int + shift_expr: int + simple_stmt: int + single_input: int + sliceop: int + small_stmt: int + star_expr: int + stmt: int + subscript: int + subscriptlist: int + suite: int + term: int + test: int + testlist: int + testlist1: int + testlist_gexp: int + testlist_safe: int + testlist_star_expr: int + tfpdef: int + tfplist: int + tname: int + trailer: int + try_stmt: int + typedargslist: int + varargslist: int + vfpdef: int + vfplist: int + vname: int + while_stmt: int + with_item: int + with_stmt: int + with_var: int + xor_expr: int + yield_arg: int + yield_expr: int + yield_stmt: int + +class pattern_symbols(Symbols): + Alternative: int + Alternatives: int + Details: int + Matcher: int + NegatedUnit: int + Repeater: int + Unit: int + +python_grammar: Grammar +python_grammar_no_print_statement: Grammar +pattern_grammar: Grammar diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi new file mode 100644 index 000000000000..48d11f84f201 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi @@ -0,0 +1,95 @@ +from lib2to3.pgen2.grammar import Grammar +from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union + +_P = TypeVar("_P") +_NL = Union[Node, Leaf] +_Context = Tuple[Text, int, int] +_Results = Dict[Text, _NL] +_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] +_Convert = Callable[[Grammar, _RawNode], Any] + +HUGE: int + +def type_repr(type_num: int) -> Text: ... + +class Base: + type: int + parent: Optional[Node] + prefix: Text + children: List[_NL] + was_changed: bool + was_checked: bool + def __eq__(self, other: Any) -> bool: ... + def _eq(self: _P, other: _P) -> bool: ... + def clone(self: _P) -> _P: ... + def post_order(self) -> Iterator[_NL]: ... + def pre_order(self) -> Iterator[_NL]: ... + def replace(self, new: Union[_NL, List[_NL]]) -> None: ... + def get_lineno(self) -> int: ... + def changed(self) -> None: ... + def remove(self) -> Optional[int]: ... + @property + def next_sibling(self) -> Optional[_NL]: ... + @property + def prev_sibling(self) -> Optional[_NL]: ... + def leaves(self) -> Iterator[Leaf]: ... + def depth(self) -> int: ... + def get_suffix(self) -> Text: ... + def get_prefix(self) -> Text: ... + def set_prefix(self, prefix: Text) -> None: ... + +class Node(Base): + fixers_applied: List[Any] + def __init__( + self, + type: int, + children: List[_NL], + context: Optional[Any] = ..., + prefix: Optional[Text] = ..., + fixers_applied: Optional[List[Any]] = ..., + ) -> None: ... + def set_child(self, i: int, child: _NL) -> None: ... + def insert_child(self, i: int, child: _NL) -> None: ... + def append_child(self, child: _NL) -> None: ... + +class Leaf(Base): + lineno: int + column: int + value: Text + fixers_applied: List[Any] + def __init__( + self, + type: int, + value: Text, + context: Optional[_Context] = ..., + prefix: Optional[Text] = ..., + fixers_applied: List[Any] = ..., + ) -> None: ... + +def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... + +class BasePattern: + type: int + content: Optional[Text] + name: Optional[Text] + def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns + def match(self, node: _NL, results: Optional[_Results] = ...) -> bool: ... + def match_seq(self, nodes: List[_NL], results: Optional[_Results] = ...) -> bool: ... + def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... + +class LeafPattern(BasePattern): + def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + +class NodePattern(BasePattern): + wildcards: bool + def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + +class WildcardPattern(BasePattern): + min: int + max: int + def __init__(self, content: Optional[Text] = ..., min: int = ..., max: int = ..., name: Optional[Text] = ...) -> None: ... + +class NegatedPattern(BasePattern): + def __init__(self, content: Optional[Text] = ...) -> None: ... + +def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... diff --git a/mypy/typeshed/stdlib/@python2/linecache.pyi b/mypy/typeshed/stdlib/@python2/linecache.pyi new file mode 100644 index 000000000000..1e5fd821b9f4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/linecache.pyi @@ -0,0 +1,9 @@ +from typing import Any, Dict, List, Optional, Text + +_ModuleGlobals = Dict[str, Any] + +def getline(filename: Text, lineno: int, module_globals: Optional[_ModuleGlobals] = ...) -> str: ... +def clearcache() -> None: ... +def getlines(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... +def checkcache(filename: Optional[Text] = ...) -> None: ... +def updatecache(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/locale.pyi b/mypy/typeshed/stdlib/@python2/locale.pyi new file mode 100644 index 000000000000..eb73dfcb62a2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/locale.pyi @@ -0,0 +1,96 @@ +# workaround for mypy#2010 +from __builtin__ import str as _str +from decimal import Decimal +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +CODESET: int +D_T_FMT: int +D_FMT: int +T_FMT: int +T_FMT_AMPM: int + +DAY_1: int +DAY_2: int +DAY_3: int +DAY_4: int +DAY_5: int +DAY_6: int +DAY_7: int +ABDAY_1: int +ABDAY_2: int +ABDAY_3: int +ABDAY_4: int +ABDAY_5: int +ABDAY_6: int +ABDAY_7: int + +MON_1: int +MON_2: int +MON_3: int +MON_4: int +MON_5: int +MON_6: int +MON_7: int +MON_8: int +MON_9: int +MON_10: int +MON_11: int +MON_12: int +ABMON_1: int +ABMON_2: int +ABMON_3: int +ABMON_4: int +ABMON_5: int +ABMON_6: int +ABMON_7: int +ABMON_8: int +ABMON_9: int +ABMON_10: int +ABMON_11: int +ABMON_12: int + +RADIXCHAR: int +THOUSEP: int +YESEXPR: int +NOEXPR: int +CRNCYSTR: int + +ERA: int +ERA_D_T_FMT: int +ERA_D_FMT: int +ERA_T_FMT: int + +ALT_DIGITS: int + +LC_CTYPE: int +LC_COLLATE: int +LC_TIME: int +LC_MONETARY: int +LC_MESSAGES: int +LC_NUMERIC: int +LC_ALL: int + +CHAR_MAX: int + +class Error(Exception): ... + +def setlocale(category: int, locale: Union[_str, Iterable[_str], None] = ...) -> _str: ... +def localeconv() -> Mapping[_str, Union[int, _str, List[int]]]: ... +def nl_langinfo(__key: int) -> _str: ... +def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[Optional[_str], Optional[_str]]: ... +def getlocale(category: int = ...) -> Sequence[_str]: ... +def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... +def normalize(localename: _str) -> _str: ... +def resetlocale(category: int = ...) -> None: ... +def strcoll(string1: _str, string2: _str) -> int: ... +def strxfrm(string: _str) -> _str: ... +def format(percent: _str, value: Union[float, Decimal], grouping: bool = ..., monetary: bool = ..., *additional: Any) -> _str: ... +def format_string(f: _str, val: Any, grouping: bool = ...) -> _str: ... +def currency(val: Union[int, float, Decimal], symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... +def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... +def atoi(string: _str) -> int: ... +def str(val: float) -> _str: ... + +locale_alias: Dict[_str, _str] # undocumented +locale_encoding_alias: Dict[_str, _str] # undocumented +windows_locale: Dict[int, _str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi index 240215528527..242132c820d5 100644 --- a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -1,24 +1,8 @@ import threading from _typeshed import StrPath -from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Iterable, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Text, - Tuple, - Union, - overload, -) +from typing import IO, Any, Callable, Dict, List, Mapping, MutableMapping, Optional, Sequence, Text, Tuple, Union, overload _SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType] diff --git a/mypy/typeshed/stdlib/@python2/logging/config.pyi b/mypy/typeshed/stdlib/@python2/logging/config.pyi index 695001221d79..3d8817b7736f 100644 --- a/mypy/typeshed/stdlib/@python2/logging/config.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/config.pyi @@ -1,8 +1,6 @@ -from _typeshed import AnyPath, StrPath +from _typeshed import StrPath from threading import Thread -from typing import IO, Any, Callable, Dict, Optional, Union - -from ConfigParser import RawConfigParser +from typing import IO, Any, Dict, Optional, Union _Path = StrPath diff --git a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi index 9403409fce87..ed7e6d74dd17 100644 --- a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi @@ -1,10 +1,7 @@ -import datetime -import ssl from _typeshed import StrPath from logging import FileHandler, Handler, LogRecord -from Queue import Queue from socket import SocketKind, SocketType -from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union +from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union DEFAULT_TCP_LOGGING_PORT: int DEFAULT_UDP_LOGGING_PORT: int diff --git a/mypy/typeshed/stdlib/@python2/macpath.pyi b/mypy/typeshed/stdlib/@python2/macpath.pyi new file mode 100644 index 000000000000..74e3315f6481 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/macpath.pyi @@ -0,0 +1,55 @@ +from genericpath import ( + commonprefix as commonprefix, + exists as exists, + getatime as getatime, + getctime as getctime, + getmtime as getmtime, + getsize as getsize, + isdir as isdir, + isfile as isfile, +) + +# Re-export common definitions from posixpath to reduce duplication +from posixpath import ( + abspath as abspath, + curdir as curdir, + defpath as defpath, + devnull as devnull, + expanduser as expanduser, + expandvars as expandvars, + extsep as extsep, + isabs as isabs, + lexists as lexists, + pardir as pardir, + pathsep as pathsep, + sep as sep, + splitdrive as splitdrive, + splitext as splitext, + supports_unicode_filenames as supports_unicode_filenames, +) +from typing import AnyStr, Optional, Text, Tuple, overload + +altsep: Optional[str] + +def basename(s: AnyStr) -> AnyStr: ... +def dirname(s: AnyStr) -> AnyStr: ... +def normcase(path: AnyStr) -> AnyStr: ... +def normpath(s: AnyStr) -> AnyStr: ... +def realpath(path: AnyStr) -> AnyStr: ... +def islink(s: Text) -> bool: ... + +# Make sure signatures are disjunct, and allow combinations of bytes and unicode. +# (Since Python 2 allows that, too) +# Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in +# a type error. +@overload +def join(__p1: bytes, *p: bytes) -> bytes: ... +@overload +def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... +@overload +def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... +@overload +def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... +@overload +def join(__p1: Text, *p: Text) -> Text: ... +def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/macurl2path.pyi b/mypy/typeshed/stdlib/@python2/macurl2path.pyi new file mode 100644 index 000000000000..025820b44e89 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/macurl2path.pyi @@ -0,0 +1,5 @@ +from typing import Union + +def url2pathname(pathname: str) -> str: ... +def pathname2url(pathname: str) -> str: ... +def _pncomp2url(component: Union[str, bytes]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/mailbox.pyi b/mypy/typeshed/stdlib/@python2/mailbox.pyi new file mode 100644 index 000000000000..38663a391b8f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mailbox.pyi @@ -0,0 +1,194 @@ +import email.message +from types import TracebackType +from typing import ( + IO, + Any, + AnyStr, + Callable, + Dict, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Protocol, + Sequence, + Text, + Tuple, + Type, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal + +_T = TypeVar("_T") +_MessageT = TypeVar("_MessageT", bound=Message) +_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] + +class _HasIteritems(Protocol): + def iteritems(self) -> Iterator[Tuple[str, _MessageData]]: ... + +class _HasItems(Protocol): + def items(self) -> Iterator[Tuple[str, _MessageData]]: ... + +linesep: bytes + +class Mailbox(Generic[_MessageT]): + + _path: Union[bytes, str] # undocumented + _factory: Optional[Callable[[IO[Any]], _MessageT]] # undocumented + def __init__(self, path: Text, factory: Optional[Callable[[IO[Any]], _MessageT]] = ..., create: bool = ...) -> None: ... + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def discard(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + @overload + def get(self, key: str, default: None = ...) -> Optional[_MessageT]: ... + @overload + def get(self, key: str, default: _T) -> Union[_MessageT, _T]: ... + def __getitem__(self, key: str) -> _MessageT: ... + def get_message(self, key: str) -> _MessageT: ... + def get_string(self, key: str) -> str: ... + def get_bytes(self, key: str) -> bytes: ... + # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here + def get_file(self, key: str) -> Any: ... + def iterkeys(self) -> Iterator[str]: ... + def keys(self) -> List[str]: ... + def itervalues(self) -> Iterator[_MessageT]: ... + def __iter__(self) -> Iterator[_MessageT]: ... + def values(self) -> List[_MessageT]: ... + def iteritems(self) -> Iterator[Tuple[str, _MessageT]]: ... + def items(self) -> List[Tuple[str, _MessageT]]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def clear(self) -> None: ... + @overload + def pop(self, key: str, default: None = ...) -> Optional[_MessageT]: ... + @overload + def pop(self, key: str, default: _T = ...) -> Union[_MessageT, _T]: ... + def popitem(self) -> Tuple[str, _MessageT]: ... + def update(self, arg: Optional[Union[_HasIteritems, _HasItems, Iterable[Tuple[str, _MessageData]]]] = ...) -> None: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... + +class Maildir(Mailbox[MaildirMessage]): + + colon: str + def __init__( + self, dirname: Text, factory: Optional[Callable[[IO[Any]], MaildirMessage]] = ..., create: bool = ... + ) -> None: ... + def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def list_folders(self) -> List[str]: ... + def get_folder(self, folder: Text) -> Maildir: ... + def add_folder(self, folder: Text) -> Maildir: ... + def remove_folder(self, folder: Text) -> None: ... + def clean(self) -> None: ... + def next(self) -> Optional[str]: ... + +class _singlefileMailbox(Mailbox[_MessageT]): ... + +class _mboxMMDF(_singlefileMailbox[_MessageT]): + def get_file(self, key: str, from_: bool = ...) -> _PartialFile[bytes]: ... + def get_bytes(self, key: str, from_: bool = ...) -> bytes: ... + def get_string(self, key: str, from_: bool = ...) -> str: ... + +class mbox(_mboxMMDF[mboxMessage]): + def __init__(self, path: Text, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ...) -> None: ... + +class MMDF(_mboxMMDF[MMDFMessage]): + def __init__(self, path: Text, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ...) -> None: ... + +class MH(Mailbox[MHMessage]): + def __init__(self, path: Text, factory: Optional[Callable[[IO[Any]], MHMessage]] = ..., create: bool = ...) -> None: ... + def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def list_folders(self) -> List[str]: ... + def get_folder(self, folder: Text) -> MH: ... + def add_folder(self, folder: Text) -> MH: ... + def remove_folder(self, folder: Text) -> None: ... + def get_sequences(self) -> Dict[str, List[int]]: ... + def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... + def pack(self) -> None: ... + +class Babyl(_singlefileMailbox[BabylMessage]): + def __init__(self, path: Text, factory: Optional[Callable[[IO[Any]], BabylMessage]] = ..., create: bool = ...) -> None: ... + def get_file(self, key: str) -> IO[bytes]: ... + def get_labels(self) -> List[str]: ... + +class Message(email.message.Message): + def __init__(self, message: Optional[_MessageData] = ...) -> None: ... + +class MaildirMessage(Message): + def get_subdir(self) -> str: ... + def set_subdir(self, subdir: Literal["new", "cur"]) -> None: ... + def get_flags(self) -> str: ... + def set_flags(self, flags: Iterable[str]) -> None: ... + def add_flag(self, flag: str) -> None: ... + def remove_flag(self, flag: str) -> None: ... + def get_date(self) -> int: ... + def set_date(self, date: float) -> None: ... + def get_info(self) -> str: ... + def set_info(self, info: str) -> None: ... + +class _mboxMMDFMessage(Message): + def get_from(self) -> str: ... + def set_from( + self, from_: str, time_: Optional[Union[bool, Tuple[int, int, int, int, int, int, int, int, int]]] = ... + ) -> None: ... + def get_flags(self) -> str: ... + def set_flags(self, flags: Iterable[str]) -> None: ... + def add_flag(self, flag: str) -> None: ... + def remove_flag(self, flag: str) -> None: ... + +class mboxMessage(_mboxMMDFMessage): ... + +class MHMessage(Message): + def get_sequences(self) -> List[str]: ... + def set_sequences(self, sequences: Iterable[str]) -> None: ... + def add_sequence(self, sequence: str) -> None: ... + def remove_sequence(self, sequence: str) -> None: ... + +class BabylMessage(Message): + def get_labels(self) -> List[str]: ... + def set_labels(self, labels: Iterable[str]) -> None: ... + def add_label(self, label: str) -> None: ... + def remove_label(self, label: str) -> None: ... + def get_visible(self) -> Message: ... + def set_visible(self, visible: _MessageData) -> None: ... + def update_visible(self) -> None: ... + +class MMDFMessage(_mboxMMDFMessage): ... + +class _ProxyFile(Generic[AnyStr]): + def __init__(self, f: IO[AnyStr], pos: Optional[int] = ...) -> None: ... + def read(self, size: Optional[int] = ...) -> AnyStr: ... + def read1(self, size: Optional[int] = ...) -> AnyStr: ... + def readline(self, size: Optional[int] = ...) -> AnyStr: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[AnyStr]: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: int = ...) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> _ProxyFile[AnyStr]: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType] + ) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def flush(self) -> None: ... + @property + def closed(self) -> bool: ... + +class _PartialFile(_ProxyFile[AnyStr]): + def __init__(self, f: IO[AnyStr], start: Optional[int] = ..., stop: Optional[int] = ...) -> None: ... + +class Error(Exception): ... +class NoSuchMailboxError(Error): ... +class NotEmptyError(Error): ... +class ExternalClashError(Error): ... +class FormatError(Error): ... diff --git a/mypy/typeshed/stdlib/@python2/mailcap.pyi b/mypy/typeshed/stdlib/@python2/mailcap.pyi new file mode 100644 index 000000000000..a65cc3a329d3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mailcap.pyi @@ -0,0 +1,8 @@ +from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union + +_Cap = Dict[str, Union[str, int]] + +def findmatch( + caps: Mapping[str, List[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... +) -> Tuple[Optional[str], Optional[_Cap]]: ... +def getcaps() -> Dict[str, List[_Cap]]: ... diff --git a/mypy/typeshed/stdlib/@python2/marshal.pyi b/mypy/typeshed/stdlib/@python2/marshal.pyi new file mode 100644 index 000000000000..b2fde674a647 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/marshal.pyi @@ -0,0 +1,8 @@ +from typing import IO, Any + +version: int + +def dump(__value: Any, __file: IO[Any], __version: int = ...) -> None: ... +def load(__file: IO[Any]) -> Any: ... +def dumps(__value: Any, __version: int = ...) -> bytes: ... +def loads(__bytes: bytes) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/math.pyi b/mypy/typeshed/stdlib/@python2/math.pyi new file mode 100644 index 000000000000..caddcedd864b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/math.pyi @@ -0,0 +1,45 @@ +from typing import Iterable, SupportsFloat, SupportsInt, Tuple + +e: float +pi: float + +def acos(__x: SupportsFloat) -> float: ... +def acosh(__x: SupportsFloat) -> float: ... +def asin(__x: SupportsFloat) -> float: ... +def asinh(__x: SupportsFloat) -> float: ... +def atan(__x: SupportsFloat) -> float: ... +def atan2(__y: SupportsFloat, __x: SupportsFloat) -> float: ... +def atanh(__x: SupportsFloat) -> float: ... +def ceil(__x: SupportsFloat) -> float: ... +def copysign(__x: SupportsFloat, __y: SupportsFloat) -> float: ... +def cos(__x: SupportsFloat) -> float: ... +def cosh(__x: SupportsFloat) -> float: ... +def degrees(__x: SupportsFloat) -> float: ... +def erf(__x: SupportsFloat) -> float: ... +def erfc(__x: SupportsFloat) -> float: ... +def exp(__x: SupportsFloat) -> float: ... +def expm1(__x: SupportsFloat) -> float: ... +def fabs(__x: SupportsFloat) -> float: ... +def factorial(__x: SupportsInt) -> int: ... +def floor(__x: SupportsFloat) -> float: ... +def fmod(__x: SupportsFloat, __y: SupportsFloat) -> float: ... +def frexp(__x: SupportsFloat) -> Tuple[float, int]: ... +def fsum(__seq: Iterable[float]) -> float: ... +def gamma(__x: SupportsFloat) -> float: ... +def hypot(__x: SupportsFloat, __y: SupportsFloat) -> float: ... +def isinf(__x: SupportsFloat) -> bool: ... +def isnan(__x: SupportsFloat) -> bool: ... +def ldexp(__x: SupportsFloat, __i: int) -> float: ... +def lgamma(__x: SupportsFloat) -> float: ... +def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... +def log10(__x: SupportsFloat) -> float: ... +def log1p(__x: SupportsFloat) -> float: ... +def modf(__x: SupportsFloat) -> Tuple[float, float]: ... +def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... +def radians(__x: SupportsFloat) -> float: ... +def sin(__x: SupportsFloat) -> float: ... +def sinh(__x: SupportsFloat) -> float: ... +def sqrt(__x: SupportsFloat) -> float: ... +def tan(__x: SupportsFloat) -> float: ... +def tanh(__x: SupportsFloat) -> float: ... +def trunc(__x: SupportsFloat) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/mimetypes.pyi b/mypy/typeshed/stdlib/@python2/mimetypes.pyi new file mode 100644 index 000000000000..5412a5c7c21b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mimetypes.pyi @@ -0,0 +1,30 @@ +import sys +from typing import IO, Dict, List, Optional, Sequence, Text, Tuple + +def guess_type(url: Text, strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... +def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... +def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ... +def init(files: Optional[Sequence[str]] = ...) -> None: ... +def read_mime_types(file: str) -> Optional[Dict[str, str]]: ... +def add_type(type: str, ext: str, strict: bool = ...) -> None: ... + +inited: bool +knownfiles: List[str] +suffix_map: Dict[str, str] +encodings_map: Dict[str, str] +types_map: Dict[str, str] +common_types: Dict[str, str] + +class MimeTypes: + suffix_map: Dict[str, str] + encodings_map: Dict[str, str] + types_map: Tuple[Dict[str, str], Dict[str, str]] + types_map_inv: Tuple[Dict[str, str], Dict[str, str]] + def __init__(self, filenames: Tuple[str, ...] = ..., strict: bool = ...) -> None: ... + def guess_extension(self, type: str, strict: bool = ...) -> Optional[str]: ... + def guess_type(self, url: str, strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + def guess_all_extensions(self, type: str, strict: bool = ...) -> List[str]: ... + def read(self, filename: str, strict: bool = ...) -> None: ... + def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... + if sys.platform == "win32": + def read_windows_registry(self, strict: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/mmap.pyi b/mypy/typeshed/stdlib/@python2/mmap.pyi new file mode 100644 index 000000000000..1b8a0202fa76 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mmap.pyi @@ -0,0 +1,55 @@ +import sys +from typing import AnyStr, Generic, Optional, Sequence, Union + +ACCESS_DEFAULT: int +ACCESS_READ: int +ACCESS_WRITE: int +ACCESS_COPY: int + +ALLOCATIONGRANULARITY: int + +if sys.platform == "linux": + MAP_DENYWRITE: int + MAP_EXECUTABLE: int + +if sys.platform != "win32": + MAP_ANON: int + MAP_ANONYMOUS: int + MAP_PRIVATE: int + MAP_SHARED: int + PROT_EXEC: int + PROT_READ: int + PROT_WRITE: int + + PAGESIZE: int + +class _mmap(Generic[AnyStr]): + if sys.platform == "win32": + def __init__( + self, fileno: int, length: int, tagname: Optional[str] = ..., access: int = ..., offset: int = ... + ) -> None: ... + else: + def __init__( + self, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ... + ) -> None: ... + def close(self) -> None: ... + def flush(self, offset: int = ..., size: int = ...) -> int: ... + def move(self, dest: int, src: int, count: int) -> None: ... + def read_byte(self) -> AnyStr: ... + def readline(self) -> AnyStr: ... + def resize(self, newsize: int) -> None: ... + def seek(self, pos: int, whence: int = ...) -> None: ... + def size(self) -> int: ... + def tell(self) -> int: ... + def write_byte(self, byte: AnyStr) -> None: ... + def __len__(self) -> int: ... + +class mmap(_mmap[bytes], Sequence[bytes]): + def find(self, string: bytes, start: int = ..., end: int = ...) -> int: ... + def rfind(self, string: bytes, start: int = ..., stop: int = ...) -> int: ... + def read(self, num: int) -> bytes: ... + def write(self, string: bytes) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> bytes: ... + def __getslice__(self, i: Optional[int], j: Optional[int]) -> bytes: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __setitem__(self, index: Union[int, slice], object: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/modulefinder.pyi b/mypy/typeshed/stdlib/@python2/modulefinder.pyi new file mode 100644 index 000000000000..6fb953242b72 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/modulefinder.pyi @@ -0,0 +1,63 @@ +from types import CodeType +from typing import IO, Any, Container, Dict, Iterable, List, Optional, Sequence, Tuple + +LOAD_CONST: int # undocumented +IMPORT_NAME: int # undocumented +STORE_NAME: int # undocumented +STORE_GLOBAL: int # undocumented +STORE_OPS: Tuple[int, int] # undocumented +EXTENDED_ARG: int # undocumented + +packagePathMap: Dict[str, List[str]] # undocumented + +def AddPackagePath(packagename: str, path: str) -> None: ... + +replacePackageMap: Dict[str, str] # undocumented + +def ReplacePackage(oldname: str, newname: str) -> None: ... + +class Module: # undocumented + def __init__(self, name: str, file: Optional[str] = ..., path: Optional[str] = ...) -> None: ... + def __repr__(self) -> str: ... + +class ModuleFinder: + + modules: Dict[str, Module] + path: List[str] # undocumented + badmodules: Dict[str, Dict[str, int]] # undocumented + debug: int # undocumented + indent: int # undocumented + excludes: Container[str] # undocumented + replace_paths: Sequence[Tuple[str, str]] # undocumented + def __init__( + self, + path: Optional[List[str]] = ..., + debug: int = ..., + excludes: Container[str] = ..., + replace_paths: Sequence[Tuple[str, str]] = ..., + ) -> None: ... + def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented + def msgin(self, *args: Any) -> None: ... # undocumented + def msgout(self, *args: Any) -> None: ... # undocumented + def run_script(self, pathname: str) -> None: ... + def load_file(self, pathname: str) -> None: ... # undocumented + def import_hook( + self, name: str, caller: Optional[Module] = ..., fromlist: Optional[List[str]] = ..., level: int = ... + ) -> Optional[Module]: ... # undocumented + def determine_parent(self, caller: Optional[Module], level: int = ...) -> Optional[Module]: ... # undocumented + def find_head_package(self, parent: Module, name: str) -> Tuple[Module, str]: ... # undocumented + def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented + def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = ...) -> None: ... # undocumented + def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented + def import_module(self, partname: str, fqname: str, parent: Module) -> Optional[Module]: ... # undocumented + def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented + def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented + def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented + def add_module(self, fqname: str) -> Module: ... # undocumented + def find_module( + self, name: str, path: Optional[str], parent: Optional[Module] = ... + ) -> Tuple[Optional[IO[Any]], Optional[str], Tuple[str, str, int]]: ... # undocumented + def report(self) -> None: ... + def any_missing(self) -> List[str]: ... # undocumented + def any_missing_maybe(self) -> Tuple[List[str], List[str]]: ... # undocumented + def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi new file mode 100644 index 000000000000..c783493f315e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi @@ -0,0 +1,195 @@ +import sys +from types import ModuleType +from typing import Any, Container, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type, Union +from typing_extensions import Literal + +if sys.platform == "win32": + from _msi import _Database + + AMD64: bool + Itanium: bool + Win64: bool + + datasizemask: Literal[0x00FF] + type_valid: Literal[0x0100] + type_localizable: Literal[0x0200] + typemask: Literal[0x0C00] + type_long: Literal[0x0000] + type_short: Literal[0x0400] + type_string: Literal[0x0C00] + type_binary: Literal[0x0800] + type_nullable: Literal[0x1000] + type_key: Literal[0x2000] + knownbits: Literal[0x3FFF] + class Table: + + name: str + fields: List[Tuple[int, str, int]] + def __init__(self, name: str) -> None: ... + def add_field(self, index: int, name: str, type: int) -> None: ... + def sql(self) -> str: ... + def create(self, db: _Database) -> None: ... + class _Unspecified: ... + def change_sequence( + seq: Sequence[Tuple[str, Optional[str], int]], + action: str, + seqno: Union[int, Type[_Unspecified]] = ..., + cond: Union[str, Type[_Unspecified]] = ..., + ) -> None: ... + def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> None: ... + def add_stream(db: _Database, name: str, path: str) -> None: ... + def init_database( + name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str + ) -> _Database: ... + def add_tables(db: _Database, module: ModuleType) -> None: ... + def make_id(str: str) -> str: ... + def gen_uuid() -> str: ... + class CAB: + + name: str + files: List[Tuple[str, str]] + filenames: Set[str] + index: int + def __init__(self, name: str) -> None: ... + def gen_id(self, file: str) -> str: ... + def append(self, full: str, file: str, logical: str) -> Tuple[int, str]: ... + def commit(self, db: _Database) -> None: ... + _directories: Set[str] + class Directory: + + db: _Database + cab: CAB + basedir: str + physical: str + logical: str + component: Optional[str] + short_names: Set[str] + ids: Set[str] + keyfiles: Dict[str, str] + componentflags: Optional[int] + absolute: str + def __init__( + self, + db: _Database, + cab: CAB, + basedir: str, + physical: str, + _logical: str, + default: str, + componentflags: Optional[int] = ..., + ) -> None: ... + def start_component( + self, + component: Optional[str] = ..., + feature: Optional[Feature] = ..., + flags: Optional[int] = ..., + keyfile: Optional[str] = ..., + uuid: Optional[str] = ..., + ) -> None: ... + def make_short(self, file: str) -> str: ... + def add_file( + self, file: str, src: Optional[str] = ..., version: Optional[str] = ..., language: Optional[str] = ... + ) -> str: ... + def glob(self, pattern: str, exclude: Optional[Container[str]] = ...) -> List[str]: ... + def remove_pyc(self) -> None: ... + class Binary: + + name: str + def __init__(self, fname: str) -> None: ... + def __repr__(self) -> str: ... + class Feature: + + id: str + def __init__( + self, + db: _Database, + id: str, + title: str, + desc: str, + display: int, + level: int = ..., + parent: Optional[Feature] = ..., + directory: Optional[str] = ..., + attributes: int = ..., + ) -> None: ... + def set_current(self) -> None: ... + class Control: + + dlg: Dialog + name: str + def __init__(self, dlg: Dialog, name: str) -> None: ... + def event(self, event: str, argument: str, condition: str = ..., ordering: Optional[int] = ...) -> None: ... + def mapping(self, event: str, attribute: str) -> None: ... + def condition(self, action: str, condition: str) -> None: ... + class RadioButtonGroup(Control): + + property: str + index: int + def __init__(self, dlg: Dialog, name: str, property: str) -> None: ... + def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: Optional[str] = ...) -> None: ... + class Dialog: + + db: _Database + name: str + x: int + y: int + w: int + h: int + def __init__( + self, + db: _Database, + name: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + title: str, + first: str, + default: str, + cancel: str, + ) -> None: ... + def control( + self, + name: str, + type: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + prop: Optional[str], + text: Optional[str], + next: Optional[str], + help: Optional[str], + ) -> Control: ... + def text(self, name: str, x: int, y: int, w: int, h: int, attr: int, text: Optional[str]) -> Control: ... + def bitmap(self, name: str, x: int, y: int, w: int, h: int, text: Optional[str]) -> Control: ... + def line(self, name: str, x: int, y: int, w: int, h: int) -> Control: ... + def pushbutton( + self, name: str, x: int, y: int, w: int, h: int, attr: int, text: Optional[str], next: Optional[str] + ) -> Control: ... + def radiogroup( + self, + name: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + prop: Optional[str], + text: Optional[str], + next: Optional[str], + ) -> RadioButtonGroup: ... + def checkbox( + self, + name: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + prop: Optional[str], + text: Optional[str], + next: Optional[str], + ) -> Control: ... diff --git a/mypy/typeshed/stdlib/@python2/msilib/schema.pyi b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi new file mode 100644 index 000000000000..10b65088cf80 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi @@ -0,0 +1,97 @@ +import sys +from typing import List, Optional, Tuple + +if sys.platform == "win32": + from . import Table + + _Validation: Table + ActionText: Table + AdminExecuteSequence: Table + Condition: Table + AdminUISequence: Table + AdvtExecuteSequence: Table + AdvtUISequence: Table + AppId: Table + AppSearch: Table + Property: Table + BBControl: Table + Billboard: Table + Feature: Table + Binary: Table + BindImage: Table + File: Table + CCPSearch: Table + CheckBox: Table + Class: Table + Component: Table + Icon: Table + ProgId: Table + ComboBox: Table + CompLocator: Table + Complus: Table + Directory: Table + Control: Table + Dialog: Table + ControlCondition: Table + ControlEvent: Table + CreateFolder: Table + CustomAction: Table + DrLocator: Table + DuplicateFile: Table + Environment: Table + Error: Table + EventMapping: Table + Extension: Table + MIME: Table + FeatureComponents: Table + FileSFPCatalog: Table + SFPCatalog: Table + Font: Table + IniFile: Table + IniLocator: Table + InstallExecuteSequence: Table + InstallUISequence: Table + IsolatedComponent: Table + LaunchCondition: Table + ListBox: Table + ListView: Table + LockPermissions: Table + Media: Table + MoveFile: Table + MsiAssembly: Table + MsiAssemblyName: Table + MsiDigitalCertificate: Table + MsiDigitalSignature: Table + MsiFileHash: Table + MsiPatchHeaders: Table + ODBCAttribute: Table + ODBCDriver: Table + ODBCDataSource: Table + ODBCSourceAttribute: Table + ODBCTranslator: Table + Patch: Table + PatchPackage: Table + PublishComponent: Table + RadioButton: Table + Registry: Table + RegLocator: Table + RemoveFile: Table + RemoveIniFile: Table + RemoveRegistry: Table + ReserveCost: Table + SelfReg: Table + ServiceControl: Table + ServiceInstall: Table + Shortcut: Table + Signature: Table + TextStyle: Table + TypeLib: Table + UIText: Table + Upgrade: Table + Verb: Table + + tables: List[Table] + + _Validation_records: List[ + Tuple[str, str, str, Optional[int], Optional[int], Optional[str], Optional[int], Optional[str], Optional[str], str] + ] diff --git a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi new file mode 100644 index 000000000000..e4f400d33233 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi @@ -0,0 +1,14 @@ +import sys +from typing import List, Optional, Tuple + +if sys.platform == "win32": + + _SequenceType = List[Tuple[str, Optional[str], int]] + + AdminExecuteSequence: _SequenceType + AdminUISequence: _SequenceType + AdvtExecuteSequence: _SequenceType + InstallExecuteSequence: _SequenceType + InstallUISequence: _SequenceType + + tables: List[str] diff --git a/mypy/typeshed/stdlib/@python2/msilib/text.pyi b/mypy/typeshed/stdlib/@python2/msilib/text.pyi new file mode 100644 index 000000000000..e338b8b5ba3d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/msilib/text.pyi @@ -0,0 +1,9 @@ +import sys +from typing import List, Optional, Tuple + +if sys.platform == "win32": + + ActionText: List[Tuple[str, str, Optional[str]]] + UIText: List[Tuple[str, Optional[str]]] + + tables: List[str] diff --git a/mypy/typeshed/stdlib/@python2/msvcrt.pyi b/mypy/typeshed/stdlib/@python2/msvcrt.pyi new file mode 100644 index 000000000000..ede80c9fbb66 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/msvcrt.pyi @@ -0,0 +1,24 @@ +import sys +from typing import Text + +# This module is only available on Windows +if sys.platform == "win32": + LK_LOCK: int + LK_NBLCK: int + LK_NBRLCK: int + LK_RLCK: int + LK_UNLCK: int + def locking(__fd: int, __mode: int, __nbytes: int) -> None: ... + def setmode(__fd: int, __mode: int) -> int: ... + def open_osfhandle(__handle: int, __flags: int) -> int: ... + def get_osfhandle(__fd: int) -> int: ... + def kbhit() -> bool: ... + def getch() -> bytes: ... + def getwch() -> Text: ... + def getche() -> bytes: ... + def getwche() -> Text: ... + def putch(__char: bytes) -> None: ... + def putwch(__unicode_char: Text) -> None: ... + def ungetch(__char: bytes) -> None: ... + def ungetwch(__unicode_char: Text) -> None: ... + def heapmin() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi index 8f6b2124094d..dd0b5f5246b7 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi @@ -1,13 +1,8 @@ import array -import itertools -import sys import threading import weakref -from multiprocessing import TimeoutError, cpu_count -from multiprocessing.dummy.connection import Pipe from Queue import Queue -from threading import BoundedSemaphore, Event, Lock, RLock, Semaphore -from typing import Any, List, Optional, Type +from typing import Any, List, Optional class DummyProcess(threading.Thread): _children: weakref.WeakKeyDictionary[Any, Any] diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi index 60e456e3918d..73789028611e 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi @@ -1,5 +1,5 @@ from Queue import Queue -from typing import Any, List, Optional, Tuple, Type +from typing import Any, List, Optional, Tuple families: List[None] diff --git a/mypy/typeshed/stdlib/@python2/netrc.pyi b/mypy/typeshed/stdlib/@python2/netrc.pyi new file mode 100644 index 000000000000..2ee3c522516a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/netrc.pyi @@ -0,0 +1,16 @@ +from typing import Dict, List, Optional, Text, Tuple + +class NetrcParseError(Exception): + filename: Optional[str] + lineno: Optional[int] + msg: str + def __init__(self, msg: str, filename: Optional[Text] = ..., lineno: Optional[int] = ...) -> None: ... + +# (login, account, password) tuple +_NetrcTuple = Tuple[str, Optional[str], Optional[str]] + +class netrc: + hosts: Dict[str, _NetrcTuple] + macros: Dict[str, List[str]] + def __init__(self, file: Optional[Text] = ...) -> None: ... + def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/mypy/typeshed/stdlib/@python2/nis.pyi b/mypy/typeshed/stdlib/@python2/nis.pyi new file mode 100644 index 000000000000..bc6c2bc07256 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/nis.pyi @@ -0,0 +1,9 @@ +import sys +from typing import Dict, List + +if sys.platform != "win32": + def cat(map: str, domain: str = ...) -> Dict[str, str]: ... + def get_default_domain() -> str: ... + def maps(domain: str = ...) -> List[str]: ... + def match(key: str, map: str, domain: str = ...) -> str: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/nntplib.pyi b/mypy/typeshed/stdlib/@python2/nntplib.pyi new file mode 100644 index 000000000000..21b33f55d051 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/nntplib.pyi @@ -0,0 +1,111 @@ +import datetime +import socket +import ssl +from typing import IO, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, TypeVar, Union + +_SelfT = TypeVar("_SelfT", bound=_NNTPBase) +_File = Union[IO[bytes], bytes, str, None] + +class NNTPError(Exception): + response: str + +class NNTPReplyError(NNTPError): ... +class NNTPTemporaryError(NNTPError): ... +class NNTPPermanentError(NNTPError): ... +class NNTPProtocolError(NNTPError): ... +class NNTPDataError(NNTPError): ... + +NNTP_PORT: int +NNTP_SSL_PORT: int + +class GroupInfo(NamedTuple): + group: str + last: str + first: str + flag: str + +class ArticleInfo(NamedTuple): + number: int + message_id: str + lines: List[bytes] + +def decode_header(header_str: str) -> str: ... + +class _NNTPBase: + encoding: str + errors: str + + host: str + file: IO[bytes] + debugging: int + welcome: str + readermode_afterauth: bool + tls_on: bool + authenticated: bool + nntp_implementation: str + nntp_version: int + def __init__(self, file: IO[bytes], host: str, readermode: Optional[bool] = ..., timeout: float = ...) -> None: ... + def __enter__(self: _SelfT) -> _SelfT: ... + def __exit__(self, *args: Any) -> None: ... + def getwelcome(self) -> str: ... + def getcapabilities(self) -> Dict[str, List[str]]: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def capabilities(self) -> Tuple[str, Dict[str, List[str]]]: ... + def newgroups(self, date: Union[datetime.date, datetime.datetime], *, file: _File = ...) -> Tuple[str, List[str]]: ... + def newnews( + self, group: str, date: Union[datetime.date, datetime.datetime], *, file: _File = ... + ) -> Tuple[str, List[str]]: ... + def list(self, group_pattern: Optional[str] = ..., *, file: _File = ...) -> Tuple[str, List[str]]: ... + def description(self, group: str) -> str: ... + def descriptions(self, group_pattern: str) -> Tuple[str, Dict[str, str]]: ... + def group(self, name: str) -> Tuple[str, int, int, int, str]: ... + def help(self, *, file: _File = ...) -> Tuple[str, List[str]]: ... + def stat(self, message_spec: Any = ...) -> Tuple[str, int, str]: ... + def next(self) -> Tuple[str, int, str]: ... + def last(self) -> Tuple[str, int, str]: ... + def head(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def body(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def article(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def slave(self) -> str: ... + def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> Tuple[str, List[str]]: ... + def xover(self, start: int, end: int, *, file: _File = ...) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... + def over( + self, message_spec: Union[None, str, List[Any], Tuple[Any, ...]], *, file: _File = ... + ) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... + def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... + def xpath(self, id: Any) -> Tuple[str, str]: ... + def date(self) -> Tuple[str, datetime.datetime]: ... + def post(self, data: Union[bytes, Iterable[bytes]]) -> str: ... + def ihave(self, message_id: Any, data: Union[bytes, Iterable[bytes]]) -> str: ... + def quit(self) -> str: ... + def login(self, user: Optional[str] = ..., password: Optional[str] = ..., usenetrc: bool = ...) -> None: ... + def starttls(self, context: Optional[ssl.SSLContext] = ...) -> None: ... + +class NNTP(_NNTPBase): + port: int + sock: socket.socket + def __init__( + self, + host: str, + port: int = ..., + user: Optional[str] = ..., + password: Optional[str] = ..., + readermode: Optional[bool] = ..., + usenetrc: bool = ..., + timeout: float = ..., + ) -> None: ... + +class NNTP_SSL(_NNTPBase): + sock: socket.socket + def __init__( + self, + host: str, + port: int = ..., + user: Optional[str] = ..., + password: Optional[str] = ..., + ssl_context: Optional[ssl.SSLContext] = ..., + readermode: Optional[bool] = ..., + usenetrc: bool = ..., + timeout: float = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ntpath.pyi b/mypy/typeshed/stdlib/@python2/ntpath.pyi index f096428602d4..07bd9653efd9 100644 --- a/mypy/typeshed/stdlib/@python2/ntpath.pyi +++ b/mypy/typeshed/stdlib/@python2/ntpath.pyi @@ -1,6 +1,5 @@ import os import sys -from _typeshed import AnyPath, BytesPath, StrPath from genericpath import exists as exists from typing import Any, AnyStr, Callable, List, Optional, Sequence, Text, Tuple, TypeVar, overload @@ -39,20 +38,20 @@ else: # NOTE: Empty lists results in '' (str) regardless of contained type. # Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes # So, fall back to Any -def commonprefix(m: Sequence[AnyPath]) -> Any: ... -def lexists(path: AnyPath) -> bool: ... +def commonprefix(m: Sequence[Text]) -> Any: ... +def lexists(path: Text) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: AnyPath) -> float: ... -def getmtime(filename: AnyPath) -> float: ... -def getctime(filename: AnyPath) -> float: ... -def getsize(filename: AnyPath) -> int: ... -def isabs(s: AnyPath) -> bool: ... -def isfile(path: AnyPath) -> bool: ... -def isdir(s: AnyPath) -> bool: ... -def islink(path: AnyPath) -> bool: ... -def ismount(path: AnyPath) -> bool: ... +def getatime(filename: Text) -> float: ... +def getmtime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... +def getsize(filename: Text) -> int: ... +def isabs(s: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def islink(path: Text) -> bool: ... +def ismount(path: Text) -> bool: ... # Make sure signatures are disjunct, and allow combinations of bytes and unicode. # (Since Python 2 allows that, too) @@ -61,18 +60,18 @@ def ismount(path: AnyPath) -> bool: ... @overload def join(__p1: bytes, *p: bytes) -> bytes: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload -def join(__p1: Text, *p: AnyPath) -> Text: ... +def join(__p1: Text, *p: Text) -> Text: ... @overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +def relpath(path: str, start: Optional[str] = ...) -> str: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... -def samefile(f1: AnyPath, f2: AnyPath) -> bool: ... +def relpath(path: Text, start: Optional[Text] = ...) -> Text: ... +def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/numbers.pyi b/mypy/typeshed/stdlib/@python2/numbers.pyi new file mode 100644 index 000000000000..fa0c0a17b8a7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/numbers.pyi @@ -0,0 +1,119 @@ +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. + +from abc import ABCMeta, abstractmethod +from typing import Any, Optional, SupportsFloat + +class Number(metaclass=ABCMeta): + @abstractmethod + def __hash__(self) -> int: ... + +class Complex(Number): + @abstractmethod + def __complex__(self) -> complex: ... + def __nonzero__(self) -> bool: ... + @property + @abstractmethod + def real(self) -> Any: ... + @property + @abstractmethod + def imag(self) -> Any: ... + @abstractmethod + def __add__(self, other: Any) -> Any: ... + @abstractmethod + def __radd__(self, other: Any) -> Any: ... + @abstractmethod + def __neg__(self) -> Any: ... + @abstractmethod + def __pos__(self) -> Any: ... + def __sub__(self, other: Any) -> Any: ... + def __rsub__(self, other: Any) -> Any: ... + @abstractmethod + def __mul__(self, other: Any) -> Any: ... + @abstractmethod + def __rmul__(self, other: Any) -> Any: ... + @abstractmethod + def __div__(self, other): ... + @abstractmethod + def __rdiv__(self, other): ... + @abstractmethod + def __truediv__(self, other: Any) -> Any: ... + @abstractmethod + def __rtruediv__(self, other: Any) -> Any: ... + @abstractmethod + def __pow__(self, exponent: Any) -> Any: ... + @abstractmethod + def __rpow__(self, base: Any) -> Any: ... + def __abs__(self) -> Real: ... + def conjugate(self) -> Any: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +class Real(Complex, SupportsFloat): + @abstractmethod + def __float__(self) -> float: ... + @abstractmethod + def __trunc__(self) -> int: ... + def __divmod__(self, other: Any) -> Any: ... + def __rdivmod__(self, other: Any) -> Any: ... + @abstractmethod + def __floordiv__(self, other: Any) -> int: ... + @abstractmethod + def __rfloordiv__(self, other: Any) -> int: ... + @abstractmethod + def __mod__(self, other: Any) -> Any: ... + @abstractmethod + def __rmod__(self, other: Any) -> Any: ... + @abstractmethod + def __lt__(self, other: Any) -> bool: ... + @abstractmethod + def __le__(self, other: Any) -> bool: ... + def __complex__(self) -> complex: ... + @property + def real(self) -> Any: ... + @property + def imag(self) -> Any: ... + def conjugate(self) -> Any: ... + +class Rational(Real): + @property + @abstractmethod + def numerator(self) -> int: ... + @property + @abstractmethod + def denominator(self) -> int: ... + def __float__(self) -> float: ... + +class Integral(Rational): + @abstractmethod + def __long__(self) -> long: ... + def __index__(self) -> int: ... + @abstractmethod + def __pow__(self, exponent: Any, modulus: Optional[Any] = ...) -> Any: ... + @abstractmethod + def __lshift__(self, other: Any) -> Any: ... + @abstractmethod + def __rlshift__(self, other: Any) -> Any: ... + @abstractmethod + def __rshift__(self, other: Any) -> Any: ... + @abstractmethod + def __rrshift__(self, other: Any) -> Any: ... + @abstractmethod + def __and__(self, other: Any) -> Any: ... + @abstractmethod + def __rand__(self, other: Any) -> Any: ... + @abstractmethod + def __xor__(self, other: Any) -> Any: ... + @abstractmethod + def __rxor__(self, other: Any) -> Any: ... + @abstractmethod + def __or__(self, other: Any) -> Any: ... + @abstractmethod + def __ror__(self, other: Any) -> Any: ... + @abstractmethod + def __invert__(self) -> Any: ... + def __float__(self) -> float: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/opcode.pyi b/mypy/typeshed/stdlib/@python2/opcode.pyi new file mode 100644 index 000000000000..893dd7c7df9c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/opcode.pyi @@ -0,0 +1,15 @@ +from typing import Dict, List, Sequence + +cmp_op: Sequence[str] +hasconst: List[int] +hasname: List[int] +hasjrel: List[int] +hasjabs: List[int] +haslocal: List[int] +hascompare: List[int] +hasfree: List[int] +opname: List[str] + +opmap: Dict[str, int] +HAVE_ARGUMENT: int +EXTENDED_ARG: int diff --git a/mypy/typeshed/stdlib/@python2/operator.pyi b/mypy/typeshed/stdlib/@python2/operator.pyi new file mode 100644 index 000000000000..76a8a9b6bee4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/operator.pyi @@ -0,0 +1,190 @@ +from typing import ( + Any, + Container, + Generic, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + SupportsAbs, + Tuple, + TypeVar, + overload, +) + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_K = TypeVar("_K") +_V = TypeVar("_V") + +def lt(__a: Any, __b: Any) -> Any: ... +def le(__a: Any, __b: Any) -> Any: ... +def eq(__a: Any, __b: Any) -> Any: ... +def ne(__a: Any, __b: Any) -> Any: ... +def ge(__a: Any, __b: Any) -> Any: ... +def gt(__a: Any, __b: Any) -> Any: ... +def __lt__(a: Any, b: Any) -> Any: ... +def __le__(a: Any, b: Any) -> Any: ... +def __eq__(a: Any, b: Any) -> Any: ... +def __ne__(a: Any, b: Any) -> Any: ... +def __ge__(a: Any, b: Any) -> Any: ... +def __gt__(a: Any, b: Any) -> Any: ... +def not_(__a: Any) -> bool: ... +def __not__(a: Any) -> bool: ... +def truth(__a: Any) -> bool: ... +def is_(__a: Any, __b: Any) -> bool: ... +def is_not(__a: Any, __b: Any) -> bool: ... +def abs(__a: SupportsAbs[_T]) -> _T: ... +def __abs__(a: SupportsAbs[_T]) -> _T: ... +def add(__a: Any, __b: Any) -> Any: ... +def __add__(a: Any, b: Any) -> Any: ... +def and_(__a: Any, __b: Any) -> Any: ... +def __and__(a: Any, b: Any) -> Any: ... +def div(a: Any, b: Any) -> Any: ... +def __div__(a: Any, b: Any) -> Any: ... +def floordiv(__a: Any, __b: Any) -> Any: ... +def __floordiv__(a: Any, b: Any) -> Any: ... +def index(__a: Any) -> int: ... +def __index__(a: Any) -> int: ... +def inv(__a: Any) -> Any: ... +def invert(__a: Any) -> Any: ... +def __inv__(a: Any) -> Any: ... +def __invert__(a: Any) -> Any: ... +def lshift(__a: Any, __b: Any) -> Any: ... +def __lshift__(a: Any, b: Any) -> Any: ... +def mod(__a: Any, __b: Any) -> Any: ... +def __mod__(a: Any, b: Any) -> Any: ... +def mul(__a: Any, __b: Any) -> Any: ... +def __mul__(a: Any, b: Any) -> Any: ... +def neg(__a: Any) -> Any: ... +def __neg__(a: Any) -> Any: ... +def or_(__a: Any, __b: Any) -> Any: ... +def __or__(a: Any, b: Any) -> Any: ... +def pos(__a: Any) -> Any: ... +def __pos__(a: Any) -> Any: ... +def pow(__a: Any, __b: Any) -> Any: ... +def __pow__(a: Any, b: Any) -> Any: ... +def rshift(__a: Any, __b: Any) -> Any: ... +def __rshift__(a: Any, b: Any) -> Any: ... +def sub(__a: Any, __b: Any) -> Any: ... +def __sub__(a: Any, b: Any) -> Any: ... +def truediv(__a: Any, __b: Any) -> Any: ... +def __truediv__(a: Any, b: Any) -> Any: ... +def xor(__a: Any, __b: Any) -> Any: ... +def __xor__(a: Any, b: Any) -> Any: ... +def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... +def __concat__(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ... +def contains(__a: Container[Any], __b: Any) -> bool: ... +def __contains__(a: Container[Any], b: Any) -> bool: ... +def countOf(__a: Container[Any], __b: Any) -> int: ... +@overload +def delitem(__a: MutableSequence[Any], __b: int) -> None: ... +@overload +def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... +@overload +def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... +@overload +def __delitem__(a: MutableSequence[Any], b: int) -> None: ... +@overload +def __delitem__(a: MutableSequence[Any], b: slice) -> None: ... +@overload +def __delitem__(a: MutableMapping[_K, Any], b: _K) -> None: ... +def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ... +def __delslice__(a: MutableSequence[Any], b: int, c: int) -> None: ... +@overload +def getitem(__a: Sequence[_T], __b: int) -> _T: ... +@overload +def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... +@overload +def getitem(__a: Mapping[_K, _V], __b: _K) -> _V: ... +@overload +def __getitem__(a: Sequence[_T], b: int) -> _T: ... +@overload +def __getitem__(a: Sequence[_T], b: slice) -> Sequence[_T]: ... +@overload +def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... +def getslice(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... +def __getslice__(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... +def indexOf(__a: Sequence[_T], __b: _T) -> int: ... +def repeat(a: Any, b: int) -> Any: ... +def __repeat__(a: Any, b: int) -> Any: ... +def sequenceIncludes(a: Container[Any], b: Any) -> bool: ... +@overload +def setitem(__a: MutableSequence[_T], __b: int, __c: _T) -> None: ... +@overload +def setitem(__a: MutableSequence[_T], __b: slice, __c: Sequence[_T]) -> None: ... +@overload +def setitem(__a: MutableMapping[_K, _V], __b: _K, __c: _V) -> None: ... +@overload +def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ... +@overload +def __setitem__(a: MutableSequence[_T], b: slice, c: Sequence[_T]) -> None: ... +@overload +def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... +def setslice(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... +def __setslice__(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... + +class attrgetter(Generic[_T_co]): + @overload + def __new__(cls, attr: str) -> attrgetter[Any]: ... + @overload + def __new__(cls, attr: str, __attr2: str) -> attrgetter[Tuple[Any, Any]]: ... + @overload + def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[Tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[Tuple[Any, Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... + def __call__(self, obj: Any) -> _T_co: ... + +class itemgetter(Generic[_T_co]): + @overload + def __new__(cls, item: Any) -> itemgetter[Any]: ... + @overload + def __new__(cls, item: Any, __item2: Any) -> itemgetter[Tuple[Any, Any]]: ... + @overload + def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[Tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[Tuple[Any, Any, Any, Any]]: ... + @overload + def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... + def __call__(self, obj: Any) -> _T_co: ... + +class methodcaller: + def __init__(self, __name: str, *args: Any, **kwargs: Any) -> None: ... + def __call__(self, obj: Any) -> Any: ... + +def iadd(__a: Any, __b: Any) -> Any: ... +def __iadd__(a: Any, b: Any) -> Any: ... +def iand(__a: Any, __b: Any) -> Any: ... +def __iand__(a: Any, b: Any) -> Any: ... +def iconcat(__a: Any, __b: Any) -> Any: ... +def __iconcat__(a: Any, b: Any) -> Any: ... +def idiv(a: Any, b: Any) -> Any: ... +def __idiv__(a: Any, b: Any) -> Any: ... +def ifloordiv(__a: Any, __b: Any) -> Any: ... +def __ifloordiv__(a: Any, b: Any) -> Any: ... +def ilshift(__a: Any, __b: Any) -> Any: ... +def __ilshift__(a: Any, b: Any) -> Any: ... +def imod(__a: Any, __b: Any) -> Any: ... +def __imod__(a: Any, b: Any) -> Any: ... +def imul(__a: Any, __b: Any) -> Any: ... +def __imul__(a: Any, b: Any) -> Any: ... +def ior(__a: Any, __b: Any) -> Any: ... +def __ior__(a: Any, b: Any) -> Any: ... +def ipow(__a: Any, __b: Any) -> Any: ... +def __ipow__(a: Any, b: Any) -> Any: ... +def irepeat(a: Any, b: int) -> Any: ... +def __irepeat__(a: Any, b: int) -> Any: ... +def irshift(__a: Any, __b: Any) -> Any: ... +def __irshift__(a: Any, b: Any) -> Any: ... +def isub(__a: Any, __b: Any) -> Any: ... +def __isub__(a: Any, b: Any) -> Any: ... +def itruediv(__a: Any, __b: Any) -> Any: ... +def __itruediv__(a: Any, b: Any) -> Any: ... +def ixor(__a: Any, __b: Any) -> Any: ... +def __ixor__(a: Any, b: Any) -> Any: ... +def isCallable(x: Any) -> bool: ... +def isMappingType(x: Any) -> bool: ... +def isNumberType(x: Any) -> bool: ... +def isSequenceType(x: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/optparse.pyi b/mypy/typeshed/stdlib/@python2/optparse.pyi new file mode 100644 index 000000000000..62ae8ef8a8bf --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/optparse.pyi @@ -0,0 +1,231 @@ +from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, Union, overload + +# See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g +_Text = Union[str, unicode] + +NO_DEFAULT: Tuple[_Text, ...] +SUPPRESS_HELP: _Text +SUPPRESS_USAGE: _Text + +def check_builtin(option: Option, opt: Any, value: _Text) -> Any: ... +def check_choice(option: Option, opt: Any, value: _Text) -> Any: ... +def isbasestring(x: Any) -> bool: ... + +class OptParseError(Exception): + msg: _Text + def __init__(self, msg: _Text) -> None: ... + +class BadOptionError(OptParseError): + opt_str: _Text + def __init__(self, opt_str: _Text) -> None: ... + +class AmbiguousOptionError(BadOptionError): + possibilities: Iterable[_Text] + def __init__(self, opt_str: _Text, possibilities: Sequence[_Text]) -> None: ... + +class OptionError(OptParseError): + msg: _Text + option_id: _Text + def __init__(self, msg: _Text, option: Option) -> None: ... + +class OptionConflictError(OptionError): ... +class OptionValueError(OptParseError): ... + +class HelpFormatter: + NO_DEFAULT_VALUE: _Text + _long_opt_fmt: _Text + _short_opt_fmt: _Text + current_indent: int + default_tag: _Text + help_position: Any + help_width: Any + indent_increment: int + level: int + max_help_position: int + option_strings: Dict[Option, _Text] + parser: OptionParser + short_first: Any + width: int + def __init__(self, indent_increment: int, max_help_position: int, width: Optional[int], short_first: int) -> None: ... + def dedent(self) -> None: ... + def expand_default(self, option: Option) -> _Text: ... + def format_description(self, description: _Text) -> _Text: ... + def format_epilog(self, epilog: _Text) -> _Text: ... + def format_heading(self, heading: Any) -> _Text: ... + def format_option(self, option: Option) -> _Text: ... + def format_option_strings(self, option: Option) -> _Text: ... + def format_usage(self, usage: Any) -> _Text: ... + def indent(self) -> None: ... + def set_long_opt_delimiter(self, delim: _Text) -> None: ... + def set_parser(self, parser: OptionParser) -> None: ... + def set_short_opt_delimiter(self, delim: _Text) -> None: ... + def store_option_strings(self, parser: OptionParser) -> None: ... + +class IndentedHelpFormatter(HelpFormatter): + def __init__( + self, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ..., short_first: int = ... + ) -> None: ... + def format_heading(self, heading: _Text) -> _Text: ... + def format_usage(self, usage: _Text) -> _Text: ... + +class TitledHelpFormatter(HelpFormatter): + def __init__( + self, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ..., short_first: int = ... + ) -> None: ... + def format_heading(self, heading: _Text) -> _Text: ... + def format_usage(self, usage: _Text) -> _Text: ... + +class Option: + ACTIONS: Tuple[_Text, ...] + ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] + ATTRS: List[_Text] + CHECK_METHODS: Optional[List[Callable[..., Any]]] + CONST_ACTIONS: Tuple[_Text, ...] + STORE_ACTIONS: Tuple[_Text, ...] + TYPED_ACTIONS: Tuple[_Text, ...] + TYPES: Tuple[_Text, ...] + TYPE_CHECKER: Dict[_Text, Callable[..., Any]] + _long_opts: List[_Text] + _short_opts: List[_Text] + action: _Text + dest: Optional[_Text] + default: Any + nargs: int + type: Any + callback: Optional[Callable[..., Any]] + callback_args: Optional[Tuple[Any, ...]] + callback_kwargs: Optional[Dict[_Text, Any]] + help: Optional[_Text] + metavar: Optional[_Text] + def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... + def _check_action(self) -> None: ... + def _check_callback(self) -> None: ... + def _check_choice(self) -> None: ... + def _check_const(self) -> None: ... + def _check_dest(self) -> None: ... + def _check_nargs(self) -> None: ... + def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... + def _check_type(self) -> None: ... + def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... + def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... + def check_value(self, opt: _Text, value: Any) -> Any: ... + def convert_value(self, opt: _Text, value: Any) -> Any: ... + def get_opt_string(self) -> _Text: ... + def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def takes_value(self) -> bool: ... + +make_option = Option + +class OptionContainer: + _long_opt: Dict[_Text, Option] + _short_opt: Dict[_Text, Option] + conflict_handler: _Text + defaults: Dict[_Text, Any] + description: Any + option_class: Type[Option] + def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... + def _check_conflict(self, option: Any) -> None: ... + def _create_option_mappings(self) -> None: ... + def _share_option_mappings(self, parser: OptionParser) -> None: ... + @overload + def add_option(self, opt: Option) -> Option: ... + @overload + def add_option(self, *args: Optional[_Text], **kwargs: Any) -> Any: ... + def add_options(self, option_list: Iterable[Option]) -> None: ... + def destroy(self) -> None: ... + def format_description(self, formatter: Optional[HelpFormatter]) -> Any: ... + def format_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... + def format_option_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... + def get_description(self) -> Any: ... + def get_option(self, opt_str: _Text) -> Optional[Option]: ... + def has_option(self, opt_str: _Text) -> bool: ... + def remove_option(self, opt_str: _Text) -> None: ... + def set_conflict_handler(self, handler: Any) -> None: ... + def set_description(self, description: Any) -> None: ... + +class OptionGroup(OptionContainer): + option_list: List[Option] + parser: OptionParser + title: _Text + def __init__(self, parser: OptionParser, title: _Text, description: Optional[_Text] = ...) -> None: ... + def _create_option_list(self) -> None: ... + def set_title(self, title: _Text) -> None: ... + +class Values: + def __init__(self, defaults: Optional[Mapping[str, Any]] = ...) -> None: ... + def _update(self, dict: Mapping[_Text, Any], mode: Any) -> None: ... + def _update_careful(self, dict: Mapping[_Text, Any]) -> None: ... + def _update_loose(self, dict: Mapping[_Text, Any]) -> None: ... + def ensure_value(self, attr: _Text, value: Any) -> Any: ... + def read_file(self, filename: _Text, mode: _Text = ...) -> None: ... + def read_module(self, modname: _Text, mode: _Text = ...) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class OptionParser(OptionContainer): + allow_interspersed_args: bool + epilog: Optional[_Text] + formatter: HelpFormatter + largs: Optional[List[_Text]] + option_groups: List[OptionGroup] + option_list: List[Option] + process_default_values: Any + prog: Optional[_Text] + rargs: Optional[List[Any]] + standard_option_list: List[Option] + usage: Optional[_Text] + values: Optional[Values] + version: _Text + def __init__( + self, + usage: Optional[_Text] = ..., + option_list: Optional[Iterable[Option]] = ..., + option_class: Type[Option] = ..., + version: Optional[_Text] = ..., + conflict_handler: _Text = ..., + description: Optional[_Text] = ..., + formatter: Optional[HelpFormatter] = ..., + add_help_option: bool = ..., + prog: Optional[_Text] = ..., + epilog: Optional[_Text] = ..., + ) -> None: ... + def _add_help_option(self) -> None: ... + def _add_version_option(self) -> None: ... + def _create_option_list(self) -> None: ... + def _get_all_options(self) -> List[Option]: ... + def _get_args(self, args: Iterable[Any]) -> List[Any]: ... + def _init_parsing_state(self) -> None: ... + def _match_long_opt(self, opt: _Text) -> _Text: ... + def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... + def _process_args(self, largs: List[Any], rargs: List[Any], values: Values) -> None: ... + def _process_long_opt(self, rargs: List[Any], values: Any) -> None: ... + def _process_short_opts(self, rargs: List[Any], values: Any) -> None: ... + @overload + def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... + @overload + def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... + def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... + def disable_interspersed_args(self) -> None: ... + def enable_interspersed_args(self) -> None: ... + def error(self, msg: _Text) -> None: ... + def exit(self, status: int = ..., msg: Optional[str] = ...) -> None: ... + def expand_prog_name(self, s: Optional[_Text]) -> Any: ... + def format_epilog(self, formatter: HelpFormatter) -> Any: ... + def format_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... + def format_option_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... + def get_default_values(self) -> Values: ... + def get_option_group(self, opt_str: _Text) -> Any: ... + def get_prog_name(self) -> _Text: ... + def get_usage(self) -> _Text: ... + def get_version(self) -> _Text: ... + def parse_args( + self, args: Optional[Sequence[AnyStr]] = ..., values: Optional[Values] = ... + ) -> Tuple[Values, List[AnyStr]]: ... + def print_usage(self, file: Optional[IO[str]] = ...) -> None: ... + def print_help(self, file: Optional[IO[str]] = ...) -> None: ... + def print_version(self, file: Optional[IO[str]] = ...) -> None: ... + def set_default(self, dest: Any, value: Any) -> None: ... + def set_defaults(self, **kwargs: Any) -> None: ... + def set_process_default_values(self, process: Any) -> None: ... + def set_usage(self, usage: _Text) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/os/__init__.pyi b/mypy/typeshed/stdlib/@python2/os/__init__.pyi index 7b32f5087495..3b4f9698dd14 100644 --- a/mypy/typeshed/stdlib/@python2/os/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/os/__init__.pyi @@ -1,7 +1,6 @@ import sys -from _typeshed import AnyPath, FileDescriptorLike +from _typeshed import FileDescriptorLike from builtins import OSError -from io import TextIOWrapper as _TextIOWrapper from posix import listdir as listdir, stat_result as stat_result # TODO: use this, see https://github.com/python/mypy/issues/3078 from typing import ( IO, @@ -18,7 +17,6 @@ from typing import ( NoReturn, Optional, Sequence, - Set, Text, Tuple, TypeVar, @@ -37,15 +35,6 @@ _T = TypeVar("_T") error = OSError -if sys.version_info >= (3, 2): - supports_bytes_environ: bool - -if sys.version_info >= (3, 3): - supports_dir_fd: Set[Callable[..., Any]] - supports_fd: Set[Callable[..., Any]] - supports_effective_ids: Set[Callable[..., Any]] - supports_follow_symlinks: Set[Callable[..., Any]] - SEEK_SET: int SEEK_CUR: int SEEK_END: int @@ -110,9 +99,6 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): def __len__(self) -> int: ... environ: _Environ[str] -if sys.version_info >= (3, 2): - environb: _Environ[bytes] - if sys.platform != "win32": # Unix only confstr_names: Dict[str, int] @@ -212,44 +198,40 @@ def dup2(fd: int, fd2: int) -> None: ... def fstat(fd: int) -> Any: ... def fsync(fd: FileDescriptorLike) -> None: ... def lseek(fd: int, pos: int, how: int) -> int: ... -def open(file: AnyPath, flags: int, mode: int = ...) -> int: ... +def open(file: Text, flags: int, mode: int = ...) -> int: ... def pipe() -> Tuple[int, int]: ... def read(fd: int, n: int) -> bytes: ... def write(fd: int, string: Union[bytes, buffer]) -> int: ... -def access(path: AnyPath, mode: int) -> bool: ... -def chdir(path: AnyPath) -> None: ... +def access(path: Text, mode: int) -> bool: ... +def chdir(path: Text) -> None: ... def fchdir(fd: FileDescriptorLike) -> None: ... def getcwd() -> str: ... def getcwdu() -> unicode: ... -def chmod(path: AnyPath, mode: int) -> None: ... -def link(src: AnyPath, link_name: AnyPath) -> None: ... -def lstat(path: AnyPath) -> Any: ... -def mknod(filename: AnyPath, mode: int = ..., device: int = ...) -> None: ... +def chmod(path: Text, mode: int) -> None: ... +def link(src: Text, link_name: Text) -> None: ... +def lstat(path: Text) -> Any: ... +def mknod(filename: Text, mode: int = ..., device: int = ...) -> None: ... def major(device: int) -> int: ... def minor(device: int) -> int: ... def makedev(major: int, minor: int) -> int: ... -def mkdir(path: AnyPath, mode: int = ...) -> None: ... -def makedirs(path: AnyPath, mode: int = ...) -> None: ... +def mkdir(path: Text, mode: int = ...) -> None: ... +def makedirs(path: Text, mode: int = ...) -> None: ... def readlink(path: AnyStr) -> AnyStr: ... -def remove(path: AnyPath) -> None: ... -def removedirs(path: AnyPath) -> None: ... -def rename(src: AnyPath, dst: AnyPath) -> None: ... -def renames(old: AnyPath, new: AnyPath) -> None: ... -def rmdir(path: AnyPath) -> None: ... -def stat(path: AnyPath) -> Any: ... +def remove(path: Text) -> None: ... +def removedirs(path: Text) -> None: ... +def rename(src: Text, dst: Text) -> None: ... +def renames(old: Text, new: Text) -> None: ... +def rmdir(path: Text) -> None: ... +def stat(path: Text) -> Any: ... @overload def stat_float_times() -> bool: ... @overload def stat_float_times(newvalue: bool) -> None: ... -def symlink(source: AnyPath, link_name: AnyPath) -> None: ... -def unlink(path: AnyPath) -> None: ... +def symlink(source: Text, link_name: Text) -> None: ... +def unlink(path: Text) -> None: ... # TODO: add ns, dir_fd, follow_symlinks argument -if sys.version_info >= (3, 0): - def utime(path: AnyPath, times: Optional[Tuple[float, float]] = ...) -> None: ... - -else: - def utime(path: AnyPath, times: Optional[Tuple[float, float]]) -> None: ... +def utime(path: Text, times: Optional[Tuple[float, float]]) -> None: ... if sys.platform != "win32": # Unix only @@ -265,47 +247,37 @@ if sys.platform != "win32": def tcgetpgrp(fd: int) -> int: ... def tcsetpgrp(fd: int, pg: int) -> None: ... def ttyname(fd: int) -> str: ... - def chflags(path: AnyPath, flags: int) -> None: ... - def chroot(path: AnyPath) -> None: ... - def chown(path: AnyPath, uid: int, gid: int) -> None: ... - def lchflags(path: AnyPath, flags: int) -> None: ... - def lchmod(path: AnyPath, mode: int) -> None: ... - def lchown(path: AnyPath, uid: int, gid: int) -> None: ... - def mkfifo(path: AnyPath, mode: int = ...) -> None: ... - def pathconf(path: AnyPath, name: Union[str, int]) -> int: ... - def statvfs(path: AnyPath) -> _StatVFS: ... - -if sys.version_info >= (3, 6): - def walk( - top: Union[AnyStr, PathLike[AnyStr]], - topdown: bool = ..., - onerror: Optional[Callable[[OSError], Any]] = ..., - followlinks: bool = ..., - ) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... - -else: - def walk( - top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ..., followlinks: bool = ... - ) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... - + def chflags(path: Text, flags: int) -> None: ... + def chroot(path: Text) -> None: ... + def chown(path: Text, uid: int, gid: int) -> None: ... + def lchflags(path: Text, flags: int) -> None: ... + def lchmod(path: Text, mode: int) -> None: ... + def lchown(path: Text, uid: int, gid: int) -> None: ... + def mkfifo(path: Text, mode: int = ...) -> None: ... + def pathconf(path: Text, name: Union[str, int]) -> int: ... + def statvfs(path: Text) -> _StatVFS: ... + +def walk( + top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ..., followlinks: bool = ... +) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... def abort() -> NoReturn: ... # These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: AnyPath, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... -def execlp(file: AnyPath, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... +def execl(file: Text, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... +def execlp(file: Text, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... # These are: execle(file, *args, env) but env is pulled from the last element of the args. -def execle(file: AnyPath, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... -def execlpe(file: AnyPath, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... +def execle(file: Text, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... +def execlpe(file: Text, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. _ExecVArgs = Union[Tuple[Union[bytes, Text], ...], List[bytes], List[Text], List[Union[bytes, Text]]] -def execv(path: AnyPath, args: _ExecVArgs) -> NoReturn: ... -def execve(path: AnyPath, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... -def execvp(file: AnyPath, args: _ExecVArgs) -> NoReturn: ... -def execvpe(file: AnyPath, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... +def execv(path: Text, args: _ExecVArgs) -> NoReturn: ... +def execve(path: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... +def execvp(file: Text, args: _ExecVArgs) -> NoReturn: ... +def execvpe(file: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... def _exit(n: int) -> NoReturn: ... def kill(pid: int, sig: int) -> None: ... @@ -317,36 +289,28 @@ if sys.platform != "win32": def nice(increment: int) -> int: ... def plock(op: int) -> None: ... # ???op is int? -if sys.version_info >= (3, 0): - class popen(_TextIOWrapper): - # TODO 'b' modes or bytes command not accepted? - def __init__(self, command: str, mode: str = ..., bufsize: int = ...) -> None: ... - def close(self) -> Any: ... # may return int - -else: - def popen(command: str, *args, **kwargs) -> IO[Any]: ... - def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... - def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ... - def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... - -def spawnl(mode: int, path: AnyPath, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... -def spawnle(mode: int, path: AnyPath, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise sig -def spawnv(mode: int, path: AnyPath, args: List[Union[bytes, Text]]) -> int: ... -def spawnve(mode: int, path: AnyPath, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... -def system(command: AnyPath) -> int: ... +def popen(command: str, *args, **kwargs) -> IO[Any]: ... +def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... +def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ... +def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... +def spawnl(mode: int, path: Text, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... +def spawnle(mode: int, path: Text, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise sig +def spawnv(mode: int, path: Text, args: List[Union[bytes, Text]]) -> int: ... +def spawnve(mode: int, path: Text, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... +def system(command: Text) -> int: ... def times() -> Tuple[float, float, float, float, float]: ... def waitpid(pid: int, options: int) -> Tuple[int, int]: ... def urandom(n: int) -> bytes: ... if sys.platform == "win32": - def startfile(path: AnyPath, operation: Optional[str] = ...) -> None: ... + def startfile(path: Text, operation: Optional[str] = ...) -> None: ... else: # Unix only - def spawnlp(mode: int, file: AnyPath, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... - def spawnlpe(mode: int, file: AnyPath, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: AnyPath, args: List[Union[bytes, Text]]) -> int: ... - def spawnvpe(mode: int, file: AnyPath, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... + def spawnlp(mode: int, file: Text, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... + def spawnlpe(mode: int, file: Text, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise signature + def spawnvp(mode: int, file: Text, args: List[Union[bytes, Text]]) -> int: ... + def spawnvpe(mode: int, file: Text, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... def wait() -> Tuple[int, int]: ... def wait3(options: int) -> Tuple[int, int, Any]: ... def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... @@ -362,18 +326,9 @@ else: def getloadavg() -> Tuple[float, float, float]: ... def sysconf(name: Union[str, int]) -> int: ... -if sys.version_info >= (3, 0): - def sched_getaffinity(id: int) -> Set[int]: ... - -if sys.version_info >= (3, 3): - class waitresult: - si_pid: int - def waitid(idtype: int, id: int, options: int) -> waitresult: ... - -if sys.version_info < (3, 0): - def tmpfile() -> IO[Any]: ... - def tmpnam() -> str: ... - def tempnam(dir: str = ..., prefix: str = ...) -> str: ... +def tmpfile() -> IO[Any]: ... +def tmpnam() -> str: ... +def tempnam(dir: str = ..., prefix: str = ...) -> str: ... P_ALL: int WEXITED: int diff --git a/mypy/typeshed/stdlib/@python2/os/path.pyi b/mypy/typeshed/stdlib/@python2/os/path.pyi index c89bc8b69e8d..124385f1301d 100644 --- a/mypy/typeshed/stdlib/@python2/os/path.pyi +++ b/mypy/typeshed/stdlib/@python2/os/path.pyi @@ -1,6 +1,5 @@ import os import sys -from _typeshed import AnyPath, BytesPath, StrPath from typing import Any, AnyStr, Callable, List, Optional, Sequence, Text, Tuple, TypeVar, overload _T = TypeVar("_T") @@ -38,21 +37,21 @@ else: # NOTE: Empty lists results in '' (str) regardless of contained type. # Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes # So, fall back to Any -def commonprefix(m: Sequence[AnyPath]) -> Any: ... -def exists(path: AnyPath) -> bool: ... -def lexists(path: AnyPath) -> bool: ... +def commonprefix(m: Sequence[Text]) -> Any: ... +def exists(path: Text) -> bool: ... +def lexists(path: Text) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: AnyPath) -> float: ... -def getmtime(filename: AnyPath) -> float: ... -def getctime(filename: AnyPath) -> float: ... -def getsize(filename: AnyPath) -> int: ... -def isabs(s: AnyPath) -> bool: ... -def isfile(path: AnyPath) -> bool: ... -def isdir(s: AnyPath) -> bool: ... -def islink(path: AnyPath) -> bool: ... -def ismount(path: AnyPath) -> bool: ... +def getatime(filename: Text) -> float: ... +def getmtime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... +def getsize(filename: Text) -> int: ... +def isabs(s: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def islink(path: Text) -> bool: ... +def ismount(path: Text) -> bool: ... # Make sure signatures are disjunct, and allow combinations of bytes and unicode. # (Since Python 2 allows that, too) @@ -61,18 +60,18 @@ def ismount(path: AnyPath) -> bool: ... @overload def join(__p1: bytes, *p: bytes) -> bytes: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload -def join(__p1: Text, *p: AnyPath) -> Text: ... +def join(__p1: Text, *p: Text) -> Text: ... @overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +def relpath(path: str, start: Optional[str] = ...) -> str: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... -def samefile(f1: AnyPath, f2: AnyPath) -> bool: ... +def relpath(path: Text, start: Optional[Text] = ...) -> Text: ... +def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi index f096428602d4..07bd9653efd9 100644 --- a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi +++ b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi @@ -1,6 +1,5 @@ import os import sys -from _typeshed import AnyPath, BytesPath, StrPath from genericpath import exists as exists from typing import Any, AnyStr, Callable, List, Optional, Sequence, Text, Tuple, TypeVar, overload @@ -39,20 +38,20 @@ else: # NOTE: Empty lists results in '' (str) regardless of contained type. # Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes # So, fall back to Any -def commonprefix(m: Sequence[AnyPath]) -> Any: ... -def lexists(path: AnyPath) -> bool: ... +def commonprefix(m: Sequence[Text]) -> Any: ... +def lexists(path: Text) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: AnyPath) -> float: ... -def getmtime(filename: AnyPath) -> float: ... -def getctime(filename: AnyPath) -> float: ... -def getsize(filename: AnyPath) -> int: ... -def isabs(s: AnyPath) -> bool: ... -def isfile(path: AnyPath) -> bool: ... -def isdir(s: AnyPath) -> bool: ... -def islink(path: AnyPath) -> bool: ... -def ismount(path: AnyPath) -> bool: ... +def getatime(filename: Text) -> float: ... +def getmtime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... +def getsize(filename: Text) -> int: ... +def isabs(s: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def islink(path: Text) -> bool: ... +def ismount(path: Text) -> bool: ... # Make sure signatures are disjunct, and allow combinations of bytes and unicode. # (Since Python 2 allows that, too) @@ -61,18 +60,18 @@ def ismount(path: AnyPath) -> bool: ... @overload def join(__p1: bytes, *p: bytes) -> bytes: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload -def join(__p1: Text, *p: AnyPath) -> Text: ... +def join(__p1: Text, *p: Text) -> Text: ... @overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +def relpath(path: str, start: Optional[str] = ...) -> str: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... -def samefile(f1: AnyPath, f2: AnyPath) -> bool: ... +def relpath(path: Text, start: Optional[Text] = ...) -> Text: ... +def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi new file mode 100644 index 000000000000..af3e2c210930 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi @@ -0,0 +1,131 @@ +from typing import Any, List, overload +from typing_extensions import Literal + +AFMT_AC3: int +AFMT_A_LAW: int +AFMT_IMA_ADPCM: int +AFMT_MPEG: int +AFMT_MU_LAW: int +AFMT_QUERY: int +AFMT_S16_BE: int +AFMT_S16_LE: int +AFMT_S16_NE: int +AFMT_S8: int +AFMT_U16_BE: int +AFMT_U16_LE: int +AFMT_U8: int +SNDCTL_COPR_HALT: int +SNDCTL_COPR_LOAD: int +SNDCTL_COPR_RCODE: int +SNDCTL_COPR_RCVMSG: int +SNDCTL_COPR_RDATA: int +SNDCTL_COPR_RESET: int +SNDCTL_COPR_RUN: int +SNDCTL_COPR_SENDMSG: int +SNDCTL_COPR_WCODE: int +SNDCTL_COPR_WDATA: int +SNDCTL_DSP_BIND_CHANNEL: int +SNDCTL_DSP_CHANNELS: int +SNDCTL_DSP_GETBLKSIZE: int +SNDCTL_DSP_GETCAPS: int +SNDCTL_DSP_GETCHANNELMASK: int +SNDCTL_DSP_GETFMTS: int +SNDCTL_DSP_GETIPTR: int +SNDCTL_DSP_GETISPACE: int +SNDCTL_DSP_GETODELAY: int +SNDCTL_DSP_GETOPTR: int +SNDCTL_DSP_GETOSPACE: int +SNDCTL_DSP_GETSPDIF: int +SNDCTL_DSP_GETTRIGGER: int +SNDCTL_DSP_MAPINBUF: int +SNDCTL_DSP_MAPOUTBUF: int +SNDCTL_DSP_NONBLOCK: int +SNDCTL_DSP_POST: int +SNDCTL_DSP_PROFILE: int +SNDCTL_DSP_RESET: int +SNDCTL_DSP_SAMPLESIZE: int +SNDCTL_DSP_SETDUPLEX: int +SNDCTL_DSP_SETFMT: int +SNDCTL_DSP_SETFRAGMENT: int +SNDCTL_DSP_SETSPDIF: int +SNDCTL_DSP_SETSYNCRO: int +SNDCTL_DSP_SETTRIGGER: int +SNDCTL_DSP_SPEED: int +SNDCTL_DSP_STEREO: int +SNDCTL_DSP_SUBDIVIDE: int +SNDCTL_DSP_SYNC: int +SNDCTL_FM_4OP_ENABLE: int +SNDCTL_FM_LOAD_INSTR: int +SNDCTL_MIDI_INFO: int +SNDCTL_MIDI_MPUCMD: int +SNDCTL_MIDI_MPUMODE: int +SNDCTL_MIDI_PRETIME: int +SNDCTL_SEQ_CTRLRATE: int +SNDCTL_SEQ_GETINCOUNT: int +SNDCTL_SEQ_GETOUTCOUNT: int +SNDCTL_SEQ_GETTIME: int +SNDCTL_SEQ_NRMIDIS: int +SNDCTL_SEQ_NRSYNTHS: int +SNDCTL_SEQ_OUTOFBAND: int +SNDCTL_SEQ_PANIC: int +SNDCTL_SEQ_PERCMODE: int +SNDCTL_SEQ_RESET: int +SNDCTL_SEQ_RESETSAMPLES: int +SNDCTL_SEQ_SYNC: int +SNDCTL_SEQ_TESTMIDI: int +SNDCTL_SEQ_THRESHOLD: int +SNDCTL_SYNTH_CONTROL: int +SNDCTL_SYNTH_ID: int +SNDCTL_SYNTH_INFO: int +SNDCTL_SYNTH_MEMAVL: int +SNDCTL_SYNTH_REMOVESAMPLE: int +SNDCTL_TMR_CONTINUE: int +SNDCTL_TMR_METRONOME: int +SNDCTL_TMR_SELECT: int +SNDCTL_TMR_SOURCE: int +SNDCTL_TMR_START: int +SNDCTL_TMR_STOP: int +SNDCTL_TMR_TEMPO: int +SNDCTL_TMR_TIMEBASE: int +SOUND_MIXER_ALTPCM: int +SOUND_MIXER_BASS: int +SOUND_MIXER_CD: int +SOUND_MIXER_DIGITAL1: int +SOUND_MIXER_DIGITAL2: int +SOUND_MIXER_DIGITAL3: int +SOUND_MIXER_IGAIN: int +SOUND_MIXER_IMIX: int +SOUND_MIXER_LINE: int +SOUND_MIXER_LINE1: int +SOUND_MIXER_LINE2: int +SOUND_MIXER_LINE3: int +SOUND_MIXER_MIC: int +SOUND_MIXER_MONITOR: int +SOUND_MIXER_NRDEVICES: int +SOUND_MIXER_OGAIN: int +SOUND_MIXER_PCM: int +SOUND_MIXER_PHONEIN: int +SOUND_MIXER_PHONEOUT: int +SOUND_MIXER_RADIO: int +SOUND_MIXER_RECLEV: int +SOUND_MIXER_SPEAKER: int +SOUND_MIXER_SYNTH: int +SOUND_MIXER_TREBLE: int +SOUND_MIXER_VIDEO: int +SOUND_MIXER_VOLUME: int + +control_labels: List[str] +control_names: List[str] + +# TODO: oss_audio_device return type +@overload +def open(mode: Literal["r", "w", "rw"]) -> Any: ... +@overload +def open(device: str, mode: Literal["r", "w", "rw"]) -> Any: ... + +# TODO: oss_mixer_device return type +def openmixer(device: str = ...) -> Any: ... + +class OSSAudioError(Exception): ... + +error = OSSAudioError diff --git a/mypy/typeshed/stdlib/@python2/parser.pyi b/mypy/typeshed/stdlib/@python2/parser.pyi new file mode 100644 index 000000000000..ff8bf039ee80 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/parser.pyi @@ -0,0 +1,21 @@ +from types import CodeType +from typing import Any, List, Sequence, Text, Tuple + +def expr(source: Text) -> STType: ... +def suite(source: Text) -> STType: ... +def sequence2st(sequence: Sequence[Any]) -> STType: ... +def tuple2st(sequence: Sequence[Any]) -> STType: ... +def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... +def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... +def compilest(st: STType, filename: Text = ...) -> CodeType: ... +def isexpr(st: STType) -> bool: ... +def issuite(st: STType) -> bool: ... + +class ParserError(Exception): ... + +class STType: + def compile(self, filename: Text = ...) -> CodeType: ... + def isexpr(self) -> bool: ... + def issuite(self) -> bool: ... + def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... + def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/pdb.pyi b/mypy/typeshed/stdlib/@python2/pdb.pyi new file mode 100644 index 000000000000..ba04e4d28fab --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pdb.pyi @@ -0,0 +1,169 @@ +from bdb import Bdb +from cmd import Cmd +from types import FrameType, TracebackType +from typing import IO, Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Optional, Tuple, TypeVar, Union + +_T = TypeVar("_T") + +line_prefix: str # undocumented + +class Restart(Exception): ... + +def run(statement: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> None: ... +def runeval(expression: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +def runctx(statement: str, globals: Dict[str, Any], locals: Mapping[str, Any]) -> None: ... +def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> Optional[_T]: ... +def set_trace() -> None: ... +def post_mortem(t: Optional[TracebackType] = ...) -> None: ... +def pm() -> None: ... + +class Pdb(Bdb, Cmd): + # Everything here is undocumented, except for __init__ + + commands_resuming: ClassVar[List[str]] + + aliases: Dict[str, str] + mainpyfile: str + _wait_for_mainpyfile: bool + rcLines: List[str] + commands: Dict[int, List[str]] + commands_doprompt: Dict[int, bool] + commands_silent: Dict[int, bool] + commands_defining: bool + commands_bnum: Optional[int] + lineno: Optional[int] + stack: List[Tuple[FrameType, int]] + curindex: int + curframe: Optional[FrameType] + curframe_locals: Mapping[str, Any] + def __init__( + self, + completekey: str = ..., + stdin: Optional[IO[str]] = ..., + stdout: Optional[IO[str]] = ..., + skip: Optional[Iterable[str]] = ..., + ) -> None: ... + def forget(self) -> None: ... + def setup(self, f: Optional[FrameType], tb: Optional[TracebackType]) -> None: ... + def execRcLines(self) -> None: ... + def bp_commands(self, frame: FrameType) -> bool: ... + def interaction(self, frame: Optional[FrameType], traceback: Optional[TracebackType]) -> None: ... + def displayhook(self, obj: object) -> None: ... + def handle_command_def(self, line: str) -> bool: ... + def defaultFile(self) -> str: ... + def lineinfo(self, identifier: str) -> Union[Tuple[None, None, None], Tuple[str, str, int]]: ... + def checkline(self, filename: str, lineno: int) -> int: ... + def _getval(self, arg: str) -> object: ... + def print_stack_trace(self) -> None: ... + def print_stack_entry(self, frame_lineno: Tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... + def lookupmodule(self, filename: str) -> Optional[str]: ... + def _runscript(self, filename: str) -> None: ... + def do_commands(self, arg: str) -> Optional[bool]: ... + def do_break(self, arg: str, temporary: bool = ...) -> Optional[bool]: ... + def do_tbreak(self, arg: str) -> Optional[bool]: ... + def do_enable(self, arg: str) -> Optional[bool]: ... + def do_disable(self, arg: str) -> Optional[bool]: ... + def do_condition(self, arg: str) -> Optional[bool]: ... + def do_ignore(self, arg: str) -> Optional[bool]: ... + def do_clear(self, arg: str) -> Optional[bool]: ... + def do_where(self, arg: str) -> Optional[bool]: ... + def do_up(self, arg: str) -> Optional[bool]: ... + def do_down(self, arg: str) -> Optional[bool]: ... + def do_until(self, arg: str) -> Optional[bool]: ... + def do_step(self, arg: str) -> Optional[bool]: ... + def do_next(self, arg: str) -> Optional[bool]: ... + def do_run(self, arg: str) -> Optional[bool]: ... + def do_return(self, arg: str) -> Optional[bool]: ... + def do_continue(self, arg: str) -> Optional[bool]: ... + def do_jump(self, arg: str) -> Optional[bool]: ... + def do_debug(self, arg: str) -> Optional[bool]: ... + def do_quit(self, arg: str) -> Optional[bool]: ... + def do_EOF(self, arg: str) -> Optional[bool]: ... + def do_args(self, arg: str) -> Optional[bool]: ... + def do_retval(self, arg: str) -> Optional[bool]: ... + def do_p(self, arg: str) -> Optional[bool]: ... + def do_pp(self, arg: str) -> Optional[bool]: ... + def do_list(self, arg: str) -> Optional[bool]: ... + def do_whatis(self, arg: str) -> Optional[bool]: ... + def do_alias(self, arg: str) -> Optional[bool]: ... + def do_unalias(self, arg: str) -> Optional[bool]: ... + def do_help(self, arg: str) -> Optional[bool]: ... + do_b = do_break + do_cl = do_clear + do_w = do_where + do_bt = do_where + do_u = do_up + do_d = do_down + do_unt = do_until + do_s = do_step + do_n = do_next + do_restart = do_run + do_r = do_return + do_c = do_continue + do_cont = do_continue + do_j = do_jump + do_q = do_quit + do_exit = do_quit + do_a = do_args + do_rv = do_retval + do_l = do_list + do_h = do_help + def help_exec(self) -> None: ... + def help_pdb(self) -> None: ... + def help_help(self) -> None: ... + def help_h(self) -> None: ... + def help_where(self) -> None: ... + def help_w(self) -> None: ... + def help_down(self) -> None: ... + def help_d(self) -> None: ... + def help_up(self) -> None: ... + def help_u(self) -> None: ... + def help_break(self) -> None: ... + def help_b(self) -> None: ... + def help_clear(self) -> None: ... + def help_cl(self) -> None: ... + def help_tbreak(self) -> None: ... + def help_enable(self) -> None: ... + def help_disable(self) -> None: ... + def help_ignore(self) -> None: ... + def help_condition(self) -> None: ... + def help_step(self) -> None: ... + def help_s(self) -> None: ... + def help_until(self) -> None: ... + def help_unt(self) -> None: ... + def help_next(self) -> None: ... + def help_n(self) -> None: ... + def help_return(self) -> None: ... + def help_r(self) -> None: ... + def help_continue(self) -> None: ... + def help_cont(self) -> None: ... + def help_c(self) -> None: ... + def help_jump(self) -> None: ... + def help_j(self) -> None: ... + def help_debug(self) -> None: ... + def help_list(self) -> None: ... + def help_l(self) -> None: ... + def help_args(self) -> None: ... + def help_a(self) -> None: ... + def help_p(self) -> None: ... + def help_pp(self) -> None: ... + def help_run(self) -> None: ... + def help_quit(self) -> None: ... + def help_q(self) -> None: ... + def help_whatis(self) -> None: ... + def help_EOF(self) -> None: ... + def help_alias(self) -> None: ... + def help_unalias(self) -> None: ... + def help_commands(self) -> None: ... + help_bt = help_w + help_restart = help_run + help_exit = help_q + +# undocumented + +def find_function(funcname: str, filename: str) -> Optional[Tuple[str, str, int]]: ... +def main() -> None: ... +def help() -> None: ... + +class _rstr(str): + def __repr__(self) -> _rstr: ... diff --git a/mypy/typeshed/stdlib/@python2/pickle.pyi b/mypy/typeshed/stdlib/@python2/pickle.pyi new file mode 100644 index 000000000000..8272caeeed23 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pickle.pyi @@ -0,0 +1,95 @@ +from typing import IO, Any, Callable, Iterator, Optional, Tuple, Type, Union + +HIGHEST_PROTOCOL: int +bytes_types: Tuple[Type[Any], ...] # undocumented + +def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... +def dumps(obj: Any, protocol: Optional[int] = ...) -> bytes: ... +def load(file: IO[bytes]) -> Any: ... +def loads(string: bytes) -> Any: ... + +class PickleError(Exception): ... +class PicklingError(PickleError): ... +class UnpicklingError(PickleError): ... + +_reducedtype = Union[ + str, + Tuple[Callable[..., Any], Tuple[Any, ...]], + Tuple[Callable[..., Any], Tuple[Any, ...], Any], + Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], + Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], +] + +class Pickler: + fast: bool + def __init__(self, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... + def dump(self, __obj: Any) -> None: ... + def clear_memo(self) -> None: ... + def persistent_id(self, obj: Any) -> Any: ... + +class Unpickler: + def __init__(self, file: IO[bytes]) -> None: ... + def load(self) -> Any: ... + def find_class(self, __module_name: str, __global_name: str) -> Any: ... + +MARK: bytes +STOP: bytes +POP: bytes +POP_MARK: bytes +DUP: bytes +FLOAT: bytes +INT: bytes +BININT: bytes +BININT1: bytes +LONG: bytes +BININT2: bytes +NONE: bytes +PERSID: bytes +BINPERSID: bytes +REDUCE: bytes +STRING: bytes +BINSTRING: bytes +SHORT_BINSTRING: bytes +UNICODE: bytes +BINUNICODE: bytes +APPEND: bytes +BUILD: bytes +GLOBAL: bytes +DICT: bytes +EMPTY_DICT: bytes +APPENDS: bytes +GET: bytes +BINGET: bytes +INST: bytes +LONG_BINGET: bytes +LIST: bytes +EMPTY_LIST: bytes +OBJ: bytes +PUT: bytes +BINPUT: bytes +LONG_BINPUT: bytes +SETITEM: bytes +TUPLE: bytes +EMPTY_TUPLE: bytes +SETITEMS: bytes +BINFLOAT: bytes + +TRUE: bytes +FALSE: bytes + +# protocol 2 +PROTO: bytes +NEWOBJ: bytes +EXT1: bytes +EXT2: bytes +EXT4: bytes +TUPLE1: bytes +TUPLE2: bytes +TUPLE3: bytes +NEWTRUE: bytes +NEWFALSE: bytes +LONG1: bytes +LONG4: bytes + +def encode_long(x: int) -> bytes: ... # undocumented +def decode_long(data: bytes) -> int: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/pickletools.pyi b/mypy/typeshed/stdlib/@python2/pickletools.pyi new file mode 100644 index 000000000000..154aaf174f5d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pickletools.pyi @@ -0,0 +1,127 @@ +from typing import IO, Any, Callable, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union + +_Reader = Callable[[IO[bytes]], Any] + +UP_TO_NEWLINE: int +TAKEN_FROM_ARGUMENT1: int +TAKEN_FROM_ARGUMENT4: int + +class ArgumentDescriptor(object): + name: str + n: int + reader: _Reader + doc: str + def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ... + +def read_uint1(f: IO[bytes]) -> int: ... + +uint1: ArgumentDescriptor + +def read_uint2(f: IO[bytes]) -> int: ... + +uint2: ArgumentDescriptor + +def read_int4(f: IO[bytes]) -> int: ... + +int4: ArgumentDescriptor + +def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> Union[bytes, Text]: ... + +stringnl: ArgumentDescriptor + +def read_stringnl_noescape(f: IO[bytes]) -> str: ... + +stringnl_noescape: ArgumentDescriptor + +def read_stringnl_noescape_pair(f: IO[bytes]) -> Text: ... + +stringnl_noescape_pair: ArgumentDescriptor + +def read_string1(f: IO[bytes]) -> str: ... + +string1: ArgumentDescriptor + +def read_string4(f: IO[bytes]) -> str: ... + +string4: ArgumentDescriptor + +def read_unicodestringnl(f: IO[bytes]) -> Text: ... + +unicodestringnl: ArgumentDescriptor + +def read_unicodestring4(f: IO[bytes]) -> Text: ... + +unicodestring4: ArgumentDescriptor + +def read_decimalnl_short(f: IO[bytes]) -> int: ... +def read_decimalnl_long(f: IO[bytes]) -> int: ... + +decimalnl_short: ArgumentDescriptor +decimalnl_long: ArgumentDescriptor + +def read_floatnl(f: IO[bytes]) -> float: ... + +floatnl: ArgumentDescriptor + +def read_float8(f: IO[bytes]) -> float: ... + +float8: ArgumentDescriptor + +def read_long1(f: IO[bytes]) -> int: ... + +long1: ArgumentDescriptor + +def read_long4(f: IO[bytes]) -> int: ... + +long4: ArgumentDescriptor + +class StackObject(object): + name: str + obtype: Union[Type[Any], Tuple[Type[Any], ...]] + doc: str + def __init__(self, name: str, obtype: Union[Type[Any], Tuple[Type[Any], ...]], doc: str) -> None: ... + +pyint: StackObject +pylong: StackObject +pyinteger_or_bool: StackObject +pybool: StackObject +pyfloat: StackObject +pystring: StackObject +pyunicode: StackObject +pynone: StackObject +pytuple: StackObject +pylist: StackObject +pydict: StackObject +anyobject: StackObject +markobject: StackObject +stackslice: StackObject + +class OpcodeInfo(object): + name: str + code: str + arg: Optional[ArgumentDescriptor] + stack_before: List[StackObject] + stack_after: List[StackObject] + proto: int + doc: str + def __init__( + self, + name: str, + code: str, + arg: Optional[ArgumentDescriptor], + stack_before: List[StackObject], + stack_after: List[StackObject], + proto: int, + doc: str, + ) -> None: ... + +opcodes: List[OpcodeInfo] + +def genops(pickle: Union[bytes, IO[bytes]]) -> Iterator[Tuple[OpcodeInfo, Optional[Any], Optional[int]]]: ... +def optimize(p: Union[bytes, IO[bytes]]) -> bytes: ... +def dis( + pickle: Union[bytes, IO[bytes]], + out: Optional[IO[str]] = ..., + memo: Optional[MutableMapping[int, Any]] = ..., + indentlevel: int = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pkgutil.pyi b/mypy/typeshed/stdlib/@python2/pkgutil.pyi new file mode 100644 index 000000000000..5fefef39bd6b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pkgutil.pyi @@ -0,0 +1,27 @@ +from _typeshed import SupportsRead +from typing import IO, Any, Callable, Iterable, Iterator, List, Optional, Tuple, Union + +Loader = Any +MetaPathFinder = Any +PathEntryFinder = Any + +_ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] + +def extend_path(path: List[str], name: str) -> List[str]: ... + +class ImpImporter: + def __init__(self, path: Optional[str] = ...) -> None: ... + +class ImpLoader: + def __init__(self, fullname: str, file: IO[str], filename: str, etc: Tuple[str, str, int]) -> None: ... + +def find_loader(fullname: str) -> Optional[Loader]: ... +def get_importer(path_item: str) -> Optional[PathEntryFinder]: ... +def get_loader(module_or_name: str) -> Loader: ... +def iter_importers(fullname: str = ...) -> Iterator[Union[MetaPathFinder, PathEntryFinder]]: ... +def iter_modules(path: Optional[Iterable[str]] = ..., prefix: str = ...) -> Iterator[_ModuleInfoLike]: ... +def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented +def walk_packages( + path: Optional[Iterable[str]] = ..., prefix: str = ..., onerror: Optional[Callable[[str], None]] = ... +) -> Iterator[_ModuleInfoLike]: ... +def get_data(package: str, resource: str) -> Optional[bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/plistlib.pyi b/mypy/typeshed/stdlib/@python2/plistlib.pyi new file mode 100644 index 000000000000..23115812ad69 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/plistlib.pyi @@ -0,0 +1,24 @@ +from typing import IO, Any, Dict as DictT, Mapping, Text, Union + +_Path = Union[str, Text] + +def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> Any: ... +def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ... +def readPlistFromBytes(data: bytes) -> Any: ... +def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... +def readPlistFromResource(path: _Path, restype: str = ..., resid: int = ...) -> Any: ... +def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, restype: str = ..., resid: int = ...) -> None: ... +def readPlistFromString(data: str) -> Any: ... +def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... + +class Dict(DictT[str, Any]): + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, value: Any) -> None: ... + def __delattr__(self, attr: str) -> None: ... + +class Data: + data: bytes + def __init__(self, data: bytes) -> None: ... + +class InvalidFileException(ValueError): + def __init__(self, message: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/popen2.pyi b/mypy/typeshed/stdlib/@python2/popen2.pyi index 5101a6f87487..b37a71085bf4 100644 --- a/mypy/typeshed/stdlib/@python2/popen2.pyi +++ b/mypy/typeshed/stdlib/@python2/popen2.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union +from typing import Any, Iterable, Optional, TextIO, Tuple, TypeVar, Union _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/@python2/poplib.pyi b/mypy/typeshed/stdlib/@python2/poplib.pyi new file mode 100644 index 000000000000..603093d419a2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/poplib.pyi @@ -0,0 +1,45 @@ +import socket +from typing import Any, BinaryIO, List, Optional, Pattern, Text, Tuple, overload + +_LongResp = Tuple[bytes, List[bytes], int] + +class error_proto(Exception): ... + +POP3_PORT: int +POP3_SSL_PORT: int +CR: bytes +LF: bytes +CRLF: bytes + +class POP3: + host: Text + port: int + sock: socket.socket + file: BinaryIO + welcome: bytes + def __init__(self, host: Text, port: int = ..., timeout: float = ...) -> None: ... + def getwelcome(self) -> bytes: ... + def set_debuglevel(self, level: int) -> None: ... + def user(self, user: Text) -> bytes: ... + def pass_(self, pswd: Text) -> bytes: ... + def stat(self) -> Tuple[int, int]: ... + def list(self, which: Optional[Any] = ...) -> _LongResp: ... + def retr(self, which: Any) -> _LongResp: ... + def dele(self, which: Any) -> bytes: ... + def noop(self) -> bytes: ... + def rset(self) -> bytes: ... + def quit(self) -> bytes: ... + def close(self) -> None: ... + def rpop(self, user: Text) -> bytes: ... + timestamp: Pattern[Text] + def apop(self, user: Text, secret: Text) -> bytes: ... + def top(self, which: Any, howmuch: int) -> _LongResp: ... + @overload + def uidl(self) -> _LongResp: ... + @overload + def uidl(self, which: Any) -> bytes: ... + +class POP3_SSL(POP3): + def __init__( + self, host: Text, port: int = ..., keyfile: Optional[Text] = ..., certfile: Optional[Text] = ..., timeout: float = ... + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/posixpath.pyi b/mypy/typeshed/stdlib/@python2/posixpath.pyi index f096428602d4..07bd9653efd9 100644 --- a/mypy/typeshed/stdlib/@python2/posixpath.pyi +++ b/mypy/typeshed/stdlib/@python2/posixpath.pyi @@ -1,6 +1,5 @@ import os import sys -from _typeshed import AnyPath, BytesPath, StrPath from genericpath import exists as exists from typing import Any, AnyStr, Callable, List, Optional, Sequence, Text, Tuple, TypeVar, overload @@ -39,20 +38,20 @@ else: # NOTE: Empty lists results in '' (str) regardless of contained type. # Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes # So, fall back to Any -def commonprefix(m: Sequence[AnyPath]) -> Any: ... -def lexists(path: AnyPath) -> bool: ... +def commonprefix(m: Sequence[Text]) -> Any: ... +def lexists(path: Text) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: AnyPath) -> float: ... -def getmtime(filename: AnyPath) -> float: ... -def getctime(filename: AnyPath) -> float: ... -def getsize(filename: AnyPath) -> int: ... -def isabs(s: AnyPath) -> bool: ... -def isfile(path: AnyPath) -> bool: ... -def isdir(s: AnyPath) -> bool: ... -def islink(path: AnyPath) -> bool: ... -def ismount(path: AnyPath) -> bool: ... +def getatime(filename: Text) -> float: ... +def getmtime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... +def getsize(filename: Text) -> int: ... +def isabs(s: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def islink(path: Text) -> bool: ... +def ismount(path: Text) -> bool: ... # Make sure signatures are disjunct, and allow combinations of bytes and unicode. # (Since Python 2 allows that, too) @@ -61,18 +60,18 @@ def ismount(path: AnyPath) -> bool: ... @overload def join(__p1: bytes, *p: bytes) -> bytes: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: bytes, __p3: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... @overload -def join(__p1: bytes, __p2: Text, *p: AnyPath) -> Text: ... +def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload -def join(__p1: Text, *p: AnyPath) -> Text: ... +def join(__p1: Text, *p: Text) -> Text: ... @overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +def relpath(path: str, start: Optional[str] = ...) -> str: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... -def samefile(f1: AnyPath, f2: AnyPath) -> bool: ... +def relpath(path: Text, start: Optional[Text] = ...) -> Text: ... +def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/pprint.pyi b/mypy/typeshed/stdlib/@python2/pprint.pyi new file mode 100644 index 000000000000..bdf750407d12 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pprint.pyi @@ -0,0 +1,19 @@ +from typing import IO, Any, Dict, Optional, Tuple + +def pformat(object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ...) -> str: ... +def pprint( + object: object, stream: Optional[IO[str]] = ..., indent: int = ..., width: int = ..., depth: Optional[int] = ... +) -> None: ... +def isreadable(object: object) -> bool: ... +def isrecursive(object: object) -> bool: ... +def saferepr(object: object) -> str: ... + +class PrettyPrinter: + def __init__( + self, indent: int = ..., width: int = ..., depth: Optional[int] = ..., stream: Optional[IO[str]] = ... + ) -> None: ... + def pformat(self, object: object) -> str: ... + def pprint(self, object: object) -> None: ... + def isreadable(self, object: object) -> bool: ... + def isrecursive(self, object: object) -> bool: ... + def format(self, object: object, context: Dict[int, Any], maxlevels: int, level: int) -> Tuple[str, bool, bool]: ... diff --git a/mypy/typeshed/stdlib/@python2/profile.pyi b/mypy/typeshed/stdlib/@python2/profile.pyi new file mode 100644 index 000000000000..e799c6b36e2f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/profile.pyi @@ -0,0 +1,26 @@ +from typing import Any, Callable, Dict, Optional, Text, Tuple, TypeVar, Union + +def run(statement: str, filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... +def runctx( + statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: Optional[str] = ..., sort: Union[str, int] = ... +) -> None: ... + +_SelfT = TypeVar("_SelfT", bound=Profile) +_T = TypeVar("_T") +_Label = Tuple[str, int, str] + +class Profile: + bias: int + stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented + def __init__(self, timer: Optional[Callable[[], float]] = ..., bias: Optional[int] = ...) -> None: ... + def set_cmd(self, cmd: str) -> None: ... + def simulate_call(self, name: str) -> None: ... + def simulate_cmd_complete(self) -> None: ... + def print_stats(self, sort: Union[str, int] = ...) -> None: ... + def dump_stats(self, file: Text) -> None: ... + def create_stats(self) -> None: ... + def snapshot_stats(self) -> None: ... + def run(self: _SelfT, cmd: str) -> _SelfT: ... + def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/pstats.pyi b/mypy/typeshed/stdlib/@python2/pstats.pyi new file mode 100644 index 000000000000..d1404dc7c01a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pstats.pyi @@ -0,0 +1,37 @@ +from cProfile import Profile as _cProfile +from profile import Profile +from typing import IO, Any, Dict, Iterable, List, Optional, Text, Tuple, TypeVar, Union, overload + +_Selector = Union[str, float, int] +_T = TypeVar("_T", bound=Stats) + +class Stats: + sort_arg_dict_default: Dict[str, Tuple[Any, str]] + def __init__( + self: _T, + __arg: Union[None, str, Text, Profile, _cProfile] = ..., + *args: Union[None, str, Text, Profile, _cProfile, _T], + stream: Optional[IO[Any]] = ..., + ) -> None: ... + def init(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... + def load_stats(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... + def get_top_level_stats(self) -> None: ... + def add(self: _T, *arg_list: Union[None, str, Text, Profile, _cProfile, _T]) -> _T: ... + def dump_stats(self, filename: Text) -> None: ... + def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... + @overload + def sort_stats(self: _T, field: int) -> _T: ... + @overload + def sort_stats(self: _T, *field: str) -> _T: ... + def reverse_order(self: _T) -> _T: ... + def strip_dirs(self: _T) -> _T: ... + def calc_callees(self) -> None: ... + def eval_print_amount(self, sel: _Selector, list: List[str], msg: str) -> Tuple[List[str], str]: ... + def get_print_list(self, sel_list: Iterable[_Selector]) -> Tuple[int, List[str]]: ... + def print_stats(self: _T, *amount: _Selector) -> _T: ... + def print_callees(self: _T, *amount: _Selector) -> _T: ... + def print_callers(self: _T, *amount: _Selector) -> _T: ... + def print_call_heading(self, name_size: int, column_title: str) -> None: ... + def print_call_line(self, name_size: int, source: str, call_dict: Dict[str, Any], arrow: str = ...) -> None: ... + def print_title(self) -> None: ... + def print_line(self, func: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pty.pyi b/mypy/typeshed/stdlib/@python2/pty.pyi new file mode 100644 index 000000000000..93983690fff4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pty.pyi @@ -0,0 +1,15 @@ +from typing import Callable, Iterable, Tuple, Union + +_Reader = Callable[[int], bytes] + +STDIN_FILENO: int +STDOUT_FILENO: int +STDERR_FILENO: int + +CHILD: int + +def openpty() -> Tuple[int, int]: ... +def master_open() -> Tuple[int, str]: ... +def slave_open(tty_name: str) -> int: ... +def fork() -> Tuple[int, int]: ... +def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pwd.pyi b/mypy/typeshed/stdlib/@python2/pwd.pyi new file mode 100644 index 000000000000..83020c1576dd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pwd.pyi @@ -0,0 +1,14 @@ +from typing import List, Tuple + +class struct_passwd(Tuple[str, str, int, int, str, str, str]): + pw_name: str + pw_passwd: str + pw_uid: int + pw_gid: int + pw_gecos: str + pw_dir: str + pw_shell: str + +def getpwall() -> List[struct_passwd]: ... +def getpwuid(__uid: int) -> struct_passwd: ... +def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/@python2/py_compile.pyi b/mypy/typeshed/stdlib/@python2/py_compile.pyi new file mode 100644 index 000000000000..94a8ace8e69a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/py_compile.pyi @@ -0,0 +1,15 @@ +from typing import List, Optional, Text, Type, Union + +_EitherStr = Union[bytes, Text] + +class PyCompileError(Exception): + exc_type_name: str + exc_value: BaseException + file: str + msg: str + def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... + +def compile( + file: _EitherStr, cfile: Optional[_EitherStr] = ..., dfile: Optional[_EitherStr] = ..., doraise: bool = ... +) -> None: ... +def main(args: Optional[List[Text]] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/pyclbr.pyi b/mypy/typeshed/stdlib/@python2/pyclbr.pyi new file mode 100644 index 000000000000..855a2963c453 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pyclbr.pyi @@ -0,0 +1,20 @@ +from typing import Dict, List, Optional, Sequence, Union + +class Class: + module: str + name: str + super: Optional[List[Union[Class, str]]] + methods: Dict[str, int] + file: int + lineno: int + def __init__(self, module: str, name: str, super: Optional[List[Union[Class, str]]], file: str, lineno: int) -> None: ... + +class Function: + module: str + name: str + file: int + lineno: int + def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... + +def readmodule(module: str, path: Optional[Sequence[str]] = ...) -> Dict[str, Class]: ... +def readmodule_ex(module: str, path: Optional[Sequence[str]] = ...) -> Dict[str, Union[Class, Function, List[str]]]: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc.pyi b/mypy/typeshed/stdlib/@python2/pydoc.pyi new file mode 100644 index 000000000000..857ed5a82c63 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pydoc.pyi @@ -0,0 +1,265 @@ +from _typeshed import SupportsWrite +from types import MethodType, ModuleType, TracebackType +from typing import ( + IO, + Any, + AnyStr, + Callable, + Container, + Dict, + List, + Mapping, + MutableMapping, + NoReturn, + Optional, + Text, + Tuple, + Type, + Union, +) + +from repr import Repr + +# the return type of sys.exc_info(), used by ErrorDuringImport.__init__ +_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +__author__: str +__date__: str +__version__: str +__credits__: str + +def pathdirs() -> List[str]: ... +def getdoc(object: object) -> Text: ... +def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def classname(object: object, modname: str) -> str: ... +def isdata(object: object) -> bool: ... +def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... +def cram(text: str, maxlen: int) -> str: ... +def stripid(text: str) -> str: ... +def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... +def visiblename(name: str, all: Optional[Container[str]] = ..., obj: Optional[object] = ...) -> bool: ... +def classify_class_attrs(object: object) -> List[Tuple[str, str, type, str]]: ... +def ispackage(path: str) -> bool: ... +def source_synopsis(file: IO[AnyStr]) -> Optional[AnyStr]: ... +def synopsis(filename: str, cache: MutableMapping[str, Tuple[int, str]] = ...) -> Optional[str]: ... + +class ErrorDuringImport(Exception): + filename: str + exc: Optional[Type[BaseException]] + value: Optional[BaseException] + tb: Optional[TracebackType] + def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... + +def importfile(path: str) -> ModuleType: ... +def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = ...) -> ModuleType: ... + +class Doc: + PYTHONDOCS: str + def document(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def fail(self, object: object, name: Optional[str] = ..., *args: Any) -> NoReturn: ... + def docmodule(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docroutine(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def getdocloc(self, object: object, basedir: str = ...) -> Optional[str]: ... + +class HTMLRepr(Repr): + maxlist: int + maxtuple: int + maxdict: int + maxstring: int + maxother: int + def __init__(self) -> None: ... + def escape(self, text: str) -> str: ... + def repr(self, object: object) -> str: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: Text, level: complex) -> str: ... + def repr_str(self, x: Text, level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + def repr_unicode(self, x: AnyStr, level: complex) -> str: ... + +class HTMLDoc(Doc): + repr: Callable[[object], str] + escape: Callable[[str], str] + def page(self, title: str, contents: str) -> str: ... + def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... + def section( + self, + title: str, + fgcol: str, + bgcol: str, + contents: str, + width: int = ..., + prelude: str = ..., + marginalia: Optional[str] = ..., + gap: str = ..., + ) -> str: ... + def bigsection(self, title: str, *args: Any) -> str: ... + def preformat(self, text: str) -> str: ... + def multicolumn(self, list: List[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... + def grey(self, text: str) -> str: ... + def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... + def classlink(self, object: object, modname: str) -> str: ... + def modulelink(self, object: object) -> str: ... + def modpkglink(self, modpkginfo: Tuple[str, str, bool, bool]) -> str: ... + def markup( + self, + text: str, + escape: Optional[Callable[[str], str]] = ..., + funcs: Mapping[str, str] = ..., + classes: Mapping[str, str] = ..., + methods: Mapping[str, str] = ..., + ) -> str: ... + def formattree( + self, tree: List[Union[Tuple[type, Tuple[type, ...]], List[Any]]], modname: str, parent: Optional[type] = ... + ) -> str: ... + def docmodule(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored: Any) -> str: ... + def docclass( + self, + object: object, + name: Optional[str] = ..., + mod: Optional[str] = ..., + funcs: Mapping[str, str] = ..., + classes: Mapping[str, str] = ..., + *ignored: Any, + ) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docroutine( + self, + object: object, + name: Optional[str] = ..., + mod: Optional[str] = ..., + funcs: Mapping[str, str] = ..., + classes: Mapping[str, str] = ..., + methods: Mapping[str, str] = ..., + cl: Optional[type] = ..., + *ignored: Any, + ) -> str: ... + def docproperty( + self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored: Any + ) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored: Any) -> str: ... + def docdata( + self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored: Any + ) -> str: ... + def index(self, dir: str, shadowed: Optional[MutableMapping[str, bool]] = ...) -> str: ... + def filelink(self, url: str, path: str) -> str: ... + +class TextRepr(Repr): + maxlist: int + maxtuple: int + maxdict: int + maxstring: int + maxother: int + def __init__(self) -> None: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: str, level: complex) -> str: ... + def repr_str(self, x: str, level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + +class TextDoc(Doc): + repr: Callable[[object], str] + def bold(self, text: str) -> str: ... + def indent(self, text: str, prefix: str = ...) -> str: ... + def section(self, title: str, contents: str) -> str: ... + def formattree( + self, + tree: List[Union[Tuple[type, Tuple[type, ...]], List[Any]]], + modname: str, + parent: Optional[type] = ..., + prefix: str = ..., + ) -> str: ... + def docmodule(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored: Any) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored: Any) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docroutine( + self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored: Any + ) -> str: ... + def docproperty( + self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored: Any + ) -> str: ... + def docdata( + self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored: Any + ) -> str: ... + def docother( + self, + object: object, + name: Optional[str] = ..., + mod: Optional[str] = ..., + parent: Optional[str] = ..., + maxlen: Optional[int] = ..., + doc: Optional[Any] = ..., + *ignored: Any, + ) -> str: ... + +def pager(text: str) -> None: ... +def getpager() -> Callable[[str], None]: ... +def plain(text: str) -> str: ... +def pipepager(text: str, cmd: str) -> None: ... +def tempfilepager(text: str, cmd: str) -> None: ... +def ttypager(text: str) -> None: ... +def plainpager(text: str) -> None: ... +def describe(thing: Any) -> str: ... +def locate(path: str, forceload: bool = ...) -> object: ... + +text: TextDoc +html: HTMLDoc + +class _OldStyleClass: ... + +def resolve(thing: Union[str, object], forceload: bool = ...) -> Optional[Tuple[object, str]]: ... +def render_doc(thing: Union[str, object], title: str = ..., forceload: bool = ..., renderer: Optional[Doc] = ...) -> str: ... +def doc( + thing: Union[str, object], title: str = ..., forceload: bool = ..., output: Optional[SupportsWrite[str]] = ... +) -> None: ... +def writedoc(thing: Union[str, object], forceload: bool = ...) -> None: ... +def writedocs(dir: str, pkgpath: str = ..., done: Optional[Any] = ...) -> None: ... + +class Helper: + keywords: Dict[str, Union[str, Tuple[str, str]]] + symbols: Dict[str, str] + topics: Dict[str, Union[str, Tuple[str, ...]]] + def __init__(self, input: Optional[IO[str]] = ..., output: Optional[IO[str]] = ...) -> None: ... + input: IO[str] + output: IO[str] + def __call__(self, request: Union[str, Helper, object] = ...) -> None: ... + def interact(self) -> None: ... + def getline(self, prompt: str) -> str: ... + def help(self, request: Any) -> None: ... + def intro(self) -> None: ... + def list(self, items: List[str], columns: int = ..., width: int = ...) -> None: ... + def listkeywords(self) -> None: ... + def listsymbols(self) -> None: ... + def listtopics(self) -> None: ... + def showtopic(self, topic: str, more_xrefs: str = ...) -> None: ... + def showsymbol(self, symbol: str) -> None: ... + def listmodules(self, key: str = ...) -> None: ... + +help: Helper + +# See Python issue #11182: "remove the unused and undocumented pydoc.Scanner class" +# class Scanner: +# roots = ... # type: Any +# state = ... # type: Any +# children = ... # type: Any +# descendp = ... # type: Any +# def __init__(self, roots, children, descendp) -> None: ... +# def next(self): ... + +class ModuleScanner: + quit: bool + def run( + self, + callback: Callable[[Optional[str], str, str], None], + key: Optional[Any] = ..., + completer: Optional[Callable[[], None]] = ..., + onerror: Optional[Callable[[str], None]] = ..., + ) -> None: ... + +def apropos(key: str) -> None: ... +def ispath(x: Any) -> bool: ... +def cli() -> None: ... +def serve(port: int, callback: Optional[Callable[[Any], None]] = ..., completer: Optional[Callable[[], None]] = ...) -> None: ... +def gui() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc_data/__init__.pyi b/mypy/typeshed/stdlib/@python2/pydoc_data/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi new file mode 100644 index 000000000000..1c48f4022fd6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi @@ -0,0 +1,3 @@ +from typing import Dict + +topics: Dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi new file mode 100644 index 000000000000..65f6b0e9f7de --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi @@ -0,0 +1,79 @@ +import pyexpat.errors as errors +import pyexpat.model as model +from _typeshed import SupportsRead +from typing import Any, Callable, Dict, List, Optional, Text, Tuple, Union + +EXPAT_VERSION: str # undocumented +version_info: Tuple[int, int, int] # undocumented +native_encoding: str # undocumented +features: List[Tuple[str, int]] # undocumented + +class ExpatError(Exception): + code: int + lineno: int + offset: int + +error = ExpatError + +XML_PARAM_ENTITY_PARSING_NEVER: int +XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int +XML_PARAM_ENTITY_PARSING_ALWAYS: int + +_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] + +class XMLParserType(object): + def Parse(self, __data: Union[Text, bytes], __isfinal: bool = ...) -> int: ... + def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... + def SetBase(self, __base: Text) -> None: ... + def GetBase(self) -> Optional[str]: ... + def GetInputContext(self) -> Optional[bytes]: ... + def ExternalEntityParserCreate(self, __context: Optional[Text], __encoding: Text = ...) -> XMLParserType: ... + def SetParamEntityParsing(self, __flag: int) -> int: ... + def UseForeignDTD(self, __flag: bool = ...) -> None: ... + buffer_size: int + buffer_text: bool + buffer_used: int + namespace_prefixes: bool # undocumented + ordered_attributes: bool + specified_attributes: bool + ErrorByteIndex: int + ErrorCode: int + ErrorColumnNumber: int + ErrorLineNumber: int + CurrentByteIndex: int + CurrentColumnNumber: int + CurrentLineNumber: int + XmlDeclHandler: Optional[Callable[[str, Optional[str], int], Any]] + StartDoctypeDeclHandler: Optional[Callable[[str, Optional[str], Optional[str], bool], Any]] + EndDoctypeDeclHandler: Optional[Callable[[], Any]] + ElementDeclHandler: Optional[Callable[[str, _Model], Any]] + AttlistDeclHandler: Optional[Callable[[str, str, str, Optional[str], bool], Any]] + StartElementHandler: Optional[ + Union[ + Callable[[str, Dict[str, str]], Any], + Callable[[str, List[str]], Any], + Callable[[str, Union[Dict[str, str]], List[str]], Any], + ] + ] + EndElementHandler: Optional[Callable[[str], Any]] + ProcessingInstructionHandler: Optional[Callable[[str, str], Any]] + CharacterDataHandler: Optional[Callable[[str], Any]] + UnparsedEntityDeclHandler: Optional[Callable[[str, Optional[str], str, Optional[str], str], Any]] + EntityDeclHandler: Optional[Callable[[str, bool, Optional[str], Optional[str], str, Optional[str], Optional[str]], Any]] + NotationDeclHandler: Optional[Callable[[str, Optional[str], str, Optional[str]], Any]] + StartNamespaceDeclHandler: Optional[Callable[[str, str], Any]] + EndNamespaceDeclHandler: Optional[Callable[[str], Any]] + CommentHandler: Optional[Callable[[str], Any]] + StartCdataSectionHandler: Optional[Callable[[], Any]] + EndCdataSectionHandler: Optional[Callable[[], Any]] + DefaultHandler: Optional[Callable[[str], Any]] + DefaultHandlerExpand: Optional[Callable[[str], Any]] + NotStandaloneHandler: Optional[Callable[[], int]] + ExternalEntityRefHandler: Optional[Callable[[str, Optional[str], Optional[str], Optional[str]], int]] + +def ErrorString(__code: int) -> str: ... + +# intern is undocumented +def ParserCreate( + encoding: Optional[Text] = ..., namespace_separator: Optional[Text] = ..., intern: Optional[Dict[str, Any]] = ... +) -> XMLParserType: ... diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/errors.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/errors.pyi new file mode 100644 index 000000000000..498030fd695f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pyexpat/errors.pyi @@ -0,0 +1,37 @@ +XML_ERROR_ABORTED: str +XML_ERROR_ASYNC_ENTITY: str +XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: str +XML_ERROR_BAD_CHAR_REF: str +XML_ERROR_BINARY_ENTITY_REF: str +XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: str +XML_ERROR_DUPLICATE_ATTRIBUTE: str +XML_ERROR_ENTITY_DECLARED_IN_PE: str +XML_ERROR_EXTERNAL_ENTITY_HANDLING: str +XML_ERROR_FEATURE_REQUIRES_XML_DTD: str +XML_ERROR_FINISHED: str +XML_ERROR_INCOMPLETE_PE: str +XML_ERROR_INCORRECT_ENCODING: str +XML_ERROR_INVALID_TOKEN: str +XML_ERROR_JUNK_AFTER_DOC_ELEMENT: str +XML_ERROR_MISPLACED_XML_PI: str +XML_ERROR_NOT_STANDALONE: str +XML_ERROR_NOT_SUSPENDED: str +XML_ERROR_NO_ELEMENTS: str +XML_ERROR_NO_MEMORY: str +XML_ERROR_PARAM_ENTITY_REF: str +XML_ERROR_PARTIAL_CHAR: str +XML_ERROR_PUBLICID: str +XML_ERROR_RECURSIVE_ENTITY_REF: str +XML_ERROR_SUSPENDED: str +XML_ERROR_SUSPEND_PE: str +XML_ERROR_SYNTAX: str +XML_ERROR_TAG_MISMATCH: str +XML_ERROR_TEXT_DECL: str +XML_ERROR_UNBOUND_PREFIX: str +XML_ERROR_UNCLOSED_CDATA_SECTION: str +XML_ERROR_UNCLOSED_TOKEN: str +XML_ERROR_UNDECLARING_PREFIX: str +XML_ERROR_UNDEFINED_ENTITY: str +XML_ERROR_UNEXPECTED_STATE: str +XML_ERROR_UNKNOWN_ENCODING: str +XML_ERROR_XML_DECL: str diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/model.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/model.pyi new file mode 100644 index 000000000000..f357cf6511a2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pyexpat/model.pyi @@ -0,0 +1,11 @@ +XML_CTYPE_ANY: int +XML_CTYPE_CHOICE: int +XML_CTYPE_EMPTY: int +XML_CTYPE_MIXED: int +XML_CTYPE_NAME: int +XML_CTYPE_SEQ: int + +XML_CQUANT_NONE: int +XML_CQUANT_OPT: int +XML_CQUANT_PLUS: int +XML_CQUANT_REP: int diff --git a/mypy/typeshed/stdlib/@python2/quopri.pyi b/mypy/typeshed/stdlib/@python2/quopri.pyi new file mode 100644 index 000000000000..c2ffabe7d531 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/quopri.pyi @@ -0,0 +1,6 @@ +from typing import BinaryIO + +def encode(input: BinaryIO, output: BinaryIO, quotetabs: int, header: int = ...) -> None: ... +def encodestring(s: bytes, quotetabs: int = ..., header: int = ...) -> bytes: ... +def decode(input: BinaryIO, output: BinaryIO, header: int = ...) -> None: ... +def decodestring(s: bytes, header: int = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/random.pyi b/mypy/typeshed/stdlib/@python2/random.pyi index 059bd9360708..6fb5d602067c 100644 --- a/mypy/typeshed/stdlib/@python2/random.pyi +++ b/mypy/typeshed/stdlib/@python2/random.pyi @@ -1,5 +1,5 @@ import _random -from typing import AbstractSet, Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, Union, overload +from typing import Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, overload _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) diff --git a/mypy/typeshed/stdlib/@python2/re.pyi b/mypy/typeshed/stdlib/@python2/re.pyi index 11e3d02fcf5c..aa770b6b64be 100644 --- a/mypy/typeshed/stdlib/@python2/re.pyi +++ b/mypy/typeshed/stdlib/@python2/re.pyi @@ -1,19 +1,4 @@ -from typing import ( - Any, - AnyStr, - Callable, - Dict, - Generic, - Iterator, - List, - Match, - Optional, - Pattern, - Sequence, - Tuple, - Union, - overload, -) +from typing import Any, AnyStr, Callable, Iterator, List, Match, Optional, Pattern, Tuple, Union, overload # ----- re variables and constants ----- DEBUG: int diff --git a/mypy/typeshed/stdlib/@python2/readline.pyi b/mypy/typeshed/stdlib/@python2/readline.pyi new file mode 100644 index 000000000000..579308f75bc1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/readline.pyi @@ -0,0 +1,30 @@ +from typing import Callable, Optional, Sequence, Text + +_CompleterT = Optional[Callable[[str, int], Optional[str]]] +_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + +def parse_and_bind(__string: str) -> None: ... +def read_init_file(__filename: Optional[Text] = ...) -> None: ... +def get_line_buffer() -> str: ... +def insert_text(__string: str) -> None: ... +def redisplay() -> None: ... +def read_history_file(__filename: Optional[Text] = ...) -> None: ... +def write_history_file(__filename: Optional[Text] = ...) -> None: ... +def get_history_length() -> int: ... +def set_history_length(__length: int) -> None: ... +def clear_history() -> None: ... +def get_current_history_length() -> int: ... +def get_history_item(__index: int) -> str: ... +def remove_history_item(__pos: int) -> None: ... +def replace_history_item(__pos: int, __line: str) -> None: ... +def add_history(__string: str) -> None: ... +def set_startup_hook(__function: Optional[Callable[[], None]] = ...) -> None: ... +def set_pre_input_hook(__function: Optional[Callable[[], None]] = ...) -> None: ... +def set_completer(__function: _CompleterT = ...) -> None: ... +def get_completer() -> _CompleterT: ... +def get_completion_type() -> int: ... +def get_begidx() -> int: ... +def get_endidx() -> int: ... +def set_completer_delims(__string: str) -> None: ... +def get_completer_delims() -> str: ... +def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi new file mode 100644 index 000000000000..a542c45c979b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi @@ -0,0 +1,7 @@ +from typing import Any, Dict, Optional, Union + +_Text = Union[str, unicode] + +class Completer: + def __init__(self, namespace: Optional[Dict[str, Any]] = ...) -> None: ... + def complete(self, text: _Text, state: int) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/sched.pyi b/mypy/typeshed/stdlib/@python2/sched.pyi new file mode 100644 index 000000000000..f718dd7a57bd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sched.pyi @@ -0,0 +1,18 @@ +from typing import Any, Callable, Dict, List, NamedTuple, Text, Tuple + +class Event(NamedTuple): + time: float + priority: Any + action: Callable[..., Any] + argument: Tuple[Any, ...] + kwargs: Dict[Text, Any] + +class scheduler: + def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... + def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def run(self) -> None: ... + def cancel(self, event: Event) -> None: ... + def empty(self) -> bool: ... + @property + def queue(self) -> List[Event]: ... diff --git a/mypy/typeshed/stdlib/@python2/select.pyi b/mypy/typeshed/stdlib/@python2/select.pyi new file mode 100644 index 000000000000..716c34a378ca --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/select.pyi @@ -0,0 +1,124 @@ +import sys +from _typeshed import FileDescriptorLike +from typing import Any, Iterable, List, Optional, Tuple + +if sys.platform != "win32": + PIPE_BUF: int + POLLERR: int + POLLHUP: int + POLLIN: int + POLLMSG: int + POLLNVAL: int + POLLOUT: int + POLLPRI: int + POLLRDBAND: int + POLLRDNORM: int + POLLWRBAND: int + POLLWRNORM: int + +class poll: + def __init__(self) -> None: ... + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... + def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ... + +def select( + __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: Optional[float] = ... +) -> Tuple[List[Any], List[Any], List[Any]]: ... + +class error(Exception): ... + +if sys.platform != "linux" and sys.platform != "win32": + # BSD only + class kevent(object): + data: Any + fflags: int + filter: int + flags: int + ident: int + udata: Any + def __init__( + self, + ident: FileDescriptorLike, + filter: int = ..., + flags: int = ..., + fflags: int = ..., + data: Any = ..., + udata: Any = ..., + ) -> None: ... + # BSD only + class kqueue(object): + closed: bool + def __init__(self) -> None: ... + def close(self) -> None: ... + def control( + self, __changelist: Optional[Iterable[kevent]], __maxevents: int, __timeout: Optional[float] = ... + ) -> List[kevent]: ... + def fileno(self) -> int: ... + @classmethod + def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... + KQ_EV_ADD: int + KQ_EV_CLEAR: int + KQ_EV_DELETE: int + KQ_EV_DISABLE: int + KQ_EV_ENABLE: int + KQ_EV_EOF: int + KQ_EV_ERROR: int + KQ_EV_FLAG1: int + KQ_EV_ONESHOT: int + KQ_EV_SYSFLAGS: int + KQ_FILTER_AIO: int + KQ_FILTER_NETDEV: int + KQ_FILTER_PROC: int + KQ_FILTER_READ: int + KQ_FILTER_SIGNAL: int + KQ_FILTER_TIMER: int + KQ_FILTER_VNODE: int + KQ_FILTER_WRITE: int + KQ_NOTE_ATTRIB: int + KQ_NOTE_CHILD: int + KQ_NOTE_DELETE: int + KQ_NOTE_EXEC: int + KQ_NOTE_EXIT: int + KQ_NOTE_EXTEND: int + KQ_NOTE_FORK: int + KQ_NOTE_LINK: int + if sys.platform != "darwin": + KQ_NOTE_LINKDOWN: int + KQ_NOTE_LINKINV: int + KQ_NOTE_LINKUP: int + KQ_NOTE_LOWAT: int + KQ_NOTE_PCTRLMASK: int + KQ_NOTE_PDATAMASK: int + KQ_NOTE_RENAME: int + KQ_NOTE_REVOKE: int + KQ_NOTE_TRACK: int + KQ_NOTE_TRACKERR: int + KQ_NOTE_WRITE: int + +if sys.platform == "linux": + class epoll(object): + def __init__(self, sizehint: int = ...) -> None: ... + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... + def poll(self, timeout: Optional[float] = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ... + @classmethod + def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... + EPOLLERR: int + EPOLLET: int + EPOLLHUP: int + EPOLLIN: int + EPOLLMSG: int + EPOLLONESHOT: int + EPOLLOUT: int + EPOLLPRI: int + EPOLLRDBAND: int + EPOLLRDNORM: int + EPOLLWRBAND: int + EPOLLWRNORM: int + EPOLL_RDHUP: int diff --git a/mypy/typeshed/stdlib/@python2/sets.pyi b/mypy/typeshed/stdlib/@python2/sets.pyi index e0a652053cc5..1ee3e8b26e1b 100644 --- a/mypy/typeshed/stdlib/@python2/sets.pyi +++ b/mypy/typeshed/stdlib/@python2/sets.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union +from typing import Any, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union _T = TypeVar("_T") _Setlike = Union[BaseSet[_T], Iterable[_T]] diff --git a/mypy/typeshed/stdlib/@python2/shutil.pyi b/mypy/typeshed/stdlib/@python2/shutil.pyi new file mode 100644 index 000000000000..ff4467ffc471 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/shutil.pyi @@ -0,0 +1,45 @@ +from _typeshed import SupportsRead, SupportsWrite +from typing import Any, AnyStr, Callable, Iterable, List, Optional, Sequence, Set, Text, Tuple, Type, TypeVar, Union + +_AnyStr = TypeVar("_AnyStr", str, unicode) +_AnyPath = TypeVar("_AnyPath", str, unicode) +_PathReturn = Type[None] + +class Error(EnvironmentError): ... +class SpecialFileError(EnvironmentError): ... +class ExecError(EnvironmentError): ... + +def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... +def copyfile(src: Text, dst: Text) -> None: ... +def copymode(src: Text, dst: Text) -> None: ... +def copystat(src: Text, dst: Text) -> None: ... +def copy(src: Text, dst: Text) -> _PathReturn: ... +def copy2(src: Text, dst: Text) -> _PathReturn: ... +def ignore_patterns(*patterns: Text) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... +def copytree( + src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: Union[None, Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]]] = ... +) -> _PathReturn: ... +def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Optional[Callable[[Any, _AnyPath, Any], Any]] = ...) -> None: ... + +_CopyFn = Union[Callable[[str, str], None], Callable[[Text, Text], None]] + +def move(src: Text, dst: Text) -> _PathReturn: ... +def make_archive( + base_name: _AnyStr, + format: str, + root_dir: Optional[Text] = ..., + base_dir: Optional[Text] = ..., + verbose: bool = ..., + dry_run: bool = ..., + owner: Optional[str] = ..., + group: Optional[str] = ..., + logger: Optional[Any] = ..., +) -> _AnyStr: ... +def get_archive_formats() -> List[Tuple[str, str]]: ... +def register_archive_format( + name: str, + function: Callable[..., Any], + extra_args: Optional[Sequence[Union[Tuple[str, Any], List[Any]]]] = ..., + description: str = ..., +) -> None: ... +def unregister_archive_format(name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/signal.pyi b/mypy/typeshed/stdlib/@python2/signal.pyi index c33ff19dcf10..16a8f2d1cb8b 100644 --- a/mypy/typeshed/stdlib/@python2/signal.pyi +++ b/mypy/typeshed/stdlib/@python2/signal.pyi @@ -1,5 +1,5 @@ from types import FrameType -from typing import Any, Callable, Tuple, Union +from typing import Callable, Tuple, Union SIG_DFL: int = ... SIG_IGN: int = ... diff --git a/mypy/typeshed/stdlib/@python2/site.pyi b/mypy/typeshed/stdlib/@python2/site.pyi new file mode 100644 index 000000000000..db7bbefcc794 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/site.pyi @@ -0,0 +1,12 @@ +from typing import Iterable, List, Optional + +PREFIXES: List[str] +ENABLE_USER_SITE: Optional[bool] +USER_SITE: Optional[str] +USER_BASE: Optional[str] + +def main() -> None: ... +def addsitedir(sitedir: str, known_paths: Optional[Iterable[str]] = ...) -> None: ... +def getsitepackages(prefixes: Optional[Iterable[str]] = ...) -> List[str]: ... +def getuserbase() -> str: ... +def getusersitepackages() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/smtpd.pyi b/mypy/typeshed/stdlib/@python2/smtpd.pyi new file mode 100644 index 000000000000..33d84ffde4c8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/smtpd.pyi @@ -0,0 +1,45 @@ +import asynchat +import asyncore +import socket +from typing import Any, List, Optional, Text, Tuple, Type, Union + +_Address = Tuple[str, int] # (host, port) + +class SMTPChannel(asynchat.async_chat): + COMMAND: int + DATA: int + def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ... + # base asynchat.async_chat.push() accepts bytes + def push(self, msg: Text) -> None: ... # type: ignore + def collect_incoming_data(self, data: bytes) -> None: ... + def found_terminator(self) -> None: ... + def smtp_HELO(self, arg: str) -> None: ... + def smtp_NOOP(self, arg: str) -> None: ... + def smtp_QUIT(self, arg: str) -> None: ... + def smtp_MAIL(self, arg: str) -> None: ... + def smtp_RCPT(self, arg: str) -> None: ... + def smtp_RSET(self, arg: str) -> None: ... + def smtp_DATA(self, arg: str) -> None: ... + +class SMTPServer(asyncore.dispatcher): + channel_class: Type[SMTPChannel] + + data_size_limit: int + enable_SMTPUTF8: bool + def __init__(self, localaddr: _Address, remoteaddr: _Address, data_size_limit: int = ...) -> None: ... + def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... + def process_message( + self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str], **kwargs: Any + ) -> Optional[str]: ... + +class DebuggingServer(SMTPServer): ... + +class PureProxy(SMTPServer): + def process_message( # type: ignore + self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str] + ) -> Optional[str]: ... + +class MailmanProxy(PureProxy): + def process_message( # type: ignore + self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str] + ) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/sndhdr.pyi b/mypy/typeshed/stdlib/@python2/sndhdr.pyi new file mode 100644 index 000000000000..a5ae485c24a2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sndhdr.pyi @@ -0,0 +1,6 @@ +from typing import Optional, Text, Tuple, Union + +_SndHeaders = Tuple[str, int, int, int, Union[int, str]] + +def what(filename: Text) -> Optional[_SndHeaders]: ... +def whathdr(filename: Text) -> Optional[_SndHeaders]: ... diff --git a/mypy/typeshed/stdlib/@python2/socket.pyi b/mypy/typeshed/stdlib/@python2/socket.pyi new file mode 100644 index 000000000000..ea3d47757a77 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/socket.pyi @@ -0,0 +1,471 @@ +import sys +from typing import Any, BinaryIO, Iterable, List, Optional, Text, Tuple, TypeVar, Union, overload + +# ----- Constants ----- +# Some socket families are listed in the "Socket families" section of the docs, +# but not the "Constants" section. These are listed at the end of the list of +# constants. +# +# Besides those and the first few constants listed, the constants are listed in +# documentation order. + +# Constants defined by Python (i.e. not OS constants re-exported from C) +has_ipv6: bool +SocketType: Any +# Re-exported errno +EAGAIN: int +EBADF: int +EINTR: int +EWOULDBLOCK: int + +# Constants re-exported from C + +# Per socketmodule.c, only these three families are portable +AF_UNIX: AddressFamily +AF_INET: AddressFamily +AF_INET6: AddressFamily + +SOCK_STREAM: SocketKind +SOCK_DGRAM: SocketKind +SOCK_RAW: SocketKind +SOCK_RDM: SocketKind +SOCK_SEQPACKET: SocketKind + +# Address families not mentioned in the docs +AF_AAL5: AddressFamily +AF_APPLETALK: AddressFamily +AF_ASH: AddressFamily +AF_ATMPVC: AddressFamily +AF_ATMSVC: AddressFamily +AF_AX25: AddressFamily +AF_BRIDGE: AddressFamily +AF_DECnet: AddressFamily +AF_ECONET: AddressFamily +AF_IPX: AddressFamily +AF_IRDA: AddressFamily +AF_KEY: AddressFamily +AF_LLC: AddressFamily +AF_NETBEUI: AddressFamily +AF_NETROM: AddressFamily +AF_PPPOX: AddressFamily +AF_ROSE: AddressFamily +AF_ROUTE: AddressFamily +AF_SECURITY: AddressFamily +AF_SNA: AddressFamily +AF_SYSTEM: AddressFamily +AF_UNSPEC: AddressFamily +AF_WANPIPE: AddressFamily +AF_X25: AddressFamily + +# The "many constants" referenced by the docs +SOMAXCONN: int +AI_ADDRCONFIG: AddressInfo +AI_ALL: AddressInfo +AI_CANONNAME: AddressInfo +AI_DEFAULT: AddressInfo +AI_MASK: AddressInfo +AI_NUMERICHOST: AddressInfo +AI_NUMERICSERV: AddressInfo +AI_PASSIVE: AddressInfo +AI_V4MAPPED: AddressInfo +AI_V4MAPPED_CFG: AddressInfo +EAI_ADDRFAMILY: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_BADHINTS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MAX: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_OVERFLOW: int +EAI_PROTOCOL: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +EAI_SYSTEM: int +INADDR_ALLHOSTS_GROUP: int +INADDR_ANY: int +INADDR_BROADCAST: int +INADDR_LOOPBACK: int +INADDR_MAX_LOCAL_GROUP: int +INADDR_NONE: int +INADDR_UNSPEC_GROUP: int +IPPORT_RESERVED: int +IPPORT_USERRESERVED: int +IPPROTO_AH: int +IPPROTO_BIP: int +IPPROTO_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_EON: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GGP: int +IPPROTO_GRE: int +IPPROTO_HELLO: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMP: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IP: int +IPPROTO_IPCOMP: int +IPPROTO_IPIP: int +IPPROTO_IPV4: int +IPPROTO_IPV6: int +IPPROTO_MAX: int +IPPROTO_MOBILE: int +IPPROTO_ND: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_RAW: int +IPPROTO_ROUTING: int +IPPROTO_RSVP: int +IPPROTO_SCTP: int +IPPROTO_TCP: int +IPPROTO_TP: int +IPPROTO_UDP: int +IPPROTO_VRRP: int +IPPROTO_XTP: int +IPV6_CHECKSUM: int +IPV6_DONTFRAG: int +IPV6_DSTOPTS: int +IPV6_HOPLIMIT: int +IPV6_HOPOPTS: int +IPV6_JOIN_GROUP: int +IPV6_LEAVE_GROUP: int +IPV6_MULTICAST_HOPS: int +IPV6_MULTICAST_IF: int +IPV6_MULTICAST_LOOP: int +IPV6_NEXTHOP: int +IPV6_PATHMTU: int +IPV6_PKTINFO: int +IPV6_RECVDSTOPTS: int +IPV6_RECVHOPLIMIT: int +IPV6_RECVHOPOPTS: int +IPV6_RECVPATHMTU: int +IPV6_RECVPKTINFO: int +IPV6_RECVRTHDR: int +IPV6_RECVTCLASS: int +IPV6_RTHDR: int +IPV6_RTHDRDSTOPTS: int +IPV6_RTHDR_TYPE_0: int +IPV6_TCLASS: int +IPV6_UNICAST_HOPS: int +IPV6_USE_MIN_MTU: int +IPV6_V6ONLY: int +IPX_TYPE: int +IP_ADD_MEMBERSHIP: int +IP_DEFAULT_MULTICAST_LOOP: int +IP_DEFAULT_MULTICAST_TTL: int +IP_DROP_MEMBERSHIP: int +IP_HDRINCL: int +IP_MAX_MEMBERSHIPS: int +IP_MULTICAST_IF: int +IP_MULTICAST_LOOP: int +IP_MULTICAST_TTL: int +IP_OPTIONS: int +IP_RECVDSTADDR: int +IP_RECVOPTS: int +IP_RECVRETOPTS: int +IP_RETOPTS: int +IP_TOS: int +IP_TRANSPARENT: int +IP_TTL: int +LOCAL_PEERCRED: int +MSG_BCAST: MsgFlag +MSG_BTAG: MsgFlag +MSG_CMSG_CLOEXEC: MsgFlag +MSG_CONFIRM: MsgFlag +MSG_CTRUNC: MsgFlag +MSG_DONTROUTE: MsgFlag +MSG_DONTWAIT: MsgFlag +MSG_EOF: MsgFlag +MSG_EOR: MsgFlag +MSG_ERRQUEUE: MsgFlag +MSG_ETAG: MsgFlag +MSG_FASTOPEN: MsgFlag +MSG_MCAST: MsgFlag +MSG_MORE: MsgFlag +MSG_NOSIGNAL: MsgFlag +MSG_NOTIFICATION: MsgFlag +MSG_OOB: MsgFlag +MSG_PEEK: MsgFlag +MSG_TRUNC: MsgFlag +MSG_WAITALL: MsgFlag +NI_DGRAM: int +NI_MAXHOST: int +NI_MAXSERV: int +NI_NAMEREQD: int +NI_NOFQDN: int +NI_NUMERICHOST: int +NI_NUMERICSERV: int +SCM_CREDENTIALS: int +SCM_CREDS: int +SCM_RIGHTS: int +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int +SOL_ATALK: int +SOL_AX25: int +SOL_HCI: int +SOL_IP: int +SOL_IPX: int +SOL_NETROM: int +SOL_ROSE: int +SOL_SOCKET: int +SOL_TCP: int +SOL_UDP: int +SO_ACCEPTCONN: int +SO_BINDTODEVICE: int +SO_BROADCAST: int +SO_DEBUG: int +SO_DONTROUTE: int +SO_ERROR: int +SO_EXCLUSIVEADDRUSE: int +SO_KEEPALIVE: int +SO_LINGER: int +SO_MARK: int +SO_OOBINLINE: int +SO_PASSCRED: int +SO_PEERCRED: int +SO_PRIORITY: int +SO_RCVBUF: int +SO_RCVLOWAT: int +SO_RCVTIMEO: int +SO_REUSEADDR: int +SO_REUSEPORT: int +SO_SETFIB: int +SO_SNDBUF: int +SO_SNDLOWAT: int +SO_SNDTIMEO: int +SO_TYPE: int +SO_USELOOPBACK: int +TCP_CORK: int +TCP_DEFER_ACCEPT: int +TCP_FASTOPEN: int +TCP_INFO: int +TCP_KEEPCNT: int +TCP_KEEPIDLE: int +TCP_KEEPINTVL: int +TCP_LINGER2: int +TCP_MAXSEG: int +TCP_NODELAY: int +TCP_QUICKACK: int +TCP_SYNCNT: int +TCP_WINDOW_CLAMP: int +# Specifically-documented constants + +if sys.platform == "linux": + AF_PACKET: AddressFamily + PF_PACKET: int + PACKET_BROADCAST: int + PACKET_FASTROUTE: int + PACKET_HOST: int + PACKET_LOOPBACK: int + PACKET_MULTICAST: int + PACKET_OTHERHOST: int + PACKET_OUTGOING: int + +if sys.platform == "win32": + SIO_RCVALL: int + SIO_KEEPALIVE_VALS: int + RCVALL_IPLEVEL: int + RCVALL_MAX: int + RCVALL_OFF: int + RCVALL_ON: int + RCVALL_SOCKETLEVELONLY: int + +if sys.platform == "linux": + AF_TIPC: AddressFamily + SOL_TIPC: int + TIPC_ADDR_ID: int + TIPC_ADDR_NAME: int + TIPC_ADDR_NAMESEQ: int + TIPC_CFG_SRV: int + TIPC_CLUSTER_SCOPE: int + TIPC_CONN_TIMEOUT: int + TIPC_CRITICAL_IMPORTANCE: int + TIPC_DEST_DROPPABLE: int + TIPC_HIGH_IMPORTANCE: int + TIPC_IMPORTANCE: int + TIPC_LOW_IMPORTANCE: int + TIPC_MEDIUM_IMPORTANCE: int + TIPC_NODE_SCOPE: int + TIPC_PUBLISHED: int + TIPC_SRC_DROPPABLE: int + TIPC_SUBSCR_TIMEOUT: int + TIPC_SUB_CANCEL: int + TIPC_SUB_PORTS: int + TIPC_SUB_SERVICE: int + TIPC_TOP_SRV: int + TIPC_WAIT_FOREVER: int + TIPC_WITHDRAWN: int + TIPC_ZONE_SCOPE: int + +AF_LINK: AddressFamily # Availability: BSD, macOS + +# Semi-documented constants +# (Listed under "Socket families" in the docs, but not "Constants") + +if sys.platform == "linux": + # Netlink is defined by Linux + AF_NETLINK: AddressFamily + NETLINK_ARPD: int + NETLINK_CRYPTO: int + NETLINK_DNRTMSG: int + NETLINK_FIREWALL: int + NETLINK_IP6_FW: int + NETLINK_NFLOG: int + NETLINK_ROUTE6: int + NETLINK_ROUTE: int + NETLINK_SKIP: int + NETLINK_TAPBASE: int + NETLINK_TCPDIAG: int + NETLINK_USERSOCK: int + NETLINK_W1: int + NETLINK_XFRM: int + +if sys.platform != "win32" and sys.platform != "darwin": + # Linux and some BSD support is explicit in the docs + # Windows and macOS do not support in practice + AF_BLUETOOTH: AddressFamily + BTPROTO_HCI: int + BTPROTO_L2CAP: int + BTPROTO_RFCOMM: int + BTPROTO_SCO: int # not in FreeBSD + + BDADDR_ANY: str + BDADDR_LOCAL: str + + HCI_FILTER: int # not in NetBSD or DragonFlyBSD + # not in FreeBSD, NetBSD, or DragonFlyBSD + HCI_TIME_STAMP: int + HCI_DATA_DIR: int + +if sys.platform == "darwin": + # PF_SYSTEM is defined by macOS + PF_SYSTEM: int + SYSPROTO_CONTROL: int + +# enum versions of above flags +AddressFamily = int +SocketKind = int + +AddressInfo = int +MsgFlag = int + +# ----- Exceptions ----- + +class error(IOError): ... + +class herror(error): + def __init__(self, herror: int = ..., string: str = ...) -> None: ... + +class gaierror(error): + def __init__(self, error: int = ..., string: str = ...) -> None: ... + +class timeout(error): + def __init__(self, error: int = ..., string: str = ...) -> None: ... + +# ----- Classes ----- + +# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, +# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). +_Address = Union[Tuple[Any, ...], str] +_RetAddress = Any +# TODO Most methods allow bytes as address objects + +_WriteBuffer = Union[bytearray, memoryview] + +_CMSG = Tuple[int, int, bytes] +_SelfT = TypeVar("_SelfT", bound=socket) + +class socket: + family: int + type: int + proto: int + def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... + # --- methods --- + def accept(self) -> Tuple[socket, _RetAddress]: ... + def bind(self, address: Union[_Address, bytes]) -> None: ... + def close(self) -> None: ... + def connect(self, address: Union[_Address, bytes]) -> None: ... + def connect_ex(self, address: Union[_Address, bytes]) -> int: ... + def detach(self) -> int: ... + def dup(self) -> socket: ... + def fileno(self) -> int: ... + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + def gettimeout(self) -> Optional[float]: ... + if sys.platform == "win32": + def ioctl(self, control: int, option: Union[int, Tuple[int, int, int]]) -> None: ... + def listen(self, __backlog: int) -> None: ... + # Note that the makefile's documented windows-specific behavior is not represented + def makefile(self, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... + def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + def sendall(self, data: bytes, flags: int = ...) -> None: ... # return type: None on success + @overload + def sendto(self, data: bytes, address: _Address) -> int: ... + @overload + def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: Optional[float]) -> None: ... + def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... + if sys.platform == "win32": + def share(self, process_id: int) -> bytes: ... + def shutdown(self, how: int) -> None: ... + +# ----- Functions ----- + +def create_connection( + address: Tuple[Optional[str], int], + timeout: Optional[float] = ..., + source_address: Optional[Tuple[Union[bytearray, bytes, Text], int]] = ..., +) -> socket: ... +def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... + +# the 5th tuple item is an address +def getaddrinfo( + host: Optional[Union[bytearray, bytes, Text]], + port: Union[str, int, None], + family: int = ..., + socktype: int = ..., + proto: int = ..., + flags: int = ..., +) -> List[Tuple[AddressFamily, SocketKind, int, str, Tuple[Any, ...]]]: ... +def getfqdn(name: str = ...) -> str: ... +def gethostbyname(hostname: str) -> str: ... +def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... +def gethostname() -> str: ... +def gethostbyaddr(ip_address: str) -> Tuple[str, List[str], List[str]]: ... +def getnameinfo(sockaddr: Union[Tuple[str, int], Tuple[str, int, int, int]], flags: int) -> Tuple[str, str]: ... +def getprotobyname(protocolname: str) -> int: ... +def getservbyname(servicename: str, protocolname: str = ...) -> int: ... +def getservbyport(port: int, protocolname: str = ...) -> str: ... + +if sys.platform == "win32": + def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + +else: + def socketpair(family: Optional[int] = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + +def ntohl(x: int) -> int: ... # param & ret val are 32-bit ints +def ntohs(x: int) -> int: ... # param & ret val are 16-bit ints +def htonl(x: int) -> int: ... # param & ret val are 32-bit ints +def htons(x: int) -> int: ... # param & ret val are 16-bit ints +def inet_aton(ip_string: str) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(packed_ip: bytes) -> str: ... +def inet_pton(address_family: int, ip_string: str) -> bytes: ... +def inet_ntop(address_family: int, packed_ip: bytes) -> str: ... +def getdefaulttimeout() -> Optional[float]: ... +def setdefaulttimeout(timeout: Optional[float]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi new file mode 100644 index 000000000000..d5d20d67b58e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi @@ -0,0 +1 @@ +from sqlite3.dbapi2 import * # noqa: F403 diff --git a/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi new file mode 100644 index 000000000000..e89ae080aed0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi @@ -0,0 +1,251 @@ +from datetime import date, datetime, time +from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Protocol, Text, Tuple, Type, TypeVar, Union + +_T = TypeVar("_T") + +paramstyle: str +threadsafety: int +apilevel: str +Date = date +Time = time +Timestamp = datetime + +def DateFromTicks(ticks: float) -> Date: ... +def TimeFromTicks(ticks: float) -> Time: ... +def TimestampFromTicks(ticks: float) -> Timestamp: ... + +version_info: Tuple[int, int, int] +sqlite_version_info: Tuple[int, int, int] +Binary = buffer + +# The remaining definitions are imported from _sqlite3. + +PARSE_COLNAMES: int +PARSE_DECLTYPES: int +SQLITE_ALTER_TABLE: int +SQLITE_ANALYZE: int +SQLITE_ATTACH: int +SQLITE_CREATE_INDEX: int +SQLITE_CREATE_TABLE: int +SQLITE_CREATE_TEMP_INDEX: int +SQLITE_CREATE_TEMP_TABLE: int +SQLITE_CREATE_TEMP_TRIGGER: int +SQLITE_CREATE_TEMP_VIEW: int +SQLITE_CREATE_TRIGGER: int +SQLITE_CREATE_VIEW: int +SQLITE_DELETE: int +SQLITE_DENY: int +SQLITE_DETACH: int +SQLITE_DROP_INDEX: int +SQLITE_DROP_TABLE: int +SQLITE_DROP_TEMP_INDEX: int +SQLITE_DROP_TEMP_TABLE: int +SQLITE_DROP_TEMP_TRIGGER: int +SQLITE_DROP_TEMP_VIEW: int +SQLITE_DROP_TRIGGER: int +SQLITE_DROP_VIEW: int +SQLITE_IGNORE: int +SQLITE_INSERT: int +SQLITE_OK: int +SQLITE_PRAGMA: int +SQLITE_READ: int +SQLITE_REINDEX: int +SQLITE_SELECT: int +SQLITE_TRANSACTION: int +SQLITE_UPDATE: int +adapters: Any +converters: Any +sqlite_version: str +version: str + +# TODO: adapt needs to get probed +def adapt(obj, protocol, alternate): ... +def complete_statement(sql: str) -> bool: ... +def connect( + database: Union[bytes, Text], + timeout: float = ..., + detect_types: int = ..., + isolation_level: Optional[str] = ..., + check_same_thread: bool = ..., + factory: Optional[Type[Connection]] = ..., + cached_statements: int = ..., +) -> Connection: ... +def enable_callback_tracebacks(__enable: bool) -> None: ... +def enable_shared_cache(enable: int) -> None: ... +def register_adapter(__type: Type[_T], __caster: Callable[[_T], Union[int, float, str, bytes]]) -> None: ... +def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... + +class Cache(object): + def __init__(self, *args, **kwargs) -> None: ... + def display(self, *args, **kwargs) -> None: ... + def get(self, *args, **kwargs) -> None: ... + +class _AggregateProtocol(Protocol): + def step(self, value: int) -> None: ... + def finalize(self) -> int: ... + +class Connection(object): + DataError: Any + DatabaseError: Any + Error: Any + IntegrityError: Any + InterfaceError: Any + InternalError: Any + NotSupportedError: Any + OperationalError: Any + ProgrammingError: Any + Warning: Any + in_transaction: Any + isolation_level: Any + row_factory: Any + text_factory: Any + total_changes: Any + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def close(self) -> None: ... + def commit(self) -> None: ... + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... + def create_collation(self, __name: str, __callback: Any) -> None: ... + def create_function(self, name: str, num_params: int, func: Any) -> None: ... + def cursor(self, cursorClass: Optional[type] = ...) -> Cursor: ... + def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... + # TODO: please check in executemany() if seq_of_parameters type is possible like this + def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... + def executescript(self, __sql_script: Union[bytes, Text]) -> Cursor: ... + def interrupt(self, *args: Any, **kwargs: Any) -> None: ... + def iterdump(self, *args: Any, **kwargs: Any) -> Generator[str, None, None]: ... + def rollback(self, *args: Any, **kwargs: Any) -> None: ... + # TODO: set_authorizer(authorzer_callback) + # see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_authorizer + # returns [SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE] so perhaps int + def set_authorizer(self, *args: Any, **kwargs: Any) -> None: ... + # set_progress_handler(handler, n) -> see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_progress_handler + def set_progress_handler(self, *args: Any, **kwargs: Any) -> None: ... + def set_trace_callback(self, *args: Any, **kwargs: Any) -> None: ... + # enable_load_extension and load_extension is not available on python distributions compiled + # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 + def enable_load_extension(self, enabled: bool) -> None: ... + def load_extension(self, path: str) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __enter__(self) -> Connection: ... + def __exit__(self, t: Optional[type], exc: Optional[BaseException], tb: Optional[Any]) -> None: ... + +class Cursor(Iterator[Any]): + arraysize: Any + connection: Any + description: Any + lastrowid: Any + row_factory: Any + rowcount: Any + # TODO: Cursor class accepts exactly 1 argument + # required type is sqlite3.Connection (which is imported as _Connection) + # however, the name of the __init__ variable is unknown + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def close(self, *args: Any, **kwargs: Any) -> None: ... + def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... + def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... + def executescript(self, __sql_script: Union[bytes, Text]) -> Cursor: ... + def fetchall(self) -> List[Any]: ... + def fetchmany(self, size: Optional[int] = ...) -> List[Any]: ... + def fetchone(self) -> Any: ... + def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... + def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... + def __iter__(self) -> Cursor: ... + def next(self) -> Any: ... + +class DataError(DatabaseError): ... +class DatabaseError(Error): ... +class Error(Exception): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(Error): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... + +class OptimizedUnicode(object): + maketrans: Any + def __init__(self, *args, **kwargs): ... + def capitalize(self, *args, **kwargs): ... + def casefold(self, *args, **kwargs): ... + def center(self, *args, **kwargs): ... + def count(self, *args, **kwargs): ... + def encode(self, *args, **kwargs): ... + def endswith(self, *args, **kwargs): ... + def expandtabs(self, *args, **kwargs): ... + def find(self, *args, **kwargs): ... + def format(self, *args, **kwargs): ... + def format_map(self, *args, **kwargs): ... + def index(self, *args, **kwargs): ... + def isalnum(self, *args, **kwargs): ... + def isalpha(self, *args, **kwargs): ... + def isdecimal(self, *args, **kwargs): ... + def isdigit(self, *args, **kwargs): ... + def isidentifier(self, *args, **kwargs): ... + def islower(self, *args, **kwargs): ... + def isnumeric(self, *args, **kwargs): ... + def isprintable(self, *args, **kwargs): ... + def isspace(self, *args, **kwargs): ... + def istitle(self, *args, **kwargs): ... + def isupper(self, *args, **kwargs): ... + def join(self, *args, **kwargs): ... + def ljust(self, *args, **kwargs): ... + def lower(self, *args, **kwargs): ... + def lstrip(self, *args, **kwargs): ... + def partition(self, *args, **kwargs): ... + def replace(self, *args, **kwargs): ... + def rfind(self, *args, **kwargs): ... + def rindex(self, *args, **kwargs): ... + def rjust(self, *args, **kwargs): ... + def rpartition(self, *args, **kwargs): ... + def rsplit(self, *args, **kwargs): ... + def rstrip(self, *args, **kwargs): ... + def split(self, *args, **kwargs): ... + def splitlines(self, *args, **kwargs): ... + def startswith(self, *args, **kwargs): ... + def strip(self, *args, **kwargs): ... + def swapcase(self, *args, **kwargs): ... + def title(self, *args, **kwargs): ... + def translate(self, *args, **kwargs): ... + def upper(self, *args, **kwargs): ... + def zfill(self, *args, **kwargs): ... + def __add__(self, other): ... + def __contains__(self, *args, **kwargs): ... + def __eq__(self, other): ... + def __format__(self, *args, **kwargs): ... + def __ge__(self, other): ... + def __getitem__(self, index): ... + def __getnewargs__(self, *args, **kwargs): ... + def __gt__(self, other): ... + def __hash__(self): ... + def __iter__(self): ... + def __le__(self, other): ... + def __len__(self, *args, **kwargs): ... + def __lt__(self, other): ... + def __mod__(self, other): ... + def __mul__(self, other): ... + def __ne__(self, other): ... + def __rmod__(self, other): ... + def __rmul__(self, other): ... + +class PrepareProtocol(object): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +class ProgrammingError(DatabaseError): ... + +class Row(object): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def keys(self, *args: Any, **kwargs: Any): ... + def __eq__(self, other): ... + def __ge__(self, other): ... + def __getitem__(self, index): ... + def __gt__(self, other): ... + def __hash__(self): ... + def __iter__(self): ... + def __le__(self, other): ... + def __len__(self): ... + def __lt__(self, other): ... + def __ne__(self, other): ... + +class Statement(object): + def __init__(self, *args, **kwargs): ... + +class Warning(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/sre_compile.pyi b/mypy/typeshed/stdlib/@python2/sre_compile.pyi new file mode 100644 index 000000000000..23317a918dad --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sre_compile.pyi @@ -0,0 +1,22 @@ +from sre_constants import ( + SRE_FLAG_DEBUG as SRE_FLAG_DEBUG, + SRE_FLAG_DOTALL as SRE_FLAG_DOTALL, + SRE_FLAG_IGNORECASE as SRE_FLAG_IGNORECASE, + SRE_FLAG_LOCALE as SRE_FLAG_LOCALE, + SRE_FLAG_MULTILINE as SRE_FLAG_MULTILINE, + SRE_FLAG_TEMPLATE as SRE_FLAG_TEMPLATE, + SRE_FLAG_UNICODE as SRE_FLAG_UNICODE, + SRE_FLAG_VERBOSE as SRE_FLAG_VERBOSE, + SRE_INFO_CHARSET as SRE_INFO_CHARSET, + SRE_INFO_LITERAL as SRE_INFO_LITERAL, + SRE_INFO_PREFIX as SRE_INFO_PREFIX, +) +from sre_parse import SubPattern +from typing import Any, List, Pattern, Tuple, Type, Union + +MAXCODE: int +STRING_TYPES: Tuple[Type[str], Type[unicode]] +_IsStringType = int + +def isstring(obj: Any) -> _IsStringType: ... +def compile(p: Union[str, bytes, SubPattern], flags: int = ...) -> Pattern[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/ssl.pyi b/mypy/typeshed/stdlib/@python2/ssl.pyi new file mode 100644 index 000000000000..b9693fa89768 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ssl.pyi @@ -0,0 +1,267 @@ +import socket +import sys +from _typeshed import StrPath +from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Tuple, Union, overload +from typing_extensions import Literal + +_PCTRTT = Tuple[Tuple[str, str], ...] +_PCTRTTT = Tuple[_PCTRTT, ...] +_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] +_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] +_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] +_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] + +_SC1ArgT = SSLSocket +_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] + +class SSLError(OSError): + library: str + reason: str + +class SSLZeroReturnError(SSLError): ... +class SSLWantReadError(SSLError): ... +class SSLWantWriteError(SSLError): ... +class SSLSyscallError(SSLError): ... +class SSLEOFError(SSLError): ... +class CertificateError(ValueError): ... + +def wrap_socket( + sock: socket.socket, + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + server_side: bool = ..., + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: Optional[str] = ..., + do_handshake_on_connect: bool = ..., + suppress_ragged_eofs: bool = ..., + ciphers: Optional[str] = ..., +) -> SSLSocket: ... +def create_default_context( + purpose: Any = ..., *, cafile: Optional[str] = ..., capath: Optional[str] = ..., cadata: Union[Text, bytes, None] = ... +) -> SSLContext: ... +def _create_unverified_context( + protocol: int = ..., + *, + cert_reqs: Optional[int] = ..., + check_hostname: bool = ..., + purpose: Any = ..., + certfile: Optional[str] = ..., + keyfile: Optional[str] = ..., + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Union[Text, bytes, None] = ..., +) -> SSLContext: ... + +_create_default_https_context: Callable[..., SSLContext] + +def RAND_status() -> bool: ... +def RAND_egd(path: str) -> None: ... +def RAND_add(__s: bytes, __entropy: float) -> None: ... +def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... +def cert_time_to_seconds(cert_time: str) -> int: ... +def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ..., ca_certs: Optional[str] = ...) -> str: ... +def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... +def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... + +class DefaultVerifyPaths(NamedTuple): + cafile: str + capath: str + openssl_cafile_env: str + openssl_cafile: str + openssl_capath_env: str + openssl_capath: str + +def get_default_verify_paths() -> DefaultVerifyPaths: ... + +if sys.platform == "win32": + def enum_certificates(store_name: str) -> _EnumRetType: ... + def enum_crls(store_name: str) -> _EnumRetType: ... + +CERT_NONE: int +CERT_OPTIONAL: int +CERT_REQUIRED: int + +VERIFY_DEFAULT: int +VERIFY_CRL_CHECK_LEAF: int +VERIFY_CRL_CHECK_CHAIN: int +VERIFY_X509_STRICT: int +VERIFY_X509_TRUSTED_FIRST: int + +PROTOCOL_SSLv23: int +PROTOCOL_SSLv2: int +PROTOCOL_SSLv3: int +PROTOCOL_TLSv1: int +PROTOCOL_TLSv1_1: int +PROTOCOL_TLSv1_2: int +PROTOCOL_TLS: int +OP_ALL: int +OP_NO_SSLv2: int +OP_NO_SSLv3: int +OP_NO_TLSv1: int +OP_NO_TLSv1_1: int +OP_NO_TLSv1_2: int +OP_CIPHER_SERVER_PREFERENCE: int +OP_SINGLE_DH_USE: int +OP_SINGLE_ECDH_USE: int +OP_NO_COMPRESSION: int + +HAS_ALPN: bool +HAS_ECDH: bool +HAS_SNI: bool +HAS_NPN: bool +CHANNEL_BINDING_TYPES: List[str] + +OPENSSL_VERSION: str +OPENSSL_VERSION_INFO: Tuple[int, int, int, int, int] +OPENSSL_VERSION_NUMBER: int + +ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int +ALERT_DESCRIPTION_INTERNAL_ERROR: int +ALERT_DESCRIPTION_ACCESS_DENIED: int +ALERT_DESCRIPTION_BAD_CERTIFICATE: int +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int +ALERT_DESCRIPTION_BAD_RECORD_MAC: int +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int +ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int +ALERT_DESCRIPTION_CLOSE_NOTIFY: int +ALERT_DESCRIPTION_DECODE_ERROR: int +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int +ALERT_DESCRIPTION_DECRYPT_ERROR: int +ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int +ALERT_DESCRIPTION_NO_RENEGOTIATION: int +ALERT_DESCRIPTION_PROTOCOL_VERSION: int +ALERT_DESCRIPTION_RECORD_OVERFLOW: int +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int +ALERT_DESCRIPTION_UNKNOWN_CA: int +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int +ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int +ALERT_DESCRIPTION_USER_CANCELLED: int + +class _ASN1Object(NamedTuple): + nid: int + shortname: str + longname: str + oid: str + +class Purpose(_ASN1Object): + SERVER_AUTH: ClassVar[Purpose] + CLIENT_AUTH: ClassVar[Purpose] + +class SSLSocket(socket.socket): + context: SSLContext + server_side: bool + server_hostname: Optional[str] + def __init__( + self, + sock: Optional[socket.socket] = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + server_side: bool = ..., + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: Optional[str] = ..., + do_handshake_on_connect: bool = ..., + family: int = ..., + type: int = ..., + proto: int = ..., + fileno: Optional[int] = ..., + suppress_ragged_eofs: bool = ..., + npn_protocols: Optional[Iterable[str]] = ..., + ciphers: Optional[str] = ..., + server_hostname: Optional[str] = ..., + _context: Optional[SSLContext] = ..., + _session: Optional[Any] = ..., + ) -> None: ... + def connect(self, addr: Union[socket._Address, bytes]) -> None: ... + def connect_ex(self, addr: Union[socket._Address, bytes]) -> int: ... + def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... + def recv_into(self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ...) -> int: ... + def recvfrom(self, buflen: int = ..., flags: int = ...) -> tuple[bytes, socket._RetAddress]: ... + def recvfrom_into( + self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ... + ) -> tuple[int, socket._RetAddress]: ... + @overload + def sendto(self, data: bytes, flags_or_addr: socket._Address) -> int: ... + @overload + def sendto(self, data: bytes, flags_or_addr: Union[int, socket._Address], addr: Optional[socket._Address] = ...) -> int: ... + def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... + def write(self, data: bytes) -> int: ... + def do_handshake(self, block: bool = ...) -> None: ... # block is undocumented + @overload + def getpeercert(self, binary_form: Literal[False] = ...) -> Optional[_PeerCertRetDictType]: ... + @overload + def getpeercert(self, binary_form: Literal[True]) -> Optional[bytes]: ... + @overload + def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + def cipher(self) -> Optional[Tuple[str, str, int]]: ... + def compression(self) -> Optional[str]: ... + def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... + def selected_alpn_protocol(self) -> Optional[str]: ... + def selected_npn_protocol(self) -> Optional[str]: ... + def accept(self) -> Tuple[SSLSocket, socket._RetAddress]: ... + def unwrap(self) -> socket.socket: ... + def version(self) -> Optional[str]: ... + def pending(self) -> int: ... + +class SSLContext: + check_hostname: bool + options: int + def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> SSLContext: ... + @property + def protocol(self) -> int: ... + verify_flags: int + verify_mode: int + def __init__(self, protocol: int) -> None: ... + def cert_store_stats(self) -> Dict[str, int]: ... + def load_cert_chain( + self, certfile: StrPath, keyfile: Optional[StrPath] = ..., password: Optional[_PasswordType] = ... + ) -> None: ... + def load_default_certs(self, purpose: Purpose = ...) -> None: ... + def load_verify_locations( + self, cafile: Optional[StrPath] = ..., capath: Optional[StrPath] = ..., cadata: Union[Text, bytes, None] = ... + ) -> None: ... + def get_ca_certs(self, binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ... + def set_default_verify_paths(self) -> None: ... + def set_ciphers(self, __cipherlist: str) -> None: ... + def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... + def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... + def set_servername_callback(self, __method: Optional[_SrvnmeCbType]) -> None: ... + def load_dh_params(self, __path: str) -> None: ... + def set_ecdh_curve(self, __name: str) -> None: ... + def wrap_socket( + self, + sock: socket.socket, + server_side: bool = ..., + do_handshake_on_connect: bool = ..., + suppress_ragged_eofs: bool = ..., + server_hostname: Optional[str] = ..., + ) -> SSLSocket: ... + def session_stats(self) -> Dict[str, int]: ... + +# TODO below documented in cpython but not in docs.python.org +# taken from python 3.4 +SSL_ERROR_EOF: int +SSL_ERROR_INVALID_ERROR_CODE: int +SSL_ERROR_SSL: int +SSL_ERROR_SYSCALL: int +SSL_ERROR_WANT_CONNECT: int +SSL_ERROR_WANT_READ: int +SSL_ERROR_WANT_WRITE: int +SSL_ERROR_WANT_X509_LOOKUP: int +SSL_ERROR_ZERO_RETURN: int + +def get_protocol_name(protocol_code: int) -> str: ... + +AF_INET: int +PEM_FOOTER: str +PEM_HEADER: str +SOCK_STREAM: int +SOL_SOCKET: int +SO_TYPE: int diff --git a/mypy/typeshed/stdlib/@python2/string.pyi b/mypy/typeshed/stdlib/@python2/string.pyi index 03a6a2dfd800..a2b0a9d25ddb 100644 --- a/mypy/typeshed/stdlib/@python2/string.pyi +++ b/mypy/typeshed/stdlib/@python2/string.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Iterable, List, Mapping, Optional, Sequence, Text, Tuple, Union, overload +from typing import Any, AnyStr, Iterable, List, Mapping, Sequence, Text, Tuple, Union, overload ascii_letters: str ascii_lowercase: str diff --git a/mypy/typeshed/stdlib/@python2/stringold.pyi b/mypy/typeshed/stdlib/@python2/stringold.pyi index ea11da72575d..271da8357c70 100644 --- a/mypy/typeshed/stdlib/@python2/stringold.pyi +++ b/mypy/typeshed/stdlib/@python2/stringold.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, Iterable, List, Optional, Type +from typing import AnyStr, Iterable, List, Optional whitespace: str lowercase: str diff --git a/mypy/typeshed/stdlib/@python2/stringprep.pyi b/mypy/typeshed/stdlib/@python2/stringprep.pyi new file mode 100644 index 000000000000..604fd2f2cae7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/stringprep.pyi @@ -0,0 +1,21 @@ +from typing import Text + +def in_table_a1(code: Text) -> bool: ... +def in_table_b1(code: Text) -> bool: ... +def map_table_b3(code: Text) -> Text: ... +def map_table_b2(a: Text) -> Text: ... +def in_table_c11(code: Text) -> bool: ... +def in_table_c12(code: Text) -> bool: ... +def in_table_c11_c12(code: Text) -> bool: ... +def in_table_c21(code: Text) -> bool: ... +def in_table_c22(code: Text) -> bool: ... +def in_table_c21_c22(code: Text) -> bool: ... +def in_table_c3(code: Text) -> bool: ... +def in_table_c4(code: Text) -> bool: ... +def in_table_c5(code: Text) -> bool: ... +def in_table_c6(code: Text) -> bool: ... +def in_table_c7(code: Text) -> bool: ... +def in_table_c8(code: Text) -> bool: ... +def in_table_c9(code: Text) -> bool: ... +def in_table_d1(code: Text) -> bool: ... +def in_table_d2(code: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/struct.pyi b/mypy/typeshed/stdlib/@python2/struct.pyi new file mode 100644 index 000000000000..bf27d12783da --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/struct.pyi @@ -0,0 +1,24 @@ +from array import array +from mmap import mmap +from typing import Any, Text, Tuple, Union + +class error(Exception): ... + +_FmtType = Union[bytes, Text] +_BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] +_WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] + +def pack(fmt: _FmtType, *v: Any) -> bytes: ... +def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... +def unpack(__format: _FmtType, __buffer: _BufferType) -> Tuple[Any, ...]: ... +def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... +def calcsize(__format: _FmtType) -> int: ... + +class Struct: + format: bytes + size: int + def __init__(self, format: _FmtType) -> None: ... + def pack(self, *v: Any) -> bytes: ... + def pack_into(self, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... + def unpack(self, __buffer: _BufferType) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/subprocess.pyi b/mypy/typeshed/stdlib/@python2/subprocess.pyi index b3a2e92e7fec..28a4c0574419 100644 --- a/mypy/typeshed/stdlib/@python2/subprocess.pyi +++ b/mypy/typeshed/stdlib/@python2/subprocess.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Generic, List, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union +from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union _FILE = Union[None, int, IO[Any]] _TXT = Union[bytes, Text] diff --git a/mypy/typeshed/stdlib/@python2/sunau.pyi b/mypy/typeshed/stdlib/@python2/sunau.pyi new file mode 100644 index 000000000000..e40ae2181be0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sunau.pyi @@ -0,0 +1,66 @@ +from typing import IO, Any, NoReturn, Optional, Text, Tuple, Union + +_File = Union[Text, IO[bytes]] + +class Error(Exception): ... + +AUDIO_FILE_MAGIC: int +AUDIO_FILE_ENCODING_MULAW_8: int +AUDIO_FILE_ENCODING_LINEAR_8: int +AUDIO_FILE_ENCODING_LINEAR_16: int +AUDIO_FILE_ENCODING_LINEAR_24: int +AUDIO_FILE_ENCODING_LINEAR_32: int +AUDIO_FILE_ENCODING_FLOAT: int +AUDIO_FILE_ENCODING_DOUBLE: int +AUDIO_FILE_ENCODING_ADPCM_G721: int +AUDIO_FILE_ENCODING_ADPCM_G722: int +AUDIO_FILE_ENCODING_ADPCM_G723_3: int +AUDIO_FILE_ENCODING_ADPCM_G723_5: int +AUDIO_FILE_ENCODING_ALAW_8: int +AUDIO_UNKNOWN_SIZE: int + +_sunau_params = Tuple[int, int, int, int, str, str] + +class Au_read: + def __init__(self, f: _File) -> None: ... + def getfp(self) -> Optional[IO[bytes]]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _sunau_params: ... + def getmarkers(self) -> None: ... + def getmark(self, id: Any) -> NoReturn: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> Optional[bytes]: ... + +class Au_write: + def __init__(self, f: _File) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, type: str, name: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def setparams(self, params: _sunau_params) -> None: ... + def getparams(self) -> _sunau_params: ... + def tell(self) -> int: ... + # should be any bytes-like object after 3.4, but we don't have a type for that + def writeframesraw(self, data: bytes) -> None: ... + def writeframes(self, data: bytes) -> None: ... + def close(self) -> None: ... + +# Returns a Au_read if mode is rb and Au_write if mode is wb +def open(f: _File, mode: Optional[str] = ...) -> Any: ... + +openfp = open diff --git a/mypy/typeshed/stdlib/@python2/symtable.pyi b/mypy/typeshed/stdlib/@python2/symtable.pyi new file mode 100644 index 000000000000..c7b8092aedbb --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/symtable.pyi @@ -0,0 +1,43 @@ +from typing import Any, List, Optional, Sequence, Text, Tuple + +def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... + +class SymbolTable(object): + def __init__(self, raw_table: Any, filename: str) -> None: ... + def get_type(self) -> str: ... + def get_id(self) -> int: ... + def get_name(self) -> str: ... + def get_lineno(self) -> int: ... + def is_optimized(self) -> bool: ... + def is_nested(self) -> bool: ... + def has_children(self) -> bool: ... + def has_exec(self) -> bool: ... + def has_import_star(self) -> bool: ... + def get_identifiers(self) -> Sequence[str]: ... + def lookup(self, name: str) -> Symbol: ... + def get_symbols(self) -> List[Symbol]: ... + def get_children(self) -> List[SymbolTable]: ... + +class Function(SymbolTable): + def get_parameters(self) -> Tuple[str, ...]: ... + def get_locals(self) -> Tuple[str, ...]: ... + def get_globals(self) -> Tuple[str, ...]: ... + def get_frees(self) -> Tuple[str, ...]: ... + +class Class(SymbolTable): + def get_methods(self) -> Tuple[str, ...]: ... + +class Symbol(object): + def __init__(self, name: str, flags: int, namespaces: Optional[Sequence[SymbolTable]] = ...) -> None: ... + def get_name(self) -> str: ... + def is_referenced(self) -> bool: ... + def is_parameter(self) -> bool: ... + def is_global(self) -> bool: ... + def is_declared_global(self) -> bool: ... + def is_local(self) -> bool: ... + def is_free(self) -> bool: ... + def is_imported(self) -> bool: ... + def is_assigned(self) -> bool: ... + def is_namespace(self) -> bool: ... + def get_namespaces(self) -> Sequence[SymbolTable]: ... + def get_namespace(self) -> SymbolTable: ... diff --git a/mypy/typeshed/stdlib/@python2/sys.pyi b/mypy/typeshed/stdlib/@python2/sys.pyi index 0136f3456c58..7852911b6532 100644 --- a/mypy/typeshed/stdlib/@python2/sys.pyi +++ b/mypy/typeshed/stdlib/@python2/sys.pyi @@ -1,5 +1,5 @@ -from types import ClassType, FrameType, ModuleType, TracebackType -from typing import IO, Any, BinaryIO, Callable, Dict, List, NoReturn, Optional, Sequence, Text, Tuple, Type, Union, overload +from types import ClassType, FrameType, TracebackType +from typing import IO, Any, Callable, Dict, List, NoReturn, Optional, Text, Tuple, Type, Union # The following type alias are stub-only and do not exist during runtime _ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] diff --git a/mypy/typeshed/stdlib/@python2/sysconfig.pyi b/mypy/typeshed/stdlib/@python2/sysconfig.pyi new file mode 100644 index 000000000000..b8044bcaa615 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sysconfig.pyi @@ -0,0 +1,17 @@ +from typing import IO, Any, Dict, List, Optional, Tuple, overload + +def get_config_var(name: str) -> Optional[str]: ... +@overload +def get_config_vars() -> Dict[str, Any]: ... +@overload +def get_config_vars(arg: str, *args: str) -> List[Any]: ... +def get_scheme_names() -> Tuple[str, ...]: ... +def get_path_names() -> Tuple[str, ...]: ... +def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Optional[str]: ... +def get_paths(scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Dict[str, str]: ... +def get_python_version() -> str: ... +def get_platform() -> str: ... +def is_python_build(check_home: bool = ...) -> bool: ... +def parse_config_h(fp: IO[Any], vars: Optional[Dict[str, Any]] = ...) -> Dict[str, Any]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/syslog.pyi b/mypy/typeshed/stdlib/@python2/syslog.pyi new file mode 100644 index 000000000000..49169f40db5c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/syslog.pyi @@ -0,0 +1,43 @@ +from typing import overload + +LOG_ALERT: int +LOG_AUTH: int +LOG_CONS: int +LOG_CRIT: int +LOG_CRON: int +LOG_DAEMON: int +LOG_DEBUG: int +LOG_EMERG: int +LOG_ERR: int +LOG_INFO: int +LOG_KERN: int +LOG_LOCAL0: int +LOG_LOCAL1: int +LOG_LOCAL2: int +LOG_LOCAL3: int +LOG_LOCAL4: int +LOG_LOCAL5: int +LOG_LOCAL6: int +LOG_LOCAL7: int +LOG_LPR: int +LOG_MAIL: int +LOG_NDELAY: int +LOG_NEWS: int +LOG_NOTICE: int +LOG_NOWAIT: int +LOG_PERROR: int +LOG_PID: int +LOG_SYSLOG: int +LOG_USER: int +LOG_UUCP: int +LOG_WARNING: int + +def LOG_MASK(a: int) -> int: ... +def LOG_UPTO(a: int) -> int: ... +def closelog() -> None: ... +def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... +def setlogmask(x: int) -> int: ... +@overload +def syslog(priority: int, message: str) -> None: ... +@overload +def syslog(message: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/tabnanny.pyi b/mypy/typeshed/stdlib/@python2/tabnanny.pyi new file mode 100644 index 000000000000..95873761ee75 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/tabnanny.pyi @@ -0,0 +1,13 @@ +from typing import Iterable, Text, Tuple + +verbose: int +filename_only: int + +class NannyNag(Exception): + def __init__(self, lineno: int, msg: str, line: str) -> None: ... + def get_lineno(self) -> int: ... + def get_msg(self) -> str: ... + def get_line(self) -> str: ... + +def check(file: Text) -> None: ... +def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/tarfile.pyi b/mypy/typeshed/stdlib/@python2/tarfile.pyi new file mode 100644 index 000000000000..169d7d2c89f6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/tarfile.pyi @@ -0,0 +1,290 @@ +import io +from types import TracebackType +from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Text, Tuple, Type, Union + +# tar constants +NUL: bytes +BLOCKSIZE: int +RECORDSIZE: int +GNU_MAGIC: bytes +POSIX_MAGIC: bytes + +LENGTH_NAME: int +LENGTH_LINK: int +LENGTH_PREFIX: int + +REGTYPE: bytes +AREGTYPE: bytes +LNKTYPE: bytes +SYMTYPE: bytes +CONTTYPE: bytes +BLKTYPE: bytes +DIRTYPE: bytes +FIFOTYPE: bytes +CHRTYPE: bytes + +GNUTYPE_LONGNAME: bytes +GNUTYPE_LONGLINK: bytes +GNUTYPE_SPARSE: bytes + +XHDTYPE: bytes +XGLTYPE: bytes +SOLARIS_XHDTYPE: bytes + +USTAR_FORMAT: int +GNU_FORMAT: int +PAX_FORMAT: int +DEFAULT_FORMAT: int + +# tarfile constants + +SUPPORTED_TYPES: Tuple[bytes, ...] +REGULAR_TYPES: Tuple[bytes, ...] +GNU_TYPES: Tuple[bytes, ...] +PAX_FIELDS: Tuple[str, ...] +PAX_NUMBER_FIELDS: Dict[str, type] + +ENCODING: str + +TAR_PLAIN: int +TAR_GZIPPED: int + +def open( + name: Optional[Text] = ..., + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + bufsize: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + compresslevel: Optional[int] = ..., +) -> TarFile: ... + +class ExFileObject(io.BufferedReader): + def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... + +class TarFile(Iterable[TarInfo]): + OPEN_METH: Mapping[str, str] + name: Optional[Text] + mode: str + fileobj: Optional[IO[bytes]] + format: Optional[int] + tarinfo: Type[TarInfo] + dereference: Optional[bool] + ignore_zeros: Optional[bool] + encoding: Optional[str] + errors: str + fileobject: Type[ExFileObject] + pax_headers: Optional[Mapping[str, str]] + debug: Optional[int] + errorlevel: Optional[int] + offset: int # undocumented + posix: bool + def __init__( + self, + name: Optional[Text] = ..., + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + copybufsize: Optional[int] = ..., # undocumented + ) -> None: ... + def __enter__(self) -> TarFile: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def __iter__(self) -> Iterator[TarInfo]: ... + @classmethod + def open( + cls, + name: Optional[Text] = ..., + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + bufsize: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def taropen( + cls, + name: Optional[Text], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + *, + compresslevel: int = ..., + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def gzopen( + cls, + name: Optional[Text], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def bz2open( + cls, + name: Optional[Text], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def xzopen( + cls, + name: Optional[Text], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + preset: Optional[int] = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + def getmember(self, name: str) -> TarInfo: ... + def getmembers(self) -> List[TarInfo]: ... + def getnames(self) -> List[str]: ... + def list(self, verbose: bool = ...) -> None: ... + def next(self) -> Optional[TarInfo]: ... + def extractall(self, path: Text = ..., members: Optional[Iterable[TarInfo]] = ...) -> None: ... + def extract(self, member: Union[str, TarInfo], path: Text = ...) -> None: ... + def extractfile(self, member: Union[str, TarInfo]) -> Optional[IO[bytes]]: ... + def makedir(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def makefile(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def makeunknown(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def makefifo(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def makedev(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def makelink(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def chown(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def chmod(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def utime(self, tarinfo: TarInfo, targetpath: Text) -> None: ... # undocumented + def add( + self, + name: str, + arcname: Optional[str] = ..., + recursive: bool = ..., + exclude: Optional[Callable[[str], bool]] = ..., + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ..., + ) -> None: ... + def addfile(self, tarinfo: TarInfo, fileobj: Optional[IO[bytes]] = ...) -> None: ... + def gettarinfo( + self, name: Optional[str] = ..., arcname: Optional[str] = ..., fileobj: Optional[IO[bytes]] = ... + ) -> TarInfo: ... + def close(self) -> None: ... + +def is_tarfile(name: Text) -> bool: ... +def filemode(mode: int) -> str: ... # undocumented + +class TarFileCompat: + def __init__(self, filename: str, mode: str = ..., compression: int = ...) -> None: ... + +class TarError(Exception): ... +class ReadError(TarError): ... +class CompressionError(TarError): ... +class StreamError(TarError): ... +class ExtractError(TarError): ... +class HeaderError(TarError): ... + +class TarInfo: + name: str + path: str + size: int + mtime: int + chksum: int + devmajor: int + devminor: int + offset: int + offset_data: int + sparse: Optional[bytes] + tarfile: Optional[TarFile] + mode: int + type: bytes + linkname: str + uid: int + gid: int + uname: str + gname: str + pax_headers: Mapping[str, str] + def __init__(self, name: str = ...) -> None: ... + @classmethod + def frombuf(cls, buf: bytes) -> TarInfo: ... + @classmethod + def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + @property + def linkpath(self) -> str: ... + @linkpath.setter + def linkpath(self, linkname: str) -> None: ... + def get_info(self) -> Mapping[str, Union[str, int, bytes, Mapping[str, str]]]: ... + def tobuf(self, format: Optional[int] = ..., encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... + def create_ustar_header( + self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str, errors: str + ) -> bytes: ... + def create_gnu_header( + self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str, errors: str + ) -> bytes: ... + def create_pax_header(self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str) -> bytes: ... + @classmethod + def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: ... + def isfile(self) -> bool: ... + def isreg(self) -> bool: ... + def issparse(self) -> bool: ... + def isdir(self) -> bool: ... + def issym(self) -> bool: ... + def islnk(self) -> bool: ... + def ischr(self) -> bool: ... + def isblk(self) -> bool: ... + def isfifo(self) -> bool: ... + def isdev(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/telnetlib.pyi b/mypy/typeshed/stdlib/@python2/telnetlib.pyi new file mode 100644 index 000000000000..388e5a8c9310 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/telnetlib.pyi @@ -0,0 +1,111 @@ +import socket +from typing import Any, Callable, Match, Optional, Pattern, Sequence, Tuple, Union + +DEBUGLEVEL: int +TELNET_PORT: int + +IAC: bytes +DONT: bytes +DO: bytes +WONT: bytes +WILL: bytes +theNULL: bytes + +SE: bytes +NOP: bytes +DM: bytes +BRK: bytes +IP: bytes +AO: bytes +AYT: bytes +EC: bytes +EL: bytes +GA: bytes +SB: bytes + +BINARY: bytes +ECHO: bytes +RCP: bytes +SGA: bytes +NAMS: bytes +STATUS: bytes +TM: bytes +RCTE: bytes +NAOL: bytes +NAOP: bytes +NAOCRD: bytes +NAOHTS: bytes +NAOHTD: bytes +NAOFFD: bytes +NAOVTS: bytes +NAOVTD: bytes +NAOLFD: bytes +XASCII: bytes +LOGOUT: bytes +BM: bytes +DET: bytes +SUPDUP: bytes +SUPDUPOUTPUT: bytes +SNDLOC: bytes +TTYPE: bytes +EOR: bytes +TUID: bytes +OUTMRK: bytes +TTYLOC: bytes +VT3270REGIME: bytes +X3PAD: bytes +NAWS: bytes +TSPEED: bytes +LFLOW: bytes +LINEMODE: bytes +XDISPLOC: bytes +OLD_ENVIRON: bytes +AUTHENTICATION: bytes +ENCRYPT: bytes +NEW_ENVIRON: bytes + +TN3270E: bytes +XAUTH: bytes +CHARSET: bytes +RSP: bytes +COM_PORT_OPTION: bytes +SUPPRESS_LOCAL_ECHO: bytes +TLS: bytes +KERMIT: bytes +SEND_URL: bytes +FORWARD_X: bytes +PRAGMA_LOGON: bytes +SSPI_LOGON: bytes +PRAGMA_HEARTBEAT: bytes +EXOPL: bytes +NOOPT: bytes + +class Telnet: + host: Optional[str] # undocumented + def __init__(self, host: Optional[str] = ..., port: int = ..., timeout: float = ...) -> None: ... + def open(self, host: str, port: int = ..., timeout: float = ...) -> None: ... + def msg(self, msg: str, *args: Any) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + def close(self) -> None: ... + def get_socket(self) -> socket.socket: ... + def fileno(self) -> int: ... + def write(self, buffer: bytes) -> None: ... + def read_until(self, match: bytes, timeout: Optional[float] = ...) -> bytes: ... + def read_all(self) -> bytes: ... + def read_some(self) -> bytes: ... + def read_very_eager(self) -> bytes: ... + def read_eager(self) -> bytes: ... + def read_lazy(self) -> bytes: ... + def read_very_lazy(self) -> bytes: ... + def read_sb_data(self) -> bytes: ... + def set_option_negotiation_callback(self, callback: Optional[Callable[[socket.socket, bytes, bytes], Any]]) -> None: ... + def process_rawq(self) -> None: ... + def rawq_getchar(self) -> bytes: ... + def fill_rawq(self) -> None: ... + def sock_avail(self) -> bool: ... + def interact(self) -> None: ... + def mt_interact(self) -> None: ... + def listener(self) -> None: ... + def expect( + self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[float] = ... + ) -> Tuple[int, Optional[Match[bytes]], bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/termios.pyi b/mypy/typeshed/stdlib/@python2/termios.pyi new file mode 100644 index 000000000000..0c627f4b72bd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/termios.pyi @@ -0,0 +1,246 @@ +from _typeshed import FileDescriptorLike +from typing import Any, List, Union + +_Attr = List[Union[int, List[Union[bytes, int]]]] + +# TODO constants not really documented +B0: int +B1000000: int +B110: int +B115200: int +B1152000: int +B1200: int +B134: int +B150: int +B1500000: int +B1800: int +B19200: int +B200: int +B2000000: int +B230400: int +B2400: int +B2500000: int +B300: int +B3000000: int +B3500000: int +B38400: int +B4000000: int +B460800: int +B4800: int +B50: int +B500000: int +B57600: int +B576000: int +B600: int +B75: int +B921600: int +B9600: int +BRKINT: int +BS0: int +BS1: int +BSDLY: int +CBAUD: int +CBAUDEX: int +CDSUSP: int +CEOF: int +CEOL: int +CEOT: int +CERASE: int +CFLUSH: int +CIBAUD: int +CINTR: int +CKILL: int +CLNEXT: int +CLOCAL: int +CQUIT: int +CR0: int +CR1: int +CR2: int +CR3: int +CRDLY: int +CREAD: int +CRPRNT: int +CRTSCTS: int +CS5: int +CS6: int +CS7: int +CS8: int +CSIZE: int +CSTART: int +CSTOP: int +CSTOPB: int +CSUSP: int +CWERASE: int +ECHO: int +ECHOCTL: int +ECHOE: int +ECHOK: int +ECHOKE: int +ECHONL: int +ECHOPRT: int +EXTA: int +EXTB: int +FF0: int +FF1: int +FFDLY: int +FIOASYNC: int +FIOCLEX: int +FIONBIO: int +FIONCLEX: int +FIONREAD: int +FLUSHO: int +HUPCL: int +ICANON: int +ICRNL: int +IEXTEN: int +IGNBRK: int +IGNCR: int +IGNPAR: int +IMAXBEL: int +INLCR: int +INPCK: int +IOCSIZE_MASK: int +IOCSIZE_SHIFT: int +ISIG: int +ISTRIP: int +IUCLC: int +IXANY: int +IXOFF: int +IXON: int +NCC: int +NCCS: int +NL0: int +NL1: int +NLDLY: int +NOFLSH: int +N_MOUSE: int +N_PPP: int +N_SLIP: int +N_STRIP: int +N_TTY: int +OCRNL: int +OFDEL: int +OFILL: int +OLCUC: int +ONLCR: int +ONLRET: int +ONOCR: int +OPOST: int +PARENB: int +PARMRK: int +PARODD: int +PENDIN: int +TAB0: int +TAB1: int +TAB2: int +TAB3: int +TABDLY: int +TCFLSH: int +TCGETA: int +TCGETS: int +TCIFLUSH: int +TCIOFF: int +TCIOFLUSH: int +TCION: int +TCOFLUSH: int +TCOOFF: int +TCOON: int +TCSADRAIN: int +TCSAFLUSH: int +TCSANOW: int +TCSBRK: int +TCSBRKP: int +TCSETA: int +TCSETAF: int +TCSETAW: int +TCSETS: int +TCSETSF: int +TCSETSW: int +TCXONC: int +TIOCCONS: int +TIOCEXCL: int +TIOCGETD: int +TIOCGICOUNT: int +TIOCGLCKTRMIOS: int +TIOCGPGRP: int +TIOCGSERIAL: int +TIOCGSOFTCAR: int +TIOCGWINSZ: int +TIOCINQ: int +TIOCLINUX: int +TIOCMBIC: int +TIOCMBIS: int +TIOCMGET: int +TIOCMIWAIT: int +TIOCMSET: int +TIOCM_CAR: int +TIOCM_CD: int +TIOCM_CTS: int +TIOCM_DSR: int +TIOCM_DTR: int +TIOCM_LE: int +TIOCM_RI: int +TIOCM_RNG: int +TIOCM_RTS: int +TIOCM_SR: int +TIOCM_ST: int +TIOCNOTTY: int +TIOCNXCL: int +TIOCOUTQ: int +TIOCPKT: int +TIOCPKT_DATA: int +TIOCPKT_DOSTOP: int +TIOCPKT_FLUSHREAD: int +TIOCPKT_FLUSHWRITE: int +TIOCPKT_NOSTOP: int +TIOCPKT_START: int +TIOCPKT_STOP: int +TIOCSCTTY: int +TIOCSERCONFIG: int +TIOCSERGETLSR: int +TIOCSERGETMULTI: int +TIOCSERGSTRUCT: int +TIOCSERGWILD: int +TIOCSERSETMULTI: int +TIOCSERSWILD: int +TIOCSER_TEMT: int +TIOCSETD: int +TIOCSLCKTRMIOS: int +TIOCSPGRP: int +TIOCSSERIAL: int +TIOCSSOFTCAR: int +TIOCSTI: int +TIOCSWINSZ: int +TOSTOP: int +VDISCARD: int +VEOF: int +VEOL: int +VEOL2: int +VERASE: int +VINTR: int +VKILL: int +VLNEXT: int +VMIN: int +VQUIT: int +VREPRINT: int +VSTART: int +VSTOP: int +VSUSP: int +VSWTC: int +VSWTCH: int +VT0: int +VT1: int +VTDLY: int +VTIME: int +VWERASE: int +XCASE: int +XTABS: int + +def tcgetattr(__fd: FileDescriptorLike) -> List[Any]: ... +def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... +def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... +def tcdrain(__fd: FileDescriptorLike) -> None: ... +def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... +def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + +class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/this.pyi b/mypy/typeshed/stdlib/@python2/this.pyi new file mode 100644 index 000000000000..0687a6675cca --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/this.pyi @@ -0,0 +1,4 @@ +from typing import Dict + +s: str +d: Dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/threading.pyi b/mypy/typeshed/stdlib/@python2/threading.pyi new file mode 100644 index 000000000000..bab2acdc84cd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/threading.pyi @@ -0,0 +1,109 @@ +from types import FrameType, TracebackType +from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar, Union + +# TODO recursive type +_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] + +_PF = Callable[[FrameType, str, Any], None] +_T = TypeVar("_T") + +__all__: List[str] + +def active_count() -> int: ... +def activeCount() -> int: ... +def current_thread() -> Thread: ... +def currentThread() -> Thread: ... +def enumerate() -> List[Thread]: ... +def settrace(func: _TF) -> None: ... +def setprofile(func: Optional[_PF]) -> None: ... +def stack_size(size: int = ...) -> int: ... + +class ThreadError(Exception): ... + +class local(object): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class Thread: + name: str + ident: Optional[int] + daemon: bool + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: Optional[Mapping[Text, Any]] = ..., + ) -> None: ... + def start(self) -> None: ... + def run(self) -> None: ... + def join(self, timeout: Optional[float] = ...) -> None: ... + def getName(self) -> str: ... + def setName(self, name: Text) -> None: ... + def is_alive(self) -> bool: ... + def isAlive(self) -> bool: ... + def isDaemon(self) -> bool: ... + def setDaemon(self, daemonic: bool) -> None: ... + +class _DummyThread(Thread): ... + +class Lock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + +class _RLock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + +RLock = _RLock + +class Condition: + def __init__(self, lock: Union[Lock, _RLock, None] = ...) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + def notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + def notifyAll(self) -> None: ... + +class Semaphore: + def __init__(self, value: int = ...) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def acquire(self, blocking: bool = ...) -> bool: ... + def __enter__(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + +class BoundedSemaphore(Semaphore): ... + +class Event: + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + def isSet(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + +class Timer(Thread): + def __init__( + self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... + ) -> None: ... + def cancel(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/time.pyi b/mypy/typeshed/stdlib/@python2/time.pyi new file mode 100644 index 000000000000..0a5353fca9c6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/time.pyi @@ -0,0 +1,45 @@ +import sys +from typing import Any, NamedTuple, Optional, Tuple, Union + +_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] + +accept2dyear: bool +altzone: int +daylight: int +timezone: int +tzname: Tuple[str, str] + +class _struct_time(NamedTuple): + tm_year: int + tm_mon: int + tm_mday: int + tm_hour: int + tm_min: int + tm_sec: int + tm_wday: int + tm_yday: int + tm_isdst: int + @property + def n_fields(self) -> int: ... + @property + def n_sequence_fields(self) -> int: ... + @property + def n_unnamed_fields(self) -> int: ... + +class struct_time(_struct_time): + def __init__(self, o: _TimeTuple, _arg: Any = ...) -> None: ... + def __new__(cls, o: _TimeTuple, _arg: Any = ...) -> struct_time: ... + +def asctime(t: Union[_TimeTuple, struct_time] = ...) -> str: ... +def clock() -> float: ... +def ctime(secs: Optional[float] = ...) -> str: ... +def gmtime(secs: Optional[float] = ...) -> struct_time: ... +def localtime(secs: Optional[float] = ...) -> struct_time: ... +def mktime(t: Union[_TimeTuple, struct_time]) -> float: ... +def sleep(secs: float) -> None: ... +def strftime(format: str, t: Union[_TimeTuple, struct_time] = ...) -> str: ... +def strptime(string: str, format: str = ...) -> struct_time: ... +def time() -> float: ... + +if sys.platform != "win32": + def tzset() -> None: ... # Unix only diff --git a/mypy/typeshed/stdlib/@python2/timeit.pyi b/mypy/typeshed/stdlib/@python2/timeit.pyi new file mode 100644 index 000000000000..dfb6a7b731ae --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/timeit.pyi @@ -0,0 +1,20 @@ +from typing import IO, Any, Callable, List, Optional, Sequence, Text, Union + +_str = Union[str, Text] +_Timer = Callable[[], float] +_stmt = Union[_str, Callable[[], Any]] + +default_timer: _Timer + +class Timer: + def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... + def print_exc(self, file: Optional[IO[str]] = ...) -> None: ... + def timeit(self, number: int = ...) -> float: ... + def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... + +def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... +def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> List[float]: ... + +_timerFunc = Callable[[], float] + +def main(args: Optional[Sequence[str]] = ..., *, _wrap_timer: Optional[Callable[[_timerFunc], _timerFunc]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/token.pyi b/mypy/typeshed/stdlib/@python2/token.pyi new file mode 100644 index 000000000000..4ba710470624 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/token.pyi @@ -0,0 +1,62 @@ +from typing import Dict + +ENDMARKER: int +NAME: int +NUMBER: int +STRING: int +NEWLINE: int +INDENT: int +DEDENT: int +LPAR: int +RPAR: int +LSQB: int +RSQB: int +COLON: int +COMMA: int +SEMI: int +PLUS: int +MINUS: int +STAR: int +SLASH: int +VBAR: int +AMPER: int +LESS: int +GREATER: int +EQUAL: int +DOT: int +PERCENT: int +BACKQUOTE: int +LBRACE: int +RBRACE: int +EQEQUAL: int +NOTEQUAL: int +LESSEQUAL: int +GREATEREQUAL: int +TILDE: int +CIRCUMFLEX: int +LEFTSHIFT: int +RIGHTSHIFT: int +DOUBLESTAR: int +PLUSEQUAL: int +MINEQUAL: int +STAREQUAL: int +SLASHEQUAL: int +PERCENTEQUAL: int +AMPEREQUAL: int +VBAREQUAL: int +CIRCUMFLEXEQUAL: int +LEFTSHIFTEQUAL: int +RIGHTSHIFTEQUAL: int +DOUBLESTAREQUAL: int +DOUBLESLASH: int +DOUBLESLASHEQUAL: int +AT: int +OP: int +ERRORTOKEN: int +N_TOKENS: int +NT_OFFSET: int +tok_name: Dict[int, str] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/tokenize.pyi index 86d5937d6bc9..98ec01a6cb75 100644 --- a/mypy/typeshed/stdlib/@python2/tokenize.pyi +++ b/mypy/typeshed/stdlib/@python2/tokenize.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple, Union +from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple __author__: str __credits__: str diff --git a/mypy/typeshed/stdlib/@python2/trace.pyi b/mypy/typeshed/stdlib/@python2/trace.pyi new file mode 100644 index 000000000000..810639869e20 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/trace.pyi @@ -0,0 +1,52 @@ +import types +from _typeshed import StrPath +from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, TypeVar, Union + +_T = TypeVar("_T") +_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] +_fileModuleFunction = Tuple[str, Optional[str], str] + +class CoverageResults: + def __init__( + self, + counts: Optional[Dict[Tuple[str, int], int]] = ..., + calledfuncs: Optional[Dict[_fileModuleFunction, int]] = ..., + infile: Optional[StrPath] = ..., + callers: Optional[Dict[Tuple[_fileModuleFunction, _fileModuleFunction], int]] = ..., + outfile: Optional[StrPath] = ..., + ) -> None: ... # undocumented + def update(self, other: CoverageResults) -> None: ... + def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: Optional[StrPath] = ...) -> None: ... + def write_results_file( + self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: Optional[str] = ... + ) -> Tuple[int, int]: ... + +class Trace: + def __init__( + self, + count: int = ..., + trace: int = ..., + countfuncs: int = ..., + countcallers: int = ..., + ignoremods: Sequence[str] = ..., + ignoredirs: Sequence[str] = ..., + infile: Optional[StrPath] = ..., + outfile: Optional[StrPath] = ..., + timing: bool = ..., + ) -> None: ... + def run(self, cmd: Union[str, types.CodeType]) -> None: ... + def runctx( + self, + cmd: Union[str, types.CodeType], + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + ) -> None: ... + def runfunc(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... + def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def results(self) -> CoverageResults: ... diff --git a/mypy/typeshed/stdlib/@python2/traceback.pyi b/mypy/typeshed/stdlib/@python2/traceback.pyi new file mode 100644 index 000000000000..3144fdd6700b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/traceback.pyi @@ -0,0 +1,27 @@ +from types import FrameType, TracebackType +from typing import IO, List, Optional, Tuple, Type + +_PT = Tuple[str, int, str, Optional[str]] + +def print_tb(tb: Optional[TracebackType], limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... +def print_exception( + etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], + limit: Optional[int] = ..., + file: Optional[IO[str]] = ..., +) -> None: ... +def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... +def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... +def print_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... +def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[_PT]: ... +def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> List[_PT]: ... +def format_list(extracted_list: List[_PT]) -> List[str]: ... +def format_exception_only(etype: Optional[Type[BaseException]], value: Optional[BaseException]) -> List[str]: ... +def format_exception( + etype: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType], limit: Optional[int] = ... +) -> List[str]: ... +def format_exc(limit: Optional[int] = ...) -> str: ... +def format_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[str]: ... +def format_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> List[str]: ... +def tb_lineno(tb: TracebackType) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/tty.pyi b/mypy/typeshed/stdlib/@python2/tty.pyi new file mode 100644 index 000000000000..c0dc418e9933 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/tty.pyi @@ -0,0 +1,15 @@ +from typing import IO, Union + +_FD = Union[int, IO[str]] + +# XXX: Undocumented integer constants +IFLAG: int +OFLAG: int +CFLAG: int +LFLAG: int +ISPEED: int +OSPEED: int +CC: int + +def setraw(fd: _FD, when: int = ...) -> None: ... +def setcbreak(fd: _FD, when: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/turtle.pyi b/mypy/typeshed/stdlib/@python2/turtle.pyi new file mode 100644 index 000000000000..6476c9de04ff --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/turtle.pyi @@ -0,0 +1,508 @@ +from typing import Any, Callable, Dict, List, Optional, Sequence, Text, Tuple, TypeVar, Union, overload + +# TODO: Replace these aliases once we have Python 2 stubs for the Tkinter module. +Canvas = Any +PhotoImage = Any + +# Note: '_Color' is the alias we use for arguments and _AnyColor is the +# alias we use for return types. Really, these two aliases should be the +# same, but as per the "no union returns" typeshed policy, we'll return +# Any instead. +_Color = Union[Text, Tuple[float, float, float]] +_AnyColor = Any + +# TODO: Replace this with a TypedDict once it becomes standardized. +_PenState = Dict[str, Any] + +_Speed = Union[str, float] +_PolygonCoords = Sequence[Tuple[float, float]] + +# TODO: Type this more accurately +# Vec2D is actually a custom subclass of 'tuple'. +Vec2D = Tuple[float, float] + +class TurtleScreenBase(object): + cv: Canvas = ... + canvwidth: int = ... + canvheight: int = ... + xscale: float = ... + yscale: float = ... + def __init__(self, cv: Canvas) -> None: ... + +class Terminator(Exception): ... +class TurtleGraphicsError(Exception): ... + +class Shape(object): + def __init__(self, type_: str, data: Union[_PolygonCoords, PhotoImage, None] = ...) -> None: ... + def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: Optional[_Color] = ...) -> None: ... + +class TurtleScreen(TurtleScreenBase): + def __init__(self, cv: Canvas, mode: str = ..., colormode: float = ..., delay: int = ...) -> None: ... + def clear(self) -> None: ... + @overload + def mode(self, mode: None = ...) -> str: ... + @overload + def mode(self, mode: str) -> None: ... + def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ... + def register_shape(self, name: str, shape: Union[_PolygonCoords, Shape, None] = ...) -> None: ... + @overload + def colormode(self, cmode: None = ...) -> float: ... + @overload + def colormode(self, cmode: float) -> None: ... + def reset(self) -> None: ... + def turtles(self) -> List[Turtle]: ... + @overload + def bgcolor(self) -> _AnyColor: ... + @overload + def bgcolor(self, color: _Color) -> None: ... + @overload + def bgcolor(self, r: float, g: float, b: float) -> None: ... + @overload + def tracer(self, n: None = ...) -> int: ... + @overload + def tracer(self, n: int, delay: Optional[int] = ...) -> None: ... + @overload + def delay(self, delay: None = ...) -> int: ... + @overload + def delay(self, delay: int) -> None: ... + def update(self) -> None: ... + def window_width(self) -> int: ... + def window_height(self) -> int: ... + def getcanvas(self) -> Canvas: ... + def getshapes(self) -> List[str]: ... + def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Optional[Any] = ...) -> None: ... + def onkey(self, fun: Callable[[], Any], key: str) -> None: ... + def listen(self, xdummy: Optional[float] = ..., ydummy: Optional[float] = ...) -> None: ... + def ontimer(self, fun: Callable[[], Any], t: int = ...) -> None: ... + @overload + def bgpic(self, picname: None = ...) -> str: ... + @overload + def bgpic(self, picname: str) -> None: ... + @overload + def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... + # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well + @overload + def screensize(self, canvwidth: int, canvheight: int, bg: Optional[_Color] = ...) -> None: ... + onscreenclick = onclick + resetscreen = reset + clearscreen = clear + addshape = register_shape + +class TNavigator(object): + START_ORIENTATION: Dict[str, Vec2D] = ... + DEFAULT_MODE: str = ... + DEFAULT_ANGLEOFFSET: int = ... + DEFAULT_ANGLEORIENT: int = ... + def __init__(self, mode: str = ...) -> None: ... + def reset(self) -> None: ... + def degrees(self, fullcircle: float = ...) -> None: ... + def radians(self) -> None: ... + def forward(self, distance: float) -> None: ... + def back(self, distance: float) -> None: ... + def right(self, angle: float) -> None: ... + def left(self, angle: float) -> None: ... + def pos(self) -> Vec2D: ... + def xcor(self) -> float: ... + def ycor(self) -> float: ... + @overload + def goto(self, x: Tuple[float, float], y: None = ...) -> None: ... + @overload + def goto(self, x: float, y: float) -> None: ... + def home(self) -> None: ... + def setx(self, x: float) -> None: ... + def sety(self, y: float) -> None: ... + @overload + def distance(self, x: Union[TNavigator, Tuple[float, float]], y: None = ...) -> float: ... + @overload + def distance(self, x: float, y: float) -> float: ... + @overload + def towards(self, x: Union[TNavigator, Tuple[float, float]], y: None = ...) -> float: ... + @overload + def towards(self, x: float, y: float) -> float: ... + def heading(self) -> float: ... + def setheading(self, to_angle: float) -> None: ... + def circle(self, radius: float, extent: Optional[float] = ..., steps: Optional[int] = ...) -> None: ... + fd = forward + bk = back + backward = back + rt = right + lt = left + position = pos + setpos = goto + setposition = goto + seth = setheading + +class TPen(object): + def __init__(self, resizemode: str = ...) -> None: ... + @overload + def resizemode(self, rmode: None = ...) -> str: ... + @overload + def resizemode(self, rmode: str) -> None: ... + @overload + def pensize(self, width: None = ...) -> int: ... + @overload + def pensize(self, width: int) -> None: ... + def penup(self) -> None: ... + def pendown(self) -> None: ... + def isdown(self) -> bool: ... + @overload + def speed(self, speed: None = ...) -> int: ... + @overload + def speed(self, speed: _Speed) -> None: ... + @overload + def pencolor(self) -> _AnyColor: ... + @overload + def pencolor(self, color: _Color) -> None: ... + @overload + def pencolor(self, r: float, g: float, b: float) -> None: ... + @overload + def fillcolor(self) -> _AnyColor: ... + @overload + def fillcolor(self, color: _Color) -> None: ... + @overload + def fillcolor(self, r: float, g: float, b: float) -> None: ... + @overload + def color(self) -> Tuple[_AnyColor, _AnyColor]: ... + @overload + def color(self, color: _Color) -> None: ... + @overload + def color(self, r: float, g: float, b: float) -> None: ... + @overload + def color(self, color1: _Color, color2: _Color) -> None: ... + def showturtle(self) -> None: ... + def hideturtle(self) -> None: ... + def isvisible(self) -> bool: ... + # Note: signatures 1 and 2 overlap unsafely when no arguments are provided + @overload + def pen(self) -> _PenState: ... # type: ignore + @overload + def pen( + self, + pen: Optional[_PenState] = ..., + *, + shown: bool = ..., + pendown: bool = ..., + pencolor: _Color = ..., + fillcolor: _Color = ..., + pensize: int = ..., + speed: int = ..., + resizemode: str = ..., + stretchfactor: Tuple[float, float] = ..., + outline: int = ..., + tilt: float = ..., + ) -> None: ... + width = pensize + up = penup + pu = penup + pd = pendown + down = pendown + st = showturtle + ht = hideturtle + +_T = TypeVar("_T") + +class RawTurtle(TPen, TNavigator): + def __init__( + self, canvas: Union[Canvas, TurtleScreen, None] = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... + ) -> None: ... + def reset(self) -> None: ... + def setundobuffer(self, size: Optional[int]) -> None: ... + def undobufferentries(self) -> int: ... + def clear(self) -> None: ... + def clone(self: _T) -> _T: ... + @overload + def shape(self, name: None = ...) -> str: ... + @overload + def shape(self, name: str) -> None: ... + # Unsafely overlaps when no arguments are provided + @overload + def shapesize(self) -> Tuple[float, float, float]: ... # type: ignore + @overload + def shapesize( + self, stretch_wid: Optional[float] = ..., stretch_len: Optional[float] = ..., outline: Optional[float] = ... + ) -> None: ... + def settiltangle(self, angle: float) -> None: ... + @overload + def tiltangle(self, angle: None = ...) -> float: ... + @overload + def tiltangle(self, angle: float) -> None: ... + def tilt(self, angle: float) -> None: ... + # Can return either 'int' or Tuple[int, ...] based on if the stamp is + # a compound stamp or not. So, as per the "no Union return" policy, + # we return Any. + def stamp(self) -> Any: ... + def clearstamp(self, stampid: Union[int, Tuple[int, ...]]) -> None: ... + def clearstamps(self, n: Optional[int] = ...) -> None: ... + def filling(self) -> bool: ... + def begin_fill(self) -> None: ... + def end_fill(self) -> None: ... + def dot(self, size: Optional[int] = ..., *color: _Color) -> None: ... + def write(self, arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... + def begin_poly(self) -> None: ... + def end_poly(self) -> None: ... + def get_poly(self) -> Optional[_PolygonCoords]: ... + def getscreen(self) -> TurtleScreen: ... + def getturtle(self: _T) -> _T: ... + getpen = getturtle + def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Optional[bool] = ...) -> None: ... + def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: Optional[bool] = ...) -> None: ... + def ondrag(self, fun: Callable[[float, float], Any], btn: int = ..., add: Optional[bool] = ...) -> None: ... + def undo(self) -> None: ... + turtlesize = shapesize + +class _Screen(TurtleScreen): + def __init__(self) -> None: ... + # Note int and float are interpreted differently, hence the Union instead of just float + def setup( + self, + width: Union[int, float] = ..., + height: Union[int, float] = ..., + startx: Optional[int] = ..., + starty: Optional[int] = ..., + ) -> None: ... + def title(self, titlestring: str) -> None: ... + def bye(self) -> None: ... + def exitonclick(self) -> None: ... + +class Turtle(RawTurtle): + def __init__(self, shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ... + +RawPen = RawTurtle +Pen = Turtle + +def write_docstringdict(filename: str = ...) -> None: ... + +# Note: it's somewhat unfortunate that we have to copy the function signatures. +# It would be nice if we could partially reduce the redundancy by doing something +# like the following: +# +# _screen: Screen +# clear = _screen.clear +# +# However, it seems pytype does not support this type of syntax in pyi files. + +# Functions copied from TurtleScreenBase: + +# Note: mainloop() was always present in the global scope, but was added to +# TurtleScreenBase in Python 3.0 +def mainloop() -> None: ... + +# Functions copied from TurtleScreen: + +def clear() -> None: ... +@overload +def mode(mode: None = ...) -> str: ... +@overload +def mode(mode: str) -> None: ... +def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ... +def register_shape(name: str, shape: Union[_PolygonCoords, Shape, None] = ...) -> None: ... +@overload +def colormode(cmode: None = ...) -> float: ... +@overload +def colormode(cmode: float) -> None: ... +def reset() -> None: ... +def turtles() -> List[Turtle]: ... +@overload +def bgcolor() -> _AnyColor: ... +@overload +def bgcolor(color: _Color) -> None: ... +@overload +def bgcolor(r: float, g: float, b: float) -> None: ... +@overload +def tracer(n: None = ...) -> int: ... +@overload +def tracer(n: int, delay: Optional[int] = ...) -> None: ... +@overload +def delay(delay: None = ...) -> int: ... +@overload +def delay(delay: int) -> None: ... +def update() -> None: ... +def window_width() -> int: ... +def window_height() -> int: ... +def getcanvas() -> Canvas: ... +def getshapes() -> List[str]: ... +def onclick(fun: Callable[[float, float], Any], btn: int = ..., add: Optional[Any] = ...) -> None: ... +def onkey(fun: Callable[[], Any], key: str) -> None: ... +def listen(xdummy: Optional[float] = ..., ydummy: Optional[float] = ...) -> None: ... +def ontimer(fun: Callable[[], Any], t: int = ...) -> None: ... +@overload +def bgpic(picname: None = ...) -> str: ... +@overload +def bgpic(picname: str) -> None: ... +@overload +def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... +@overload +def screensize(canvwidth: int, canvheight: int, bg: Optional[_Color] = ...) -> None: ... + +onscreenclick = onclick +resetscreen = reset +clearscreen = clear +addshape = register_shape +# Functions copied from _Screen: + +def setup(width: float = ..., height: float = ..., startx: Optional[int] = ..., starty: Optional[int] = ...) -> None: ... +def title(titlestring: str) -> None: ... +def bye() -> None: ... +def exitonclick() -> None: ... +def Screen() -> _Screen: ... + +# Functions copied from TNavigator: + +def degrees(fullcircle: float = ...) -> None: ... +def radians() -> None: ... +def forward(distance: float) -> None: ... +def back(distance: float) -> None: ... +def right(angle: float) -> None: ... +def left(angle: float) -> None: ... +def pos() -> Vec2D: ... +def xcor() -> float: ... +def ycor() -> float: ... +@overload +def goto(x: Tuple[float, float], y: None = ...) -> None: ... +@overload +def goto(x: float, y: float) -> None: ... +def home() -> None: ... +def setx(x: float) -> None: ... +def sety(y: float) -> None: ... +@overload +def distance(x: Union[TNavigator, Tuple[float, float]], y: None = ...) -> float: ... +@overload +def distance(x: float, y: float) -> float: ... +@overload +def towards(x: Union[TNavigator, Tuple[float, float]], y: None = ...) -> float: ... +@overload +def towards(x: float, y: float) -> float: ... +def heading() -> float: ... +def setheading(to_angle: float) -> None: ... +def circle(radius: float, extent: Optional[float] = ..., steps: Optional[int] = ...) -> None: ... + +fd = forward +bk = back +backward = back +rt = right +lt = left +position = pos +setpos = goto +setposition = goto +seth = setheading + +# Functions copied from TPen: +@overload +def resizemode(rmode: None = ...) -> str: ... +@overload +def resizemode(rmode: str) -> None: ... +@overload +def pensize(width: None = ...) -> int: ... +@overload +def pensize(width: int) -> None: ... +def penup() -> None: ... +def pendown() -> None: ... +def isdown() -> bool: ... +@overload +def speed(speed: None = ...) -> int: ... +@overload +def speed(speed: _Speed) -> None: ... +@overload +def pencolor() -> _AnyColor: ... +@overload +def pencolor(color: _Color) -> None: ... +@overload +def pencolor(r: float, g: float, b: float) -> None: ... +@overload +def fillcolor() -> _AnyColor: ... +@overload +def fillcolor(color: _Color) -> None: ... +@overload +def fillcolor(r: float, g: float, b: float) -> None: ... +@overload +def color() -> Tuple[_AnyColor, _AnyColor]: ... +@overload +def color(color: _Color) -> None: ... +@overload +def color(r: float, g: float, b: float) -> None: ... +@overload +def color(color1: _Color, color2: _Color) -> None: ... +def showturtle() -> None: ... +def hideturtle() -> None: ... +def isvisible() -> bool: ... + +# Note: signatures 1 and 2 overlap unsafely when no arguments are provided +@overload +def pen() -> _PenState: ... # type: ignore +@overload +def pen( + pen: Optional[_PenState] = ..., + *, + shown: bool = ..., + pendown: bool = ..., + pencolor: _Color = ..., + fillcolor: _Color = ..., + pensize: int = ..., + speed: int = ..., + resizemode: str = ..., + stretchfactor: Tuple[float, float] = ..., + outline: int = ..., + tilt: float = ..., +) -> None: ... + +width = pensize +up = penup +pu = penup +pd = pendown +down = pendown +st = showturtle +ht = hideturtle + +# Functions copied from RawTurtle: + +def setundobuffer(size: Optional[int]) -> None: ... +def undobufferentries() -> int: ... +@overload +def shape(name: None = ...) -> str: ... +@overload +def shape(name: str) -> None: ... + +# Unsafely overlaps when no arguments are provided +@overload +def shapesize() -> Tuple[float, float, float]: ... # type: ignore +@overload +def shapesize(stretch_wid: Optional[float] = ..., stretch_len: Optional[float] = ..., outline: Optional[float] = ...) -> None: ... +def settiltangle(angle: float) -> None: ... +@overload +def tiltangle(angle: None = ...) -> float: ... +@overload +def tiltangle(angle: float) -> None: ... +def tilt(angle: float) -> None: ... + +# Can return either 'int' or Tuple[int, ...] based on if the stamp is +# a compound stamp or not. So, as per the "no Union return" policy, +# we return Any. +def stamp() -> Any: ... +def clearstamp(stampid: Union[int, Tuple[int, ...]]) -> None: ... +def clearstamps(n: Optional[int] = ...) -> None: ... +def filling() -> bool: ... +def begin_fill() -> None: ... +def end_fill() -> None: ... +def dot(size: Optional[int] = ..., *color: _Color) -> None: ... +def write(arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... +def begin_poly() -> None: ... +def end_poly() -> None: ... +def get_poly() -> Optional[_PolygonCoords]: ... +def getscreen() -> TurtleScreen: ... +def getturtle() -> Turtle: ... + +getpen = getturtle + +def onrelease(fun: Callable[[float, float], Any], btn: int = ..., add: Optional[Any] = ...) -> None: ... +def ondrag(fun: Callable[[float, float], Any], btn: int = ..., add: Optional[Any] = ...) -> None: ... +def undo() -> None: ... + +turtlesize = shapesize + +# Functions copied from RawTurtle with a few tweaks: + +def clone() -> Turtle: ... + +# Extra functions present only in the global scope: + +done = mainloop diff --git a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi new file mode 100644 index 000000000000..2499ae19d0f9 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi @@ -0,0 +1,107 @@ +import abc +from typing import ( + TYPE_CHECKING as TYPE_CHECKING, + Any, + Callable, + ClassVar as ClassVar, + ContextManager as ContextManager, + Counter as Counter, + DefaultDict as DefaultDict, + Deque as Deque, + Dict, + ItemsView, + KeysView, + Mapping, + NewType as NewType, + NoReturn as NoReturn, + Optional, + Text as Text, + Tuple, + Type as Type, + TypeVar, + Union, + ValuesView, + _Alias, + overload as overload, +) + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_TC = TypeVar("_TC", bound=Type[object]) + +class _SpecialForm: + def __getitem__(self, typeargs: Any) -> Any: ... + +def runtime_checkable(cls: _TC) -> _TC: ... + +# This alias for above is kept here for backwards compatibility. +runtime = runtime_checkable +Protocol: _SpecialForm = ... +Final: _SpecialForm = ... + +def final(f: _F) -> _F: ... + +Literal: _SpecialForm = ... + +def IntVar(name: str) -> Any: ... # returns a new TypeVar + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): + def copy(self: _T) -> _T: ... + # Using NoReturn so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: NoReturn, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore + def update(self: _T, __m: _T) -> None: ... + def has_key(self, k: str) -> bool: ... + def viewitems(self) -> ItemsView[str, object]: ... + def viewkeys(self) -> KeysView[str]: ... + def viewvalues(self) -> ValuesView[object]: ... + def __delitem__(self, k: NoReturn) -> None: ... + +# TypedDict is a (non-subscriptable) special form. +TypedDict: object = ... + +OrderedDict = _Alias() + +def get_type_hints( + obj: Callable[..., Any], + globalns: Optional[Dict[str, Any]] = ..., + localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ..., +) -> Dict[str, Any]: ... + +Annotated: _SpecialForm = ... +_AnnotatedAlias: Any = ... # undocumented + +@runtime_checkable +class SupportsIndex(Protocol, metaclass=abc.ABCMeta): + @abc.abstractmethod + def __index__(self) -> int: ... + +# PEP 612 support for Python < 3.9 +class ParamSpecArgs: + __origin__: ParamSpec + def __init__(self, origin: ParamSpec) -> None: ... + +class ParamSpecKwargs: + __origin__: ParamSpec + def __init__(self, origin: ParamSpec) -> None: ... + +class ParamSpec: + __name__: str + __bound__: Optional[Type[Any]] + __covariant__: bool + __contravariant__: bool + def __init__( + self, name: str, *, bound: Union[None, Type[Any], str] = ..., contravariant: bool = ..., covariant: bool = ... + ) -> None: ... + @property + def args(self) -> ParamSpecArgs: ... + @property + def kwargs(self) -> ParamSpecKwargs: ... + +Concatenate: _SpecialForm = ... +TypeAlias: _SpecialForm = ... +TypeGuard: _SpecialForm = ... diff --git a/mypy/typeshed/stdlib/@python2/unicodedata.pyi b/mypy/typeshed/stdlib/@python2/unicodedata.pyi new file mode 100644 index 000000000000..19c4a6781660 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/unicodedata.pyi @@ -0,0 +1,37 @@ +from typing import Any, Text, TypeVar, Union + +ucd_3_2_0: UCD +ucnhash_CAPI: Any +unidata_version: str + +_T = TypeVar("_T") + +def bidirectional(__chr: Text) -> Text: ... +def category(__chr: Text) -> Text: ... +def combining(__chr: Text) -> int: ... +def decimal(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... +def decomposition(__chr: Text) -> Text: ... +def digit(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... +def east_asian_width(__chr: Text) -> Text: ... +def lookup(__name: Union[Text, bytes]) -> Text: ... +def mirrored(__chr: Text) -> int: ... +def name(__chr: Text, __default: _T = ...) -> Union[Text, _T]: ... +def normalize(__form: Text, __unistr: Text) -> Text: ... +def numeric(__chr: Text, __default: _T = ...) -> Union[float, _T]: ... + +class UCD(object): + # The methods below are constructed from the same array in C + # (unicodedata_functions) and hence identical to the methods above. + unidata_version: str + def bidirectional(self, __chr: Text) -> str: ... + def category(self, __chr: Text) -> str: ... + def combining(self, __chr: Text) -> int: ... + def decimal(self, __chr: Text, __default: _T = ...) -> Union[int, _T]: ... + def decomposition(self, __chr: Text) -> str: ... + def digit(self, __chr: Text, __default: _T = ...) -> Union[int, _T]: ... + def east_asian_width(self, __chr: Text) -> str: ... + def lookup(self, __name: Union[Text, bytes]) -> Text: ... + def mirrored(self, __chr: Text) -> int: ... + def name(self, __chr: Text, __default: _T = ...) -> Union[Text, _T]: ... + def normalize(self, __form: Text, __unistr: Text) -> Text: ... + def numeric(self, __chr: Text, __default: _T = ...) -> Union[float, _T]: ... diff --git a/mypy/typeshed/stdlib/@python2/uu.pyi b/mypy/typeshed/stdlib/@python2/uu.pyi new file mode 100644 index 000000000000..69d5754bc216 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/uu.pyi @@ -0,0 +1,8 @@ +from typing import BinaryIO, Optional, Text, Union + +_File = Union[Text, BinaryIO] + +class Error(Exception): ... + +def encode(in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ...) -> None: ... +def decode(in_file: _File, out_file: Optional[_File] = ..., mode: Optional[int] = ..., quiet: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/uuid.pyi b/mypy/typeshed/stdlib/@python2/uuid.pyi new file mode 100644 index 000000000000..791268a18475 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/uuid.pyi @@ -0,0 +1,81 @@ +from typing import Any, Optional, Text, Tuple + +# Because UUID has properties called int and bytes we need to rename these temporarily. +_Int = int +_Bytes = bytes +_FieldsType = Tuple[int, int, int, int, int, int] + +class UUID: + def __init__( + self, + hex: Optional[Text] = ..., + bytes: Optional[_Bytes] = ..., + bytes_le: Optional[_Bytes] = ..., + fields: Optional[_FieldsType] = ..., + int: Optional[_Int] = ..., + version: Optional[_Int] = ..., + ) -> None: ... + @property + def bytes(self) -> _Bytes: ... + @property + def bytes_le(self) -> _Bytes: ... + @property + def clock_seq(self) -> _Int: ... + @property + def clock_seq_hi_variant(self) -> _Int: ... + @property + def clock_seq_low(self) -> _Int: ... + @property + def fields(self) -> _FieldsType: ... + @property + def hex(self) -> str: ... + @property + def int(self) -> _Int: ... + @property + def node(self) -> _Int: ... + @property + def time(self) -> _Int: ... + @property + def time_hi_version(self) -> _Int: ... + @property + def time_low(self) -> _Int: ... + @property + def time_mid(self) -> _Int: ... + @property + def urn(self) -> str: ... + @property + def variant(self) -> str: ... + @property + def version(self) -> Optional[_Int]: ... + def __int__(self) -> _Int: ... + def get_bytes(self) -> _Bytes: ... + def get_bytes_le(self) -> _Bytes: ... + def get_clock_seq(self) -> _Int: ... + def get_clock_seq_hi_variant(self) -> _Int: ... + def get_clock_seq_low(self) -> _Int: ... + def get_fields(self) -> _FieldsType: ... + def get_hex(self) -> str: ... + def get_node(self) -> _Int: ... + def get_time(self) -> _Int: ... + def get_time_hi_version(self) -> _Int: ... + def get_time_low(self) -> _Int: ... + def get_time_mid(self) -> _Int: ... + def get_urn(self) -> str: ... + def get_variant(self) -> str: ... + def get_version(self) -> Optional[_Int]: ... + def __cmp__(self, other: Any) -> _Int: ... + +def getnode() -> int: ... +def uuid1(node: Optional[_Int] = ..., clock_seq: Optional[_Int] = ...) -> UUID: ... +def uuid3(namespace: UUID, name: str) -> UUID: ... +def uuid4() -> UUID: ... +def uuid5(namespace: UUID, name: str) -> UUID: ... + +NAMESPACE_DNS: UUID +NAMESPACE_URL: UUID +NAMESPACE_OID: UUID +NAMESPACE_X500: UUID +RESERVED_NCS: str +RFC_4122: str +RESERVED_MICROSOFT: str +RESERVED_FUTURE: str diff --git a/mypy/typeshed/stdlib/@python2/warnings.pyi b/mypy/typeshed/stdlib/@python2/warnings.pyi new file mode 100644 index 000000000000..a94e9fc86d2e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/warnings.pyi @@ -0,0 +1,59 @@ +from types import ModuleType, TracebackType +from typing import List, Optional, TextIO, Type, Union, overload +from typing_extensions import Literal + +from _warnings import warn as warn, warn_explicit as warn_explicit + +def showwarning( + message: Union[Warning, str], + category: Type[Warning], + filename: str, + lineno: int, + file: Optional[TextIO] = ..., + line: Optional[str] = ..., +) -> None: ... +def formatwarning( + message: Union[Warning, str], category: Type[Warning], filename: str, lineno: int, line: Optional[str] = ... +) -> str: ... +def filterwarnings( + action: str, message: str = ..., category: Type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ... +) -> None: ... +def simplefilter(action: str, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... +def resetwarnings() -> None: ... + +class _OptionError(Exception): ... + +class WarningMessage: + message: Union[Warning, str] + category: Type[Warning] + filename: str + lineno: int + file: Optional[TextIO] + line: Optional[str] + def __init__( + self, + message: Union[Warning, str], + category: Type[Warning], + filename: str, + lineno: int, + file: Optional[TextIO] = ..., + line: Optional[str] = ..., + ) -> None: ... + +class catch_warnings: + @overload + def __new__(cls, *, record: Literal[False] = ..., module: Optional[ModuleType] = ...) -> _catch_warnings_without_records: ... + @overload + def __new__(cls, *, record: Literal[True], module: Optional[ModuleType] = ...) -> _catch_warnings_with_records: ... + @overload + def __new__(cls, *, record: bool, module: Optional[ModuleType] = ...) -> catch_warnings: ... + def __enter__(self) -> Optional[List[WarningMessage]]: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + +class _catch_warnings_without_records(catch_warnings): + def __enter__(self) -> None: ... + +class _catch_warnings_with_records(catch_warnings): + def __enter__(self) -> List[WarningMessage]: ... diff --git a/mypy/typeshed/stdlib/@python2/wave.pyi b/mypy/typeshed/stdlib/@python2/wave.pyi new file mode 100644 index 000000000000..8615d8fad8ca --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wave.pyi @@ -0,0 +1,56 @@ +from typing import IO, Any, BinaryIO, NoReturn, Optional, Text, Tuple, Union + +_File = Union[Text, IO[bytes]] + +class Error(Exception): ... + +WAVE_FORMAT_PCM: int + +_wave_params = Tuple[int, int, int, int, str, str] + +class Wave_read: + def __init__(self, f: _File) -> None: ... + def getfp(self) -> Optional[BinaryIO]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _wave_params: ... + def getmarkers(self) -> None: ... + def getmark(self, id: Any) -> NoReturn: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes: ... + +class Wave_write: + def __init__(self, f: _File) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: str, compname: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def setparams(self, params: _wave_params) -> None: ... + def getparams(self) -> _wave_params: ... + def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... + def getmark(self, id: Any) -> NoReturn: ... + def getmarkers(self) -> None: ... + def tell(self) -> int: ... + # should be any bytes-like object after 3.4, but we don't have a type for that + def writeframesraw(self, data: bytes) -> None: ... + def writeframes(self, data: bytes) -> None: ... + def close(self) -> None: ... + +# Returns a Wave_read if mode is rb and Wave_write if mode is wb +def open(f: _File, mode: Optional[str] = ...) -> Any: ... + +openfp = open diff --git a/mypy/typeshed/stdlib/@python2/weakref.pyi b/mypy/typeshed/stdlib/@python2/weakref.pyi new file mode 100644 index 000000000000..5e8f4cd12b03 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/weakref.pyi @@ -0,0 +1,86 @@ +from _weakrefset import WeakSet as WeakSet +from typing import ( + Any, + Callable, + Generic, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + Tuple, + Type, + TypeVar, + Union, + overload, +) + +from _weakref import ( + CallableProxyType as CallableProxyType, + ProxyType as ProxyType, + ReferenceType as ReferenceType, + getweakrefcount as getweakrefcount, + getweakrefs as getweakrefs, + proxy as proxy, + ref as ref, +) +from exceptions import ReferenceError as ReferenceError + +_S = TypeVar("_S") +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +ProxyTypes: Tuple[Type[Any], ...] + +class WeakValueDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __other: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def has_key(self, key: object) -> bool: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + def copy(self) -> WeakValueDictionary[_KT, _VT]: ... + def keys(self) -> List[_KT]: ... + def values(self) -> List[_VT]: ... + def items(self) -> List[Tuple[_KT, _VT]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... + def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... + +class KeyedRef(ref[_T], Generic[_KT, _T]): + key: _KT + # This __new__ method uses a non-standard name for the "cls" parameter + def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore + def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... + +class WeakKeyDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self, dict: None = ...) -> None: ... + @overload + def __init__(self, dict: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]]) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def has_key(self, key: object) -> bool: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... + def keys(self) -> List[_KT]: ... + def values(self) -> List[_VT]: ... + def items(self) -> List[Tuple[_KT, _VT]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... + def keyrefs(self) -> List[ref[_KT]]: ... diff --git a/mypy/typeshed/stdlib/@python2/webbrowser.pyi b/mypy/typeshed/stdlib/@python2/webbrowser.pyi new file mode 100644 index 000000000000..9e143bb8c88f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/webbrowser.pyi @@ -0,0 +1,96 @@ +import sys +from typing import Callable, List, Optional, Sequence, Text, Union + +class Error(Exception): ... + +def register( + name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., update_tryorder: int = ... +) -> None: ... +def get(using: Optional[Text] = ...) -> BaseBrowser: ... +def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... +def open_new(url: Text) -> bool: ... +def open_new_tab(url: Text) -> bool: ... + +class BaseBrowser: + args: List[str] + name: str + basename: str + def __init__(self, name: Text = ...) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open_new(self, url: Text) -> bool: ... + def open_new_tab(self, url: Text) -> bool: ... + +class GenericBrowser(BaseBrowser): + args: List[str] + name: str + basename: str + def __init__(self, name: Union[Text, Sequence[Text]]) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class BackgroundBrowser(GenericBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class UnixBrowser(BaseBrowser): + raise_opts: Optional[List[str]] + background: bool + redirect_stdout: bool + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Mozilla(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Galeon(UnixBrowser): + raise_opts: List[str] + remote_args: List[str] + remote_action: str + remote_action_newwin: str + background: bool + +class Chrome(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Opera(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + +class Elinks(UnixBrowser): + remote_args: List[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + background: bool + redirect_stdout: bool + +class Konqueror(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Grail(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +if sys.platform == "win32": + class WindowsDefault(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +if sys.platform == "darwin": + class MacOSX(BaseBrowser): + name: str + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + class MacOSXOSAScript(BaseBrowser): + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/winsound.pyi b/mypy/typeshed/stdlib/@python2/winsound.pyi new file mode 100644 index 000000000000..be9a8c660781 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/winsound.pyi @@ -0,0 +1,27 @@ +import sys +from typing import Optional, Union, overload +from typing_extensions import Literal + +if sys.platform == "win32": + SND_FILENAME: int + SND_ALIAS: int + SND_LOOP: int + SND_MEMORY: int + SND_PURGE: int + SND_ASYNC: int + SND_NODEFAULT: int + SND_NOSTOP: int + SND_NOWAIT: int + + MB_ICONASTERISK: int + MB_ICONEXCLAMATION: int + MB_ICONHAND: int + MB_ICONQUESTION: int + MB_OK: int + def Beep(frequency: int, duration: int) -> None: ... + # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible + @overload + def PlaySound(sound: Optional[bytes], flags: Literal[4]) -> None: ... + @overload + def PlaySound(sound: Optional[Union[str, bytes]], flags: int) -> None: ... + def MessageBeep(type: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/__init__.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi new file mode 100644 index 000000000000..e8d32bea3f7b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi @@ -0,0 +1,89 @@ +from abc import abstractmethod +from types import TracebackType +from typing import IO, Callable, List, MutableMapping, Optional, Text, Tuple, Type + +from .headers import Headers +from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment +from .util import FileWrapper + +_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +def format_date_time(timestamp: Optional[float]) -> str: ... # undocumented + +class BaseHandler: + wsgi_version: Tuple[int, int] # undocumented + wsgi_multithread: bool + wsgi_multiprocess: bool + wsgi_run_once: bool + + origin_server: bool + http_version: str + server_software: Optional[str] + + os_environ: MutableMapping[str, str] + + wsgi_file_wrapper: Optional[Type[FileWrapper]] + headers_class: Type[Headers] # undocumented + + traceback_limit: Optional[int] + error_status: str + error_headers: List[Tuple[Text, Text]] + error_body: bytes + def run(self, application: WSGIApplication) -> None: ... + def setup_environ(self) -> None: ... + def finish_response(self) -> None: ... + def get_scheme(self) -> str: ... + def set_content_length(self) -> None: ... + def cleanup_headers(self) -> None: ... + def start_response( + self, status: Text, headers: List[Tuple[Text, Text]], exc_info: Optional[_exc_info] = ... + ) -> Callable[[bytes], None]: ... + def send_preamble(self) -> None: ... + def write(self, data: bytes) -> None: ... + def sendfile(self) -> bool: ... + def finish_content(self) -> None: ... + def close(self) -> None: ... + def send_headers(self) -> None: ... + def result_is_file(self) -> bool: ... + def client_is_modern(self) -> bool: ... + def log_exception(self, exc_info: _exc_info) -> None: ... + def handle_error(self) -> None: ... + def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... + @abstractmethod + def _write(self, data: bytes) -> None: ... + @abstractmethod + def _flush(self) -> None: ... + @abstractmethod + def get_stdin(self) -> InputStream: ... + @abstractmethod + def get_stderr(self) -> ErrorStream: ... + @abstractmethod + def add_cgi_vars(self) -> None: ... + +class SimpleHandler(BaseHandler): + stdin: InputStream + stdout: IO[bytes] + stderr: ErrorStream + base_env: MutableMapping[str, str] + def __init__( + self, + stdin: InputStream, + stdout: IO[bytes], + stderr: ErrorStream, + environ: MutableMapping[str, str], + multithread: bool = ..., + multiprocess: bool = ..., + ) -> None: ... + def get_stdin(self) -> InputStream: ... + def get_stderr(self) -> ErrorStream: ... + def add_cgi_vars(self) -> None: ... + def _write(self, data: bytes) -> None: ... + def _flush(self) -> None: ... + +class BaseCGIHandler(SimpleHandler): ... + +class CGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... + +class IISCGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi new file mode 100644 index 000000000000..b1c0d4f56fe6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi @@ -0,0 +1,24 @@ +from typing import List, Optional, Pattern, Tuple, overload + +_HeaderList = List[Tuple[str, str]] + +tspecials: Pattern[str] # undocumented + +class Headers: + def __init__(self, headers: _HeaderList) -> None: ... + def __len__(self) -> int: ... + def __setitem__(self, name: str, val: str) -> None: ... + def __delitem__(self, name: str) -> None: ... + def __getitem__(self, name: str) -> Optional[str]: ... + def has_key(self, name: str) -> bool: ... + def __contains__(self, name: str) -> bool: ... + def get_all(self, name: str) -> List[str]: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: Optional[str] = ...) -> Optional[str]: ... + def keys(self) -> List[str]: ... + def values(self) -> List[str]: ... + def items(self) -> _HeaderList: ... + def setdefault(self, name: str, value: str) -> str: ... + def add_header(self, _name: str, _value: Optional[str], **_params: Optional[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi new file mode 100644 index 000000000000..7e18442f6055 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi @@ -0,0 +1,37 @@ +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from typing import List, Optional, Type, TypeVar, overload + +from .handlers import SimpleHandler +from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment + +server_version: str # undocumented +sys_version: str # undocumented +software_version: str # undocumented + +class ServerHandler(SimpleHandler): # undocumented + server_software: str + def close(self) -> None: ... + +class WSGIServer(HTTPServer): + application: Optional[WSGIApplication] + base_environ: WSGIEnvironment # only available after call to setup_environ() + def setup_environ(self) -> None: ... + def get_app(self) -> Optional[WSGIApplication]: ... + def set_app(self, application: Optional[WSGIApplication]) -> None: ... + +class WSGIRequestHandler(BaseHTTPRequestHandler): + server_version: str + def get_environ(self) -> WSGIEnvironment: ... + def get_stderr(self) -> ErrorStream: ... + def handle(self) -> None: ... + +def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... + +_S = TypeVar("_S", bound=WSGIServer) + +@overload +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +@overload +def make_server( + host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... +) -> _S: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/types.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/types.pyi new file mode 100644 index 000000000000..c272ae67c391 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/types.pyi @@ -0,0 +1,3 @@ +# Obsolete, use _typeshed.wsgi directly. + +from _typeshed.wsgi import * diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/util.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/util.pyi new file mode 100644 index 000000000000..e1179ebab365 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/util.pyi @@ -0,0 +1,19 @@ +from typing import IO, Any, Callable, Optional + +from .types import WSGIEnvironment + +class FileWrapper: + filelike: IO[bytes] + blksize: int + close: Callable[[], None] # only exists if filelike.close exists + def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... + def __getitem__(self, key: Any) -> bytes: ... + def __iter__(self) -> FileWrapper: ... + def next(self) -> bytes: ... + +def guess_scheme(environ: WSGIEnvironment) -> str: ... +def application_uri(environ: WSGIEnvironment) -> str: ... +def request_uri(environ: WSGIEnvironment, include_query: bool = ...) -> str: ... +def shift_path_info(environ: WSGIEnvironment) -> Optional[str]: ... +def setup_testing_defaults(environ: WSGIEnvironment) -> None: ... +def is_hop_by_hop(header_name: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/validate.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/validate.pyi new file mode 100644 index 000000000000..5918374d5fd8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/wsgiref/validate.pyi @@ -0,0 +1,44 @@ +from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication +from typing import Any, Callable, Iterable, Iterator, NoReturn, Optional + +class WSGIWarning(Warning): ... + +def validator(application: WSGIApplication) -> WSGIApplication: ... + +class InputWrapper: + input: InputStream + def __init__(self, wsgi_input: InputStream) -> None: ... + def read(self, size: int = ...) -> bytes: ... + def readline(self) -> bytes: ... + def readlines(self, hint: int = ...) -> bytes: ... + def __iter__(self) -> Iterable[bytes]: ... + def close(self) -> NoReturn: ... + +class ErrorWrapper: + errors: ErrorStream + def __init__(self, wsgi_errors: ErrorStream) -> None: ... + def write(self, s: str) -> None: ... + def flush(self) -> None: ... + def writelines(self, seq: Iterable[str]) -> None: ... + def close(self) -> NoReturn: ... + +class WriteWrapper: + writer: Callable[[bytes], Any] + def __init__(self, wsgi_writer: Callable[[bytes], Any]) -> None: ... + def __call__(self, s: bytes) -> None: ... + +class PartialIteratorWrapper: + iterator: Iterator[bytes] + def __init__(self, wsgi_iterator: Iterator[bytes]) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + +class IteratorWrapper: + original_iterator: Iterator[bytes] + iterator: Iterator[bytes] + closed: bool + check_start_response: Optional[bool] + def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: Optional[bool]) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + def next(self) -> bytes: ... + def close(self) -> None: ... + def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xdrlib.pyi b/mypy/typeshed/stdlib/@python2/xdrlib.pyi new file mode 100644 index 000000000000..378504c37227 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xdrlib.pyi @@ -0,0 +1,55 @@ +from typing import Callable, List, Sequence, TypeVar + +_T = TypeVar("_T") + +class Error(Exception): + msg: str + def __init__(self, msg: str) -> None: ... + +class ConversionError(Error): ... + +class Packer: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def get_buffer(self) -> bytes: ... + def get_buf(self) -> bytes: ... + def pack_uint(self, x: int) -> None: ... + def pack_int(self, x: int) -> None: ... + def pack_enum(self, x: int) -> None: ... + def pack_bool(self, x: bool) -> None: ... + def pack_uhyper(self, x: int) -> None: ... + def pack_hyper(self, x: int) -> None: ... + def pack_float(self, x: float) -> None: ... + def pack_double(self, x: float) -> None: ... + def pack_fstring(self, n: int, s: bytes) -> None: ... + def pack_fopaque(self, n: int, s: bytes) -> None: ... + def pack_string(self, s: bytes) -> None: ... + def pack_opaque(self, s: bytes) -> None: ... + def pack_bytes(self, s: bytes) -> None: ... + def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + +class Unpacker: + def __init__(self, data: bytes) -> None: ... + def reset(self, data: bytes) -> None: ... + def get_position(self) -> int: ... + def set_position(self, position: int) -> None: ... + def get_buffer(self) -> bytes: ... + def done(self) -> None: ... + def unpack_uint(self) -> int: ... + def unpack_int(self) -> int: ... + def unpack_enum(self) -> int: ... + def unpack_bool(self) -> bool: ... + def unpack_uhyper(self) -> int: ... + def unpack_hyper(self) -> int: ... + def unpack_float(self) -> float: ... + def unpack_double(self) -> float: ... + def unpack_fstring(self, n: int) -> bytes: ... + def unpack_fopaque(self, n: int) -> bytes: ... + def unpack_string(self) -> bytes: ... + def unpack_opaque(self) -> bytes: ... + def unpack_bytes(self) -> bytes: ... + def unpack_list(self, unpack_item: Callable[[], _T]) -> List[_T]: ... + def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> List[_T]: ... + def unpack_array(self, unpack_item: Callable[[], _T]) -> List[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/__init__.pyi new file mode 100644 index 000000000000..c524ac2b1cfc --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers as parsers diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/NodeFilter.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/NodeFilter.pyi new file mode 100644 index 000000000000..80fb73d23433 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/NodeFilter.pyi @@ -0,0 +1,19 @@ +class NodeFilter: + FILTER_ACCEPT: int + FILTER_REJECT: int + FILTER_SKIP: int + + SHOW_ALL: int + SHOW_ELEMENT: int + SHOW_ATTRIBUTE: int + SHOW_TEXT: int + SHOW_CDATA_SECTION: int + SHOW_ENTITY_REFERENCE: int + SHOW_ENTITY: int + SHOW_PROCESSING_INSTRUCTION: int + SHOW_COMMENT: int + SHOW_DOCUMENT: int + SHOW_DOCUMENT_TYPE: int + SHOW_DOCUMENT_FRAGMENT: int + SHOW_NOTATION: int + def acceptNode(self, node) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/__init__.pyi new file mode 100644 index 000000000000..c5766c326c3e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/__init__.pyi @@ -0,0 +1,68 @@ +from typing import Any + +from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation + +class Node: + ELEMENT_NODE: int + ATTRIBUTE_NODE: int + TEXT_NODE: int + CDATA_SECTION_NODE: int + ENTITY_REFERENCE_NODE: int + ENTITY_NODE: int + PROCESSING_INSTRUCTION_NODE: int + COMMENT_NODE: int + DOCUMENT_NODE: int + DOCUMENT_TYPE_NODE: int + DOCUMENT_FRAGMENT_NODE: int + NOTATION_NODE: int + +# ExceptionCode +INDEX_SIZE_ERR: int +DOMSTRING_SIZE_ERR: int +HIERARCHY_REQUEST_ERR: int +WRONG_DOCUMENT_ERR: int +INVALID_CHARACTER_ERR: int +NO_DATA_ALLOWED_ERR: int +NO_MODIFICATION_ALLOWED_ERR: int +NOT_FOUND_ERR: int +NOT_SUPPORTED_ERR: int +INUSE_ATTRIBUTE_ERR: int +INVALID_STATE_ERR: int +SYNTAX_ERR: int +INVALID_MODIFICATION_ERR: int +NAMESPACE_ERR: int +INVALID_ACCESS_ERR: int +VALIDATION_ERR: int + +class DOMException(Exception): + code: int + def __init__(self, *args: Any, **kw: Any) -> None: ... + def _get_code(self) -> int: ... + +class IndexSizeErr(DOMException): ... +class DomstringSizeErr(DOMException): ... +class HierarchyRequestErr(DOMException): ... +class WrongDocumentErr(DOMException): ... +class NoDataAllowedErr(DOMException): ... +class NoModificationAllowedErr(DOMException): ... +class NotFoundErr(DOMException): ... +class NotSupportedErr(DOMException): ... +class InuseAttributeErr(DOMException): ... +class InvalidStateErr(DOMException): ... +class SyntaxErr(DOMException): ... +class InvalidModificationErr(DOMException): ... +class NamespaceErr(DOMException): ... +class InvalidAccessErr(DOMException): ... +class ValidationErr(DOMException): ... + +class UserDataHandler: + NODE_CLONED: int + NODE_IMPORTED: int + NODE_DELETED: int + NODE_RENAMED: int + +XML_NAMESPACE: str +XMLNS_NAMESPACE: str +XHTML_NAMESPACE: str +EMPTY_NAMESPACE: None +EMPTY_PREFIX: None diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi new file mode 100644 index 000000000000..bf63ff09e106 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi @@ -0,0 +1,10 @@ +from _typeshed.xml import DOMImplementation +from typing import Callable, Dict, Iterable, Optional, Tuple, Union + +well_known_implementations: Dict[str, str] +registered: Dict[str, Callable[[], DOMImplementation]] + +def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... +def getDOMImplementation( + name: Optional[str] = ..., features: Union[str, Iterable[Tuple[str, Optional[str]]]] = ... +) -> DOMImplementation: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/expatbuilder.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/expatbuilder.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/expatbuilder.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi new file mode 100644 index 000000000000..aa8efd03b19f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi @@ -0,0 +1,17 @@ +from typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar + +_T = TypeVar("_T") + +StringTypes: Tuple[Type[str]] + +class NodeList(List[_T]): + length: int + def item(self, index: int) -> Optional[_T]: ... + +class EmptyNodeList(Tuple[Any, ...]): + length: int + def item(self, index: int) -> None: ... + def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore + def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... + +def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi new file mode 100644 index 000000000000..2f5988bf76e0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi @@ -0,0 +1,294 @@ +import xml.dom +from typing import IO, Any, Optional, Text as _Text, TypeVar, Union +from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS +from xml.sax.xmlreader import XMLReader + +_T = TypeVar("_T") + +def parse(file: Union[str, IO[Any]], parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... +def parseString(string: Union[bytes, _Text], parser: Optional[XMLReader] = ...): ... +def getDOMImplementation(features=...): ... + +class Node(xml.dom.Node): + namespaceURI: Optional[str] + parentNode: Any + ownerDocument: Any + nextSibling: Any + previousSibling: Any + prefix: Any + def toxml(self, encoding: Optional[Any] = ...): ... + def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Optional[Any] = ...): ... + def hasChildNodes(self) -> bool: ... + def insertBefore(self, newChild, refChild): ... + def appendChild(self, node): ... + def replaceChild(self, newChild, oldChild): ... + def removeChild(self, oldChild): ... + def normalize(self) -> None: ... + def cloneNode(self, deep): ... + def isSupported(self, feature, version): ... + def isSameNode(self, other): ... + def getInterface(self, feature): ... + def getUserData(self, key): ... + def setUserData(self, key, data, handler): ... + childNodes: Any + def unlink(self) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, et, ev, tb) -> None: ... + +class DocumentFragment(Node): + nodeType: Any + nodeName: str + nodeValue: Any + attributes: Any + parentNode: Any + childNodes: Any + def __init__(self) -> None: ... + +class Attr(Node): + name: str + nodeType: Any + attributes: Any + specified: bool + ownerElement: Any + namespaceURI: Optional[str] + childNodes: Any + nodeName: Any + nodeValue: str + value: str + prefix: Any + def __init__( + self, qName: str, namespaceURI: Optional[str] = ..., localName: Optional[Any] = ..., prefix: Optional[Any] = ... + ) -> None: ... + def unlink(self) -> None: ... + +class NamedNodeMap: + def __init__(self, attrs, attrsNS, ownerElement) -> None: ... + def item(self, index): ... + def items(self): ... + def itemsNS(self): ... + def __contains__(self, key): ... + def keys(self): ... + def keysNS(self): ... + def values(self): ... + def get(self, name, value: Optional[Any] = ...): ... + def __len__(self) -> int: ... + def __eq__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: ... + def __getitem__(self, attname_or_tuple): ... + def __setitem__(self, attname, value) -> None: ... + def getNamedItem(self, name): ... + def getNamedItemNS(self, namespaceURI: str, localName): ... + def removeNamedItem(self, name): ... + def removeNamedItemNS(self, namespaceURI: str, localName): ... + def setNamedItem(self, node): ... + def setNamedItemNS(self, node): ... + def __delitem__(self, attname_or_tuple) -> None: ... + +AttributeList = NamedNodeMap + +class TypeInfo: + namespace: Any + name: Any + def __init__(self, namespace, name) -> None: ... + +class Element(Node): + nodeType: Any + nodeValue: Any + schemaType: Any + parentNode: Any + tagName: str + prefix: Any + namespaceURI: Optional[str] + childNodes: Any + nextSibling: Any + def __init__( + self, tagName, namespaceURI: Optional[str] = ..., prefix: Optional[Any] = ..., localName: Optional[Any] = ... + ) -> None: ... + def unlink(self) -> None: ... + def getAttribute(self, attname): ... + def getAttributeNS(self, namespaceURI: str, localName): ... + def setAttribute(self, attname, value) -> None: ... + def setAttributeNS(self, namespaceURI: str, qualifiedName: str, value) -> None: ... + def getAttributeNode(self, attrname): ... + def getAttributeNodeNS(self, namespaceURI: str, localName): ... + def setAttributeNode(self, attr): ... + setAttributeNodeNS: Any + def removeAttribute(self, name) -> None: ... + def removeAttributeNS(self, namespaceURI: str, localName) -> None: ... + def removeAttributeNode(self, node): ... + removeAttributeNodeNS: Any + def hasAttribute(self, name: str) -> bool: ... + def hasAttributeNS(self, namespaceURI: str, localName) -> bool: ... + def getElementsByTagName(self, name): ... + def getElementsByTagNameNS(self, namespaceURI: str, localName): ... + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + def hasAttributes(self) -> bool: ... + def setIdAttribute(self, name) -> None: ... + def setIdAttributeNS(self, namespaceURI: str, localName) -> None: ... + def setIdAttributeNode(self, idAttr) -> None: ... + +class Childless: + attributes: Any + childNodes: Any + firstChild: Any + lastChild: Any + def appendChild(self, node) -> None: ... + def hasChildNodes(self) -> bool: ... + def insertBefore(self, newChild, refChild) -> None: ... + def removeChild(self, oldChild) -> None: ... + def normalize(self) -> None: ... + def replaceChild(self, newChild, oldChild) -> None: ... + +class ProcessingInstruction(Childless, Node): + nodeType: Any + target: Any + data: Any + def __init__(self, target, data) -> None: ... + nodeValue: Any + nodeName: Any + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + +class CharacterData(Childless, Node): + ownerDocument: Any + previousSibling: Any + def __init__(self) -> None: ... + def __len__(self) -> int: ... + data: str + nodeValue: Any + def substringData(self, offset: int, count: int) -> str: ... + def appendData(self, arg: str) -> None: ... + def insertData(self, offset: int, arg: str) -> None: ... + def deleteData(self, offset: int, count: int) -> None: ... + def replaceData(self, offset: int, count: int, arg: str) -> None: ... + +class Text(CharacterData): + nodeType: Any + nodeName: str + attributes: Any + data: Any + def splitText(self, offset): ... + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + def replaceWholeText(self, content): ... + +class Comment(CharacterData): + nodeType: Any + nodeName: str + def __init__(self, data) -> None: ... + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + +class CDATASection(Text): + nodeType: Any + nodeName: str + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + +class ReadOnlySequentialNamedNodeMap: + def __init__(self, seq=...) -> None: ... + def __len__(self): ... + def getNamedItem(self, name): ... + def getNamedItemNS(self, namespaceURI: str, localName): ... + def __getitem__(self, name_or_tuple): ... + def item(self, index): ... + def removeNamedItem(self, name) -> None: ... + def removeNamedItemNS(self, namespaceURI: str, localName) -> None: ... + def setNamedItem(self, node) -> None: ... + def setNamedItemNS(self, node) -> None: ... + +class Identified: ... + +class DocumentType(Identified, Childless, Node): + nodeType: Any + nodeValue: Any + name: Any + publicId: Any + systemId: Any + internalSubset: Any + entities: Any + notations: Any + nodeName: Any + def __init__(self, qualifiedName: str) -> None: ... + def cloneNode(self, deep): ... + def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... + +class Entity(Identified, Node): + attributes: Any + nodeType: Any + nodeValue: Any + actualEncoding: Any + encoding: Any + version: Any + nodeName: Any + notationName: Any + childNodes: Any + def __init__(self, name, publicId, systemId, notation) -> None: ... + def appendChild(self, newChild) -> None: ... + def insertBefore(self, newChild, refChild) -> None: ... + def removeChild(self, oldChild) -> None: ... + def replaceChild(self, newChild, oldChild) -> None: ... + +class Notation(Identified, Childless, Node): + nodeType: Any + nodeValue: Any + nodeName: Any + def __init__(self, name, publicId, systemId) -> None: ... + +class DOMImplementation(DOMImplementationLS): + def hasFeature(self, feature, version) -> bool: ... + def createDocument(self, namespaceURI: str, qualifiedName: str, doctype): ... + def createDocumentType(self, qualifiedName: str, publicId, systemId): ... + def getInterface(self, feature): ... + +class ElementInfo: + tagName: Any + def __init__(self, name) -> None: ... + def getAttributeType(self, aname): ... + def getAttributeTypeNS(self, namespaceURI: str, localName): ... + def isElementContent(self): ... + def isEmpty(self): ... + def isId(self, aname): ... + def isIdNS(self, namespaceURI: str, localName): ... + +class Document(Node, DocumentLS): + implementation: Any + nodeType: Any + nodeName: str + nodeValue: Any + attributes: Any + parentNode: Any + previousSibling: Any + nextSibling: Any + actualEncoding: Any + encoding: Any + standalone: Any + version: Any + strictErrorChecking: bool + errorHandler: Any + documentURI: Any + doctype: Any + childNodes: Any + def __init__(self) -> None: ... + def appendChild(self, node): ... + documentElement: Any + def removeChild(self, oldChild): ... + def unlink(self) -> None: ... + def cloneNode(self, deep): ... + def createDocumentFragment(self): ... + def createElement(self, tagName: str): ... + def createTextNode(self, data): ... + def createCDATASection(self, data): ... + def createComment(self, data): ... + def createProcessingInstruction(self, target, data): ... + def createAttribute(self, qName) -> Attr: ... + def createElementNS(self, namespaceURI: str, qualifiedName: str): ... + def createAttributeNS(self, namespaceURI: str, qualifiedName: str) -> Attr: ... + def getElementById(self, id): ... + def getElementsByTagName(self, name: str): ... + def getElementsByTagNameNS(self, namespaceURI: str, localName): ... + def isSupported(self, feature, version): ... + def importNode(self, node, deep): ... + def writexml( + self, writer, indent: str = ..., addindent: str = ..., newl: str = ..., encoding: Optional[Any] = ... + ) -> None: ... + def renameNode(self, n, namespaceURI: str, name): ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/pulldom.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/pulldom.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi new file mode 100644 index 000000000000..d8936bdc2ab4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi @@ -0,0 +1,6 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete + +class DocumentLS(Any): ... # type: ignore +class DOMImplementationLS(Any): ... # type: ignore diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementInclude.pyi new file mode 100644 index 000000000000..c6144e40852a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementInclude.pyi @@ -0,0 +1,15 @@ +from typing import Callable, Optional, Union +from xml.etree.ElementTree import Element + +XINCLUDE: str +XINCLUDE_INCLUDE: str +XINCLUDE_FALLBACK: str + +class FatalIncludeError(SyntaxError): ... + +def default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[str] = ...) -> Union[str, Element]: ... + +# TODO: loader is of type default_loader ie it takes a callable that has the +# same signature as default_loader. But default_loader has a keyword argument +# Which can't be represented using Callable... +def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi new file mode 100644 index 000000000000..de49ffcf1209 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi @@ -0,0 +1,33 @@ +from typing import Callable, Dict, Generator, List, Optional, Pattern, Tuple, TypeVar, Union +from xml.etree.ElementTree import Element + +xpath_tokenizer_re: Pattern[str] + +_token = Tuple[str, str] +_next = Callable[[], _token] +_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] + +def xpath_tokenizer(pattern: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[_token, None, None]: ... +def get_parent_map(context: _SelectorContext) -> Dict[Element, Element]: ... +def prepare_child(next: _next, token: _token) -> _callback: ... +def prepare_star(next: _next, token: _token) -> _callback: ... +def prepare_self(next: _next, token: _token) -> _callback: ... +def prepare_descendant(next: _next, token: _token) -> _callback: ... +def prepare_parent(next: _next, token: _token) -> _callback: ... +def prepare_predicate(next: _next, token: _token) -> _callback: ... + +ops: Dict[str, Callable[[_next, _token], _callback]] + +class _SelectorContext: + parent_map: Optional[Dict[Element, Element]] + root: Element + def __init__(self, root: Element) -> None: ... + +_T = TypeVar("_T") + +def iterfind(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[Element, None, None]: ... +def find(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Optional[Element]: ... +def findall(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... +def findtext( + elem: Element, path: str, default: Optional[_T] = ..., namespaces: Optional[Dict[str, str]] = ... +) -> Union[_T, str]: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi new file mode 100644 index 000000000000..f7527fa5d890 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi @@ -0,0 +1,208 @@ +from _typeshed import FileDescriptor +from typing import ( + IO, + Any, + Callable, + Dict, + Generator, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + MutableSequence, + Optional, + Sequence, + Text, + Tuple, + TypeVar, + Union, + overload, +) + +VERSION: str + +class ParseError(SyntaxError): + code: int + position: Tuple[int, int] + +def iselement(element: object) -> bool: ... + +_T = TypeVar("_T") + +# Type for parser inputs. Parser will accept any unicode/str/bytes and coerce, +# and this is true in py2 and py3 (even fromstringlist() in python3 can be +# called with a heterogeneous list) +_parser_input_type = Union[bytes, Text] + +# Type for individual tag/attr/ns/text values in args to most functions. +# In py2, the library accepts str or unicode everywhere and coerces +# aggressively. +# In py3, bytes is not coerced to str and so use of bytes is probably an error, +# so we exclude it. (why? the parser never produces bytes when it parses XML, +# so e.g., element.get(b'name') will always return None for parsed XML, even if +# there is a 'name' attribute.) +_str_argument_type = Union[str, Text] + +# Type for return values from individual tag/attr/text values +# in python2, if the tag/attribute/text wasn't decode-able as ascii, it +# comes out as a unicode string; otherwise it comes out as str. (see +# _fixtext function in the source). Client code knows best: +_str_result_type = Any + +_file_or_filename = Union[Text, FileDescriptor, IO[Any]] + +class Element(MutableSequence[Element]): + tag: _str_result_type + attrib: Dict[_str_result_type, _str_result_type] + text: Optional[_str_result_type] + tail: Optional[_str_result_type] + def __init__( + self, + tag: Union[_str_argument_type, Callable[..., Element]], + attrib: Dict[_str_argument_type, _str_argument_type] = ..., + **extra: _str_argument_type, + ) -> None: ... + def append(self, __subelement: Element) -> None: ... + def clear(self) -> None: ... + def extend(self, __elements: Iterable[Element]) -> None: ... + def find( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Optional[Element]: ... + def findall( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> List[Element]: ... + @overload + def findtext( + self, + path: _str_argument_type, + default: None = ..., + namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ..., + ) -> Optional[_str_result_type]: ... + @overload + def findtext( + self, path: _str_argument_type, default: _T, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Union[_T, _str_result_type]: ... + @overload + def get(self, key: _str_argument_type, default: None = ...) -> Optional[_str_result_type]: ... + @overload + def get(self, key: _str_argument_type, default: _T) -> Union[_str_result_type, _T]: ... + def insert(self, __index: int, __element: Element) -> None: ... + def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... + def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... + def iterfind( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Generator[Element, None, None]: ... + def itertext(self) -> Generator[_str_result_type, None, None]: ... + def keys(self) -> KeysView[_str_result_type]: ... + def makeelement(self, __tag: _str_argument_type, __attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... + def remove(self, __subelement: Element) -> None: ... + def set(self, __key: _str_argument_type, __value: _str_argument_type) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + @overload + def __getitem__(self, i: int) -> Element: ... + @overload + def __getitem__(self, s: slice) -> MutableSequence[Element]: ... + def __len__(self) -> int: ... + @overload + def __setitem__(self, i: int, o: Element) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... + def getchildren(self) -> List[Element]: ... + def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + +def SubElement( + parent: Element, + tag: _str_argument_type, + attrib: Dict[_str_argument_type, _str_argument_type] = ..., + **extra: _str_argument_type, +) -> Element: ... +def Comment(text: Optional[_str_argument_type] = ...) -> Element: ... +def ProcessingInstruction(target: _str_argument_type, text: Optional[_str_argument_type] = ...) -> Element: ... + +PI: Callable[..., Element] + +class QName: + text: str + def __init__(self, text_or_uri: _str_argument_type, tag: Optional[_str_argument_type] = ...) -> None: ... + +class ElementTree: + def __init__(self, element: Optional[Element] = ..., file: Optional[_file_or_filename] = ...) -> None: ... + def getroot(self) -> Element: ... + def parse(self, source: _file_or_filename, parser: Optional[XMLParser] = ...) -> Element: ... + def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... + def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + def find( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Optional[Element]: ... + @overload + def findtext( + self, + path: _str_argument_type, + default: None = ..., + namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ..., + ) -> Optional[_str_result_type]: ... + @overload + def findtext( + self, path: _str_argument_type, default: _T, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Union[_T, _str_result_type]: ... + def findall( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> List[Element]: ... + def iterfind( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> Generator[Element, None, None]: ... + def write( + self, + file_or_filename: _file_or_filename, + encoding: Optional[str] = ..., + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + method: Optional[str] = ..., + ) -> None: ... + def write_c14n(self, file: _file_or_filename) -> None: ... + +def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... +def tostring(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> bytes: ... +def tostringlist(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> List[bytes]: ... +def dump(elem: Element) -> None: ... +def parse(source: _file_or_filename, parser: Optional[XMLParser] = ...) -> ElementTree: ... +def iterparse( + source: _file_or_filename, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ... +) -> Iterator[Tuple[str, Any]]: ... +def XML(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Element: ... +def XMLID(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... + +# This is aliased to XML in the source. +fromstring = XML + +def fromstringlist(sequence: Sequence[_parser_input_type], parser: Optional[XMLParser] = ...) -> Element: ... + +# This type is both not precise enough and too precise. The TreeBuilder +# requires the elementfactory to accept tag and attrs in its args and produce +# some kind of object that has .text and .tail properties. +# I've chosen to constrain the ElementFactory to always produce an Element +# because that is how almost everyone will use it. +# Unfortunately, the type of the factory arguments is dependent on how +# TreeBuilder is called by client code (they could pass strs, bytes or whatever); +# but we don't want to use a too-broad type, or it would be too hard to write +# elementfactories. +_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] + +class TreeBuilder: + def __init__(self, element_factory: Optional[_ElementFactory] = ...) -> None: ... + def close(self) -> Element: ... + def data(self, __data: _parser_input_type) -> None: ... + def start(self, __tag: _parser_input_type, __attrs: Dict[_parser_input_type, _parser_input_type]) -> Element: ... + def end(self, __tag: _parser_input_type) -> Element: ... + +class XMLParser: + parser: Any + target: Any + # TODO-what is entity used for??? + entity: Any + version: str + def __init__(self, html: int = ..., target: Any = ..., encoding: Optional[str] = ...) -> None: ... + def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... + def close(self) -> Any: ... + def feed(self, __data: _parser_input_type) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi new file mode 100644 index 000000000000..c41e2bee0eb1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi @@ -0,0 +1 @@ +from xml.etree.ElementTree import * # noqa: F403 diff --git a/mypy/typeshed/stdlib/@python2/xml/parsers/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/parsers/__init__.pyi new file mode 100644 index 000000000000..cac086235cba --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/parsers/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers.expat as expat diff --git a/mypy/typeshed/stdlib/@python2/xml/parsers/expat/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/__init__.pyi new file mode 100644 index 000000000000..73f3758c61ec --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/__init__.pyi @@ -0,0 +1 @@ +from pyexpat import * diff --git a/mypy/typeshed/stdlib/@python2/xml/parsers/expat/errors.pyi b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/errors.pyi new file mode 100644 index 000000000000..e22d769ec340 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/errors.pyi @@ -0,0 +1 @@ +from pyexpat.errors import * diff --git a/mypy/typeshed/stdlib/@python2/xml/parsers/expat/model.pyi b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/model.pyi new file mode 100644 index 000000000000..d8f44b47c51b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/parsers/expat/model.pyi @@ -0,0 +1 @@ +from pyexpat.model import * diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi new file mode 100644 index 000000000000..f4ad8ba34c89 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi @@ -0,0 +1,27 @@ +from typing import IO, Any, List, NoReturn, Optional, Text, Union +from xml.sax.handler import ContentHandler, ErrorHandler +from xml.sax.xmlreader import Locator, XMLReader + +class SAXException(Exception): + def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ... + def getMessage(self) -> str: ... + def getException(self) -> Exception: ... + def __getitem__(self, ix: Any) -> NoReturn: ... + +class SAXParseException(SAXException): + def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... + def getColumnNumber(self) -> int: ... + def getLineNumber(self) -> int: ... + def getPublicId(self): ... + def getSystemId(self): ... + +class SAXNotRecognizedException(SAXException): ... +class SAXNotSupportedException(SAXException): ... +class SAXReaderNotAvailable(SAXNotSupportedException): ... + +default_parser_list: List[str] + +def make_parser(parser_list: List[str] = ...) -> XMLReader: ... +def parse(source: Union[str, IO[str], IO[bytes]], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... +def parseString(string: Union[bytes, Text], handler: ContentHandler, errorHandler: Optional[ErrorHandler] = ...) -> None: ... +def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/handler.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/handler.pyi new file mode 100644 index 000000000000..3a5193300981 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/sax/handler.pyi @@ -0,0 +1,46 @@ +from typing import Any + +version: Any + +class ErrorHandler: + def error(self, exception): ... + def fatalError(self, exception): ... + def warning(self, exception): ... + +class ContentHandler: + def __init__(self) -> None: ... + def setDocumentLocator(self, locator): ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, whitespace): ... + def processingInstruction(self, target, data): ... + def skippedEntity(self, name): ... + +class DTDHandler: + def notationDecl(self, name, publicId, systemId): ... + def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... + +class EntityResolver: + def resolveEntity(self, publicId, systemId): ... + +feature_namespaces: Any +feature_namespace_prefixes: Any +feature_string_interning: Any +feature_validation: Any +feature_external_ges: Any +feature_external_pes: Any +all_features: Any +property_lexical_handler: Any +property_declaration_handler: Any +property_dom_node: Any +property_xml_string: Any +property_encoding: Any +property_interning_dict: Any +all_properties: Any diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/saxutils.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/saxutils.pyi new file mode 100644 index 000000000000..3f2671eaacfe --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/sax/saxutils.pyi @@ -0,0 +1,59 @@ +from _typeshed import SupportsWrite +from codecs import StreamReaderWriter, StreamWriter +from io import RawIOBase, TextIOBase +from typing import Mapping, Optional, Text, Union +from xml.sax import handler, xmlreader + +def escape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... +def unescape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... +def quoteattr(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... + +class XMLGenerator(handler.ContentHandler): + def __init__( + self, + out: Optional[Union[TextIOBase, RawIOBase, StreamWriter, StreamReaderWriter, SupportsWrite[str]]] = ..., + encoding: Text = ..., + ) -> None: ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, content): ... + def processingInstruction(self, target, data): ... + +class XMLFilterBase(xmlreader.XMLReader): + def __init__(self, parent: Optional[xmlreader.XMLReader] = ...) -> None: ... + def error(self, exception): ... + def fatalError(self, exception): ... + def warning(self, exception): ... + def setDocumentLocator(self, locator): ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, chars): ... + def processingInstruction(self, target, data): ... + def skippedEntity(self, name): ... + def notationDecl(self, name, publicId, systemId): ... + def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... + def resolveEntity(self, publicId, systemId): ... + def parse(self, source): ... + def setLocale(self, locale): ... + def getFeature(self, name): ... + def setFeature(self, name, state): ... + def getProperty(self, name): ... + def setProperty(self, name, value): ... + def getParent(self): ... + def setParent(self, parent): ... + +def prepare_input_source(source, base=...): ... diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi new file mode 100644 index 000000000000..9dd6b75fd52f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi @@ -0,0 +1,72 @@ +from typing import Mapping, Optional, Tuple + +class XMLReader: + def __init__(self) -> None: ... + def parse(self, source): ... + def getContentHandler(self): ... + def setContentHandler(self, handler): ... + def getDTDHandler(self): ... + def setDTDHandler(self, handler): ... + def getEntityResolver(self): ... + def setEntityResolver(self, resolver): ... + def getErrorHandler(self): ... + def setErrorHandler(self, handler): ... + def setLocale(self, locale): ... + def getFeature(self, name): ... + def setFeature(self, name, state): ... + def getProperty(self, name): ... + def setProperty(self, name, value): ... + +class IncrementalParser(XMLReader): + def __init__(self, bufsize: int = ...) -> None: ... + def parse(self, source): ... + def feed(self, data): ... + def prepareParser(self, source): ... + def close(self): ... + def reset(self): ... + +class Locator: + def getColumnNumber(self): ... + def getLineNumber(self): ... + def getPublicId(self): ... + def getSystemId(self): ... + +class InputSource: + def __init__(self, system_id: Optional[str] = ...) -> None: ... + def setPublicId(self, public_id): ... + def getPublicId(self): ... + def setSystemId(self, system_id): ... + def getSystemId(self): ... + def setEncoding(self, encoding): ... + def getEncoding(self): ... + def setByteStream(self, bytefile): ... + def getByteStream(self): ... + def setCharacterStream(self, charfile): ... + def getCharacterStream(self): ... + +class AttributesImpl: + def __init__(self, attrs: Mapping[str, str]) -> None: ... + def getLength(self): ... + def getType(self, name): ... + def getValue(self, name): ... + def getValueByQName(self, name): ... + def getNameByQName(self, name): ... + def getQNameByName(self, name): ... + def getNames(self): ... + def getQNames(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def keys(self): ... + def __contains__(self, name): ... + def get(self, name, alternative=...): ... + def copy(self): ... + def items(self): ... + def values(self): ... + +class AttributesNSImpl(AttributesImpl): + def __init__(self, attrs: Mapping[Tuple[str, str], str], qnames: Mapping[Tuple[str, str], str]) -> None: ... + def getValueByQName(self, name): ... + def getNameByQName(self, name): ... + def getQNameByName(self, name): ... + def getQNames(self): ... + def copy(self): ... diff --git a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi index 52e36b61a209..868de39ee7f7 100644 --- a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi +++ b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi @@ -5,7 +5,7 @@ from ssl import SSLContext from StringIO import StringIO from time import struct_time from types import InstanceType -from typing import IO, Any, AnyStr, Callable, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, TypeVar, Union +from typing import IO, Any, AnyStr, Callable, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, Union _Unmarshaller = Any _timeTuple = Tuple[int, int, int, int, int, int, int, int, int] diff --git a/mypy/typeshed/stdlib/@python2/zipfile.pyi b/mypy/typeshed/stdlib/@python2/zipfile.pyi new file mode 100644 index 000000000000..043aa5e342c7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/zipfile.pyi @@ -0,0 +1,105 @@ +import io +from _typeshed import StrPath +from types import TracebackType +from typing import IO, Any, Callable, Dict, Iterable, List, Optional, Pattern, Protocol, Sequence, Text, Tuple, Type, Union + +_SZI = Union[Text, ZipInfo] +_DT = Tuple[int, int, int, int, int, int] + +class BadZipfile(Exception): ... + +error = BadZipfile + +class LargeZipFile(Exception): ... + +class ZipExtFile(io.BufferedIOBase): + MAX_N: int = ... + MIN_READ_SIZE: int = ... + + PATTERN: Pattern[str] = ... + + newlines: Optional[List[bytes]] + mode: str + name: str + def __init__( + self, + fileobj: IO[bytes], + mode: str, + zipinfo: ZipInfo, + decrypter: Optional[Callable[[Sequence[int]], bytes]] = ..., + close_fileobj: bool = ..., + ) -> None: ... + def read(self, n: Optional[int] = ...) -> bytes: ... + def readline(self, limit: int = ...) -> bytes: ... # type: ignore + def __repr__(self) -> str: ... + def peek(self, n: int = ...) -> bytes: ... + def read1(self, n: Optional[int]) -> bytes: ... # type: ignore + +class _Writer(Protocol): + def write(self, __s: str) -> Any: ... + +class ZipFile: + filename: Optional[Text] + debug: int + comment: bytes + filelist: List[ZipInfo] + fp: Optional[IO[bytes]] + NameToInfo: Dict[Text, ZipInfo] + start_dir: int # undocumented + def __init__( + self, file: Union[StrPath, IO[bytes]], mode: Text = ..., compression: int = ..., allowZip64: bool = ... + ) -> None: ... + def __enter__(self) -> ZipFile: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def close(self) -> None: ... + def getinfo(self, name: Text) -> ZipInfo: ... + def infolist(self) -> List[ZipInfo]: ... + def namelist(self) -> List[Text]: ... + def open(self, name: _SZI, mode: Text = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... + def extract(self, member: _SZI, path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... + def extractall( + self, path: Optional[StrPath] = ..., members: Optional[Iterable[Text]] = ..., pwd: Optional[bytes] = ... + ) -> None: ... + def printdir(self) -> None: ... + def setpassword(self, pwd: bytes) -> None: ... + def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... + def testzip(self) -> Optional[str]: ... + def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ...) -> None: ... + def writestr(self, zinfo_or_arcname: _SZI, bytes: bytes, compress_type: Optional[int] = ...) -> None: ... + +class PyZipFile(ZipFile): + def writepy(self, pathname: Text, basename: Text = ...) -> None: ... + +class ZipInfo: + filename: Text + date_time: _DT + compress_type: int + comment: bytes + extra: bytes + create_system: int + create_version: int + extract_version: int + reserved: int + flag_bits: int + volume: int + internal_attr: int + external_attr: int + header_offset: int + CRC: int + compress_size: int + file_size: int + def __init__(self, filename: Optional[Text] = ..., date_time: Optional[_DT] = ...) -> None: ... + def FileHeader(self, zip64: Optional[bool] = ...) -> bytes: ... + +class _PathOpenProtocol(Protocol): + def __call__(self, mode: str = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... + +def is_zipfile(filename: Union[StrPath, IO[bytes]]) -> bool: ... + +ZIP_STORED: int +ZIP_DEFLATED: int +ZIP64_LIMIT: int +ZIP_FILECOUNT_LIMIT: int +ZIP_MAX_COMMENT: int diff --git a/mypy/typeshed/stdlib/@python2/zipimport.pyi b/mypy/typeshed/stdlib/@python2/zipimport.pyi new file mode 100644 index 000000000000..14aa86bb90ad --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/zipimport.pyi @@ -0,0 +1,16 @@ +from types import CodeType, ModuleType +from typing import Optional, Union + +class ZipImportError(ImportError): ... + +class zipimporter(object): + archive: str + prefix: str + def __init__(self, path: Union[str, bytes]) -> None: ... + def find_module(self, fullname: str, path: Optional[str] = ...) -> Optional[zipimporter]: ... + def get_code(self, fullname: str) -> CodeType: ... + def get_data(self, pathname: str) -> str: ... + def get_filename(self, fullname: str) -> str: ... + def get_source(self, fullname: str) -> Optional[str]: ... + def is_package(self, fullname: str) -> bool: ... + def load_module(self, fullname: str) -> ModuleType: ... diff --git a/mypy/typeshed/stdlib/@python2/zlib.pyi b/mypy/typeshed/stdlib/@python2/zlib.pyi new file mode 100644 index 000000000000..f33777ced457 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/zlib.pyi @@ -0,0 +1,40 @@ +from array import array +from typing import Any, Union + +DEFLATED: int +DEF_MEM_LEVEL: int +MAX_WBITS: int +ZLIB_VERSION: str +Z_BEST_COMPRESSION: int +Z_BEST_SPEED: int +Z_DEFAULT_COMPRESSION: int +Z_DEFAULT_STRATEGY: int +Z_FILTERED: int +Z_FINISH: int +Z_FIXED: int +Z_FULL_FLUSH: int +Z_HUFFMAN_ONLY: int +Z_NO_FLUSH: int +Z_RLE: int +Z_SYNC_FLUSH: int + +class error(Exception): ... + +class _Compress: + def compress(self, data: bytes) -> bytes: ... + def flush(self, mode: int = ...) -> bytes: ... + def copy(self) -> _Compress: ... + +class _Decompress: + unused_data: bytes + unconsumed_tail: bytes + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + def flush(self, length: int = ...) -> bytes: ... + def copy(self) -> _Decompress: ... + +def adler32(__data: bytes, __value: int = ...) -> int: ... +def compress(__data: bytes, level: int = ...) -> bytes: ... +def compressobj(level: int = ..., method: int = ..., wbits: int = ..., memlevel: int = ..., strategy: int = ...) -> _Compress: ... +def crc32(__data: Union[array[Any], bytes], __value: int = ...) -> int: ... +def decompress(__data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ... +def decompressobj(wbits: int = ...) -> _Decompress: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index 11219357c638..3f0f81947f07 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -1,6 +1,6 @@ # The structure of this file is as follows: -# - Blank lines and lines starting with `#` are ignored. -# - Lines contain the name of a top-level module, followed by a colon, +# - Blank lines and comments starting with `#` are ignored. +# - Lines contain the name of a module, followed by a colon, # a space, and a version range (for example: `symbol: 2.7-3.9`). # # Version ranges may be of the form "X.Y-A.B" or "X.Y-". The @@ -9,6 +9,9 @@ # introduced in version X.Y and is still available in the latest # version of Python. # +# If a submodule is not listed separately, it has the same lifetime as +# its parent module. +# # Python versions before 2.7 are ignored, so any module that was already # present in 2.7 will have "2.7" as its minimum version. Version ranges # for unsupported versions of Python 3 (currently 3.5 and lower) are @@ -45,7 +48,7 @@ _thread: 2.7- _threading_local: 3.6- _tkinter: 2.7- _tracemalloc: 3.6- -_typeshed: 2.7- +_typeshed: 2.7- # not present at runtime, only for type checking _warnings: 2.7- _weakref: 2.7- _weakrefset: 2.7- @@ -126,15 +129,16 @@ gzip: 2.7- hashlib: 2.7- heapq: 2.7- hmac: 2.7- -html: 2.7- +html: 3.0- http: 3.0- imaplib: 2.7- imghdr: 2.7- imp: 2.7- importlib: 2.7- +importlib.resources: 3.7- inspect: 2.7- io: 2.7- -ipaddress: 2.7- +ipaddress: 3.3- itertools: 2.7- json: 2.7- keyword: 2.7- @@ -188,12 +192,12 @@ pyclbr: 2.7- pydoc: 2.7- pydoc_data: 2.7- pyexpat: 2.7- -queue: 2.7- +queue: 3.0- quopri: 2.7- random: 2.7- re: 2.7- readline: 2.7- -reprlib: 2.7- +reprlib: 3.0- resource: 2.7- rlcompleter: 2.7- runpy: 2.7- @@ -210,7 +214,7 @@ smtpd: 2.7- smtplib: 2.7- sndhdr: 2.7- socket: 2.7- -socketserver: 2.7- +socketserver: 3.0- spwd: 2.7- sqlite3: 2.7- sre_compile: 2.7- @@ -260,7 +264,7 @@ warnings: 2.7- wave: 2.7- weakref: 2.7- webbrowser: 2.7- -winreg: 2.7- +winreg: 3.0- winsound: 2.7- wsgiref: 2.7- xdrlib: 2.7- diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index 8a5035271eec..a68183dbe23e 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -14,11 +14,8 @@ nested_scopes: _Feature print_function: _Feature unicode_literals: _Feature with_statement: _Feature -if sys.version_info >= (3, 0): - barry_as_FLUFL: _Feature - -if sys.version_info >= (3, 5): - generator_stop: _Feature +barry_as_FLUFL: _Feature +generator_stop: _Feature if sys.version_info >= (3, 7): annotations: _Feature diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index fbb014aadbfb..9d420af898e2 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,82 +1,68 @@ import codecs import sys -from typing import Any, Callable, Dict, Optional, Text, Tuple, Union - -# For convenience: -_Handler = Callable[[Exception], Tuple[Text, int]] -_String = Union[bytes, str] -_Errors = Union[str, Text, None] -if sys.version_info >= (3, 0): - _Decodable = bytes - _Encodable = str -else: - _Decodable = Union[bytes, Text] - _Encodable = Union[bytes, Text] +from typing import Any, Callable, Dict, Optional, Tuple, Union # This type is not exposed; it is defined in unicodeobject.c -class _EncodingMap(object): +class _EncodingMap: def size(self) -> int: ... _MapT = Union[Dict[int, int], _EncodingMap] +_Handler = Callable[[Exception], Tuple[str, int]] def register(__search_function: Callable[[str], Any]) -> None: ... -def register_error(__errors: Union[str, Text], __handler: _Handler) -> None: ... -def lookup(__encoding: Union[str, Text]) -> codecs.CodecInfo: ... -def lookup_error(__name: Union[str, Text]) -> _Handler: ... -def decode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... -def encode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... -def charmap_build(__map: Text) -> _MapT: ... -def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... - -if sys.version_info < (3, 2): - def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... - -def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: Optional[_MapT] = ...) -> Tuple[Text, int]: ... -def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: Optional[_MapT] = ...) -> Tuple[bytes, int]: ... -def escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +def register_error(__errors: str, __handler: _Handler) -> None: ... +def lookup(__encoding: str) -> codecs.CodecInfo: ... +def lookup_error(__name: str) -> _Handler: ... +def decode(obj: Any, encoding: str = ..., errors: Optional[str] = ...) -> Any: ... +def encode(obj: Any, encoding: str = ..., errors: Optional[str] = ...) -> Any: ... +def charmap_build(__map: str) -> _MapT: ... +def ascii_decode(__data: bytes, __errors: Optional[str] = ...) -> Tuple[str, int]: ... +def ascii_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def charmap_decode(__data: bytes, __errors: Optional[str] = ..., __mapping: Optional[_MapT] = ...) -> Tuple[str, int]: ... +def charmap_encode(__str: str, __errors: Optional[str] = ..., __mapping: Optional[_MapT] = ...) -> Tuple[bytes, int]: ... +def escape_decode(__data: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[str, int]: ... +def escape_encode(__data: bytes, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def latin_1_decode(__data: bytes, __errors: Optional[str] = ...) -> Tuple[str, int]: ... +def latin_1_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def raw_unicode_escape_decode(__data: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[str, int]: ... +def raw_unicode_escape_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def readbuffer_encode(__data: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def unicode_escape_decode(__data: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[str, int]: ... +def unicode_escape_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... if sys.version_info < (3, 8): - def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... - def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... + def unicode_internal_decode(__obj: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[str, int]: ... + def unicode_internal_encode(__obj: Union[str, bytes], __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... -def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +def utf_16_be_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_16_be_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def utf_16_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_16_encode(__str: str, __errors: Optional[str] = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... def utf_16_ex_decode( - __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... + __data: bytes, __errors: Optional[str] = ..., __byteorder: int = ..., __final: int = ... +) -> Tuple[str, int, int]: ... +def utf_16_le_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_16_le_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def utf_32_be_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_32_be_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def utf_32_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_32_encode(__str: str, __errors: Optional[str] = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... def utf_32_ex_decode( - __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_32_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_7_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_7_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_8_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_8_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... + __data: bytes, __errors: Optional[str] = ..., __byteorder: int = ..., __final: int = ... +) -> Tuple[str, int, int]: ... +def utf_32_le_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_32_le_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def utf_7_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_7_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def utf_8_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... +def utf_8_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... if sys.platform == "win32": - def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... - def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... - if sys.version_info >= (3, 0): - def code_page_decode(__codepage: int, __data: bytes, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... - def code_page_encode(__code_page: int, __str: Text, __errors: _Errors = ...) -> Tuple[bytes, int]: ... - if sys.version_info >= (3, 6): - def oem_decode(__data: bytes, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... - def oem_encode(__str: Text, __errors: _Errors = ...) -> Tuple[bytes, int]: ... + def mbcs_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... + def mbcs_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... + def code_page_decode( + __codepage: int, __data: bytes, __errors: Optional[str] = ..., __final: int = ... + ) -> Tuple[str, int]: ... + def code_page_encode(__code_page: int, __str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... + def oem_decode(__data: bytes, __errors: Optional[str] = ..., __final: int = ...) -> Tuple[str, int]: ... + def oem_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 2b4b1a743865..45d05f478cb4 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,5 +1,4 @@ -import sys -from typing import Any, Iterable, Iterator, List, Optional, Protocol, Sequence, Text, Type, Union +from typing import Any, Iterable, Iterator, List, Optional, Protocol, Type, Union QUOTE_ALL: int QUOTE_MINIMAL: int @@ -24,26 +23,18 @@ _DialectLike = Union[str, Dialect, Type[Dialect]] class _reader(Iterator[List[str]]): dialect: Dialect line_num: int - if sys.version_info >= (3, 0): - def __next__(self) -> List[str]: ... - else: - def next(self) -> List[str]: ... + def __next__(self) -> List[str]: ... class _writer: dialect: Dialect - - if sys.version_info >= (3, 5): - def writerow(self, row: Iterable[Any]) -> Any: ... - def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... - else: - def writerow(self, row: Sequence[Any]) -> Any: ... - def writerows(self, rows: Iterable[Sequence[Any]]) -> None: ... + def writerow(self, row: Iterable[Any]) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... class _Writer(Protocol): def write(self, s: str) -> Any: ... def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... -def reader(csvfile: Iterable[Text], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... +def reader(csvfile: Iterable[str], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... def unregister_dialect(name: str) -> None: ... def get_dialect(name: str) -> Dialect: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 1ccd54e35edd..db9b049a9392 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -348,24 +348,17 @@ def tparm( ) -> bytes: ... def typeahead(__fd: int) -> None: ... def unctrl(__ch: _chtype) -> bytes: ... - -if sys.version_info >= (3, 3): - def unget_wch(__ch: Union[int, str]) -> None: ... - +def unget_wch(__ch: Union[int, str]) -> None: ... def ungetch(__ch: _chtype) -> None: ... def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... - -if sys.version_info >= (3, 5): - def update_lines_cols() -> int: ... - +def update_lines_cols() -> int: ... def use_default_colors() -> None: ... def use_env(__flag: bool) -> None: ... class error(Exception): ... class _CursesWindow: - if sys.version_info >= (3, 3): - encoding: str + encoding: str @overload def addch(self, ch: _chtype, attr: int = ...) -> None: ... @overload @@ -429,11 +422,10 @@ class _CursesWindow: def getch(self) -> int: ... @overload def getch(self, y: int, x: int) -> int: ... - if sys.version_info >= (3, 3): - @overload - def get_wch(self) -> Union[int, str]: ... - @overload - def get_wch(self, y: int, x: int) -> Union[int, str]: ... + @overload + def get_wch(self) -> Union[int, str]: ... + @overload + def get_wch(self, y: int, x: int) -> Union[int, str]: ... @overload def getkey(self) -> str: ... @overload diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index af0b0af89d9b..de75375056e0 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar, Union +from typing import Any, Callable, Iterable, List, Mapping, Optional, Type, TypeVar, Union # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -11,20 +11,11 @@ _T = TypeVar("_T") __all__: List[str] def active_count() -> int: ... - -if sys.version_info < (3,): - def activeCount() -> int: ... - def current_thread() -> Thread: ... def currentThread() -> Thread: ... - -if sys.version_info >= (3,): - def get_ident() -> int: ... - +def get_ident() -> int: ... def enumerate() -> List[Thread]: ... - -if sys.version_info >= (3, 4): - def main_thread() -> Thread: ... +def main_thread() -> Thread: ... if sys.version_info >= (3, 8): from _thread import get_native_id as get_native_id @@ -33,8 +24,7 @@ def settrace(func: _TF) -> None: ... def setprofile(func: Optional[_PF]) -> None: ... def stack_size(size: int = ...) -> int: ... -if sys.version_info >= (3,): - TIMEOUT_MAX: float +TIMEOUT_MAX: float class ThreadError(Exception): ... @@ -47,31 +37,21 @@ class Thread: name: str ident: Optional[int] daemon: bool - if sys.version_info >= (3,): - def __init__( - self, - group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[str] = ..., - args: Iterable[Any] = ..., - kwargs: Optional[Mapping[str, Any]] = ..., - *, - daemon: Optional[bool] = ..., - ) -> None: ... - else: - def __init__( - self, - group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[Text] = ..., - args: Iterable[Any] = ..., - kwargs: Optional[Mapping[Text, Any]] = ..., - ) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., + *, + daemon: Optional[bool] = ..., + ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: Optional[float] = ...) -> None: ... def getName(self) -> str: ... - def setName(self, name: Text) -> None: ... + def setName(self, name: str) -> None: ... if sys.version_info >= (3, 8): @property def native_id(self) -> Optional[int]: ... # only available on some platforms @@ -89,10 +69,7 @@ class Lock: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... def locked(self) -> bool: ... @@ -102,10 +79,7 @@ class _RLock: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... RLock = _RLock @@ -116,14 +90,10 @@ class Condition: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... def wait(self, timeout: Optional[float] = ...) -> bool: ... - if sys.version_info >= (3,): - def wait_for(self, predicate: Callable[[], _T], timeout: Optional[float] = ...) -> _T: ... + def wait_for(self, predicate: Callable[[], _T], timeout: Optional[float] = ...) -> _T: ... def notify(self, n: int = ...) -> None: ... def notify_all(self) -> None: ... def notifyAll(self) -> None: ... @@ -133,12 +103,8 @@ class Semaphore: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... - def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... - def __enter__(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... + def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... if sys.version_info >= (3, 9): def release(self, n: int = ...) -> None: ... else: @@ -149,8 +115,6 @@ class BoundedSemaphore(Semaphore): ... class Event: def __init__(self) -> None: ... def is_set(self) -> bool: ... - if sys.version_info < (3,): - def isSet(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... def wait(self, timeout: Optional[float] = ...) -> bool: ... @@ -162,27 +126,22 @@ if sys.version_info >= (3, 8): ExceptHookArgs = _ExceptHookArgs class Timer(Thread): - if sys.version_info >= (3,): - def __init__( - self, - interval: float, - function: Callable[..., Any], - args: Optional[Iterable[Any]] = ..., - kwargs: Optional[Mapping[str, Any]] = ..., - ) -> None: ... - else: - def __init__( - self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... - ) -> None: ... + def __init__( + self, + interval: float, + function: Callable[..., Any], + args: Optional[Iterable[Any]] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., + ) -> None: ... def cancel(self) -> None: ... -if sys.version_info >= (3,): - class Barrier: - parties: int - n_waiting: int - broken: bool - def __init__(self, parties: int, action: Optional[Callable[[], None]] = ..., timeout: Optional[float] = ...) -> None: ... - def wait(self, timeout: Optional[float] = ...) -> int: ... - def reset(self) -> None: ... - def abort(self) -> None: ... - class BrokenBarrierError(RuntimeError): ... +class Barrier: + parties: int + n_waiting: int + broken: bool + def __init__(self, parties: int, action: Optional[Callable[[], None]] = ..., timeout: Optional[float] = ...) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> int: ... + def reset(self) -> None: ... + def abort(self) -> None: ... + +class BrokenBarrierError(RuntimeError): ... diff --git a/mypy/typeshed/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi index 5b14a9de773d..8c8339755342 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -1,5 +1,4 @@ -import sys -from typing import Any, Callable, Iterable, List, Optional, TypeVar +from typing import Any, List, TypeVar _T = TypeVar("_T") @@ -8,7 +7,3 @@ def heappop(__heap: List[_T]) -> _T: ... def heappush(__heap: List[_T], __item: _T) -> None: ... def heappushpop(__heap: List[_T], __item: _T) -> _T: ... def heapreplace(__heap: List[_T], __item: _T) -> _T: ... - -if sys.version_info < (3,): - def nlargest(__n: int, __iterable: Iterable[_T], __key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... - def nsmallest(__n: int, __iterable: Iterable[_T], __key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index aa09693420ca..fa80c6d98144 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -1,4 +1,3 @@ -import sys from typing import Tuple # Actually Tuple[(int,) * 625] @@ -11,5 +10,3 @@ class Random(object): def setstate(self, __state: _State) -> None: ... def random(self) -> float: ... def getrandbits(self, __k: int) -> int: ... - if sys.version_info < (3,): - def jumpahead(self, i: int) -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/README.md b/mypy/typeshed/stdlib/_typeshed/README.md new file mode 100644 index 000000000000..f4808944fa7b --- /dev/null +++ b/mypy/typeshed/stdlib/_typeshed/README.md @@ -0,0 +1,34 @@ +# Utility types for typeshed + +This package and its submodules contains various common types used by +typeshed. It can also be used by packages outside typeshed, but beware +the API stability guarantees below. + +## Usage + +The `_typeshed` package and its types do not exist at runtime, but can be +used freely in stubs (`.pyi`) files. To import the types from this package in +implementation (`.py`) files, use the following construct: + +```python +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from _typeshed import ... +``` + +Types can then be used in annotations by either quoting them or +using: + +```python +from __future__ import annotations +``` + +## API Stability + +You can use this package and its submodules outside of typeshed, but we +guarantee only limited API stability. Items marked as "stable" will not be +removed or changed in an incompatible way for at least one year. +Before making such a change, the "stable" moniker will be removed +and we will mark the type in question as deprecated. No guarantees +are made about unmarked types. diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 948d4269f575..60719553b46b 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -1,21 +1,12 @@ # Utility types for typeshed - -# This module contains various common types to be used by typeshed. The -# module and its types do not exist at runtime. You can use this module -# outside of typeshed, but no API stability guarantees are made. To use -# it in implementation (.py) files, the following construct must be used: -# -# from typing import TYPE_CHECKING -# if TYPE_CHECKING: -# from _typeshed import ... # -# If on Python versions < 3.10 and "from __future__ import annotations" -# is not used, types from this module must be quoted. +# See the README.md file in this directory for more information. import array import mmap import sys -from typing import AbstractSet, Any, Container, Iterable, Protocol, Text, Tuple, TypeVar, Union +from os import PathLike +from typing import AbstractSet, Any, Container, Iterable, Protocol, Tuple, TypeVar, Union from typing_extensions import Literal, final _KT = TypeVar("_KT") @@ -23,9 +14,14 @@ _KT_co = TypeVar("_KT_co", covariant=True) _KT_contra = TypeVar("_KT_contra", contravariant=True) _VT = TypeVar("_VT") _VT_co = TypeVar("_VT_co", covariant=True) +_T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) +# stable +class IdentityFunction(Protocol): + def __call__(self, __x: _T) -> _T: ... + class SupportsLessThan(Protocol): def __lt__(self, __other: Any) -> bool: ... @@ -39,36 +35,29 @@ class SupportsRDivMod(Protocol[_T_contra, _T_co]): # Mapping-like protocols +# stable class SupportsItems(Protocol[_KT_co, _VT_co]): - if sys.version_info >= (3,): - def items(self) -> AbstractSet[Tuple[_KT_co, _VT_co]]: ... - else: - # We want dictionaries to support this on Python 2. - def items(self) -> Iterable[Tuple[_KT_co, _VT_co]]: ... + def items(self) -> AbstractSet[Tuple[_KT_co, _VT_co]]: ... +# stable class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... def __getitem__(self, __k: _KT) -> _VT_co: ... +# stable class SupportsGetItem(Container[_KT_contra], Protocol[_KT_contra, _VT_co]): def __getitem__(self, __k: _KT_contra) -> _VT_co: ... +# stable class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): def __setitem__(self, __k: _KT_contra, __v: _VT) -> None: ... def __delitem__(self, __v: _KT_contra) -> None: ... -# StrPath and AnyPath can be used in places where a -# path can be used instead of a string, starting with Python 3.6. -if sys.version_info >= (3, 6): - from os import PathLike - - StrPath = Union[str, PathLike[str]] - BytesPath = Union[bytes, PathLike[bytes]] - AnyPath = Union[str, bytes, PathLike[str], PathLike[bytes]] -else: - StrPath = Text - BytesPath = bytes - AnyPath = Union[Text, bytes] +# These aliases are simple strings in Python 2. +StrPath = Union[str, PathLike[str]] # stable +BytesPath = Union[bytes, PathLike[bytes]] # stable +StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable +AnyPath = StrOrBytesPath # obsolete, will be removed soon OpenTextModeUpdating = Literal[ "r+", @@ -137,31 +126,33 @@ OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] +# stable class HasFileno(Protocol): def fileno(self) -> int: ... -FileDescriptor = int -FileDescriptorLike = Union[int, HasFileno] +FileDescriptor = int # stable +FileDescriptorLike = Union[int, HasFileno] # stable +# stable class SupportsRead(Protocol[_T_co]): def read(self, __length: int = ...) -> _T_co: ... +# stable class SupportsReadline(Protocol[_T_co]): def readline(self, __length: int = ...) -> _T_co: ... +# stable class SupportsNoArgReadline(Protocol[_T_co]): def readline(self) -> _T_co: ... +# stable class SupportsWrite(Protocol[_T_contra]): def write(self, __s: _T_contra) -> Any: ... -if sys.version_info >= (3,): - ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap] - WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap] -else: - ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] - WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] +ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap] # stable +WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap] # stable +# stable if sys.version_info >= (3, 10): from types import NoneType as NoneType else: diff --git a/mypy/typeshed/stdlib/_typeshed/tkinter.pyi b/mypy/typeshed/stdlib/_typeshed/tkinter.pyi index 565635adbb74..2fe0c4255e03 100644 --- a/mypy/typeshed/stdlib/_typeshed/tkinter.pyi +++ b/mypy/typeshed/stdlib/_typeshed/tkinter.pyi @@ -1,7 +1,7 @@ -import sys +# See the README.md file in this directory for more information. + +from tkinter import Event, Misc, Widget from typing import Optional, Protocol -if sys.version_info >= (3,): - from tkinter import Event, Misc, Widget - class DndSource(Protocol): - def dnd_end(self, target: Optional[Widget], event: Optional[Event[Misc]]) -> None: ... +class DndSource(Protocol): + def dnd_end(self, target: Optional[Widget], event: Optional[Event[Misc]]) -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index bafaf7bc5f66..d99d37f05ab2 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -1,27 +1,27 @@ # Types to support PEP 3333 (WSGI) # -# This module doesn't exist at runtime and neither do the types defined in this -# file. They are provided for type checking purposes. +# See the README.md file in this directory for more information. from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Text, Tuple +from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Tuple +# stable class StartResponse(Protocol): def __call__( self, status: str, headers: List[Tuple[str, str]], exc_info: Optional[_OptExcInfo] = ... ) -> Callable[[bytes], Any]: ... -WSGIEnvironment = Dict[Text, Any] -WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] +WSGIEnvironment = Dict[str, Any] # stable +WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable -# WSGI input streams per PEP 3333 +# WSGI input streams per PEP 3333, stable class InputStream(Protocol): def read(self, size: int = ...) -> bytes: ... def readline(self, size: int = ...) -> bytes: ... def readlines(self, hint: int = ...) -> List[bytes]: ... def __iter__(self) -> Iterable[bytes]: ... -# WSGI error streams per PEP 3333 +# WSGI error streams per PEP 3333, stable class ErrorStream(Protocol): def flush(self) -> None: ... def write(self, s: str) -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/xml.pyi b/mypy/typeshed/stdlib/_typeshed/xml.pyi index 7ad28aef1b75..cabac0bc9991 100644 --- a/mypy/typeshed/stdlib/_typeshed/xml.pyi +++ b/mypy/typeshed/stdlib/_typeshed/xml.pyi @@ -1,4 +1,4 @@ -# Stub-only types. This module does not exist at runtime. +# See the README.md file in this directory for more information. from typing import Any, Optional from typing_extensions import Protocol diff --git a/mypy/typeshed/stdlib/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi index b4ec4e6ee794..33d4f0b9e3bb 100644 --- a/mypy/typeshed/stdlib/_warnings.pyi +++ b/mypy/typeshed/stdlib/_warnings.pyi @@ -1,67 +1,32 @@ -import sys from typing import Any, Dict, List, Optional, Tuple, Type, Union, overload -if sys.version_info >= (3, 0): - _defaultaction: str - _onceregistry: Dict[Any, Any] -else: - default_action: str - once_registry: Dict[Any, Any] - +_defaultaction: str +_onceregistry: Dict[Any, Any] filters: List[Tuple[Any, ...]] -if sys.version_info >= (3, 6): - @overload - def warn( - message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ... - ) -> None: ... - @overload - def warn(message: Warning, category: Any = ..., stacklevel: int = ..., source: Optional[Any] = ...) -> None: ... - @overload - def warn_explicit( - message: str, - category: Type[Warning], - filename: str, - lineno: int, - module: Optional[str] = ..., - registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., - module_globals: Optional[Dict[str, Any]] = ..., - source: Optional[Any] = ..., - ) -> None: ... - @overload - def warn_explicit( - message: Warning, - category: Any, - filename: str, - lineno: int, - module: Optional[str] = ..., - registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., - module_globals: Optional[Dict[str, Any]] = ..., - source: Optional[Any] = ..., - ) -> None: ... - -else: - @overload - def warn(message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ...) -> None: ... - @overload - def warn(message: Warning, category: Any = ..., stacklevel: int = ...) -> None: ... - @overload - def warn_explicit( - message: str, - category: Type[Warning], - filename: str, - lineno: int, - module: Optional[str] = ..., - registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., - module_globals: Optional[Dict[str, Any]] = ..., - ) -> None: ... - @overload - def warn_explicit( - message: Warning, - category: Any, - filename: str, - lineno: int, - module: Optional[str] = ..., - registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., - module_globals: Optional[Dict[str, Any]] = ..., - ) -> None: ... +@overload +def warn(message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ...) -> None: ... +@overload +def warn(message: Warning, category: Any = ..., stacklevel: int = ..., source: Optional[Any] = ...) -> None: ... +@overload +def warn_explicit( + message: str, + category: Type[Warning], + filename: str, + lineno: int, + module: Optional[str] = ..., + registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., + module_globals: Optional[Dict[str, Any]] = ..., + source: Optional[Any] = ..., +) -> None: ... +@overload +def warn_explicit( + message: Warning, + category: Any, + filename: str, + lineno: int, + module: Optional[str] = ..., + registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., + module_globals: Optional[Dict[str, Any]] = ..., + source: Optional[Any] = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 115a591ce4c8..01974c522369 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -14,8 +14,7 @@ class ProxyType(Generic[_T]): # "weakproxy" def __getattr__(self, attr: str) -> Any: ... class ReferenceType(Generic[_T]): - if sys.version_info >= (3, 4): - __callback__: Callable[[ReferenceType[_T]], Any] + __callback__: Callable[[ReferenceType[_T]], Any] def __init__(self, o: _T, callback: Optional[Callable[[ReferenceType[_T]], Any]] = ...) -> None: ... def __call__(self) -> Optional[_T]: ... def __hash__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index f812ac593e97..b43af47ff5e8 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,6 +1,6 @@ import sys from types import TracebackType -from typing import IO, Any, List, NamedTuple, Optional, Text, Tuple, Type, Union, overload +from typing import IO, Any, List, NamedTuple, Optional, Tuple, Type, Union, overload from typing_extensions import Literal class Error(Exception): ... @@ -13,16 +13,15 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[Text, IO[bytes]] +_File = Union[str, IO[bytes]] _Marker = Tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... - if sys.version_info >= (3, 4): - def __enter__(self) -> Aifc_read: ... - def __exit__( - self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] - ) -> None: ... + def __enter__(self) -> Aifc_read: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def getfp(self) -> IO[bytes]: ... def rewind(self) -> None: ... @@ -43,11 +42,10 @@ class Aifc_read: class Aifc_write: def __init__(self, f: _File) -> None: ... def __del__(self) -> None: ... - if sys.version_info >= (3, 4): - def __enter__(self) -> Aifc_write: ... - def __exit__( - self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] - ) -> None: ... + def __enter__(self) -> Aifc_write: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def aiff(self) -> None: ... def aifc(self) -> None: ... diff --git a/mypy/typeshed/stdlib/antigravity.pyi b/mypy/typeshed/stdlib/antigravity.pyi index 52e2c5d96bef..e30917511030 100644 --- a/mypy/typeshed/stdlib/antigravity.pyi +++ b/mypy/typeshed/stdlib/antigravity.pyi @@ -1,4 +1 @@ -import sys - -if sys.version_info >= (3, 0): - def geohash(latitude: float, longitude: float, datedow: bytes) -> None: ... +def geohash(latitude: float, longitude: float, datedow: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 9dceaabd4631..2d5efdf4e98a 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -12,7 +12,6 @@ from typing import ( Pattern, Protocol, Sequence, - Text, Tuple, Type, TypeVar, @@ -24,11 +23,6 @@ _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _N = TypeVar("_N") -if sys.version_info >= (3,): - _Text = str -else: - _Text = Union[str, unicode] - ONE_OR_MORE: str OPTIONAL: str PARSER: str @@ -49,40 +43,38 @@ class _AttributeHolder: # undocumented class _ActionsContainer: - description: Optional[_Text] - prefix_chars: _Text + description: Optional[str] + prefix_chars: str argument_default: Any - conflict_handler: _Text + conflict_handler: str - _registries: Dict[_Text, Dict[Any, Any]] + _registries: Dict[str, Dict[Any, Any]] _actions: List[Action] - _option_string_actions: Dict[_Text, Action] + _option_string_actions: Dict[str, Action] _action_groups: List[_ArgumentGroup] _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] _defaults: Dict[str, Any] _negative_number_matcher: Pattern[str] _has_negative_number_optionals: List[bool] - def __init__( - self, description: Optional[Text], prefix_chars: Text, argument_default: Any, conflict_handler: Text - ) -> None: ... - def register(self, registry_name: Text, value: Any, object: Any) -> None: ... - def _registry_get(self, registry_name: Text, value: Any, default: Any = ...) -> Any: ... + def __init__(self, description: Optional[str], prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ... + def register(self, registry_name: str, value: Any, object: Any) -> None: ... + def _registry_get(self, registry_name: str, value: Any, default: Any = ...) -> Any: ... def set_defaults(self, **kwargs: Any) -> None: ... - def get_default(self, dest: Text) -> Any: ... + def get_default(self, dest: str) -> Any: ... def add_argument( self, - *name_or_flags: Text, - action: Union[Text, Type[Action]] = ..., - nargs: Union[int, Text] = ..., + *name_or_flags: str, + action: Union[str, Type[Action]] = ..., + nargs: Union[int, str] = ..., const: Any = ..., default: Any = ..., - type: Union[Callable[[Text], _T], Callable[[str], _T], FileType] = ..., + type: Union[Callable[[str], _T], Callable[[str], _T], FileType] = ..., choices: Iterable[_T] = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., - dest: Optional[Text] = ..., - version: Text = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., + dest: Optional[str] = ..., + version: str = ..., **kwargs: Any, ) -> Action: ... def add_argument_group(self, *args: Any, **kwargs: Any) -> _ArgumentGroup: ... @@ -90,27 +82,25 @@ class _ActionsContainer: def _add_action(self, action: _ActionT) -> _ActionT: ... def _remove_action(self, action: Action) -> None: ... def _add_container_actions(self, container: _ActionsContainer) -> None: ... - def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> Dict[str, Any]: ... + def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> Dict[str, Any]: ... def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... def _pop_action_class(self, kwargs: Any, default: Optional[Type[Action]] = ...) -> Type[Action]: ... - def _get_handler(self) -> Callable[[Action, Iterable[Tuple[Text, Action]]], Any]: ... + def _get_handler(self) -> Callable[[Action, Iterable[Tuple[str, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... - def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> NoReturn: ... - def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> None: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[str, Action]]) -> NoReturn: ... + def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[str, Action]]) -> None: ... class _FormatterClass(Protocol): def __call__(self, prog: str) -> HelpFormatter: ... class ArgumentParser(_AttributeHolder, _ActionsContainer): - prog: _Text - usage: Optional[_Text] - epilog: Optional[_Text] + prog: str + usage: Optional[str] + epilog: Optional[str] formatter_class: _FormatterClass - fromfile_prefix_chars: Optional[_Text] + fromfile_prefix_chars: Optional[str] add_help: bool - - if sys.version_info >= (3, 5): - allow_abbrev: bool + allow_abbrev: bool # undocumented _positionals: _ArgumentGroup @@ -134,7 +124,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): allow_abbrev: bool = ..., exit_on_error: bool = ..., ) -> None: ... - elif sys.version_info >= (3, 5): + else: def __init__( self, prog: Optional[str] = ..., @@ -150,29 +140,14 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): add_help: bool = ..., allow_abbrev: bool = ..., ) -> None: ... - else: - def __init__( - self, - prog: Optional[Text] = ..., - usage: Optional[Text] = ..., - description: Optional[Text] = ..., - epilog: Optional[Text] = ..., - parents: Sequence[ArgumentParser] = ..., - formatter_class: _FormatterClass = ..., - prefix_chars: Text = ..., - fromfile_prefix_chars: Optional[Text] = ..., - argument_default: Any = ..., - conflict_handler: Text = ..., - add_help: bool = ..., - ) -> None: ... # The type-ignores in these overloads should be temporary. See: # https://github.com/python/typeshed/pull/2643#issuecomment-442280277 @overload - def parse_args(self, args: Optional[Sequence[Text]] = ...) -> Namespace: ... + def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace: ... @overload - def parse_args(self, args: Optional[Sequence[Text]], namespace: None) -> Namespace: ... # type: ignore + def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace: ... # type: ignore @overload - def parse_args(self, args: Optional[Sequence[Text]], namespace: _N) -> _N: ... + def parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N: ... @overload def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore @overload @@ -196,26 +171,26 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def add_subparsers( self, *, - title: Text = ..., - description: Optional[Text] = ..., - prog: Text = ..., + title: str = ..., + description: Optional[str] = ..., + prog: str = ..., parser_class: Type[ArgumentParser] = ..., action: Type[Action] = ..., - option_string: Text = ..., - dest: Optional[Text] = ..., - help: Optional[Text] = ..., - metavar: Optional[Text] = ..., + option_string: str = ..., + dest: Optional[str] = ..., + help: Optional[str] = ..., + metavar: Optional[str] = ..., ) -> _SubParsersAction: ... def print_usage(self, file: Optional[IO[str]] = ...) -> None: ... def print_help(self, file: Optional[IO[str]] = ...) -> None: ... def format_usage(self) -> str: ... def format_help(self) -> str: ... def parse_known_args( - self, args: Optional[Sequence[Text]] = ..., namespace: Optional[Namespace] = ... + self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ... ) -> Tuple[Namespace, List[str]]: ... - def convert_arg_line_to_args(self, arg_line: Text) -> List[str]: ... - def exit(self, status: int = ..., message: Optional[Text] = ...) -> NoReturn: ... - def error(self, message: Text) -> NoReturn: ... + def convert_arg_line_to_args(self, arg_line: str) -> List[str]: ... + def exit(self, status: int = ..., message: Optional[str] = ...) -> NoReturn: ... + def error(self, message: str) -> NoReturn: ... if sys.version_info >= (3, 7): def parse_intermixed_args( self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ... @@ -226,22 +201,22 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): # undocumented def _get_optional_actions(self) -> List[Action]: ... def _get_positional_actions(self) -> List[Action]: ... - def _parse_known_args(self, arg_strings: List[Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... - def _read_args_from_files(self, arg_strings: List[Text]) -> List[Text]: ... - def _match_argument(self, action: Action, arg_strings_pattern: Text) -> int: ... - def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> List[int]: ... - def _parse_optional(self, arg_string: Text) -> Optional[Tuple[Optional[Action], Text, Optional[Text]]]: ... - def _get_option_tuples(self, option_string: Text) -> List[Tuple[Action, Text, Optional[Text]]]: ... - def _get_nargs_pattern(self, action: Action) -> _Text: ... - def _get_values(self, action: Action, arg_strings: List[Text]) -> Any: ... - def _get_value(self, action: Action, arg_string: Text) -> Any: ... + def _parse_known_args(self, arg_strings: List[str], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... + def _read_args_from_files(self, arg_strings: List[str]) -> List[str]: ... + def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> List[int]: ... + def _parse_optional(self, arg_string: str) -> Optional[Tuple[Optional[Action], str, Optional[str]]]: ... + def _get_option_tuples(self, option_string: str) -> List[Tuple[Action, str, Optional[str]]]: ... + def _get_nargs_pattern(self, action: Action) -> str: ... + def _get_values(self, action: Action, arg_strings: List[str]) -> Any: ... + def _get_value(self, action: Action, arg_string: str) -> Any: ... def _check_value(self, action: Action, value: Any) -> None: ... def _get_formatter(self) -> HelpFormatter: ... def _print_message(self, message: str, file: Optional[IO[str]] = ...) -> None: ... class HelpFormatter: # undocumented - _prog: _Text + _prog: str _indent_increment: int _max_help_position: int _width: int @@ -254,75 +229,73 @@ class HelpFormatter: _long_break_matcher: Pattern[str] _Section: Type[Any] # Nested class def __init__( - self, prog: Text, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ... + self, prog: str, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ... ) -> None: ... def _indent(self) -> None: ... def _dedent(self) -> None: ... - def _add_item(self, func: Callable[..., _Text], args: Iterable[Any]) -> None: ... - def start_section(self, heading: Optional[Text]) -> None: ... + def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ... + def start_section(self, heading: Optional[str]) -> None: ... def end_section(self) -> None: ... - def add_text(self, text: Optional[Text]) -> None: ... + def add_text(self, text: Optional[str]) -> None: ... def add_usage( - self, usage: Optional[Text], actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[Text] = ... + self, usage: Optional[str], actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[str] = ... ) -> None: ... def add_argument(self, action: Action) -> None: ... def add_arguments(self, actions: Iterable[Action]) -> None: ... - def format_help(self) -> _Text: ... - def _join_parts(self, part_strings: Iterable[Text]) -> _Text: ... + def format_help(self) -> str: ... + def _join_parts(self, part_strings: Iterable[str]) -> str: ... def _format_usage( - self, usage: Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[Text] - ) -> _Text: ... - def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> _Text: ... - def _format_text(self, text: Text) -> _Text: ... - def _format_action(self, action: Action) -> _Text: ... - def _format_action_invocation(self, action: Action) -> _Text: ... - def _metavar_formatter(self, action: Action, default_metavar: Text) -> Callable[[int], Tuple[_Text, ...]]: ... - def _format_args(self, action: Action, default_metavar: Text) -> _Text: ... - def _expand_help(self, action: Action) -> _Text: ... + self, usage: str, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[str] + ) -> str: ... + def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> str: ... + def _format_text(self, text: str) -> str: ... + def _format_action(self, action: Action) -> str: ... + def _format_action_invocation(self, action: Action) -> str: ... + def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], Tuple[str, ...]]: ... + def _format_args(self, action: Action, default_metavar: str) -> str: ... + def _expand_help(self, action: Action) -> str: ... def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... - def _split_lines(self, text: Text, width: int) -> List[_Text]: ... - def _fill_text(self, text: Text, width: int, indent: Text) -> _Text: ... - def _get_help_string(self, action: Action) -> Optional[_Text]: ... - def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... - def _get_default_metavar_for_positional(self, action: Action) -> _Text: ... + def _split_lines(self, text: str, width: int) -> List[str]: ... + def _fill_text(self, text: str, width: int, indent: str) -> str: ... + def _get_help_string(self, action: Action) -> Optional[str]: ... + def _get_default_metavar_for_optional(self, action: Action) -> str: ... + def _get_default_metavar_for_positional(self, action: Action) -> str: ... class RawDescriptionHelpFormatter(HelpFormatter): ... class RawTextHelpFormatter(RawDescriptionHelpFormatter): ... class ArgumentDefaultsHelpFormatter(HelpFormatter): ... - -if sys.version_info >= (3,): - class MetavarTypeHelpFormatter(HelpFormatter): ... +class MetavarTypeHelpFormatter(HelpFormatter): ... class Action(_AttributeHolder): - option_strings: Sequence[_Text] - dest: _Text - nargs: Optional[Union[int, _Text]] + option_strings: Sequence[str] + dest: str + nargs: Optional[Union[int, str]] const: Any default: Any type: Union[Callable[[str], Any], FileType, None] choices: Optional[Iterable[Any]] required: bool - help: Optional[_Text] - metavar: Optional[Union[_Text, Tuple[_Text, ...]]] + help: Optional[str] + metavar: Optional[Union[str, Tuple[str, ...]]] def __init__( self, - option_strings: Sequence[Text], - dest: Text, - nargs: Optional[Union[int, Text]] = ..., + option_strings: Sequence[str], + dest: str, + nargs: Optional[Union[int, str]] = ..., const: Optional[_T] = ..., default: Union[_T, str, None] = ..., - type: Optional[Union[Callable[[Text], _T], Callable[[str], _T], FileType]] = ..., + type: Optional[Union[Callable[[str], _T], Callable[[str], _T], FileType]] = ..., choices: Optional[Iterable[_T]] = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... def __call__( self, parser: ArgumentParser, namespace: Namespace, - values: Union[Text, Sequence[Any], None], - option_string: Optional[Text] = ..., + values: Union[str, Sequence[Any], None], + option_string: Optional[str] = ..., ) -> None: ... if sys.version_info >= (3, 9): def format_usage(self) -> str: ... @@ -334,39 +307,36 @@ if sys.version_info >= (3, 9): option_strings: Sequence[str], dest: str, default: Union[_T, str, None] = ..., - type: Optional[Union[Callable[[Text], _T], Callable[[str], _T], FileType]] = ..., + type: Optional[Union[Callable[[str], _T], Callable[[str], _T], FileType]] = ..., choices: Optional[Iterable[_T]] = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... class Namespace(_AttributeHolder): def __init__(self, **kwargs: Any) -> None: ... - def __getattr__(self, name: Text) -> Any: ... - def __setattr__(self, name: Text, value: Any) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... def __contains__(self, key: str) -> bool: ... class FileType: # undocumented - _mode: _Text + _mode: str _bufsize: int - if sys.version_info >= (3,): - _encoding: Optional[str] - _errors: Optional[str] - def __init__( - self, mode: str = ..., bufsize: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ... - ) -> None: ... - else: - def __init__(self, mode: Text = ..., bufsize: Optional[int] = ...) -> None: ... - def __call__(self, string: Text) -> IO[Any]: ... + _encoding: Optional[str] + _errors: Optional[str] + def __init__( + self, mode: str = ..., bufsize: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ... + ) -> None: ... + def __call__(self, string: str) -> IO[Any]: ... # undocumented class _ArgumentGroup(_ActionsContainer): - title: Optional[_Text] + title: Optional[str] _group_actions: List[Action] def __init__( - self, container: _ActionsContainer, title: Optional[Text] = ..., description: Optional[Text] = ..., **kwargs: Any + self, container: _ActionsContainer, title: Optional[str] = ..., description: Optional[str] = ..., **kwargs: Any ) -> None: ... # undocumented @@ -382,25 +352,25 @@ class _StoreAction(Action): ... class _StoreConstAction(Action): def __init__( self, - option_strings: Sequence[Text], - dest: Text, + option_strings: Sequence[str], + dest: str, const: Any, default: Any = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... # undocumented class _StoreTrueAction(_StoreConstAction): def __init__( - self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Optional[Text] = ... + self, option_strings: Sequence[str], dest: str, default: bool = ..., required: bool = ..., help: Optional[str] = ... ) -> None: ... # undocumented class _StoreFalseAction(_StoreConstAction): def __init__( - self, option_strings: Sequence[Text], dest: Text, default: bool = ..., required: bool = ..., help: Optional[Text] = ... + self, option_strings: Sequence[str], dest: str, default: bool = ..., required: bool = ..., help: Optional[str] = ... ) -> None: ... # undocumented @@ -410,70 +380,63 @@ class _AppendAction(Action): ... class _AppendConstAction(Action): def __init__( self, - option_strings: Sequence[Text], - dest: Text, + option_strings: Sequence[str], + dest: str, const: Any, default: Any = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... # undocumented class _CountAction(Action): def __init__( - self, option_strings: Sequence[Text], dest: Text, default: Any = ..., required: bool = ..., help: Optional[Text] = ... + self, option_strings: Sequence[str], dest: str, default: Any = ..., required: bool = ..., help: Optional[str] = ... ) -> None: ... # undocumented class _HelpAction(Action): - def __init__( - self, option_strings: Sequence[Text], dest: Text = ..., default: Text = ..., help: Optional[Text] = ... - ) -> None: ... + def __init__(self, option_strings: Sequence[str], dest: str = ..., default: str = ..., help: Optional[str] = ...) -> None: ... # undocumented class _VersionAction(Action): - version: Optional[_Text] + version: Optional[str] def __init__( - self, - option_strings: Sequence[Text], - version: Optional[Text] = ..., - dest: Text = ..., - default: Text = ..., - help: Text = ..., + self, option_strings: Sequence[str], version: Optional[str] = ..., dest: str = ..., default: str = ..., help: str = ... ) -> None: ... # undocumented class _SubParsersAction(Action): _ChoicesPseudoAction: Type[Any] # nested class - _prog_prefix: _Text + _prog_prefix: str _parser_class: Type[ArgumentParser] - _name_parser_map: Dict[_Text, ArgumentParser] - choices: Dict[_Text, ArgumentParser] + _name_parser_map: Dict[str, ArgumentParser] + choices: Dict[str, ArgumentParser] _choices_actions: List[Action] if sys.version_info >= (3, 7): def __init__( self, - option_strings: Sequence[Text], - prog: Text, + option_strings: Sequence[str], + prog: str, parser_class: Type[ArgumentParser], - dest: Text = ..., + dest: str = ..., required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... else: def __init__( self, - option_strings: Sequence[Text], - prog: Text, + option_strings: Sequence[str], + prog: str, parser_class: Type[ArgumentParser], - dest: Text = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + dest: str = ..., + help: Optional[str] = ..., + metavar: Optional[Union[str, Tuple[str, ...]]] = ..., ) -> None: ... # TODO: Type keyword args properly. - def add_parser(self, name: Text, **kwargs: Any) -> ArgumentParser: ... + def add_parser(self, name: str, **kwargs: Any) -> ArgumentParser: ... def _get_subactions(self) -> List[Action]: ... # undocumented @@ -481,7 +444,7 @@ class ArgumentTypeError(Exception): ... if sys.version_info < (3, 7): # undocumented - def _ensure_value(namespace: Namespace, name: Text, value: Any) -> Any: ... + def _ensure_value(namespace: Namespace, name: str, value: Any) -> Any: ... # undocumented def _get_action_name(argument: Optional[Action]) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 498bf92919f1..a215494d2ff0 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Text, Tuple, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Tuple, TypeVar, Union, overload from typing_extensions import Literal _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] @@ -7,10 +7,9 @@ _FloatTypeCode = Literal["f", "d"] _UnicodeTypeCode = Literal["u"] _TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] -_T = TypeVar("_T", int, float, Text) +_T = TypeVar("_T", int, float, str) -if sys.version_info >= (3,): - typecodes: str +typecodes: str class array(MutableSequence[_T], Generic[_T]): typecode: _TypeCode @@ -20,7 +19,7 @@ class array(MutableSequence[_T], Generic[_T]): @overload def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... @overload - def __init__(self: array[Text], typecode: _UnicodeTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + def __init__(self: array[str], typecode: _UnicodeTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... @overload def __init__(self, typecode: str, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... def append(self, __v: _T) -> None: ... @@ -28,8 +27,7 @@ class array(MutableSequence[_T], Generic[_T]): def byteswap(self) -> None: ... def count(self, __v: Any) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... - if sys.version_info >= (3, 2): - def frombytes(self, __buffer: bytes) -> None: ... + def frombytes(self, __buffer: bytes) -> None: ... def fromfile(self, __f: BinaryIO, __n: int) -> None: ... def fromlist(self, __list: List[_T]) -> None: ... def fromunicode(self, __ustr: str) -> None: ... @@ -39,17 +37,12 @@ class array(MutableSequence[_T], Generic[_T]): def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence def insert(self, __i: int, __v: _T) -> None: ... def pop(self, __i: int = ...) -> _T: ... - if sys.version_info < (3,): - def read(self, f: BinaryIO, n: int) -> None: ... def remove(self, __v: Any) -> None: ... def reverse(self) -> None: ... - if sys.version_info >= (3, 2): - def tobytes(self) -> bytes: ... + def tobytes(self) -> bytes: ... def tofile(self, __f: BinaryIO) -> None: ... def tolist(self) -> List[_T]: ... def tounicode(self) -> str: ... - if sys.version_info < (3,): - def write(self, f: BinaryIO) -> None: ... if sys.version_info < (3, 9): def fromstring(self, __buffer: bytes) -> None: ... def tostring(self) -> bytes: ... @@ -72,9 +65,5 @@ class array(MutableSequence[_T], Generic[_T]): def __lt__(self, other: array[_T]) -> bool: ... def __mul__(self, n: int) -> array[_T]: ... def __rmul__(self, n: int) -> array[_T]: ... - if sys.version_info < (3,): - def __delslice__(self, i: int, j: int) -> None: ... - def __getslice__(self, i: int, j: int) -> array[_T]: ... - def __setslice__(self, i: int, j: int, y: array[_T]) -> None: ... ArrayType = array diff --git a/mypy/typeshed/stdlib/asynchat.pyi b/mypy/typeshed/stdlib/asynchat.pyi index 34039b993400..94637d04a264 100644 --- a/mypy/typeshed/stdlib/asynchat.pyi +++ b/mypy/typeshed/stdlib/asynchat.pyi @@ -1,8 +1,7 @@ import asyncore import socket -import sys from abc import abstractmethod -from typing import Optional, Sequence, Tuple, Union +from typing import Optional, Union class simple_producer: def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... @@ -28,12 +27,3 @@ class async_chat(asyncore.dispatcher): def close_when_done(self) -> None: ... def initiate_send(self) -> None: ... def discard_buffers(self) -> None: ... - -if sys.version_info < (3, 0): - class fifo: - def __init__(self, list: Sequence[Union[bytes, simple_producer]] = ...) -> None: ... - def __len__(self) -> int: ... - def is_empty(self) -> bool: ... - def first(self) -> bytes: ... - def push(self, data: Union[bytes, simple_producer]) -> None: ... - def pop(self) -> Tuple[int, bytes]: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index c2ad4a609c01..4c171f0ce9db 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -65,7 +65,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): def create_future(self) -> Future[Any]: ... # Tasks methods if sys.version_info >= (3, 8): - def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]], *, name: Optional[str] = ...) -> Task[_T]: ... + def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]], *, name: object = ...) -> Task[_T]: ... else: def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... def set_task_factory( diff --git a/mypy/typeshed/stdlib/asyncio/base_tasks.pyi b/mypy/typeshed/stdlib/asyncio/base_tasks.pyi index fbe0a03e8755..b336ae488aed 100644 --- a/mypy/typeshed/stdlib/asyncio/base_tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_tasks.pyi @@ -1,4 +1,4 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import FrameType from typing import Any, List, Optional @@ -6,4 +6,4 @@ from . import tasks def _task_repr_info(task: tasks.Task[Any]) -> List[str]: ... # undocumented def _task_get_stack(task: tasks.Task[Any], limit: Optional[int]) -> List[FrameType]: ... # undocumented -def _task_print_stack(task: tasks.Task[Any], limit: Optional[int], file: AnyPath) -> None: ... # undocumented +def _task_print_stack(task: tasks.Task[Any], limit: Optional[int], file: StrOrBytesPath) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index dea090682f2b..e514b884c201 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -3,5 +3,5 @@ from typing import Any, Callable, TypeVar _F = TypeVar("_F", bound=Callable[..., Any]) def coroutine(func: _F) -> _F: ... -def iscoroutinefunction(func: Callable[..., Any]) -> bool: ... -def iscoroutine(obj: Any) -> bool: ... +def iscoroutinefunction(func: object) -> bool: ... +def iscoroutine(obj: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index a6367201052b..f0879b8daa33 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import StrPath from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional, Tuple, Union from . import events, protocols, transports @@ -36,9 +37,7 @@ async def start_server( if sys.platform != "win32": if sys.version_info >= (3, 7): - from os import PathLike - - _PathType = Union[str, PathLike[str]] + _PathType = StrPath else: _PathType = str async def open_unix_connection( diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index d443625db28a..9d28d9e2bc4b 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -1,12 +1,12 @@ import subprocess import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports from typing import IO, Any, Callable, Optional, Tuple, Union from typing_extensions import Literal if sys.version_info >= (3, 8): - _ExecArg = AnyPath + _ExecArg = StrOrBytesPath else: _ExecArg = Union[str, bytes] @@ -56,10 +56,10 @@ if sys.version_info >= (3, 10): errors: None = ..., text: Literal[False, None] = ..., # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[subprocess._ENV] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., @@ -82,10 +82,10 @@ if sys.version_info >= (3, 10): errors: None = ..., # These parameters are taken by subprocess.Popen, which this ultimately delegates to text: Optional[bool] = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[subprocess._ENV] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., @@ -111,10 +111,10 @@ else: errors: None = ..., text: Literal[False, None] = ..., # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[subprocess._ENV] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., @@ -138,10 +138,10 @@ else: errors: None = ..., # These parameters are taken by subprocess.Popen, which this ultimately delegates to text: Optional[bool] = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[subprocess._ENV] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index a05a205115f3..629b28752a0d 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -59,36 +59,6 @@ class dispatcher: def handle_connect(self) -> None: ... def handle_accept(self) -> None: ... def handle_close(self) -> None: ... - if sys.version_info < (3, 5): - # Historically, some methods were "imported" from `self.socket` by - # means of `__getattr__`. This was long deprecated, and as of Python - # 3.5 has been removed; simply call the relevant methods directly on - # self.socket if necessary. - def detach(self) -> int: ... - def fileno(self) -> int: ... - # return value is an address - def getpeername(self) -> Any: ... - def getsockname(self) -> Any: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: None = ...) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - def gettimeout(self) -> float: ... - def ioctl(self, control: object, option: Tuple[int, int, int]) -> None: ... - # TODO the return value may be BinaryIO or TextIO, depending on mode - def makefile( - self, mode: str = ..., buffering: int = ..., encoding: str = ..., errors: str = ..., newline: str = ... - ) -> Any: ... - # return type is an address - def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ... - def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... - def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... - def sendto(self, data: bytes, address: Union[Tuple[str, int], str], flags: int = ...) -> int: ... - def setblocking(self, flag: bool) -> None: ... - def settimeout(self, value: Union[float, None]) -> None: ... - def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... - def shutdown(self, how: int) -> None: ... class dispatcher_with_send(dispatcher): def __init__(self, sock: SocketType = ..., map: Optional[_maptype] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index e217d6d3dbf2..47118516ca82 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -1,40 +1,31 @@ import sys from typing import IO, Optional, Union -if sys.version_info >= (3, 0): - _encodable = bytes - _decodable = Union[bytes, str] -else: - _encodable = Union[bytes, unicode] - _decodable = Union[bytes, unicode] - -def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... -def b64decode(s: _decodable, altchars: Optional[bytes] = ..., validate: bool = ...) -> bytes: ... -def standard_b64encode(s: _encodable) -> bytes: ... -def standard_b64decode(s: _decodable) -> bytes: ... -def urlsafe_b64encode(s: _encodable) -> bytes: ... -def urlsafe_b64decode(s: _decodable) -> bytes: ... -def b32encode(s: _encodable) -> bytes: ... -def b32decode(s: _decodable, casefold: bool = ..., map01: Optional[bytes] = ...) -> bytes: ... -def b16encode(s: _encodable) -> bytes: ... -def b16decode(s: _decodable, casefold: bool = ...) -> bytes: ... +def b64encode(s: bytes, altchars: Optional[bytes] = ...) -> bytes: ... +def b64decode(s: Union[str, bytes], altchars: Optional[bytes] = ..., validate: bool = ...) -> bytes: ... +def standard_b64encode(s: bytes) -> bytes: ... +def standard_b64decode(s: Union[str, bytes]) -> bytes: ... +def urlsafe_b64encode(s: bytes) -> bytes: ... +def urlsafe_b64decode(s: Union[str, bytes]) -> bytes: ... +def b32encode(s: bytes) -> bytes: ... +def b32decode(s: Union[str, bytes], casefold: bool = ..., map01: Optional[bytes] = ...) -> bytes: ... +def b16encode(s: bytes) -> bytes: ... +def b16decode(s: Union[str, bytes], casefold: bool = ...) -> bytes: ... if sys.version_info >= (3, 10): - def b32hexencode(s: _encodable) -> bytes: ... - def b32hexdecode(s: _decodable, casefold: bool = ...) -> bytes: ... - -if sys.version_info >= (3, 4): - def a85encode(b: _encodable, *, foldspaces: bool = ..., wrapcol: int = ..., pad: bool = ..., adobe: bool = ...) -> bytes: ... - def a85decode(b: _decodable, *, foldspaces: bool = ..., adobe: bool = ..., ignorechars: Union[str, bytes] = ...) -> bytes: ... - def b85encode(b: _encodable, pad: bool = ...) -> bytes: ... - def b85decode(b: _decodable) -> bytes: ... + def b32hexencode(s: bytes) -> bytes: ... + def b32hexdecode(s: Union[str, bytes], casefold: bool = ...) -> bytes: ... +def a85encode(b: bytes, *, foldspaces: bool = ..., wrapcol: int = ..., pad: bool = ..., adobe: bool = ...) -> bytes: ... +def a85decode( + b: Union[str, bytes], *, foldspaces: bool = ..., adobe: bool = ..., ignorechars: Union[str, bytes] = ... +) -> bytes: ... +def b85encode(b: bytes, pad: bool = ...) -> bytes: ... +def b85decode(b: Union[str, bytes]) -> bytes: ... def decode(input: IO[bytes], output: IO[bytes]) -> None: ... def encode(input: IO[bytes], output: IO[bytes]) -> None: ... - -if sys.version_info >= (3,): - def encodebytes(s: bytes) -> bytes: ... - def decodebytes(s: bytes) -> bytes: ... +def encodebytes(s: bytes) -> bytes: ... +def decodebytes(s: bytes) -> bytes: ... if sys.version_info < (3, 9): def encodestring(s: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index db843ad6ca31..b74df13c3187 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,50 +1,34 @@ import sys -from typing import Text, Union +from typing import Union -if sys.version_info >= (3, 0): - # But since Python 3.3 ASCII-only unicode strings are accepted by the - # a2b_* functions. - _Bytes = bytes - _Ascii = Union[bytes, str] -else: - # Python 2 accepts unicode ascii pretty much everywhere. - _Bytes = Text - _Ascii = Text - -def a2b_uu(__data: _Ascii) -> bytes: ... +def a2b_uu(__data: Union[str, bytes]) -> bytes: ... if sys.version_info >= (3, 7): - def b2a_uu(__data: _Bytes, *, backtick: bool = ...) -> bytes: ... - -else: - def b2a_uu(__data: _Bytes) -> bytes: ... - -def a2b_base64(__data: _Ascii) -> bytes: ... - -if sys.version_info >= (3, 6): - def b2a_base64(__data: _Bytes, *, newline: bool = ...) -> bytes: ... + def b2a_uu(__data: bytes, *, backtick: bool = ...) -> bytes: ... else: - def b2a_base64(__data: _Bytes) -> bytes: ... - -def a2b_qp(data: _Ascii, header: bool = ...) -> bytes: ... -def b2a_qp(data: _Bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... -def a2b_hqx(__data: _Ascii) -> bytes: ... -def rledecode_hqx(__data: _Bytes) -> bytes: ... -def rlecode_hqx(__data: _Bytes) -> bytes: ... -def b2a_hqx(__data: _Bytes) -> bytes: ... -def crc_hqx(__data: _Bytes, __crc: int) -> int: ... -def crc32(__data: _Bytes, __crc: int = ...) -> int: ... -def b2a_hex(__data: _Bytes) -> bytes: ... + def b2a_uu(__data: bytes) -> bytes: ... + +def a2b_base64(__data: Union[str, bytes]) -> bytes: ... +def b2a_base64(__data: bytes, *, newline: bool = ...) -> bytes: ... +def a2b_qp(data: Union[str, bytes], header: bool = ...) -> bytes: ... +def b2a_qp(data: bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... +def a2b_hqx(__data: Union[str, bytes]) -> bytes: ... +def rledecode_hqx(__data: bytes) -> bytes: ... +def rlecode_hqx(__data: bytes) -> bytes: ... +def b2a_hqx(__data: bytes) -> bytes: ... +def crc_hqx(__data: bytes, __crc: int) -> int: ... +def crc32(__data: bytes, __crc: int = ...) -> int: ... +def b2a_hex(__data: bytes) -> bytes: ... if sys.version_info >= (3, 8): def hexlify(data: bytes, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> bytes: ... else: - def hexlify(__data: _Bytes) -> bytes: ... + def hexlify(__data: bytes) -> bytes: ... -def a2b_hex(__hexstr: _Ascii) -> bytes: ... -def unhexlify(__hexstr: _Ascii) -> bytes: ... +def a2b_hex(__hexstr: Union[str, bytes]) -> bytes: ... +def unhexlify(__hexstr: Union[str, bytes]) -> bytes: ... class Error(ValueError): ... class Incomplete(Exception): ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 69da371906d0..752755d2bf92 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1,13 +1,13 @@ import sys import types from _typeshed import ( - AnyPath, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, ReadableBuffer, + StrOrBytesPath, SupportsDivMod, SupportsKeysAndGetItem, SupportsLessThan, @@ -156,6 +156,7 @@ class type(object): def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... if sys.version_info >= (3, 10): def __or__(self, t: Any) -> types.Union: ... + def __ror__(self, t: Any) -> types.Union: ... class super(object): @overload @@ -723,7 +724,7 @@ class tuple(Sequence[_T_co], Generic[_T_co]): @overload def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... @overload - def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __add__(self, x: Tuple[_T, ...]) -> Tuple[Union[_T_co, _T], ...]: ... def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... @@ -810,10 +811,10 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def items(self) -> ItemsView[_KT, _VT]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> dict[_T, Optional[Any]]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... def __len__(self) -> int: ... def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... @@ -1018,7 +1019,12 @@ class filter(Iterator[_T], Generic[_T]): def __next__(self) -> _T: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -def getattr(__o: Any, name: str, __default: Any = ...) -> Any: ... +@overload +def getattr(__o: Any, name: str) -> Any: ... +@overload +def getattr(__o: Any, name: str, __default: None) -> Optional[Any]: ... +@overload +def getattr(__o: Any, name: str, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: str) -> bool: ... def hash(__obj: object) -> int: ... @@ -1032,8 +1038,19 @@ def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... def iter(__function: Callable[[], Optional[_T]], __sentinel: None) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... + +if sys.version_info >= (3, 10): + def isinstance( + __obj: object, __class_or_tuple: Union[type, types.Union, Tuple[Union[type, types.Union, Tuple[Any, ...]], ...]] + ) -> bool: ... + def issubclass( + __cls: type, __class_or_tuple: Union[type, types.Union, Tuple[Union[type, types.Union, Tuple[Any, ...]], ...]] + ) -> bool: ... + +else: + def isinstance(__obj: object, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... + def issubclass(__cls: type, __class_or_tuple: Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]) -> bool: ... + def len(__obj: Sized) -> int: ... def license() -> None: ... def locals() -> Dict[str, Any]: ... @@ -1115,7 +1132,7 @@ def next(__i: Iterator[_T]) -> _T: ... def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... def oct(__number: Union[int, SupportsIndex]) -> str: ... -_OpenFile = Union[AnyPath, int] +_OpenFile = Union[StrOrBytesPath, int] _Opener = Callable[[str, int], int] # Text mode: always returns a TextIOWrapper diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index dfc1876bf43e..390024a04184 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -1,45 +1,45 @@ import io import sys -from _typeshed import AnyPath, ReadableBuffer, WriteableBuffer +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from typing import IO, Any, Iterable, List, Optional, TextIO, TypeVar, Union, overload from typing_extensions import Literal, SupportsIndex -_PathOrFile = Union[AnyPath, IO[bytes]] +_PathOrFile = Union[StrOrBytesPath, IO[bytes]] _T = TypeVar("_T") def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... -if sys.version_info >= (3, 3): - _OpenBinaryMode = Literal["r", "rb", "w", "wb", "x", "xb", "a", "ab"] - _OpenTextMode = Literal["rt", "wt", "xt", "at"] - @overload - def open( - filename: _PathOrFile, - mode: _OpenBinaryMode = ..., - compresslevel: int = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - ) -> BZ2File: ... - @overload - def open( - filename: AnyPath, - mode: _OpenTextMode, - compresslevel: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - ) -> TextIO: ... - @overload - def open( - filename: _PathOrFile, - mode: str, - compresslevel: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - ) -> Union[BZ2File, TextIO]: ... +_OpenBinaryMode = Literal["r", "rb", "w", "wb", "x", "xb", "a", "ab"] +_OpenTextMode = Literal["rt", "wt", "xt", "at"] + +@overload +def open( + filename: _PathOrFile, + mode: _OpenBinaryMode = ..., + compresslevel: int = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> BZ2File: ... +@overload +def open( + filename: StrOrBytesPath, + mode: _OpenTextMode, + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> TextIO: ... +@overload +def open( + filename: _PathOrFile, + mode: str, + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> Union[BZ2File, TextIO]: ... class BZ2File(io.BufferedIOBase, IO[bytes]): def __enter__(self: _T) -> _T: ... @@ -64,15 +64,10 @@ class BZ2Compressor(object): def flush(self) -> bytes: ... class BZ2Decompressor(object): - if sys.version_info >= (3, 5): - def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... - else: - def decompress(self, data: bytes) -> bytes: ... - if sys.version_info >= (3, 3): - @property - def eof(self) -> bool: ... - if sys.version_info >= (3, 5): - @property - def needs_input(self) -> bool: ... + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + @property + def eof(self) -> bool: ... + @property + def needs_input(self) -> bool: ... @property def unused_data(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 638a2a79f2e5..6648ed5b94a3 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import CodeType from typing import Any, Callable, Dict, Optional, Tuple, TypeVar, Union @@ -20,7 +20,7 @@ class Profile: def enable(self) -> None: ... def disable(self) -> None: ... def print_stats(self, sort: Union[str, int] = ...) -> None: ... - def dump_stats(self, file: AnyPath) -> None: ... + def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... def run(self: _SelfT, cmd: str) -> _SelfT: ... diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index ad73132b4595..c1d69a466f2e 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -77,17 +77,10 @@ class HTMLCalendar(Calendar): cssclass_year: str cssclass_year_head: str -if sys.version_info >= (3, 0): - class different_locale: - def __init__(self, locale: _LocaleType) -> None: ... - def __enter__(self) -> _LocaleType: ... - def __exit__(self, *args: Any) -> None: ... - -else: - class TimeEncoding: - def __init__(self, locale: _LocaleType) -> None: ... - def __enter__(self) -> _LocaleType: ... - def __exit__(self, *args: Any) -> None: ... +class different_locale: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> _LocaleType: ... + def __exit__(self, *args: Any) -> None: ... class LocaleTextCalendar(TextCalendar): def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index 7603ecd9afbe..b8db1d8092a1 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,4 +1,4 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import FrameType, TracebackType from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type @@ -19,7 +19,7 @@ class Hook: # undocumented def __init__( self, display: int = ..., - logdir: Optional[AnyPath] = ..., + logdir: Optional[StrOrBytesPath] = ..., context: int = ..., file: Optional[IO[str]] = ..., format: str = ..., @@ -30,4 +30,4 @@ class Hook: # undocumented def handle(self, info: Optional[_ExcInfo] = ...) -> None: ... def handler(info: Optional[_ExcInfo] = ...) -> None: ... -def enable(display: int = ..., logdir: Optional[AnyPath] = ..., context: int = ..., format: str = ...) -> None: ... +def enable(display: int = ..., logdir: Optional[StrOrBytesPath] = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index eaa62eafcb33..8d67e6c47bb4 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,14 +1,12 @@ -import sys from typing import SupportsComplex, SupportsFloat, Tuple, Union e: float pi: float -if sys.version_info >= (3, 6): - inf: float - infj: complex - nan: float - nanj: complex - tau: float +inf: float +infj: complex +nan: float +nanj: complex +tau: float _C = Union[SupportsFloat, SupportsComplex, complex] @@ -21,10 +19,7 @@ def atanh(__z: _C) -> complex: ... def cos(__z: _C) -> complex: ... def cosh(__z: _C) -> complex: ... def exp(__z: _C) -> complex: ... - -if sys.version_info >= (3, 5): - def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... - +def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... def isinf(__z: _C) -> bool: ... def isnan(__z: _C) -> bool: ... def log(__x: _C, __y_obj: _C = ...) -> complex: ... @@ -37,6 +32,4 @@ def sinh(__z: _C) -> complex: ... def sqrt(__z: _C) -> complex: ... def tan(__z: _C) -> complex: ... def tanh(__z: _C) -> complex: ... - -if sys.version_info >= (3,): - def isfinite(__z: _C) -> bool: ... +def isfinite(__z: _C) -> bool: ... diff --git a/mypy/typeshed/stdlib/code.pyi b/mypy/typeshed/stdlib/code.pyi index 16c2b129dd1e..5111e928efc8 100644 --- a/mypy/typeshed/stdlib/code.pyi +++ b/mypy/typeshed/stdlib/code.pyi @@ -1,4 +1,3 @@ -import sys from types import CodeType from typing import Any, Callable, Mapping, Optional @@ -12,25 +11,15 @@ class InteractiveInterpreter: class InteractiveConsole(InteractiveInterpreter): def __init__(self, locals: Optional[Mapping[str, Any]] = ..., filename: str = ...) -> None: ... - if sys.version_info >= (3, 6): - def interact(self, banner: Optional[str] = ..., exitmsg: Optional[str] = ...) -> None: ... - else: - def interact(self, banner: Optional[str] = ...) -> None: ... + def interact(self, banner: Optional[str] = ..., exitmsg: Optional[str] = ...) -> None: ... def push(self, line: str) -> bool: ... def resetbuffer(self) -> None: ... def raw_input(self, prompt: str = ...) -> str: ... -if sys.version_info >= (3, 6): - def interact( - banner: Optional[str] = ..., - readfunc: Optional[Callable[[str], str]] = ..., - local: Optional[Mapping[str, Any]] = ..., - exitmsg: Optional[str] = ..., - ) -> None: ... - -else: - def interact( - banner: Optional[str] = ..., readfunc: Optional[Callable[[str], str]] = ..., local: Optional[Mapping[str, Any]] = ... - ) -> None: ... - +def interact( + banner: Optional[str] = ..., + readfunc: Optional[Callable[[str], str]] = ..., + local: Optional[Mapping[str, Any]] = ..., + exitmsg: Optional[str] = ..., +) -> None: ... def compile_command(source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 79be8e254c4c..7172d0074c7b 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -1,4 +1,3 @@ -import sys import types from abc import abstractmethod from typing import ( @@ -12,7 +11,6 @@ from typing import ( List, Optional, Protocol, - Text, TextIO, Tuple, Type, @@ -23,25 +21,22 @@ from typing import ( from typing_extensions import Literal # TODO: this only satisfies the most common interface, where -# bytes (py2 str) is the raw form and str (py2 unicode) is the cooked form. +# bytes is the raw form and str is the cooked form. # In the long run, both should become template parameters maybe? # There *are* bytes->bytes and str->str encodings in the standard library. # They are much more common in Python 2 than in Python 3. -_Decoded = Text -_Encoded = bytes - class _Encoder(Protocol): - def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode + def __call__(self, input: str, errors: str = ...) -> Tuple[bytes, int]: ... # signature of Codec().encode class _Decoder(Protocol): - def __call__(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... # signature of Codec().decode + def __call__(self, input: bytes, errors: str = ...) -> Tuple[str, int]: ... # signature of Codec().decode class _StreamReader(Protocol): - def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamReader: ... + def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamReader: ... class _StreamWriter(Protocol): - def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamWriter: ... + def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamWriter: ... class _IncrementalEncoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalEncoder: ... @@ -75,18 +70,16 @@ def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> b @overload def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore @overload -def encode(obj: _Decoded, encoding: str = ..., errors: str = ...) -> _Encoded: ... +def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... @overload def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore @overload -def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> Text: ... +def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... @overload -def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: ... +def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ... def lookup(__encoding: str) -> CodecInfo: ... -def utf_16_be_decode( - __data: _Encoded, __errors: Optional[str] = ..., __final: bool = ... -) -> Tuple[_Decoded, int]: ... # undocumented -def utf_16_be_encode(__str: _Decoded, __errors: Optional[str] = ...) -> Tuple[_Encoded, int]: ... # undocumented +def utf_16_be_decode(__data: bytes, __errors: Optional[str] = ..., __final: bool = ...) -> Tuple[str, int]: ... # undocumented +def utf_16_be_encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... # undocumented class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property @@ -125,11 +118,9 @@ def register(__search_function: Callable[[str], Optional[CodecInfo]]) -> None: . def open( filename: str, mode: str = ..., encoding: Optional[str] = ..., errors: str = ..., buffering: int = ... ) -> StreamReaderWriter: ... -def EncodedFile( - file: IO[_Encoded], data_encoding: str, file_encoding: Optional[str] = ..., errors: str = ... -) -> StreamRecoder: ... -def iterencode(iterator: Iterable[_Decoded], encoding: str, errors: str = ...) -> Generator[_Encoded, None, None]: ... -def iterdecode(iterator: Iterable[_Encoded], encoding: str, errors: str = ...) -> Generator[_Decoded, None, None]: ... +def EncodedFile(file: IO[bytes], data_encoding: str, file_encoding: Optional[str] = ..., errors: str = ...) -> StreamRecoder: ... +def iterencode(iterator: Iterable[str], encoding: str, errors: str = ...) -> Generator[bytes, None, None]: ... +def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> Generator[str, None, None]: ... BOM: bytes BOM_BE: bytes @@ -156,42 +147,42 @@ def backslashreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], class Codec: # These are sort of @abstractmethod but sort of not. # The StreamReader and StreamWriter subclasses only implement one. - def encode(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... - def decode(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... + def encode(self, input: str, errors: str = ...) -> Tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = ...) -> Tuple[str, int]: ... class IncrementalEncoder: errors: str def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... + def encode(self, input: str, final: bool = ...) -> bytes: ... def reset(self) -> None: ... # documentation says int but str is needed for the subclass. - def getstate(self) -> Union[int, _Decoded]: ... - def setstate(self, state: Union[int, _Decoded]) -> None: ... + def getstate(self) -> Union[int, str]: ... + def setstate(self, state: Union[int, str]) -> None: ... class IncrementalDecoder: errors: str def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... + def decode(self, input: bytes, final: bool = ...) -> str: ... def reset(self) -> None: ... - def getstate(self) -> Tuple[_Encoded, int]: ... - def setstate(self, state: Tuple[_Encoded, int]) -> None: ... + def getstate(self) -> Tuple[bytes, int]: ... + def setstate(self, state: Tuple[bytes, int]) -> None: ... # These are not documented but used in encodings/*.py implementations. class BufferedIncrementalEncoder(IncrementalEncoder): buffer: str def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def _buffer_encode(self, input: _Decoded, errors: str, final: bool) -> _Encoded: ... - def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... + def _buffer_encode(self, input: str, errors: str, final: bool) -> bytes: ... + def encode(self, input: str, final: bool = ...) -> bytes: ... class BufferedIncrementalDecoder(IncrementalDecoder): buffer: bytes def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... - def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[str, int]: ... + def decode(self, input: bytes, final: bool = ...) -> str: ... _SW = TypeVar("_SW", bound=StreamWriter) @@ -199,9 +190,9 @@ _SW = TypeVar("_SW", bound=StreamWriter) # attributes and methods are passed-through from the stream. class StreamWriter(Codec): errors: str - def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... - def write(self, object: _Decoded) -> None: ... - def writelines(self, list: Iterable[_Decoded]) -> None: ... + def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... + def write(self, object: str) -> None: ... + def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... def __enter__(self: _SW) -> _SW: ... def __exit__( @@ -213,16 +204,16 @@ _SR = TypeVar("_SR", bound=StreamReader) class StreamReader(Codec): errors: str - def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... - def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... - def readline(self, size: Optional[int] = ..., keepends: bool = ...) -> _Decoded: ... - def readlines(self, sizehint: Optional[int] = ..., keepends: bool = ...) -> List[_Decoded]: ... + def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... + def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> str: ... + def readline(self, size: Optional[int] = ..., keepends: bool = ...) -> str: ... + def readlines(self, sizehint: Optional[int] = ..., keepends: bool = ...) -> List[str]: ... def reset(self) -> None: ... def __enter__(self: _SR) -> _SR: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... - def __iter__(self) -> Iterator[_Decoded]: ... + def __iter__(self) -> Iterator[str]: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... _T = TypeVar("_T", bound=StreamReaderWriter) @@ -230,18 +221,15 @@ _T = TypeVar("_T", bound=StreamReaderWriter) # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): - def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... - def read(self, size: int = ...) -> _Decoded: ... - def readline(self, size: Optional[int] = ...) -> _Decoded: ... - def readlines(self, sizehint: Optional[int] = ...) -> List[_Decoded]: ... - if sys.version_info >= (3,): - def __next__(self) -> Text: ... - else: - def next(self) -> Text: ... + def __init__(self, stream: IO[bytes], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: Optional[int] = ...) -> str: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[str]: ... + def __next__(self) -> str: ... def __iter__(self: _T) -> _T: ... # This actually returns None, but that's incompatible with the supertype - def write(self, data: _Decoded) -> int: ... - def writelines(self, list: Iterable[_Decoded]) -> None: ... + def write(self, data: str) -> int: ... + def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... # Same as write() def seek(self, offset: int, whence: int = ...) -> int: ... @@ -267,7 +255,7 @@ _SRT = TypeVar("_SRT", bound=StreamRecoder) class StreamRecoder(BinaryIO): def __init__( self, - stream: IO[_Encoded], + stream: IO[bytes], encode: _Encoder, decode: _Decoder, Reader: _StreamReader, @@ -277,10 +265,7 @@ class StreamRecoder(BinaryIO): def read(self, size: int = ...) -> bytes: ... def readline(self, size: Optional[int] = ...) -> bytes: ... def readlines(self, sizehint: Optional[int] = ...) -> List[bytes]: ... - if sys.version_info >= (3,): - def __next__(self) -> bytes: ... - else: - def next(self) -> bytes: ... + def __next__(self) -> bytes: ... def __iter__(self: _SRT) -> _SRT: ... def write(self, data: bytes) -> int: ... def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index aedfe5d05bad..9826922ca74f 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -26,10 +26,8 @@ class ThreadPoolExecutor(Executor): initializer: Optional[Callable[..., None]] = ..., initargs: Tuple[Any, ...] = ..., ) -> None: ... - elif sys.version_info >= (3, 6): - def __init__(self, max_workers: Optional[int] = ..., thread_name_prefix: str = ...) -> None: ... else: - def __init__(self, max_workers: Optional[int] = ...) -> None: ... + def __init__(self, max_workers: Optional[int] = ..., thread_name_prefix: str = ...) -> None: ... class _WorkItem(Generic[_S]): future: Future[_S] diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index f4a4e889c646..46e5201a10bb 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath, StrPath, SupportsWrite +from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from typing import ( AbstractSet, Any, @@ -30,7 +30,7 @@ _converters = Dict[str, _converter] _T = TypeVar("_T") if sys.version_info >= (3, 7): - _Path = AnyPath + _Path = StrOrBytesPath else: _Path = StrPath diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 19ef45bed241..3cadf91df90f 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,13 +1,21 @@ import sys from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Type, TypeVar, overload +from typing import ( + IO, + Any, + AsyncContextManager, + AsyncIterator, + Callable, + ContextManager, + Iterator, + Optional, + Type, + TypeVar, + overload, +) from typing_extensions import Protocol -if sys.version_info >= (3, 5): - from typing import AsyncContextManager, AsyncIterator - -if sys.version_info >= (3, 6): - AbstractContextManager = ContextManager +AbstractContextManager = ContextManager if sys.version_info >= (3, 7): AbstractAsyncContextManager = AsyncContextManager @@ -19,22 +27,14 @@ _F = TypeVar("_F", bound=Callable[..., Any]) _ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] _CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) -if sys.version_info >= (3, 2): - class _GeneratorContextManager(ContextManager[_T_co]): - def __call__(self, func: _F) -> _F: ... - def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]: ... +class _GeneratorContextManager(ContextManager[_T_co]): + def __call__(self, func: _F) -> _F: ... -else: - class GeneratorContextManager(ContextManager[_T_co]): - def __call__(self, func: _F) -> _F: ... - def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... +def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]: ... if sys.version_info >= (3, 7): def asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]: ... -if sys.version_info < (3,): - def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... - class _SupportsClose(Protocol): def close(self) -> None: ... @@ -50,37 +50,37 @@ if sys.version_info >= (3, 10): class aclosing(AsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... -if sys.version_info >= (3, 4): - class suppress(ContextManager[None]): - def __init__(self, *exceptions: Type[BaseException]) -> None: ... - def __exit__( - self, exctype: Optional[Type[BaseException]], excinst: Optional[BaseException], exctb: Optional[TracebackType] - ) -> bool: ... - class redirect_stdout(ContextManager[_T_io]): - def __init__(self, new_target: _T_io) -> None: ... - -if sys.version_info >= (3, 5): - class redirect_stderr(ContextManager[_T_io]): - def __init__(self, new_target: _T_io) -> None: ... - -if sys.version_info >= (3,): - class ContextDecorator: - def __call__(self, func: _F) -> _F: ... - _U = TypeVar("_U", bound=ExitStack) - class ExitStack(ContextManager[ExitStack]): - def __init__(self) -> None: ... - def enter_context(self, cm: ContextManager[_T]) -> _T: ... - def push(self, exit: _CM_EF) -> _CM_EF: ... - def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... - def pop_all(self: _U) -> _U: ... - def close(self) -> None: ... - def __enter__(self: _U) -> _U: ... - def __exit__( - self, - __exc_type: Optional[Type[BaseException]], - __exc_value: Optional[BaseException], - __traceback: Optional[TracebackType], - ) -> bool: ... +class suppress(ContextManager[None]): + def __init__(self, *exceptions: Type[BaseException]) -> None: ... + def __exit__( + self, exctype: Optional[Type[BaseException]], excinst: Optional[BaseException], exctb: Optional[TracebackType] + ) -> bool: ... + +class redirect_stdout(ContextManager[_T_io]): + def __init__(self, new_target: _T_io) -> None: ... + +class redirect_stderr(ContextManager[_T_io]): + def __init__(self, new_target: _T_io) -> None: ... + +class ContextDecorator: + def __call__(self, func: _F) -> _F: ... + +_U = TypeVar("_U", bound=ExitStack) + +class ExitStack(ContextManager[ExitStack]): + def __init__(self) -> None: ... + def enter_context(self, cm: ContextManager[_T]) -> _T: ... + def push(self, exit: _CM_EF) -> _CM_EF: ... + def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... + def pop_all(self: _U) -> _U: ... + def close(self) -> None: ... + def __enter__(self: _U) -> _U: ... + def __exit__( + self, + __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> bool: ... if sys.version_info >= (3, 7): from typing import Awaitable diff --git a/mypy/typeshed/stdlib/crypt.pyi b/mypy/typeshed/stdlib/crypt.pyi index 18893721a11f..d8db0ffb4cea 100644 --- a/mypy/typeshed/stdlib/crypt.pyi +++ b/mypy/typeshed/stdlib/crypt.pyi @@ -1,22 +1,21 @@ import sys from typing import List, Optional, Union -if sys.version_info >= (3, 3): - class _Method: ... - METHOD_CRYPT: _Method - METHOD_MD5: _Method - METHOD_SHA256: _Method - METHOD_SHA512: _Method - if sys.version_info >= (3, 7): - METHOD_BLOWFISH: _Method +class _Method: ... - methods: List[_Method] +METHOD_CRYPT: _Method +METHOD_MD5: _Method +METHOD_SHA256: _Method +METHOD_SHA512: _Method +if sys.version_info >= (3, 7): + METHOD_BLOWFISH: _Method - if sys.version_info >= (3, 7): - def mksalt(method: Optional[_Method] = ..., *, rounds: Optional[int] = ...) -> str: ... - else: - def mksalt(method: Optional[_Method] = ...) -> str: ... - def crypt(word: str, salt: Optional[Union[str, _Method]] = ...) -> str: ... +methods: List[_Method] + +if sys.version_info >= (3, 7): + def mksalt(method: Optional[_Method] = ..., *, rounds: Optional[int] = ...) -> str: ... else: - def crypt(word: str, salt: str) -> str: ... + def mksalt(method: Optional[_Method] = ...) -> str: ... + +def crypt(word: str, salt: Optional[Union[str, _Method]] = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index db48e9e6c78a..25a9e4aeb6c0 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -17,9 +17,9 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) -from typing import Any, Generic, Iterable, Iterator, List, Mapping, Optional, Sequence, Text, Type, TypeVar, overload +from typing import Any, Generic, Iterable, Iterator, List, Mapping, Optional, Sequence, Type, TypeVar, overload -if sys.version_info >= (3, 8) or sys.version_info < (3, 6): +if sys.version_info >= (3, 8): from typing import Dict as _DictReadMapping else: from collections import OrderedDict as _DictReadMapping @@ -37,14 +37,13 @@ class excel(Dialect): class excel_tab(excel): delimiter: str -if sys.version_info >= (3,): - class unix_dialect(Dialect): - delimiter: str - quotechar: str - doublequote: bool - skipinitialspace: bool - lineterminator: str - quoting: int +class unix_dialect(Dialect): + delimiter: str + quotechar: str + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: int class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): fieldnames: Optional[Sequence[_T]] @@ -56,7 +55,7 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): @overload def __init__( self, - f: Iterable[Text], + f: Iterable[str], fieldnames: Sequence[_T], restkey: Optional[str] = ..., restval: Optional[str] = ..., @@ -67,7 +66,7 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): @overload def __init__( self: DictReader[str], - f: Iterable[Text], + f: Iterable[str], fieldnames: Optional[Sequence[str]] = ..., restkey: Optional[str] = ..., restval: Optional[str] = ..., @@ -76,10 +75,7 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): **kwds: Any, ) -> None: ... def __iter__(self) -> DictReader[_T]: ... - if sys.version_info >= (3,): - def __next__(self) -> _DictReadMapping[_T, str]: ... - else: - def next(self) -> _DictReadMapping[_T, str]: ... + def __next__(self) -> _DictReadMapping[_T, str]: ... class DictWriter(Generic[_T]): fieldnames: Sequence[_T] diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 299672ad0629..131bb4d7e1c0 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -11,7 +11,6 @@ from typing import ( Mapping, Optional, Sequence, - Text, Tuple, Type, TypeVar, @@ -166,7 +165,7 @@ def create_string_buffer(init: _UnionT[int, bytes], size: Optional[int] = ...) - c_buffer = create_string_buffer -def create_unicode_buffer(init: _UnionT[int, Text], size: Optional[int] = ...) -> Array[c_wchar]: ... +def create_unicode_buffer(init: _UnionT[int, str], size: Optional[int] = ...) -> Array[c_wchar]: ... if sys.platform == "win32": def DllCanUnloadNow() -> int: ... @@ -200,10 +199,6 @@ class pointer(Generic[_CT], _PointerLike, _CData): def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... def resize(obj: _CData, size: int) -> None: ... - -if sys.version_info < (3,): - def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... - def set_errno(value: int) -> int: ... if sys.platform == "win32": @@ -252,10 +247,10 @@ class c_ulong(_SimpleCData[int]): ... class c_ulonglong(_SimpleCData[int]): ... class c_ushort(_SimpleCData[int]): ... class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... -class c_wchar(_SimpleCData[Text]): ... +class c_wchar(_SimpleCData[str]): ... -class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): - def __init__(self, value: Optional[_UnionT[int, Text]] = ...) -> None: ... +class c_wchar_p(_PointerLike, _SimpleCData[Optional[str]]): + def __init__(self, value: Optional[_UnionT[int, str]] = ...) -> None: ... class c_bool(_SimpleCData[bool]): def __init__(self, value: bool = ...) -> None: ... @@ -289,7 +284,7 @@ class Array(Generic[_CT], _CData): _length_: ClassVar[int] = ... _type_: ClassVar[Type[_CT]] = ... raw: bytes = ... # Note: only available if _CT == c_char - value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise + value: Any = ... # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT # here, because of a special feature of ctypes. diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 1e619516f1cc..8d4ab1b1efba 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -10,6 +10,10 @@ class _MISSING_TYPE: ... MISSING: _MISSING_TYPE +if sys.version_info >= (3, 10): + class _KW_ONLY_TYPE: ... + KW_ONLY: _KW_ONLY_TYPE + @overload def asdict(obj: Any) -> Dict[str, Any]: ... @overload @@ -20,7 +24,6 @@ def astuple(obj: Any) -> Tuple[Any, ...]: ... def astuple(obj: Any, *, tuple_factory: Callable[[List[Any]], _T]) -> _T: ... if sys.version_info >= (3, 10): - # Added match_args @overload def dataclass(__cls: Type[_T]) -> Type[_T]: ... @overload @@ -35,6 +38,8 @@ if sys.version_info >= (3, 10): unsafe_hash: bool = ..., frozen: bool = ..., match_args: bool = ..., + kw_only: bool = ..., + slots: bool = ..., ) -> Callable[[Type[_T]], Type[_T]]: ... elif sys.version_info >= (3, 8): @@ -68,50 +73,100 @@ class Field(Generic[_T]): init: bool compare: bool metadata: Mapping[str, Any] - def __init__( - self, - default: _T, - default_factory: Callable[[], _T], - init: bool, - repr: bool, - hash: Optional[bool], - compare: bool, - metadata: Mapping[str, Any], - ) -> None: ... + if sys.version_info >= (3, 10): + kw_only: bool + def __init__( + self, + default: _T, + default_factory: Callable[[], _T], + init: bool, + repr: bool, + hash: Optional[bool], + compare: bool, + metadata: Mapping[str, Any], + kw_only: bool, + ) -> None: ... + else: + def __init__( + self, + default: _T, + default_factory: Callable[[], _T], + init: bool, + repr: bool, + hash: Optional[bool], + compare: bool, + metadata: Mapping[str, Any], + ) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... # NOTE: Actual return type is 'Field[_T]', but we want to help type checkers # to understand the magic that happens at runtime. -@overload # `default` and `default_factory` are optional and mutually exclusive. -def field( - *, - default: _T, - init: bool = ..., - repr: bool = ..., - hash: Optional[bool] = ..., - compare: bool = ..., - metadata: Optional[Mapping[str, Any]] = ..., -) -> _T: ... -@overload -def field( - *, - default_factory: Callable[[], _T], - init: bool = ..., - repr: bool = ..., - hash: Optional[bool] = ..., - compare: bool = ..., - metadata: Optional[Mapping[str, Any]] = ..., -) -> _T: ... -@overload -def field( - *, - init: bool = ..., - repr: bool = ..., - hash: Optional[bool] = ..., - compare: bool = ..., - metadata: Optional[Mapping[str, Any]] = ..., -) -> Any: ... +if sys.version_info >= (3, 10): + @overload # `default` and `default_factory` are optional and mutually exclusive. + def field( + *, + default: _T, + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + kw_only: bool = ..., + ) -> _T: ... + @overload + def field( + *, + default_factory: Callable[[], _T], + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + kw_only: bool = ..., + ) -> _T: ... + @overload + def field( + *, + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + kw_only: bool = ..., + ) -> Any: ... + +else: + @overload # `default` and `default_factory` are optional and mutually exclusive. + def field( + *, + default: _T, + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + ) -> _T: ... + @overload + def field( + *, + default_factory: Callable[[], _T], + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + ) -> _T: ... + @overload + def field( + *, + init: bool = ..., + repr: bool = ..., + hash: Optional[bool] = ..., + compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ..., + ) -> Any: ... + def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... def is_dataclass(obj: Any) -> bool: ... @@ -126,17 +181,36 @@ class InitVar(Generic[_T]): @overload def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... -def make_dataclass( - cls_name: str, - fields: Iterable[Union[str, Tuple[str, type], Tuple[str, type, Field[Any]]]], - *, - bases: Tuple[type, ...] = ..., - namespace: Optional[Dict[str, Any]] = ..., - init: bool = ..., - repr: bool = ..., - eq: bool = ..., - order: bool = ..., - unsafe_hash: bool = ..., - frozen: bool = ..., -) -> type: ... +if sys.version_info >= (3, 10): + def make_dataclass( + cls_name: str, + fields: Iterable[Union[str, Tuple[str, type], Tuple[str, type, Field[Any]]]], + *, + bases: Tuple[type, ...] = ..., + namespace: Optional[Dict[str, Any]] = ..., + init: bool = ..., + repr: bool = ..., + eq: bool = ..., + order: bool = ..., + unsafe_hash: bool = ..., + frozen: bool = ..., + match_args: bool = ..., + slots: bool = ..., + ) -> type: ... + +else: + def make_dataclass( + cls_name: str, + fields: Iterable[Union[str, Tuple[str, type], Tuple[str, type, Field[Any]]]], + *, + bases: Tuple[type, ...] = ..., + namespace: Optional[Dict[str, Any]] = ..., + init: bool = ..., + repr: bool = ..., + eq: bool = ..., + order: bool = ..., + unsafe_hash: bool = ..., + frozen: bool = ..., + ) -> type: ... + def replace(__obj: _T, **changes: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 4692f590b5b3..e82b26923571 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,14 +1,9 @@ import sys from time import struct_time -from typing import AnyStr, ClassVar, NamedTuple, Optional, SupportsAbs, Tuple, Type, TypeVar, Union, overload +from typing import ClassVar, NamedTuple, Optional, SupportsAbs, Tuple, Type, TypeVar, overload _S = TypeVar("_S") -if sys.version_info >= (3,): - _Text = str -else: - _Text = Union[str, unicode] - MINYEAR: int MAXYEAR: int @@ -18,13 +13,15 @@ class tzinfo: def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ... def fromutc(self, dt: datetime) -> datetime: ... -if sys.version_info >= (3, 2): - class timezone(tzinfo): - utc: ClassVar[timezone] - min: ClassVar[timezone] - max: ClassVar[timezone] - def __init__(self, offset: timedelta, name: str = ...) -> None: ... - def __hash__(self) -> int: ... +# Alias required to avoid name conflicts with date(time).tzinfo. +_tzinfo = tzinfo + +class timezone(tzinfo): + utc: ClassVar[timezone] + min: ClassVar[timezone] + max: ClassVar[timezone] + def __init__(self, offset: timedelta, name: str = ...) -> None: ... + def __hash__(self) -> int: ... if sys.version_info >= (3, 9): class _IsoCalendarDate(NamedTuple): @@ -32,8 +29,6 @@ if sys.version_info >= (3, 9): week: int weekday: int -_tzinfo = tzinfo - class date: min: ClassVar[date] max: ClassVar[date] @@ -58,11 +53,8 @@ class date: @property def day(self) -> int: ... def ctime(self) -> str: ... - def strftime(self, fmt: _Text) -> str: ... - if sys.version_info >= (3,): - def __format__(self, fmt: str) -> str: ... - else: - def __format__(self, fmt: AnyStr) -> AnyStr: ... + def strftime(self, fmt: str) -> str: ... + def __format__(self, fmt: str) -> str: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... @@ -93,22 +85,16 @@ class time: min: ClassVar[time] max: ClassVar[time] resolution: ClassVar[timedelta] - - if sys.version_info >= (3, 6): - def __init__( - self, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - *, - fold: int = ..., - ) -> None: ... - else: - def __init__( - self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ... - ) -> None: ... + def __new__( + cls: Type[_S], + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + *, + fold: int = ..., + ) -> _S: ... @property def hour(self) -> int: ... @property @@ -119,44 +105,32 @@ class time: def microsecond(self) -> int: ... @property def tzinfo(self) -> Optional[_tzinfo]: ... - if sys.version_info >= (3, 6): - @property - def fold(self) -> int: ... + @property + def fold(self) -> int: ... def __le__(self, other: time) -> bool: ... def __lt__(self, other: time) -> bool: ... def __ge__(self, other: time) -> bool: ... def __gt__(self, other: time) -> bool: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 6): - def isoformat(self, timespec: str = ...) -> str: ... - else: - def isoformat(self) -> str: ... + def isoformat(self, timespec: str = ...) -> str: ... if sys.version_info >= (3, 7): @classmethod def fromisoformat(cls: Type[_S], time_string: str) -> _S: ... - def strftime(self, fmt: _Text) -> str: ... - if sys.version_info >= (3,): - def __format__(self, fmt: str) -> str: ... - else: - def __format__(self, fmt: AnyStr) -> AnyStr: ... + def strftime(self, fmt: str) -> str: ... + def __format__(self, fmt: str) -> str: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... - if sys.version_info >= (3, 6): - def replace( - self, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - *, - fold: int = ..., - ) -> time: ... - else: - def replace( - self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ... - ) -> time: ... + def replace( + self, + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + *, + fold: int = ..., + ) -> time: ... _date = date _time = time @@ -165,31 +139,16 @@ class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] max: ClassVar[timedelta] resolution: ClassVar[timedelta] - - if sys.version_info >= (3, 6): - def __init__( - self, - days: float = ..., - seconds: float = ..., - microseconds: float = ..., - milliseconds: float = ..., - minutes: float = ..., - hours: float = ..., - weeks: float = ..., - *, - fold: int = ..., - ) -> None: ... - else: - def __init__( - self, - days: float = ..., - seconds: float = ..., - microseconds: float = ..., - milliseconds: float = ..., - minutes: float = ..., - hours: float = ..., - weeks: float = ..., - ) -> None: ... + def __new__( + cls: Type[_S], + days: float = ..., + seconds: float = ..., + microseconds: float = ..., + milliseconds: float = ..., + minutes: float = ..., + hours: float = ..., + weeks: float = ..., + ) -> _S: ... @property def days(self) -> int: ... @property @@ -210,18 +169,12 @@ class timedelta(SupportsAbs[timedelta]): def __floordiv__(self, other: timedelta) -> int: ... @overload def __floordiv__(self, other: int) -> timedelta: ... - if sys.version_info >= (3,): - @overload - def __truediv__(self, other: timedelta) -> float: ... - @overload - def __truediv__(self, other: float) -> timedelta: ... - def __mod__(self, other: timedelta) -> timedelta: ... - def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... - else: - @overload - def __div__(self, other: timedelta) -> float: ... - @overload - def __div__(self, other: float) -> timedelta: ... + @overload + def __truediv__(self, other: timedelta) -> float: ... + @overload + def __truediv__(self, other: float) -> timedelta: ... + def __mod__(self, other: timedelta) -> timedelta: ... + def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... def __le__(self, other: timedelta) -> bool: ... def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... @@ -232,33 +185,19 @@ class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] - - if sys.version_info >= (3, 6): - def __new__( - cls: Type[_S], - year: int, - month: int, - day: int, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - *, - fold: int = ..., - ) -> _S: ... - else: - def __new__( - cls: Type[_S], - year: int, - month: int, - day: int, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - ) -> _S: ... + def __new__( + cls: Type[_S], + year: int, + month: int, + day: int, + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + *, + fold: int = ..., + ) -> _S: ... @property def year(self) -> int: ... @property @@ -275,9 +214,8 @@ class datetime(date): def microsecond(self) -> int: ... @property def tzinfo(self) -> Optional[_tzinfo]: ... - if sys.version_info >= (3, 6): - @property - def fold(self) -> int: ... + @property + def fold(self) -> int: ... @classmethod def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... @classmethod @@ -298,67 +236,41 @@ class datetime(date): def now(cls, tz: _tzinfo) -> datetime: ... @classmethod def utcnow(cls: Type[_S]) -> _S: ... - if sys.version_info >= (3, 6): - @classmethod - def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... - else: - @classmethod - def combine(cls, date: _date, time: _time) -> datetime: ... + @classmethod + def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... if sys.version_info >= (3, 7): @classmethod def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... - def strftime(self, fmt: _Text) -> str: ... - if sys.version_info >= (3,): - def __format__(self, fmt: str) -> str: ... - else: - def __format__(self, fmt: AnyStr) -> AnyStr: ... + def strftime(self, fmt: str) -> str: ... + def __format__(self, fmt: str) -> str: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... - if sys.version_info >= (3, 3): - def timestamp(self) -> float: ... + def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... - if sys.version_info >= (3, 6): - def replace( - self, - year: int = ..., - month: int = ..., - day: int = ..., - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - *, - fold: int = ..., - ) -> datetime: ... - else: - def replace( - self, - year: int = ..., - month: int = ..., - day: int = ..., - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: Optional[_tzinfo] = ..., - ) -> datetime: ... + def replace( + self, + year: int = ..., + month: int = ..., + day: int = ..., + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., + *, + fold: int = ..., + ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... - elif sys.version_info >= (3, 3): - def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: - def astimezone(self, tz: _tzinfo) -> datetime: ... + def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... def ctime(self) -> str: ... - if sys.version_info >= (3, 6): - def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... - else: - def isoformat(self, sep: str = ...) -> str: ... + def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod - def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... + def strptime(cls, date_string: str, format: str) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index edce1ea02861..f2d64446a6a2 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -4,6 +4,72 @@ from typing_extensions import Literal _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] +_TFlags = Literal[ + "r", + "w", + "c", + "n", + "rf", + "wf", + "cf", + "nf", + "rs", + "ws", + "cs", + "ns", + "ru", + "wu", + "cu", + "nu", + "rfs", + "wfs", + "cfs", + "nfs", + "rfu", + "wfu", + "cfu", + "nfu", + "rsf", + "wsf", + "csf", + "nsf", + "rsu", + "wsu", + "csu", + "nsu", + "ruf", + "wuf", + "cuf", + "nuf", + "rus", + "wus", + "cus", + "nus", + "rfsu", + "wfsu", + "cfsu", + "nfsu", + "rfus", + "wfus", + "cfus", + "nfus", + "rsfu", + "wsfu", + "csfu", + "nsfu", + "rsuf", + "wsuf", + "csuf", + "nsuf", + "rufs", + "wufs", + "cufs", + "nufs", + "rusf", + "wusf", + "cusf", + "nusf", +] class _Database(MutableMapping[_KeyType, bytes]): def close(self) -> None: ... @@ -23,4 +89,4 @@ class _error(Exception): ... error = Tuple[Type[_error], Type[OSError]] def whichdb(filename: str) -> str: ... -def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... +def open(file: str, flag: _TFlags = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 8f13a2988488..20033ded6373 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -17,6 +17,7 @@ class _gdbm: def __getitem__(self, item: _KeyType) -> bytes: ... def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... def __delitem__(self, key: _KeyType) -> None: ... + def __contains__(self, key: _KeyType) -> bool: ... def __len__(self) -> int: ... def __enter__(self) -> _gdbm: ... def __exit__( diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index c3a671d4ba5f..f63243853133 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -1,14 +1,10 @@ import numbers -import sys from types import TracebackType -from typing import Any, Container, Dict, List, NamedTuple, Optional, Sequence, Text, Tuple, Type, TypeVar, Union, overload +from typing import Any, Container, Dict, List, NamedTuple, Optional, Sequence, Tuple, Type, TypeVar, Union, overload _Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] -if sys.version_info >= (3,): - _ComparableNum = Union[Decimal, float, numbers.Rational] -else: - _ComparableNum = Union[Decimal, float] +_DecimalNew = Union[Decimal, float, str, Tuple[int, Sequence[int], int]] +_ComparableNum = Union[Decimal, float, numbers.Rational] _DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): @@ -25,17 +21,13 @@ ROUND_UP: str ROUND_HALF_DOWN: str ROUND_05UP: str -if sys.version_info >= (3,): - HAVE_THREADS: bool - MAX_EMAX: int - MAX_PREC: int - MIN_EMIN: int - MIN_ETINY: int - -class DecimalException(ArithmeticError): - if sys.version_info < (3,): - def handle(self, context: Context, *args: Any) -> Optional[Decimal]: ... +HAVE_THREADS: bool +MAX_EMAX: int +MAX_PREC: int +MIN_EMIN: int +MIN_ETINY: int +class DecimalException(ArithmeticError): ... class Clamped(DecimalException): ... class InvalidOperation(DecimalException): ... class ConversionSyntax(InvalidOperation): ... @@ -48,9 +40,7 @@ class Rounded(DecimalException): ... class Subnormal(DecimalException): ... class Overflow(Inexact, Rounded): ... class Underflow(Inexact, Rounded, Subnormal): ... - -if sys.version_info >= (3,): - class FloatOperation(DecimalException, TypeError): ... +class FloatOperation(DecimalException, TypeError): ... def setcontext(__context: Context) -> None: ... def getcontext() -> Context: ... @@ -60,69 +50,36 @@ class Decimal(object): def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Optional[Context] = ...) -> _DecimalT: ... @classmethod def from_float(cls, __f: float) -> Decimal: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - def __div__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rdiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __ne__(self, other: object, context: Optional[Context] = ...) -> bool: ... + def __bool__(self) -> bool: ... def compare(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def __hash__(self) -> int: ... def as_tuple(self) -> DecimalTuple: ... - if sys.version_info >= (3, 6): - def as_integer_ratio(self) -> Tuple[int, int]: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... def to_eng_string(self, context: Optional[Context] = ...) -> str: ... - if sys.version_info >= (3,): - def __abs__(self) -> Decimal: ... - def __add__(self, other: _Decimal) -> Decimal: ... - def __divmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ... - def __eq__(self, other: object) -> bool: ... - def __floordiv__(self, other: _Decimal) -> Decimal: ... - def __ge__(self, other: _ComparableNum) -> bool: ... - def __gt__(self, other: _ComparableNum) -> bool: ... - def __le__(self, other: _ComparableNum) -> bool: ... - def __lt__(self, other: _ComparableNum) -> bool: ... - def __mod__(self, other: _Decimal) -> Decimal: ... - def __mul__(self, other: _Decimal) -> Decimal: ... - def __neg__(self) -> Decimal: ... - def __pos__(self) -> Decimal: ... - def __pow__(self, other: _Decimal, modulo: Optional[_Decimal] = ...) -> Decimal: ... - def __radd__(self, other: _Decimal) -> Decimal: ... - def __rdivmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, other: _Decimal) -> Decimal: ... - def __rmod__(self, other: _Decimal) -> Decimal: ... - def __rmul__(self, other: _Decimal) -> Decimal: ... - def __rsub__(self, other: _Decimal) -> Decimal: ... - def __rtruediv__(self, other: _Decimal) -> Decimal: ... - def __str__(self) -> str: ... - def __sub__(self, other: _Decimal) -> Decimal: ... - def __truediv__(self, other: _Decimal) -> Decimal: ... - else: - def __abs__(self, round: bool = ..., context: Optional[Context] = ...) -> Decimal: ... - def __add__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __divmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... - def __eq__(self, other: object, context: Optional[Context] = ...) -> bool: ... - def __floordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __ge__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... - def __gt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... - def __le__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... - def __lt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... - def __mod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __mul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __neg__(self, context: Optional[Context] = ...) -> Decimal: ... - def __pos__(self, context: Optional[Context] = ...) -> Decimal: ... - def __pow__(self, other: _Decimal, modulo: Optional[_Decimal] = ..., context: Optional[Context] = ...) -> Decimal: ... - def __radd__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rdivmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rmul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rsub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __rtruediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __str__(self, eng: bool = ..., context: Optional[Context] = ...) -> str: ... - def __sub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def __truediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __abs__(self) -> Decimal: ... + def __add__(self, other: _Decimal) -> Decimal: ... + def __divmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ... + def __eq__(self, other: object) -> bool: ... + def __floordiv__(self, other: _Decimal) -> Decimal: ... + def __ge__(self, other: _ComparableNum) -> bool: ... + def __gt__(self, other: _ComparableNum) -> bool: ... + def __le__(self, other: _ComparableNum) -> bool: ... + def __lt__(self, other: _ComparableNum) -> bool: ... + def __mod__(self, other: _Decimal) -> Decimal: ... + def __mul__(self, other: _Decimal) -> Decimal: ... + def __neg__(self) -> Decimal: ... + def __pos__(self) -> Decimal: ... + def __pow__(self, other: _Decimal, modulo: Optional[_Decimal] = ...) -> Decimal: ... + def __radd__(self, other: _Decimal) -> Decimal: ... + def __rdivmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, other: _Decimal) -> Decimal: ... + def __rmod__(self, other: _Decimal) -> Decimal: ... + def __rmul__(self, other: _Decimal) -> Decimal: ... + def __rsub__(self, other: _Decimal) -> Decimal: ... + def __rtruediv__(self, other: _Decimal) -> Decimal: ... + def __str__(self) -> str: ... + def __sub__(self, other: _Decimal) -> Decimal: ... + def __truediv__(self, other: _Decimal) -> Decimal: ... def remainder_near(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -133,26 +90,17 @@ class Decimal(object): def imag(self) -> Decimal: ... def conjugate(self) -> Decimal: ... def __complex__(self) -> complex: ... - if sys.version_info >= (3,): - @overload - def __round__(self) -> int: ... - @overload - def __round__(self, ndigits: int) -> Decimal: ... - def __floor__(self) -> int: ... - def __ceil__(self) -> int: ... - else: - def __long__(self) -> long: ... + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: int) -> Decimal: ... + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... def fma(self, other: _Decimal, third: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def __rpow__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def normalize(self, context: Optional[Context] = ...) -> Decimal: ... - if sys.version_info >= (3,): - def quantize(self, exp: _Decimal, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... - def same_quantum(self, other: _Decimal, context: Optional[Context] = ...) -> bool: ... - else: - def quantize( - self, exp: _Decimal, rounding: Optional[str] = ..., context: Optional[Context] = ..., watchexp: bool = ... - ) -> Decimal: ... - def same_quantum(self, other: _Decimal) -> bool: ... + def quantize(self, exp: _Decimal, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def same_quantum(self, other: _Decimal, context: Optional[Context] = ...) -> bool: ... def to_integral_exact(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... def to_integral_value(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... def to_integral(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... @@ -160,23 +108,13 @@ class Decimal(object): def max(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def min(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def adjusted(self) -> int: ... - if sys.version_info >= (3,): - def canonical(self) -> Decimal: ... - else: - def canonical(self, context: Optional[Context] = ...) -> Decimal: ... + def canonical(self) -> Decimal: ... def compare_signal(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - if sys.version_info >= (3,): - def compare_total(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - def compare_total_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - else: - def compare_total(self, other: _Decimal) -> Decimal: ... - def compare_total_mag(self, other: _Decimal) -> Decimal: ... + def compare_total(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def compare_total_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def copy_abs(self) -> Decimal: ... def copy_negate(self) -> Decimal: ... - if sys.version_info >= (3,): - def copy_sign(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... - else: - def copy_sign(self, other: _Decimal) -> Decimal: ... + def copy_sign(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... def exp(self, context: Optional[Context] = ...) -> Decimal: ... def is_canonical(self) -> bool: ... def is_finite(self) -> bool: ... @@ -225,46 +163,27 @@ class Context(object): Emin: int Emax: int capitals: int - if sys.version_info >= (3,): - clamp: int - else: - _clamp: int + clamp: int traps: Dict[_TrapType, bool] flags: Dict[_TrapType, bool] - if sys.version_info >= (3,): - def __init__( - self, - prec: Optional[int] = ..., - rounding: Optional[str] = ..., - Emin: Optional[int] = ..., - Emax: Optional[int] = ..., - capitals: Optional[int] = ..., - clamp: Optional[int] = ..., - flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., - traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., - _ignored_flags: Optional[List[_TrapType]] = ..., - ) -> None: ... - else: - def __init__( - self, - prec: Optional[int] = ..., - rounding: Optional[str] = ..., - traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., - flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., - Emin: Optional[int] = ..., - Emax: Optional[int] = ..., - capitals: Optional[int] = ..., - _clamp: Optional[int] = ..., - _ignored_flags: Optional[List[_TrapType]] = ..., - ) -> None: ... - if sys.version_info >= (3,): - # __setattr__() only allows to set a specific set of attributes, - # already defined above. - def __delattr__(self, name: str) -> None: ... - def __reduce__(self) -> Tuple[Type[Context], Tuple[Any, ...]]: ... + def __init__( + self, + prec: Optional[int] = ..., + rounding: Optional[str] = ..., + Emin: Optional[int] = ..., + Emax: Optional[int] = ..., + capitals: Optional[int] = ..., + clamp: Optional[int] = ..., + flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + _ignored_flags: Optional[List[_TrapType]] = ..., + ) -> None: ... + # __setattr__() only allows to set a specific set of attributes, + # already defined above. + def __delattr__(self, name: str) -> None: ... + def __reduce__(self) -> Tuple[Type[Context], Tuple[Any, ...]]: ... def clear_flags(self) -> None: ... - if sys.version_info >= (3,): - def clear_traps(self) -> None: ... + def clear_traps(self) -> None: ... def copy(self) -> Context: ... def __copy__(self) -> Context: ... __hash__: Any = ... diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 572972ccda9e..9dd98d331f3c 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -10,7 +10,6 @@ from typing import ( NamedTuple, Optional, Sequence, - Text, Tuple, TypeVar, Union, @@ -21,14 +20,7 @@ if sys.version_info >= (3, 9): from types import GenericAlias _T = TypeVar("_T") - -if sys.version_info >= (3,): - _StrType = Text -else: - # Aliases can't point to type vars, so we need to redeclare AnyStr - _StrType = TypeVar("_StrType", Text, bytes) - -_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] +_JunkCallback = Union[Callable[[str], bool], Callable[[str], bool]] class Match(NamedTuple): a: int @@ -69,33 +61,33 @@ def get_close_matches( class Differ: def __init__(self, linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ...) -> None: ... - def compare(self, a: Sequence[_StrType], b: Sequence[_StrType]) -> Iterator[_StrType]: ... + def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ... -def IS_LINE_JUNK(line: _StrType, pat: Any = ...) -> bool: ... # pat is undocumented -def IS_CHARACTER_JUNK(ch: _StrType, ws: _StrType = ...) -> bool: ... # ws is undocumented +def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: ... # pat is undocumented +def IS_CHARACTER_JUNK(ch: str, ws: str = ...) -> bool: ... # ws is undocumented def unified_diff( - a: Sequence[_StrType], - b: Sequence[_StrType], - fromfile: _StrType = ..., - tofile: _StrType = ..., - fromfiledate: _StrType = ..., - tofiledate: _StrType = ..., + a: Sequence[str], + b: Sequence[str], + fromfile: str = ..., + tofile: str = ..., + fromfiledate: str = ..., + tofiledate: str = ..., n: int = ..., - lineterm: _StrType = ..., -) -> Iterator[_StrType]: ... + lineterm: str = ..., +) -> Iterator[str]: ... def context_diff( - a: Sequence[_StrType], - b: Sequence[_StrType], - fromfile: _StrType = ..., - tofile: _StrType = ..., - fromfiledate: _StrType = ..., - tofiledate: _StrType = ..., + a: Sequence[str], + b: Sequence[str], + fromfile: str = ..., + tofile: str = ..., + fromfiledate: str = ..., + tofiledate: str = ..., n: int = ..., - lineterm: _StrType = ..., -) -> Iterator[_StrType]: ... + lineterm: str = ..., +) -> Iterator[str]: ... def ndiff( - a: Sequence[_StrType], b: Sequence[_StrType], linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ... -) -> Iterator[_StrType]: ... + a: Sequence[str], b: Sequence[str], linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ... +) -> Iterator[str]: ... class HtmlDiff(object): def __init__( @@ -105,49 +97,36 @@ class HtmlDiff(object): linejunk: Optional[_JunkCallback] = ..., charjunk: Optional[_JunkCallback] = ..., ) -> None: ... - if sys.version_info >= (3, 5): - def make_file( - self, - fromlines: Sequence[_StrType], - tolines: Sequence[_StrType], - fromdesc: _StrType = ..., - todesc: _StrType = ..., - context: bool = ..., - numlines: int = ..., - *, - charset: str = ..., - ) -> _StrType: ... - else: - def make_file( - self, - fromlines: Sequence[_StrType], - tolines: Sequence[_StrType], - fromdesc: _StrType = ..., - todesc: _StrType = ..., - context: bool = ..., - numlines: int = ..., - ) -> _StrType: ... + def make_file( + self, + fromlines: Sequence[str], + tolines: Sequence[str], + fromdesc: str = ..., + todesc: str = ..., + context: bool = ..., + numlines: int = ..., + *, + charset: str = ..., + ) -> str: ... def make_table( self, - fromlines: Sequence[_StrType], - tolines: Sequence[_StrType], - fromdesc: _StrType = ..., - todesc: _StrType = ..., + fromlines: Sequence[str], + tolines: Sequence[str], + fromdesc: str = ..., + todesc: str = ..., context: bool = ..., numlines: int = ..., - ) -> _StrType: ... + ) -> str: ... -def restore(delta: Iterable[_StrType], which: int) -> Iterator[_StrType]: ... - -if sys.version_info >= (3, 5): - def diff_bytes( - dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]], - a: Sequence[bytes], - b: Sequence[bytes], - fromfile: bytes = ..., - tofile: bytes = ..., - fromfiledate: bytes = ..., - tofiledate: bytes = ..., - n: int = ..., - lineterm: bytes = ..., - ) -> Iterator[bytes]: ... +def restore(delta: Iterable[str], which: int) -> Iterator[str]: ... +def diff_bytes( + dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]], + a: Sequence[bytes], + b: Sequence[bytes], + fromfile: bytes = ..., + tofile: bytes = ..., + fromfiledate: bytes = ..., + tofiledate: bytes = ..., + n: int = ..., + lineterm: bytes = ..., +) -> Iterator[bytes]: ... diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index b52d0ed624f6..60fa845d0206 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -11,73 +11,56 @@ from opcode import ( hasjrel as hasjrel, haslocal as haslocal, hasname as hasname, + hasnargs as hasnargs, opmap as opmap, opname as opname, + stack_effect as stack_effect, ) from typing import IO, Any, Callable, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union -if sys.version_info >= (3, 4): - from opcode import stack_effect as stack_effect - -if sys.version_info >= (3, 6): - from opcode import hasnargs as hasnargs - # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) _have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] _have_code_or_string = Union[_have_code, str, bytes] -if sys.version_info >= (3, 4): - class Instruction(NamedTuple): - opname: str - opcode: int - arg: Optional[int] - argval: Any - argrepr: str - offset: int - starts_line: Optional[int] - is_jump_target: bool - class Bytecode: - codeobj: types.CodeType - first_line: int - def __init__( - self, x: _have_code_or_string, *, first_line: Optional[int] = ..., current_offset: Optional[int] = ... - ) -> None: ... - def __iter__(self) -> Iterator[Instruction]: ... - def __repr__(self) -> str: ... - def info(self) -> str: ... - def dis(self) -> str: ... - @classmethod - def from_traceback(cls, tb: types.TracebackType) -> Bytecode: ... +class Instruction(NamedTuple): + opname: str + opcode: int + arg: Optional[int] + argval: Any + argrepr: str + offset: int + starts_line: Optional[int] + is_jump_target: bool + +class Bytecode: + codeobj: types.CodeType + first_line: int + def __init__( + self, x: _have_code_or_string, *, first_line: Optional[int] = ..., current_offset: Optional[int] = ... + ) -> None: ... + def __iter__(self) -> Iterator[Instruction]: ... + def __repr__(self) -> str: ... + def info(self) -> str: ... + def dis(self) -> str: ... + @classmethod + def from_traceback(cls, tb: types.TracebackType) -> Bytecode: ... COMPILER_FLAG_NAMES: Dict[int, str] def findlabels(code: _have_code) -> List[int]: ... def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... - -if sys.version_info >= (3, 0): - def pretty_flags(flags: int) -> str: ... - def code_info(x: _have_code_or_string) -> str: ... +def pretty_flags(flags: int) -> str: ... +def code_info(x: _have_code_or_string) -> str: ... if sys.version_info >= (3, 7): def dis(x: Optional[_have_code_or_string] = ..., *, file: Optional[IO[str]] = ..., depth: Optional[int] = ...) -> None: ... -elif sys.version_info >= (3, 4): - def dis(x: Optional[_have_code_or_string] = ..., *, file: Optional[IO[str]] = ...) -> None: ... - else: - def dis(x: _have_code_or_string = ...) -> None: ... - -if sys.version_info >= (3, 4): - def distb(tb: Optional[types.TracebackType] = ..., *, file: Optional[IO[str]] = ...) -> None: ... - def disassemble(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... - def disco(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... - def show_code(co: _have_code, *, file: Optional[IO[str]] = ...) -> None: ... - def get_instructions(x: _have_code, *, first_line: Optional[int] = ...) -> Iterator[Instruction]: ... + def dis(x: Optional[_have_code_or_string] = ..., *, file: Optional[IO[str]] = ...) -> None: ... -else: - def distb(tb: types.TracebackType = ...) -> None: ... - def disassemble(co: _have_code, lasti: int = ...) -> None: ... - def disco(co: _have_code, lasti: int = ...) -> None: ... - if sys.version_info >= (3, 0): - def show_code(co: _have_code) -> None: ... +def distb(tb: Optional[types.TracebackType] = ..., *, file: Optional[IO[str]] = ...) -> None: ... +def disassemble(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... +def disco(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... +def show_code(co: _have_code, *, file: Optional[IO[str]] = ...) -> None: ... +def get_instructions(x: _have_code, *, first_line: Optional[int] = ...) -> Iterator[Instruction]: ... diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index d3acdafbd5b1..8655371adfaa 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -1,9 +1,9 @@ -from _typeshed import AnyPath, SupportsWrite +from _typeshed import StrOrBytesPath, SupportsWrite from distutils.cmd import Command from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union class DistributionMetadata: - def __init__(self, path: Optional[Union[int, AnyPath]] = ...) -> None: ... + def __init__(self, path: Optional[Union[int, StrOrBytesPath]] = ...) -> None: ... name: Optional[str] version: Optional[str] author: Optional[str] diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index ae84c2c25efc..93dbdae1f44a 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -1,4 +1,3 @@ -import sys import types import unittest from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union @@ -24,8 +23,7 @@ REPORT_UDIFF: int REPORT_CDIFF: int REPORT_NDIFF: int REPORT_ONLY_FIRST_FAILURE: int -if sys.version_info >= (3, 4): - FAIL_FAST: int +FAIL_FAST: int REPORTING_FLAGS: int @@ -189,11 +187,7 @@ class SkipDocTestCase(DocTestCase): def test_skip(self) -> None: ... def shortDescription(self) -> str: ... -if sys.version_info >= (3, 4): - class _DocTestSuite(unittest.TestSuite): ... - -else: - _DocTestSuite = unittest.TestSuite +class _DocTestSuite(unittest.TestSuite): ... def DocTestSuite( module: Union[None, str, types.ModuleType] = ..., diff --git a/mypy/typeshed/stdlib/ensurepip/__init__.pyi b/mypy/typeshed/stdlib/ensurepip/__init__.pyi index a411dbb456d2..2b0d602c37db 100644 --- a/mypy/typeshed/stdlib/ensurepip/__init__.pyi +++ b/mypy/typeshed/stdlib/ensurepip/__init__.pyi @@ -1,25 +1,12 @@ -import sys from typing import Optional def version() -> str: ... - -if sys.version_info >= (3, 0): - def bootstrap( - *, - root: Optional[str] = ..., - upgrade: bool = ..., - user: bool = ..., - altinstall: bool = ..., - default_pip: bool = ..., - verbosity: int = ..., - ) -> None: ... - -else: - def bootstrap( - root: Optional[str] = ..., - upgrade: bool = ..., - user: bool = ..., - altinstall: bool = ..., - default_pip: bool = ..., - verbosity: int = ..., - ) -> None: ... +def bootstrap( + *, + root: Optional[str] = ..., + upgrade: bool = ..., + user: bool = ..., + altinstall: bool = ..., + default_pip: bool = ..., + verbosity: int = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index b05eebac07c9..b3f20eb6b266 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,44 +1,29 @@ import sys -from typing import Any, AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Text, Tuple, Union - -if sys.version_info >= (3, 6): - from os import PathLike +from _typeshed import StrOrBytesPath +from os import PathLike +from typing import Any, AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Tuple, Union if sys.version_info >= (3, 9): from types import GenericAlias DEFAULT_IGNORES: List[str] -if sys.version_info >= (3, 6): - def cmp( - f1: Union[bytes, Text, PathLike[AnyStr]], f2: Union[bytes, Text, PathLike[AnyStr]], shallow: Union[int, bool] = ... - ) -> bool: ... - def cmpfiles( - a: Union[AnyStr, PathLike[AnyStr]], - b: Union[AnyStr, PathLike[AnyStr]], - common: Iterable[AnyStr], - shallow: Union[int, bool] = ..., - ) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... - -else: - def cmp(f1: Union[bytes, Text], f2: Union[bytes, Text], shallow: Union[int, bool] = ...) -> bool: ... - def cmpfiles( - a: AnyStr, b: AnyStr, common: Iterable[AnyStr], shallow: Union[int, bool] = ... - ) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... +def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: Union[int, bool] = ...) -> bool: ... +def cmpfiles( + a: Union[AnyStr, PathLike[AnyStr]], + b: Union[AnyStr, PathLike[AnyStr]], + common: Iterable[AnyStr], + shallow: Union[int, bool] = ..., +) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... class dircmp(Generic[AnyStr]): - if sys.version_info >= (3, 6): - def __init__( - self, - a: Union[AnyStr, PathLike[AnyStr]], - b: Union[AnyStr, PathLike[AnyStr]], - ignore: Optional[Sequence[AnyStr]] = ..., - hide: Optional[Sequence[AnyStr]] = ..., - ) -> None: ... - else: - def __init__( - self, a: AnyStr, b: AnyStr, ignore: Optional[Sequence[AnyStr]] = ..., hide: Optional[Sequence[AnyStr]] = ... - ) -> None: ... + def __init__( + self, + a: Union[AnyStr, PathLike[AnyStr]], + b: Union[AnyStr, PathLike[AnyStr]], + ignore: Optional[Sequence[AnyStr]] = ..., + hide: Optional[Sequence[AnyStr]] = ..., + ) -> None: ... left: AnyStr right: AnyStr hide: Sequence[AnyStr] @@ -69,5 +54,4 @@ class dircmp(Generic[AnyStr]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... -if sys.version_info >= (3,): - def clear_cache() -> None: ... +def clear_cache() -> None: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index fbb602b3bf45..ed07ebecde86 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,25 +1,25 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Optional, Union if sys.version_info >= (3, 8): def input( - files: Union[AnyPath, Iterable[AnyPath], None] = ..., + files: Union[StrOrBytesPath, Iterable[StrOrBytesPath], None] = ..., inplace: bool = ..., backup: str = ..., *, mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., ) -> FileInput[AnyStr]: ... else: def input( - files: Union[AnyPath, Iterable[AnyPath], None] = ..., + files: Union[StrOrBytesPath, Iterable[StrOrBytesPath], None] = ..., inplace: bool = ..., backup: str = ..., bufsize: int = ..., mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., ) -> FileInput[AnyStr]: ... def close() -> None: ... @@ -35,28 +35,27 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): if sys.version_info >= (3, 8): def __init__( self, - files: Union[None, AnyPath, Iterable[AnyPath]] = ..., + files: Union[None, StrOrBytesPath, Iterable[StrOrBytesPath]] = ..., inplace: bool = ..., backup: str = ..., *, mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., ) -> None: ... else: def __init__( self, - files: Union[None, AnyPath, Iterable[AnyPath]] = ..., + files: Union[None, StrOrBytesPath, Iterable[StrOrBytesPath]] = ..., inplace: bool = ..., backup: str = ..., bufsize: int = ..., mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., ) -> None: ... def __del__(self) -> None: ... def close(self) -> None: ... - if sys.version_info >= (3, 2): - def __enter__(self) -> FileInput[AnyStr]: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __enter__(self) -> FileInput[AnyStr]: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __next__(self) -> AnyStr: ... def __getitem__(self, i: int) -> AnyStr: ... @@ -69,10 +68,5 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): def isfirstline(self) -> bool: ... def isstdin(self) -> bool: ... -def hook_compressed(filename: AnyPath, mode: str) -> IO[Any]: ... - -if sys.version_info >= (3, 6): - def hook_encoded(encoding: str, errors: Optional[str] = ...) -> Callable[[AnyPath, str], IO[Any]]: ... - -else: - def hook_encoded(encoding: str) -> Callable[[AnyPath, str], IO[Any]]: ... +def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ... +def hook_encoded(encoding: str, errors: Optional[str] = ...) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 75cfa48a1cf6..a59683c6b39f 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -87,19 +87,6 @@ class Fraction(Rational): def __rtruediv__(self, other: float) -> float: ... @overload def __rtruediv__(self, other: complex) -> complex: ... - if sys.version_info < (3, 0): - @overload - def __div__(self, other: Union[int, Fraction]) -> Fraction: ... - @overload - def __div__(self, other: float) -> float: ... - @overload - def __div__(self, other: complex) -> complex: ... - @overload - def __rdiv__(self, other: Union[int, Fraction]) -> Fraction: ... - @overload - def __rdiv__(self, other: float) -> float: ... - @overload - def __rdiv__(self, other: complex) -> complex: ... @overload def __floordiv__(self, other: Union[int, Fraction]) -> int: ... @overload @@ -138,23 +125,19 @@ class Fraction(Rational): def __neg__(self) -> Fraction: ... def __abs__(self) -> Fraction: ... def __trunc__(self) -> int: ... - if sys.version_info >= (3, 0): - def __floor__(self) -> int: ... - def __ceil__(self) -> int: ... - @overload - def __round__(self, ndigits: None = ...) -> int: ... - @overload - def __round__(self, ndigits: int) -> Fraction: ... + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @overload + def __round__(self, ndigits: int) -> Fraction: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... def __lt__(self, other: _ComparableNum) -> bool: ... def __gt__(self, other: _ComparableNum) -> bool: ... def __le__(self, other: _ComparableNum) -> bool: ... def __ge__(self, other: _ComparableNum) -> bool: ... - if sys.version_info >= (3, 0): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... # Not actually defined within fractions.py, but provides more useful # overrides @property diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index bdb1716549c0..c474da2e3a37 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -1,20 +1,17 @@ -import sys from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, BinaryIO, Callable, Dict, Iterable, Iterator, List, Optional, Text, TextIO, Tuple, Type, TypeVar, Union +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, TypeVar, Union from typing_extensions import Literal _T = TypeVar("_T") -_IntOrStr = Union[int, Text] MSG_OOB: int FTP_PORT: int MAXLINE: int CRLF: str -if sys.version_info >= (3,): - B_CRLF: bytes +B_CRLF: bytes class Error(Exception): ... class error_reply(Error): ... @@ -26,11 +23,7 @@ all_errors: Tuple[Type[Exception], ...] class FTP: debugging: int - - # Note: This is technically the type that's passed in as the host argument. But to make it easier in Python 2 we - # accept Text but return str. host: str - port: int maxline: int sock: Optional[socket] @@ -39,83 +32,71 @@ class FTP: timeout: int af: int lastresp: str - - if sys.version_info >= (3,): - file: Optional[TextIO] - encoding: str - def __enter__(self: _T) -> _T: ... - def __exit__( - self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] - ) -> None: ... - else: - file: Optional[BinaryIO] - - if sys.version_info >= (3, 3): - source_address: Optional[Tuple[str, int]] - def __init__( - self, - host: Text = ..., - user: Text = ..., - passwd: Text = ..., - acct: Text = ..., - timeout: float = ..., - source_address: Optional[Tuple[str, int]] = ..., - ) -> None: ... - def connect( - self, host: Text = ..., port: int = ..., timeout: float = ..., source_address: Optional[Tuple[str, int]] = ... - ) -> str: ... - else: - def __init__( - self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., timeout: float = ... - ) -> None: ... - def connect(self, host: Text = ..., port: int = ..., timeout: float = ...) -> str: ... + file: Optional[TextIO] + encoding: str + def __enter__(self: _T) -> _T: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + source_address: Optional[Tuple[str, int]] + def __init__( + self, + host: str = ..., + user: str = ..., + passwd: str = ..., + acct: str = ..., + timeout: float = ..., + source_address: Optional[Tuple[str, int]] = ..., + ) -> None: ... + def connect( + self, host: str = ..., port: int = ..., timeout: float = ..., source_address: Optional[Tuple[str, int]] = ... + ) -> str: ... def getwelcome(self) -> str: ... def set_debuglevel(self, level: int) -> None: ... def debug(self, level: int) -> None: ... def set_pasv(self, val: Union[bool, int]) -> None: ... - def sanitize(self, s: Text) -> str: ... - def putline(self, line: Text) -> None: ... - def putcmd(self, line: Text) -> None: ... + def sanitize(self, s: str) -> str: ... + def putline(self, line: str) -> None: ... + def putcmd(self, line: str) -> None: ... def getline(self) -> str: ... def getmultiline(self) -> str: ... def getresp(self) -> str: ... def voidresp(self) -> str: ... def abort(self) -> str: ... - def sendcmd(self, cmd: Text) -> str: ... - def voidcmd(self, cmd: Text) -> str: ... - def sendport(self, host: Text, port: int) -> str: ... - def sendeprt(self, host: Text, port: int) -> str: ... + def sendcmd(self, cmd: str) -> str: ... + def voidcmd(self, cmd: str) -> str: ... + def sendport(self, host: str, port: int) -> str: ... + def sendeprt(self, host: str, port: int) -> str: ... def makeport(self) -> socket: ... def makepasv(self) -> Tuple[str, int]: ... - def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ...) -> str: ... + def login(self, user: str = ..., passwd: str = ..., acct: str = ...) -> str: ... # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. - def ntransfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> Tuple[socket, int]: ... - def transfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> socket: ... + def ntransfercmd(self, cmd: str, rest: Optional[Union[int, str]] = ...) -> Tuple[socket, int]: ... + def transfercmd(self, cmd: str, rest: Optional[Union[int, str]] = ...) -> socket: ... def retrbinary( - self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: Optional[_IntOrStr] = ... + self, cmd: str, callback: Callable[[bytes], Any], blocksize: int = ..., rest: Optional[Union[int, str]] = ... ) -> str: ... def storbinary( self, - cmd: Text, + cmd: str, fp: SupportsRead[bytes], blocksize: int = ..., callback: Optional[Callable[[bytes], Any]] = ..., - rest: Optional[_IntOrStr] = ..., + rest: Optional[Union[int, str]] = ..., ) -> str: ... - def retrlines(self, cmd: Text, callback: Optional[Callable[[str], Any]] = ...) -> str: ... - def storlines(self, cmd: Text, fp: SupportsReadline[bytes], callback: Optional[Callable[[bytes], Any]] = ...) -> str: ... - def acct(self, password: Text) -> str: ... - def nlst(self, *args: Text) -> List[str]: ... + def retrlines(self, cmd: str, callback: Optional[Callable[[str], Any]] = ...) -> str: ... + def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Optional[Callable[[bytes], Any]] = ...) -> str: ... + def acct(self, password: str) -> str: ... + def nlst(self, *args: str) -> List[str]: ... # Technically only the last arg can be a Callable but ... def dir(self, *args: Union[str, Callable[[str], None]]) -> None: ... - if sys.version_info >= (3, 3): - def mlsd(self, path: Text = ..., facts: Iterable[str] = ...) -> Iterator[Tuple[str, Dict[str, str]]]: ... - def rename(self, fromname: Text, toname: Text) -> str: ... - def delete(self, filename: Text) -> str: ... - def cwd(self, dirname: Text) -> str: ... - def size(self, filename: Text) -> Optional[int]: ... - def mkd(self, dirname: Text) -> str: ... - def rmd(self, dirname: Text) -> str: ... + def mlsd(self, path: str = ..., facts: Iterable[str] = ...) -> Iterator[Tuple[str, Dict[str, str]]]: ... + def rename(self, fromname: str, toname: str) -> str: ... + def delete(self, filename: str) -> str: ... + def cwd(self, dirname: str) -> str: ... + def size(self, filename: str) -> Optional[int]: ... + def mkd(self, dirname: str) -> str: ... + def rmd(self, dirname: str) -> str: ... def pwd(self) -> str: ... def quit(self) -> str: ... def close(self) -> None: ... @@ -123,10 +104,10 @@ class FTP: class FTP_TLS(FTP): def __init__( self, - host: Text = ..., - user: Text = ..., - passwd: Text = ..., - acct: Text = ..., + host: str = ..., + user: str = ..., + passwd: str = ..., + acct: str = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ..., context: Optional[SSLContext] = ..., @@ -137,20 +118,11 @@ class FTP_TLS(FTP): keyfile: Optional[str] certfile: Optional[str] context: SSLContext - def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ..., secure: bool = ...) -> str: ... + def login(self, user: str = ..., passwd: str = ..., acct: str = ..., secure: bool = ...) -> str: ... def auth(self) -> str: ... def prot_p(self) -> str: ... def prot_c(self) -> str: ... - if sys.version_info >= (3, 3): - def ccc(self) -> str: ... - -if sys.version_info < (3,): - class Netrc: - def __init__(self, filename: Optional[Text] = ...) -> None: ... - def get_hosts(self) -> List[str]: ... - def get_account(self, host: Text) -> Tuple[Optional[str], Optional[str], Optional[str]]: ... - def get_macros(self) -> List[str]: ... - def get_macro(self, macro: Text) -> Tuple[str, ...]: ... + def ccc(self) -> str: ... def parse150(resp: str) -> Optional[int]: ... # undocumented def parse227(resp: str) -> Tuple[str, int]: ... # undocumented diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 28c94ae1676a..7bd6a1ebda58 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -1,6 +1,5 @@ import os -import sys -from _typeshed import AnyPath, BytesPath, StrPath, SupportsLessThanT +from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsLessThanT from typing import List, Sequence, Tuple, Union, overload from typing_extensions import Literal @@ -15,18 +14,16 @@ def commonprefix(m: Sequence[BytesPath]) -> Union[bytes, Literal[""]]: ... def commonprefix(m: Sequence[List[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... @overload def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... -def exists(path: AnyPath) -> bool: ... -def getsize(filename: AnyPath) -> int: ... -def isfile(path: AnyPath) -> bool: ... -def isdir(s: AnyPath) -> bool: ... +def exists(path: StrOrBytesPath) -> bool: ... +def getsize(filename: StrOrBytesPath) -> int: ... +def isfile(path: StrOrBytesPath) -> bool: ... +def isdir(s: StrOrBytesPath) -> bool: ... # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: AnyPath) -> float: ... -def getmtime(filename: AnyPath) -> float: ... -def getctime(filename: AnyPath) -> float: ... - -if sys.version_info >= (3, 4): - def samefile(f1: AnyPath, f2: AnyPath) -> bool: ... - def sameopenfile(fp1: int, fp2: int) -> bool: ... - def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... +def getatime(filename: StrOrBytesPath) -> float: ... +def getmtime(filename: StrOrBytesPath) -> float: ... +def getctime(filename: StrOrBytesPath) -> float: ... +def samefile(f1: StrOrBytesPath, f2: StrOrBytesPath) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... diff --git a/mypy/typeshed/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi index 42269e95d896..33582d15f2d0 100644 --- a/mypy/typeshed/stdlib/glob.pyi +++ b/mypy/typeshed/stdlib/glob.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import AnyStr, Iterator, List, Optional, Union def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... @@ -7,10 +7,10 @@ def glob1(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... if sys.version_info >= (3, 10): def glob( - pathname: AnyStr, *, root_dir: Optional[AnyPath] = ..., dir_fd: Optional[int] = ..., recursive: bool = ... + pathname: AnyStr, *, root_dir: Optional[StrOrBytesPath] = ..., dir_fd: Optional[int] = ..., recursive: bool = ... ) -> List[AnyStr]: ... def iglob( - pathname: AnyStr, *, root_dir: Optional[AnyPath] = ..., dir_fd: Optional[int] = ..., recursive: bool = ... + pathname: AnyStr, *, root_dir: Optional[StrOrBytesPath] = ..., dir_fd: Optional[int] = ..., recursive: bool = ... ) -> Iterator[AnyStr]: ... else: diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index 8d061e051b93..efba70703d8d 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -1,7 +1,7 @@ import _compression import sys import zlib -from _typeshed import AnyPath, ReadableBuffer +from _typeshed import ReadableBuffer, StrOrBytesPath from io import FileIO from typing import Any, Optional, Protocol, TextIO, Union, overload from typing_extensions import Literal @@ -31,7 +31,7 @@ class _WritableFileobj(Protocol): @overload def open( - filename: Union[AnyPath, _ReadableFileobj], + filename: Union[StrOrBytesPath, _ReadableFileobj], mode: _ReadBinaryMode = ..., compresslevel: int = ..., encoding: None = ..., @@ -40,7 +40,7 @@ def open( ) -> GzipFile: ... @overload def open( - filename: Union[AnyPath, _WritableFileobj], + filename: Union[StrOrBytesPath, _WritableFileobj], mode: _WriteBinaryMode, compresslevel: int = ..., encoding: None = ..., @@ -49,7 +49,7 @@ def open( ) -> GzipFile: ... @overload def open( - filename: AnyPath, + filename: StrOrBytesPath, mode: _OpenTextMode, compresslevel: int = ..., encoding: Optional[str] = ..., @@ -58,7 +58,7 @@ def open( ) -> TextIO: ... @overload def open( - filename: Union[AnyPath, _ReadableFileobj, _WritableFileobj], + filename: Union[StrOrBytesPath, _ReadableFileobj, _WritableFileobj], mode: str, compresslevel: int = ..., encoding: Optional[str] = ..., @@ -86,7 +86,7 @@ class GzipFile(_compression.BaseStream): @overload def __init__( self, - filename: Optional[AnyPath], + filename: Optional[StrOrBytesPath], mode: _ReadBinaryMode, compresslevel: int = ..., fileobj: Optional[_ReadableFileobj] = ..., @@ -104,7 +104,7 @@ class GzipFile(_compression.BaseStream): @overload def __init__( self, - filename: Optional[AnyPath], + filename: Optional[StrOrBytesPath], mode: _WriteBinaryMode, compresslevel: int = ..., fileobj: Optional[_WritableFileobj] = ..., @@ -122,7 +122,7 @@ class GzipFile(_compression.BaseStream): @overload def __init__( self, - filename: Optional[AnyPath] = ..., + filename: Optional[StrOrBytesPath] = ..., mode: Optional[str] = ..., compresslevel: int = ..., fileobj: Union[_ReadableFileobj, _WritableFileobj, None] = ..., diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index ca4013da7879..de7b23d7ce00 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -17,18 +17,13 @@ if sys.version_info >= (3, 8): @overload def new(key: bytes, *, digestmod: _DigestMod) -> HMAC: ... -elif sys.version_info >= (3, 4): - def new(key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: Optional[_DigestMod] = ...) -> HMAC: ... - else: def new(key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: Optional[_DigestMod] = ...) -> HMAC: ... class HMAC: - if sys.version_info >= (3,): - digest_size: int - if sys.version_info >= (3, 4): - block_size: int - name: str + digest_size: int + block_size: int + name: str def __init__(self, key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: _DigestMod = ...) -> None: ... def update(self, msg: ReadableBuffer) -> None: ... def digest(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 9398bae00951..094cebe49ca0 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,6 +1,6 @@ import sys +from _typeshed import StrPath from http.client import HTTPResponse -from os import PathLike from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload from urllib.request import Request @@ -26,7 +26,7 @@ class FileCookieJar(CookieJar): delayload: bool if sys.version_info >= (3, 8): def __init__( - self, filename: Optional[Union[str, PathLike[str]]] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... + self, filename: Optional[StrPath] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... ) -> None: ... else: def __init__( diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index f9a13d013167..5d06bd5c700f 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -1,7 +1,7 @@ import email.message import socketserver import sys -from os import PathLike +from _typeshed import StrPath from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union class HTTPServer(socketserver.TCPServer): @@ -57,7 +57,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer, - directory: Optional[Union[str, PathLike[str]]] = ..., + directory: Optional[StrPath] = ..., ) -> None: ... else: def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index bb9e9c6db132..9fc3a740c463 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -4,7 +4,7 @@ import time from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, Dict, List, Optional, Pattern, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Dict, List, Optional, Pattern, Tuple, Type, Union from typing_extensions import Literal # TODO: Commands should use their actual return types, not this type alias. @@ -17,17 +17,17 @@ class IMAP4: error: Type[Exception] = ... abort: Type[Exception] = ... readonly: Type[Exception] = ... - mustquote: Pattern[Text] = ... + mustquote: Pattern[str] = ... debug: int = ... state: str = ... - literal: Optional[Text] = ... + literal: Optional[str] = ... tagged_commands: Dict[bytes, Optional[List[bytes]]] untagged_responses: Dict[str, List[Union[bytes, Tuple[bytes, bytes]]]] continuation_response: str = ... is_readonly: bool = ... tagnum: int = ... tagpre: str = ... - tagre: Pattern[Text] = ... + tagre: Pattern[str] = ... welcome: bytes = ... capabilities: Tuple[str] = ... PROTOCOL_VERSION: str = ... @@ -41,7 +41,7 @@ class IMAP4: host: str = ... port: int = ... sock: _socket = ... - file: Union[IO[Text], IO[bytes]] = ... + file: Union[IO[str], IO[bytes]] = ... def read(self, size: int) -> bytes: ... def readline(self) -> bytes: ... def send(self, data: bytes) -> None: ... @@ -58,10 +58,9 @@ class IMAP4: def create(self, mailbox: str) -> _CommandResults: ... def delete(self, mailbox: str) -> _CommandResults: ... def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... - if sys.version_info >= (3, 5): - def enable(self, capability: str) -> _CommandResults: ... - def __enter__(self) -> IMAP4: ... - def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... + def enable(self, capability: str) -> _CommandResults: ... + def __enter__(self) -> IMAP4: ... + def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... def expunge(self) -> _CommandResults: ... def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... def getacl(self, mailbox: str) -> _CommandResults: ... @@ -85,8 +84,7 @@ class IMAP4: def setannotation(self, *args: str) -> _CommandResults: ... def setquota(self, root: str, limits: str) -> _CommandResults: ... def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... - if sys.version_info >= (3,): - def starttls(self, ssl_context: Optional[Any] = ...) -> Tuple[Literal["OK"], List[None]]: ... + def starttls(self, ssl_context: Optional[Any] = ...) -> Tuple[Literal["OK"], List[None]]: ... def status(self, mailbox: str, names: str) -> _CommandResults: ... def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... def subscribe(self, mailbox: str) -> _CommandResults: ... @@ -111,7 +109,7 @@ class IMAP4_SSL(IMAP4): ssl_context: Optional[SSLContext] = ..., timeout: Optional[float] = ..., ) -> None: ... - elif sys.version_info >= (3, 3): + else: def __init__( self, host: str = ..., @@ -120,10 +118,6 @@ class IMAP4_SSL(IMAP4): certfile: Optional[str] = ..., ssl_context: Optional[SSLContext] = ..., ) -> None: ... - else: - def __init__( - self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ... - ) -> None: ... host: str = ... port: int = ... sock: _socket = ... diff --git a/mypy/typeshed/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi index ffdbbf20e97b..2b28b718a649 100644 --- a/mypy/typeshed/stdlib/imghdr.pyi +++ b/mypy/typeshed/stdlib/imghdr.pyi @@ -1,19 +1,13 @@ -import os -import sys -from typing import Any, BinaryIO, Callable, List, Optional, Protocol, Text, Union, overload +from _typeshed import StrPath +from typing import Any, BinaryIO, Callable, List, Optional, Protocol, Union, overload class _ReadableBinary(Protocol): def tell(self) -> int: ... def read(self, size: int) -> bytes: ... def seek(self, offset: int) -> Any: ... -if sys.version_info >= (3, 6): - _File = Union[Text, os.PathLike[Text], _ReadableBinary] -else: - _File = Union[Text, _ReadableBinary] - @overload -def what(file: _File, h: None = ...) -> Optional[str]: ... +def what(file: Union[StrPath, _ReadableBinary], h: None = ...) -> Optional[str]: ... @overload def what(file: Any, h: bytes) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index adcf6e097b84..c6049c38ee18 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -1,6 +1,6 @@ -import os import types from _typeshed import StrPath +from os import PathLike from typing import IO, Any, List, Optional, Protocol, Tuple, TypeVar, Union from _imp import ( @@ -57,7 +57,7 @@ def load_module(name: str, file: Optional[_FileLike], filename: str, details: Tu # IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise. def find_module( - name: str, path: Union[None, List[str], List[os.PathLike[str]], List[StrPath]] = ... + name: str, path: Union[None, List[str], List[PathLike[str]], List[StrPath]] = ... ) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... def reload(module: types.ModuleType) -> types.ModuleType: ... def init_builtin(name: str) -> Optional[types.ModuleType]: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 62b391e216fc..69b03567bb22 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -1,6 +1,6 @@ import sys import types -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from abc import ABCMeta, abstractmethod from importlib.machinery import ModuleSpec from typing import IO, Any, Iterator, Mapping, Optional, Protocol, Sequence, Tuple, Union @@ -73,9 +73,9 @@ class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): if sys.version_info >= (3, 7): class ResourceReader(metaclass=ABCMeta): @abstractmethod - def open_resource(self, resource: AnyPath) -> IO[bytes]: ... + def open_resource(self, resource: StrOrBytesPath) -> IO[bytes]: ... @abstractmethod - def resource_path(self, resource: AnyPath) -> str: ... + def resource_path(self, resource: StrOrBytesPath) -> str: ... @abstractmethod def is_resource(self, name: str) -> bool: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata.pyi index ae39c89b542a..47c2825b70bf 100644 --- a/mypy/typeshed/stdlib/importlib/metadata.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata.pyi @@ -1,11 +1,12 @@ import abc -import os import pathlib import sys +from _typeshed import StrPath from email.message import Message from importlib.abc import MetaPathFinder +from os import PathLike from pathlib import Path -from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union, overload +from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, overload if sys.version_info >= (3, 8): class PackageNotFoundError(ModuleNotFoundError): ... @@ -20,7 +21,7 @@ if sys.version_info >= (3, 8): class PackagePath(pathlib.PurePosixPath): def read_text(self, encoding: str = ...) -> str: ... def read_binary(self) -> bytes: ... - def locate(self) -> os.PathLike[str]: ... + def locate(self) -> PathLike[str]: ... # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: hash: Optional[FileHash] size: Optional[int] @@ -33,7 +34,7 @@ if sys.version_info >= (3, 8): @abc.abstractmethod def read_text(self, filename: str) -> Optional[str]: ... @abc.abstractmethod - def locate_file(self, path: Union[os.PathLike[str], str]) -> os.PathLike[str]: ... + def locate_file(self, path: StrPath) -> PathLike[str]: ... @classmethod def from_name(cls, name: str) -> Distribution: ... @overload @@ -45,7 +46,7 @@ if sys.version_info >= (3, 8): cls, *, context: None = ..., name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any ) -> Iterable[Distribution]: ... @staticmethod - def at(path: Union[str, os.PathLike[str]]) -> PathDistribution: ... + def at(path: StrPath) -> PathDistribution: ... @property def metadata(self) -> Message: ... @property @@ -69,8 +70,8 @@ if sys.version_info >= (3, 8): def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... class PathDistribution(Distribution): def __init__(self, path: Path) -> None: ... - def read_text(self, filename: Union[str, os.PathLike[str]]) -> str: ... - def locate_file(self, path: Union[str, os.PathLike[str]]) -> os.PathLike[str]: ... + def read_text(self, filename: StrPath) -> str: ... + def locate_file(self, path: StrPath) -> PathLike[str]: ... def distribution(distribution_name: str) -> Distribution: ... @overload def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index e5d4ec399a22..7dea5a718179 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -1,8 +1,8 @@ import importlib.abc import importlib.machinery -import os import types -from typing import Any, Callable, List, Optional, Union +from _typeshed import StrOrBytesPath +from typing import Any, Callable, List, Optional def module_for_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... def set_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... @@ -20,7 +20,7 @@ def spec_from_loader( ) -> Optional[importlib.machinery.ModuleSpec]: ... def spec_from_file_location( name: str, - location: Optional[Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]] = ..., + location: Optional[StrOrBytesPath] = ..., *, loader: Optional[importlib.abc.Loader] = ..., submodule_search_locations: Optional[List[str]] = ..., diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index 3e095ed5f94c..ac052feeba58 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,7 +1,7 @@ import sys -from typing import Sequence, Text +from typing import Sequence -def iskeyword(s: Text) -> bool: ... +def iskeyword(s: str) -> bool: ... kwlist: Sequence[str] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi index 841b0e4b1cb3..f50cbd78bbaa 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -2,7 +2,7 @@ from _typeshed import StrPath from lib2to3.pgen2.grammar import Grammar from lib2to3.pytree import _NL, _Convert from logging import Logger -from typing import IO, Any, Iterable, Optional, Text +from typing import IO, Any, Iterable, Optional class Driver: grammar: Grammar @@ -10,11 +10,11 @@ class Driver: convert: _Convert def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ..., logger: Optional[Logger] = ...) -> None: ... def parse_tokens(self, tokens: Iterable[Any], debug: bool = ...) -> _NL: ... - def parse_stream_raw(self, stream: IO[Text], debug: bool = ...) -> _NL: ... - def parse_stream(self, stream: IO[Text], debug: bool = ...) -> _NL: ... - def parse_file(self, filename: StrPath, encoding: Optional[Text] = ..., debug: bool = ...) -> _NL: ... - def parse_string(self, text: Text, debug: bool = ...) -> _NL: ... + def parse_stream_raw(self, stream: IO[str], debug: bool = ...) -> _NL: ... + def parse_stream(self, stream: IO[str], debug: bool = ...) -> _NL: ... + def parse_file(self, filename: StrPath, encoding: Optional[str] = ..., debug: bool = ...) -> _NL: ... + def parse_string(self, text: str, debug: bool = ...) -> _NL: ... def load_grammar( - gt: Text = ..., gp: Optional[Text] = ..., save: bool = ..., force: bool = ..., logger: Optional[Logger] = ... + gt: str = ..., gp: Optional[str] = ..., save: bool = ..., force: bool = ..., logger: Optional[Logger] = ... ) -> Grammar: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index 6ec97ce849d2..fe250cfe7717 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,20 +1,20 @@ from _typeshed import StrPath -from typing import Dict, List, Optional, Text, Tuple, TypeVar +from typing import Dict, List, Optional, Tuple, TypeVar _P = TypeVar("_P") -_Label = Tuple[int, Optional[Text]] +_Label = Tuple[int, Optional[str]] _DFA = List[List[Tuple[int, int]]] _DFAS = Tuple[_DFA, Dict[int, int]] class Grammar: - symbol2number: Dict[Text, int] - number2symbol: Dict[int, Text] + symbol2number: Dict[str, int] + number2symbol: Dict[int, str] states: List[_DFA] dfas: Dict[int, _DFAS] labels: List[_Label] - keywords: Dict[Text, int] + keywords: Dict[str, int] tokens: Dict[int, int] - symbol2label: Dict[Text, int] + symbol2label: Dict[str, int] start: int def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... @@ -22,5 +22,5 @@ class Grammar: def copy(self: _P) -> _P: ... def report(self) -> None: ... -opmap_raw: Text -opmap: Dict[Text, Text] +opmap_raw: str +opmap: Dict[str, str] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi index 160d6fd76f76..4c162ecf2747 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi @@ -1,7 +1,7 @@ -from typing import Dict, Match, Text +from typing import Dict, Match -simple_escapes: Dict[Text, Text] +simple_escapes: Dict[str, str] -def escape(m: Match[str]) -> Text: ... -def evalString(s: Text) -> Text: ... +def escape(m: Match[str]) -> str: ... +def evalString(s: str) -> str: ... def test() -> None: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index b7018cba9c1d..c84d2cdf73cc 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,26 +1,26 @@ from lib2to3.pgen2.grammar import _DFAS, Grammar from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, List, Optional, Sequence, Set, Text, Tuple +from typing import Any, List, Optional, Sequence, Set, Tuple _Context = Sequence[Any] class ParseError(Exception): - msg: Text + msg: str type: int - value: Optional[Text] + value: Optional[str] context: _Context - def __init__(self, msg: Text, type: int, value: Optional[Text], context: _Context) -> None: ... + def __init__(self, msg: str, type: int, value: Optional[str], context: _Context) -> None: ... class Parser: grammar: Grammar convert: _Convert stack: List[Tuple[_DFAS, int, _RawNode]] rootnode: Optional[_NL] - used_names: Set[Text] + used_names: Set[str] def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ...) -> None: ... def setup(self, start: Optional[int] = ...) -> None: ... - def addtoken(self, type: int, value: Optional[Text], context: _Context) -> bool: ... - def classify(self, type: int, value: Optional[Text], context: _Context) -> int: ... - def shift(self, type: int, value: Optional[Text], newstate: int, context: _Context) -> None: ... + def addtoken(self, type: int, value: Optional[str], context: _Context) -> bool: ... + def classify(self, type: int, value: Optional[str], context: _Context) -> int: ... + def shift(self, type: int, value: Optional[str], newstate: int, context: _Context) -> None: ... def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ... def pop(self) -> None: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 7920262f4f04..6909eed9b5f1 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -1,45 +1,45 @@ from _typeshed import StrPath from lib2to3.pgen2 import grammar from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Optional, Text, Tuple +from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Optional, Tuple class PgenGrammar(grammar.Grammar): ... class ParserGenerator: filename: StrPath - stream: IO[Text] + stream: IO[str] generator: Iterator[_TokenInfo] - first: Dict[Text, Dict[Text, int]] - def __init__(self, filename: StrPath, stream: Optional[IO[Text]] = ...) -> None: ... + first: Dict[str, Dict[str, int]] + def __init__(self, filename: StrPath, stream: Optional[IO[str]] = ...) -> None: ... def make_grammar(self) -> PgenGrammar: ... - def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... - def make_label(self, c: PgenGrammar, label: Text) -> int: ... + def make_first(self, c: PgenGrammar, name: str) -> Dict[int, int]: ... + def make_label(self, c: PgenGrammar, label: str) -> int: ... def addfirstsets(self) -> None: ... - def calcfirst(self, name: Text) -> None: ... - def parse(self) -> Tuple[Dict[Text, List[DFAState]], Text]: ... + def calcfirst(self, name: str) -> None: ... + def parse(self) -> Tuple[Dict[str, List[DFAState]], str]: ... def make_dfa(self, start: NFAState, finish: NFAState) -> List[DFAState]: ... - def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> List[DFAState]: ... - def dump_dfa(self, name: Text, dfa: Iterable[DFAState]) -> None: ... + def dump_nfa(self, name: str, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def dump_dfa(self, name: str, dfa: Iterable[DFAState]) -> None: ... def simplify_dfa(self, dfa: List[DFAState]) -> None: ... def parse_rhs(self) -> Tuple[NFAState, NFAState]: ... def parse_alt(self) -> Tuple[NFAState, NFAState]: ... def parse_item(self) -> Tuple[NFAState, NFAState]: ... def parse_atom(self) -> Tuple[NFAState, NFAState]: ... - def expect(self, type: int, value: Optional[Any] = ...) -> Text: ... + def expect(self, type: int, value: Optional[Any] = ...) -> str: ... def gettoken(self) -> None: ... def raise_error(self, msg: str, *args: Any) -> NoReturn: ... class NFAState: - arcs: List[Tuple[Optional[Text], NFAState]] + arcs: List[Tuple[Optional[str], NFAState]] def __init__(self) -> None: ... - def addarc(self, next: NFAState, label: Optional[Text] = ...) -> None: ... + def addarc(self, next: NFAState, label: Optional[str] = ...) -> None: ... class DFAState: nfaset: Dict[NFAState, Any] isfinal: bool - arcs: Dict[Text, DFAState] + arcs: Dict[str, DFAState] def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... - def addarc(self, next: DFAState, label: Text) -> None: ... + def addarc(self, next: DFAState, label: str) -> None: ... def unifystate(self, old: DFAState, new: DFAState) -> None: ... def __eq__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi index 19660cb0ce26..86cafdcbb700 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi @@ -1,5 +1,4 @@ -import sys -from typing import Dict, Text +from typing import Dict ENDMARKER: int NAME: int @@ -54,17 +53,15 @@ DOUBLESLASHEQUAL: int OP: int COMMENT: int NL: int -if sys.version_info >= (3,): - RARROW: int -if sys.version_info >= (3, 5): - AT: int - ATEQUAL: int - AWAIT: int - ASYNC: int +RARROW: int +AT: int +ATEQUAL: int +AWAIT: int +ASYNC: int ERRORTOKEN: int N_TOKENS: int NT_OFFSET: int -tok_name: Dict[int, Text] +tok_name: Dict[int, str] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index 477341c1a54e..116f77a69fe2 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,23 +1,23 @@ from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, List, Text, Tuple +from typing import Callable, Iterable, Iterator, List, Tuple _Coord = Tuple[int, int] -_TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] -_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] +_TokenEater = Callable[[int, str, _Coord, _Coord, str], None] +_TokenInfo = Tuple[int, str, _Coord, _Coord, str] class TokenError(Exception): ... class StopTokenizing(Exception): ... -def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... +def tokenize(readline: Callable[[], str], tokeneater: _TokenEater = ...) -> None: ... class Untokenizer: - tokens: List[Text] + tokens: List[str] prev_row: int prev_col: int def __init__(self) -> None: ... def add_whitespace(self, start: _Coord) -> None: ... - def untokenize(self, iterable: Iterable[_TokenInfo]) -> Text: ... - def compat(self, token: Tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... + def untokenize(self, iterable: Iterable[_TokenInfo]) -> str: ... + def compat(self, token: Tuple[int, str], iterable: Iterable[_TokenInfo]) -> None: ... -def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... -def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... +def untokenize(iterable: Iterable[_TokenInfo]) -> str: ... +def generate_tokens(readline: Callable[[], str]) -> Iterator[_TokenInfo]: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 955763588cd1..8d90ee39b76b 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,22 +1,21 @@ -import sys from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union _P = TypeVar("_P") _NL = Union[Node, Leaf] -_Context = Tuple[Text, int, int] -_Results = Dict[Text, _NL] -_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] +_Context = Tuple[str, int, int] +_Results = Dict[str, _NL] +_RawNode = Tuple[int, str, _Context, Optional[List[_NL]]] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int -def type_repr(type_num: int) -> Text: ... +def type_repr(type_num: int) -> str: ... class Base: type: int parent: Optional[Node] - prefix: Text + prefix: str children: List[_NL] was_changed: bool was_checked: bool @@ -35,10 +34,7 @@ class Base: def prev_sibling(self) -> Optional[_NL]: ... def leaves(self) -> Iterator[Leaf]: ... def depth(self) -> int: ... - def get_suffix(self) -> Text: ... - if sys.version_info < (3,): - def get_prefix(self) -> Text: ... - def set_prefix(self, prefix: Text) -> None: ... + def get_suffix(self) -> str: ... class Node(Base): fixers_applied: List[Any] @@ -47,7 +43,7 @@ class Node(Base): type: int, children: List[_NL], context: Optional[Any] = ..., - prefix: Optional[Text] = ..., + prefix: Optional[str] = ..., fixers_applied: Optional[List[Any]] = ..., ) -> None: ... def set_child(self, i: int, child: _NL) -> None: ... @@ -57,14 +53,14 @@ class Node(Base): class Leaf(Base): lineno: int column: int - value: Text + value: str fixers_applied: List[Any] def __init__( self, type: int, - value: Text, + value: str, context: Optional[_Context] = ..., - prefix: Optional[Text] = ..., + prefix: Optional[str] = ..., fixers_applied: List[Any] = ..., ) -> None: ... @@ -72,26 +68,26 @@ def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... class BasePattern: type: int - content: Optional[Text] - name: Optional[Text] + content: Optional[str] + name: Optional[str] def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns def match(self, node: _NL, results: Optional[_Results] = ...) -> bool: ... def match_seq(self, nodes: List[_NL], results: Optional[_Results] = ...) -> bool: ... def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... class LeafPattern(BasePattern): - def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + def __init__(self, type: Optional[int] = ..., content: Optional[str] = ..., name: Optional[str] = ...) -> None: ... class NodePattern(BasePattern): wildcards: bool - def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + def __init__(self, type: Optional[int] = ..., content: Optional[str] = ..., name: Optional[str] = ...) -> None: ... class WildcardPattern(BasePattern): min: int max: int - def __init__(self, content: Optional[Text] = ..., min: int = ..., max: int = ..., name: Optional[Text] = ...) -> None: ... + def __init__(self, content: Optional[str] = ..., min: int = ..., max: int = ..., name: Optional[str] = ...) -> None: ... class NegatedPattern(BasePattern): - def __init__(self, content: Optional[Text] = ...) -> None: ... + def __init__(self, content: Optional[str] = ...) -> None: ... def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index f52267bdba98..73c77387615c 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,13 +1,10 @@ -import sys -from typing import Any, Dict, List, Optional, Text +from typing import Any, Dict, List, Optional _ModuleGlobals = Dict[str, Any] -def getline(filename: Text, lineno: int, module_globals: Optional[_ModuleGlobals] = ...) -> str: ... +def getline(filename: str, lineno: int, module_globals: Optional[_ModuleGlobals] = ...) -> str: ... def clearcache() -> None: ... -def getlines(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... -def checkcache(filename: Optional[Text] = ...) -> None: ... -def updatecache(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... - -if sys.version_info >= (3, 5): - def lazycache(filename: Text, module_globals: _ModuleGlobals) -> bool: ... +def getlines(filename: str, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... +def checkcache(filename: Optional[str] = ...) -> None: ... +def updatecache(filename: str, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... +def lazycache(filename: str, module_globals: _ModuleGlobals) -> bool: ... diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index 9be4aa2735e1..1e575a64856a 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -1,13 +1,11 @@ import sys + +# This module defines a function "str()", which is why "str" can't be used +# as a type annotation or type alias. +from builtins import str as _str from decimal import Decimal from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union -# workaround for mypy#2010 -if sys.version_info >= (3, 0): - from builtins import str as _str -else: - from __builtin__ import str as _str - CODESET: int D_T_FMT: int D_FMT: int @@ -98,10 +96,7 @@ else: def format_string(f: _str, val: Any, grouping: bool = ...) -> _str: ... def currency(val: Union[int, float, Decimal], symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... - -if sys.version_info >= (3, 5): - def delocalize(string: _str) -> _str: ... - +def delocalize(string: _str) -> _str: ... def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... def str(val: float) -> _str: ... diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index be2f2e68508d..ed79f48aa94c 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath, StrPath +from _typeshed import StrOrBytesPath, StrPath from collections.abc import Callable from configparser import RawConfigParser from threading import Thread @@ -11,7 +11,7 @@ else: from typing_extensions import Literal if sys.version_info >= (3, 7): - _Path = AnyPath + _Path = StrOrBytesPath else: _Path = StrPath diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 7290a25b3bcd..0228b9d12d55 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,12 +1,12 @@ import io -from _typeshed import AnyPath, ReadableBuffer +from _typeshed import ReadableBuffer, StrOrBytesPath from typing import IO, Any, Mapping, Optional, Sequence, TextIO, TypeVar, Union, overload from typing_extensions import Literal _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] _OpenTextWritingMode = Literal["wt", "xt", "at"] -_PathOrFile = Union[AnyPath, IO[bytes]] +_PathOrFile = Union[StrOrBytesPath, IO[bytes]] _FilterChain = Sequence[Mapping[str, Any]] _T = TypeVar("_T") @@ -120,7 +120,7 @@ def open( ) -> LZMAFile: ... @overload def open( - filename: AnyPath, + filename: StrOrBytesPath, mode: Literal["rt"], *, format: Optional[int] = ..., @@ -133,7 +133,7 @@ def open( ) -> TextIO: ... @overload def open( - filename: AnyPath, + filename: StrOrBytesPath, mode: _OpenTextWritingMode, *, format: Optional[int] = ..., diff --git a/mypy/typeshed/stdlib/macpath.pyi b/mypy/typeshed/stdlib/macpath.pyi index 296f3a9ba151..ecb4e9146451 100644 --- a/mypy/typeshed/stdlib/macpath.pyi +++ b/mypy/typeshed/stdlib/macpath.pyi @@ -1,5 +1,4 @@ -import sys -from _typeshed import AnyPath, BytesPath, StrPath +from _typeshed import BytesPath, StrOrBytesPath, StrPath from genericpath import ( commonprefix as commonprefix, exists as exists, @@ -9,10 +8,11 @@ from genericpath import ( getsize as getsize, isdir as isdir, isfile as isfile, + samefile as samefile, + sameopenfile as sameopenfile, + samestat as samestat, ) - -if sys.version_info >= (3, 4): - from genericpath import samefile as samefile, sameopenfile as sameopenfile, samestat as samestat +from os import PathLike # Re-export common definitions from posixpath to reduce duplication from posixpath import ( @@ -32,73 +32,38 @@ from posixpath import ( splitext as splitext, supports_unicode_filenames as supports_unicode_filenames, ) -from typing import AnyStr, Optional, Text, Tuple, overload +from typing import AnyStr, Optional, Tuple, overload altsep: Optional[str] -if sys.version_info >= (3, 6): - from os import PathLike - @overload - def basename(s: PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(s: AnyStr) -> AnyStr: ... - @overload - def dirname(s: PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(s: AnyStr) -> AnyStr: ... - @overload - def normcase(path: PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(path: AnyStr) -> AnyStr: ... - @overload - def normpath(s: PathLike[AnyStr]) -> AnyStr: ... - @overload - def normpath(s: AnyStr) -> AnyStr: ... - @overload - def realpath(path: PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - -else: - def basename(s: AnyStr) -> AnyStr: ... - def dirname(s: AnyStr) -> AnyStr: ... - def normcase(path: AnyStr) -> AnyStr: ... - def normpath(s: AnyStr) -> AnyStr: ... - def realpath(path: AnyStr) -> AnyStr: ... - -def islink(s: AnyPath) -> bool: ... - -if sys.version_info >= (3, 6): - # Mypy complains that the signatures overlap, but things seem to behave correctly anyway. - @overload - def join(s: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(s: BytesPath, *paths: BytesPath) -> bytes: ... - -elif sys.version_info >= (3, 0): - def join(s: AnyStr, *paths: AnyStr) -> AnyStr: ... - -else: - # Make sure signatures are disjunct, and allow combinations of bytes and unicode. - # (Since Python 2 allows that, too) - # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in - # a type error. - @overload - def join(__p1: bytes, *p: bytes) -> bytes: ... - @overload - def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: AnyPath) -> Text: ... - @overload - def join(__p1: bytes, __p2: bytes, __p3: Text, *p: AnyPath) -> Text: ... - @overload - def join(__p1: bytes, __p2: Text, *p: AnyPath) -> Text: ... - @overload - def join(__p1: Text, *p: AnyPath) -> Text: ... - -if sys.version_info >= (3, 6): - @overload - def split(s: PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def basename(s: PathLike[AnyStr]) -> AnyStr: ... +@overload +def basename(s: AnyStr) -> AnyStr: ... +@overload +def dirname(s: PathLike[AnyStr]) -> AnyStr: ... +@overload +def dirname(s: AnyStr) -> AnyStr: ... +@overload +def normcase(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def normcase(path: AnyStr) -> AnyStr: ... +@overload +def normpath(s: PathLike[AnyStr]) -> AnyStr: ... +@overload +def normpath(s: AnyStr) -> AnyStr: ... +@overload +def realpath(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def realpath(path: AnyStr) -> AnyStr: ... +def islink(s: StrOrBytesPath) -> bool: ... -else: - def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +# Mypy complains that the signatures overlap, but things seem to behave correctly anyway. +@overload +def join(s: StrPath, *paths: StrPath) -> str: ... +@overload +def join(s: BytesPath, *paths: BytesPath) -> bytes: ... +@overload +def split(s: PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index d968e7d77244..1abe616fdc18 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -1,6 +1,6 @@ import email.message import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import TracebackType from typing import ( IO, @@ -16,7 +16,6 @@ from typing import ( Optional, Protocol, Sequence, - Text, Tuple, Type, TypeVar, @@ -44,7 +43,9 @@ class Mailbox(Generic[_MessageT]): _path: Union[bytes, str] # undocumented _factory: Optional[Callable[[IO[Any]], _MessageT]] # undocumented - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], _MessageT]] = ..., create: bool = ...) -> None: ... + def __init__( + self, path: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], _MessageT]] = ..., create: bool = ... + ) -> None: ... def add(self, message: _MessageData) -> str: ... def remove(self, key: str) -> None: ... def __delitem__(self, key: str) -> None: ... @@ -87,13 +88,13 @@ class Maildir(Mailbox[MaildirMessage]): colon: str def __init__( - self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], MaildirMessage]] = ..., create: bool = ... + self, dirname: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], MaildirMessage]] = ..., create: bool = ... ) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... def list_folders(self) -> List[str]: ... - def get_folder(self, folder: Text) -> Maildir: ... - def add_folder(self, folder: Text) -> Maildir: ... - def remove_folder(self, folder: Text) -> None: ... + def get_folder(self, folder: str) -> Maildir: ... + def add_folder(self, folder: str) -> Maildir: ... + def remove_folder(self, folder: str) -> None: ... def clean(self) -> None: ... def next(self) -> Optional[str]: ... @@ -105,24 +106,32 @@ class _mboxMMDF(_singlefileMailbox[_MessageT]): def get_string(self, key: str, from_: bool = ...) -> str: ... class mbox(_mboxMMDF[mboxMessage]): - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, path: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ... + ) -> None: ... class MMDF(_mboxMMDF[MMDFMessage]): - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, path: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ... + ) -> None: ... class MH(Mailbox[MHMessage]): - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], MHMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, path: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], MHMessage]] = ..., create: bool = ... + ) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... def list_folders(self) -> List[str]: ... - def get_folder(self, folder: AnyPath) -> MH: ... - def add_folder(self, folder: AnyPath) -> MH: ... - def remove_folder(self, folder: AnyPath) -> None: ... + def get_folder(self, folder: StrOrBytesPath) -> MH: ... + def add_folder(self, folder: StrOrBytesPath) -> MH: ... + def remove_folder(self, folder: StrOrBytesPath) -> None: ... def get_sequences(self) -> Dict[str, List[int]]: ... def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], BabylMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, path: StrOrBytesPath, factory: Optional[Callable[[IO[Any]], BabylMessage]] = ..., create: bool = ... + ) -> None: ... def get_file(self, key: str) -> IO[bytes]: ... def get_labels(self) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index 6f9a89996dc0..9aa54504c571 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -3,11 +3,9 @@ from typing import Iterable, Optional, SupportsFloat, SupportsInt, Tuple, overlo e: float pi: float -if sys.version_info >= (3, 5): - inf: float - nan: float -if sys.version_info >= (3, 6): - tau: float +inf: float +nan: float +tau: float def acos(__x: SupportsFloat) -> float: ... def acosh(__x: SupportsFloat) -> float: ... @@ -16,12 +14,7 @@ def asinh(__x: SupportsFloat) -> float: ... def atan(__x: SupportsFloat) -> float: ... def atan2(__y: SupportsFloat, __x: SupportsFloat) -> float: ... def atanh(__x: SupportsFloat) -> float: ... - -if sys.version_info >= (3,): - def ceil(__x: SupportsFloat) -> int: ... - -else: - def ceil(__x: SupportsFloat) -> float: ... +def ceil(__x: SupportsFloat) -> int: ... if sys.version_info >= (3, 8): def comb(__n: int, __k: int) -> int: ... @@ -40,13 +33,7 @@ def exp(__x: SupportsFloat) -> float: ... def expm1(__x: SupportsFloat) -> float: ... def fabs(__x: SupportsFloat) -> float: ... def factorial(__x: SupportsInt) -> int: ... - -if sys.version_info >= (3,): - def floor(__x: SupportsFloat) -> int: ... - -else: - def floor(__x: SupportsFloat) -> float: ... - +def floor(__x: SupportsFloat) -> int: ... def fmod(__x: SupportsFloat, __y: SupportsFloat) -> float: ... def frexp(__x: SupportsFloat) -> Tuple[float, int]: ... def fsum(__seq: Iterable[float]) -> float: ... @@ -55,7 +42,7 @@ def gamma(__x: SupportsFloat) -> float: ... if sys.version_info >= (3, 9): def gcd(*integers: int) -> int: ... -elif sys.version_info >= (3, 5): +else: def gcd(__x: int, __y: int) -> int: ... if sys.version_info >= (3, 8): @@ -64,14 +51,9 @@ if sys.version_info >= (3, 8): else: def hypot(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -if sys.version_info >= (3, 5): - def isclose(a: SupportsFloat, b: SupportsFloat, *, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... - +def isclose(a: SupportsFloat, b: SupportsFloat, *, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... def isinf(__x: SupportsFloat) -> bool: ... - -if sys.version_info >= (3,): - def isfinite(__x: SupportsFloat) -> bool: ... - +def isfinite(__x: SupportsFloat) -> bool: ... def isnan(__x: SupportsFloat) -> bool: ... if sys.version_info >= (3, 8): @@ -85,10 +67,7 @@ def lgamma(__x: SupportsFloat) -> float: ... def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... def log10(__x: SupportsFloat) -> float: ... def log1p(__x: SupportsFloat) -> float: ... - -if sys.version_info >= (3, 3): - def log2(__x: SupportsFloat) -> float: ... - +def log2(__x: SupportsFloat) -> float: ... def modf(__x: SupportsFloat) -> Tuple[float, float]: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index f0cfac32cafd..d1b440647620 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -1,12 +1,12 @@ import sys -from typing import IO, Dict, List, Optional, Sequence, Text, Tuple, Union +from _typeshed import StrPath +from typing import IO, Dict, List, Optional, Sequence, Tuple if sys.version_info >= (3, 8): - from os import PathLike - def guess_type(url: Union[Text, PathLike[str]], strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + def guess_type(url: StrPath, strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... else: - def guess_type(url: Text, strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + def guess_type(url: str, strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 0ba69e5896d7..691d4f621a1b 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing import AnyStr, ContextManager, Generic, Iterable, Iterator, Optional, Sequence, Sized, Union, overload +from typing import AnyStr, ContextManager, Generic, Iterable, Iterator, Optional, Sized, Union, overload ACCESS_DEFAULT: int ACCESS_READ: int @@ -48,41 +48,26 @@ class _mmap(Generic[AnyStr]): def write_byte(self, byte: AnyStr) -> None: ... def __len__(self) -> int: ... -if sys.version_info >= (3,): - class mmap(_mmap[bytes], ContextManager[mmap], Iterable[bytes], Sized): - closed: bool - if sys.version_info >= (3, 8) and sys.platform != "win32": - def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... - def find(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... - def rfind(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... - def read(self, n: Optional[int] = ...) -> bytes: ... - if sys.version_info >= (3, 6): - def write(self, bytes: ReadableBuffer) -> int: ... - else: - def write(self, bytes: ReadableBuffer) -> None: ... - @overload - def __getitem__(self, index: int) -> int: ... - @overload - def __getitem__(self, index: slice) -> bytes: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - @overload - def __setitem__(self, index: int, object: int) -> None: ... - @overload - def __setitem__(self, index: slice, object: bytes) -> None: ... - # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and - # __len__, so we claim that there is also an __iter__ to help type checkers. - def __iter__(self) -> Iterator[bytes]: ... - -else: - class mmap(_mmap[bytes], Sequence[bytes]): - def find(self, string: bytes, start: int = ..., end: int = ...) -> int: ... - def rfind(self, string: bytes, start: int = ..., stop: int = ...) -> int: ... - def read(self, num: int) -> bytes: ... - def write(self, string: bytes) -> None: ... - def __getitem__(self, index: Union[int, slice]) -> bytes: ... - def __getslice__(self, i: Optional[int], j: Optional[int]) -> bytes: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - def __setitem__(self, index: Union[int, slice], object: bytes) -> None: ... +class mmap(_mmap[bytes], ContextManager[mmap], Iterable[bytes], Sized): + closed: bool + if sys.version_info >= (3, 8) and sys.platform != "win32": + def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... + def find(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... + def rfind(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... + def read(self, n: Optional[int] = ...) -> bytes: ... + def write(self, bytes: ReadableBuffer) -> int: ... + @overload + def __getitem__(self, index: int) -> int: ... + @overload + def __getitem__(self, index: slice) -> bytes: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + @overload + def __setitem__(self, index: int, object: int) -> None: ... + @overload + def __setitem__(self, index: slice, object: bytes) -> None: ... + # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and + # __len__, so we claim that there is also an __iter__ to help type checkers. + def __iter__(self) -> Iterator[bytes]: ... if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_NORMAL: int diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index 89119b6029df..7cb715ce706c 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -62,8 +62,7 @@ class ModuleFinder: def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented def import_module(self, partname: str, fqname: str, parent: Module) -> Optional[Module]: ... # undocumented def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented - if sys.version_info >= (3, 6): - def scan_opcodes(self, co: CodeType) -> Iterator[Tuple[str, Tuple[Any, ...]]]: ... # undocumented + def scan_opcodes(self, co: CodeType) -> Iterator[Tuple[str, Tuple[Any, ...]]]: ... # undocumented def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented def add_module(self, fqname: str) -> Module: ... # undocumented diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index ede80c9fbb66..0441ed8acd24 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -1,5 +1,4 @@ import sys -from typing import Text # This module is only available on Windows if sys.platform == "win32": @@ -14,11 +13,11 @@ if sys.platform == "win32": def get_osfhandle(__fd: int) -> int: ... def kbhit() -> bool: ... def getch() -> bytes: ... - def getwch() -> Text: ... + def getwch() -> str: ... def getche() -> bytes: ... - def getwche() -> Text: ... + def getwche() -> str: ... def putch(__char: bytes) -> None: ... - def putwch(__unicode_char: Text) -> None: ... + def putwch(__unicode_char: str) -> None: ... def ungetch(__char: bytes) -> None: ... - def ungetwch(__unicode_char: Text) -> None: ... + def ungetwch(__unicode_char: str) -> None: ... def heapmin() -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 161cc72c27d8..c8f9e2c654bc 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -15,7 +15,9 @@ from multiprocessing.context import ( from multiprocessing.managers import SyncManager from multiprocessing.process import active_children as active_children, current_process as current_process -# These are technically functions that return instances of these Queue classes. See #4313 for discussion +# These are technically functions that return instances of these Queue classes. +# Using them as annotations is deprecated. Either use imports from +# multiprocessing.queues or the aliases defined below. See #4266 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support from typing import Any, Optional, Union, overload @@ -27,6 +29,26 @@ if sys.version_info >= (3, 8): if sys.platform != "win32": from multiprocessing.context import ForkContext, ForkServerContext +# The following type aliases can be used to annotate the return values of +# the corresponding functions. They are not defined at runtime. +# +# from multiprocessing import Lock +# from typing import TYPE_CHECKING +# if TYPE_CHECKING: +# from multiprocessing import _LockType +# lock: _LockType = Lock() + +_QueueType = Queue +_SimpleQueueType = SimpleQueue +_JoinableQueueType = JoinableQueue +_BarrierType = synchronize.Barrier +_BoundedSemaphoreType = synchronize.BoundedSemaphore +_ConditionType = synchronize.Condition +_EventType = synchronize.Event +_LockType = synchronize.Lock +_RLockType = synchronize.RLock +_SemaphoreType = synchronize.Semaphore + # N.B. The functions below are generated at runtime by partially applying # multiprocessing.context.BaseContext's methods, so the two signatures should # be identical (modulo self). @@ -38,13 +60,13 @@ RawArray = context._default_context.RawArray Value = context._default_context.Value Array = context._default_context.Array -def Barrier(parties: int, action: Optional[Callable[..., Any]] = ..., timeout: Optional[float] = ...) -> synchronize.Barrier: ... -def BoundedSemaphore(value: int = ...) -> synchronize.BoundedSemaphore: ... -def Condition(lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... -def Event() -> synchronize.Event: ... -def Lock() -> synchronize.Lock: ... -def RLock() -> synchronize.RLock: ... -def Semaphore(value: int = ...) -> synchronize.Semaphore: ... +def Barrier(parties: int, action: Optional[Callable[..., Any]] = ..., timeout: Optional[float] = ...) -> _BarrierType: ... +def BoundedSemaphore(value: int = ...) -> _BoundedSemaphoreType: ... +def Condition(lock: Optional[_LockLike] = ...) -> _ConditionType: ... +def Event() -> _EventType: ... +def Lock() -> _LockType: ... +def RLock() -> _RLockType: ... +def Semaphore(value: int = ...) -> _SemaphoreType: ... def Pipe(duplex: bool = ...) -> tuple[connection.Connection, connection.Connection]: ... def Pool( processes: Optional[int] = ..., diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 20a0513ea54a..b71c4b31501a 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,11 +1,11 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import Dict, List, Optional, Tuple class NetrcParseError(Exception): filename: Optional[str] lineno: Optional[int] msg: str - def __init__(self, msg: str, filename: Optional[AnyPath] = ..., lineno: Optional[int] = ...) -> None: ... + def __init__(self, msg: str, filename: Optional[StrOrBytesPath] = ..., lineno: Optional[int] = ...) -> None: ... # (login, account, password) tuple _NetrcTuple = Tuple[str, Optional[str], Optional[str]] @@ -13,5 +13,5 @@ _NetrcTuple = Tuple[str, Optional[str], Optional[str]] class netrc: hosts: Dict[str, _NetrcTuple] macros: Dict[str, List[str]] - def __init__(self, file: Optional[AnyPath] = ...) -> None: ... + def __init__(self, file: Optional[StrOrBytesPath] = ...) -> None: ... def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index 4f8a5a5d67fc..7c5dbe1610a2 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -1,7 +1,6 @@ # Note: these stubs are incomplete. The more complex type # signatures are currently omitted. -import sys from abc import ABCMeta, abstractmethod from typing import Any, Optional, SupportsFloat, overload @@ -12,10 +11,7 @@ class Number(metaclass=ABCMeta): class Complex(Number): @abstractmethod def __complex__(self) -> complex: ... - if sys.version_info >= (3, 0): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... @property @abstractmethod def real(self) -> Any: ... @@ -36,11 +32,6 @@ class Complex(Number): def __mul__(self, other: Any) -> Any: ... @abstractmethod def __rmul__(self, other: Any) -> Any: ... - if sys.version_info < (3, 0): - @abstractmethod - def __div__(self, other): ... - @abstractmethod - def __rdiv__(self, other): ... @abstractmethod def __truediv__(self, other: Any) -> Any: ... @abstractmethod @@ -52,25 +43,22 @@ class Complex(Number): def __abs__(self) -> Real: ... def conjugate(self) -> Any: ... def __eq__(self, other: Any) -> bool: ... - if sys.version_info < (3, 0): - def __ne__(self, other: Any) -> bool: ... class Real(Complex, SupportsFloat): @abstractmethod def __float__(self) -> float: ... @abstractmethod def __trunc__(self) -> int: ... - if sys.version_info >= (3, 0): - @abstractmethod - def __floor__(self) -> int: ... - @abstractmethod - def __ceil__(self) -> int: ... - @abstractmethod - @overload - def __round__(self, ndigits: None = ...) -> int: ... - @abstractmethod - @overload - def __round__(self, ndigits: int) -> Any: ... + @abstractmethod + def __floor__(self) -> int: ... + @abstractmethod + def __ceil__(self) -> int: ... + @abstractmethod + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @abstractmethod + @overload + def __round__(self, ndigits: int) -> Any: ... def __divmod__(self, other: Any) -> Any: ... def __rdivmod__(self, other: Any) -> Any: ... @abstractmethod @@ -102,12 +90,8 @@ class Rational(Real): def __float__(self) -> float: ... class Integral(Rational): - if sys.version_info >= (3, 0): - @abstractmethod - def __int__(self) -> int: ... - else: - @abstractmethod - def __long__(self) -> long: ... + @abstractmethod + def __int__(self) -> int: ... def __index__(self) -> int: ... @abstractmethod def __pow__(self, exponent: Any, modulus: Optional[Any] = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index 6307c280aebe..74b39830041a 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -18,8 +18,7 @@ EXTENDED_ARG: int if sys.version_info >= (3, 8): def stack_effect(__opcode: int, __oparg: Optional[int] = ..., *, jump: Optional[bool] = ...) -> int: ... -elif sys.version_info >= (3, 4): +else: def stack_effect(__opcode: int, __oparg: Optional[int] = ...) -> int: ... -if sys.version_info >= (3, 6): - hasnargs: List[int] +hasnargs: List[int] diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index 03510fed90fc..c9fe47c4a70f 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -1,4 +1,3 @@ -import sys from typing import ( Any, Container, @@ -41,11 +40,6 @@ def add(__a: Any, __b: Any) -> Any: ... def __add__(a: Any, b: Any) -> Any: ... def and_(__a: Any, __b: Any) -> Any: ... def __and__(a: Any, b: Any) -> Any: ... - -if sys.version_info < (3,): - def div(a: Any, b: Any) -> Any: ... - def __div__(a: Any, b: Any) -> Any: ... - def floordiv(__a: Any, __b: Any) -> Any: ... def __floordiv__(a: Any, b: Any) -> Any: ... def index(__a: Any) -> int: ... @@ -60,11 +54,8 @@ def mod(__a: Any, __b: Any) -> Any: ... def __mod__(a: Any, b: Any) -> Any: ... def mul(__a: Any, __b: Any) -> Any: ... def __mul__(a: Any, b: Any) -> Any: ... - -if sys.version_info >= (3, 5): - def matmul(__a: Any, __b: Any) -> Any: ... - def __matmul__(a: Any, b: Any) -> Any: ... - +def matmul(__a: Any, __b: Any) -> Any: ... +def __matmul__(a: Any, b: Any) -> Any: ... def neg(__a: Any) -> Any: ... def __neg__(a: Any) -> Any: ... def or_(__a: Any, __b: Any) -> Any: ... @@ -98,11 +89,6 @@ def __delitem__(a: MutableSequence[Any], b: int) -> None: ... def __delitem__(a: MutableSequence[Any], b: slice) -> None: ... @overload def __delitem__(a: MutableMapping[_K, Any], b: _K) -> None: ... - -if sys.version_info < (3,): - def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ... - def __delslice__(a: MutableSequence[Any], b: int, c: int) -> None: ... - @overload def getitem(__a: Sequence[_T], __b: int) -> _T: ... @overload @@ -115,20 +101,7 @@ def __getitem__(a: Sequence[_T], b: int) -> _T: ... def __getitem__(a: Sequence[_T], b: slice) -> Sequence[_T]: ... @overload def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... - -if sys.version_info < (3,): - def getslice(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... - def __getslice__(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... - def indexOf(__a: Sequence[_T], __b: _T) -> int: ... - -if sys.version_info < (3,): - def repeat(a: Any, b: int) -> Any: ... - def __repeat__(a: Any, b: int) -> Any: ... - -if sys.version_info < (3,): - def sequenceIncludes(a: Container[Any], b: Any) -> bool: ... - @overload def setitem(__a: MutableSequence[_T], __b: int, __c: _T) -> None: ... @overload @@ -141,13 +114,7 @@ def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ... def __setitem__(a: MutableSequence[_T], b: slice, c: Sequence[_T]) -> None: ... @overload def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... - -if sys.version_info < (3,): - def setslice(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... - def __setslice__(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... - -if sys.version_info >= (3, 4): - def length_hint(__obj: Any, __default: int = ...) -> int: ... +def length_hint(__obj: Any, __default: int = ...) -> int: ... class attrgetter(Generic[_T_co]): @overload @@ -185,11 +152,6 @@ def iand(__a: Any, __b: Any) -> Any: ... def __iand__(a: Any, b: Any) -> Any: ... def iconcat(__a: Any, __b: Any) -> Any: ... def __iconcat__(a: Any, b: Any) -> Any: ... - -if sys.version_info < (3,): - def idiv(a: Any, b: Any) -> Any: ... - def __idiv__(a: Any, b: Any) -> Any: ... - def ifloordiv(__a: Any, __b: Any) -> Any: ... def __ifloordiv__(a: Any, b: Any) -> Any: ... def ilshift(__a: Any, __b: Any) -> Any: ... @@ -198,20 +160,12 @@ def imod(__a: Any, __b: Any) -> Any: ... def __imod__(a: Any, b: Any) -> Any: ... def imul(__a: Any, __b: Any) -> Any: ... def __imul__(a: Any, b: Any) -> Any: ... - -if sys.version_info >= (3, 5): - def imatmul(__a: Any, __b: Any) -> Any: ... - def __imatmul__(a: Any, b: Any) -> Any: ... - +def imatmul(__a: Any, __b: Any) -> Any: ... +def __imatmul__(a: Any, b: Any) -> Any: ... def ior(__a: Any, __b: Any) -> Any: ... def __ior__(a: Any, b: Any) -> Any: ... def ipow(__a: Any, __b: Any) -> Any: ... def __ipow__(a: Any, b: Any) -> Any: ... - -if sys.version_info < (3,): - def irepeat(a: Any, b: int) -> Any: ... - def __irepeat__(a: Any, b: int) -> Any: ... - def irshift(__a: Any, __b: Any) -> Any: ... def __irshift__(a: Any, b: Any) -> Any: ... def isub(__a: Any, __b: Any) -> Any: ... @@ -220,9 +174,3 @@ def itruediv(__a: Any, __b: Any) -> Any: ... def __itruediv__(a: Any, b: Any) -> Any: ... def ixor(__a: Any, __b: Any) -> Any: ... def __ixor__(a: Any, b: Any) -> Any: ... - -if sys.version_info < (3,): - def isCallable(x: Any) -> bool: ... - def isMappingType(x: Any) -> bool: ... - def isNumberType(x: Any) -> bool: ... - def isSequenceType(x: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 2229807bc641..ff8ce8ea9f11 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,133 +1,123 @@ -import sys -from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, Union, overload +from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, overload -# See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g -if sys.version_info >= (3,): - _Text = str -else: - _Text = Union[str, unicode] +NO_DEFAULT: Tuple[str, ...] +SUPPRESS_HELP: str +SUPPRESS_USAGE: str -NO_DEFAULT: Tuple[_Text, ...] -SUPPRESS_HELP: _Text -SUPPRESS_USAGE: _Text - -def check_builtin(option: Option, opt: Any, value: _Text) -> Any: ... -def check_choice(option: Option, opt: Any, value: _Text) -> Any: ... - -if sys.version_info < (3,): - def isbasestring(x: Any) -> bool: ... +def check_builtin(option: Option, opt: Any, value: str) -> Any: ... +def check_choice(option: Option, opt: Any, value: str) -> Any: ... class OptParseError(Exception): - msg: _Text - def __init__(self, msg: _Text) -> None: ... + msg: str + def __init__(self, msg: str) -> None: ... class BadOptionError(OptParseError): - opt_str: _Text - def __init__(self, opt_str: _Text) -> None: ... + opt_str: str + def __init__(self, opt_str: str) -> None: ... class AmbiguousOptionError(BadOptionError): - possibilities: Iterable[_Text] - def __init__(self, opt_str: _Text, possibilities: Sequence[_Text]) -> None: ... + possibilities: Iterable[str] + def __init__(self, opt_str: str, possibilities: Sequence[str]) -> None: ... class OptionError(OptParseError): - msg: _Text - option_id: _Text - def __init__(self, msg: _Text, option: Option) -> None: ... + msg: str + option_id: str + def __init__(self, msg: str, option: Option) -> None: ... class OptionConflictError(OptionError): ... class OptionValueError(OptParseError): ... class HelpFormatter: - NO_DEFAULT_VALUE: _Text - _long_opt_fmt: _Text - _short_opt_fmt: _Text + NO_DEFAULT_VALUE: str + _long_opt_fmt: str + _short_opt_fmt: str current_indent: int - default_tag: _Text + default_tag: str help_position: Any help_width: Any indent_increment: int level: int max_help_position: int - option_strings: Dict[Option, _Text] + option_strings: Dict[Option, str] parser: OptionParser short_first: Any width: int def __init__(self, indent_increment: int, max_help_position: int, width: Optional[int], short_first: int) -> None: ... def dedent(self) -> None: ... - def expand_default(self, option: Option) -> _Text: ... - def format_description(self, description: _Text) -> _Text: ... - def format_epilog(self, epilog: _Text) -> _Text: ... - def format_heading(self, heading: Any) -> _Text: ... - def format_option(self, option: Option) -> _Text: ... - def format_option_strings(self, option: Option) -> _Text: ... - def format_usage(self, usage: Any) -> _Text: ... + def expand_default(self, option: Option) -> str: ... + def format_description(self, description: str) -> str: ... + def format_epilog(self, epilog: str) -> str: ... + def format_heading(self, heading: Any) -> str: ... + def format_option(self, option: Option) -> str: ... + def format_option_strings(self, option: Option) -> str: ... + def format_usage(self, usage: Any) -> str: ... def indent(self) -> None: ... - def set_long_opt_delimiter(self, delim: _Text) -> None: ... + def set_long_opt_delimiter(self, delim: str) -> None: ... def set_parser(self, parser: OptionParser) -> None: ... - def set_short_opt_delimiter(self, delim: _Text) -> None: ... + def set_short_opt_delimiter(self, delim: str) -> None: ... def store_option_strings(self, parser: OptionParser) -> None: ... class IndentedHelpFormatter(HelpFormatter): def __init__( self, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ..., short_first: int = ... ) -> None: ... - def format_heading(self, heading: _Text) -> _Text: ... - def format_usage(self, usage: _Text) -> _Text: ... + def format_heading(self, heading: str) -> str: ... + def format_usage(self, usage: str) -> str: ... class TitledHelpFormatter(HelpFormatter): def __init__( self, indent_increment: int = ..., max_help_position: int = ..., width: Optional[int] = ..., short_first: int = ... ) -> None: ... - def format_heading(self, heading: _Text) -> _Text: ... - def format_usage(self, usage: _Text) -> _Text: ... + def format_heading(self, heading: str) -> str: ... + def format_usage(self, usage: str) -> str: ... class Option: - ACTIONS: Tuple[_Text, ...] - ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] - ATTRS: List[_Text] + ACTIONS: Tuple[str, ...] + ALWAYS_TYPED_ACTIONS: Tuple[str, ...] + ATTRS: List[str] CHECK_METHODS: Optional[List[Callable[..., Any]]] - CONST_ACTIONS: Tuple[_Text, ...] - STORE_ACTIONS: Tuple[_Text, ...] - TYPED_ACTIONS: Tuple[_Text, ...] - TYPES: Tuple[_Text, ...] - TYPE_CHECKER: Dict[_Text, Callable[..., Any]] - _long_opts: List[_Text] - _short_opts: List[_Text] - action: _Text - dest: Optional[_Text] + CONST_ACTIONS: Tuple[str, ...] + STORE_ACTIONS: Tuple[str, ...] + TYPED_ACTIONS: Tuple[str, ...] + TYPES: Tuple[str, ...] + TYPE_CHECKER: Dict[str, Callable[..., Any]] + _long_opts: List[str] + _short_opts: List[str] + action: str + dest: Optional[str] default: Any nargs: int type: Any callback: Optional[Callable[..., Any]] callback_args: Optional[Tuple[Any, ...]] - callback_kwargs: Optional[Dict[_Text, Any]] - help: Optional[_Text] - metavar: Optional[_Text] - def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... + callback_kwargs: Optional[Dict[str, Any]] + help: Optional[str] + metavar: Optional[str] + def __init__(self, *opts: Optional[str], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... - def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... + def _check_opt_strings(self, opts: Iterable[Optional[str]]) -> List[str]: ... def _check_type(self) -> None: ... - def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... - def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... - def check_value(self, opt: _Text, value: Any) -> Any: ... - def convert_value(self, opt: _Text, value: Any) -> Any: ... - def get_opt_string(self) -> _Text: ... + def _set_attrs(self, attrs: Dict[str, Any]) -> None: ... + def _set_opt_strings(self, opts: Iterable[str]) -> None: ... + def check_value(self, opt: str, value: Any) -> Any: ... + def convert_value(self, opt: str, value: Any) -> Any: ... + def get_opt_string(self) -> str: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... - def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def take_action(self, action: str, dest: str, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... make_option = Option class OptionContainer: - _long_opt: Dict[_Text, Option] - _short_opt: Dict[_Text, Option] - conflict_handler: _Text - defaults: Dict[_Text, Any] + _long_opt: Dict[str, Option] + _short_opt: Dict[str, Option] + conflict_handler: str + defaults: Dict[str, Any] description: Any option_class: Type[Option] def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... @@ -137,64 +127,64 @@ class OptionContainer: @overload def add_option(self, opt: Option) -> Option: ... @overload - def add_option(self, *args: Optional[_Text], **kwargs: Any) -> Any: ... + def add_option(self, *args: Optional[str], **kwargs: Any) -> Any: ... def add_options(self, option_list: Iterable[Option]) -> None: ... def destroy(self) -> None: ... def format_description(self, formatter: Optional[HelpFormatter]) -> Any: ... - def format_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... - def format_option_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... + def format_help(self, formatter: Optional[HelpFormatter]) -> str: ... + def format_option_help(self, formatter: Optional[HelpFormatter]) -> str: ... def get_description(self) -> Any: ... - def get_option(self, opt_str: _Text) -> Optional[Option]: ... - def has_option(self, opt_str: _Text) -> bool: ... - def remove_option(self, opt_str: _Text) -> None: ... + def get_option(self, opt_str: str) -> Optional[Option]: ... + def has_option(self, opt_str: str) -> bool: ... + def remove_option(self, opt_str: str) -> None: ... def set_conflict_handler(self, handler: Any) -> None: ... def set_description(self, description: Any) -> None: ... class OptionGroup(OptionContainer): option_list: List[Option] parser: OptionParser - title: _Text - def __init__(self, parser: OptionParser, title: _Text, description: Optional[_Text] = ...) -> None: ... + title: str + def __init__(self, parser: OptionParser, title: str, description: Optional[str] = ...) -> None: ... def _create_option_list(self) -> None: ... - def set_title(self, title: _Text) -> None: ... + def set_title(self, title: str) -> None: ... class Values: def __init__(self, defaults: Optional[Mapping[str, Any]] = ...) -> None: ... - def _update(self, dict: Mapping[_Text, Any], mode: Any) -> None: ... - def _update_careful(self, dict: Mapping[_Text, Any]) -> None: ... - def _update_loose(self, dict: Mapping[_Text, Any]) -> None: ... - def ensure_value(self, attr: _Text, value: Any) -> Any: ... - def read_file(self, filename: _Text, mode: _Text = ...) -> None: ... - def read_module(self, modname: _Text, mode: _Text = ...) -> None: ... + def _update(self, dict: Mapping[str, Any], mode: Any) -> None: ... + def _update_careful(self, dict: Mapping[str, Any]) -> None: ... + def _update_loose(self, dict: Mapping[str, Any]) -> None: ... + def ensure_value(self, attr: str, value: Any) -> Any: ... + def read_file(self, filename: str, mode: str = ...) -> None: ... + def read_module(self, modname: str, mode: str = ...) -> None: ... def __getattr__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... class OptionParser(OptionContainer): allow_interspersed_args: bool - epilog: Optional[_Text] + epilog: Optional[str] formatter: HelpFormatter - largs: Optional[List[_Text]] + largs: Optional[List[str]] option_groups: List[OptionGroup] option_list: List[Option] process_default_values: Any - prog: Optional[_Text] + prog: Optional[str] rargs: Optional[List[Any]] standard_option_list: List[Option] - usage: Optional[_Text] + usage: Optional[str] values: Optional[Values] - version: _Text + version: str def __init__( self, - usage: Optional[_Text] = ..., + usage: Optional[str] = ..., option_list: Optional[Iterable[Option]] = ..., option_class: Type[Option] = ..., - version: Optional[_Text] = ..., - conflict_handler: _Text = ..., - description: Optional[_Text] = ..., + version: Optional[str] = ..., + conflict_handler: str = ..., + description: Optional[str] = ..., formatter: Optional[HelpFormatter] = ..., add_help_option: bool = ..., - prog: Optional[_Text] = ..., - epilog: Optional[_Text] = ..., + prog: Optional[str] = ..., + epilog: Optional[str] = ..., ) -> None: ... def _add_help_option(self) -> None: ... def _add_version_option(self) -> None: ... @@ -202,7 +192,7 @@ class OptionParser(OptionContainer): def _get_all_options(self) -> List[Option]: ... def _get_args(self, args: Iterable[Any]) -> List[Any]: ... def _init_parsing_state(self) -> None: ... - def _match_long_opt(self, opt: _Text) -> _Text: ... + def _match_long_opt(self, opt: str) -> str: ... def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... def _process_args(self, largs: List[Any], rargs: List[Any], values: Values) -> None: ... def _process_long_opt(self, rargs: List[Any], values: Any) -> None: ... @@ -211,20 +201,20 @@ class OptionParser(OptionContainer): def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... @overload def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... - def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... + def check_values(self, values: Values, args: List[str]) -> Tuple[Values, List[str]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... - def error(self, msg: _Text) -> None: ... + def error(self, msg: str) -> None: ... def exit(self, status: int = ..., msg: Optional[str] = ...) -> None: ... - def expand_prog_name(self, s: Optional[_Text]) -> Any: ... + def expand_prog_name(self, s: Optional[str]) -> Any: ... def format_epilog(self, formatter: HelpFormatter) -> Any: ... - def format_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... - def format_option_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... + def format_help(self, formatter: Optional[HelpFormatter] = ...) -> str: ... + def format_option_help(self, formatter: Optional[HelpFormatter] = ...) -> str: ... def get_default_values(self) -> Values: ... - def get_option_group(self, opt_str: _Text) -> Any: ... - def get_prog_name(self) -> _Text: ... - def get_usage(self) -> _Text: ... - def get_version(self) -> _Text: ... + def get_option_group(self, opt_str: str) -> Any: ... + def get_prog_name(self) -> str: ... + def get_usage(self) -> str: ... + def get_version(self) -> str: ... def parse_args( self, args: Optional[Sequence[AnyStr]] = ..., values: Optional[Values] = ... ) -> Tuple[Values, List[AnyStr]]: ... @@ -234,4 +224,4 @@ class OptionParser(OptionContainer): def set_default(self, dest: Any, value: Any) -> None: ... def set_defaults(self, **kwargs: Any) -> None: ... def set_process_default_values(self, process: Any) -> None: ... - def set_usage(self, usage: _Text) -> None: ... + def set_usage(self, usage: str) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 4500a748d574..5de46ca031d7 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1,12 +1,13 @@ import sys from _typeshed import ( - AnyPath, FileDescriptorLike, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, + StrOrBytesPath, + StrPath, ) from builtins import OSError from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper @@ -310,7 +311,7 @@ class stat_result: class PathLike(Protocol[_AnyStr_co]): def __fspath__(self) -> _AnyStr_co: ... -_FdOrAnyPath = Union[int, AnyPath] +_FdOrAnyPath = Union[int, StrOrBytesPath] class DirEntry(Generic[AnyStr]): # This is what the scandir interator yields @@ -367,8 +368,8 @@ if sys.platform != "win32": f_namemax: int # ----- os function stubs ----- -def fsencode(filename: Union[str, bytes, PathLike[Any]]) -> bytes: ... -def fsdecode(filename: Union[str, bytes, PathLike[Any]]) -> str: ... +def fsencode(filename: StrOrBytesPath) -> bytes: ... +def fsdecode(filename: StrOrBytesPath) -> str: ... @overload def fspath(path: str) -> str: ... @overload @@ -527,7 +528,7 @@ else: def fstat(fd: int) -> stat_result: ... def fsync(fd: FileDescriptorLike) -> None: ... def lseek(__fd: int, __position: int, __how: int) -> int: ... -def open(path: AnyPath, flags: int, mode: int = ..., *, dir_fd: Optional[int] = ...) -> int: ... +def open(path: StrOrBytesPath, flags: int, mode: int = ..., *, dir_fd: Optional[int] = ...) -> int: ... def pipe() -> Tuple[int, int]: ... def read(__fd: int, __length: int) -> bytes: ... @@ -594,43 +595,52 @@ def getcwdb() -> bytes: ... def chmod(path: _FdOrAnyPath, mode: int, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> None: ... if sys.platform != "win32": - def chflags(path: AnyPath, flags: int, follow_symlinks: bool = ...) -> None: ... # some flavors of Unix + def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = ...) -> None: ... # some flavors of Unix def chown( path: _FdOrAnyPath, uid: int, gid: int, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ... ) -> None: ... # Unix only if sys.platform != "win32": # Unix only - def chroot(path: AnyPath) -> None: ... - def lchflags(path: AnyPath, flags: int) -> None: ... - def lchmod(path: AnyPath, mode: int) -> None: ... - def lchown(path: AnyPath, uid: int, gid: int) -> None: ... + def chroot(path: StrOrBytesPath) -> None: ... + def lchflags(path: StrOrBytesPath, flags: int) -> None: ... + def lchmod(path: StrOrBytesPath, mode: int) -> None: ... + def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: ... def link( - src: AnyPath, dst: AnyPath, *, src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ..., follow_symlinks: bool = ... + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: Optional[int] = ..., + dst_dir_fd: Optional[int] = ..., + follow_symlinks: bool = ..., ) -> None: ... -def lstat(path: AnyPath, *, dir_fd: Optional[int] = ...) -> stat_result: ... -def mkdir(path: AnyPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... +def lstat(path: StrOrBytesPath, *, dir_fd: Optional[int] = ...) -> stat_result: ... +def mkdir(path: StrOrBytesPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... if sys.platform != "win32": - def mkfifo(path: AnyPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... # Unix only + def mkfifo(path: StrOrBytesPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... # Unix only -def makedirs(name: AnyPath, mode: int = ..., exist_ok: bool = ...) -> None: ... +def makedirs(name: StrOrBytesPath, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.platform != "win32": - def mknod(path: AnyPath, mode: int = ..., device: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... + def mknod(path: StrOrBytesPath, mode: int = ..., device: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... def major(__device: int) -> int: ... def minor(__device: int) -> int: ... def makedev(__major: int, __minor: int) -> int: ... def pathconf(path: _FdOrAnyPath, name: Union[str, int]) -> int: ... # Unix only def readlink(path: Union[AnyStr, PathLike[AnyStr]], *, dir_fd: Optional[int] = ...) -> AnyStr: ... -def remove(path: AnyPath, *, dir_fd: Optional[int] = ...) -> None: ... -def removedirs(name: AnyPath) -> None: ... -def rename(src: AnyPath, dst: AnyPath, *, src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ...) -> None: ... -def renames(old: AnyPath, new: AnyPath) -> None: ... -def replace(src: AnyPath, dst: AnyPath, *, src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ...) -> None: ... -def rmdir(path: AnyPath, *, dir_fd: Optional[int] = ...) -> None: ... +def remove(path: StrOrBytesPath, *, dir_fd: Optional[int] = ...) -> None: ... +def removedirs(name: StrOrBytesPath) -> None: ... +def rename( + src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ... +) -> None: ... +def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: ... +def replace( + src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ... +) -> None: ... +def rmdir(path: StrOrBytesPath, *, dir_fd: Optional[int] = ...) -> None: ... class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): def __next__(self) -> DirEntry[AnyStr]: ... @@ -661,13 +671,15 @@ if sys.version_info < (3, 7): if sys.platform != "win32": def statvfs(path: _FdOrAnyPath) -> statvfs_result: ... # Unix only -def symlink(src: AnyPath, dst: AnyPath, target_is_directory: bool = ..., *, dir_fd: Optional[int] = ...) -> None: ... +def symlink( + src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = ..., *, dir_fd: Optional[int] = ... +) -> None: ... if sys.platform != "win32": def sync() -> None: ... # Unix only def truncate(path: _FdOrAnyPath, length: int) -> None: ... # Unix only up to version 3.4 -def unlink(path: AnyPath, *, dir_fd: Optional[int] = ...) -> None: ... +def unlink(path: StrOrBytesPath, *, dir_fd: Optional[int] = ...) -> None: ... def utime( path: _FdOrAnyPath, times: Optional[Union[Tuple[int, int], Tuple[float, float]]] = ..., @@ -687,7 +699,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 7): @overload def fwalk( - top: Union[str, PathLike[str]] = ..., + top: StrPath = ..., topdown: bool = ..., onerror: Optional[_OnError] = ..., *, @@ -705,7 +717,7 @@ if sys.platform != "win32": ) -> Iterator[Tuple[bytes, List[bytes], List[bytes], int]]: ... else: def fwalk( - top: Union[str, PathLike[str]] = ..., + top: StrPath = ..., topdown: bool = ..., onerror: Optional[_OnError] = ..., *, @@ -713,22 +725,22 @@ if sys.platform != "win32": dir_fd: Optional[int] = ..., ) -> Iterator[Tuple[str, List[str], List[str], int]]: ... if sys.platform == "linux": - def getxattr(path: _FdOrAnyPath, attribute: AnyPath, *, follow_symlinks: bool = ...) -> bytes: ... + def getxattr(path: _FdOrAnyPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = ...) -> bytes: ... def listxattr(path: Optional[_FdOrAnyPath] = ..., *, follow_symlinks: bool = ...) -> List[str]: ... - def removexattr(path: _FdOrAnyPath, attribute: AnyPath, *, follow_symlinks: bool = ...) -> None: ... + def removexattr(path: _FdOrAnyPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... def setxattr( - path: _FdOrAnyPath, attribute: AnyPath, value: bytes, flags: int = ..., *, follow_symlinks: bool = ... + path: _FdOrAnyPath, attribute: StrOrBytesPath, value: bytes, flags: int = ..., *, follow_symlinks: bool = ... ) -> None: ... def abort() -> NoReturn: ... # These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: AnyPath, __arg0: AnyPath, *args: AnyPath) -> NoReturn: ... -def execlp(file: AnyPath, __arg0: AnyPath, *args: AnyPath) -> NoReturn: ... +def execl(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... +def execlp(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: StrOrBytesPath) -> NoReturn: ... # These are: execle(file, *args, env) but env is pulled from the last element of the args. -def execle(file: AnyPath, __arg0: AnyPath, *args: Any) -> NoReturn: ... -def execlpe(file: AnyPath, __arg0: AnyPath, *args: Any) -> NoReturn: ... +def execle(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoReturn: ... +def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoReturn: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. @@ -736,7 +748,7 @@ def execlpe(file: AnyPath, __arg0: AnyPath, *args: Any) -> NoReturn: ... # in practice, and doing so would explode the number of combinations in this already long union. # All these combinations are necessary due to List being invariant. _ExecVArgs = Union[ - Tuple[AnyPath, ...], + Tuple[StrOrBytesPath, ...], List[bytes], List[str], List[PathLike[Any]], @@ -747,10 +759,10 @@ _ExecVArgs = Union[ ] _ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] -def execv(__path: AnyPath, __argv: _ExecVArgs) -> NoReturn: ... +def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... def execve(path: _FdOrAnyPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... -def execvp(file: AnyPath, args: _ExecVArgs) -> NoReturn: ... -def execvpe(file: AnyPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... +def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: ... +def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... def _exit(status: int) -> NoReturn: ... def kill(__pid: int, __signal: int) -> None: ... @@ -768,30 +780,30 @@ class _wrap_close(_TextIOWrapper): def close(self) -> Optional[int]: ... # type: ignore def popen(cmd: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... -def spawnl(mode: int, file: AnyPath, arg0: AnyPath, *args: AnyPath) -> int: ... -def spawnle(mode: int, file: AnyPath, arg0: AnyPath, *args: Any) -> int: ... # Imprecise sig +def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... +def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig if sys.platform != "win32": - def spawnv(mode: int, file: AnyPath, args: _ExecVArgs) -> int: ... - def spawnve(mode: int, file: AnyPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... + def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... else: - def spawnv(__mode: int, __path: AnyPath, __argv: _ExecVArgs) -> int: ... - def spawnve(__mode: int, __path: AnyPath, __argv: _ExecVArgs, __env: _ExecEnv) -> int: ... + def spawnv(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs) -> int: ... + def spawnve(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs, __env: _ExecEnv) -> int: ... -def system(command: AnyPath) -> int: ... +def system(command: StrOrBytesPath) -> int: ... def times() -> times_result: ... def waitpid(__pid: int, __options: int) -> Tuple[int, int]: ... if sys.platform == "win32": - def startfile(path: AnyPath, operation: Optional[str] = ...) -> None: ... + def startfile(path: StrOrBytesPath, operation: Optional[str] = ...) -> None: ... else: # Unix only - def spawnlp(mode: int, file: AnyPath, arg0: AnyPath, *args: AnyPath) -> int: ... - def spawnlpe(mode: int, file: AnyPath, arg0: AnyPath, *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: AnyPath, args: _ExecVArgs) -> int: ... - def spawnvpe(mode: int, file: AnyPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... + def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... + def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature + def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... def wait() -> Tuple[int, int]: ... # Unix only if sys.platform != "darwin": from posix import waitid_result diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index 799f25cf6a48..1ad59da024f2 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,21 +1,21 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import CodeType -from typing import Any, List, Sequence, Text, Tuple +from typing import Any, List, Sequence, Tuple -def expr(source: Text) -> STType: ... -def suite(source: Text) -> STType: ... +def expr(source: str) -> STType: ... +def suite(source: str) -> STType: ... def sequence2st(sequence: Sequence[Any]) -> STType: ... def tuple2st(sequence: Sequence[Any]) -> STType: ... def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... -def compilest(st: STType, filename: AnyPath = ...) -> CodeType: ... +def compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: ... def isexpr(st: STType) -> bool: ... def issuite(st: STType) -> bool: ... class ParserError(Exception): ... class STType: - def compile(self, filename: AnyPath = ...) -> CodeType: ... + def compile(self, filename: StrOrBytesPath = ...) -> CodeType: ... def isexpr(self) -> bool: ... def issuite(self) -> bool: ... def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index 2750e9ea0f4b..ac25b368d6c6 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -45,34 +45,15 @@ class Pdb(Bdb, Cmd): curindex: int curframe: Optional[FrameType] curframe_locals: Mapping[str, Any] - - if sys.version_info >= (3, 6): - def __init__( - self, - completekey: str = ..., - stdin: Optional[IO[str]] = ..., - stdout: Optional[IO[str]] = ..., - skip: Optional[Iterable[str]] = ..., - nosigint: bool = ..., - readrc: bool = ..., - ) -> None: ... - elif sys.version_info >= (3, 2): - def __init__( - self, - completekey: str = ..., - stdin: Optional[IO[str]] = ..., - stdout: Optional[IO[str]] = ..., - skip: Optional[Iterable[str]] = ..., - nosigint: bool = ..., - ) -> None: ... - else: - def __init__( - self, - completekey: str = ..., - stdin: Optional[IO[str]] = ..., - stdout: Optional[IO[str]] = ..., - skip: Optional[Iterable[str]] = ..., - ) -> None: ... + def __init__( + self, + completekey: str = ..., + stdin: Optional[IO[str]] = ..., + stdout: Optional[IO[str]] = ..., + skip: Optional[Iterable[str]] = ..., + nosigint: bool = ..., + readrc: bool = ..., + ) -> None: ... def forget(self) -> None: ... def setup(self, f: Optional[FrameType], tb: Optional[TracebackType]) -> None: ... def execRcLines(self) -> None: ... @@ -140,111 +121,54 @@ class Pdb(Bdb, Cmd): do_h = do_help def help_exec(self) -> None: ... def help_pdb(self) -> None: ... - if sys.version_info < (3, 2): - def help_help(self) -> None: ... - def help_h(self) -> None: ... - def help_where(self) -> None: ... - def help_w(self) -> None: ... - def help_down(self) -> None: ... - def help_d(self) -> None: ... - def help_up(self) -> None: ... - def help_u(self) -> None: ... - def help_break(self) -> None: ... - def help_b(self) -> None: ... - def help_clear(self) -> None: ... - def help_cl(self) -> None: ... - def help_tbreak(self) -> None: ... - def help_enable(self) -> None: ... - def help_disable(self) -> None: ... - def help_ignore(self) -> None: ... - def help_condition(self) -> None: ... - def help_step(self) -> None: ... - def help_s(self) -> None: ... - def help_until(self) -> None: ... - def help_unt(self) -> None: ... - def help_next(self) -> None: ... - def help_n(self) -> None: ... - def help_return(self) -> None: ... - def help_r(self) -> None: ... - def help_continue(self) -> None: ... - def help_cont(self) -> None: ... - def help_c(self) -> None: ... - def help_jump(self) -> None: ... - def help_j(self) -> None: ... - def help_debug(self) -> None: ... - def help_list(self) -> None: ... - def help_l(self) -> None: ... - def help_args(self) -> None: ... - def help_a(self) -> None: ... - def help_p(self) -> None: ... - def help_pp(self) -> None: ... - def help_run(self) -> None: ... - def help_quit(self) -> None: ... - def help_q(self) -> None: ... - def help_whatis(self) -> None: ... - def help_EOF(self) -> None: ... - def help_alias(self) -> None: ... - def help_unalias(self) -> None: ... - def help_commands(self) -> None: ... - help_bt = help_w - help_restart = help_run - help_exit = help_q - - if sys.version_info >= (3, 2): - def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... - def message(self, msg: str) -> None: ... - def error(self, msg: str) -> None: ... - def _select_frame(self, number: int) -> None: ... - def _getval_except(self, arg: str, frame: Optional[FrameType] = ...) -> object: ... - def _print_lines( - self, lines: Sequence[str], start: int, breaks: Sequence[int] = ..., frame: Optional[FrameType] = ... - ) -> None: ... - def _cmdloop(self) -> None: ... - def do_display(self, arg: str) -> Optional[bool]: ... - def do_interact(self, arg: str) -> Optional[bool]: ... - def do_longlist(self, arg: str) -> Optional[bool]: ... - def do_source(self, arg: str) -> Optional[bool]: ... - def do_undisplay(self, arg: str) -> Optional[bool]: ... - do_ll = do_longlist - - if sys.version_info >= (3, 3): - def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... - def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... - def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... - def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... - def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... - complete_commands = _complete_bpnumber - complete_break = _complete_location - complete_b = _complete_location - complete_tbreak = _complete_location - complete_enable = _complete_bpnumber - complete_disable = _complete_bpnumber - complete_condition = _complete_bpnumber - complete_ignore = _complete_bpnumber - complete_clear = _complete_location - complete_cl = _complete_location - complete_debug = _complete_expression - complete_print = _complete_expression - complete_p = _complete_expression - complete_pp = _complete_expression - complete_source = _complete_expression - complete_whatis = _complete_expression - complete_display = _complete_expression + def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... + def message(self, msg: str) -> None: ... + def error(self, msg: str) -> None: ... + def _select_frame(self, number: int) -> None: ... + def _getval_except(self, arg: str, frame: Optional[FrameType] = ...) -> object: ... + def _print_lines( + self, lines: Sequence[str], start: int, breaks: Sequence[int] = ..., frame: Optional[FrameType] = ... + ) -> None: ... + def _cmdloop(self) -> None: ... + def do_display(self, arg: str) -> Optional[bool]: ... + def do_interact(self, arg: str) -> Optional[bool]: ... + def do_longlist(self, arg: str) -> Optional[bool]: ... + def do_source(self, arg: str) -> Optional[bool]: ... + def do_undisplay(self, arg: str) -> Optional[bool]: ... + do_ll = do_longlist + def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... + def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... + def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... + def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... + def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... + complete_commands = _complete_bpnumber + complete_break = _complete_location + complete_b = _complete_location + complete_tbreak = _complete_location + complete_enable = _complete_bpnumber + complete_disable = _complete_bpnumber + complete_condition = _complete_bpnumber + complete_ignore = _complete_bpnumber + complete_clear = _complete_location + complete_cl = _complete_location + complete_debug = _complete_expression + complete_print = _complete_expression + complete_p = _complete_expression + complete_pp = _complete_expression + complete_source = _complete_expression + complete_whatis = _complete_expression + complete_display = _complete_expression if sys.version_info >= (3, 7): def _runmodule(self, module_name: str) -> None: ... - if sys.version_info >= (3,) and sys.version_info < (3, 4): - do_print = do_p # undocumented def find_function(funcname: str, filename: str) -> Optional[Tuple[str, str, int]]: ... def main() -> None: ... def help() -> None: ... - -if sys.version_info >= (3, 2): - def getsourcelines(obj: _SourceObjectType) -> Tuple[List[str], int]: ... - def lasti2lineno(code: CodeType, lasti: int) -> int: ... +def getsourcelines(obj: _SourceObjectType) -> Tuple[List[str], int]: ... +def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): def __repr__(self) -> _rstr: ... diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index ddf8a4401399..e9dc2c68979f 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,9 +1,8 @@ import sys -from typing import IO, Any, Callable, Iterable, Iterator, Mapping, Optional, Tuple, Type, Union +from typing import IO, Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Tuple, Type, Union HIGHEST_PROTOCOL: int -if sys.version_info >= (3, 0): - DEFAULT_PROTOCOL: int +DEFAULT_PROTOCOL: int bytes_types: Tuple[Type[Any], ...] # undocumented @@ -38,18 +37,12 @@ if sys.version_info >= (3, 8): __data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ..., buffers: Optional[Iterable[Any]] = ... ) -> Any: ... -elif sys.version_info >= (3, 0): +else: def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ..., *, fix_imports: bool = ...) -> None: ... def dumps(obj: Any, protocol: Optional[int] = ..., *, fix_imports: bool = ...) -> bytes: ... def load(file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... def loads(data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... -else: - def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... - def dumps(obj: Any, protocol: Optional[int] = ...) -> bytes: ... - def load(file: IO[bytes]) -> Any: ... - def loads(string: bytes) -> Any: ... - class PickleError(Exception): ... class PicklingError(PickleError): ... class UnpicklingError(PickleError): ... @@ -64,8 +57,8 @@ _reducedtype = Union[ class Pickler: fast: bool - if sys.version_info >= (3, 3): - dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] + dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] + dispatch: ClassVar[dict[type, Callable[[Unpickler, Any], None]]] # undocumented, _Pickler only if sys.version_info >= (3, 8): def __init__( @@ -77,15 +70,15 @@ class Pickler: buffer_callback: _BufferCallback = ..., ) -> None: ... def reducer_override(self, obj: Any) -> Any: ... - elif sys.version_info >= (3, 0): - def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *, fix_imports: bool = ...) -> None: ... else: - def __init__(self, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... + def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *, fix_imports: bool = ...) -> None: ... def dump(self, __obj: Any) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... class Unpickler: + dispatch: ClassVar[dict[int, Callable[[Unpickler], None]]] # undocumented, _Unpickler only + if sys.version_info >= (3, 8): def __init__( self, @@ -96,14 +89,11 @@ class Unpickler: errors: str = ..., buffers: Optional[Iterable[Any]] = ..., ) -> None: ... - elif sys.version_info >= (3, 0): - def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> None: ... else: - def __init__(self, file: IO[bytes]) -> None: ... + def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> None: ... def load(self) -> Any: ... def find_class(self, __module_name: str, __global_name: str) -> Any: ... - if sys.version_info >= (3, 0): - def persistent_load(self, pid: Any) -> Any: ... + def persistent_load(self, pid: Any) -> Any: ... MARK: bytes STOP: bytes @@ -164,23 +154,25 @@ NEWFALSE: bytes LONG1: bytes LONG4: bytes -if sys.version_info >= (3, 0): - # protocol 3 - BINBYTES: bytes - SHORT_BINBYTES: bytes - -if sys.version_info >= (3, 4): - # protocol 4 - SHORT_BINUNICODE: bytes - BINUNICODE8: bytes - BINBYTES8: bytes - EMPTY_SET: bytes - ADDITEMS: bytes - FROZENSET: bytes - NEWOBJ_EX: bytes - STACK_GLOBAL: bytes - MEMOIZE: bytes - FRAME: bytes +# protocol 3 +BINBYTES: bytes +SHORT_BINBYTES: bytes + +# protocol 4 +SHORT_BINUNICODE: bytes +BINUNICODE8: bytes +BINBYTES8: bytes +EMPTY_SET: bytes +ADDITEMS: bytes +FROZENSET: bytes +NEWOBJ_EX: bytes +STACK_GLOBAL: bytes +MEMOIZE: bytes +FRAME: bytes def encode_long(x: int) -> bytes: ... # undocumented def decode_long(data: bytes) -> int: ... # undocumented + +# pure-Python implementations +_Pickler = Pickler # undocumented +_Unpickler = Unpickler # undocumented diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index ec279524bc50..59c06624a6d5 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,18 +1,13 @@ -import sys -from typing import IO, Any, Callable, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Iterator, List, MutableMapping, Optional, Tuple, Type, Union _Reader = Callable[[IO[bytes]], Any] - -if sys.version_info >= (3, 0): - bytes_types: Tuple[Type[Any], ...] +bytes_types: Tuple[Type[Any], ...] UP_TO_NEWLINE: int TAKEN_FROM_ARGUMENT1: int TAKEN_FROM_ARGUMENT4: int -if sys.version_info >= (3, 3): - TAKEN_FROM_ARGUMENT4U: int -if sys.version_info >= (3, 4): - TAKEN_FROM_ARGUMENT8U: int +TAKEN_FROM_ARGUMENT4U: int +TAKEN_FROM_ARGUMENT8U: int class ArgumentDescriptor(object): name: str @@ -33,15 +28,15 @@ def read_int4(f: IO[bytes]) -> int: ... int4: ArgumentDescriptor -if sys.version_info >= (3, 3): - def read_uint4(f: IO[bytes]) -> int: ... - uint4: ArgumentDescriptor +def read_uint4(f: IO[bytes]) -> int: ... + +uint4: ArgumentDescriptor -if sys.version_info >= (3, 5): - def read_uint8(f: IO[bytes]) -> int: ... - uint8: ArgumentDescriptor +def read_uint8(f: IO[bytes]) -> int: ... -def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> Union[bytes, Text]: ... +uint8: ArgumentDescriptor + +def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> Union[bytes, str]: ... stringnl: ArgumentDescriptor @@ -49,7 +44,7 @@ def read_stringnl_noescape(f: IO[bytes]) -> str: ... stringnl_noescape: ArgumentDescriptor -def read_stringnl_noescape_pair(f: IO[bytes]) -> Text: ... +def read_stringnl_noescape_pair(f: IO[bytes]) -> str: ... stringnl_noescape_pair: ArgumentDescriptor @@ -61,31 +56,33 @@ def read_string4(f: IO[bytes]) -> str: ... string4: ArgumentDescriptor -if sys.version_info >= (3, 3): - def read_bytes1(f: IO[bytes]) -> bytes: ... - bytes1: ArgumentDescriptor - def read_bytes4(f: IO[bytes]) -> bytes: ... - bytes4: ArgumentDescriptor +def read_bytes1(f: IO[bytes]) -> bytes: ... + +bytes1: ArgumentDescriptor + +def read_bytes4(f: IO[bytes]) -> bytes: ... + +bytes4: ArgumentDescriptor + +def read_bytes8(f: IO[bytes]) -> bytes: ... -if sys.version_info >= (3, 4): - def read_bytes8(f: IO[bytes]) -> bytes: ... - bytes8: ArgumentDescriptor +bytes8: ArgumentDescriptor -def read_unicodestringnl(f: IO[bytes]) -> Text: ... +def read_unicodestringnl(f: IO[bytes]) -> str: ... unicodestringnl: ArgumentDescriptor -if sys.version_info >= (3, 4): - def read_unicodestring1(f: IO[bytes]) -> Text: ... - unicodestring1: ArgumentDescriptor +def read_unicodestring1(f: IO[bytes]) -> str: ... -def read_unicodestring4(f: IO[bytes]) -> Text: ... +unicodestring1: ArgumentDescriptor + +def read_unicodestring4(f: IO[bytes]) -> str: ... unicodestring4: ArgumentDescriptor -if sys.version_info >= (3, 4): - def read_unicodestring8(f: IO[bytes]) -> Text: ... - unicodestring8: ArgumentDescriptor +def read_unicodestring8(f: IO[bytes]) -> str: ... + +unicodestring8: ArgumentDescriptor def read_decimalnl_short(f: IO[bytes]) -> int: ... def read_decimalnl_long(f: IO[bytes]) -> int: ... @@ -120,19 +117,16 @@ pylong: StackObject pyinteger_or_bool: StackObject pybool: StackObject pyfloat: StackObject -if sys.version_info >= (3, 4): - pybytes_or_str: StackObject +pybytes_or_str: StackObject pystring: StackObject -if sys.version_info >= (3, 0): - pybytes: StackObject +pybytes: StackObject pyunicode: StackObject pynone: StackObject pytuple: StackObject pylist: StackObject pydict: StackObject -if sys.version_info >= (3, 4): - pyset: StackObject - pyfrozenset: StackObject +pyset: StackObject +pyfrozenset: StackObject anyobject: StackObject markobject: StackObject stackslice: StackObject @@ -160,20 +154,10 @@ opcodes: List[OpcodeInfo] def genops(pickle: Union[bytes, IO[bytes]]) -> Iterator[Tuple[OpcodeInfo, Optional[Any], Optional[int]]]: ... def optimize(p: Union[bytes, IO[bytes]]) -> bytes: ... - -if sys.version_info >= (3, 2): - def dis( - pickle: Union[bytes, IO[bytes]], - out: Optional[IO[str]] = ..., - memo: Optional[MutableMapping[int, Any]] = ..., - indentlevel: int = ..., - annotate: int = ..., - ) -> None: ... - -else: - def dis( - pickle: Union[bytes, IO[bytes]], - out: Optional[IO[str]] = ..., - memo: Optional[MutableMapping[int, Any]] = ..., - indentlevel: int = ..., - ) -> None: ... +def dis( + pickle: Union[bytes, IO[bytes]], + out: Optional[IO[str]] = ..., + memo: Optional[MutableMapping[int, Any]] = ..., + indentlevel: int = ..., + annotate: int = ..., +) -> None: ... diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 0935e922562e..583b262d44a2 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,22 +1,12 @@ import sys from _typeshed import SupportsRead +from importlib.abc import Loader, MetaPathFinder, PathEntryFinder from typing import IO, Any, Callable, Iterable, Iterator, List, NamedTuple, Optional, Tuple, Union -if sys.version_info >= (3,): - from importlib.abc import Loader, MetaPathFinder, PathEntryFinder -else: - Loader = Any - MetaPathFinder = Any - PathEntryFinder = Any - -if sys.version_info >= (3, 6): - class ModuleInfo(NamedTuple): - module_finder: Union[MetaPathFinder, PathEntryFinder] - name: str - ispkg: bool - _ModuleInfoLike = ModuleInfo -else: - _ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] +class ModuleInfo(NamedTuple): + module_finder: Union[MetaPathFinder, PathEntryFinder] + name: str + ispkg: bool def extend_path(path: List[str], name: str) -> List[str]: ... @@ -30,11 +20,11 @@ def find_loader(fullname: str) -> Optional[Loader]: ... def get_importer(path_item: str) -> Optional[PathEntryFinder]: ... def get_loader(module_or_name: str) -> Loader: ... def iter_importers(fullname: str = ...) -> Iterator[Union[MetaPathFinder, PathEntryFinder]]: ... -def iter_modules(path: Optional[Iterable[str]] = ..., prefix: str = ...) -> Iterator[_ModuleInfoLike]: ... +def iter_modules(path: Optional[Iterable[str]] = ..., prefix: str = ...) -> Iterator[ModuleInfo]: ... def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented def walk_packages( path: Optional[Iterable[str]] = ..., prefix: str = ..., onerror: Optional[Callable[[str], None]] = ... -) -> Iterator[_ModuleInfoLike]: ... +) -> Iterator[ModuleInfo]: ... def get_data(package: str, resource: str) -> Optional[bytes]: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 5aadae9fc97b..c74d0d8d5951 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -1,21 +1,19 @@ import sys -from typing import IO, Any, Dict as DictT, Mapping, MutableMapping, Optional, Text, Type, Union +from enum import Enum +from typing import IO, Any, Dict as DictT, Mapping, MutableMapping, Optional, Type, Union -if sys.version_info >= (3,): - from enum import Enum - class PlistFormat(Enum): - FMT_XML: int - FMT_BINARY: int - FMT_XML = PlistFormat.FMT_XML - FMT_BINARY = PlistFormat.FMT_BINARY +class PlistFormat(Enum): + FMT_XML: int + FMT_BINARY: int -_Path = Union[str, Text] +FMT_XML = PlistFormat.FMT_XML +FMT_BINARY = PlistFormat.FMT_BINARY if sys.version_info >= (3, 9): def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... -elif sys.version_info >= (3, 4): +else: def load( fp: IO[bytes], *, @@ -31,24 +29,17 @@ elif sys.version_info >= (3, 4): dict_type: Type[MutableMapping[str, Any]] = ..., ) -> Any: ... -if sys.version_info >= (3, 4): - def dump( - value: Mapping[str, Any], fp: IO[bytes], *, fmt: PlistFormat = ..., sort_keys: bool = ..., skipkeys: bool = ... - ) -> None: ... - def dumps(value: Mapping[str, Any], *, fmt: PlistFormat = ..., skipkeys: bool = ..., sort_keys: bool = ...) -> bytes: ... +def dump( + value: Mapping[str, Any], fp: IO[bytes], *, fmt: PlistFormat = ..., sort_keys: bool = ..., skipkeys: bool = ... +) -> None: ... +def dumps(value: Mapping[str, Any], *, fmt: PlistFormat = ..., skipkeys: bool = ..., sort_keys: bool = ...) -> bytes: ... if sys.version_info < (3, 9): - def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> Any: ... - def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ... + def readPlist(pathOrFile: Union[str, IO[bytes]]) -> Any: ... + def writePlist(value: Mapping[str, Any], pathOrFile: Union[str, IO[bytes]]) -> None: ... def readPlistFromBytes(data: bytes) -> Any: ... def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... -if sys.version_info < (3,): - def readPlistFromResource(path: _Path, restype: str = ..., resid: int = ...) -> Any: ... - def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, restype: str = ..., resid: int = ...) -> None: ... - def readPlistFromString(data: str) -> Any: ... - def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... - if sys.version_info < (3, 7): class Dict(DictT[str, Any]): def __getattr__(self, attr: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index 2c08f3586c0f..8f09c59f930b 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -1,7 +1,6 @@ import socket import ssl -import sys -from typing import Any, BinaryIO, Dict, List, Optional, Pattern, Text, Tuple, overload +from typing import Any, BinaryIO, Dict, List, Optional, Pattern, Tuple, overload _LongResp = Tuple[bytes, List[bytes], int] @@ -14,19 +13,17 @@ LF: bytes CRLF: bytes class POP3: - if sys.version_info >= (3, 0): - encoding: Text - - host: Text + encoding: str + host: str port: int sock: socket.socket file: BinaryIO welcome: bytes - def __init__(self, host: Text, port: int = ..., timeout: float = ...) -> None: ... + def __init__(self, host: str, port: int = ..., timeout: float = ...) -> None: ... def getwelcome(self) -> bytes: ... def set_debuglevel(self, level: int) -> None: ... - def user(self, user: Text) -> bytes: ... - def pass_(self, pswd: Text) -> bytes: ... + def user(self, user: str) -> bytes: ... + def pass_(self, pswd: str) -> bytes: ... def stat(self) -> Tuple[int, int]: ... def list(self, which: Optional[Any] = ...) -> _LongResp: ... def retr(self, which: Any) -> _LongResp: ... @@ -35,39 +32,27 @@ class POP3: def rset(self) -> bytes: ... def quit(self) -> bytes: ... def close(self) -> None: ... - def rpop(self, user: Text) -> bytes: ... - timestamp: Pattern[Text] - - if sys.version_info < (3, 0): - def apop(self, user: Text, secret: Text) -> bytes: ... - else: - def apop(self, user: Text, password: Text) -> bytes: ... + def rpop(self, user: str) -> bytes: ... + timestamp: Pattern[str] + def apop(self, user: str, password: str) -> bytes: ... def top(self, which: Any, howmuch: int) -> _LongResp: ... @overload def uidl(self) -> _LongResp: ... @overload def uidl(self, which: Any) -> bytes: ... - if sys.version_info >= (3, 5): - def utf8(self) -> bytes: ... - if sys.version_info >= (3, 4): - def capa(self) -> Dict[Text, List[Text]]: ... - def stls(self, context: Optional[ssl.SSLContext] = ...) -> bytes: ... + def utf8(self) -> bytes: ... + def capa(self) -> Dict[str, List[str]]: ... + def stls(self, context: Optional[ssl.SSLContext] = ...) -> bytes: ... class POP3_SSL(POP3): - if sys.version_info >= (3, 0): - def __init__( - self, - host: Text, - port: int = ..., - keyfile: Optional[Text] = ..., - certfile: Optional[Text] = ..., - timeout: float = ..., - context: Optional[ssl.SSLContext] = ..., - ) -> None: ... - else: - def __init__( - self, host: Text, port: int = ..., keyfile: Optional[Text] = ..., certfile: Optional[Text] = ..., timeout: float = ... - ) -> None: ... - if sys.version_info >= (3, 4): - # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored - def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> bytes: ... + def __init__( + self, + host: str, + port: int = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + timeout: float = ..., + context: Optional[ssl.SSLContext] = ..., + ) -> None: ... + # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored + def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 98176eaa03ec..4f0fcb7ed191 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath, BytesPath, StrPath +from _typeshed import BytesPath, StrOrBytesPath, StrPath from genericpath import ( commonprefix as commonprefix, exists as exists, @@ -93,7 +93,7 @@ def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... def splitext(p: PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... @overload def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def isabs(s: AnyPath) -> bool: ... -def islink(path: AnyPath) -> bool: ... -def ismount(path: AnyPath) -> bool: ... -def lexists(path: AnyPath) -> bool: ... +def isabs(s: StrOrBytesPath) -> bool: ... +def islink(path: StrOrBytesPath) -> bool: ... +def ismount(path: StrOrBytesPath) -> bool: ... +def lexists(path: StrOrBytesPath) -> bool: ... diff --git a/mypy/typeshed/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi index 9484f92eca46..7220010c8f05 100644 --- a/mypy/typeshed/stdlib/pprint.pyi +++ b/mypy/typeshed/stdlib/pprint.pyi @@ -24,14 +24,11 @@ elif sys.version_info >= (3, 8): sort_dicts: bool = ..., ) -> str: ... -elif sys.version_info >= (3, 4): +else: def pformat( object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ..., *, compact: bool = ... ) -> str: ... -else: - def pformat(object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ...) -> str: ... - if sys.version_info >= (3, 10): def pp( object: object, @@ -82,7 +79,7 @@ elif sys.version_info >= (3, 8): sort_dicts: bool = ..., ) -> None: ... -elif sys.version_info >= (3, 4): +else: def pprint( object: object, stream: Optional[IO[str]] = ..., @@ -93,11 +90,6 @@ elif sys.version_info >= (3, 4): compact: bool = ..., ) -> None: ... -else: - def pprint( - object: object, stream: Optional[IO[str]] = ..., indent: int = ..., width: int = ..., depth: Optional[int] = ... - ) -> None: ... - def isreadable(object: object) -> bool: ... def isrecursive(object: object) -> bool: ... def saferepr(object: object) -> str: ... @@ -126,7 +118,7 @@ class PrettyPrinter: compact: bool = ..., sort_dicts: bool = ..., ) -> None: ... - elif sys.version_info >= (3, 4): + else: def __init__( self, indent: int = ..., @@ -136,10 +128,6 @@ class PrettyPrinter: *, compact: bool = ..., ) -> None: ... - else: - def __init__( - self, indent: int = ..., width: int = ..., depth: Optional[int] = ..., stream: Optional[IO[str]] = ... - ) -> None: ... def pformat(self, object: object) -> str: ... def pprint(self, object: object) -> None: ... def isreadable(self, object: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index cc769b604a71..8052ede76aaf 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -1,4 +1,4 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import Any, Callable, Dict, Optional, Tuple, TypeVar, Union def run(statement: str, filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... @@ -18,7 +18,7 @@ class Profile: def simulate_call(self, name: str) -> None: ... def simulate_cmd_complete(self) -> None: ... def print_stats(self, sort: Union[str, int] = ...) -> None: ... - def dump_stats(self, file: AnyPath) -> None: ... + def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... def run(self: _SelfT, cmd: str) -> _SelfT: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 9c74aeb9c3de..80ce44ddd54b 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -1,8 +1,8 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Dict, Iterable, List, Optional, Text, Tuple, TypeVar, Union, overload +from typing import IO, Any, Dict, Iterable, List, Optional, Tuple, TypeVar, Union, overload _Selector = Union[str, float, int] _T = TypeVar("_T", bound=Stats) @@ -24,15 +24,15 @@ class Stats: sort_arg_dict_default: Dict[str, Tuple[Any, str]] def __init__( self: _T, - __arg: Union[None, str, Text, Profile, _cProfile] = ..., - *args: Union[None, str, Text, Profile, _cProfile, _T], + __arg: Union[None, str, Profile, _cProfile] = ..., + *args: Union[None, str, Profile, _cProfile, _T], stream: Optional[IO[Any]] = ..., ) -> None: ... - def init(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... - def load_stats(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... + def init(self, arg: Union[None, str, Profile, _cProfile]) -> None: ... + def load_stats(self, arg: Union[None, str, Profile, _cProfile]) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: Union[None, str, Text, Profile, _cProfile, _T]) -> _T: ... - def dump_stats(self, filename: AnyPath) -> None: ... + def add(self: _T, *arg_list: Union[None, str, Profile, _cProfile, _T]) -> _T: ... + def dump_stats(self, filename: StrOrBytesPath) -> None: ... def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... @overload def sort_stats(self: _T, field: int) -> _T: ... diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index f31e2c61ca9b..d554d6041d3d 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,4 +1,3 @@ -import sys from typing import Callable, Iterable, Tuple, Union _Reader = Callable[[int], bytes] @@ -13,9 +12,4 @@ def openpty() -> Tuple[int, int]: ... def master_open() -> Tuple[int, str]: ... def slave_open(tty_name: str) -> int: ... def fork() -> Tuple[int, int]: ... - -if sys.version_info >= (3, 4): - def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... - -else: - def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... +def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 49473b17708e..6a563a858282 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -1,7 +1,5 @@ import sys -from typing import AnyStr, List, Optional, Text, Type, Union - -_EitherStr = Union[bytes, Text] +from typing import AnyStr, List, Optional, Type class PyCompileError(Exception): exc_type_name: str @@ -39,14 +37,9 @@ elif sys.version_info >= (3, 7): invalidation_mode: Optional[PycInvalidationMode] = ..., ) -> Optional[AnyStr]: ... -elif sys.version_info >= (3, 2): +else: def compile( file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ... ) -> Optional[AnyStr]: ... -else: - def compile( - file: _EitherStr, cfile: Optional[_EitherStr] = ..., dfile: Optional[_EitherStr] = ..., doraise: bool = ... - ) -> None: ... - -def main(args: Optional[List[Text]] = ...) -> int: ... +def main(args: Optional[List[str]] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index 39252dd9f725..b41bef54304f 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,5 +1,5 @@ -import sys from _typeshed import SupportsWrite +from reprlib import Repr from types import MethodType, ModuleType, TracebackType from typing import ( IO, @@ -13,17 +13,11 @@ from typing import ( MutableMapping, NoReturn, Optional, - Text, Tuple, Type, Union, ) -if sys.version_info >= (3,): - from reprlib import Repr -else: - from repr import Repr - # the return type of sys.exc_info(), used by ErrorDuringImport.__init__ _Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] @@ -33,7 +27,7 @@ __version__: str __credits__: str def pathdirs() -> List[str]: ... -def getdoc(object: object) -> Text: ... +def getdoc(object: object) -> str: ... def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... def classname(object: object, modname: str) -> str: ... def isdata(object: object) -> bool: ... @@ -79,8 +73,8 @@ class HTMLRepr(Repr): def escape(self, text: str) -> str: ... def repr(self, object: object) -> str: ... def repr1(self, x: object, level: complex) -> str: ... - def repr_string(self, x: Text, level: complex) -> str: ... - def repr_str(self, x: Text, level: complex) -> str: ... + def repr_string(self, x: str, level: complex) -> str: ... + def repr_str(self, x: str, level: complex) -> str: ... def repr_instance(self, x: object, level: complex) -> str: ... def repr_unicode(self, x: AnyStr, level: complex) -> str: ... @@ -265,9 +259,3 @@ class ModuleScanner: def apropos(key: str) -> None: ... def ispath(x: Any) -> bool: ... def cli() -> None: ... - -if sys.version_info < (3,): - def serve( - port: int, callback: Optional[Callable[[Any], None]] = ..., completer: Optional[Callable[[], None]] = ... - ) -> None: ... - def gui() -> None: ... diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 65f6b0e9f7de..c58958d15085 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,7 +1,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Dict, List, Optional, Text, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Union EXPAT_VERSION: str # undocumented version_info: Tuple[int, int, int] # undocumented @@ -22,12 +22,12 @@ XML_PARAM_ENTITY_PARSING_ALWAYS: int _Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] class XMLParserType(object): - def Parse(self, __data: Union[Text, bytes], __isfinal: bool = ...) -> int: ... + def Parse(self, __data: Union[str, bytes], __isfinal: bool = ...) -> int: ... def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... - def SetBase(self, __base: Text) -> None: ... + def SetBase(self, __base: str) -> None: ... def GetBase(self) -> Optional[str]: ... def GetInputContext(self) -> Optional[bytes]: ... - def ExternalEntityParserCreate(self, __context: Optional[Text], __encoding: Text = ...) -> XMLParserType: ... + def ExternalEntityParserCreate(self, __context: Optional[str], __encoding: str = ...) -> XMLParserType: ... def SetParamEntityParsing(self, __flag: int) -> int: ... def UseForeignDTD(self, __flag: bool = ...) -> None: ... buffer_size: int @@ -75,5 +75,5 @@ def ErrorString(__code: int) -> str: ... # intern is undocumented def ParserCreate( - encoding: Optional[Text] = ..., namespace_separator: Optional[Text] = ..., intern: Optional[Dict[str, Any]] = ... + encoding: Optional[str] = ..., namespace_separator: Optional[str] = ..., intern: Optional[Dict[str, Any]] = ... ) -> XMLParserType: ... diff --git a/mypy/typeshed/stdlib/pyexpat/errors.pyi b/mypy/typeshed/stdlib/pyexpat/errors.pyi index 6cde43e3b61f..7c443917cdd0 100644 --- a/mypy/typeshed/stdlib/pyexpat/errors.pyi +++ b/mypy/typeshed/stdlib/pyexpat/errors.pyi @@ -1,9 +1,7 @@ -import sys from typing import Dict -if sys.version_info >= (3, 2): - codes: Dict[str, int] - messages: Dict[int, str] +codes: Dict[str, int] +messages: Dict[int, str] XML_ERROR_ABORTED: str XML_ERROR_ASYNC_ENTITY: str diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index 8f28a2b2b760..39f0001d048b 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,21 +1,17 @@ -import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import Callable, Optional, Sequence _CompleterT = Optional[Callable[[str, int], Optional[str]]] _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] def parse_and_bind(__string: str) -> None: ... -def read_init_file(__filename: Optional[AnyPath] = ...) -> None: ... +def read_init_file(__filename: Optional[StrOrBytesPath] = ...) -> None: ... def get_line_buffer() -> str: ... def insert_text(__string: str) -> None: ... def redisplay() -> None: ... -def read_history_file(__filename: Optional[AnyPath] = ...) -> None: ... -def write_history_file(__filename: Optional[AnyPath] = ...) -> None: ... - -if sys.version_info >= (3, 5): - def append_history_file(__nelements: int, __filename: Optional[AnyPath] = ...) -> None: ... - +def read_history_file(__filename: Optional[StrOrBytesPath] = ...) -> None: ... +def write_history_file(__filename: Optional[StrOrBytesPath] = ...) -> None: ... +def append_history_file(__nelements: int, __filename: Optional[StrOrBytesPath] = ...) -> None: ... def get_history_length() -> int: ... def set_history_length(__length: int) -> None: ... def clear_history() -> None: ... @@ -24,10 +20,7 @@ def get_history_item(__index: int) -> str: ... def remove_history_item(__pos: int) -> None: ... def replace_history_item(__pos: int, __line: str) -> None: ... def add_history(__string: str) -> None: ... - -if sys.version_info >= (3, 6): - def set_auto_history(__enabled: bool) -> None: ... - +def set_auto_history(__enabled: bool) -> None: ... def set_startup_hook(__function: Optional[Callable[[], None]] = ...) -> None: ... def set_pre_input_hook(__function: Optional[Callable[[], None]] = ...) -> None: ... def set_completer(__function: _CompleterT = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/rlcompleter.pyi b/mypy/typeshed/stdlib/rlcompleter.pyi index 3733cc13110c..8afb5b1ef628 100644 --- a/mypy/typeshed/stdlib/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/rlcompleter.pyi @@ -1,11 +1,5 @@ -import sys -from typing import Any, Dict, Optional, Union - -if sys.version_info >= (3,): - _Text = str -else: - _Text = Union[str, unicode] +from typing import Any, Dict, Optional class Completer: def __init__(self, namespace: Optional[Dict[str, Any]] = ...) -> None: ... - def complete(self, text: _Text, state: int) -> Optional[str]: ... + def complete(self, text: str, state: int) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index 21d81e16ec60..379d5a5186d9 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -1,38 +1,31 @@ -import sys -from typing import Any, Callable, Dict, List, NamedTuple, Optional, Text, Tuple +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple class Event(NamedTuple): time: float priority: Any action: Callable[..., Any] argument: Tuple[Any, ...] - kwargs: Dict[Text, Any] + kwargs: Dict[str, Any] class scheduler: - if sys.version_info >= (3, 3): - def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ... - def enterabs( - self, - time: float, - priority: Any, - action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., - kwargs: Dict[str, Any] = ..., - ) -> Event: ... - def enter( - self, - delay: float, - priority: Any, - action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., - kwargs: Dict[str, Any] = ..., - ) -> Event: ... - def run(self, blocking: bool = ...) -> Optional[float]: ... - else: - def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... - def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def run(self) -> None: ... + def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ... + def enterabs( + self, + time: float, + priority: Any, + action: Callable[..., Any], + argument: Tuple[Any, ...] = ..., + kwargs: Dict[str, Any] = ..., + ) -> Event: ... + def enter( + self, + delay: float, + priority: Any, + action: Callable[..., Any], + argument: Tuple[Any, ...] = ..., + kwargs: Dict[str, Any] = ..., + ) -> Event: ... + def run(self, blocking: bool = ...) -> Optional[float]: ... def cancel(self, event: Event) -> None: ... def empty(self) -> bool: ... @property diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index e0cf3bdd4d75..1a046c7b9bc3 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -28,10 +28,7 @@ def select( __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: Optional[float] = ... ) -> Tuple[List[Any], List[Any], List[Any]]: ... -if sys.version_info >= (3, 3): - error = OSError -else: - class error(Exception): ... +error = OSError if sys.platform != "linux" and sys.platform != "win32": # BSD only @@ -103,18 +100,14 @@ if sys.platform != "linux" and sys.platform != "win32": if sys.platform == "linux": class epoll(object): - if sys.version_info >= (3, 3): - def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... - else: - def __init__(self, sizehint: int = ...) -> None: ... - if sys.version_info >= (3, 4): - def __enter__(self) -> epoll: ... - def __exit__( - self, - exc_type: Optional[Type[BaseException]] = ..., - exc_val: Optional[BaseException] = ..., - exc_tb: Optional[TracebackType] = ..., - ) -> None: ... + def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... + def __enter__(self) -> epoll: ... + def __exit__( + self, + exc_type: Optional[Type[BaseException]] = ..., + exc_val: Optional[BaseException] = ..., + exc_tb: Optional[TracebackType] = ..., + ) -> None: ... def close(self) -> None: ... closed: bool def fileno(self) -> int: ... @@ -139,14 +132,12 @@ if sys.platform == "linux": EPOLL_RDHUP: int if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": - if sys.version_info >= (3, 3): - # Solaris only - class devpoll: - if sys.version_info >= (3, 4): - def close(self) -> None: ... - closed: bool - def fileno(self) -> int: ... - def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... - def modify(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... - def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ... + # Solaris only + class devpoll: + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... + def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index c0779d871c14..ad077df80d07 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,68 +1,27 @@ import os import sys from _typeshed import StrPath, SupportsRead, SupportsWrite -from typing import ( - Any, - AnyStr, - Callable, - Iterable, - List, - NamedTuple, - Optional, - Sequence, - Set, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -if sys.version_info >= (3, 6): - _AnyStr = str - _AnyPath = TypeVar("_AnyPath", str, os.PathLike[str]) - # Return value of some functions that may either return a path-like object that was passed in or - # a string - _PathReturn = Any -elif sys.version_info >= (3,): - _AnyStr = str - _AnyPath = str - _PathReturn = str -else: - _AnyStr = TypeVar("_AnyStr", str, unicode) - _AnyPath = TypeVar("_AnyPath", str, unicode) - _PathReturn = Type[None] - -if sys.version_info >= (3,): - class Error(OSError): ... - class SameFileError(Error): ... - class SpecialFileError(OSError): ... - class ExecError(OSError): ... - class ReadError(OSError): ... - class RegistryError(Exception): ... - -else: - class Error(EnvironmentError): ... - class SpecialFileError(EnvironmentError): ... - class ExecError(EnvironmentError): ... +from typing import Any, AnyStr, Callable, Iterable, List, NamedTuple, Optional, Sequence, Set, Tuple, TypeVar, Union, overload -def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... - -if sys.version_info >= (3,): - def copyfile(src: StrPath, dst: _AnyPath, *, follow_symlinks: bool = ...) -> _AnyPath: ... - def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... - def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... - def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... - def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +_PathT = TypeVar("_PathT", str, os.PathLike[str]) +# Return value of some functions that may either return a path-like object that was passed in or +# a string +_PathReturn = Any -else: - def copyfile(src: StrPath, dst: StrPath) -> None: ... - def copymode(src: StrPath, dst: StrPath) -> None: ... - def copystat(src: StrPath, dst: StrPath) -> None: ... - def copy(src: StrPath, dst: StrPath) -> _PathReturn: ... - def copy2(src: StrPath, dst: StrPath) -> _PathReturn: ... +class Error(OSError): ... +class SameFileError(Error): ... +class SpecialFileError(OSError): ... +class ExecError(OSError): ... +class ReadError(OSError): ... +class RegistryError(Exception): ... -def ignore_patterns(*patterns: StrPath) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... +def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... +def copyfile(src: StrPath, dst: _PathT, *, follow_symlinks: bool = ...) -> _PathT: ... +def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... +def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... +def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +def ignore_patterns(*patterns: StrPath) -> Callable[[Any, List[str]], Set[str]]: ... if sys.version_info >= (3, 8): def copytree( @@ -75,7 +34,7 @@ if sys.version_info >= (3, 8): dirs_exist_ok: bool = ..., ) -> _PathReturn: ... -elif sys.version_info >= (3,): +else: def copytree( src: StrPath, dst: StrPath, @@ -85,43 +44,26 @@ elif sys.version_info >= (3,): ignore_dangling_symlinks: bool = ..., ) -> _PathReturn: ... -else: - def copytree( - src: AnyStr, - dst: AnyStr, - symlinks: bool = ..., - ignore: Union[None, Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]]] = ..., - ) -> _PathReturn: ... - -if sys.version_info >= (3,): - def rmtree( - path: Union[bytes, StrPath], ignore_errors: bool = ..., onerror: Optional[Callable[[Any, Any, Any], Any]] = ... - ) -> None: ... - -else: - def rmtree( - path: _AnyPath, ignore_errors: bool = ..., onerror: Optional[Callable[[Any, _AnyPath, Any], Any]] = ... - ) -> None: ... +def rmtree( + path: Union[bytes, StrPath], ignore_errors: bool = ..., onerror: Optional[Callable[[Any, Any, Any], Any]] = ... +) -> None: ... _CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] if sys.version_info >= (3, 9): def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... -elif sys.version_info >= (3, 5): +else: # See https://bugs.python.org/issue32689 def move(src: str, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... -else: - def move(src: StrPath, dst: StrPath) -> _PathReturn: ... +class _ntuple_diskusage(NamedTuple): + total: int + used: int + free: int -if sys.version_info >= (3,): - class _ntuple_diskusage(NamedTuple): - total: int - used: int - free: int - def disk_usage(path: StrPath) -> _ntuple_diskusage: ... - def chown(path: StrPath, user: Optional[Union[str, int]] = ..., group: Optional[Union[str, int]] = ...) -> None: ... +def disk_usage(path: StrPath) -> _ntuple_diskusage: ... +def chown(path: StrPath, user: Optional[Union[str, int]] = ..., group: Optional[Union[str, int]] = ...) -> None: ... if sys.version_info >= (3, 8): @overload @@ -129,11 +71,11 @@ if sys.version_info >= (3, 8): @overload def which(cmd: bytes, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[bytes]: ... -elif sys.version_info >= (3,): +else: def which(cmd: StrPath, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[str]: ... def make_archive( - base_name: _AnyStr, + base_name: str, format: str, root_dir: Optional[StrPath] = ..., base_dir: Optional[StrPath] = ..., @@ -142,7 +84,7 @@ def make_archive( owner: Optional[str] = ..., group: Optional[str] = ..., logger: Optional[Any] = ..., -) -> _AnyStr: ... +) -> str: ... def get_archive_formats() -> List[Tuple[str, str]]: ... def register_archive_format( name: str, @@ -152,19 +94,16 @@ def register_archive_format( ) -> None: ... def unregister_archive_format(name: str) -> None: ... -if sys.version_info >= (3,): - if sys.version_info >= (3, 7): - def unpack_archive(filename: StrPath, extract_dir: Optional[StrPath] = ..., format: Optional[str] = ...) -> None: ... - else: - # See http://bugs.python.org/issue30218 - def unpack_archive(filename: str, extract_dir: Optional[StrPath] = ..., format: Optional[str] = ...) -> None: ... - def register_unpack_format( - name: str, - extensions: List[str], - function: Any, - extra_args: Optional[Sequence[Tuple[str, Any]]] = ..., - description: str = ..., - ) -> None: ... - def unregister_unpack_format(name: str) -> None: ... - def get_unpack_formats() -> List[Tuple[str, List[str], str]]: ... - def get_terminal_size(fallback: Tuple[int, int] = ...) -> os.terminal_size: ... +if sys.version_info >= (3, 7): + def unpack_archive(filename: StrPath, extract_dir: Optional[StrPath] = ..., format: Optional[str] = ...) -> None: ... + +else: + # See http://bugs.python.org/issue30218 + def unpack_archive(filename: str, extract_dir: Optional[StrPath] = ..., format: Optional[str] = ...) -> None: ... + +def register_unpack_format( + name: str, extensions: List[str], function: Any, extra_args: Optional[Sequence[Tuple[str, Any]]] = ..., description: str = ... +) -> None: ... +def unregister_unpack_format(name: str) -> None: ... +def get_unpack_formats() -> List[Tuple[str, List[str], str]]: ... +def get_terminal_size(fallback: Tuple[int, int] = ...) -> os.terminal_size: ... diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 92f078a063f6..313e722163c0 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -1,8 +1,7 @@ import asynchat import asyncore import socket -import sys -from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type, Union +from typing import Any, DefaultDict, List, Optional, Tuple, Type, Union _Address = Tuple[str, int] # (host, port) @@ -10,41 +9,37 @@ class SMTPChannel(asynchat.async_chat): COMMAND: int DATA: int - if sys.version_info >= (3,): - command_size_limits: DefaultDict[str, int] - smtp_server: SMTPServer - conn: socket.socket - addr: Any - received_lines: List[Text] - smtp_state: int - seen_greeting: str - mailfrom: str - rcpttos: List[str] - received_data: str - fqdn: str - peer: str + command_size_limits: DefaultDict[str, int] + smtp_server: SMTPServer + conn: socket.socket + addr: Any + received_lines: List[str] + smtp_state: int + seen_greeting: str + mailfrom: str + rcpttos: List[str] + received_data: str + fqdn: str + peer: str - command_size_limit: int - data_size_limit: int + command_size_limit: int + data_size_limit: int - enable_SMTPUTF8: bool - @property - def max_command_size_limit(self) -> int: ... - if sys.version_info >= (3,): - def __init__( - self, - server: SMTPServer, - conn: socket.socket, - addr: Any, - data_size_limit: int = ..., - map: Optional[asyncore._maptype] = ..., - enable_SMTPUTF8: bool = ..., - decode_data: bool = ..., - ) -> None: ... - else: - def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ... + enable_SMTPUTF8: bool + @property + def max_command_size_limit(self) -> int: ... + def __init__( + self, + server: SMTPServer, + conn: socket.socket, + addr: Any, + data_size_limit: int = ..., + map: Optional[asyncore._maptype] = ..., + enable_SMTPUTF8: bool = ..., + decode_data: bool = ..., + ) -> None: ... # base asynchat.async_chat.push() accepts bytes - def push(self, msg: Text) -> None: ... # type: ignore + def push(self, msg: str) -> None: ... # type: ignore def collect_incoming_data(self, data: bytes) -> None: ... def found_terminator(self) -> None: ... def smtp_HELO(self, arg: str) -> None: ... @@ -54,43 +49,38 @@ class SMTPChannel(asynchat.async_chat): def smtp_RCPT(self, arg: str) -> None: ... def smtp_RSET(self, arg: str) -> None: ... def smtp_DATA(self, arg: str) -> None: ... - if sys.version_info >= (3, 3): - def smtp_EHLO(self, arg: str) -> None: ... - def smtp_HELP(self, arg: str) -> None: ... - def smtp_VRFY(self, arg: str) -> None: ... - def smtp_EXPN(self, arg: str) -> None: ... + def smtp_EHLO(self, arg: str) -> None: ... + def smtp_HELP(self, arg: str) -> None: ... + def smtp_VRFY(self, arg: str) -> None: ... + def smtp_EXPN(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): channel_class: Type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool - - if sys.version_info >= (3,): - def __init__( - self, - localaddr: _Address, - remoteaddr: _Address, - data_size_limit: int = ..., - map: Optional[asyncore._maptype] = ..., - enable_SMTPUTF8: bool = ..., - decode_data: bool = ..., - ) -> None: ... - else: - def __init__(self, localaddr: _Address, remoteaddr: _Address, data_size_limit: int = ...) -> None: ... + def __init__( + self, + localaddr: _Address, + remoteaddr: _Address, + data_size_limit: int = ..., + map: Optional[asyncore._maptype] = ..., + enable_SMTPUTF8: bool = ..., + decode_data: bool = ..., + ) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message( - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str], **kwargs: Any + self, peer: _Address, mailfrom: str, rcpttos: List[str], data: Union[bytes, str], **kwargs: Any ) -> Optional[str]: ... class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str] + self, peer: _Address, mailfrom: str, rcpttos: List[str], data: Union[bytes, str] ) -> Optional[str]: ... class MailmanProxy(PureProxy): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str] + self, peer: _Address, mailfrom: str, rcpttos: List[str], data: Union[bytes, str] ) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/sndhdr.pyi b/mypy/typeshed/stdlib/sndhdr.pyi index ef025ac571a7..4f8ab2652b93 100644 --- a/mypy/typeshed/stdlib/sndhdr.pyi +++ b/mypy/typeshed/stdlib/sndhdr.pyi @@ -1,17 +1,12 @@ -import sys -from _typeshed import AnyPath -from typing import NamedTuple, Optional, Tuple, Union +from _typeshed import StrOrBytesPath +from typing import NamedTuple, Optional, Union -if sys.version_info >= (3, 5): - class SndHeaders(NamedTuple): - filetype: str - framerate: int - nchannels: int - nframes: int - sampwidth: Union[int, str] - _SndHeaders = SndHeaders -else: - _SndHeaders = Tuple[str, int, int, int, Union[int, str]] +class SndHeaders(NamedTuple): + filetype: str + framerate: int + nchannels: int + nframes: int + sampwidth: Union[int, str] -def what(filename: AnyPath) -> Optional[_SndHeaders]: ... -def whathdr(filename: AnyPath) -> Optional[_SndHeaders]: ... +def what(filename: StrOrBytesPath) -> Optional[SndHeaders]: ... +def whathdr(filename: StrOrBytesPath) -> Optional[SndHeaders]: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index e3f5d9b35bef..06adfe49e93a 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, BinaryIO, Iterable, List, Optional, Text, TextIO, Tuple, TypeVar, Union, overload +from enum import IntEnum, IntFlag +from typing import Any, BinaryIO, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union, overload from typing_extensions import Literal # ----- Constants ----- @@ -13,8 +14,7 @@ from typing_extensions import Literal # Constants defined by Python (i.e. not OS constants re-exported from C) has_ipv6: bool SocketType: Any -if sys.version_info >= (3,): - SocketIO: Any +SocketIO: Any # Re-exported errno EAGAIN: int @@ -35,7 +35,7 @@ SOCK_RAW: SocketKind SOCK_RDM: SocketKind SOCK_SEQPACKET: SocketKind -if sys.platform == "linux" and sys.version_info >= (3,): +if sys.platform == "linux": SOCK_CLOEXEC: SocketKind SOCK_NONBLOCK: SocketKind @@ -268,7 +268,7 @@ if sys.version_info >= (3, 7): # Specifically-documented constants -if sys.platform == "linux" and sys.version_info >= (3,): +if sys.platform == "linux": AF_CAN: AddressFamily PF_CAN: int SOL_CAN_BASE: int @@ -361,7 +361,7 @@ if sys.platform == "linux": PACKET_OTHERHOST: int PACKET_OUTGOING: int -if sys.platform == "linux" and sys.version_info >= (3,): +if sys.platform == "linux": AF_RDS: AddressFamily PF_RDS: int SOL_RDS: int @@ -387,8 +387,7 @@ if sys.platform == "linux" and sys.version_info >= (3,): if sys.platform == "win32": SIO_RCVALL: int SIO_KEEPALIVE_VALS: int - if sys.version_info >= (3, 6): - SIO_LOOPBACK_FAST_PATH: int + SIO_LOOPBACK_FAST_PATH: int RCVALL_IPLEVEL: int RCVALL_MAX: int RCVALL_OFF: int @@ -422,7 +421,7 @@ if sys.platform == "linux": TIPC_WITHDRAWN: int TIPC_ZONE_SCOPE: int -if sys.platform == "linux" and sys.version_info >= (3, 6): +if sys.platform == "linux": AF_ALG: AddressFamily SOL_ALG: int ALG_OP_DECRYPT: int @@ -451,13 +450,12 @@ AF_LINK: AddressFamily # Availability: BSD, macOS # BDADDR_* and HCI_* listed with other bluetooth constants below -if sys.version_info >= (3, 6): - SO_DOMAIN: int - SO_PASSSEC: int - SO_PEERSEC: int - SO_PROTOCOL: int - TCP_CONGESTION: int - TCP_USER_TIMEOUT: int +SO_DOMAIN: int +SO_PASSSEC: int +SO_PEERSEC: int +SO_PROTOCOL: int +TCP_CONGESTION: int +TCP_USER_TIMEOUT: int if sys.platform == "linux" and sys.version_info >= (3, 8): AF_QIPCRTR: AddressFamily @@ -506,90 +504,76 @@ if sys.platform == "darwin": SYSPROTO_CONTROL: int # enum versions of above flags -if sys.version_info >= (3, 4): - from enum import IntEnum - class AddressFamily(IntEnum): - AF_UNIX: int - AF_INET: int - AF_INET6: int - AF_AAL5: int - AF_ALG: int - AF_APPLETALK: int - AF_ASH: int - AF_ATMPVC: int - AF_ATMSVC: int - AF_AX25: int - AF_BLUETOOTH: int - AF_BRIDGE: int - AF_CAN: int - AF_DECnet: int - AF_ECONET: int - AF_IPX: int - AF_IRDA: int - AF_KEY: int - AF_LINK: int - AF_LLC: int - AF_NETBEUI: int - AF_NETLINK: int - AF_NETROM: int - AF_PACKET: int - AF_PPPOX: int - AF_QIPCRTR: int - AF_RDS: int - AF_ROSE: int - AF_ROUTE: int - AF_SECURITY: int - AF_SNA: int - AF_SYSTEM: int - AF_TIPC: int - AF_UNSPEC: int - AF_VSOCK: int - AF_WANPIPE: int - AF_X25: int - class SocketKind(IntEnum): - SOCK_STREAM: int - SOCK_DGRAM: int - SOCK_RAW: int - SOCK_RDM: int - SOCK_SEQPACKET: int - SOCK_CLOEXEC: int - SOCK_NONBLOCK: int - -else: - AddressFamily = int - SocketKind = int - -if sys.version_info >= (3, 6): - from enum import IntFlag - class AddressInfo(IntFlag): - AI_ADDRCONFIG: int - AI_ALL: int - AI_CANONNAME: int - AI_NUMERICHOST: int - AI_NUMERICSERV: int - AI_PASSIVE: int - AI_V4MAPPED: int - class MsgFlag(IntFlag): - MSG_CTRUNC: int - MSG_DONTROUTE: int - MSG_DONTWAIT: int - MSG_EOR: int - MSG_OOB: int - MSG_PEEK: int - MSG_TRUNC: int - MSG_WAITALL: int - -else: - AddressInfo = int - MsgFlag = int +class AddressFamily(IntEnum): + AF_UNIX: int + AF_INET: int + AF_INET6: int + AF_AAL5: int + AF_ALG: int + AF_APPLETALK: int + AF_ASH: int + AF_ATMPVC: int + AF_ATMSVC: int + AF_AX25: int + AF_BLUETOOTH: int + AF_BRIDGE: int + AF_CAN: int + AF_DECnet: int + AF_ECONET: int + AF_IPX: int + AF_IRDA: int + AF_KEY: int + AF_LINK: int + AF_LLC: int + AF_NETBEUI: int + AF_NETLINK: int + AF_NETROM: int + AF_PACKET: int + AF_PPPOX: int + AF_QIPCRTR: int + AF_RDS: int + AF_ROSE: int + AF_ROUTE: int + AF_SECURITY: int + AF_SNA: int + AF_SYSTEM: int + AF_TIPC: int + AF_UNSPEC: int + AF_VSOCK: int + AF_WANPIPE: int + AF_X25: int + +class SocketKind(IntEnum): + SOCK_STREAM: int + SOCK_DGRAM: int + SOCK_RAW: int + SOCK_RDM: int + SOCK_SEQPACKET: int + SOCK_CLOEXEC: int + SOCK_NONBLOCK: int + +class AddressInfo(IntFlag): + AI_ADDRCONFIG: int + AI_ALL: int + AI_CANONNAME: int + AI_NUMERICHOST: int + AI_NUMERICSERV: int + AI_PASSIVE: int + AI_V4MAPPED: int + +class MsgFlag(IntFlag): + MSG_CTRUNC: int + MSG_DONTROUTE: int + MSG_DONTWAIT: int + MSG_EOR: int + MSG_OOB: int + MSG_PEEK: int + MSG_TRUNC: int + MSG_WAITALL: int # ----- Exceptions ----- -if sys.version_info < (3,): - class error(IOError): ... - -else: - error = OSError +error = OSError class herror(error): def __init__(self, herror: int = ..., string: str = ...) -> None: ... @@ -617,13 +601,9 @@ class socket: family: int type: int proto: int - - if sys.version_info < (3,): - def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... - else: - def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: Optional[int] = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... - def __exit__(self, *args: Any) -> None: ... + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: Optional[int] = ...) -> None: ... + def __enter__(self: _SelfT) -> _SelfT: ... + def __exit__(self, *args: Any) -> None: ... # --- methods --- def accept(self) -> Tuple[socket, _RetAddress]: ... def bind(self, address: Union[_Address, bytes]) -> None: ... @@ -633,8 +613,7 @@ class socket: def detach(self) -> int: ... def dup(self) -> socket: ... def fileno(self) -> int: ... - if sys.version_info >= (3, 4): - def get_inheritable(self) -> bool: ... + def get_inheritable(self) -> bool: ... def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... @overload @@ -644,42 +623,34 @@ class socket: if sys.version_info >= (3, 7): def getblocking(self) -> bool: ... def gettimeout(self) -> Optional[float]: ... - if sys.platform == "win32" and sys.version_info >= (3, 6): + if sys.platform == "win32": def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> None: ... - elif sys.platform == "win32": - def ioctl(self, control: int, option: Union[int, Tuple[int, int, int]]) -> None: ... - if sys.version_info >= (3, 5): - def listen(self, __backlog: int = ...) -> None: ... - else: - def listen(self, __backlog: int) -> None: ... + def listen(self, __backlog: int = ...) -> None: ... # Note that the makefile's documented windows-specific behavior is not represented - if sys.version_info >= (3,): - # mode strings with duplicates are intentionally excluded - @overload - def makefile( - self, - mode: Literal["r", "w", "rw", "wr", ""] = ..., - buffering: Optional[int] = ..., - *, - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - ) -> TextIO: ... - @overload - def makefile( - self, - mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], - buffering: Optional[int] = ..., - *, - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - ) -> BinaryIO: ... - else: - def makefile(self, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + # mode strings with duplicates are intentionally excluded + @overload + def makefile( + self, + mode: Literal["r", "w", "rw", "wr", ""] = ..., + buffering: Optional[int] = ..., + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + ) -> TextIO: ... + @overload + def makefile( + self, + mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Optional[int] = ..., + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + ) -> BinaryIO: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... - if sys.version_info >= (3, 3) and sys.platform != "win32": + if sys.platform != "win32": def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> Tuple[bytes, List[_CMSG], int, Any]: ... def recvmsg_into( self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... @@ -692,26 +663,22 @@ class socket: def sendto(self, data: bytes, address: _Address) -> int: ... @overload def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... - if sys.version_info >= (3, 3) and sys.platform != "win32": + if sys.platform != "win32": def sendmsg( self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... ) -> int: ... - if sys.platform == "linux" and sys.version_info >= (3, 6): + if sys.platform == "linux": def sendmsg_afalg( self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... ) -> int: ... - if sys.version_info >= (3,): - def sendfile(self, file: BinaryIO, offset: int = ..., count: Optional[int] = ...) -> int: ... - def set_inheritable(self, inheritable: bool) -> None: ... + def sendfile(self, file: BinaryIO, offset: int = ..., count: Optional[int] = ...) -> int: ... + def set_inheritable(self, inheritable: bool) -> None: ... def setblocking(self, flag: bool) -> None: ... def settimeout(self, value: Optional[float]) -> None: ... - if sys.version_info < (3, 6): - def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... - else: - @overload - def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... - @overload - def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... if sys.platform == "win32": def share(self, process_id: int) -> bytes: ... def shutdown(self, how: int) -> None: ... @@ -724,7 +691,7 @@ if sys.version_info >= (3, 7): def create_connection( address: Tuple[Optional[str], int], timeout: Optional[float] = ..., - source_address: Optional[Tuple[Union[bytearray, bytes, Text], int]] = ..., + source_address: Optional[Tuple[Union[bytearray, bytes, str], int]] = ..., ) -> socket: ... if sys.version_info >= (3, 8): @@ -735,30 +702,18 @@ if sys.version_info >= (3, 8): def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... -if sys.platform == "win32" and sys.version_info >= (3, 3): +if sys.platform == "win32": def fromshare(info: bytes) -> socket: ... # the 5th tuple item is an address -if sys.version_info >= (3,): - def getaddrinfo( - host: Optional[Union[bytearray, bytes, Text]], - port: Union[str, int, None], - family: int = ..., - type: int = ..., - proto: int = ..., - flags: int = ..., - ) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]]: ... - -else: - def getaddrinfo( - host: Optional[Union[bytearray, bytes, Text]], - port: Union[str, int, None], - family: int = ..., - socktype: int = ..., - proto: int = ..., - flags: int = ..., - ) -> List[Tuple[AddressFamily, SocketKind, int, str, Tuple[Any, ...]]]: ... - +def getaddrinfo( + host: Optional[Union[bytearray, bytes, str]], + port: Union[str, int, None], + family: int = ..., + type: int = ..., + proto: int = ..., + flags: int = ..., +) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]]: ... def getfqdn(name: str = ...) -> str: ... def gethostbyname(hostname: str) -> str: ... def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... @@ -792,18 +747,16 @@ if sys.version_info >= (3, 9): ) -> int: ... def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = ...) -> Tuple[bytes, List[int], int, Any]: ... -if sys.version_info >= (3, 3): - def CMSG_LEN(length: int) -> int: ... - def CMSG_SPACE(length: int) -> int: ... - +def CMSG_LEN(length: int) -> int: ... +def CMSG_SPACE(length: int) -> int: ... def getdefaulttimeout() -> Optional[float]: ... def setdefaulttimeout(timeout: Optional[float]) -> None: ... -if sys.version_info >= (3, 3): - if sys.platform != "win32": - def sethostname(name: str) -> None: ... - # Windows added these in 3.8, but didn't have them before - if sys.platform != "win32" or sys.version_info >= (3, 8): - def if_nameindex() -> List[Tuple[int, str]]: ... - def if_nametoindex(name: str) -> int: ... - def if_indextoname(index: int) -> str: ... +if sys.platform != "win32": + def sethostname(name: str) -> None: ... + +# Windows added these in 3.8, but didn't have them before +if sys.platform != "win32" or sys.version_info >= (3, 8): + def if_nameindex() -> List[Tuple[int, str]]: ... + def if_nametoindex(name: str) -> int: ... + def if_indextoname(index: int) -> str: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 74caa0e64cf1..c53141856ca8 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,7 +1,7 @@ -import os import sys +from _typeshed import StrOrBytesPath from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Protocol, Text, Tuple, Type, TypeVar, Union +from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Protocol, Tuple, Type, TypeVar, Union _T = TypeVar("_T") @@ -18,10 +18,7 @@ def TimestampFromTicks(ticks: float) -> Timestamp: ... version_info: Tuple[int, int, int] sqlite_version_info: Tuple[int, int, int] -if sys.version_info >= (3,): - Binary = memoryview -else: - Binary = buffer +Binary = memoryview # The remaining definitions are imported from _sqlite3. @@ -69,19 +66,7 @@ def complete_statement(sql: str) -> bool: ... if sys.version_info >= (3, 7): def connect( - database: Union[bytes, Text, os.PathLike[Text]], - timeout: float = ..., - detect_types: int = ..., - isolation_level: Optional[str] = ..., - check_same_thread: bool = ..., - factory: Optional[Type[Connection]] = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> Connection: ... - -elif sys.version_info >= (3, 4): - def connect( - database: Union[bytes, Text], + database: StrOrBytesPath, timeout: float = ..., detect_types: int = ..., isolation_level: Optional[str] = ..., @@ -93,13 +78,14 @@ elif sys.version_info >= (3, 4): else: def connect( - database: Union[bytes, Text], + database: Union[bytes, str], timeout: float = ..., detect_types: int = ..., isolation_level: Optional[str] = ..., check_same_thread: bool = ..., factory: Optional[Type[Connection]] = ..., cached_statements: int = ..., + uri: bool = ..., ) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... @@ -146,7 +132,7 @@ class Connection(object): def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... # TODO: please check in executemany() if seq_of_parameters type is possible like this def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: Union[bytes, Text]) -> Cursor: ... + def executescript(self, __sql_script: Union[bytes, str]) -> Cursor: ... def interrupt(self, *args: Any, **kwargs: Any) -> None: ... def iterdump(self, *args: Any, **kwargs: Any) -> Generator[str, None, None]: ... def rollback(self, *args: Any, **kwargs: Any) -> None: ... @@ -189,17 +175,14 @@ class Cursor(Iterator[Any]): def close(self, *args: Any, **kwargs: Any) -> None: ... def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: Union[bytes, Text]) -> Cursor: ... + def executescript(self, __sql_script: Union[bytes, str]) -> Cursor: ... def fetchall(self) -> List[Any]: ... def fetchmany(self, size: Optional[int] = ...) -> List[Any]: ... def fetchone(self) -> Any: ... def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... def __iter__(self) -> Cursor: ... - if sys.version_info >= (3, 0): - def __next__(self) -> Any: ... - else: - def next(self) -> Any: ... + def __next__(self) -> Any: ... class DataError(DatabaseError): ... class DatabaseError(Error): ... @@ -210,73 +193,7 @@ class InternalError(DatabaseError): ... class NotSupportedError(DatabaseError): ... class OperationalError(DatabaseError): ... -if sys.version_info >= (3,): - OptimizedUnicode = str -else: - class OptimizedUnicode(object): - maketrans: Any - def __init__(self, *args, **kwargs): ... - def capitalize(self, *args, **kwargs): ... - def casefold(self, *args, **kwargs): ... - def center(self, *args, **kwargs): ... - def count(self, *args, **kwargs): ... - def encode(self, *args, **kwargs): ... - def endswith(self, *args, **kwargs): ... - def expandtabs(self, *args, **kwargs): ... - def find(self, *args, **kwargs): ... - def format(self, *args, **kwargs): ... - def format_map(self, *args, **kwargs): ... - def index(self, *args, **kwargs): ... - def isalnum(self, *args, **kwargs): ... - def isalpha(self, *args, **kwargs): ... - def isdecimal(self, *args, **kwargs): ... - def isdigit(self, *args, **kwargs): ... - def isidentifier(self, *args, **kwargs): ... - def islower(self, *args, **kwargs): ... - def isnumeric(self, *args, **kwargs): ... - def isprintable(self, *args, **kwargs): ... - def isspace(self, *args, **kwargs): ... - def istitle(self, *args, **kwargs): ... - def isupper(self, *args, **kwargs): ... - def join(self, *args, **kwargs): ... - def ljust(self, *args, **kwargs): ... - def lower(self, *args, **kwargs): ... - def lstrip(self, *args, **kwargs): ... - def partition(self, *args, **kwargs): ... - def replace(self, *args, **kwargs): ... - def rfind(self, *args, **kwargs): ... - def rindex(self, *args, **kwargs): ... - def rjust(self, *args, **kwargs): ... - def rpartition(self, *args, **kwargs): ... - def rsplit(self, *args, **kwargs): ... - def rstrip(self, *args, **kwargs): ... - def split(self, *args, **kwargs): ... - def splitlines(self, *args, **kwargs): ... - def startswith(self, *args, **kwargs): ... - def strip(self, *args, **kwargs): ... - def swapcase(self, *args, **kwargs): ... - def title(self, *args, **kwargs): ... - def translate(self, *args, **kwargs): ... - def upper(self, *args, **kwargs): ... - def zfill(self, *args, **kwargs): ... - def __add__(self, other): ... - def __contains__(self, *args, **kwargs): ... - def __eq__(self, other): ... - def __format__(self, *args, **kwargs): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __getnewargs__(self, *args, **kwargs): ... - def __gt__(self, other): ... - def __hash__(self): ... - def __iter__(self): ... - def __le__(self, other): ... - def __len__(self, *args, **kwargs): ... - def __lt__(self, other): ... - def __mod__(self, other): ... - def __mul__(self, other): ... - def __ne__(self, other): ... - def __rmod__(self, other): ... - def __rmul__(self, other): ... +OptimizedUnicode = str class PrepareProtocol(object): def __init__(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/sre_compile.pyi b/mypy/typeshed/stdlib/sre_compile.pyi index 9b50b75d8c31..492a194f1a26 100644 --- a/mypy/typeshed/stdlib/sre_compile.pyi +++ b/mypy/typeshed/stdlib/sre_compile.pyi @@ -1,5 +1,5 @@ -import sys from sre_constants import ( + SRE_FLAG_ASCII as SRE_FLAG_ASCII, SRE_FLAG_DEBUG as SRE_FLAG_DEBUG, SRE_FLAG_DOTALL as SRE_FLAG_DOTALL, SRE_FLAG_IGNORECASE as SRE_FLAG_IGNORECASE, @@ -11,21 +11,13 @@ from sre_constants import ( SRE_INFO_CHARSET as SRE_INFO_CHARSET, SRE_INFO_LITERAL as SRE_INFO_LITERAL, SRE_INFO_PREFIX as SRE_INFO_PREFIX, + _NamedIntConstant, ) from sre_parse import SubPattern -from typing import Any, List, Pattern, Tuple, Type, Union - -if sys.version_info >= (3,): - from sre_constants import SRE_FLAG_ASCII as SRE_FLAG_ASCII +from typing import Any, List, Pattern, Union MAXCODE: int -if sys.version_info < (3, 0): - STRING_TYPES: Tuple[Type[str], Type[unicode]] - _IsStringType = int -else: - from sre_constants import _NamedIntConstant - def dis(code: List[_NamedIntConstant]) -> None: ... - _IsStringType = bool -def isstring(obj: Any) -> _IsStringType: ... +def dis(code: List[_NamedIntConstant]) -> None: ... +def isstring(obj: Any) -> bool: ... def compile(p: Union[str, bytes, SubPattern], flags: int = ...) -> Pattern[Any]: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 838211d959e5..ccae3e3b3c11 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -1,12 +1,10 @@ +import enum import socket import sys from _typeshed import StrPath -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Tuple, Type, Union, overload +from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Type, Union, overload from typing_extensions import Literal -if sys.version_info >= (3, 4): - import enum - _PCTRTT = Tuple[Tuple[str, str], ...] _PCTRTTT = Tuple[_PCTRTT, ...] _PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] @@ -14,11 +12,7 @@ _PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] _EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] _PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] -if sys.version_info >= (3, 5): - _SC1ArgT = Union[SSLSocket, SSLObject] -else: - _SC1ArgT = SSLSocket -_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] +_SrvnmeCbType = Callable[[Union[SSLSocket, SSLObject], Optional[str], SSLSocket], Optional[int]] class SSLError(OSError): library: str @@ -51,7 +45,7 @@ def wrap_socket( ciphers: Optional[str] = ..., ) -> SSLSocket: ... def create_default_context( - purpose: Any = ..., *, cafile: Optional[str] = ..., capath: Optional[str] = ..., cadata: Union[Text, bytes, None] = ... + purpose: Any = ..., *, cafile: Optional[str] = ..., capath: Optional[str] = ..., cadata: Union[str, bytes, None] = ... ) -> SSLContext: ... if sys.version_info >= (3, 7): @@ -65,7 +59,7 @@ if sys.version_info >= (3, 7): keyfile: Optional[str] = ..., cafile: Optional[str] = ..., capath: Optional[str] = ..., - cadata: Union[Text, bytes, None] = ..., + cadata: Union[str, bytes, None] = ..., ) -> SSLContext: ... else: @@ -79,15 +73,13 @@ else: keyfile: Optional[str] = ..., cafile: Optional[str] = ..., capath: Optional[str] = ..., - cadata: Union[Text, bytes, None] = ..., + cadata: Union[str, bytes, None] = ..., ) -> SSLContext: ... _create_default_https_context: Callable[..., SSLContext] -if sys.version_info >= (3, 3): - def RAND_bytes(__num: int) -> bytes: ... - def RAND_pseudo_bytes(__num: int) -> Tuple[bytes, bool]: ... - +def RAND_bytes(__num: int) -> bytes: ... +def RAND_pseudo_bytes(__num: int) -> Tuple[bytes, bool]: ... def RAND_status() -> bool: ... def RAND_egd(path: str) -> None: ... def RAND_add(__s: bytes, __entropy: float) -> None: ... @@ -128,55 +120,43 @@ PROTOCOL_TLSv1: int PROTOCOL_TLSv1_1: int PROTOCOL_TLSv1_2: int PROTOCOL_TLS: int -if sys.version_info >= (3, 6): - PROTOCOL_TLS_CLIENT: int - PROTOCOL_TLS_SERVER: int - -if sys.version_info >= (3, 6): - class Options(enum.IntFlag): - OP_ALL: int - OP_NO_SSLv2: int - OP_NO_SSLv3: int - OP_NO_TLSv1: int - OP_NO_TLSv1_1: int - OP_NO_TLSv1_2: int - OP_NO_TLSv1_3: int - OP_CIPHER_SERVER_PREFERENCE: int - OP_SINGLE_DH_USE: int - OP_SINGLE_ECDH_USE: int - OP_NO_COMPRESSION: int - OP_NO_TICKET: int - if sys.version_info >= (3, 7): - OP_NO_RENEGOTIATION: int - if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: int - OP_ALL: Options - OP_NO_SSLv2: Options - OP_NO_SSLv3: Options - OP_NO_TLSv1: Options - OP_NO_TLSv1_1: Options - OP_NO_TLSv1_2: Options - OP_NO_TLSv1_3: Options - OP_CIPHER_SERVER_PREFERENCE: Options - OP_SINGLE_DH_USE: Options - OP_SINGLE_ECDH_USE: Options - OP_NO_COMPRESSION: Options - OP_NO_TICKET: Options - if sys.version_info >= (3, 7): - OP_NO_RENEGOTIATION: Options - if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: Options -else: +PROTOCOL_TLS_CLIENT: int +PROTOCOL_TLS_SERVER: int + +class Options(enum.IntFlag): OP_ALL: int OP_NO_SSLv2: int OP_NO_SSLv3: int OP_NO_TLSv1: int OP_NO_TLSv1_1: int OP_NO_TLSv1_2: int + OP_NO_TLSv1_3: int OP_CIPHER_SERVER_PREFERENCE: int OP_SINGLE_DH_USE: int OP_SINGLE_ECDH_USE: int OP_NO_COMPRESSION: int + OP_NO_TICKET: int + if sys.version_info >= (3, 7): + OP_NO_RENEGOTIATION: int + if sys.version_info >= (3, 8): + OP_ENABLE_MIDDLEBOX_COMPAT: int + +OP_ALL: Options +OP_NO_SSLv2: Options +OP_NO_SSLv3: Options +OP_NO_TLSv1: Options +OP_NO_TLSv1_1: Options +OP_NO_TLSv1_2: Options +OP_NO_TLSv1_3: Options +OP_CIPHER_SERVER_PREFERENCE: Options +OP_SINGLE_DH_USE: Options +OP_SINGLE_ECDH_USE: Options +OP_NO_COMPRESSION: Options +OP_NO_TICKET: Options +if sys.version_info >= (3, 7): + OP_NO_RENEGOTIATION: Options +if sys.version_info >= (3, 8): + OP_ENABLE_MIDDLEBOX_COMPAT: Options if sys.version_info >= (3, 7): HAS_NEVER_CHECK_COMMON_NAME: bool @@ -230,23 +210,16 @@ class _ASN1Object(NamedTuple): longname: str oid: str -if sys.version_info >= (3, 4): - class Purpose(_ASN1Object, enum.Enum): - SERVER_AUTH: _ASN1Object - CLIENT_AUTH: _ASN1Object - -else: - class Purpose(_ASN1Object): - SERVER_AUTH: ClassVar[Purpose] - CLIENT_AUTH: ClassVar[Purpose] +class Purpose(_ASN1Object, enum.Enum): + SERVER_AUTH: _ASN1Object + CLIENT_AUTH: _ASN1Object class SSLSocket(socket.socket): context: SSLContext server_side: bool server_hostname: Optional[str] - if sys.version_info >= (3, 6): - session: Optional[SSLSession] - session_reused: Optional[bool] + session: Optional[SSLSession] + session_reused: Optional[bool] if sys.version_info < (3, 7): def __init__( self, @@ -293,8 +266,7 @@ class SSLSocket(socket.socket): @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... def cipher(self) -> Optional[Tuple[str, str, int]]: ... - if sys.version_info >= (3, 5): - def shared_ciphers(self) -> Optional[List[Tuple[str, str, int]]]: ... + def shared_ciphers(self) -> Optional[List[Tuple[str, str, int]]]: ... def compression(self) -> Optional[str]: ... def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... def selected_alpn_protocol(self) -> Optional[str]: ... @@ -318,31 +290,22 @@ if sys.version_info >= (3, 7): class SSLContext: check_hostname: bool - if sys.version_info >= (3, 6): - options: Options - else: - options: int + options: Options if sys.version_info >= (3, 8): post_handshake_auth: bool - if sys.version_info >= (3, 5): - def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> SSLContext: ... - else: - def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> SSLContext: ... + def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> SSLContext: ... @property def protocol(self) -> int: ... verify_flags: int verify_mode: int - if sys.version_info >= (3, 5): - def __init__(self, protocol: int = ...) -> None: ... - else: - def __init__(self, protocol: int) -> None: ... + def __init__(self, protocol: int = ...) -> None: ... def cert_store_stats(self) -> Dict[str, int]: ... def load_cert_chain( self, certfile: StrPath, keyfile: Optional[StrPath] = ..., password: Optional[_PasswordType] = ... ) -> None: ... def load_default_certs(self, purpose: Purpose = ...) -> None: ... def load_verify_locations( - self, cafile: Optional[StrPath] = ..., capath: Optional[StrPath] = ..., cadata: Union[Text, bytes, None] = ... + self, cafile: Optional[StrPath] = ..., capath: Optional[StrPath] = ..., cadata: Union[str, bytes, None] = ... ) -> None: ... def get_ca_certs(self, binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ... def set_default_verify_paths(self) -> None: ... @@ -358,102 +321,87 @@ class SSLContext: def set_servername_callback(self, __method: Optional[_SrvnmeCbType]) -> None: ... def load_dh_params(self, __path: str) -> None: ... def set_ecdh_curve(self, __name: str) -> None: ... - if sys.version_info >= (3, 6): - def wrap_socket( - self, - sock: socket.socket, - server_side: bool = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - server_hostname: Optional[str] = ..., - session: Optional[SSLSession] = ..., - ) -> SSLSocket: ... - else: - def wrap_socket( - self, - sock: socket.socket, - server_side: bool = ..., - do_handshake_on_connect: bool = ..., - suppress_ragged_eofs: bool = ..., - server_hostname: Optional[str] = ..., - ) -> SSLSocket: ... - if sys.version_info >= (3, 6): - def wrap_bio( - self, - incoming: MemoryBIO, - outgoing: MemoryBIO, - server_side: bool = ..., - server_hostname: Optional[str] = ..., - session: Optional[SSLSession] = ..., - ) -> SSLObject: ... - elif sys.version_info >= (3, 5): - def wrap_bio( - self, incoming: MemoryBIO, outgoing: MemoryBIO, server_side: bool = ..., server_hostname: Optional[str] = ... - ) -> SSLObject: ... + def wrap_socket( + self, + sock: socket.socket, + server_side: bool = ..., + do_handshake_on_connect: bool = ..., + suppress_ragged_eofs: bool = ..., + server_hostname: Optional[str] = ..., + session: Optional[SSLSession] = ..., + ) -> SSLSocket: ... + def wrap_bio( + self, + incoming: MemoryBIO, + outgoing: MemoryBIO, + server_side: bool = ..., + server_hostname: Optional[str] = ..., + session: Optional[SSLSession] = ..., + ) -> SSLObject: ... def session_stats(self) -> Dict[str, int]: ... if sys.version_info >= (3, 7): hostname_checks_common_name: bool maximum_version: TLSVersion minimum_version: TLSVersion -if sys.version_info >= (3, 5): - class SSLObject: - context: SSLContext - server_side: bool - server_hostname: Optional[str] - if sys.version_info >= (3, 6): - session: Optional[SSLSession] - session_reused: bool - if sys.version_info >= (3, 7): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - else: - def __init__( - self, sslobj: Any, owner: Optional[Union[SSLSocket, SSLObject]] = ..., session: Optional[Any] = ... - ) -> None: ... - def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... - def write(self, data: bytes) -> int: ... - @overload - def getpeercert(self, binary_form: Literal[False] = ...) -> Optional[_PeerCertRetDictType]: ... - @overload - def getpeercert(self, binary_form: Literal[True]) -> Optional[bytes]: ... - @overload - def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... - def selected_alpn_protocol(self) -> Optional[str]: ... - def selected_npn_protocol(self) -> Optional[str]: ... - def cipher(self) -> Optional[Tuple[str, str, int]]: ... - def shared_ciphers(self) -> Optional[List[Tuple[str, str, int]]]: ... - def compression(self) -> Optional[str]: ... - def pending(self) -> int: ... - def do_handshake(self) -> None: ... - def unwrap(self) -> None: ... - def version(self) -> Optional[str]: ... - def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... - if sys.version_info >= (3, 8): - def verify_client_post_handshake(self) -> None: ... - class MemoryBIO: - pending: int - eof: bool - def read(self, __size: int = ...) -> bytes: ... - def write(self, __buf: bytes) -> int: ... - def write_eof(self) -> None: ... - -if sys.version_info >= (3, 6): - class SSLSession: - id: bytes - time: int - timeout: int - ticket_lifetime_hint: int - has_ticket: bool - class VerifyFlags(enum.IntFlag): - VERIFY_DEFAULT: int - VERIFY_CRL_CHECK_LEAF: int - VERIFY_CRL_CHECK_CHAIN: int - VERIFY_X509_STRICT: int - VERIFY_X509_TRUSTED_FIRST: int - class VerifyMode(enum.IntEnum): - CERT_NONE: int - CERT_OPTIONAL: int - CERT_REQUIRED: int +class SSLObject: + context: SSLContext + server_side: bool + server_hostname: Optional[str] + session: Optional[SSLSession] + session_reused: bool + if sys.version_info >= (3, 7): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + else: + def __init__( + self, sslobj: Any, owner: Optional[Union[SSLSocket, SSLObject]] = ..., session: Optional[Any] = ... + ) -> None: ... + def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... + def write(self, data: bytes) -> int: ... + @overload + def getpeercert(self, binary_form: Literal[False] = ...) -> Optional[_PeerCertRetDictType]: ... + @overload + def getpeercert(self, binary_form: Literal[True]) -> Optional[bytes]: ... + @overload + def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + def selected_alpn_protocol(self) -> Optional[str]: ... + def selected_npn_protocol(self) -> Optional[str]: ... + def cipher(self) -> Optional[Tuple[str, str, int]]: ... + def shared_ciphers(self) -> Optional[List[Tuple[str, str, int]]]: ... + def compression(self) -> Optional[str]: ... + def pending(self) -> int: ... + def do_handshake(self) -> None: ... + def unwrap(self) -> None: ... + def version(self) -> Optional[str]: ... + def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... + if sys.version_info >= (3, 8): + def verify_client_post_handshake(self) -> None: ... + +class MemoryBIO: + pending: int + eof: bool + def read(self, __size: int = ...) -> bytes: ... + def write(self, __buf: bytes) -> int: ... + def write_eof(self) -> None: ... + +class SSLSession: + id: bytes + time: int + timeout: int + ticket_lifetime_hint: int + has_ticket: bool + +class VerifyFlags(enum.IntFlag): + VERIFY_DEFAULT: int + VERIFY_CRL_CHECK_LEAF: int + VERIFY_CRL_CHECK_CHAIN: int + VERIFY_X509_STRICT: int + VERIFY_X509_TRUSTED_FIRST: int + +class VerifyMode(enum.IntEnum): + CERT_NONE: int + CERT_OPTIONAL: int + CERT_REQUIRED: int # TODO below documented in cpython but not in docs.python.org # taken from python 3.4 diff --git a/mypy/typeshed/stdlib/stringprep.pyi b/mypy/typeshed/stdlib/stringprep.pyi index 604fd2f2cae7..cbc562d460f6 100644 --- a/mypy/typeshed/stdlib/stringprep.pyi +++ b/mypy/typeshed/stdlib/stringprep.pyi @@ -1,21 +1,19 @@ -from typing import Text - -def in_table_a1(code: Text) -> bool: ... -def in_table_b1(code: Text) -> bool: ... -def map_table_b3(code: Text) -> Text: ... -def map_table_b2(a: Text) -> Text: ... -def in_table_c11(code: Text) -> bool: ... -def in_table_c12(code: Text) -> bool: ... -def in_table_c11_c12(code: Text) -> bool: ... -def in_table_c21(code: Text) -> bool: ... -def in_table_c22(code: Text) -> bool: ... -def in_table_c21_c22(code: Text) -> bool: ... -def in_table_c3(code: Text) -> bool: ... -def in_table_c4(code: Text) -> bool: ... -def in_table_c5(code: Text) -> bool: ... -def in_table_c6(code: Text) -> bool: ... -def in_table_c7(code: Text) -> bool: ... -def in_table_c8(code: Text) -> bool: ... -def in_table_c9(code: Text) -> bool: ... -def in_table_d1(code: Text) -> bool: ... -def in_table_d2(code: Text) -> bool: ... +def in_table_a1(code: str) -> bool: ... +def in_table_b1(code: str) -> bool: ... +def map_table_b3(code: str) -> str: ... +def map_table_b2(a: str) -> str: ... +def in_table_c11(code: str) -> bool: ... +def in_table_c12(code: str) -> bool: ... +def in_table_c11_c12(code: str) -> bool: ... +def in_table_c21(code: str) -> bool: ... +def in_table_c22(code: str) -> bool: ... +def in_table_c21_c22(code: str) -> bool: ... +def in_table_c3(code: str) -> bool: ... +def in_table_c4(code: str) -> bool: ... +def in_table_c5(code: str) -> bool: ... +def in_table_c6(code: str) -> bool: ... +def in_table_c7(code: str) -> bool: ... +def in_table_c8(code: str) -> bool: ... +def in_table_c9(code: str) -> bool: ... +def in_table_d1(code: str) -> bool: ... +def in_table_d2(code: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index 096f8b7b85ca..ddda120254c8 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -1,27 +1,15 @@ import sys -from array import array -from mmap import mmap -from typing import Any, Iterator, Text, Tuple, Union +from _typeshed import ReadableBuffer, WriteableBuffer +from typing import Any, Iterator, Tuple, Union class error(Exception): ... -_FmtType = Union[bytes, Text] -if sys.version_info >= (3,): - _BufferType = Union[array[int], bytes, bytearray, memoryview, mmap] - _WriteBufferType = Union[array[Any], bytearray, memoryview, mmap] -else: - _BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] - _WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] - -def pack(fmt: _FmtType, *v: Any) -> bytes: ... -def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... -def unpack(__format: _FmtType, __buffer: _BufferType) -> Tuple[Any, ...]: ... -def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... - -if sys.version_info >= (3, 4): - def iter_unpack(__format: _FmtType, __buffer: _BufferType) -> Iterator[Tuple[Any, ...]]: ... - -def calcsize(__format: _FmtType) -> int: ... +def pack(fmt: Union[str, bytes], *v: Any) -> bytes: ... +def pack_into(fmt: Union[str, bytes], buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... +def unpack(__format: Union[str, bytes], __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... +def unpack_from(__format: Union[str, bytes], buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... +def iter_unpack(__format: Union[str, bytes], __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... +def calcsize(__format: Union[str, bytes]) -> int: ... class Struct: if sys.version_info >= (3, 7): @@ -29,10 +17,9 @@ class Struct: else: format: bytes size: int - def __init__(self, format: _FmtType) -> None: ... + def __init__(self, format: Union[str, bytes]) -> None: ... def pack(self, *v: Any) -> bytes: ... - def pack_into(self, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: _BufferType) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... - if sys.version_info >= (3, 4): - def iter_unpack(self, __buffer: _BufferType) -> Iterator[Tuple[Any, ...]]: ... + def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... + def unpack(self, __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... + def iter_unpack(self, __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 3a0361ca0931..9a431f082c37 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import TracebackType from typing import IO, Any, AnyStr, Callable, Generic, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload from typing_extensions import Literal @@ -24,15 +24,15 @@ if sys.version_info >= (3, 9): _FILE = Union[None, int, IO[Any]] _TXT = Union[bytes, str] if sys.version_info >= (3, 8): - _CMD = Union[AnyPath, Sequence[AnyPath]] + _CMD = Union[StrOrBytesPath, Sequence[StrOrBytesPath]] else: # Python 3.6 doesn't support _CMD being a single PathLike. # See: https://bugs.python.org/issue31961 - _CMD = Union[_TXT, Sequence[AnyPath]] + _CMD = Union[_TXT, Sequence[StrOrBytesPath]] if sys.platform == "win32": _ENV = Mapping[str, str] else: - _ENV = Union[Mapping[bytes, AnyPath], Mapping[str, AnyPath]] + _ENV = Union[Mapping[bytes, StrOrBytesPath], Mapping[str, StrOrBytesPath]] _S = TypeVar("_S") _T = TypeVar("_T") @@ -56,14 +56,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -84,14 +84,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -112,14 +112,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -140,14 +140,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], @@ -169,14 +169,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Any = ..., @@ -197,14 +197,14 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -228,14 +228,14 @@ else: def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -254,14 +254,14 @@ else: def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -280,14 +280,14 @@ else: def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], @@ -307,14 +307,14 @@ else: def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Any = ..., @@ -333,14 +333,14 @@ else: def run( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -360,14 +360,14 @@ else: def call( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -383,14 +383,14 @@ def call( def check_call( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: StrOrBytesPath = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -407,13 +407,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -432,13 +432,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -457,13 +457,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -482,13 +482,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], @@ -508,13 +508,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Any = ..., @@ -533,13 +533,13 @@ if sys.version_info >= (3, 7): def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -560,13 +560,13 @@ else: def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -584,13 +584,13 @@ else: def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -608,13 +608,13 @@ else: def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., startupinfo: Any = ..., creationflags: int = ..., @@ -632,13 +632,13 @@ else: def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Any = ..., @@ -656,13 +656,13 @@ else: def check_output( args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: _FILE = ..., stderr: _FILE = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Any = ..., @@ -724,14 +724,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -749,14 +749,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -774,14 +774,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], @@ -800,14 +800,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -825,14 +825,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., @@ -850,14 +850,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -876,14 +876,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -900,14 +900,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., @@ -924,14 +924,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], @@ -949,14 +949,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., @@ -973,14 +973,14 @@ class Popen(Generic[AnyStr]): cls, args: _CMD, bufsize: int = ..., - executable: Optional[AnyPath] = ..., + executable: Optional[StrOrBytesPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., - cwd: Optional[AnyPath] = ..., + cwd: Optional[StrOrBytesPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 175068861ee9..79d0881c96c2 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,7 +1,7 @@ import sys -from typing import IO, Any, NamedTuple, NoReturn, Optional, Text, Tuple, Union +from typing import IO, Any, NamedTuple, NoReturn, Optional, Union -_File = Union[Text, IO[bytes]] +_File = Union[str, IO[bytes]] class Error(Exception): ... @@ -20,23 +20,18 @@ AUDIO_FILE_ENCODING_ADPCM_G723_5: int AUDIO_FILE_ENCODING_ALAW_8: int AUDIO_UNKNOWN_SIZE: int -if sys.version_info >= (3, 0): - class _sunau_params(NamedTuple): - nchannels: int - sampwidth: int - framerate: int - nframes: int - comptype: str - compname: str - -else: - _sunau_params = Tuple[int, int, int, int, str, str] +class _sunau_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: str + compname: str class Au_read: def __init__(self, f: _File) -> None: ... - if sys.version_info >= (3, 3): - def __enter__(self) -> Au_read: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Au_read: ... + def __exit__(self, *args: Any) -> None: ... def getfp(self) -> Optional[IO[bytes]]: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -55,9 +50,8 @@ class Au_read: class Au_write: def __init__(self, f: _File) -> None: ... - if sys.version_info >= (3, 3): - def __enter__(self) -> Au_write: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Au_write: ... + def __exit__(self, *args: Any) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index b528481bf510..ea6ed55719c7 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,7 +1,7 @@ import sys -from typing import Any, List, Optional, Sequence, Text, Tuple +from typing import Any, List, Optional, Sequence, Tuple -def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... +def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... class SymbolTable(object): def __init__(self, raw_table: Any, filename: str) -> None: ... @@ -13,8 +13,6 @@ class SymbolTable(object): def is_nested(self) -> bool: ... def has_children(self) -> bool: ... def has_exec(self) -> bool: ... - if sys.version_info < (3, 0): - def has_import_star(self) -> bool: ... def get_identifiers(self) -> Sequence[str]: ... def lookup(self, name: str) -> Symbol: ... def get_symbols(self) -> List[Symbol]: ... @@ -42,8 +40,7 @@ class Symbol(object): def is_global(self) -> bool: ... def is_declared_global(self) -> bool: ... def is_local(self) -> bool: ... - if sys.version_info >= (3, 6): - def is_annotated(self) -> bool: ... + def is_annotated(self) -> bool: ... def is_free(self) -> bool: ... def is_imported(self) -> bool: ... def is_assigned(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index d431d2733b1c..8370f0b29477 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -8,6 +8,7 @@ from typing import ( AsyncGenerator, Callable, Dict, + FrozenSet, List, NoReturn, Optional, @@ -60,6 +61,8 @@ maxsize: int maxunicode: int meta_path: List[_MetaPathFinder] modules: Dict[str, ModuleType] +if sys.version_info >= (3, 10): + orig_argv: List[str] path: List[str] path_hooks: List[Any] # TODO precise type; function, path to finder path_importer_cache: Dict[str, Optional[PathEntryFinder]] @@ -74,6 +77,8 @@ ps2: str stdin: TextIO stdout: TextIO stderr: TextIO +if sys.version_info >= (3, 10): + stdlib_module_names: FrozenSet[str] __stdin__: TextIO __stdout__: TextIO __stderr__: TextIO diff --git a/mypy/typeshed/stdlib/tabnanny.pyi b/mypy/typeshed/stdlib/tabnanny.pyi index 7784c9fc8d1b..584c6d4e26bd 100644 --- a/mypy/typeshed/stdlib/tabnanny.pyi +++ b/mypy/typeshed/stdlib/tabnanny.pyi @@ -1,4 +1,4 @@ -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from typing import Iterable, Tuple verbose: int @@ -10,5 +10,5 @@ class NannyNag(Exception): def get_msg(self) -> str: ... def get_line(self) -> str: ... -def check(file: AnyPath) -> None: ... +def check(file: StrOrBytesPath) -> None: ... def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index afb88161d68b..16f759e986e6 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -1,8 +1,21 @@ import io import sys -from _typeshed import AnyPath, StrPath +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable, Iterator, Mapping +from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, Type, Union +from typing import IO, Dict, List, Optional, Protocol, Set, Tuple, Type, Union, overload +from typing_extensions import Literal + +class _Fileobj(Protocol): + def read(self, __size: int) -> bytes: ... + def write(self, __b: bytes) -> object: ... + def tell(self) -> int: ... + def seek(self, __pos: int) -> object: ... + def close(self) -> object: ... + # Optional fields: + # name: str | bytes + # mode: Literal["rb", "r+b", "wb", "xb"] # tar constants NUL: bytes @@ -45,20 +58,14 @@ REGULAR_TYPES: Tuple[bytes, ...] GNU_TYPES: Tuple[bytes, ...] PAX_FIELDS: Tuple[str, ...] PAX_NUMBER_FIELDS: Dict[str, type] - -if sys.version_info >= (3,): - PAX_NAME_FIELDS: Set[str] +PAX_NAME_FIELDS: Set[str] ENCODING: str -if sys.version_info < (3,): - TAR_PLAIN: int - TAR_GZIPPED: int - def open( - name: Optional[AnyPath] = ..., + name: Optional[StrOrBytesPath] = ..., mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., + fileobj: Optional[IO[bytes]] = ..., # depends on mode bufsize: int = ..., *, format: Optional[int] = ..., @@ -76,11 +83,11 @@ def open( class ExFileObject(io.BufferedReader): def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... -class TarFile(Iterable[TarInfo]): +class TarFile: OPEN_METH: Mapping[str, str] - name: Optional[AnyPath] - mode: str - fileobj: Optional[IO[bytes]] + name: Optional[StrOrBytesPath] + mode: Literal["r", "a", "w", "x"] + fileobj: Optional[_Fileobj] format: Optional[int] tarinfo: Type[TarInfo] dereference: Optional[bool] @@ -92,13 +99,11 @@ class TarFile(Iterable[TarInfo]): debug: Optional[int] errorlevel: Optional[int] offset: int # undocumented - if sys.version_info < (3,): - posix: bool def __init__( self, - name: Optional[AnyPath] = ..., - mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., + name: Optional[StrOrBytesPath] = ..., + mode: Literal["r", "a", "w", "x"] = ..., + fileobj: Optional[_Fileobj] = ..., format: Optional[int] = ..., tarinfo: Optional[Type[TarInfo]] = ..., dereference: Optional[bool] = ..., @@ -118,9 +123,9 @@ class TarFile(Iterable[TarInfo]): @classmethod def open( cls, - name: Optional[AnyPath] = ..., + name: Optional[StrOrBytesPath] = ..., mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., + fileobj: Optional[IO[bytes]] = ..., # depends on mode bufsize: int = ..., *, format: Optional[int] = ..., @@ -136,9 +141,9 @@ class TarFile(Iterable[TarInfo]): @classmethod def taropen( cls, - name: Optional[AnyPath], - mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., + name: Optional[StrOrBytesPath], + mode: Literal["r", "a", "w", "x"] = ..., + fileobj: Optional[_Fileobj] = ..., *, compresslevel: int = ..., format: Optional[int] = ..., @@ -150,12 +155,31 @@ class TarFile(Iterable[TarInfo]): debug: Optional[int] = ..., errorlevel: Optional[int] = ..., ) -> TarFile: ... + @overload @classmethod def gzopen( cls, - name: Optional[AnyPath], - mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., + name: Optional[StrOrBytesPath], + mode: Literal["r"] = ..., + fileobj: Optional[_GzipReadableFileobj] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @overload + @classmethod + def gzopen( + cls, + name: Optional[StrOrBytesPath], + mode: Literal["w", "x"], + fileobj: Optional[_GzipWritableFileobj] = ..., compresslevel: int = ..., *, format: Optional[int] = ..., @@ -170,8 +194,8 @@ class TarFile(Iterable[TarInfo]): @classmethod def bz2open( cls, - name: Optional[AnyPath], - mode: str = ..., + name: Optional[StrOrBytesPath], + mode: Literal["r", "w", "x"] = ..., fileobj: Optional[IO[bytes]] = ..., compresslevel: int = ..., *, @@ -187,8 +211,8 @@ class TarFile(Iterable[TarInfo]): @classmethod def xzopen( cls, - name: Optional[AnyPath], - mode: str = ..., + name: Optional[StrOrBytesPath], + mode: Literal["r", "w", "x"] = ..., fileobj: Optional[IO[bytes]] = ..., preset: Optional[int] = ..., *, @@ -204,36 +228,24 @@ class TarFile(Iterable[TarInfo]): def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> List[TarInfo]: ... def getnames(self) -> List[str]: ... - if sys.version_info >= (3, 5): - def list(self, verbose: bool = ..., *, members: Optional[List[TarInfo]] = ...) -> None: ... - else: - def list(self, verbose: bool = ...) -> None: ... + def list(self, verbose: bool = ..., *, members: Optional[List[TarInfo]] = ...) -> None: ... def next(self) -> Optional[TarInfo]: ... - if sys.version_info >= (3, 5): - def extractall( - self, path: AnyPath = ..., members: Optional[Iterable[TarInfo]] = ..., *, numeric_owner: bool = ... - ) -> None: ... - else: - def extractall(self, path: AnyPath = ..., members: Optional[Iterable[TarInfo]] = ...) -> None: ... - if sys.version_info >= (3, 5): - def extract( - self, member: Union[str, TarInfo], path: AnyPath = ..., set_attrs: bool = ..., *, numeric_owner: bool = ... - ) -> None: ... - else: - def extract(self, member: Union[str, TarInfo], path: AnyPath = ...) -> None: ... + def extractall( + self, path: StrOrBytesPath = ..., members: Optional[Iterable[TarInfo]] = ..., *, numeric_owner: bool = ... + ) -> None: ... + def extract( + self, member: Union[str, TarInfo], path: StrOrBytesPath = ..., set_attrs: bool = ..., *, numeric_owner: bool = ... + ) -> None: ... def extractfile(self, member: Union[str, TarInfo]) -> Optional[IO[bytes]]: ... - def makedir(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def makefile(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def makeunknown(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def makefifo(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def makedev(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def makelink(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - if sys.version_info >= (3, 5): - def chown(self, tarinfo: TarInfo, targetpath: AnyPath, numeric_owner: bool) -> None: ... # undocumented - else: - def chown(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def chmod(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented - def utime(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented + def makedir(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makefile(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makeunknown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makefifo(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makedev(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makelink(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def chown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath, numeric_owner: bool) -> None: ... # undocumented + def chmod(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def utime(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented if sys.version_info >= (3, 7): def add( self, @@ -243,7 +255,7 @@ class TarFile(Iterable[TarInfo]): *, filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ..., ) -> None: ... - elif sys.version_info >= (3,): + else: def add( self, name: StrPath, @@ -253,15 +265,6 @@ class TarFile(Iterable[TarInfo]): *, filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ..., ) -> None: ... - else: - def add( - self, - name: str, - arcname: Optional[str] = ..., - recursive: bool = ..., - exclude: Optional[Callable[[str], bool]] = ..., - filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ..., - ) -> None: ... def addfile(self, tarinfo: TarInfo, fileobj: Optional[IO[bytes]] = ...) -> None: ... def gettarinfo( self, name: Optional[str] = ..., arcname: Optional[str] = ..., fileobj: Optional[IO[bytes]] = ... @@ -269,18 +272,14 @@ class TarFile(Iterable[TarInfo]): def close(self) -> None: ... if sys.version_info >= (3, 9): - def is_tarfile(name: Union[AnyPath, IO[bytes]]) -> bool: ... + def is_tarfile(name: Union[StrOrBytesPath, IO[bytes]]) -> bool: ... else: - def is_tarfile(name: AnyPath) -> bool: ... + def is_tarfile(name: StrOrBytesPath) -> bool: ... if sys.version_info < (3, 8): def filemode(mode: int) -> str: ... # undocumented -if sys.version_info < (3,): - class TarFileCompat: - def __init__(self, filename: str, mode: str = ..., compression: int = ...) -> None: ... - class TarError(Exception): ... class ReadError(TarError): ... class CompressionError(TarError): ... @@ -309,12 +308,8 @@ class TarInfo: gname: str pax_headers: Mapping[str, str] def __init__(self, name: str = ...) -> None: ... - if sys.version_info >= (3,): - @classmethod - def frombuf(cls, buf: bytes, encoding: str, errors: str) -> TarInfo: ... - else: - @classmethod - def frombuf(cls, buf: bytes) -> TarInfo: ... + @classmethod + def frombuf(cls, buf: bytes, encoding: str, errors: str) -> TarInfo: ... @classmethod def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... @property diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index 31fd3eef81cd..0ee5b760b184 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -1,5 +1,4 @@ import socket -import sys from typing import Any, Callable, Match, Optional, Pattern, Sequence, Tuple, Union DEBUGLEVEL: int @@ -110,6 +109,5 @@ class Telnet: def expect( self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[float] = ... ) -> Tuple[int, Optional[Match[bytes]], bytes]: ... - if sys.version_info >= (3, 6): - def __enter__(self) -> Telnet: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __enter__(self) -> Telnet: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index ddf9f582809c..f618ce1751d2 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -28,7 +28,7 @@ if sys.version_info >= (3, 8): delete: bool = ..., *, errors: Optional[str] = ..., - ) -> IO[str]: ... + ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., @@ -41,7 +41,7 @@ if sys.version_info >= (3, 8): delete: bool = ..., *, errors: Optional[str] = ..., - ) -> IO[bytes]: ... + ) -> _TemporaryFileWrapper[bytes]: ... @overload def NamedTemporaryFile( mode: str = ..., @@ -54,7 +54,7 @@ if sys.version_info >= (3, 8): delete: bool = ..., *, errors: Optional[str] = ..., - ) -> IO[Any]: ... + ) -> _TemporaryFileWrapper[Any]: ... else: @overload @@ -67,7 +67,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., - ) -> IO[str]: ... + ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., @@ -78,7 +78,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., - ) -> IO[bytes]: ... + ) -> _TemporaryFileWrapper[bytes]: ... @overload def NamedTemporaryFile( mode: str = ..., @@ -89,7 +89,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., - ) -> IO[Any]: ... + ) -> _TemporaryFileWrapper[Any]: ... if sys.platform == "win32": TemporaryFile = NamedTemporaryFile @@ -163,38 +163,44 @@ else: dir: Optional[_DirT[AnyStr]] = ..., ) -> IO[Any]: ... -class _TemporaryFileWrapper(IO[str]): - file: IO[str] - name: Any +class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): + file: IO[AnyStr] # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter + name: str delete: bool - def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... - def __enter__(self) -> _TemporaryFileWrapper: ... + def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... + def __enter__(self) -> _TemporaryFileWrapper[AnyStr]: ... def __exit__( self, exc: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType] ) -> Optional[bool]: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: ... - def unlink(self, path: str) -> None: ... # These methods don't exist directly on this object, but # are delegated to the underlying IO object through __getattr__. # We need to add them here so that this class is concrete. - def __iter__(self) -> Iterator[str]: ... - def __next__(self) -> str: ... + def __iter__(self) -> Iterator[AnyStr]: ... + # FIXME: __next__ doesn't actually exist on this class and should be removed: + # see also https://github.com/python/typeshed/pull/5456#discussion_r633068648 + # >>> import tempfile + # >>> ntf=tempfile.NamedTemporaryFile() + # >>> next(ntf) + # Traceback (most recent call last): + # File "", line 1, in + # TypeError: '_TemporaryFileWrapper' object is not an iterator + def __next__(self) -> AnyStr: ... def fileno(self) -> int: ... def flush(self) -> None: ... def isatty(self) -> bool: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... + def read(self, n: int = ...) -> AnyStr: ... def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readline(self, limit: int = ...) -> AnyStr: ... + def readlines(self, hint: int = ...) -> list[AnyStr]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def seekable(self) -> bool: ... def tell(self) -> int: ... def truncate(self, size: Optional[int] = ...) -> int: ... def writable(self) -> bool: ... - def write(self, s: str) -> int: ... - def writelines(self, lines: Iterable[str]) -> None: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, lines: Iterable[AnyStr]) -> None: ... # It does not actually derive from IO[AnyStr], but it does implement the # protocol. diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index af0b0af89d9b..de75375056e0 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar, Union +from typing import Any, Callable, Iterable, List, Mapping, Optional, Type, TypeVar, Union # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -11,20 +11,11 @@ _T = TypeVar("_T") __all__: List[str] def active_count() -> int: ... - -if sys.version_info < (3,): - def activeCount() -> int: ... - def current_thread() -> Thread: ... def currentThread() -> Thread: ... - -if sys.version_info >= (3,): - def get_ident() -> int: ... - +def get_ident() -> int: ... def enumerate() -> List[Thread]: ... - -if sys.version_info >= (3, 4): - def main_thread() -> Thread: ... +def main_thread() -> Thread: ... if sys.version_info >= (3, 8): from _thread import get_native_id as get_native_id @@ -33,8 +24,7 @@ def settrace(func: _TF) -> None: ... def setprofile(func: Optional[_PF]) -> None: ... def stack_size(size: int = ...) -> int: ... -if sys.version_info >= (3,): - TIMEOUT_MAX: float +TIMEOUT_MAX: float class ThreadError(Exception): ... @@ -47,31 +37,21 @@ class Thread: name: str ident: Optional[int] daemon: bool - if sys.version_info >= (3,): - def __init__( - self, - group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[str] = ..., - args: Iterable[Any] = ..., - kwargs: Optional[Mapping[str, Any]] = ..., - *, - daemon: Optional[bool] = ..., - ) -> None: ... - else: - def __init__( - self, - group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[Text] = ..., - args: Iterable[Any] = ..., - kwargs: Optional[Mapping[Text, Any]] = ..., - ) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., + *, + daemon: Optional[bool] = ..., + ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: Optional[float] = ...) -> None: ... def getName(self) -> str: ... - def setName(self, name: Text) -> None: ... + def setName(self, name: str) -> None: ... if sys.version_info >= (3, 8): @property def native_id(self) -> Optional[int]: ... # only available on some platforms @@ -89,10 +69,7 @@ class Lock: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... def locked(self) -> bool: ... @@ -102,10 +79,7 @@ class _RLock: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... RLock = _RLock @@ -116,14 +90,10 @@ class Condition: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... def wait(self, timeout: Optional[float] = ...) -> bool: ... - if sys.version_info >= (3,): - def wait_for(self, predicate: Callable[[], _T], timeout: Optional[float] = ...) -> _T: ... + def wait_for(self, predicate: Callable[[], _T], timeout: Optional[float] = ...) -> _T: ... def notify(self, n: int = ...) -> None: ... def notify_all(self) -> None: ... def notifyAll(self) -> None: ... @@ -133,12 +103,8 @@ class Semaphore: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... - if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... - def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... - else: - def acquire(self, blocking: bool = ...) -> bool: ... - def __enter__(self, blocking: bool = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... + def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... if sys.version_info >= (3, 9): def release(self, n: int = ...) -> None: ... else: @@ -149,8 +115,6 @@ class BoundedSemaphore(Semaphore): ... class Event: def __init__(self) -> None: ... def is_set(self) -> bool: ... - if sys.version_info < (3,): - def isSet(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... def wait(self, timeout: Optional[float] = ...) -> bool: ... @@ -162,27 +126,22 @@ if sys.version_info >= (3, 8): ExceptHookArgs = _ExceptHookArgs class Timer(Thread): - if sys.version_info >= (3,): - def __init__( - self, - interval: float, - function: Callable[..., Any], - args: Optional[Iterable[Any]] = ..., - kwargs: Optional[Mapping[str, Any]] = ..., - ) -> None: ... - else: - def __init__( - self, interval: float, function: Callable[..., Any], args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ... - ) -> None: ... + def __init__( + self, + interval: float, + function: Callable[..., Any], + args: Optional[Iterable[Any]] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., + ) -> None: ... def cancel(self) -> None: ... -if sys.version_info >= (3,): - class Barrier: - parties: int - n_waiting: int - broken: bool - def __init__(self, parties: int, action: Optional[Callable[[], None]] = ..., timeout: Optional[float] = ...) -> None: ... - def wait(self, timeout: Optional[float] = ...) -> int: ... - def reset(self) -> None: ... - def abort(self) -> None: ... - class BrokenBarrierError(RuntimeError): ... +class Barrier: + parties: int + n_waiting: int + broken: bool + def __init__(self, parties: int, action: Optional[Callable[[], None]] = ..., timeout: Optional[float] = ...) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> int: ... + def reset(self) -> None: ... + def abort(self) -> None: ... + +class BrokenBarrierError(RuntimeError): ... diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 6e926c68dc39..48111fba1f79 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,13 +1,9 @@ import sys +from types import SimpleNamespace from typing import Any, NamedTuple, Optional, Tuple, Union -if sys.version_info >= (3, 3): - from types import SimpleNamespace - _TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] -if sys.version_info < (3, 3): - accept2dyear: bool altzone: int daylight: int timezone: int @@ -20,7 +16,7 @@ if sys.version_info >= (3, 7): CLOCK_PROF: int # FreeBSD, NetBSD, OpenBSD CLOCK_UPTIME: int # FreeBSD, OpenBSD -if sys.version_info >= (3, 3) and sys.platform != "win32": +if sys.platform != "win32": CLOCK_MONOTONIC: int CLOCK_MONOTONIC_RAW: int CLOCK_PROCESS_CPUTIME_ID: int @@ -52,36 +48,29 @@ class _struct_time(NamedTuple): @property def n_unnamed_fields(self) -> int: ... -if sys.version_info >= (3, 3): - class struct_time(_struct_time): - def __init__( - self, - o: Union[ - Tuple[int, int, int, int, int, int, int, int, int], - Tuple[int, int, int, int, int, int, int, int, int, str], - Tuple[int, int, int, int, int, int, int, int, int, str, int], - ], - _arg: Any = ..., - ) -> None: ... - def __new__( - cls, - o: Union[ - Tuple[int, int, int, int, int, int, int, int, int], - Tuple[int, int, int, int, int, int, int, int, int, str], - Tuple[int, int, int, int, int, int, int, int, int, str, int], - ], - _arg: Any = ..., - ) -> struct_time: ... - if sys.version_info >= (3, 6) or sys.platform != "win32": - @property - def tm_zone(self) -> str: ... - @property - def tm_gmtoff(self) -> int: ... - -else: - class struct_time(_struct_time): - def __init__(self, o: _TimeTuple, _arg: Any = ...) -> None: ... - def __new__(cls, o: _TimeTuple, _arg: Any = ...) -> struct_time: ... +class struct_time(_struct_time): + def __init__( + self, + o: Union[ + Tuple[int, int, int, int, int, int, int, int, int], + Tuple[int, int, int, int, int, int, int, int, int, str], + Tuple[int, int, int, int, int, int, int, int, int, str, int], + ], + _arg: Any = ..., + ) -> None: ... + def __new__( + cls, + o: Union[ + Tuple[int, int, int, int, int, int, int, int, int], + Tuple[int, int, int, int, int, int, int, int, int, str], + Tuple[int, int, int, int, int, int, int, int, int, str, int], + ], + _arg: Any = ..., + ) -> struct_time: ... + @property + def tm_zone(self) -> str: ... + @property + def tm_gmtoff(self) -> int: ... def asctime(t: Union[_TimeTuple, struct_time] = ...) -> str: ... @@ -100,15 +89,15 @@ def time() -> float: ... if sys.platform != "win32": def tzset() -> None: ... # Unix only -if sys.version_info >= (3, 3): - def get_clock_info(name: str) -> SimpleNamespace: ... - def monotonic() -> float: ... - def perf_counter() -> float: ... - def process_time() -> float: ... - if sys.platform != "win32": - def clock_getres(clk_id: int) -> float: ... # Unix only - def clock_gettime(clk_id: int) -> float: ... # Unix only - def clock_settime(clk_id: int, time: float) -> None: ... # Unix only +def get_clock_info(name: str) -> SimpleNamespace: ... +def monotonic() -> float: ... +def perf_counter() -> float: ... +def process_time() -> float: ... + +if sys.platform != "win32": + def clock_getres(clk_id: int) -> float: ... # Unix only + def clock_gettime(clk_id: int) -> float: ... # Unix only + def clock_settime(clk_id: int, time: float) -> None: ... # Unix only if sys.version_info >= (3, 7): if sys.platform != "win32": diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index 8de9af28d7ad..18ab9bd93db4 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,43 +1,30 @@ -import sys -from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Text, Tuple, Union +from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -_str = Union[str, Text] _Timer = Callable[[], float] -_stmt = Union[_str, Callable[[], Any]] +_Stmt = Union[str, Callable[[], Any]] default_timer: _Timer class Timer: - if sys.version_info >= (3, 5): - def __init__( - self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., globals: Optional[Dict[str, Any]] = ... - ) -> None: ... - else: - def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... + def __init__( + self, stmt: _Stmt = ..., setup: _Stmt = ..., timer: _Timer = ..., globals: Optional[Dict[str, Any]] = ... + ) -> None: ... def print_exc(self, file: Optional[IO[str]] = ...) -> None: ... def timeit(self, number: int = ...) -> float: ... def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... - if sys.version_info >= (3, 6): - def autorange(self, callback: Optional[Callable[[int, float], Any]] = ...) -> Tuple[int, float]: ... + def autorange(self, callback: Optional[Callable[[int, float], Any]] = ...) -> Tuple[int, float]: ... -if sys.version_info >= (3, 5): - def timeit( - stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ..., globals: Optional[Dict[str, Any]] = ... - ) -> float: ... - def repeat( - stmt: _stmt = ..., - setup: _stmt = ..., - timer: _Timer = ..., - repeat: int = ..., - number: int = ..., - globals: Optional[Dict[str, Any]] = ..., - ) -> List[float]: ... - -else: - def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... - def repeat( - stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ... - ) -> List[float]: ... +def timeit( + stmt: _Stmt = ..., setup: _Stmt = ..., timer: _Timer = ..., number: int = ..., globals: Optional[Dict[str, Any]] = ... +) -> float: ... +def repeat( + stmt: _Stmt = ..., + setup: _Stmt = ..., + timer: _Timer = ..., + repeat: int = ..., + number: int = ..., + globals: Optional[Dict[str, Any]] = ..., +) -> List[float]: ... _timerFunc = Callable[[], float] diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index db1dd1584ae8..8d328abae4d5 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -1,6 +1,6 @@ import _tkinter import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from enum import Enum from tkinter.constants import * # comment this out to find undefined identifier names with flake8 from tkinter.font import _FontDescription @@ -2791,7 +2791,7 @@ class PhotoImage(Image): *, data: Union[str, bytes] = ..., # not same as data argument of put() format: str = ..., - file: AnyPath = ..., + file: StrOrBytesPath = ..., gamma: float = ..., height: int = ..., palette: Union[int, str] = ..., @@ -2802,7 +2802,7 @@ class PhotoImage(Image): *, data: Union[str, bytes] = ..., format: str = ..., - file: AnyPath = ..., + file: StrOrBytesPath = ..., gamma: float = ..., height: int = ..., palette: Union[int, str] = ..., @@ -2819,7 +2819,9 @@ class PhotoImage(Image): def put( self, data: Union[str, _TkinterSequence[str], _TkinterSequence2D[_Color]], to: Optional[Tuple[int, int]] = ... ) -> None: ... - def write(self, filename: AnyPath, format: Optional[str] = ..., from_coords: Optional[Tuple[int, int]] = ...) -> None: ... + def write( + self, filename: StrOrBytesPath, format: Optional[str] = ..., from_coords: Optional[Tuple[int, int]] = ... + ) -> None: ... if sys.version_info >= (3, 8): def transparency_get(self, x: int, y: int) -> bool: ... def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... @@ -2833,10 +2835,10 @@ class BitmapImage(Image): *, background: _Color = ..., data: Union[str, bytes] = ..., - file: AnyPath = ..., + file: StrOrBytesPath = ..., foreground: _Color = ..., maskdata: str = ..., - maskfile: AnyPath = ..., + maskfile: StrOrBytesPath = ..., ) -> None: ... def image_names() -> Tuple[str, ...]: ... diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index a806a466b8ea..4833438e4128 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -26,8 +26,6 @@ GREATER: int EQUAL: int DOT: int PERCENT: int -if sys.version_info < (3,): - BACKQUOTE: int LBRACE: int RBRACE: int EQEQUAL: int @@ -53,16 +51,11 @@ DOUBLESTAREQUAL: int DOUBLESLASH: int DOUBLESLASHEQUAL: int AT: int -if sys.version_info >= (3,): - RARROW: int - ELLIPSIS: int -if sys.version_info >= (3, 5): - ATEQUAL: int - if sys.version_info < (3, 7): - # These were removed in Python 3.7 but added back in Python 3.8 - AWAIT: int - ASYNC: int -if sys.version_info >= (3, 8): +RARROW: int +ELLIPSIS: int +ATEQUAL: int +if sys.version_info < (3, 7) or sys.version_info >= (3, 8): + # These were removed in Python 3.7 but added back in Python 3.8 AWAIT: int ASYNC: int OP: int diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 23babea287e3..a6e6abae5037 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -1,6 +1,6 @@ import sys +from _typeshed import StrOrBytesPath from builtins import open as _builtin_open -from os import PathLike from token import * # noqa: F403 from typing import ( Any, @@ -62,7 +62,7 @@ def untokenize(iterable: Iterable[_Token]) -> Any: ... def detect_encoding(readline: Callable[[], bytes]) -> Tuple[str, Sequence[bytes]]: ... def tokenize(readline: Callable[[], bytes]) -> Generator[TokenInfo, None, None]: ... def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ... # undocumented -def open(filename: Union[str, bytes, int, PathLike[Any]]) -> TextIO: ... +def open(filename: Union[StrOrBytesPath, int]) -> TextIO: ... def group(*choices: str) -> str: ... # undocumented def any(*choices: str) -> str: ... # undocumented def maybe(*choices: str) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 3c24ee21bee4..dca5f480c3ba 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -17,16 +17,6 @@ if sys.version_info >= (3, 10): chain: bool = ..., ) -> None: ... -elif sys.version_info >= (3,): - def print_exception( - etype: Optional[Type[BaseException]], - value: Optional[BaseException], - tb: Optional[TracebackType], - limit: Optional[int] = ..., - file: Optional[IO[str]] = ..., - chain: bool = ..., - ) -> None: ... - else: def print_exception( etype: Optional[Type[BaseException]], @@ -34,29 +24,18 @@ else: tb: Optional[TracebackType], limit: Optional[int] = ..., file: Optional[IO[str]] = ..., + chain: bool = ..., ) -> None: ... -if sys.version_info >= (3,): - def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., chain: bool = ...) -> None: ... - def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., chain: bool = ...) -> None: ... - -else: - def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... - def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... - +def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., chain: bool = ...) -> None: ... +def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., chain: bool = ...) -> None: ... def print_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ..., file: Optional[IO[str]] = ...) -> None: ... +def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> StackSummary: ... +def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> StackSummary: ... +def format_list(extracted_list: List[FrameSummary]) -> List[str]: ... -if sys.version_info >= (3, 5): - def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> StackSummary: ... - def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> StackSummary: ... - def format_list(extracted_list: List[FrameSummary]) -> List[str]: ... - # undocumented - def print_list(extracted_list: List[FrameSummary], file: Optional[SupportsWrite[str]] = ...) -> None: ... - -else: - def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[_PT]: ... - def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> List[_PT]: ... - def format_list(extracted_list: List[_PT]) -> List[str]: ... +# undocumented +def print_list(extracted_list: List[FrameSummary], file: Optional[SupportsWrite[str]] = ...) -> None: ... if sys.version_info >= (3, 10): def format_exception_only(__exc: Optional[Type[BaseException]], value: Optional[BaseException] = ...) -> List[str]: ... @@ -73,125 +52,106 @@ if sys.version_info >= (3, 10): chain: bool = ..., ) -> List[str]: ... -elif sys.version_info >= (3,): - def format_exception( - etype: Optional[Type[BaseException]], - value: Optional[BaseException], - tb: Optional[TracebackType], - limit: Optional[int] = ..., - chain: bool = ..., - ) -> List[str]: ... - else: def format_exception( etype: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType], limit: Optional[int] = ..., + chain: bool = ..., ) -> List[str]: ... -if sys.version_info >= (3,): - def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ... - -else: - def format_exc(limit: Optional[int] = ...) -> str: ... - +def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ... def format_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[str]: ... def format_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> List[str]: ... - -if sys.version_info >= (3, 4): - def clear_frames(tb: TracebackType) -> None: ... - -if sys.version_info >= (3, 5): - def walk_stack(f: Optional[FrameType]) -> Iterator[Tuple[FrameType, int]]: ... - def walk_tb(tb: Optional[TracebackType]) -> Iterator[Tuple[FrameType, int]]: ... - -if sys.version_info < (3,): - def tb_lineno(tb: TracebackType) -> int: ... - -if sys.version_info >= (3, 5): - class TracebackException: - __cause__: TracebackException - __context__: TracebackException - __suppress_context__: bool - stack: StackSummary - exc_type: Type[BaseException] - filename: str - lineno: int - text: str - offset: int - msg: str - if sys.version_info >= (3, 10): - def __init__( - self, - exc_type: Type[BaseException], - exc_value: BaseException, - exc_traceback: TracebackType, - *, - limit: Optional[int] = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - compact: bool = ..., - _seen: Optional[Set[int]] = ..., - ) -> None: ... - @classmethod - def from_exception( - cls, - exc: BaseException, - *, - limit: Optional[int] = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - compact: bool = ..., - ) -> TracebackException: ... - else: - def __init__( - self, - exc_type: Type[BaseException], - exc_value: BaseException, - exc_traceback: TracebackType, - *, - limit: Optional[int] = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - _seen: Optional[Set[int]] = ..., - ) -> None: ... - @classmethod - def from_exception( - cls, exc: BaseException, *, limit: Optional[int] = ..., lookup_lines: bool = ..., capture_locals: bool = ... - ) -> TracebackException: ... - def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... - def format_exception_only(self) -> Generator[str, None, None]: ... - class FrameSummary(Iterable[Any]): - filename: str - lineno: int - name: str - line: str - locals: Optional[Dict[str, str]] +def clear_frames(tb: TracebackType) -> None: ... +def walk_stack(f: Optional[FrameType]) -> Iterator[Tuple[FrameType, int]]: ... +def walk_tb(tb: Optional[TracebackType]) -> Iterator[Tuple[FrameType, int]]: ... + +class TracebackException: + __cause__: TracebackException + __context__: TracebackException + __suppress_context__: bool + stack: StackSummary + exc_type: Type[BaseException] + filename: str + lineno: int + text: str + offset: int + msg: str + if sys.version_info >= (3, 10): def __init__( self, - filename: str, - lineno: int, - name: str, + exc_type: Type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType, *, - lookup_line: bool = ..., - locals: Optional[Mapping[str, str]] = ..., - line: Optional[str] = ..., + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + _seen: Optional[Set[int]] = ..., ) -> None: ... - # TODO: more precise typing for __getitem__ and __iter__, - # for a namedtuple-like view on (filename, lineno, name, str). - def __getitem__(self, i: int) -> Any: ... - def __iter__(self) -> Iterator[Any]: ... - class StackSummary(List[FrameSummary]): @classmethod - def extract( + def from_exception( cls, - frame_gen: Generator[Tuple[FrameType, int], None, None], + exc: BaseException, + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + ) -> TracebackException: ... + else: + def __init__( + self, + exc_type: Type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType, *, limit: Optional[int] = ..., lookup_lines: bool = ..., capture_locals: bool = ..., - ) -> StackSummary: ... + _seen: Optional[Set[int]] = ..., + ) -> None: ... @classmethod - def from_list(cls, a_list: List[_PT]) -> StackSummary: ... - def format(self) -> List[str]: ... + def from_exception( + cls, exc: BaseException, *, limit: Optional[int] = ..., lookup_lines: bool = ..., capture_locals: bool = ... + ) -> TracebackException: ... + def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... + def format_exception_only(self) -> Generator[str, None, None]: ... + +class FrameSummary(Iterable[Any]): + filename: str + lineno: int + name: str + line: str + locals: Optional[Dict[str, str]] + def __init__( + self, + filename: str, + lineno: int, + name: str, + *, + lookup_line: bool = ..., + locals: Optional[Mapping[str, str]] = ..., + line: Optional[str] = ..., + ) -> None: ... + # TODO: more precise typing for __getitem__ and __iter__, + # for a namedtuple-like view on (filename, lineno, name, str). + def __getitem__(self, i: int) -> Any: ... + def __iter__(self) -> Iterator[Any]: ... + +class StackSummary(List[FrameSummary]): + @classmethod + def extract( + cls, + frame_gen: Generator[Tuple[FrameType, int], None, None], + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + ) -> StackSummary: ... + @classmethod + def from_list(cls, a_list: List[_PT]) -> StackSummary: ... + def format(self) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index a44b25926968..e04a96257d96 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -1,18 +1,11 @@ -import sys -from typing import Any, Callable, Dict, List, Optional, Sequence, Text, Tuple, TypeVar, Union, overload - -if sys.version_info >= (3,): - from tkinter import Canvas, PhotoImage -else: - # TODO: Replace these aliases once we have Python 2 stubs for the Tkinter module. - Canvas = Any - PhotoImage = Any +from tkinter import Canvas, PhotoImage +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, overload # Note: '_Color' is the alias we use for arguments and _AnyColor is the # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[Text, Tuple[float, float, float]] +_Color = Union[str, Tuple[float, float, float]] _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. @@ -32,17 +25,16 @@ class TurtleScreenBase(object): xscale: float = ... yscale: float = ... def __init__(self, cv: Canvas) -> None: ... - if sys.version_info >= (3,): - def mainloop(self) -> None: ... - def textinput(self, title: str, prompt: str) -> Optional[str]: ... - def numinput( - self, - title: str, - prompt: str, - default: Optional[float] = ..., - minval: Optional[float] = ..., - maxval: Optional[float] = ..., - ) -> Optional[float]: ... + def mainloop(self) -> None: ... + def textinput(self, title: str, prompt: str) -> Optional[str]: ... + def numinput( + self, + title: str, + prompt: str, + default: Optional[float] = ..., + minval: Optional[float] = ..., + maxval: Optional[float] = ..., + ) -> Optional[float]: ... class Terminator(Exception): ... class TurtleGraphicsError(Exception): ... @@ -102,9 +94,8 @@ class TurtleScreen(TurtleScreenBase): resetscreen = reset clearscreen = clear addshape = register_shape - if sys.version_info >= (3,): - def onkeypress(self, fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... - onkeyrelease = onkey + def onkeypress(self, fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... + onkeyrelease = onkey class TNavigator(object): START_ORIENTATION: Dict[str, Vec2D] = ... @@ -239,19 +230,18 @@ class RawTurtle(TPen, TNavigator): def shapesize( self, stretch_wid: Optional[float] = ..., stretch_len: Optional[float] = ..., outline: Optional[float] = ... ) -> None: ... - if sys.version_info >= (3,): - @overload - def shearfactor(self, shear: None = ...) -> float: ... - @overload - def shearfactor(self, shear: float) -> None: ... - # Unsafely overlaps when no arguments are provided - @overload - def shapetransform(self) -> Tuple[float, float, float, float]: ... # type: ignore - @overload - def shapetransform( - self, t11: Optional[float] = ..., t12: Optional[float] = ..., t21: Optional[float] = ..., t22: Optional[float] = ... - ) -> None: ... - def get_shapepoly(self) -> Optional[_PolygonCoords]: ... + @overload + def shearfactor(self, shear: None = ...) -> float: ... + @overload + def shearfactor(self, shear: float) -> None: ... + # Unsafely overlaps when no arguments are provided + @overload + def shapetransform(self) -> Tuple[float, float, float, float]: ... # type: ignore + @overload + def shapetransform( + self, t11: Optional[float] = ..., t12: Optional[float] = ..., t21: Optional[float] = ..., t22: Optional[float] = ... + ) -> None: ... + def get_shapepoly(self) -> Optional[_PolygonCoords]: ... def settiltangle(self, angle: float) -> None: ... @overload def tiltangle(self, angle: None = ...) -> float: ... @@ -317,12 +307,10 @@ def write_docstringdict(filename: str = ...) -> None: ... # Note: mainloop() was always present in the global scope, but was added to # TurtleScreenBase in Python 3.0 def mainloop() -> None: ... - -if sys.version_info >= (3,): - def textinput(title: str, prompt: str) -> Optional[str]: ... - def numinput( - title: str, prompt: str, default: Optional[float] = ..., minval: Optional[float] = ..., maxval: Optional[float] = ... - ) -> Optional[float]: ... +def textinput(title: str, prompt: str) -> Optional[str]: ... +def numinput( + title: str, prompt: str, default: Optional[float] = ..., minval: Optional[float] = ..., maxval: Optional[float] = ... +) -> Optional[float]: ... # Functions copied from TurtleScreen: @@ -375,9 +363,10 @@ onscreenclick = onclick resetscreen = reset clearscreen = clear addshape = register_shape -if sys.version_info >= (3,): - def onkeypress(fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... - onkeyrelease = onkey + +def onkeypress(fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... + +onkeyrelease = onkey # Functions copied from _Screen: @@ -508,21 +497,19 @@ def shape(name: str) -> None: ... def shapesize() -> Tuple[float, float, float]: ... # type: ignore @overload def shapesize(stretch_wid: Optional[float] = ..., stretch_len: Optional[float] = ..., outline: Optional[float] = ...) -> None: ... +@overload +def shearfactor(shear: None = ...) -> float: ... +@overload +def shearfactor(shear: float) -> None: ... -if sys.version_info >= (3,): - @overload - def shearfactor(shear: None = ...) -> float: ... - @overload - def shearfactor(shear: float) -> None: ... - # Unsafely overlaps when no arguments are provided - @overload - def shapetransform() -> Tuple[float, float, float, float]: ... # type: ignore - @overload - def shapetransform( - t11: Optional[float] = ..., t12: Optional[float] = ..., t21: Optional[float] = ..., t22: Optional[float] = ... - ) -> None: ... - def get_shapepoly() -> Optional[_PolygonCoords]: ... - +# Unsafely overlaps when no arguments are provided +@overload +def shapetransform() -> Tuple[float, float, float, float]: ... # type: ignore +@overload +def shapetransform( + t11: Optional[float] = ..., t12: Optional[float] = ..., t21: Optional[float] = ..., t22: Optional[float] = ... +) -> None: ... +def get_shapepoly() -> Optional[_PolygonCoords]: ... def settiltangle(angle: float) -> None: ... @overload def tiltangle(angle: None = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 2b4d32392a45..e280150e3406 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -2,7 +2,23 @@ import sys import typing from importlib.abc import _LoaderProtocol from importlib.machinery import ModuleSpec -from typing import Any, Awaitable, Callable, Dict, Generic, Iterable, Iterator, Mapping, Optional, Tuple, Type, TypeVar, overload +from typing import ( + Any, + AsyncGenerator, + Awaitable, + Callable, + Dict, + Generator, + Generic, + Iterable, + Iterator, + Mapping, + Optional, + Tuple, + Type, + TypeVar, + overload, +) from typing_extensions import Literal, final # Note, all classes "defined" here require special handling. @@ -12,6 +28,7 @@ _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) _KT = TypeVar("_KT") _VT = TypeVar("_VT") +_V_co = TypeVar("_V_co", covariant=True) class _Cell: cell_contents: Any @@ -142,28 +159,28 @@ class ModuleType: __spec__: Optional[ModuleSpec] def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... -class GeneratorType: +class GeneratorType(Generator[_T_co, _T_contra, _V_co]): gi_code: CodeType gi_frame: FrameType gi_running: bool - gi_yieldfrom: Optional[GeneratorType] - def __iter__(self) -> GeneratorType: ... - def __next__(self) -> Any: ... + gi_yieldfrom: Optional[GeneratorType[_T_co, _T_contra, Any]] + def __iter__(self) -> GeneratorType[_T_co, _T_contra, _V_co]: ... + def __next__(self) -> _T_co: ... def close(self) -> None: ... - def send(self, __arg: Any) -> Any: ... + def send(self, __arg: _T_contra) -> _T_co: ... @overload def throw( self, __typ: Type[BaseException], __val: typing.Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... - ) -> Any: ... + ) -> _T_co: ... @overload - def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... -class AsyncGeneratorType(Generic[_T_co, _T_contra]): +class AsyncGeneratorType(AsyncGenerator[_T_co, _T_contra]): ag_await: Optional[Awaitable[Any]] ag_frame: FrameType ag_running: bool ag_code: CodeType - def __aiter__(self) -> Awaitable[AsyncGeneratorType[_T_co, _T_contra]]: ... + def __aiter__(self) -> AsyncGeneratorType[_T_co, _T_contra]: ... def __anext__(self) -> Awaitable[_T_co]: ... def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... @overload @@ -335,3 +352,5 @@ if sys.version_info >= (3, 10): NotImplementedType = _NotImplementedType # noqa F811 from builtins class Union: __args__: Tuple[Any, ...] + def __or__(self, obj: Any) -> Union: ... + def __ror__(self, obj: Any) -> Union: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 0250866f3eb8..807e37ef29d6 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -3,9 +3,16 @@ import sys from typing import ( TYPE_CHECKING as TYPE_CHECKING, Any, + AsyncContextManager as AsyncContextManager, + AsyncGenerator as AsyncGenerator, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, Callable, + ChainMap as ChainMap, ClassVar as ClassVar, ContextManager as ContextManager, + Coroutine as Coroutine, Counter as Counter, DefaultDict as DefaultDict, Deque as Deque, @@ -55,15 +62,9 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore def update(self: _T, __m: _T) -> None: ... - if sys.version_info >= (3, 0): - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - else: - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... + def items(self) -> ItemsView[str, object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... # TypedDict is a (non-subscriptable) special form. @@ -71,21 +72,6 @@ TypedDict: object = ... OrderedDict = _Alias() -if sys.version_info >= (3, 3): - from typing import ChainMap as ChainMap - -if sys.version_info >= (3, 5): - from typing import ( - AsyncContextManager as AsyncContextManager, - AsyncIterable as AsyncIterable, - AsyncIterator as AsyncIterator, - Awaitable as Awaitable, - Coroutine as Coroutine, - ) - -if sys.version_info >= (3, 6): - from typing import AsyncGenerator as AsyncGenerator - def get_type_hints( obj: Callable[..., Any], globalns: Optional[Dict[str, Any]] = ..., diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index a83d79ff2ed0..3bc4f6f33411 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Text, TypeVar, Union +from typing import Any, TypeVar, Union ucd_3_2_0: UCD ucnhash_CAPI: Any @@ -7,36 +7,36 @@ unidata_version: str _T = TypeVar("_T") -def bidirectional(__chr: Text) -> Text: ... -def category(__chr: Text) -> Text: ... -def combining(__chr: Text) -> int: ... -def decimal(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... -def decomposition(__chr: Text) -> Text: ... -def digit(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... -def east_asian_width(__chr: Text) -> Text: ... +def bidirectional(__chr: str) -> str: ... +def category(__chr: str) -> str: ... +def combining(__chr: str) -> int: ... +def decimal(__chr: str, __default: _T = ...) -> Union[int, _T]: ... +def decomposition(__chr: str) -> str: ... +def digit(__chr: str, __default: _T = ...) -> Union[int, _T]: ... +def east_asian_width(__chr: str) -> str: ... if sys.version_info >= (3, 8): def is_normalized(__form: str, __unistr: str) -> bool: ... -def lookup(__name: Union[Text, bytes]) -> Text: ... -def mirrored(__chr: Text) -> int: ... -def name(__chr: Text, __default: _T = ...) -> Union[Text, _T]: ... -def normalize(__form: Text, __unistr: Text) -> Text: ... -def numeric(__chr: Text, __default: _T = ...) -> Union[float, _T]: ... +def lookup(__name: Union[str, bytes]) -> str: ... +def mirrored(__chr: str) -> int: ... +def name(__chr: str, __default: _T = ...) -> Union[str, _T]: ... +def normalize(__form: str, __unistr: str) -> str: ... +def numeric(__chr: str, __default: _T = ...) -> Union[float, _T]: ... class UCD(object): # The methods below are constructed from the same array in C # (unicodedata_functions) and hence identical to the methods above. unidata_version: str - def bidirectional(self, __chr: Text) -> str: ... - def category(self, __chr: Text) -> str: ... - def combining(self, __chr: Text) -> int: ... - def decimal(self, __chr: Text, __default: _T = ...) -> Union[int, _T]: ... - def decomposition(self, __chr: Text) -> str: ... - def digit(self, __chr: Text, __default: _T = ...) -> Union[int, _T]: ... - def east_asian_width(self, __chr: Text) -> str: ... - def lookup(self, __name: Union[Text, bytes]) -> Text: ... - def mirrored(self, __chr: Text) -> int: ... - def name(self, __chr: Text, __default: _T = ...) -> Union[Text, _T]: ... - def normalize(self, __form: Text, __unistr: Text) -> Text: ... - def numeric(self, __chr: Text, __default: _T = ...) -> Union[float, _T]: ... + def bidirectional(self, __chr: str) -> str: ... + def category(self, __chr: str) -> str: ... + def combining(self, __chr: str) -> int: ... + def decimal(self, __chr: str, __default: _T = ...) -> Union[int, _T]: ... + def decomposition(self, __chr: str) -> str: ... + def digit(self, __chr: str, __default: _T = ...) -> Union[int, _T]: ... + def east_asian_width(self, __chr: str) -> str: ... + def lookup(self, __name: Union[str, bytes]) -> str: ... + def mirrored(self, __chr: str) -> int: ... + def name(self, __chr: str, __default: _T = ...) -> Union[str, _T]: ... + def normalize(self, __form: str, __unistr: str) -> str: ... + def numeric(self, __chr: str, __default: _T = ...) -> Union[float, _T]: ... diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index fd767272e66a..40cb7743362a 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -96,7 +96,7 @@ class NonCallableMock(Base, Any): # type: ignore def assert_not_called(self) -> None: ... def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ... - elif sys.version_info >= (3, 5): + else: def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... def assert_not_called(_mock_self) -> None: ... def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... @@ -104,7 +104,7 @@ class NonCallableMock(Base, Any): # type: ignore if sys.version_info >= (3, 8): def assert_called(self) -> None: ... def assert_called_once(self) -> None: ... - elif sys.version_info >= (3, 6): + else: def assert_called(_mock_self) -> None: ... def assert_called_once(_mock_self) -> None: ... def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... @@ -204,112 +204,112 @@ class _patcher: TEST_PREFIX: str dict: Type[_patch_dict] if sys.version_info >= (3, 8): + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. @overload def __call__( # type: ignore self, target: Any, - *, + new: _T, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[Union[MagicMock, AsyncMock]]: ... - # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. - # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], - # but that's impossible with the current type system. + ) -> _patch[_T]: ... @overload - def __call__( + def __call__( # type: ignore self, target: Any, - new: _T, + *, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[_T]: ... + ) -> _patch[Union[MagicMock, AsyncMock]]: ... else: @overload def __call__( # type: ignore self, target: Any, - *, + new: _T, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[MagicMock]: ... + ) -> _patch[_T]: ... @overload - def __call__( + def __call__( # type: ignore self, target: Any, - new: _T, + *, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[_T]: ... + ) -> _patch[MagicMock]: ... if sys.version_info >= (3, 8): @overload def object( # type: ignore self, target: Any, attribute: str, - *, + new: _T, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[Union[MagicMock, AsyncMock]]: ... + ) -> _patch[_T]: ... @overload - def object( + def object( # type: ignore self, target: Any, attribute: str, - new: _T = ..., + *, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[_T]: ... + ) -> _patch[Union[MagicMock, AsyncMock]]: ... else: @overload def object( # type: ignore self, target: Any, attribute: str, - *, + new: _T, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[MagicMock]: ... + ) -> _patch[_T]: ... @overload - def object( + def object( # type: ignore self, target: Any, attribute: str, - new: _T = ..., + *, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any, - ) -> _patch[_T]: ... + ) -> _patch[MagicMock]: ... def multiple( self, target: Any, diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 3f09496a6dcf..60ccdf2dd90c 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -1,6 +1,6 @@ -import os import ssl import sys +from _typeshed import StrOrBytesPath from email.message import Message from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol from http.cookiejar import CookieJar @@ -271,7 +271,7 @@ class HTTPErrorProcessor(BaseHandler): def urlretrieve( url: str, - filename: Optional[Union[str, os.PathLike[Any]]] = ..., + filename: Optional[StrOrBytesPath] = ..., reporthook: Optional[Callable[[int, int, int], None]] = ..., data: Optional[bytes] = ..., ) -> Tuple[str, HTTPMessage]: ... diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index 2bb2c2a1c90e..91ce210ae96d 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,7 +1,7 @@ import sys -from typing import BinaryIO, Optional, Text, Union +from typing import BinaryIO, Optional, Union -_File = Union[Text, BinaryIO] +_File = Union[str, BinaryIO] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 68b235162210..b66b169c5ff7 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Optional, Text, Tuple +from typing import Any, Optional, Tuple # Because UUID has properties called int and bytes we need to rename these temporarily. _Int = int @@ -17,7 +17,7 @@ class UUID: if sys.version_info >= (3, 7): def __init__( self, - hex: Optional[Text] = ..., + hex: Optional[str] = ..., bytes: Optional[_Bytes] = ..., bytes_le: Optional[_Bytes] = ..., fields: Optional[_FieldsType] = ..., @@ -31,7 +31,7 @@ class UUID: else: def __init__( self, - hex: Optional[Text] = ..., + hex: Optional[str] = ..., bytes: Optional[_Bytes] = ..., bytes_le: Optional[_Bytes] = ..., fields: Optional[_FieldsType] = ..., @@ -71,29 +71,11 @@ class UUID: @property def version(self) -> Optional[_Int]: ... def __int__(self) -> _Int: ... - if sys.version_info >= (3,): - def __eq__(self, other: Any) -> bool: ... - def __lt__(self, other: Any) -> bool: ... - def __le__(self, other: Any) -> bool: ... - def __gt__(self, other: Any) -> bool: ... - def __ge__(self, other: Any) -> bool: ... - else: - def get_bytes(self) -> _Bytes: ... - def get_bytes_le(self) -> _Bytes: ... - def get_clock_seq(self) -> _Int: ... - def get_clock_seq_hi_variant(self) -> _Int: ... - def get_clock_seq_low(self) -> _Int: ... - def get_fields(self) -> _FieldsType: ... - def get_hex(self) -> str: ... - def get_node(self) -> _Int: ... - def get_time(self) -> _Int: ... - def get_time_hi_version(self) -> _Int: ... - def get_time_low(self) -> _Int: ... - def get_time_mid(self) -> _Int: ... - def get_urn(self) -> str: ... - def get_variant(self) -> str: ... - def get_version(self) -> Optional[_Int]: ... - def __cmp__(self, other: Any) -> _Int: ... + def __eq__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... def getnode() -> int: ... def uuid1(node: Optional[_Int] = ..., clock_seq: Optional[_Int] = ...) -> UUID: ... diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index d44d17ea9785..fe49ea65655b 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath +from _typeshed import StrOrBytesPath from types import SimpleNamespace from typing import Optional, Sequence @@ -32,11 +32,13 @@ class EnvBuilder: with_pip: bool = ..., prompt: Optional[str] = ..., ) -> None: ... - def create(self, env_dir: AnyPath) -> None: ... - def clear_directory(self, path: AnyPath) -> None: ... # undocumented - def ensure_directories(self, env_dir: AnyPath) -> SimpleNamespace: ... + def create(self, env_dir: StrOrBytesPath) -> None: ... + def clear_directory(self, path: StrOrBytesPath) -> None: ... # undocumented + def ensure_directories(self, env_dir: StrOrBytesPath) -> SimpleNamespace: ... def create_configuration(self, context: SimpleNamespace) -> None: ... - def symlink_or_copy(self, src: AnyPath, dst: AnyPath, relative_symlinks_ok: bool = ...) -> None: ... # undocumented + def symlink_or_copy( + self, src: StrOrBytesPath, dst: StrOrBytesPath, relative_symlinks_ok: bool = ... + ) -> None: ... # undocumented def setup_python(self, context: SimpleNamespace) -> None: ... def _setup_pip(self, context: SimpleNamespace) -> None: ... # undocumented def setup_scripts(self, context: SimpleNamespace) -> None: ... @@ -48,7 +50,7 @@ class EnvBuilder: if sys.version_info >= (3, 9): def create( - env_dir: AnyPath, + env_dir: StrOrBytesPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., @@ -59,7 +61,7 @@ if sys.version_info >= (3, 9): else: def create( - env_dir: AnyPath, + env_dir: StrOrBytesPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 0e64ec574775..f3f606267892 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,4 +1,3 @@ -import sys from types import ModuleType, TracebackType from typing import Any, List, Optional, TextIO, Type, Union, overload from typing_extensions import Literal @@ -31,28 +30,17 @@ class WarningMessage: lineno: int file: Optional[TextIO] line: Optional[str] - if sys.version_info >= (3, 6): - source: Optional[Any] - def __init__( - self, - message: Union[Warning, str], - category: Type[Warning], - filename: str, - lineno: int, - file: Optional[TextIO] = ..., - line: Optional[str] = ..., - source: Optional[Any] = ..., - ) -> None: ... - else: - def __init__( - self, - message: Union[Warning, str], - category: Type[Warning], - filename: str, - lineno: int, - file: Optional[TextIO] = ..., - line: Optional[str] = ..., - ) -> None: ... + source: Optional[Any] + def __init__( + self, + message: Union[Warning, str], + category: Type[Warning], + filename: str, + lineno: int, + file: Optional[TextIO] = ..., + line: Optional[str] = ..., + source: Optional[Any] = ..., + ) -> None: ... class catch_warnings: @overload diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index d415630427da..61f9136ea334 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,29 +1,24 @@ import sys -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Optional, Text, Tuple, Union +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Optional, Union -_File = Union[Text, IO[bytes]] +_File = Union[str, IO[bytes]] class Error(Exception): ... WAVE_FORMAT_PCM: int -if sys.version_info >= (3, 0): - class _wave_params(NamedTuple): - nchannels: int - sampwidth: int - framerate: int - nframes: int - comptype: str - compname: str - -else: - _wave_params = Tuple[int, int, int, int, str, str] +class _wave_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: str + compname: str class Wave_read: def __init__(self, f: _File) -> None: ... - if sys.version_info >= (3, 0): - def __enter__(self) -> Wave_read: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Wave_read: ... + def __exit__(self, *args: Any) -> None: ... def getfp(self) -> Optional[BinaryIO]: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -42,9 +37,8 @@ class Wave_read: class Wave_write: def __init__(self, f: _File) -> None: ... - if sys.version_info >= (3, 0): - def __enter__(self) -> Wave_write: ... - def __exit__(self, *args: Any) -> None: ... + def __enter__(self) -> Wave_write: ... + def __exit__(self, *args: Any) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index b43b634d6216..a4998ddc4219 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,4 +1,3 @@ -import sys import types from _weakrefset import WeakSet as WeakSet from typing import ( @@ -29,9 +28,6 @@ from _weakref import ( ref as ref, ) -if sys.version_info < (3, 0): - from exceptions import ReferenceError as ReferenceError - _S = TypeVar("_S") _T = TypeVar("_T") _KT = TypeVar("_KT") @@ -39,10 +35,9 @@ _VT = TypeVar("_VT") ProxyTypes: Tuple[Type[Any], ...] -if sys.version_info >= (3, 4): - class WeakMethod(ref[types.MethodType]): - def __new__(cls, meth: types.MethodType, callback: Optional[Callable[[types.MethodType], Any]] = ...) -> WeakMethod: ... - def __call__(self) -> Optional[types.MethodType]: ... +class WeakMethod(ref[types.MethodType]): + def __new__(cls, meth: types.MethodType, callback: Optional[Callable[[types.MethodType], Any]] = ...) -> WeakMethod: ... + def __call__(self) -> Optional[types.MethodType]: ... class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload @@ -53,24 +48,14 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... - if sys.version_info < (3, 0): - def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... - if sys.version_info >= (3, 0): - # These are incompatible with Mapping - def keys(self) -> Iterator[_KT]: ... # type: ignore - def values(self) -> Iterator[_VT]: ... # type: ignore - def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore - else: - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore + def values(self) -> Iterator[_VT]: ... # type: ignore + def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... @@ -89,32 +74,20 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... - if sys.version_info < (3, 0): - def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... - if sys.version_info >= (3, 0): - # These are incompatible with Mapping - def keys(self) -> Iterator[_KT]: ... # type: ignore - def values(self) -> Iterator[_VT]: ... # type: ignore - def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore - else: - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore + def values(self) -> Iterator[_VT]: ... # type: ignore + def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore def keyrefs(self) -> List[ref[_KT]]: ... -if sys.version_info >= (3, 4): - class finalize: - def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, _: Any = ...) -> Optional[Any]: ... - def detach(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... - def peek(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... - alive: bool - atexit: bool +class finalize: + def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, _: Any = ...) -> Optional[Any]: ... + def detach(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... + def peek(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... + alive: bool + atexit: bool diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index 322ec2764e39..bb543e2f2273 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -1,41 +1,41 @@ import sys -from typing import Callable, List, Optional, Sequence, Text, Union +from typing import Callable, List, Optional, Sequence, Union class Error(Exception): ... if sys.version_info >= (3, 7): def register( - name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., *, preferred: bool = ... + name: str, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., *, preferred: bool = ... ) -> None: ... else: def register( - name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., update_tryorder: int = ... + name: str, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., update_tryorder: int = ... ) -> None: ... -def get(using: Optional[Text] = ...) -> BaseBrowser: ... -def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... -def open_new(url: Text) -> bool: ... -def open_new_tab(url: Text) -> bool: ... +def get(using: Optional[str] = ...) -> BaseBrowser: ... +def open(url: str, new: int = ..., autoraise: bool = ...) -> bool: ... +def open_new(url: str) -> bool: ... +def open_new_tab(url: str) -> bool: ... class BaseBrowser: args: List[str] name: str basename: str - def __init__(self, name: Text = ...) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... - def open_new(self, url: Text) -> bool: ... - def open_new_tab(self, url: Text) -> bool: ... + def __init__(self, name: str = ...) -> None: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + def open_new(self, url: str) -> bool: ... + def open_new_tab(self, url: str) -> bool: ... class GenericBrowser(BaseBrowser): args: List[str] name: str basename: str - def __init__(self, name: Union[Text, Sequence[Text]]) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def __init__(self, name: Union[str, Sequence[str]]) -> None: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class BackgroundBrowser(GenericBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class UnixBrowser(BaseBrowser): raise_opts: Optional[List[str]] @@ -45,7 +45,7 @@ class UnixBrowser(BaseBrowser): remote_action: str remote_action_newwin: str remote_action_newtab: str - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class Mozilla(UnixBrowser): remote_args: List[str] @@ -84,20 +84,20 @@ class Elinks(UnixBrowser): redirect_stdout: bool class Konqueror(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class Grail(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... if sys.platform == "win32": class WindowsDefault(BaseBrowser): - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... if sys.platform == "darwin": class MacOSX(BaseBrowser): name: str - def __init__(self, name: Text) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def __init__(self, name: str) -> None: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class MacOSXOSAScript(BaseBrowser): - def __init__(self, name: Text) -> None: ... - def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def __init__(self, name: str) -> None: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi index ff764e434169..ba85292b8a5e 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,7 +1,6 @@ -import sys from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, Dict, List, MutableMapping, Optional, Text, Tuple, Type +from typing import IO, Callable, Dict, List, MutableMapping, Optional, Tuple, Type from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment @@ -10,9 +9,7 @@ from .util import FileWrapper _exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] def format_date_time(timestamp: Optional[float]) -> str: ... # undocumented - -if sys.version_info >= (3, 2): - def read_environ() -> Dict[str, str]: ... +def read_environ() -> Dict[str, str]: ... class BaseHandler: wsgi_version: Tuple[int, int] # undocumented @@ -31,7 +28,7 @@ class BaseHandler: traceback_limit: Optional[int] error_status: str - error_headers: List[Tuple[Text, Text]] + error_headers: List[Tuple[str, str]] error_body: bytes def run(self, application: WSGIApplication) -> None: ... def setup_environ(self) -> None: ... @@ -40,7 +37,7 @@ class BaseHandler: def set_content_length(self) -> None: ... def cleanup_headers(self) -> None: ... def start_response( - self, status: Text, headers: List[Tuple[Text, Text]], exc_info: Optional[_exc_info] = ... + self, status: str, headers: List[Tuple[str, str]], exc_info: Optional[_exc_info] = ... ) -> Callable[[bytes], None]: ... def send_preamble(self) -> None: ... def write(self, data: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi index c3e943200e40..71b1ea8f9c38 100644 --- a/mypy/typeshed/stdlib/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/headers.pyi @@ -1,4 +1,3 @@ -import sys from typing import List, Optional, Pattern, Tuple, overload _HeaderList = List[Tuple[str, str]] @@ -6,16 +5,11 @@ _HeaderList = List[Tuple[str, str]] tspecials: Pattern[str] # undocumented class Headers: - if sys.version_info < (3, 5): - def __init__(self, headers: _HeaderList) -> None: ... - else: - def __init__(self, headers: Optional[_HeaderList] = ...) -> None: ... + def __init__(self, headers: Optional[_HeaderList] = ...) -> None: ... def __len__(self) -> int: ... def __setitem__(self, name: str, val: str) -> None: ... def __delitem__(self, name: str) -> None: ... def __getitem__(self, name: str) -> Optional[str]: ... - if sys.version_info < (3,): - def has_key(self, name: str) -> bool: ... def __contains__(self, name: str) -> bool: ... def get_all(self, name: str) -> List[str]: ... @overload @@ -25,7 +19,6 @@ class Headers: def keys(self) -> List[str]: ... def values(self) -> List[str]: ... def items(self) -> _HeaderList: ... - if sys.version_info >= (3,): - def __bytes__(self) -> bytes: ... + def __bytes__(self) -> bytes: ... def setdefault(self, name: str, value: str) -> str: ... def add_header(self, _name: str, _value: Optional[str], **_params: Optional[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 4e0abd7e8e9d..14a20bab5709 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -1,14 +1,9 @@ -import sys +from http.server import BaseHTTPRequestHandler, HTTPServer from typing import List, Optional, Type, TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment -if sys.version_info >= (3, 0): - from http.server import BaseHTTPRequestHandler, HTTPServer -else: - from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer - server_version: str # undocumented sys_version: str # undocumented software_version: str # undocumented diff --git a/mypy/typeshed/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi index 1c66bc1fabdf..3498f6bcea1f 100644 --- a/mypy/typeshed/stdlib/wsgiref/util.pyi +++ b/mypy/typeshed/stdlib/wsgiref/util.pyi @@ -1,4 +1,3 @@ -import sys from typing import IO, Any, Callable, Optional from .types import WSGIEnvironment @@ -10,10 +9,7 @@ class FileWrapper: def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... def __getitem__(self, key: Any) -> bytes: ... def __iter__(self) -> FileWrapper: ... - if sys.version_info >= (3, 0): - def __next__(self) -> bytes: ... - else: - def next(self) -> bytes: ... + def __next__(self) -> bytes: ... def guess_scheme(environ: WSGIEnvironment) -> str: ... def application_uri(environ: WSGIEnvironment) -> str: ... diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index bc9f0b8c680f..309ca74c9150 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication from typing import Any, Callable, Iterable, Iterator, NoReturn, Optional @@ -9,12 +8,8 @@ def validator(application: WSGIApplication) -> WSGIApplication: ... class InputWrapper: input: InputStream def __init__(self, wsgi_input: InputStream) -> None: ... - if sys.version_info >= (3, 0): - def read(self, size: int) -> bytes: ... - def readline(self, size: int = ...) -> bytes: ... - else: - def read(self, size: int = ...) -> bytes: ... - def readline(self) -> bytes: ... + def read(self, size: int) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... def readlines(self, hint: int = ...) -> bytes: ... def __iter__(self) -> Iterable[bytes]: ... def close(self) -> NoReturn: ... @@ -44,9 +39,6 @@ class IteratorWrapper: check_start_response: Optional[bool] def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: Optional[bool]) -> None: ... def __iter__(self) -> IteratorWrapper: ... - if sys.version_info >= (3, 0): - def __next__(self) -> bytes: ... - else: - def next(self) -> bytes: ... + def __next__(self) -> bytes: ... def close(self) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 67e9b1189528..90396299effc 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,13 +1,13 @@ import sys import xml.dom -from typing import IO, Any, Optional, Text as _Text, TypeVar, Union +from typing import IO, Any, Optional, TypeVar, Union from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader _T = TypeVar("_T") def parse(file: Union[str, IO[Any]], parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... -def parseString(string: Union[bytes, _Text], parser: Optional[XMLReader] = ...): ... +def parseString(string: Union[str, bytes], parser: Optional[XMLReader] = ...): ... def getDOMImplementation(features=...): ... class Node(xml.dom.Node): diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index ca4e3832f37e..8251071e833a 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import AnyPath, FileDescriptor, SupportsWrite +from _typeshed import FileDescriptor, StrOrBytesPath, SupportsWrite from typing import ( IO, Any, @@ -14,7 +14,6 @@ from typing import ( MutableSequence, Optional, Sequence, - Text, Tuple, TypeVar, Union, @@ -22,6 +21,9 @@ from typing import ( ) from typing_extensions import Literal +_T = TypeVar("_T") +_File = Union[StrOrBytesPath, FileDescriptor, IO[Any]] + VERSION: str class ParseError(SyntaxError): @@ -30,41 +32,13 @@ class ParseError(SyntaxError): def iselement(element: object) -> bool: ... -_T = TypeVar("_T") - -# Type for parser inputs. Parser will accept any unicode/str/bytes and coerce, -# and this is true in py2 and py3 (even fromstringlist() in python3 can be -# called with a heterogeneous list) -_parser_input_type = Union[bytes, Text] - -# Type for individual tag/attr/ns/text values in args to most functions. -# In py2, the library accepts str or unicode everywhere and coerces -# aggressively. -# In py3, bytes is not coerced to str and so use of bytes is probably an error, -# so we exclude it. (why? the parser never produces bytes when it parses XML, -# so e.g., element.get(b'name') will always return None for parsed XML, even if -# there is a 'name' attribute.) -_str_argument_type = Union[str, Text] - -# Type for return values from individual tag/attr/text values -if sys.version_info >= (3,): - # note: in python3, everything comes out as str, yay: - _str_result_type = str -else: - # in python2, if the tag/attribute/text wasn't decode-able as ascii, it - # comes out as a unicode string; otherwise it comes out as str. (see - # _fixtext function in the source). Client code knows best: - _str_result_type = Any - -_file_or_filename = Union[AnyPath, FileDescriptor, IO[Any]] - if sys.version_info >= (3, 8): @overload def canonicalize( - xml_data: Optional[_parser_input_type] = ..., + xml_data: Optional[Union[str, bytes]] = ..., *, out: None = ..., - from_file: Optional[_file_or_filename] = ..., + from_file: Optional[_File] = ..., with_comments: bool = ..., strip_text: bool = ..., rewrite_prefixes: bool = ..., @@ -75,10 +49,10 @@ if sys.version_info >= (3, 8): ) -> str: ... @overload def canonicalize( - xml_data: Optional[_parser_input_type] = ..., + xml_data: Optional[Union[str, bytes]] = ..., *, out: SupportsWrite[str], - from_file: Optional[_file_or_filename] = ..., + from_file: Optional[_File] = ..., with_comments: bool = ..., strip_text: bool = ..., rewrite_prefixes: bool = ..., @@ -89,54 +63,33 @@ if sys.version_info >= (3, 8): ) -> None: ... class Element(MutableSequence[Element]): - tag: _str_result_type - attrib: Dict[_str_result_type, _str_result_type] - text: Optional[_str_result_type] - tail: Optional[_str_result_type] - def __init__( - self, - tag: Union[_str_argument_type, Callable[..., Element]], - attrib: Dict[_str_argument_type, _str_argument_type] = ..., - **extra: _str_argument_type, - ) -> None: ... + tag: str + attrib: Dict[str, str] + text: Optional[str] + tail: Optional[str] + def __init__(self, tag: Union[str, Callable[..., Element]], attrib: Dict[str, str] = ..., **extra: str) -> None: ... def append(self, __subelement: Element) -> None: ... def clear(self) -> None: ... def extend(self, __elements: Iterable[Element]) -> None: ... - def find( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Optional[Element]: ... - def findall( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> List[Element]: ... + def find(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Optional[Element]: ... + def findall(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... @overload - def findtext( - self, - path: _str_argument_type, - default: None = ..., - namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ..., - ) -> Optional[_str_result_type]: ... + def findtext(self, path: str, default: None = ..., namespaces: Optional[Dict[str, str]] = ...) -> Optional[str]: ... @overload - def findtext( - self, path: _str_argument_type, default: _T, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Union[_T, _str_result_type]: ... + def findtext(self, path: str, default: _T, namespaces: Optional[Dict[str, str]] = ...) -> Union[_T, str]: ... @overload - def get(self, key: _str_argument_type, default: None = ...) -> Optional[_str_result_type]: ... + def get(self, key: str, default: None = ...) -> Optional[str]: ... @overload - def get(self, key: _str_argument_type, default: _T) -> Union[_str_result_type, _T]: ... - if sys.version_info >= (3, 2): - def insert(self, __index: int, __subelement: Element) -> None: ... - else: - def insert(self, __index: int, __element: Element) -> None: ... - def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... - def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... - def iterfind( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Generator[Element, None, None]: ... - def itertext(self) -> Generator[_str_result_type, None, None]: ... - def keys(self) -> KeysView[_str_result_type]: ... - def makeelement(self, __tag: _str_argument_type, __attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... + def get(self, key: str, default: _T) -> Union[str, _T]: ... + def insert(self, __index: int, __subelement: Element) -> None: ... + def items(self) -> ItemsView[str, str]: ... + def iter(self, tag: Optional[str] = ...) -> Generator[Element, None, None]: ... + def iterfind(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[Element, None, None]: ... + def itertext(self) -> Generator[str, None, None]: ... + def keys(self) -> KeysView[str]: ... + def makeelement(self, __tag: str, __attrib: Dict[str, str]) -> Element: ... def remove(self, __subelement: Element) -> None: ... - def set(self, __key: _str_argument_type, __value: _str_argument_type) -> None: ... + def set(self, __key: str, __value: str) -> None: ... def __delitem__(self, i: Union[int, slice]) -> None: ... @overload def __getitem__(self, i: int) -> Element: ... @@ -149,73 +102,45 @@ class Element(MutableSequence[Element]): def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... if sys.version_info < (3, 9): def getchildren(self) -> List[Element]: ... - def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + def getiterator(self, tag: Optional[str] = ...) -> List[Element]: ... -def SubElement( - parent: Element, - tag: _str_argument_type, - attrib: Dict[_str_argument_type, _str_argument_type] = ..., - **extra: _str_argument_type, -) -> Element: ... -def Comment(text: Optional[_str_argument_type] = ...) -> Element: ... -def ProcessingInstruction(target: _str_argument_type, text: Optional[_str_argument_type] = ...) -> Element: ... +def SubElement(parent: Element, tag: str, attrib: Dict[str, str] = ..., **extra: str) -> Element: ... +def Comment(text: Optional[str] = ...) -> Element: ... +def ProcessingInstruction(target: str, text: Optional[str] = ...) -> Element: ... PI: Callable[..., Element] class QName: text: str - def __init__(self, text_or_uri: _str_argument_type, tag: Optional[_str_argument_type] = ...) -> None: ... + def __init__(self, text_or_uri: str, tag: Optional[str] = ...) -> None: ... class ElementTree: - def __init__(self, element: Optional[Element] = ..., file: Optional[_file_or_filename] = ...) -> None: ... + def __init__(self, element: Optional[Element] = ..., file: Optional[_File] = ...) -> None: ... def getroot(self) -> Element: ... - def parse(self, source: _file_or_filename, parser: Optional[XMLParser] = ...) -> Element: ... - def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... + def parse(self, source: _File, parser: Optional[XMLParser] = ...) -> Element: ... + def iter(self, tag: Optional[str] = ...) -> Generator[Element, None, None]: ... if sys.version_info < (3, 9): - def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... - def find( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Optional[Element]: ... + def getiterator(self, tag: Optional[str] = ...) -> List[Element]: ... + def find(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Optional[Element]: ... @overload - def findtext( - self, - path: _str_argument_type, - default: None = ..., - namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ..., - ) -> Optional[_str_result_type]: ... + def findtext(self, path: str, default: None = ..., namespaces: Optional[Dict[str, str]] = ...) -> Optional[str]: ... @overload - def findtext( - self, path: _str_argument_type, default: _T, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Union[_T, _str_result_type]: ... - def findall( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> List[Element]: ... - def iterfind( - self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> Generator[Element, None, None]: ... - if sys.version_info >= (3, 4): - def write( - self, - file_or_filename: _file_or_filename, - encoding: Optional[str] = ..., - xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., - method: Optional[str] = ..., - *, - short_empty_elements: bool = ..., - ) -> None: ... - else: - def write( - self, - file_or_filename: _file_or_filename, - encoding: Optional[str] = ..., - xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., - method: Optional[str] = ..., - ) -> None: ... - def write_c14n(self, file: _file_or_filename) -> None: ... + def findtext(self, path: str, default: _T, namespaces: Optional[Dict[str, str]] = ...) -> Union[_T, str]: ... + def findall(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... + def iterfind(self, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[Element, None, None]: ... + def write( + self, + file_or_filename: _File, + encoding: Optional[str] = ..., + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[str] = ..., + method: Optional[str] = ..., + *, + short_empty_elements: bool = ..., + ) -> None: ... + def write_c14n(self, file: _File) -> None: ... -def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... +def register_namespace(prefix: str, uri: str) -> None: ... if sys.version_info >= (3, 8): @overload @@ -225,7 +150,7 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> bytes: ... @overload @@ -235,7 +160,7 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> str: ... @overload @@ -245,7 +170,7 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> Any: ... @overload @@ -255,7 +180,7 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> List[bytes]: ... @overload @@ -265,7 +190,7 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> List[str]: ... @overload @@ -275,11 +200,11 @@ if sys.version_info >= (3, 8): method: Optional[str] = ..., *, xml_declaration: Optional[bool] = ..., - default_namespace: Optional[_str_argument_type] = ..., + default_namespace: Optional[str] = ..., short_empty_elements: bool = ..., ) -> List[Any]: ... -elif sys.version_info >= (3,): +else: @overload def tostring( element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ... @@ -303,34 +228,29 @@ elif sys.version_info >= (3,): element: Element, encoding: str, method: Optional[str] = ..., *, short_empty_elements: bool = ... ) -> List[Any]: ... -else: - def tostring(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> bytes: ... - def tostringlist(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> List[bytes]: ... - def dump(elem: Element) -> None: ... if sys.version_info >= (3, 9): def indent(tree: Union[Element, ElementTree], space: str = ..., level: int = ...) -> None: ... -def parse(source: _file_or_filename, parser: Optional[XMLParser] = ...) -> ElementTree: ... +def parse(source: _File, parser: Optional[XMLParser] = ...) -> ElementTree: ... def iterparse( - source: _file_or_filename, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ... + source: _File, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ... ) -> Iterator[Tuple[str, Any]]: ... -if sys.version_info >= (3, 4): - class XMLPullParser: - def __init__(self, events: Optional[Sequence[str]] = ..., *, _parser: Optional[XMLParser] = ...) -> None: ... - def feed(self, data: bytes) -> None: ... - def close(self) -> None: ... - def read_events(self) -> Iterator[Tuple[str, Element]]: ... +class XMLPullParser: + def __init__(self, events: Optional[Sequence[str]] = ..., *, _parser: Optional[XMLParser] = ...) -> None: ... + def feed(self, data: bytes) -> None: ... + def close(self) -> None: ... + def read_events(self) -> Iterator[Tuple[str, Element]]: ... -def XML(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Element: ... -def XMLID(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... +def XML(text: Union[str, bytes], parser: Optional[XMLParser] = ...) -> Element: ... +def XMLID(text: Union[str, bytes], parser: Optional[XMLParser] = ...) -> Tuple[Element, Dict[str, Element]]: ... # This is aliased to XML in the source. fromstring = XML -def fromstringlist(sequence: Sequence[_parser_input_type], parser: Optional[XMLParser] = ...) -> Element: ... +def fromstringlist(sequence: Sequence[Union[str, bytes]], parser: Optional[XMLParser] = ...) -> Element: ... # This type is both not precise enough and too precise. The TreeBuilder # requires the elementfactory to accept tag and attrs in its args and produce @@ -346,9 +266,9 @@ _ElementFactory = Callable[[Any, Dict[Any, Any]], Element] class TreeBuilder: def __init__(self, element_factory: Optional[_ElementFactory] = ...) -> None: ... def close(self) -> Element: ... - def data(self, __data: _parser_input_type) -> None: ... - def start(self, __tag: _parser_input_type, __attrs: Dict[_parser_input_type, _parser_input_type]) -> Element: ... - def end(self, __tag: _parser_input_type) -> Element: ... + def data(self, __data: Union[str, bytes]) -> None: ... + def start(self, __tag: Union[str, bytes], __attrs: Dict[Union[str, bytes], Union[str, bytes]]) -> Element: ... + def end(self, __tag: Union[str, bytes]) -> Element: ... if sys.version_info >= (3, 8): class C14NWriterTarget: @@ -377,4 +297,4 @@ class XMLParser: def __init__(self, html: int = ..., target: Any = ..., encoding: Optional[str] = ...) -> None: ... def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... def close(self) -> Any: ... - def feed(self, __data: _parser_input_type) -> None: ... + def feed(self, __data: Union[str, bytes]) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index a95fde106535..854a552d3e53 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,5 +1,5 @@ import sys -from typing import IO, Any, Iterable, List, NoReturn, Optional, Text, Union +from typing import IO, Any, Iterable, List, NoReturn, Optional, Union from xml.sax.handler import ContentHandler, ErrorHandler from xml.sax.xmlreader import Locator, XMLReader @@ -29,5 +29,5 @@ else: def make_parser(parser_list: List[str] = ...) -> XMLReader: ... def parse(source: Union[str, IO[str], IO[bytes]], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... -def parseString(string: Union[bytes, Text], handler: ContentHandler, errorHandler: Optional[ErrorHandler] = ...) -> None: ... +def parseString(string: Union[bytes, str], handler: ContentHandler, errorHandler: Optional[ErrorHandler] = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/xml/sax/saxutils.pyi b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi index 8ae2b80d2a26..066097fb5a53 100644 --- a/mypy/typeshed/stdlib/xml/sax/saxutils.pyi +++ b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi @@ -1,28 +1,20 @@ -import sys from _typeshed import SupportsWrite from codecs import StreamReaderWriter, StreamWriter from io import RawIOBase, TextIOBase -from typing import Mapping, Optional, Text, Union +from typing import Mapping, Optional, Union from xml.sax import handler, xmlreader -def escape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... -def unescape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... -def quoteattr(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... +def escape(data: str, entities: Mapping[str, str] = ...) -> str: ... +def unescape(data: str, entities: Mapping[str, str] = ...) -> str: ... +def quoteattr(data: str, entities: Mapping[str, str] = ...) -> str: ... class XMLGenerator(handler.ContentHandler): - if sys.version_info >= (3, 0): - def __init__( - self, - out: Optional[Union[TextIOBase, RawIOBase, StreamWriter, StreamReaderWriter, SupportsWrite[str]]] = ..., - encoding: str = ..., - short_empty_elements: bool = ..., - ) -> None: ... - else: - def __init__( - self, - out: Optional[Union[TextIOBase, RawIOBase, StreamWriter, StreamReaderWriter, SupportsWrite[str]]] = ..., - encoding: Text = ..., - ) -> None: ... + def __init__( + self, + out: Optional[Union[TextIOBase, RawIOBase, StreamWriter, StreamReaderWriter, SupportsWrite[str]]] = ..., + encoding: str = ..., + short_empty_elements: bool = ..., + ) -> None: ... def startDocument(self): ... def endDocument(self): ... def startPrefixMapping(self, prefix, uri): ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index 91727aa540fb..b43ff218c062 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -2,44 +2,32 @@ import io import sys from _typeshed import StrPath from types import TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Iterable, - Iterator, - List, - Optional, - Pattern, - Protocol, - Sequence, - Text, - Tuple, - Type, - Union, -) - -_SZI = Union[Text, ZipInfo] -_DT = Tuple[int, int, int, int, int, int] - -if sys.version_info >= (3,): - class BadZipFile(Exception): ... - BadZipfile = BadZipFile -else: - class BadZipfile(Exception): ... +from typing import IO, Callable, Dict, Iterable, Iterator, List, Optional, Protocol, Sequence, Tuple, Type, Union, overload +from typing_extensions import Literal +_DateTuple = Tuple[int, int, int, int, int, int] + +class BadZipFile(Exception): ... + +BadZipfile = BadZipFile error = BadZipfile class LargeZipFile(Exception): ... +class _ZipStream(Protocol): + def read(self, __n: int) -> bytes: ... + # The following methods are optional: + # def seekable(self) -> bool: ... + # def tell(self) -> int: ... + # def seek(self, __n: int) -> object: ... + +class _ClosableZipStream(_ZipStream, Protocol): + def close(self) -> object: ... + class ZipExtFile(io.BufferedIOBase): MAX_N: int = ... MIN_READ_SIZE: int = ... - if sys.version_info < (3, 6): - PATTERN: Pattern[str] = ... - if sys.version_info >= (3, 7): MAX_SEEK_READ: int = ... @@ -47,17 +35,57 @@ class ZipExtFile(io.BufferedIOBase): mode: str name: str if sys.version_info >= (3, 7): + @overload def __init__( - self, fileobj: IO[bytes], mode: str, zipinfo: ZipInfo, pwd: Optional[bytes] = ..., close_fileobj: bool = ... + self, fileobj: _ClosableZipStream, mode: str, zipinfo: ZipInfo, pwd: Optional[bytes], close_fileobj: Literal[True] + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ClosableZipStream, + mode: str, + zipinfo: ZipInfo, + pwd: Optional[bytes] = ..., + *, + close_fileobj: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ZipStream, + mode: str, + zipinfo: ZipInfo, + pwd: Optional[bytes] = ..., + close_fileobj: Literal[False] = ..., ) -> None: ... else: + @overload + def __init__( + self, + fileobj: _ClosableZipStream, + mode: str, + zipinfo: ZipInfo, + decrypter: Optional[Callable[[Sequence[int]], bytes]], + close_fileobj: Literal[True], + ) -> None: ... + @overload def __init__( self, - fileobj: IO[bytes], + fileobj: _ClosableZipStream, mode: str, zipinfo: ZipInfo, decrypter: Optional[Callable[[Sequence[int]], bytes]] = ..., - close_fileobj: bool = ..., + *, + close_fileobj: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ZipStream, + mode: str, + zipinfo: ZipInfo, + decrypter: Optional[Callable[[Sequence[int]], bytes]] = ..., + close_fileobj: Literal[False] = ..., ) -> None: ... def read(self, n: Optional[int] = ...) -> bytes: ... def readline(self, limit: int = ...) -> bytes: ... # type: ignore @@ -66,15 +94,15 @@ class ZipExtFile(io.BufferedIOBase): def read1(self, n: Optional[int]) -> bytes: ... # type: ignore class _Writer(Protocol): - def write(self, __s: str) -> Any: ... + def write(self, __s: str) -> object: ... class ZipFile: - filename: Optional[Text] + filename: Optional[str] debug: int comment: bytes filelist: List[ZipInfo] fp: Optional[IO[bytes]] - NameToInfo: Dict[Text, ZipInfo] + NameToInfo: Dict[str, ZipInfo] start_dir: int # undocumented if sys.version_info >= (3, 8): def __init__( @@ -98,27 +126,26 @@ class ZipFile: ) -> None: ... else: def __init__( - self, file: Union[StrPath, IO[bytes]], mode: Text = ..., compression: int = ..., allowZip64: bool = ... + self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ... ) -> None: ... def __enter__(self) -> ZipFile: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... def close(self) -> None: ... - def getinfo(self, name: Text) -> ZipInfo: ... + def getinfo(self, name: str) -> ZipInfo: ... def infolist(self) -> List[ZipInfo]: ... - def namelist(self) -> List[Text]: ... - def open(self, name: _SZI, mode: Text = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... - def extract(self, member: _SZI, path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... + def namelist(self) -> List[str]: ... + def open( + self, name: Union[str, ZipInfo], mode: str = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ... + ) -> IO[bytes]: ... + def extract(self, member: Union[str, ZipInfo], path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... def extractall( - self, path: Optional[StrPath] = ..., members: Optional[Iterable[Text]] = ..., pwd: Optional[bytes] = ... + self, path: Optional[StrPath] = ..., members: Optional[Iterable[str]] = ..., pwd: Optional[bytes] = ... ) -> None: ... - if sys.version_info >= (3,): - def printdir(self, file: Optional[_Writer] = ...) -> None: ... - else: - def printdir(self) -> None: ... + def printdir(self, file: Optional[_Writer] = ...) -> None: ... def setpassword(self, pwd: bytes) -> None: ... - def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... + def read(self, name: Union[str, ZipInfo], pwd: Optional[bytes] = ...) -> bytes: ... def testzip(self) -> Optional[str]: ... if sys.version_info >= (3, 7): def write( @@ -133,33 +160,25 @@ class ZipFile: if sys.version_info >= (3, 7): def writestr( self, - zinfo_or_arcname: _SZI, + zinfo_or_arcname: Union[str, ZipInfo], data: Union[bytes, str], compress_type: Optional[int] = ..., compresslevel: Optional[int] = ..., ) -> None: ... - elif sys.version_info >= (3,): - def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ...) -> None: ... else: - def writestr(self, zinfo_or_arcname: _SZI, bytes: bytes, compress_type: Optional[int] = ...) -> None: ... + def writestr( + self, zinfo_or_arcname: Union[str, ZipInfo], data: Union[bytes, str], compress_type: Optional[int] = ... + ) -> None: ... class PyZipFile(ZipFile): - if sys.version_info >= (3,): - def __init__( - self, - file: Union[str, IO[bytes]], - mode: str = ..., - compression: int = ..., - allowZip64: bool = ..., - optimize: int = ..., - ) -> None: ... - def writepy(self, pathname: str, basename: str = ..., filterfunc: Optional[Callable[[str], bool]] = ...) -> None: ... - else: - def writepy(self, pathname: Text, basename: Text = ...) -> None: ... + def __init__( + self, file: Union[str, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., optimize: int = ... + ) -> None: ... + def writepy(self, pathname: str, basename: str = ..., filterfunc: Optional[Callable[[str], bool]] = ...) -> None: ... class ZipInfo: - filename: Text - date_time: _DT + filename: str + date_time: _DateTuple compress_type: int comment: bytes extra: bytes @@ -175,15 +194,14 @@ class ZipInfo: CRC: int compress_size: int file_size: int - def __init__(self, filename: Optional[Text] = ..., date_time: Optional[_DT] = ...) -> None: ... + def __init__(self, filename: Optional[str] = ..., date_time: Optional[_DateTuple] = ...) -> None: ... if sys.version_info >= (3, 8): @classmethod def from_file(cls, filename: StrPath, arcname: Optional[StrPath] = ..., *, strict_timestamps: bool = ...) -> ZipInfo: ... - elif sys.version_info >= (3, 6): + else: @classmethod def from_file(cls, filename: StrPath, arcname: Optional[StrPath] = ...) -> ZipInfo: ... - if sys.version_info >= (3, 6): - def is_dir(self) -> bool: ... + def is_dir(self) -> bool: ... def FileHeader(self, zip64: Optional[bool] = ...) -> bytes: ... class _PathOpenProtocol(Protocol): @@ -224,6 +242,5 @@ ZIP_DEFLATED: int ZIP64_LIMIT: int ZIP_FILECOUNT_LIMIT: int ZIP_MAX_COMMENT: int -if sys.version_info >= (3, 3): - ZIP_BZIP2: int - ZIP_LZMA: int +ZIP_BZIP2: int +ZIP_LZMA: int diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index 0d1a330942d4..d36653196ee3 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -11,14 +11,10 @@ class ZipImportError(ImportError): ... class zipimporter(object): archive: str prefix: str - if sys.version_info >= (3, 6): - def __init__(self, path: Union[str, bytes, os.PathLike[Any]]) -> None: ... - else: - def __init__(self, path: Union[str, bytes]) -> None: ... - if sys.version_info >= (3,): - def find_loader( - self, fullname: str, path: Optional[str] = ... - ) -> Tuple[Optional[zipimporter], List[str]]: ... # undocumented + def __init__(self, path: Union[str, bytes, os.PathLike[Any]]) -> None: ... + def find_loader( + self, fullname: str, path: Optional[str] = ... + ) -> Tuple[Optional[zipimporter], List[str]]: ... # undocumented def find_module(self, fullname: str, path: Optional[str] = ...) -> Optional[zipimporter]: ... def get_code(self, fullname: str) -> CodeType: ... def get_data(self, pathname: str) -> str: ... diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index 81a9f87ce42e..c0443c5d8c60 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,4 +1,3 @@ -import sys from array import array from typing import Any, Optional, Union @@ -18,9 +17,8 @@ Z_HUFFMAN_ONLY: int Z_NO_FLUSH: int Z_RLE: int Z_SYNC_FLUSH: int -if sys.version_info >= (3,): - DEF_BUF_SIZE: int - ZLIB_RUNTIME_VERSION: str +DEF_BUF_SIZE: int +ZLIB_RUNTIME_VERSION: str class error(Exception): ... @@ -32,35 +30,16 @@ class _Compress: class _Decompress: unused_data: bytes unconsumed_tail: bytes - if sys.version_info >= (3,): - eof: bool + eof: bool def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... def flush(self, length: int = ...) -> bytes: ... def copy(self) -> _Decompress: ... def adler32(__data: bytes, __value: int = ...) -> int: ... def compress(__data: bytes, level: int = ...) -> bytes: ... - -if sys.version_info >= (3,): - def compressobj( - level: int = ..., - method: int = ..., - wbits: int = ..., - memLevel: int = ..., - strategy: int = ..., - zdict: Optional[bytes] = ..., - ) -> _Compress: ... - -else: - def compressobj( - level: int = ..., method: int = ..., wbits: int = ..., memlevel: int = ..., strategy: int = ... - ) -> _Compress: ... - +def compressobj( + level: int = ..., method: int = ..., wbits: int = ..., memLevel: int = ..., strategy: int = ..., zdict: Optional[bytes] = ... +) -> _Compress: ... def crc32(__data: Union[array[Any], bytes], __value: int = ...) -> int: ... def decompress(__data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ... - -if sys.version_info >= (3,): - def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ... - -else: - def decompressobj(wbits: int = ...) -> _Decompress: ... +def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 46cd6b871555..35bd142b8017 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,7 +1,7 @@ -import os import typing +from _typeshed import StrPath from datetime import tzinfo -from typing import Any, AnyStr, Iterable, Optional, Protocol, Sequence, Set, Type, Union +from typing import Any, Iterable, Optional, Protocol, Sequence, Set, Type _T = typing.TypeVar("_T", bound="ZoneInfo") @@ -23,7 +23,7 @@ class ZoneInfo(tzinfo): # Note: Both here and in clear_cache, the types allow the use of `str` where # a sequence of strings is required. This should be remedied if a solution # to this typing bug is found: https://github.com/python/typing/issues/256 -def reset_tzpath(to: Optional[Sequence[Union[os.PathLike[AnyStr], str]]] = ...) -> None: ... +def reset_tzpath(to: Optional[Sequence[StrPath]] = ...) -> None: ... def available_timezones() -> Set[str]: ... TZPATH: Sequence[str] diff --git a/mypy_self_check.ini b/mypy_self_check.ini index 452fd209bdf0..0139deff863b 100644 --- a/mypy_self_check.ini +++ b/mypy_self_check.ini @@ -19,4 +19,4 @@ pretty = True always_false = MYPYC plugins = misc/proper_plugin.py python_version = 3.6 -exclude = /mypy/typeshed/ +exclude = mypy/typeshed/ diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index 49f308af3610..5f6ee5bbf36e 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -797,7 +797,7 @@ t + 1 _program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" _program.py:3: note: Possible overload variants: _program.py:3: note: def __add__(self, Tuple[str, ...]) -> Tuple[str, ...] -_program.py:3: note: def __add__(self, Tuple[Any, ...]) -> Tuple[Any, ...] +_program.py:3: note: def [_T] __add__(self, Tuple[_T, ...]) -> Tuple[Union[str, _T], ...] [case testMultiplyTupleByIntegerReverse] n = 4 @@ -807,7 +807,7 @@ t + 1 _program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" _program.py:3: note: Possible overload variants: _program.py:3: note: def __add__(self, Tuple[str, ...]) -> Tuple[str, ...] -_program.py:3: note: def __add__(self, Tuple[Any, ...]) -> Tuple[Any, ...] +_program.py:3: note: def [_T] __add__(self, Tuple[_T, ...]) -> Tuple[Union[str, _T], ...] [case testDictWithKeywordArgs] from typing import Dict, Any, List