From 3f7f284b306201759370cfdfa18c79a9f3d63158 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 25 Jun 2020 14:40:13 +0100 Subject: [PATCH 01/50] Add stdlib stubs in new structure --- mypy/stdlib/VERSIONS | 251 +++ mypy/stdlib/__future__.pyi | 25 + mypy/stdlib/_ast.pyi | 418 ++++ mypy/stdlib/_bisect.pyi | 9 + mypy/stdlib/_bootlocale.pyi | 2 + mypy/stdlib/_codecs.pyi | 77 + mypy/stdlib/_compat_pickle.pyi | 14 + mypy/stdlib/_compression.pyi | 16 + mypy/stdlib/_csv.pyi | 52 + mypy/stdlib/_curses.pyi | 461 +++++ mypy/stdlib/_decimal.pyi | 2 + mypy/stdlib/_dummy_thread.pyi | 21 + mypy/stdlib/_dummy_threading.pyi | 190 ++ mypy/stdlib/_heapq.pyi | 15 + mypy/stdlib/_imp.pyi | 20 + mypy/stdlib/_importlib_modulespec.pyi | 44 + mypy/stdlib/_json.pyi | 31 + mypy/stdlib/_markupbase.pyi | 9 + mypy/stdlib/_msi.pyi | 62 + mypy/stdlib/_operator.pyi | 63 + mypy/stdlib/_osx_support.pyi | 33 + mypy/stdlib/_posixsubprocess.pyi | 14 + mypy/stdlib/_py_abc.pyi | 11 + mypy/stdlib/_pydecimal.pyi | 4 + mypy/stdlib/_random.pyi | 17 + mypy/stdlib/_sitebuiltins.pyi | 18 + mypy/stdlib/_stat.pyi | 69 + mypy/stdlib/_thread.pyi | 44 + mypy/stdlib/_threading_local.pyi | 17 + mypy/stdlib/_tracemalloc.pyi | 12 + mypy/stdlib/_typeshed/__init__.pyi | 78 + mypy/stdlib/_typeshed/wsgi.pyi | 32 + mypy/stdlib/_warnings.pyi | 64 + mypy/stdlib/_weakref.pyi | 28 + mypy/stdlib/_weakrefset.pyi | 43 + mypy/stdlib/_winapi.pyi | 103 + mypy/stdlib/abc.pyi | 19 + mypy/stdlib/aifc.pyi | 86 + mypy/stdlib/antigravity.pyi | 5 + mypy/stdlib/argparse.pyi | 447 ++++ mypy/stdlib/array.pyi | 90 + mypy/stdlib/ast.pyi | 195 ++ mypy/stdlib/asynchat.pyi | 41 + mypy/stdlib/asyncio/__init__.pyi | 138 ++ mypy/stdlib/asyncio/base_events.pyi | 218 ++ mypy/stdlib/asyncio/base_futures.pyi | 13 + mypy/stdlib/asyncio/base_subprocess.pyi | 59 + mypy/stdlib/asyncio/base_tasks.pyi | 8 + mypy/stdlib/asyncio/compat.pyi | 10 + mypy/stdlib/asyncio/constants.pyi | 16 + mypy/stdlib/asyncio/coroutines.pyi | 7 + mypy/stdlib/asyncio/events.pyi | 344 +++ mypy/stdlib/asyncio/exceptions.pyi | 15 + mypy/stdlib/asyncio/format_helpers.pyi | 25 + mypy/stdlib/asyncio/futures.pyi | 65 + mypy/stdlib/asyncio/locks.pyi | 63 + mypy/stdlib/asyncio/log.pyi | 4 + mypy/stdlib/asyncio/proactor_events.pyi | 38 + mypy/stdlib/asyncio/protocols.pyi | 27 + mypy/stdlib/asyncio/queues.pyi | 33 + mypy/stdlib/asyncio/runners.pyi | 9 + mypy/stdlib/asyncio/selector_events.pyi | 7 + mypy/stdlib/asyncio/sslproto.pyi | 131 ++ mypy/stdlib/asyncio/staggered.pyi | 7 + mypy/stdlib/asyncio/streams.pyi | 108 + mypy/stdlib/asyncio/subprocess.pyi | 67 + mypy/stdlib/asyncio/tasks.pyi | 127 ++ mypy/stdlib/asyncio/threads.pyi | 7 + mypy/stdlib/asyncio/transports.pyi | 49 + mypy/stdlib/asyncio/trsock.pyi | 78 + mypy/stdlib/asyncio/unix_events.pyi | 57 + mypy/stdlib/asyncio/windows_events.pyi | 76 + mypy/stdlib/asyncio/windows_utils.pyi | 30 + mypy/stdlib/asyncore.pyi | 137 ++ mypy/stdlib/atexit.pyi | 9 + mypy/stdlib/audioop.pyi | 42 + mypy/stdlib/base64.pyi | 40 + mypy/stdlib/bdb.pyi | 96 + mypy/stdlib/binascii.pyi | 45 + mypy/stdlib/binhex.pyi | 48 + mypy/stdlib/bisect.pyi | 4 + mypy/stdlib/builtins.pyi | 1842 +++++++++++++++++ mypy/stdlib/bz2.pyi | 76 + mypy/stdlib/cProfile.pyi | 24 + mypy/stdlib/calendar.pyi | 122 ++ mypy/stdlib/cgi.pyi | 126 ++ mypy/stdlib/cgitb.pyi | 23 + mypy/stdlib/chunk.pyi | 23 + mypy/stdlib/cmath.pyi | 42 + mypy/stdlib/cmd.pyi | 41 + mypy/stdlib/code.pyi | 38 + mypy/stdlib/codecs.pyi | 277 +++ mypy/stdlib/codeop.pyi | 17 + mypy/stdlib/collections/__init__.pyi | 343 +++ mypy/stdlib/collections/abc.pyi | 36 + mypy/stdlib/colorsys.pyi | 15 + mypy/stdlib/compileall.pyi | 109 + mypy/stdlib/concurrent/__init__.pyi | 0 mypy/stdlib/concurrent/futures/__init__.pyi | 18 + mypy/stdlib/concurrent/futures/_base.pyi | 102 + mypy/stdlib/concurrent/futures/process.pyi | 23 + mypy/stdlib/concurrent/futures/thread.pyi | 30 + mypy/stdlib/configparser.pyi | 243 +++ mypy/stdlib/contextlib.pyi | 109 + mypy/stdlib/contextvars.pyi | 30 + mypy/stdlib/copy.pyi | 14 + mypy/stdlib/copyreg.pyi | 14 + mypy/stdlib/crypt.pyi | 22 + mypy/stdlib/csv.pyi | 101 + mypy/stdlib/ctypes/__init__.pyi | 292 +++ mypy/stdlib/ctypes/util.pyi | 8 + mypy/stdlib/ctypes/wintypes.pyi | 209 ++ mypy/stdlib/curses/__init__.pyi | 15 + mypy/stdlib/curses/ascii.pyi | 62 + mypy/stdlib/curses/panel.pyi | 20 + mypy/stdlib/curses/textpad.pyi | 11 + mypy/stdlib/dataclasses.pyi | 74 + mypy/stdlib/datetime.pyi | 333 +++ mypy/stdlib/dbm/__init__.pyi | 25 + mypy/stdlib/dbm/dumb.pyi | 31 + mypy/stdlib/dbm/gnu.pyi | 36 + mypy/stdlib/dbm/ndbm.pyi | 36 + mypy/stdlib/decimal.pyi | 346 ++++ mypy/stdlib/difflib.pyi | 98 + mypy/stdlib/dis.pyi | 78 + mypy/stdlib/distutils/__init__.pyi | 0 mypy/stdlib/distutils/archive_util.pyi | 12 + mypy/stdlib/distutils/bcppcompiler.pyi | 6 + mypy/stdlib/distutils/ccompiler.pyi | 129 ++ mypy/stdlib/distutils/cmd.pyi | 40 + mypy/stdlib/distutils/command/__init__.pyi | 0 mypy/stdlib/distutils/command/bdist.pyi | 0 mypy/stdlib/distutils/command/bdist_dumb.pyi | 0 mypy/stdlib/distutils/command/bdist_msi.pyi | 6 + .../distutils/command/bdist_packager.pyi | 0 mypy/stdlib/distutils/command/bdist_rpm.pyi | 0 .../distutils/command/bdist_wininst.pyi | 0 mypy/stdlib/distutils/command/build.pyi | 0 mypy/stdlib/distutils/command/build_clib.pyi | 0 mypy/stdlib/distutils/command/build_ext.pyi | 0 mypy/stdlib/distutils/command/build_py.pyi | 10 + .../distutils/command/build_scripts.pyi | 0 mypy/stdlib/distutils/command/check.pyi | 0 mypy/stdlib/distutils/command/clean.pyi | 0 mypy/stdlib/distutils/command/config.pyi | 87 + mypy/stdlib/distutils/command/install.pyi | 14 + .../stdlib/distutils/command/install_data.pyi | 0 .../distutils/command/install_headers.pyi | 0 mypy/stdlib/distutils/command/install_lib.pyi | 0 .../distutils/command/install_scripts.pyi | 0 mypy/stdlib/distutils/command/register.pyi | 0 mypy/stdlib/distutils/command/sdist.pyi | 0 mypy/stdlib/distutils/core.pyi | 50 + mypy/stdlib/distutils/cygwinccompiler.pyi | 7 + mypy/stdlib/distutils/debug.pyi | 3 + mypy/stdlib/distutils/dep_util.pyi | 8 + mypy/stdlib/distutils/dir_util.pyi | 15 + mypy/stdlib/distutils/dist.pyi | 12 + mypy/stdlib/distutils/errors.pyi | 19 + mypy/stdlib/distutils/extension.pyi | 41 + mypy/stdlib/distutils/fancy_getopt.pyi | 27 + mypy/stdlib/distutils/file_util.pyi | 12 + mypy/stdlib/distutils/filelist.pyi | 3 + mypy/stdlib/distutils/log.pyi | 28 + mypy/stdlib/distutils/msvccompiler.pyi | 6 + mypy/stdlib/distutils/spawn.pyi | 8 + mypy/stdlib/distutils/sysconfig.pyi | 19 + mypy/stdlib/distutils/text_file.pyi | 18 + mypy/stdlib/distutils/unixccompiler.pyi | 6 + mypy/stdlib/distutils/util.pyi | 20 + mypy/stdlib/distutils/version.pyi | 54 + mypy/stdlib/doctest.pyi | 160 ++ mypy/stdlib/dummy_threading.pyi | 3 + mypy/stdlib/email/__init__.pyi | 25 + mypy/stdlib/email/charset.pyi | 31 + mypy/stdlib/email/contentmanager.pyi | 15 + mypy/stdlib/email/encoders.pyi | 8 + mypy/stdlib/email/errors.pyi | 20 + mypy/stdlib/email/feedparser.pyi | 17 + mypy/stdlib/email/generator.pyi | 27 + mypy/stdlib/email/header.pyi | 25 + mypy/stdlib/email/headerregistry.pyi | 97 + mypy/stdlib/email/iterators.pyi | 8 + mypy/stdlib/email/message.pyi | 103 + mypy/stdlib/email/mime/__init__.pyi | 0 mypy/stdlib/email/mime/application.pyi | 28 + mypy/stdlib/email/mime/audio.pyi | 28 + mypy/stdlib/email/mime/base.pyi | 14 + mypy/stdlib/email/mime/image.pyi | 28 + mypy/stdlib/email/mime/message.pyi | 13 + mypy/stdlib/email/mime/multipart.pyi | 29 + mypy/stdlib/email/mime/nonmultipart.pyi | 5 + mypy/stdlib/email/mime/text.pyi | 14 + mypy/stdlib/email/parser.pyi | 33 + mypy/stdlib/email/policy.pyi | 62 + mypy/stdlib/email/utils.pyi | 33 + mypy/stdlib/encodings/__init__.pyi | 11 + mypy/stdlib/encodings/utf_8.pyi | 15 + mypy/stdlib/ensurepip/__init__.pyi | 10 + mypy/stdlib/enum.pyi | 76 + mypy/stdlib/errno.pyi | 140 ++ mypy/stdlib/faulthandler.pyi | 12 + mypy/stdlib/fcntl.pyi | 114 + mypy/stdlib/filecmp.pyi | 61 + mypy/stdlib/fileinput.pyi | 76 + mypy/stdlib/fnmatch.pyi | 11 + mypy/stdlib/formatter.pyi | 105 + mypy/stdlib/fractions.pyi | 95 + mypy/stdlib/ftplib.pyi | 168 ++ mypy/stdlib/functools.pyi | 113 + mypy/stdlib/gc.pyi | 32 + mypy/stdlib/genericpath.pyi | 24 + mypy/stdlib/getopt.pyi | 14 + mypy/stdlib/getpass.pyi | 12 + mypy/stdlib/gettext.pyi | 63 + mypy/stdlib/glob.pyi | 19 + mypy/stdlib/grp.pyi | 11 + mypy/stdlib/gzip.pyi | 92 + mypy/stdlib/hashlib.pyi | 86 + mypy/stdlib/heapq.pyi | 18 + mypy/stdlib/hmac.pyi | 47 + mypy/stdlib/html/__init__.pyi | 4 + mypy/stdlib/html/entities.pyi | 6 + mypy/stdlib/html/parser.pyi | 23 + mypy/stdlib/http/__init__.pyi | 74 + mypy/stdlib/http/client.pyi | 200 ++ mypy/stdlib/http/cookiejar.pyi | 123 ++ mypy/stdlib/http/cookies.pyi | 35 + mypy/stdlib/http/server.pyi | 76 + mypy/stdlib/imaplib.pyi | 141 ++ mypy/stdlib/imghdr.pyi | 21 + mypy/stdlib/imp.pyi | 48 + mypy/stdlib/importlib/__init__.pyi | 16 + mypy/stdlib/importlib/abc.pyi | 92 + mypy/stdlib/importlib/machinery.pyi | 125 ++ mypy/stdlib/importlib/metadata.pyi | 87 + mypy/stdlib/importlib/resources.pyi | 25 + mypy/stdlib/importlib/util.pyi | 53 + mypy/stdlib/inspect.pyi | 316 +++ mypy/stdlib/io.pyi | 182 ++ mypy/stdlib/ipaddress.pyi | 154 ++ mypy/stdlib/itertools.pyi | 121 ++ mypy/stdlib/json/__init__.pyi | 58 + mypy/stdlib/json/decoder.pyi | 42 + mypy/stdlib/json/encoder.pyi | 42 + mypy/stdlib/keyword.pyi | 6 + mypy/stdlib/lib2to3/__init__.pyi | 1 + mypy/stdlib/lib2to3/pgen2/__init__.pyi | 0 mypy/stdlib/lib2to3/pgen2/driver.pyi | 20 + mypy/stdlib/lib2to3/pgen2/grammar.pyi | 26 + mypy/stdlib/lib2to3/pgen2/literals.pyi | 9 + mypy/stdlib/lib2to3/pgen2/parse.pyi | 29 + mypy/stdlib/lib2to3/pgen2/pgen.pyi | 49 + mypy/stdlib/lib2to3/pgen2/token.pyi | 73 + mypy/stdlib/lib2to3/pgen2/tokenize.pyi | 30 + mypy/stdlib/lib2to3/pygram.pyi | 116 ++ mypy/stdlib/lib2to3/pytree.pyi | 86 + mypy/stdlib/linecache.pyi | 12 + mypy/stdlib/locale.pyi | 113 + mypy/stdlib/logging/__init__.pyi | 556 +++++ mypy/stdlib/logging/config.pyi | 28 + mypy/stdlib/logging/handlers.pyi | 217 ++ mypy/stdlib/lzma.pyi | 164 ++ mypy/stdlib/macpath.pyi | 144 ++ mypy/stdlib/macurl2path.pyi | 9 + mypy/stdlib/mailbox.pyi | 188 ++ mypy/stdlib/mailcap.pyi | 7 + mypy/stdlib/marshal.pyi | 8 + mypy/stdlib/math.pyi | 83 + mypy/stdlib/mimetypes.pyi | 44 + mypy/stdlib/mmap.pyi | 108 + mypy/stdlib/modulefinder.pyi | 58 + mypy/stdlib/msilib/__init__.pyi | 129 ++ mypy/stdlib/msilib/schema.pyi | 96 + mypy/stdlib/msilib/sequence.pyi | 15 + mypy/stdlib/msilib/text.pyi | 10 + mypy/stdlib/msvcrt.pyi | 14 + mypy/stdlib/multiprocessing/__init__.pyi | 107 + mypy/stdlib/multiprocessing/connection.pyi | 58 + mypy/stdlib/multiprocessing/context.pyi | 180 ++ .../stdlib/multiprocessing/dummy/__init__.pyi | 46 + .../multiprocessing/dummy/connection.pyi | 35 + mypy/stdlib/multiprocessing/managers.pyi | 110 + mypy/stdlib/multiprocessing/pool.pyi | 83 + mypy/stdlib/multiprocessing/process.pyi | 38 + mypy/stdlib/multiprocessing/queues.pyi | 30 + mypy/stdlib/multiprocessing/shared_memory.pyi | 29 + mypy/stdlib/multiprocessing/spawn.pyi | 18 + mypy/stdlib/multiprocessing/synchronize.pyi | 63 + mypy/stdlib/netrc.pyi | 19 + mypy/stdlib/nis.pyi | 10 + mypy/stdlib/nntplib.pyi | 102 + mypy/stdlib/ntpath.pyi | 164 ++ mypy/stdlib/nturl2path.pyi | 2 + mypy/stdlib/numbers.pyi | 144 ++ mypy/stdlib/opcode.pyi | 25 + mypy/stdlib/operator.pyi | 239 +++ mypy/stdlib/optparse.pyi | 234 +++ mypy/stdlib/os/__init__.pyi | 717 +++++++ mypy/stdlib/os/path.pyi | 164 ++ mypy/stdlib/parser.pyi | 22 + mypy/stdlib/pathlib.pyi | 158 ++ mypy/stdlib/pdb.pyi | 252 +++ mypy/stdlib/pickle.pyi | 177 ++ mypy/stdlib/pickletools.pyi | 145 ++ mypy/stdlib/pipes.pyi | 19 + mypy/stdlib/pkgutil.pyi | 38 + mypy/stdlib/platform.pyi | 47 + mypy/stdlib/plistlib.pyi | 84 + mypy/stdlib/poplib.pyi | 77 + mypy/stdlib/posix.pyi | 126 ++ mypy/stdlib/posixpath.pyi | 164 ++ mypy/stdlib/pprint.pyi | 80 + mypy/stdlib/profile.pyi | 24 + mypy/stdlib/pstats.pyi | 35 + mypy/stdlib/pty.pyi | 20 + mypy/stdlib/pwd.pyi | 14 + mypy/stdlib/py_compile.pyi | 32 + mypy/stdlib/pyclbr.pyi | 38 + mypy/stdlib/pydoc.pyi | 185 ++ mypy/stdlib/pyexpat/__init__.pyi | 74 + mypy/stdlib/pyexpat/errors.pyi | 44 + mypy/stdlib/pyexpat/model.pyi | 11 + mypy/stdlib/python2/BaseHTTPServer.pyi | 47 + mypy/stdlib/python2/CGIHTTPServer.pyi | 8 + mypy/stdlib/python2/ConfigParser.pyi | 97 + mypy/stdlib/python2/Cookie.pyi | 40 + mypy/stdlib/python2/HTMLParser.pyi | 31 + mypy/stdlib/python2/Queue.pyi | 31 + mypy/stdlib/python2/SimpleHTTPServer.pyi | 16 + mypy/stdlib/python2/SocketServer.pyi | 135 ++ mypy/stdlib/python2/StringIO.pyi | 30 + mypy/stdlib/python2/UserDict.pyi | 44 + mypy/stdlib/python2/UserList.pyi | 19 + mypy/stdlib/python2/UserString.pyi | 75 + mypy/stdlib/python2/__builtin__.pyi | 1842 +++++++++++++++++ mypy/stdlib/python2/_ast.pyi | 330 +++ mypy/stdlib/python2/_collections.pyi | 38 + mypy/stdlib/python2/_functools.pyi | 20 + mypy/stdlib/python2/_hotshot.pyi | 24 + mypy/stdlib/python2/_io.pyi | 186 ++ mypy/stdlib/python2/_json.pyi | 7 + mypy/stdlib/python2/_md5.pyi | 13 + mypy/stdlib/python2/_sha.pyi | 15 + mypy/stdlib/python2/_sha256.pyi | 23 + mypy/stdlib/python2/_sha512.pyi | 23 + mypy/stdlib/python2/_socket.pyi | 283 +++ mypy/stdlib/python2/_sre.pyi | 55 + mypy/stdlib/python2/_struct.pyi | 22 + mypy/stdlib/python2/_symtable.pyi | 39 + mypy/stdlib/python2/_threading_local.pyi | 12 + mypy/stdlib/python2/_winreg.pyi | 99 + mypy/stdlib/python2/abc.pyi | 31 + mypy/stdlib/python2/ast.pyi | 28 + mypy/stdlib/python2/atexit.pyi | 5 + mypy/stdlib/python2/cPickle.pyi | 32 + mypy/stdlib/python2/cStringIO.pyi | 54 + mypy/stdlib/python2/collections.pyi | 120 ++ mypy/stdlib/python2/commands.pyi | 12 + mypy/stdlib/python2/compileall.pyi | 16 + mypy/stdlib/python2/cookielib.pyi | 112 + mypy/stdlib/python2/copy_reg.pyi | 14 + mypy/stdlib/python2/dircache.pyi | 10 + mypy/stdlib/python2/distutils/__init__.pyi | 0 .../stdlib/python2/distutils/emxccompiler.pyi | 5 + mypy/stdlib/python2/dummy_thread.pyi | 21 + mypy/stdlib/python2/email/MIMEText.pyi | 4 + mypy/stdlib/python2/email/__init__.pyi | 6 + mypy/stdlib/python2/email/_parseaddr.pyi | 40 + mypy/stdlib/python2/email/base64mime.pyi | 8 + mypy/stdlib/python2/email/charset.pyi | 26 + mypy/stdlib/python2/email/encoders.pyi | 4 + mypy/stdlib/python2/email/feedparser.pyi | 18 + mypy/stdlib/python2/email/generator.pyi | 9 + mypy/stdlib/python2/email/header.pyi | 11 + mypy/stdlib/python2/email/iterators.pyi | 5 + mypy/stdlib/python2/email/message.pyi | 45 + mypy/stdlib/python2/email/mime/__init__.pyi | 0 .../stdlib/python2/email/mime/application.pyi | 11 + mypy/stdlib/python2/email/mime/audio.pyi | 5 + mypy/stdlib/python2/email/mime/base.pyi | 4 + mypy/stdlib/python2/email/mime/image.pyi | 5 + mypy/stdlib/python2/email/mime/message.pyi | 5 + mypy/stdlib/python2/email/mime/multipart.pyi | 4 + .../python2/email/mime/nonmultipart.pyi | 4 + mypy/stdlib/python2/email/mime/text.pyi | 4 + mypy/stdlib/python2/email/parser.pyi | 10 + mypy/stdlib/python2/email/quoprimime.pyi | 18 + mypy/stdlib/python2/email/utils.pyi | 19 + mypy/stdlib/python2/encodings/__init__.pyi | 8 + mypy/stdlib/python2/encodings/utf_8.pyi | 15 + mypy/stdlib/python2/exceptions.pyi | 48 + mypy/stdlib/python2/fcntl.pyi | 85 + mypy/stdlib/python2/fnmatch.pyi | 8 + mypy/stdlib/python2/functools.pyi | 33 + mypy/stdlib/python2/future_builtins.pyi | 14 + mypy/stdlib/python2/gc.pyi | 29 + mypy/stdlib/python2/getopt.pyi | 12 + mypy/stdlib/python2/getpass.pyi | 8 + mypy/stdlib/python2/gettext.pyi | 41 + mypy/stdlib/python2/glob.pyi | 7 + mypy/stdlib/python2/gzip.pyi | 37 + mypy/stdlib/python2/hashlib.pyi | 31 + mypy/stdlib/python2/heapq.pyi | 18 + mypy/stdlib/python2/htmlentitydefs.pyi | 5 + mypy/stdlib/python2/httplib.pyi | 205 ++ mypy/stdlib/python2/imp.pyi | 35 + mypy/stdlib/python2/importlib.pyi | 4 + mypy/stdlib/python2/inspect.pyi | 129 ++ mypy/stdlib/python2/io.pyi | 42 + mypy/stdlib/python2/itertools.pyi | 167 ++ mypy/stdlib/python2/json.pyi | 94 + mypy/stdlib/python2/markupbase.pyi | 9 + mypy/stdlib/python2/md5.pyi | 6 + mypy/stdlib/python2/mimetools.pyi | 27 + .../python2/multiprocessing/__init__.pyi | 50 + .../multiprocessing/dummy/__init__.pyi | 51 + .../multiprocessing/dummy/connection.pyi | 26 + mypy/stdlib/python2/multiprocessing/pool.pyi | 54 + .../python2/multiprocessing/process.pyi | 36 + mypy/stdlib/python2/multiprocessing/util.pyi | 29 + mypy/stdlib/python2/mutex.pyi | 14 + mypy/stdlib/python2/nturl2path.pyi | 4 + mypy/stdlib/python2/os/__init__.pyi | 357 ++++ mypy/stdlib/python2/os/path.pyi | 164 ++ mypy/stdlib/python2/os2emxpath.pyi | 164 ++ mypy/stdlib/python2/pipes.pyi | 13 + mypy/stdlib/python2/platform.pyi | 45 + mypy/stdlib/python2/popen2.pyi | 28 + mypy/stdlib/python2/posix.pyi | 198 ++ mypy/stdlib/python2/random.pyi | 77 + mypy/stdlib/python2/re.pyi | 100 + mypy/stdlib/python2/repr.pyi | 33 + mypy/stdlib/python2/resource.pyi | 45 + mypy/stdlib/python2/rfc822.pyi | 79 + mypy/stdlib/python2/robotparser.pyi | 7 + mypy/stdlib/python2/runpy.pyi | 17 + mypy/stdlib/python2/sets.pyi | 61 + mypy/stdlib/python2/sha.pyi | 11 + mypy/stdlib/python2/shelve.pyi | 33 + mypy/stdlib/python2/shlex.pyi | 31 + mypy/stdlib/python2/signal.pyi | 68 + mypy/stdlib/python2/smtplib.pyi | 86 + mypy/stdlib/python2/spwd.pyi | 15 + mypy/stdlib/python2/sre_constants.pyi | 94 + mypy/stdlib/python2/sre_parse.pyi | 63 + mypy/stdlib/python2/stat.pyi | 59 + mypy/stdlib/python2/string.pyi | 75 + mypy/stdlib/python2/stringold.pyi | 46 + mypy/stdlib/python2/strop.pyi | 29 + mypy/stdlib/python2/subprocess.pyi | 120 ++ mypy/stdlib/python2/symbol.pyi | 91 + mypy/stdlib/python2/sys.pyi | 136 ++ mypy/stdlib/python2/tempfile.pyi | 111 + mypy/stdlib/python2/textwrap.pyi | 61 + mypy/stdlib/python2/thread.pyi | 28 + mypy/stdlib/python2/toaiff.pyi | 14 + mypy/stdlib/python2/tokenize.pyi | 136 ++ mypy/stdlib/python2/types.pyi | 187 ++ mypy/stdlib/python2/typing.pyi | 510 +++++ mypy/stdlib/python2/unittest.pyi | 290 +++ mypy/stdlib/python2/urllib.pyi | 134 ++ mypy/stdlib/python2/urllib2.pyi | 182 ++ mypy/stdlib/python2/urlparse.pyi | 66 + mypy/stdlib/python2/user.pyi | 9 + mypy/stdlib/python2/whichdb.pyi | 5 + mypy/stdlib/python2/xmlrpclib.pyi | 231 +++ mypy/stdlib/queue.pyi | 50 + mypy/stdlib/quopri.pyi | 8 + mypy/stdlib/random.pyi | 79 + mypy/stdlib/re.pyi | 160 ++ mypy/stdlib/readline.pyi | 41 + mypy/stdlib/reprlib.pyi | 37 + mypy/stdlib/resource.pyi | 53 + mypy/stdlib/rlcompleter.pyi | 14 + mypy/stdlib/runpy.pyi | 23 + mypy/stdlib/sched.pyi | 26 + mypy/stdlib/secrets.pyi | 14 + mypy/stdlib/select.pyi | 140 ++ mypy/stdlib/selectors.pyi | 79 + mypy/stdlib/shelve.pyi | 31 + mypy/stdlib/shlex.pyi | 45 + mypy/stdlib/shutil.pyi | 143 ++ mypy/stdlib/signal.pyi | 185 ++ mypy/stdlib/site.pyi | 17 + mypy/stdlib/smtpd.pyi | 78 + mypy/stdlib/smtplib.pyi | 136 ++ mypy/stdlib/sndhdr.pyi | 17 + mypy/stdlib/socket.pyi | 822 ++++++++ mypy/stdlib/socketserver.pyi | 135 ++ mypy/stdlib/spwd.pyi | 15 + mypy/stdlib/sqlite3/__init__.pyi | 1 + mypy/stdlib/sqlite3/dbapi2.pyi | 297 +++ mypy/stdlib/sre_compile.pyi | 18 + mypy/stdlib/sre_constants.pyi | 114 + mypy/stdlib/sre_parse.pyi | 102 + mypy/stdlib/ssl.pyi | 423 ++++ mypy/stdlib/stat.pyi | 97 + mypy/stdlib/statistics.pyi | 74 + mypy/stdlib/string.pyi | 39 + mypy/stdlib/stringprep.pyi | 23 + mypy/stdlib/struct.pyi | 44 + mypy/stdlib/subprocess.pyi | 1204 +++++++++++ mypy/stdlib/sunau.pyi | 87 + mypy/stdlib/symbol.pyi | 94 + mypy/stdlib/symtable.pyi | 45 + mypy/stdlib/sys.pyi | 225 ++ mypy/stdlib/sysconfig.pyi | 17 + mypy/stdlib/syslog.pyi | 44 + mypy/stdlib/tabnanny.pyi | 14 + mypy/stdlib/tarfile.pyi | 222 ++ mypy/stdlib/telnetlib.pyi | 115 + mypy/stdlib/tempfile.pyi | 302 +++ mypy/stdlib/termios.pyi | 246 +++ mypy/stdlib/textwrap.pyi | 113 + mypy/stdlib/this.pyi | 5 + mypy/stdlib/threading.pyi | 190 ++ mypy/stdlib/time.pyi | 113 + mypy/stdlib/timeit.pyi | 34 + mypy/stdlib/tkinter/__init__.pyi | 743 +++++++ mypy/stdlib/tkinter/commondialog.pyi | 8 + mypy/stdlib/tkinter/constants.pyi | 79 + mypy/stdlib/tkinter/dialog.pyi | 10 + mypy/stdlib/tkinter/filedialog.pyi | 65 + mypy/stdlib/tkinter/messagebox.pyi | 31 + mypy/stdlib/tkinter/ttk.pyi | 163 ++ mypy/stdlib/token.pyi | 84 + mypy/stdlib/tokenize.pyi | 110 + mypy/stdlib/trace.pyi | 27 + mypy/stdlib/traceback.pyi | 117 ++ mypy/stdlib/tracemalloc.pyi | 89 + mypy/stdlib/tty.pyi | 17 + mypy/stdlib/turtle.pyi | 509 +++++ mypy/stdlib/types.pyi | 302 +++ mypy/stdlib/typing.pyi | 693 +++++++ mypy/stdlib/unicodedata.pyi | 40 + mypy/stdlib/unittest/__init__.pyi | 15 + mypy/stdlib/unittest/async_case.pyi | 9 + mypy/stdlib/unittest/case.pyi | 262 +++ mypy/stdlib/unittest/loader.pyi | 49 + mypy/stdlib/unittest/main.pyi | 51 + mypy/stdlib/unittest/mock.pyi | 234 +++ mypy/stdlib/unittest/result.pyi | 46 + mypy/stdlib/unittest/runner.pyi | 39 + mypy/stdlib/unittest/signals.pyi | 14 + mypy/stdlib/unittest/suite.pyi | 24 + mypy/stdlib/unittest/util.pyi | 22 + mypy/stdlib/urllib/__init__.pyi | 0 mypy/stdlib/urllib/error.pyi | 11 + mypy/stdlib/urllib/parse.pyi | 165 ++ mypy/stdlib/urllib/request.pyi | 222 ++ mypy/stdlib/urllib/response.pyi | 51 + mypy/stdlib/urllib/robotparser.pyi | 22 + mypy/stdlib/uu.pyi | 13 + mypy/stdlib/uuid.pyi | 110 + mypy/stdlib/venv/__init__.pyi | 42 + mypy/stdlib/warnings.pyi | 67 + mypy/stdlib/wave.pyi | 76 + mypy/stdlib/weakref.pyi | 110 + mypy/stdlib/webbrowser.pyi | 100 + mypy/stdlib/winreg.pyi | 99 + mypy/stdlib/winsound.pyi | 28 + mypy/stdlib/wsgiref/__init__.pyi | 0 mypy/stdlib/wsgiref/handlers.pyi | 87 + mypy/stdlib/wsgiref/headers.pyi | 31 + mypy/stdlib/wsgiref/simple_server.pyi | 40 + mypy/stdlib/wsgiref/types.pyi | 3 + mypy/stdlib/wsgiref/util.pyi | 23 + mypy/stdlib/wsgiref/validate.pyi | 53 + mypy/stdlib/xdrlib.pyi | 56 + mypy/stdlib/xml/__init__.pyi | 1 + mypy/stdlib/xml/dom/NodeFilter.pyi | 20 + mypy/stdlib/xml/dom/__init__.pyi | 67 + mypy/stdlib/xml/dom/minidom.pyi | 3 + mypy/stdlib/xml/dom/pulldom.pyi | 3 + mypy/stdlib/xml/etree/ElementInclude.pyi | 19 + mypy/stdlib/xml/etree/ElementPath.pyi | 33 + mypy/stdlib/xml/etree/ElementTree.pyi | 314 +++ mypy/stdlib/xml/etree/__init__.pyi | 0 mypy/stdlib/xml/etree/cElementTree.pyi | 3 + mypy/stdlib/xml/parsers/__init__.pyi | 1 + mypy/stdlib/xml/parsers/expat/__init__.pyi | 1 + mypy/stdlib/xml/parsers/expat/errors.pyi | 1 + mypy/stdlib/xml/parsers/expat/model.pyi | 1 + mypy/stdlib/xml/sax/__init__.pyi | 38 + mypy/stdlib/xml/sax/handler.pyi | 46 + mypy/stdlib/xml/sax/saxutils.pyi | 61 + mypy/stdlib/xml/sax/xmlreader.pyi | 74 + mypy/stdlib/xmlrpc/__init__.pyi | 0 mypy/stdlib/xmlrpc/client.pyi | 275 +++ mypy/stdlib/xmlrpc/server.pyi | 119 ++ mypy/stdlib/zipapp.pyi | 16 + mypy/stdlib/zipfile.pyi | 189 ++ mypy/stdlib/zipimport.pyi | 29 + mypy/stdlib/zlib.pyi | 57 + mypy/stdlib/zoneinfo/__init__.pyi | 45 + 596 files changed, 46295 insertions(+) create mode 100644 mypy/stdlib/VERSIONS create mode 100644 mypy/stdlib/__future__.pyi create mode 100644 mypy/stdlib/_ast.pyi create mode 100644 mypy/stdlib/_bisect.pyi create mode 100644 mypy/stdlib/_bootlocale.pyi create mode 100644 mypy/stdlib/_codecs.pyi create mode 100644 mypy/stdlib/_compat_pickle.pyi create mode 100644 mypy/stdlib/_compression.pyi create mode 100644 mypy/stdlib/_csv.pyi create mode 100644 mypy/stdlib/_curses.pyi create mode 100644 mypy/stdlib/_decimal.pyi create mode 100644 mypy/stdlib/_dummy_thread.pyi create mode 100644 mypy/stdlib/_dummy_threading.pyi create mode 100644 mypy/stdlib/_heapq.pyi create mode 100644 mypy/stdlib/_imp.pyi create mode 100644 mypy/stdlib/_importlib_modulespec.pyi create mode 100644 mypy/stdlib/_json.pyi create mode 100644 mypy/stdlib/_markupbase.pyi create mode 100644 mypy/stdlib/_msi.pyi create mode 100644 mypy/stdlib/_operator.pyi create mode 100644 mypy/stdlib/_osx_support.pyi create mode 100644 mypy/stdlib/_posixsubprocess.pyi create mode 100644 mypy/stdlib/_py_abc.pyi create mode 100644 mypy/stdlib/_pydecimal.pyi create mode 100644 mypy/stdlib/_random.pyi create mode 100644 mypy/stdlib/_sitebuiltins.pyi create mode 100644 mypy/stdlib/_stat.pyi create mode 100644 mypy/stdlib/_thread.pyi create mode 100644 mypy/stdlib/_threading_local.pyi create mode 100644 mypy/stdlib/_tracemalloc.pyi create mode 100644 mypy/stdlib/_typeshed/__init__.pyi create mode 100644 mypy/stdlib/_typeshed/wsgi.pyi create mode 100644 mypy/stdlib/_warnings.pyi create mode 100644 mypy/stdlib/_weakref.pyi create mode 100644 mypy/stdlib/_weakrefset.pyi create mode 100644 mypy/stdlib/_winapi.pyi create mode 100644 mypy/stdlib/abc.pyi create mode 100644 mypy/stdlib/aifc.pyi create mode 100644 mypy/stdlib/antigravity.pyi create mode 100644 mypy/stdlib/argparse.pyi create mode 100644 mypy/stdlib/array.pyi create mode 100644 mypy/stdlib/ast.pyi create mode 100644 mypy/stdlib/asynchat.pyi create mode 100644 mypy/stdlib/asyncio/__init__.pyi create mode 100644 mypy/stdlib/asyncio/base_events.pyi create mode 100644 mypy/stdlib/asyncio/base_futures.pyi create mode 100644 mypy/stdlib/asyncio/base_subprocess.pyi create mode 100644 mypy/stdlib/asyncio/base_tasks.pyi create mode 100644 mypy/stdlib/asyncio/compat.pyi create mode 100644 mypy/stdlib/asyncio/constants.pyi create mode 100644 mypy/stdlib/asyncio/coroutines.pyi create mode 100644 mypy/stdlib/asyncio/events.pyi create mode 100644 mypy/stdlib/asyncio/exceptions.pyi create mode 100644 mypy/stdlib/asyncio/format_helpers.pyi create mode 100644 mypy/stdlib/asyncio/futures.pyi create mode 100644 mypy/stdlib/asyncio/locks.pyi create mode 100644 mypy/stdlib/asyncio/log.pyi create mode 100644 mypy/stdlib/asyncio/proactor_events.pyi create mode 100644 mypy/stdlib/asyncio/protocols.pyi create mode 100644 mypy/stdlib/asyncio/queues.pyi create mode 100644 mypy/stdlib/asyncio/runners.pyi create mode 100644 mypy/stdlib/asyncio/selector_events.pyi create mode 100644 mypy/stdlib/asyncio/sslproto.pyi create mode 100644 mypy/stdlib/asyncio/staggered.pyi create mode 100644 mypy/stdlib/asyncio/streams.pyi create mode 100644 mypy/stdlib/asyncio/subprocess.pyi create mode 100644 mypy/stdlib/asyncio/tasks.pyi create mode 100644 mypy/stdlib/asyncio/threads.pyi create mode 100644 mypy/stdlib/asyncio/transports.pyi create mode 100644 mypy/stdlib/asyncio/trsock.pyi create mode 100644 mypy/stdlib/asyncio/unix_events.pyi create mode 100644 mypy/stdlib/asyncio/windows_events.pyi create mode 100644 mypy/stdlib/asyncio/windows_utils.pyi create mode 100644 mypy/stdlib/asyncore.pyi create mode 100644 mypy/stdlib/atexit.pyi create mode 100644 mypy/stdlib/audioop.pyi create mode 100644 mypy/stdlib/base64.pyi create mode 100644 mypy/stdlib/bdb.pyi create mode 100644 mypy/stdlib/binascii.pyi create mode 100644 mypy/stdlib/binhex.pyi create mode 100644 mypy/stdlib/bisect.pyi create mode 100644 mypy/stdlib/builtins.pyi create mode 100644 mypy/stdlib/bz2.pyi create mode 100644 mypy/stdlib/cProfile.pyi create mode 100644 mypy/stdlib/calendar.pyi create mode 100644 mypy/stdlib/cgi.pyi create mode 100644 mypy/stdlib/cgitb.pyi create mode 100644 mypy/stdlib/chunk.pyi create mode 100644 mypy/stdlib/cmath.pyi create mode 100644 mypy/stdlib/cmd.pyi create mode 100644 mypy/stdlib/code.pyi create mode 100644 mypy/stdlib/codecs.pyi create mode 100644 mypy/stdlib/codeop.pyi create mode 100644 mypy/stdlib/collections/__init__.pyi create mode 100644 mypy/stdlib/collections/abc.pyi create mode 100644 mypy/stdlib/colorsys.pyi create mode 100644 mypy/stdlib/compileall.pyi create mode 100644 mypy/stdlib/concurrent/__init__.pyi create mode 100644 mypy/stdlib/concurrent/futures/__init__.pyi create mode 100644 mypy/stdlib/concurrent/futures/_base.pyi create mode 100644 mypy/stdlib/concurrent/futures/process.pyi create mode 100644 mypy/stdlib/concurrent/futures/thread.pyi create mode 100644 mypy/stdlib/configparser.pyi create mode 100644 mypy/stdlib/contextlib.pyi create mode 100644 mypy/stdlib/contextvars.pyi create mode 100644 mypy/stdlib/copy.pyi create mode 100644 mypy/stdlib/copyreg.pyi create mode 100644 mypy/stdlib/crypt.pyi create mode 100644 mypy/stdlib/csv.pyi create mode 100644 mypy/stdlib/ctypes/__init__.pyi create mode 100644 mypy/stdlib/ctypes/util.pyi create mode 100644 mypy/stdlib/ctypes/wintypes.pyi create mode 100644 mypy/stdlib/curses/__init__.pyi create mode 100644 mypy/stdlib/curses/ascii.pyi create mode 100644 mypy/stdlib/curses/panel.pyi create mode 100644 mypy/stdlib/curses/textpad.pyi create mode 100644 mypy/stdlib/dataclasses.pyi create mode 100644 mypy/stdlib/datetime.pyi create mode 100644 mypy/stdlib/dbm/__init__.pyi create mode 100644 mypy/stdlib/dbm/dumb.pyi create mode 100644 mypy/stdlib/dbm/gnu.pyi create mode 100644 mypy/stdlib/dbm/ndbm.pyi create mode 100644 mypy/stdlib/decimal.pyi create mode 100644 mypy/stdlib/difflib.pyi create mode 100644 mypy/stdlib/dis.pyi create mode 100644 mypy/stdlib/distutils/__init__.pyi create mode 100644 mypy/stdlib/distutils/archive_util.pyi create mode 100644 mypy/stdlib/distutils/bcppcompiler.pyi create mode 100644 mypy/stdlib/distutils/ccompiler.pyi create mode 100644 mypy/stdlib/distutils/cmd.pyi create mode 100644 mypy/stdlib/distutils/command/__init__.pyi create mode 100644 mypy/stdlib/distutils/command/bdist.pyi create mode 100644 mypy/stdlib/distutils/command/bdist_dumb.pyi create mode 100644 mypy/stdlib/distutils/command/bdist_msi.pyi create mode 100644 mypy/stdlib/distutils/command/bdist_packager.pyi create mode 100644 mypy/stdlib/distutils/command/bdist_rpm.pyi create mode 100644 mypy/stdlib/distutils/command/bdist_wininst.pyi create mode 100644 mypy/stdlib/distutils/command/build.pyi create mode 100644 mypy/stdlib/distutils/command/build_clib.pyi create mode 100644 mypy/stdlib/distutils/command/build_ext.pyi create mode 100644 mypy/stdlib/distutils/command/build_py.pyi create mode 100644 mypy/stdlib/distutils/command/build_scripts.pyi create mode 100644 mypy/stdlib/distutils/command/check.pyi create mode 100644 mypy/stdlib/distutils/command/clean.pyi create mode 100644 mypy/stdlib/distutils/command/config.pyi create mode 100644 mypy/stdlib/distutils/command/install.pyi create mode 100644 mypy/stdlib/distutils/command/install_data.pyi create mode 100644 mypy/stdlib/distutils/command/install_headers.pyi create mode 100644 mypy/stdlib/distutils/command/install_lib.pyi create mode 100644 mypy/stdlib/distutils/command/install_scripts.pyi create mode 100644 mypy/stdlib/distutils/command/register.pyi create mode 100644 mypy/stdlib/distutils/command/sdist.pyi create mode 100644 mypy/stdlib/distutils/core.pyi create mode 100644 mypy/stdlib/distutils/cygwinccompiler.pyi create mode 100644 mypy/stdlib/distutils/debug.pyi create mode 100644 mypy/stdlib/distutils/dep_util.pyi create mode 100644 mypy/stdlib/distutils/dir_util.pyi create mode 100644 mypy/stdlib/distutils/dist.pyi create mode 100644 mypy/stdlib/distutils/errors.pyi create mode 100644 mypy/stdlib/distutils/extension.pyi create mode 100644 mypy/stdlib/distutils/fancy_getopt.pyi create mode 100644 mypy/stdlib/distutils/file_util.pyi create mode 100644 mypy/stdlib/distutils/filelist.pyi create mode 100644 mypy/stdlib/distutils/log.pyi create mode 100644 mypy/stdlib/distutils/msvccompiler.pyi create mode 100644 mypy/stdlib/distutils/spawn.pyi create mode 100644 mypy/stdlib/distutils/sysconfig.pyi create mode 100644 mypy/stdlib/distutils/text_file.pyi create mode 100644 mypy/stdlib/distutils/unixccompiler.pyi create mode 100644 mypy/stdlib/distutils/util.pyi create mode 100644 mypy/stdlib/distutils/version.pyi create mode 100644 mypy/stdlib/doctest.pyi create mode 100644 mypy/stdlib/dummy_threading.pyi create mode 100644 mypy/stdlib/email/__init__.pyi create mode 100644 mypy/stdlib/email/charset.pyi create mode 100644 mypy/stdlib/email/contentmanager.pyi create mode 100644 mypy/stdlib/email/encoders.pyi create mode 100644 mypy/stdlib/email/errors.pyi create mode 100644 mypy/stdlib/email/feedparser.pyi create mode 100644 mypy/stdlib/email/generator.pyi create mode 100644 mypy/stdlib/email/header.pyi create mode 100644 mypy/stdlib/email/headerregistry.pyi create mode 100644 mypy/stdlib/email/iterators.pyi create mode 100644 mypy/stdlib/email/message.pyi create mode 100644 mypy/stdlib/email/mime/__init__.pyi create mode 100644 mypy/stdlib/email/mime/application.pyi create mode 100644 mypy/stdlib/email/mime/audio.pyi create mode 100644 mypy/stdlib/email/mime/base.pyi create mode 100644 mypy/stdlib/email/mime/image.pyi create mode 100644 mypy/stdlib/email/mime/message.pyi create mode 100644 mypy/stdlib/email/mime/multipart.pyi create mode 100644 mypy/stdlib/email/mime/nonmultipart.pyi create mode 100644 mypy/stdlib/email/mime/text.pyi create mode 100644 mypy/stdlib/email/parser.pyi create mode 100644 mypy/stdlib/email/policy.pyi create mode 100644 mypy/stdlib/email/utils.pyi create mode 100644 mypy/stdlib/encodings/__init__.pyi create mode 100644 mypy/stdlib/encodings/utf_8.pyi create mode 100644 mypy/stdlib/ensurepip/__init__.pyi create mode 100644 mypy/stdlib/enum.pyi create mode 100644 mypy/stdlib/errno.pyi create mode 100644 mypy/stdlib/faulthandler.pyi create mode 100644 mypy/stdlib/fcntl.pyi create mode 100644 mypy/stdlib/filecmp.pyi create mode 100644 mypy/stdlib/fileinput.pyi create mode 100644 mypy/stdlib/fnmatch.pyi create mode 100644 mypy/stdlib/formatter.pyi create mode 100644 mypy/stdlib/fractions.pyi create mode 100644 mypy/stdlib/ftplib.pyi create mode 100644 mypy/stdlib/functools.pyi create mode 100644 mypy/stdlib/gc.pyi create mode 100644 mypy/stdlib/genericpath.pyi create mode 100644 mypy/stdlib/getopt.pyi create mode 100644 mypy/stdlib/getpass.pyi create mode 100644 mypy/stdlib/gettext.pyi create mode 100644 mypy/stdlib/glob.pyi create mode 100644 mypy/stdlib/grp.pyi create mode 100644 mypy/stdlib/gzip.pyi create mode 100644 mypy/stdlib/hashlib.pyi create mode 100644 mypy/stdlib/heapq.pyi create mode 100644 mypy/stdlib/hmac.pyi create mode 100644 mypy/stdlib/html/__init__.pyi create mode 100644 mypy/stdlib/html/entities.pyi create mode 100644 mypy/stdlib/html/parser.pyi create mode 100644 mypy/stdlib/http/__init__.pyi create mode 100644 mypy/stdlib/http/client.pyi create mode 100644 mypy/stdlib/http/cookiejar.pyi create mode 100644 mypy/stdlib/http/cookies.pyi create mode 100644 mypy/stdlib/http/server.pyi create mode 100644 mypy/stdlib/imaplib.pyi create mode 100644 mypy/stdlib/imghdr.pyi create mode 100644 mypy/stdlib/imp.pyi create mode 100644 mypy/stdlib/importlib/__init__.pyi create mode 100644 mypy/stdlib/importlib/abc.pyi create mode 100644 mypy/stdlib/importlib/machinery.pyi create mode 100644 mypy/stdlib/importlib/metadata.pyi create mode 100644 mypy/stdlib/importlib/resources.pyi create mode 100644 mypy/stdlib/importlib/util.pyi create mode 100644 mypy/stdlib/inspect.pyi create mode 100644 mypy/stdlib/io.pyi create mode 100644 mypy/stdlib/ipaddress.pyi create mode 100644 mypy/stdlib/itertools.pyi create mode 100644 mypy/stdlib/json/__init__.pyi create mode 100644 mypy/stdlib/json/decoder.pyi create mode 100644 mypy/stdlib/json/encoder.pyi create mode 100644 mypy/stdlib/keyword.pyi create mode 100644 mypy/stdlib/lib2to3/__init__.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/__init__.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/driver.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/grammar.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/literals.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/parse.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/pgen.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/token.pyi create mode 100644 mypy/stdlib/lib2to3/pgen2/tokenize.pyi create mode 100644 mypy/stdlib/lib2to3/pygram.pyi create mode 100644 mypy/stdlib/lib2to3/pytree.pyi create mode 100644 mypy/stdlib/linecache.pyi create mode 100644 mypy/stdlib/locale.pyi create mode 100644 mypy/stdlib/logging/__init__.pyi create mode 100644 mypy/stdlib/logging/config.pyi create mode 100644 mypy/stdlib/logging/handlers.pyi create mode 100644 mypy/stdlib/lzma.pyi create mode 100644 mypy/stdlib/macpath.pyi create mode 100644 mypy/stdlib/macurl2path.pyi create mode 100644 mypy/stdlib/mailbox.pyi create mode 100644 mypy/stdlib/mailcap.pyi create mode 100644 mypy/stdlib/marshal.pyi create mode 100644 mypy/stdlib/math.pyi create mode 100644 mypy/stdlib/mimetypes.pyi create mode 100644 mypy/stdlib/mmap.pyi create mode 100644 mypy/stdlib/modulefinder.pyi create mode 100644 mypy/stdlib/msilib/__init__.pyi create mode 100644 mypy/stdlib/msilib/schema.pyi create mode 100644 mypy/stdlib/msilib/sequence.pyi create mode 100644 mypy/stdlib/msilib/text.pyi create mode 100644 mypy/stdlib/msvcrt.pyi create mode 100644 mypy/stdlib/multiprocessing/__init__.pyi create mode 100644 mypy/stdlib/multiprocessing/connection.pyi create mode 100644 mypy/stdlib/multiprocessing/context.pyi create mode 100644 mypy/stdlib/multiprocessing/dummy/__init__.pyi create mode 100644 mypy/stdlib/multiprocessing/dummy/connection.pyi create mode 100644 mypy/stdlib/multiprocessing/managers.pyi create mode 100644 mypy/stdlib/multiprocessing/pool.pyi create mode 100644 mypy/stdlib/multiprocessing/process.pyi create mode 100644 mypy/stdlib/multiprocessing/queues.pyi create mode 100644 mypy/stdlib/multiprocessing/shared_memory.pyi create mode 100644 mypy/stdlib/multiprocessing/spawn.pyi create mode 100644 mypy/stdlib/multiprocessing/synchronize.pyi create mode 100644 mypy/stdlib/netrc.pyi create mode 100644 mypy/stdlib/nis.pyi create mode 100644 mypy/stdlib/nntplib.pyi create mode 100644 mypy/stdlib/ntpath.pyi create mode 100644 mypy/stdlib/nturl2path.pyi create mode 100644 mypy/stdlib/numbers.pyi create mode 100644 mypy/stdlib/opcode.pyi create mode 100644 mypy/stdlib/operator.pyi create mode 100644 mypy/stdlib/optparse.pyi create mode 100644 mypy/stdlib/os/__init__.pyi create mode 100644 mypy/stdlib/os/path.pyi create mode 100644 mypy/stdlib/parser.pyi create mode 100644 mypy/stdlib/pathlib.pyi create mode 100644 mypy/stdlib/pdb.pyi create mode 100644 mypy/stdlib/pickle.pyi create mode 100644 mypy/stdlib/pickletools.pyi create mode 100644 mypy/stdlib/pipes.pyi create mode 100644 mypy/stdlib/pkgutil.pyi create mode 100644 mypy/stdlib/platform.pyi create mode 100644 mypy/stdlib/plistlib.pyi create mode 100644 mypy/stdlib/poplib.pyi create mode 100644 mypy/stdlib/posix.pyi create mode 100644 mypy/stdlib/posixpath.pyi create mode 100644 mypy/stdlib/pprint.pyi create mode 100644 mypy/stdlib/profile.pyi create mode 100644 mypy/stdlib/pstats.pyi create mode 100644 mypy/stdlib/pty.pyi create mode 100644 mypy/stdlib/pwd.pyi create mode 100644 mypy/stdlib/py_compile.pyi create mode 100644 mypy/stdlib/pyclbr.pyi create mode 100644 mypy/stdlib/pydoc.pyi create mode 100644 mypy/stdlib/pyexpat/__init__.pyi create mode 100644 mypy/stdlib/pyexpat/errors.pyi create mode 100644 mypy/stdlib/pyexpat/model.pyi create mode 100644 mypy/stdlib/python2/BaseHTTPServer.pyi create mode 100644 mypy/stdlib/python2/CGIHTTPServer.pyi create mode 100644 mypy/stdlib/python2/ConfigParser.pyi create mode 100644 mypy/stdlib/python2/Cookie.pyi create mode 100644 mypy/stdlib/python2/HTMLParser.pyi create mode 100644 mypy/stdlib/python2/Queue.pyi create mode 100644 mypy/stdlib/python2/SimpleHTTPServer.pyi create mode 100644 mypy/stdlib/python2/SocketServer.pyi create mode 100644 mypy/stdlib/python2/StringIO.pyi create mode 100644 mypy/stdlib/python2/UserDict.pyi create mode 100644 mypy/stdlib/python2/UserList.pyi create mode 100644 mypy/stdlib/python2/UserString.pyi create mode 100644 mypy/stdlib/python2/__builtin__.pyi create mode 100644 mypy/stdlib/python2/_ast.pyi create mode 100644 mypy/stdlib/python2/_collections.pyi create mode 100644 mypy/stdlib/python2/_functools.pyi create mode 100644 mypy/stdlib/python2/_hotshot.pyi create mode 100644 mypy/stdlib/python2/_io.pyi create mode 100644 mypy/stdlib/python2/_json.pyi create mode 100644 mypy/stdlib/python2/_md5.pyi create mode 100644 mypy/stdlib/python2/_sha.pyi create mode 100644 mypy/stdlib/python2/_sha256.pyi create mode 100644 mypy/stdlib/python2/_sha512.pyi create mode 100644 mypy/stdlib/python2/_socket.pyi create mode 100644 mypy/stdlib/python2/_sre.pyi create mode 100644 mypy/stdlib/python2/_struct.pyi create mode 100644 mypy/stdlib/python2/_symtable.pyi create mode 100644 mypy/stdlib/python2/_threading_local.pyi create mode 100644 mypy/stdlib/python2/_winreg.pyi create mode 100644 mypy/stdlib/python2/abc.pyi create mode 100644 mypy/stdlib/python2/ast.pyi create mode 100644 mypy/stdlib/python2/atexit.pyi create mode 100644 mypy/stdlib/python2/cPickle.pyi create mode 100644 mypy/stdlib/python2/cStringIO.pyi create mode 100644 mypy/stdlib/python2/collections.pyi create mode 100644 mypy/stdlib/python2/commands.pyi create mode 100644 mypy/stdlib/python2/compileall.pyi create mode 100644 mypy/stdlib/python2/cookielib.pyi create mode 100644 mypy/stdlib/python2/copy_reg.pyi create mode 100644 mypy/stdlib/python2/dircache.pyi create mode 100644 mypy/stdlib/python2/distutils/__init__.pyi create mode 100644 mypy/stdlib/python2/distutils/emxccompiler.pyi create mode 100644 mypy/stdlib/python2/dummy_thread.pyi create mode 100644 mypy/stdlib/python2/email/MIMEText.pyi create mode 100644 mypy/stdlib/python2/email/__init__.pyi create mode 100644 mypy/stdlib/python2/email/_parseaddr.pyi create mode 100644 mypy/stdlib/python2/email/base64mime.pyi create mode 100644 mypy/stdlib/python2/email/charset.pyi create mode 100644 mypy/stdlib/python2/email/encoders.pyi create mode 100644 mypy/stdlib/python2/email/feedparser.pyi create mode 100644 mypy/stdlib/python2/email/generator.pyi create mode 100644 mypy/stdlib/python2/email/header.pyi create mode 100644 mypy/stdlib/python2/email/iterators.pyi create mode 100644 mypy/stdlib/python2/email/message.pyi create mode 100644 mypy/stdlib/python2/email/mime/__init__.pyi create mode 100644 mypy/stdlib/python2/email/mime/application.pyi create mode 100644 mypy/stdlib/python2/email/mime/audio.pyi create mode 100644 mypy/stdlib/python2/email/mime/base.pyi create mode 100644 mypy/stdlib/python2/email/mime/image.pyi create mode 100644 mypy/stdlib/python2/email/mime/message.pyi create mode 100644 mypy/stdlib/python2/email/mime/multipart.pyi create mode 100644 mypy/stdlib/python2/email/mime/nonmultipart.pyi create mode 100644 mypy/stdlib/python2/email/mime/text.pyi create mode 100644 mypy/stdlib/python2/email/parser.pyi create mode 100644 mypy/stdlib/python2/email/quoprimime.pyi create mode 100644 mypy/stdlib/python2/email/utils.pyi create mode 100644 mypy/stdlib/python2/encodings/__init__.pyi create mode 100644 mypy/stdlib/python2/encodings/utf_8.pyi create mode 100644 mypy/stdlib/python2/exceptions.pyi create mode 100644 mypy/stdlib/python2/fcntl.pyi create mode 100644 mypy/stdlib/python2/fnmatch.pyi create mode 100644 mypy/stdlib/python2/functools.pyi create mode 100644 mypy/stdlib/python2/future_builtins.pyi create mode 100644 mypy/stdlib/python2/gc.pyi create mode 100644 mypy/stdlib/python2/getopt.pyi create mode 100644 mypy/stdlib/python2/getpass.pyi create mode 100644 mypy/stdlib/python2/gettext.pyi create mode 100644 mypy/stdlib/python2/glob.pyi create mode 100644 mypy/stdlib/python2/gzip.pyi create mode 100644 mypy/stdlib/python2/hashlib.pyi create mode 100644 mypy/stdlib/python2/heapq.pyi create mode 100644 mypy/stdlib/python2/htmlentitydefs.pyi create mode 100644 mypy/stdlib/python2/httplib.pyi create mode 100644 mypy/stdlib/python2/imp.pyi create mode 100644 mypy/stdlib/python2/importlib.pyi create mode 100644 mypy/stdlib/python2/inspect.pyi create mode 100644 mypy/stdlib/python2/io.pyi create mode 100644 mypy/stdlib/python2/itertools.pyi create mode 100644 mypy/stdlib/python2/json.pyi create mode 100644 mypy/stdlib/python2/markupbase.pyi create mode 100644 mypy/stdlib/python2/md5.pyi create mode 100644 mypy/stdlib/python2/mimetools.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/__init__.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/dummy/connection.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/pool.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/process.pyi create mode 100644 mypy/stdlib/python2/multiprocessing/util.pyi create mode 100644 mypy/stdlib/python2/mutex.pyi create mode 100644 mypy/stdlib/python2/nturl2path.pyi create mode 100644 mypy/stdlib/python2/os/__init__.pyi create mode 100644 mypy/stdlib/python2/os/path.pyi create mode 100644 mypy/stdlib/python2/os2emxpath.pyi create mode 100644 mypy/stdlib/python2/pipes.pyi create mode 100644 mypy/stdlib/python2/platform.pyi create mode 100644 mypy/stdlib/python2/popen2.pyi create mode 100644 mypy/stdlib/python2/posix.pyi create mode 100644 mypy/stdlib/python2/random.pyi create mode 100644 mypy/stdlib/python2/re.pyi create mode 100644 mypy/stdlib/python2/repr.pyi create mode 100644 mypy/stdlib/python2/resource.pyi create mode 100644 mypy/stdlib/python2/rfc822.pyi create mode 100644 mypy/stdlib/python2/robotparser.pyi create mode 100644 mypy/stdlib/python2/runpy.pyi create mode 100644 mypy/stdlib/python2/sets.pyi create mode 100644 mypy/stdlib/python2/sha.pyi create mode 100644 mypy/stdlib/python2/shelve.pyi create mode 100644 mypy/stdlib/python2/shlex.pyi create mode 100644 mypy/stdlib/python2/signal.pyi create mode 100644 mypy/stdlib/python2/smtplib.pyi create mode 100644 mypy/stdlib/python2/spwd.pyi create mode 100644 mypy/stdlib/python2/sre_constants.pyi create mode 100644 mypy/stdlib/python2/sre_parse.pyi create mode 100644 mypy/stdlib/python2/stat.pyi create mode 100644 mypy/stdlib/python2/string.pyi create mode 100644 mypy/stdlib/python2/stringold.pyi create mode 100644 mypy/stdlib/python2/strop.pyi create mode 100644 mypy/stdlib/python2/subprocess.pyi create mode 100644 mypy/stdlib/python2/symbol.pyi create mode 100644 mypy/stdlib/python2/sys.pyi create mode 100644 mypy/stdlib/python2/tempfile.pyi create mode 100644 mypy/stdlib/python2/textwrap.pyi create mode 100644 mypy/stdlib/python2/thread.pyi create mode 100644 mypy/stdlib/python2/toaiff.pyi create mode 100644 mypy/stdlib/python2/tokenize.pyi create mode 100644 mypy/stdlib/python2/types.pyi create mode 100644 mypy/stdlib/python2/typing.pyi create mode 100644 mypy/stdlib/python2/unittest.pyi create mode 100644 mypy/stdlib/python2/urllib.pyi create mode 100644 mypy/stdlib/python2/urllib2.pyi create mode 100644 mypy/stdlib/python2/urlparse.pyi create mode 100644 mypy/stdlib/python2/user.pyi create mode 100644 mypy/stdlib/python2/whichdb.pyi create mode 100644 mypy/stdlib/python2/xmlrpclib.pyi create mode 100644 mypy/stdlib/queue.pyi create mode 100644 mypy/stdlib/quopri.pyi create mode 100644 mypy/stdlib/random.pyi create mode 100644 mypy/stdlib/re.pyi create mode 100644 mypy/stdlib/readline.pyi create mode 100644 mypy/stdlib/reprlib.pyi create mode 100644 mypy/stdlib/resource.pyi create mode 100644 mypy/stdlib/rlcompleter.pyi create mode 100644 mypy/stdlib/runpy.pyi create mode 100644 mypy/stdlib/sched.pyi create mode 100644 mypy/stdlib/secrets.pyi create mode 100644 mypy/stdlib/select.pyi create mode 100644 mypy/stdlib/selectors.pyi create mode 100644 mypy/stdlib/shelve.pyi create mode 100644 mypy/stdlib/shlex.pyi create mode 100644 mypy/stdlib/shutil.pyi create mode 100644 mypy/stdlib/signal.pyi create mode 100644 mypy/stdlib/site.pyi create mode 100644 mypy/stdlib/smtpd.pyi create mode 100644 mypy/stdlib/smtplib.pyi create mode 100644 mypy/stdlib/sndhdr.pyi create mode 100644 mypy/stdlib/socket.pyi create mode 100644 mypy/stdlib/socketserver.pyi create mode 100644 mypy/stdlib/spwd.pyi create mode 100644 mypy/stdlib/sqlite3/__init__.pyi create mode 100644 mypy/stdlib/sqlite3/dbapi2.pyi create mode 100644 mypy/stdlib/sre_compile.pyi create mode 100644 mypy/stdlib/sre_constants.pyi create mode 100644 mypy/stdlib/sre_parse.pyi create mode 100644 mypy/stdlib/ssl.pyi create mode 100644 mypy/stdlib/stat.pyi create mode 100644 mypy/stdlib/statistics.pyi create mode 100644 mypy/stdlib/string.pyi create mode 100644 mypy/stdlib/stringprep.pyi create mode 100644 mypy/stdlib/struct.pyi create mode 100644 mypy/stdlib/subprocess.pyi create mode 100644 mypy/stdlib/sunau.pyi create mode 100644 mypy/stdlib/symbol.pyi create mode 100644 mypy/stdlib/symtable.pyi create mode 100644 mypy/stdlib/sys.pyi create mode 100644 mypy/stdlib/sysconfig.pyi create mode 100644 mypy/stdlib/syslog.pyi create mode 100644 mypy/stdlib/tabnanny.pyi create mode 100644 mypy/stdlib/tarfile.pyi create mode 100644 mypy/stdlib/telnetlib.pyi create mode 100644 mypy/stdlib/tempfile.pyi create mode 100644 mypy/stdlib/termios.pyi create mode 100644 mypy/stdlib/textwrap.pyi create mode 100644 mypy/stdlib/this.pyi create mode 100644 mypy/stdlib/threading.pyi create mode 100644 mypy/stdlib/time.pyi create mode 100644 mypy/stdlib/timeit.pyi create mode 100644 mypy/stdlib/tkinter/__init__.pyi create mode 100644 mypy/stdlib/tkinter/commondialog.pyi create mode 100644 mypy/stdlib/tkinter/constants.pyi create mode 100644 mypy/stdlib/tkinter/dialog.pyi create mode 100644 mypy/stdlib/tkinter/filedialog.pyi create mode 100644 mypy/stdlib/tkinter/messagebox.pyi create mode 100644 mypy/stdlib/tkinter/ttk.pyi create mode 100644 mypy/stdlib/token.pyi create mode 100644 mypy/stdlib/tokenize.pyi create mode 100644 mypy/stdlib/trace.pyi create mode 100644 mypy/stdlib/traceback.pyi create mode 100644 mypy/stdlib/tracemalloc.pyi create mode 100644 mypy/stdlib/tty.pyi create mode 100644 mypy/stdlib/turtle.pyi create mode 100644 mypy/stdlib/types.pyi create mode 100644 mypy/stdlib/typing.pyi create mode 100644 mypy/stdlib/unicodedata.pyi create mode 100644 mypy/stdlib/unittest/__init__.pyi create mode 100644 mypy/stdlib/unittest/async_case.pyi create mode 100644 mypy/stdlib/unittest/case.pyi create mode 100644 mypy/stdlib/unittest/loader.pyi create mode 100644 mypy/stdlib/unittest/main.pyi create mode 100644 mypy/stdlib/unittest/mock.pyi create mode 100644 mypy/stdlib/unittest/result.pyi create mode 100644 mypy/stdlib/unittest/runner.pyi create mode 100644 mypy/stdlib/unittest/signals.pyi create mode 100644 mypy/stdlib/unittest/suite.pyi create mode 100644 mypy/stdlib/unittest/util.pyi create mode 100644 mypy/stdlib/urllib/__init__.pyi create mode 100644 mypy/stdlib/urllib/error.pyi create mode 100644 mypy/stdlib/urllib/parse.pyi create mode 100644 mypy/stdlib/urllib/request.pyi create mode 100644 mypy/stdlib/urllib/response.pyi create mode 100644 mypy/stdlib/urllib/robotparser.pyi create mode 100644 mypy/stdlib/uu.pyi create mode 100644 mypy/stdlib/uuid.pyi create mode 100644 mypy/stdlib/venv/__init__.pyi create mode 100644 mypy/stdlib/warnings.pyi create mode 100644 mypy/stdlib/wave.pyi create mode 100644 mypy/stdlib/weakref.pyi create mode 100644 mypy/stdlib/webbrowser.pyi create mode 100644 mypy/stdlib/winreg.pyi create mode 100644 mypy/stdlib/winsound.pyi create mode 100644 mypy/stdlib/wsgiref/__init__.pyi create mode 100644 mypy/stdlib/wsgiref/handlers.pyi create mode 100644 mypy/stdlib/wsgiref/headers.pyi create mode 100644 mypy/stdlib/wsgiref/simple_server.pyi create mode 100644 mypy/stdlib/wsgiref/types.pyi create mode 100644 mypy/stdlib/wsgiref/util.pyi create mode 100644 mypy/stdlib/wsgiref/validate.pyi create mode 100644 mypy/stdlib/xdrlib.pyi create mode 100644 mypy/stdlib/xml/__init__.pyi create mode 100644 mypy/stdlib/xml/dom/NodeFilter.pyi create mode 100644 mypy/stdlib/xml/dom/__init__.pyi create mode 100644 mypy/stdlib/xml/dom/minidom.pyi create mode 100644 mypy/stdlib/xml/dom/pulldom.pyi create mode 100644 mypy/stdlib/xml/etree/ElementInclude.pyi create mode 100644 mypy/stdlib/xml/etree/ElementPath.pyi create mode 100644 mypy/stdlib/xml/etree/ElementTree.pyi create mode 100644 mypy/stdlib/xml/etree/__init__.pyi create mode 100644 mypy/stdlib/xml/etree/cElementTree.pyi create mode 100644 mypy/stdlib/xml/parsers/__init__.pyi create mode 100644 mypy/stdlib/xml/parsers/expat/__init__.pyi create mode 100644 mypy/stdlib/xml/parsers/expat/errors.pyi create mode 100644 mypy/stdlib/xml/parsers/expat/model.pyi create mode 100644 mypy/stdlib/xml/sax/__init__.pyi create mode 100644 mypy/stdlib/xml/sax/handler.pyi create mode 100644 mypy/stdlib/xml/sax/saxutils.pyi create mode 100644 mypy/stdlib/xml/sax/xmlreader.pyi create mode 100644 mypy/stdlib/xmlrpc/__init__.pyi create mode 100644 mypy/stdlib/xmlrpc/client.pyi create mode 100644 mypy/stdlib/xmlrpc/server.pyi create mode 100644 mypy/stdlib/zipapp.pyi create mode 100644 mypy/stdlib/zipfile.pyi create mode 100644 mypy/stdlib/zipimport.pyi create mode 100644 mypy/stdlib/zlib.pyi create mode 100644 mypy/stdlib/zoneinfo/__init__.pyi diff --git a/mypy/stdlib/VERSIONS b/mypy/stdlib/VERSIONS new file mode 100644 index 000000000000..dc749563a526 --- /dev/null +++ b/mypy/stdlib/VERSIONS @@ -0,0 +1,251 @@ +__future__: 2.7 +_ast: 3.5 +_bisect: 2.7 +_bootlocale: 3.5 +_codecs: 2.7 +_compat_pickle: 3.5 +_compression: 3.5 +_csv: 2.7 +_curses: 2.7 +_decimal: 3.5 +_dummy_thread: 3.5 +_dummy_threading: 2.7 +_heapq: 2.7 +_imp: 3.5 +_importlib_modulespec: 3.5 +_json: 3.5 +_markupbase: 3.5 +_msi: 2.7 +_operator: 3.5 +_osx_support: 3.5 +_posixsubprocess: 3.5 +_py_abc: 3.7 +_pydecimal: 3.5 +_random: 2.7 +_sitebuiltins: 3.5 +_stat: 3.5 +_thread: 3.5 +_threading_local: 3.5 +_tracemalloc: 3.5 +_typeshed: 2.7 +_warnings: 2.7 +_weakref: 2.7 +_weakrefset: 2.7 +_winapi: 3.5 +abc: 3.5 +aifc: 2.7 +antigravity: 2.7 +argparse: 2.7 +array: 2.7 +ast: 3.5 +asynchat: 2.7 +asyncio: 3.5 +asyncore: 2.7 +atexit: 3.5 +audioop: 2.7 +base64: 2.7 +bdb: 2.7 +binascii: 2.7 +binhex: 2.7 +bisect: 2.7 +builtins: 2.7 +bz2: 2.7 +cProfile: 2.7 +calendar: 2.7 +cgi: 2.7 +cgitb: 2.7 +chunk: 2.7 +cmath: 2.7 +cmd: 2.7 +code: 2.7 +codecs: 2.7 +codeop: 2.7 +collections: 3.5 +colorsys: 2.7 +compileall: 3.5 +concurrent: 3.5 +configparser: 3.5 +contextlib: 2.7 +contextvars: 3.7 +copy: 2.7 +copyreg: 3.5 +crypt: 2.7 +csv: 2.7 +ctypes: 2.7 +curses: 2.7 +dataclasses: 3.7 +datetime: 2.7 +dbm: 3.5 +decimal: 2.7 +difflib: 2.7 +dis: 2.7 +distutils: 2.7 +doctest: 2.7 +dummy_threading: 2.7 +email: 3.5 +encodings: 3.5 +ensurepip: 2.7 +enum: 3.5 +errno: 2.7 +faulthandler: 3.5 +fcntl: 3.5 +filecmp: 2.7 +fileinput: 2.7 +fnmatch: 3.5 +formatter: 2.7 +fractions: 2.7 +ftplib: 2.7 +functools: 3.5 +gc: 3.5 +genericpath: 2.7 +getopt: 3.5 +getpass: 3.5 +gettext: 3.5 +glob: 3.5 +grp: 2.7 +gzip: 3.5 +hashlib: 3.5 +heapq: 3.5 +hmac: 2.7 +html: 3.5 +http: 3.5 +imaplib: 2.7 +imghdr: 2.7 +imp: 3.5 +importlib: 3.5 +inspect: 3.5 +io: 3.5 +ipaddress: 3.5 +itertools: 3.5 +json: 3.5 +keyword: 2.7 +lib2to3: 2.7 +linecache: 2.7 +locale: 2.7 +logging: 2.7 +lzma: 3.5 +macpath: 2.7 +macurl2path: 3.5 +mailbox: 2.7 +mailcap: 2.7 +marshal: 2.7 +math: 2.7 +mimetypes: 2.7 +mmap: 2.7 +modulefinder: 2.7 +msilib: 2.7 +msvcrt: 2.7 +multiprocessing: 3.5 +netrc: 2.7 +nis: 2.7 +nntplib: 3.5 +ntpath: 2.7 +nturl2path: 3.5 +numbers: 2.7 +opcode: 2.7 +operator: 2.7 +optparse: 2.7 +os: 3.5 +parser: 2.7 +pathlib: 3.5 +pdb: 2.7 +pickle: 2.7 +pickletools: 2.7 +pipes: 3.5 +pkgutil: 2.7 +platform: 3.5 +plistlib: 2.7 +poplib: 2.7 +posix: 3.5 +posixpath: 2.7 +pprint: 2.7 +profile: 2.7 +pstats: 2.7 +pty: 2.7 +pwd: 2.7 +py_compile: 2.7 +pyclbr: 2.7 +pydoc: 2.7 +pyexpat: 2.7 +queue: 3.5 +quopri: 2.7 +random: 3.5 +re: 3.5 +readline: 2.7 +reprlib: 3.5 +resource: 3.5 +rlcompleter: 2.7 +runpy: 3.5 +sched: 2.7 +secrets: 3.6 +select: 2.7 +selectors: 3.5 +shelve: 3.5 +shlex: 3.5 +shutil: 2.7 +signal: 3.5 +site: 2.7 +smtpd: 2.7 +smtplib: 3.5 +sndhdr: 2.7 +socket: 2.7 +socketserver: 3.5 +spwd: 3.5 +sqlite3: 2.7 +sre_compile: 2.7 +sre_constants: 3.5 +sre_parse: 3.5 +ssl: 2.7 +stat: 3.5 +statistics: 3.5 +string: 3.5 +stringprep: 2.7 +struct: 2.7 +subprocess: 3.5 +sunau: 2.7 +symbol: 3.5 +symtable: 2.7 +sys: 3.5 +sysconfig: 2.7 +syslog: 2.7 +tabnanny: 2.7 +tarfile: 2.7 +telnetlib: 2.7 +tempfile: 3.5 +termios: 2.7 +textwrap: 3.5 +this: 2.7 +threading: 2.7 +time: 2.7 +timeit: 2.7 +tkinter: 3.5 +token: 2.7 +tokenize: 3.5 +trace: 2.7 +traceback: 2.7 +tracemalloc: 3.5 +tty: 2.7 +turtle: 2.7 +types: 3.5 +typing: 3.5 +unicodedata: 2.7 +unittest: 3.5 +urllib: 3.5 +uu: 2.7 +uuid: 2.7 +venv: 3.5 +warnings: 2.7 +wave: 2.7 +weakref: 2.7 +webbrowser: 2.7 +winreg: 3.5 +winsound: 2.7 +wsgiref: 2.7 +xdrlib: 2.7 +xml: 2.7 +xmlrpc: 3.5 +zipapp: 3.5 +zipfile: 2.7 +zipimport: 2.7 +zlib: 2.7 +zoneinfo: 3.9 diff --git a/mypy/stdlib/__future__.pyi b/mypy/stdlib/__future__.pyi new file mode 100644 index 000000000000..0483e736f06b --- /dev/null +++ b/mypy/stdlib/__future__.pyi @@ -0,0 +1,25 @@ +import sys +from typing import List + +class _Feature: + 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 +if sys.version_info >= (3, 0): + barry_as_FLUFL: _Feature + +if sys.version_info >= (3, 5): + generator_stop: _Feature + +if sys.version_info >= (3, 7): + annotations: _Feature + +all_feature_names: List[str] # undocumented diff --git a/mypy/stdlib/_ast.pyi b/mypy/stdlib/_ast.pyi new file mode 100644 index 000000000000..888b3876c8b4 --- /dev/null +++ b/mypy/stdlib/_ast.pyi @@ -0,0 +1,418 @@ +import sys +import typing +from typing import Any, Optional, ClassVar + +PyCF_ONLY_AST: int +if sys.version_info >= (3, 8): + PyCF_TYPE_COMMENTS: int + PyCF_ALLOW_TOP_LEVEL_AWAIT: int + +_identifier = str + +class AST: + _attributes: ClassVar[typing.Tuple[str, ...]] + _fields: ClassVar[typing.Tuple[str, ...]] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + # TODO: Not all nodes have all of the following attributes + lineno: int + col_offset: int + if sys.version_info >= (3, 8): + end_lineno: Optional[int] + end_col_offset: Optional[int] + type_comment: Optional[str] + +class mod(AST): + ... + +if sys.version_info >= (3, 8): + class type_ignore(AST): ... + + class TypeIgnore(type_ignore): ... + + class FunctionType(mod): + argtypes: typing.List[expr] + returns: expr + +class Module(mod): + body: typing.List[stmt] + if sys.version_info >= (3, 7): + docstring: Optional[str] + if sys.version_info >= (3, 8): + type_ignores: typing.List[TypeIgnore] + +class Interactive(mod): + body: typing.List[stmt] + +class Expression(mod): + body: expr + + +class stmt(AST): ... + +class FunctionDef(stmt): + name: _identifier + args: arguments + body: typing.List[stmt] + decorator_list: typing.List[expr] + returns: Optional[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class AsyncFunctionDef(stmt): + name: _identifier + args: arguments + body: typing.List[stmt] + decorator_list: typing.List[expr] + returns: Optional[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class ClassDef(stmt): + name: _identifier + bases: typing.List[expr] + keywords: typing.List[keyword] + body: typing.List[stmt] + decorator_list: typing.List[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class Return(stmt): + value: Optional[expr] + +class Delete(stmt): + targets: typing.List[expr] + +class Assign(stmt): + targets: typing.List[expr] + value: expr + +class AugAssign(stmt): + target: expr + op: operator + value: expr + +if sys.version_info >= (3, 6): + class AnnAssign(stmt): + target: expr + annotation: expr + value: Optional[expr] + simple: int + +class For(stmt): + target: expr + iter: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class AsyncFor(stmt): + target: expr + iter: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class While(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class If(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class With(stmt): + items: typing.List[withitem] + body: typing.List[stmt] + +class AsyncWith(stmt): + items: typing.List[withitem] + body: typing.List[stmt] + +class Raise(stmt): + exc: Optional[expr] + cause: Optional[expr] + +class Try(stmt): + body: typing.List[stmt] + handlers: typing.List[ExceptHandler] + orelse: typing.List[stmt] + finalbody: typing.List[stmt] + +class Assert(stmt): + test: expr + msg: Optional[expr] + +class Import(stmt): + names: typing.List[alias] + +class ImportFrom(stmt): + module: Optional[_identifier] + names: typing.List[alias] + level: int + +class Global(stmt): + names: typing.List[_identifier] + +class Nonlocal(stmt): + names: typing.List[_identifier] + +class Expr(stmt): + value: expr + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + +class expr(AST): ... + +class BoolOp(expr): + op: boolop + values: typing.List[expr] + +class BinOp(expr): + left: expr + op: operator + right: expr + +class UnaryOp(expr): + op: unaryop + operand: expr + +class Lambda(expr): + args: arguments + body: expr + +class IfExp(expr): + test: expr + body: expr + orelse: expr + +class Dict(expr): + keys: typing.List[Optional[expr]] + values: typing.List[expr] + +class Set(expr): + elts: typing.List[expr] + +class ListComp(expr): + elt: expr + generators: typing.List[comprehension] + +class SetComp(expr): + elt: expr + generators: typing.List[comprehension] + +class DictComp(expr): + key: expr + value: expr + generators: typing.List[comprehension] + +class GeneratorExp(expr): + elt: expr + generators: typing.List[comprehension] + +class Await(expr): + value: expr + +class Yield(expr): + value: Optional[expr] + +class YieldFrom(expr): + value: expr + +class Compare(expr): + left: expr + ops: typing.List[cmpop] + comparators: typing.List[expr] + +class Call(expr): + func: expr + args: typing.List[expr] + keywords: typing.List[keyword] + +if sys.version_info >= (3, 6): + class FormattedValue(expr): + value: expr + conversion: Optional[int] + format_spec: Optional[expr] + + class JoinedStr(expr): + values: typing.List[expr] + +if sys.version_info < (3, 8): + class Num(expr): # Deprecated in 3.8; use Constant + n: complex + + class Str(expr): # Deprecated in 3.8; use Constant + s: str + + class Bytes(expr): # Deprecated in 3.8; use Constant + s: bytes + + class NameConstant(expr): # Deprecated in 3.8; use Constant + value: Any + + class Ellipsis(expr): ... # Deprecated in 3.8; use Constant + +if sys.version_info >= (3, 6): + class Constant(expr): + value: Any # None, str, bytes, bool, int, float, complex, Ellipsis + kind: Optional[str] + # Aliases for value, for backwards compatibility + s: Any + n: complex + +if sys.version_info >= (3, 8): + class NamedExpr(expr): + target: expr + value: expr + +class Attribute(expr): + value: expr + attr: _identifier + ctx: expr_context + +if sys.version_info >= (3, 9): + _SliceT = expr +else: + class slice(AST): + ... + _SliceT = slice + +class Slice(_SliceT): + lower: Optional[expr] + upper: Optional[expr] + step: Optional[expr] + +if sys.version_info < (3, 9): + class ExtSlice(slice): + dims: typing.List[slice] + + class Index(slice): + value: expr + +class Subscript(expr): + value: expr + slice: _SliceT + ctx: expr_context + +class Starred(expr): + value: expr + ctx: expr_context + +class Name(expr): + id: _identifier + ctx: expr_context + +class List(expr): + elts: typing.List[expr] + ctx: expr_context + +class Tuple(expr): + elts: typing.List[expr] + ctx: expr_context + + +class expr_context(AST): + ... + +if sys.version_info < (3, 9): + class AugLoad(expr_context): ... + class AugStore(expr_context): ... + class Param(expr_context): ... + class Suite(mod): + body: typing.List[stmt] + +class Del(expr_context): ... +class Load(expr_context): ... +class Store(expr_context): ... + + +class boolop(AST): + ... + +class And(boolop): ... +class Or(boolop): ... + +class operator(AST): + ... + +class Add(operator): ... +class BitAnd(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class Div(operator): ... +class FloorDiv(operator): ... +class LShift(operator): ... +class Mod(operator): ... +class Mult(operator): ... +class MatMult(operator): ... +class Pow(operator): ... +class RShift(operator): ... +class Sub(operator): ... + +class unaryop(AST): + ... + +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... + +class cmpop(AST): + ... + +class Eq(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class In(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class NotEq(cmpop): ... +class NotIn(cmpop): ... + + +class comprehension(AST): + target: expr + iter: expr + ifs: typing.List[expr] + if sys.version_info >= (3, 6): + is_async: int + + +class excepthandler(AST): + ... + +class ExceptHandler(excepthandler): + type: Optional[expr] + name: Optional[_identifier] + body: typing.List[stmt] + + +class arguments(AST): + if sys.version_info >= (3, 8): + posonlyargs: typing.List[arg] + args: typing.List[arg] + vararg: Optional[arg] + kwonlyargs: typing.List[arg] + kw_defaults: typing.List[expr] + kwarg: Optional[arg] + defaults: typing.List[expr] + +class arg(AST): + arg: _identifier + annotation: Optional[expr] + +class keyword(AST): + arg: Optional[_identifier] + value: expr + +class alias(AST): + name: _identifier + asname: Optional[_identifier] + +class withitem(AST): + context_expr: expr + optional_vars: Optional[expr] diff --git a/mypy/stdlib/_bisect.pyi b/mypy/stdlib/_bisect.pyi new file mode 100644 index 000000000000..43ee44bba586 --- /dev/null +++ b/mypy/stdlib/_bisect.pyi @@ -0,0 +1,9 @@ +"""Stub file for the '_bisect' module.""" + +from typing import Optional, Sequence, MutableSequence, 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/stdlib/_bootlocale.pyi b/mypy/stdlib/_bootlocale.pyi new file mode 100644 index 000000000000..a29c066eba2c --- /dev/null +++ b/mypy/stdlib/_bootlocale.pyi @@ -0,0 +1,2 @@ + +def getpreferredencoding(do_setlocale: bool = ...) -> str: ... diff --git a/mypy/stdlib/_codecs.pyi b/mypy/stdlib/_codecs.pyi new file mode 100644 index 000000000000..d933d0917439 --- /dev/null +++ b/mypy/stdlib/_codecs.pyi @@ -0,0 +1,77 @@ +"""Stub file for the '_codecs' module.""" + +import sys +from typing import Any, Callable, Tuple, Optional, Dict, Text, Union + +import codecs + +# For convenience: +_Handler = Callable[[Exception], Tuple[Text, int]] +_String = Union[bytes, str] +_Errors = Union[str, Text, None] +if sys.version_info < (3, 0): + _Decodable = Union[bytes, Text] + _Encodable = Union[bytes, Text] +else: + _Decodable = bytes + _Encodable = str + +# 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]: ... +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]: ... +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 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]: ... + 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]: ... diff --git a/mypy/stdlib/_compat_pickle.pyi b/mypy/stdlib/_compat_pickle.pyi new file mode 100644 index 000000000000..688e0ad04ade --- /dev/null +++ b/mypy/stdlib/_compat_pickle.pyi @@ -0,0 +1,14 @@ + +from typing import Dict, Tuple +import sys + +IMPORT_MAPPING: Dict[str, str] +NAME_MAPPING: Dict[Tuple[str, str], Tuple[str, str]] +PYTHON2_EXCEPTIONS: Tuple[str, ...] +MULTIPROCESSING_EXCEPTIONS: Tuple[str, ...] +REVERSE_IMPORT_MAPPING: Dict[str, str] +REVERSE_NAME_MAPPING: Dict[Tuple[str, str], Tuple[str, str]] +PYTHON3_OSERROR_EXCEPTIONS: Tuple[str, ...] + +if sys.version_info >= (3, 6): + PYTHON3_IMPORTERROR_EXCEPTIONS: Tuple[str, ...] diff --git a/mypy/stdlib/_compression.pyi b/mypy/stdlib/_compression.pyi new file mode 100644 index 000000000000..99d08212b8be --- /dev/null +++ b/mypy/stdlib/_compression.pyi @@ -0,0 +1,16 @@ +from typing import Any +import io + +BUFFER_SIZE: Any + +class BaseStream(io.BufferedIOBase): ... + +class DecompressReader(io.RawIOBase): + def readable(self): ... + def __init__(self, fp, decomp_factory, trailing_error=..., **decomp_args): ... + def close(self): ... + def seekable(self): ... + def readinto(self, b): ... + def read(self, size: int = ...) -> bytes: ... + def seek(self, offset, whence=...): ... + def tell(self): ... diff --git a/mypy/stdlib/_csv.pyi b/mypy/stdlib/_csv.pyi new file mode 100644 index 000000000000..4f722891b69f --- /dev/null +++ b/mypy/stdlib/_csv.pyi @@ -0,0 +1,52 @@ +import sys + +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 + if sys.version_info >= (3, 0): + def __next__(self) -> List[str]: ... + else: + 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: ... + + +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/stdlib/_curses.pyi b/mypy/stdlib/_curses.pyi new file mode 100644 index 000000000000..8c6d986cc459 --- /dev/null +++ b/mypy/stdlib/_curses.pyi @@ -0,0 +1,461 @@ +import sys +from typing import Any, BinaryIO, IO, NamedTuple, Optional, Tuple, Union, overload + +_chtype = Union[str, bytes, 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 +if sys.version_info >= (3, 7): + A_ITALIC: 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]: ... +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: ... +if sys.version_info >= (3, 3): + 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 use_default_colors() -> None: ... +def use_env(__flag: bool) -> None: ... + +class error(Exception): ... + +class _CursesWindow: + if sys.version_info >= (3, 3): + encoding: str + @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: ... + 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 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: ... + +if sys.version_info >= (3, 8): + class _ncurses_version(NamedTuple): + major: int + minor: int + patch: int + ncurses_version: _ncurses_version diff --git a/mypy/stdlib/_decimal.pyi b/mypy/stdlib/_decimal.pyi new file mode 100644 index 000000000000..e38f3cf07653 --- /dev/null +++ b/mypy/stdlib/_decimal.pyi @@ -0,0 +1,2 @@ + +from decimal import * diff --git a/mypy/stdlib/_dummy_thread.pyi b/mypy/stdlib/_dummy_thread.pyi new file mode 100644 index 000000000000..1260d42de958 --- /dev/null +++ b/mypy/stdlib/_dummy_thread.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +TIMEOUT_MAX: int +error = RuntimeError + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/mypy/stdlib/_dummy_threading.pyi b/mypy/stdlib/_dummy_threading.pyi new file mode 100644 index 000000000000..ae8997251322 --- /dev/null +++ b/mypy/stdlib/_dummy_threading.pyi @@ -0,0 +1,190 @@ + +from typing import ( + Any, Callable, Iterable, List, Mapping, Optional, Text, Tuple, Type, Union, + TypeVar, +) +from types import FrameType, TracebackType +import sys + +# 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: ... +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 enumerate() -> List[Thread]: ... + +if sys.version_info >= (3, 4): + def main_thread() -> Thread: ... + +if sys.version_info >= (3, 8): + from _thread import get_native_id as get_native_id + +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 + +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 + if sys.version_info >= (3,): + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + *, daemon: Optional[bool] = ...) -> None: ... + else: + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: 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: ... + if sys.version_info >= (3, 8): + @property + def native_id(self) -> Optional[int]: ... # only available on some platforms + def is_alive(self) -> bool: ... + if sys.version_info < (3, 9): + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> 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 notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + def notifyAll(self) -> None: ... + + +class Semaphore: + def __init__(self, value: int = ...) -> None: ... + def __enter__(self) -> bool: ... + 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: ... + if sys.version_info >= (3, 9): + def release(self, n: int = ...) -> None: ... + else: + def release(self) -> None: ... + +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: ... + +if sys.version_info >= (3, 8): + from _thread import _ExceptHookArgs as ExceptHookArgs, ExceptHookArgs as _ExceptHookArgs # don't ask + excepthook: Callable[[_ExceptHookArgs], Any] + +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 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): ... diff --git a/mypy/stdlib/_heapq.pyi b/mypy/stdlib/_heapq.pyi new file mode 100644 index 000000000000..24e7003978ec --- /dev/null +++ b/mypy/stdlib/_heapq.pyi @@ -0,0 +1,15 @@ +"""Stub file for the '_heapq' module.""" + +from typing import TypeVar, List, Iterable, Any, Callable, Optional +import sys + +_T = TypeVar("_T") + +def heapify(__heap: List[_T]) -> 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: ... +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/stdlib/_imp.pyi b/mypy/stdlib/_imp.pyi new file mode 100644 index 000000000000..9e4bc0bfa03f --- /dev/null +++ b/mypy/stdlib/_imp.pyi @@ -0,0 +1,20 @@ +# Stubs for _imp (Python 3.6) + +import types +from typing import Any, List + +from importlib.machinery import ModuleSpec +def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... +def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> None: ... + +def acquire_lock() -> None: ... +def exec_builtin(__mod: types.ModuleType) -> int: ... +def exec_dynamic(__mod: types.ModuleType) -> int: ... +def extension_suffixes() -> List[str]: ... +def get_frozen_object(__name: str) -> types.CodeType: ... +def init_frozen(__name: str) -> types.ModuleType: ... +def is_builtin(__name: str) -> int: ... +def is_frozen(__name: str) -> bool: ... +def is_frozen_package(__name: str) -> bool: ... +def lock_held() -> bool: ... +def release_lock() -> None: ... diff --git a/mypy/stdlib/_importlib_modulespec.pyi b/mypy/stdlib/_importlib_modulespec.pyi new file mode 100644 index 000000000000..026dab8d01a3 --- /dev/null +++ b/mypy/stdlib/_importlib_modulespec.pyi @@ -0,0 +1,44 @@ +# ModuleSpec, ModuleType, Loader are part of a dependency cycle. +# They are officially defined/exported in other places: +# +# - ModuleType in types +# - Loader in importlib.abc +# - ModuleSpec in importlib.machinery (3.4 and later only) +# +# _Loader is the PEP-451-defined interface for a loader type/object. + +from abc import ABCMeta +from typing import Any, Dict, List, Optional, Protocol + +class _Loader(Protocol): + def load_module(self, fullname: str) -> ModuleType: ... + +class ModuleSpec: + def __init__(self, name: str, loader: Optional[Loader], *, + origin: Optional[str] = ..., loader_state: Any = ..., + is_package: Optional[bool] = ...) -> None: ... + name: str + loader: Optional[_Loader] + origin: Optional[str] + submodule_search_locations: Optional[List[str]] + loader_state: Any + cached: Optional[str] + parent: Optional[str] + has_location: bool + +class ModuleType: + __name__: str + __file__: str + __dict__: Dict[str, Any] + __loader__: Optional[_Loader] + __package__: Optional[str] + __spec__: Optional[ModuleSpec] + def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... + +class Loader(metaclass=ABCMeta): + def load_module(self, fullname: str) -> ModuleType: ... + def module_repr(self, module: ModuleType) -> str: ... + def create_module(self, spec: ModuleSpec) -> Optional[ModuleType]: ... + # Not defined on the actual class for backwards-compatibility reasons, + # but expected in new code. + def exec_module(self, module: ModuleType) -> None: ... diff --git a/mypy/stdlib/_json.pyi b/mypy/stdlib/_json.pyi new file mode 100644 index 000000000000..9f7c80176595 --- /dev/null +++ b/mypy/stdlib/_json.pyi @@ -0,0 +1,31 @@ +"""Stub file for the '_json' module.""" + +from typing import Any, Tuple, Optional, Dict, Callable + +class make_encoder: + sort_keys: Any + skipkeys: Any + key_separator: Any + indent: Any + markers: Any + default: Any + encoder: Any + item_separator: Any + def __init__(self, markers: Optional[Dict[int, Any]], default: Callable[[Any], Any], encoder: Callable[[str], str], + indent: Optional[int], key_separator: str, item_separator: str, sort_keys: bool, skipkeys: bool, + allow_nan: bool) -> None: ... + def __call__(self, obj: object, _current_indent_level: int) -> Any: ... + +class make_scanner: + object_hook: Any + object_pairs_hook: Any + parse_int: Any + parse_constant: Any + parse_float: Any + strict: bool + # TODO: 'context' needs the attrs above (ducktype), but not __call__. + def __init__(self, context: make_scanner) -> None: ... + def __call__(self, string: str, index: int) -> Tuple[Any, int]: ... + +def encode_basestring_ascii(s: str) -> str: ... +def scanstring(string: str, end: int, strict: bool = ...) -> Tuple[str, int]: ... diff --git a/mypy/stdlib/_markupbase.pyi b/mypy/stdlib/_markupbase.pyi new file mode 100644 index 000000000000..09f69c7420b4 --- /dev/null +++ b/mypy/stdlib/_markupbase.pyi @@ -0,0 +1,9 @@ +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/stdlib/_msi.pyi b/mypy/stdlib/_msi.pyi new file mode 100644 index 000000000000..092edf9932bc --- /dev/null +++ b/mypy/stdlib/_msi.pyi @@ -0,0 +1,62 @@ + +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/stdlib/_operator.pyi b/mypy/stdlib/_operator.pyi new file mode 100644 index 000000000000..b37475472f50 --- /dev/null +++ b/mypy/stdlib/_operator.pyi @@ -0,0 +1,63 @@ +# Stubs for _operator (Python 3.5) + +from typing import AnyStr + +# In reality the import is the other way around, but this way we can keep the operator stub in 2and3 +from operator import ( + truth as truth, + contains as contains, + indexOf as indexOf, + countOf as countOf, + is_ as is_, + is_not as is_not, + index as index, + add as add, + sub as sub, + mul as mul, + floordiv as floordiv, + truediv as truediv, + mod as mod, + neg as neg, + pos as pos, + abs as abs, + inv as inv, + invert as invert, + length_hint as length_hint, + lshift as lshift, + rshift as rshift, + not_ as not_, + and_ as and_, + xor as xor, + or_ as or_, + iadd as iadd, + isub as isub, + imul as imul, + ifloordiv as ifloordiv, + itruediv as itruediv, + imod as imod, + ilshift as ilshift, + irshift as irshift, + iand as iand, + ixor as ixor, + ior as ior, + concat as concat, + iconcat as iconcat, + getitem as getitem, + setitem as setitem, + delitem as delitem, + pow as pow, + ipow as ipow, + eq as eq, + ne as ne, + lt as lt, + le as le, + gt as gt, + ge as ge, + itemgetter as itemgetter, + attrgetter as attrgetter, + methodcaller as methodcaller, + matmul as matmul, + imatmul as imatmul, +) + +def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/mypy/stdlib/_osx_support.pyi b/mypy/stdlib/_osx_support.pyi new file mode 100644 index 000000000000..6dc0e93e75ea --- /dev/null +++ b/mypy/stdlib/_osx_support.pyi @@ -0,0 +1,33 @@ + +from typing import Tuple, List, Optional, Dict, Sequence, Iterable, 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/stdlib/_posixsubprocess.pyi b/mypy/stdlib/_posixsubprocess.pyi new file mode 100644 index 000000000000..67b7d7cc5634 --- /dev/null +++ b/mypy/stdlib/_posixsubprocess.pyi @@ -0,0 +1,14 @@ +# Stubs for _posixsubprocess + +# NOTE: These are incomplete! + +from typing import Tuple, Sequence, Callable + +def cloexec_pipe() -> Tuple[int, int]: ... +def fork_exec(args: Sequence[str], + executable_list: Sequence[bytes], close_fds: bool, fds_to_keep: Sequence[int], + cwd: str, env_list: Sequence[bytes], + p2cread: int, p2cwrite: int, c2pred: int, c2pwrite: int, + errread: int, errwrite: int, errpipe_read: int, + errpipe_write: int, restore_signals: int, start_new_session: int, + preexec_fn: Callable[[], None]) -> int: ... diff --git a/mypy/stdlib/_py_abc.pyi b/mypy/stdlib/_py_abc.pyi new file mode 100644 index 000000000000..5d71b730b149 --- /dev/null +++ b/mypy/stdlib/_py_abc.pyi @@ -0,0 +1,11 @@ + +from typing import Type, TypeVar, Tuple, Any, Dict, NewType + +_T = TypeVar('_T') + +# TODO: Change the return into a NewType bound to int after pytype/#597 +def get_cache_token() -> object: ... + +class ABCMeta(type): + def __new__(mcls, __name: str, __bases: Tuple[Type[Any], ...], __namespace: Dict[str, Any]) -> ABCMeta: ... + def register(cls, subclass: Type[_T]) -> Type[_T]: ... diff --git a/mypy/stdlib/_pydecimal.pyi b/mypy/stdlib/_pydecimal.pyi new file mode 100644 index 000000000000..4f742239336c --- /dev/null +++ b/mypy/stdlib/_pydecimal.pyi @@ -0,0 +1,4 @@ + +# This is a slight lie, the implementations aren't exactly identical +# However, in all likelihood, the differences are inconsequential +from decimal import * diff --git a/mypy/stdlib/_random.pyi b/mypy/stdlib/_random.pyi new file mode 100644 index 000000000000..ec21c420e30b --- /dev/null +++ b/mypy/stdlib/_random.pyi @@ -0,0 +1,17 @@ +# Stubs for _random + +import sys +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: ... + if sys.version_info < (3,): + def jumpahead(self, i: int) -> None: ... diff --git a/mypy/stdlib/_sitebuiltins.pyi b/mypy/stdlib/_sitebuiltins.pyi new file mode 100644 index 000000000000..bf2713f8b737 --- /dev/null +++ b/mypy/stdlib/_sitebuiltins.pyi @@ -0,0 +1,18 @@ +from typing import Optional, NoReturn, ClassVar, Iterable +from typing_extensions import Literal + +class Quitter: + name: str + eof: str + + def __init__(self, name: str, eof: str) -> None: ... + def __call__(self, code: Optional[int] = ...) -> NoReturn: ... + +class _Printer: + MAXLINES: ClassVar[Literal[23]] + + def __init__(self, name: str, data: str, files: Iterable[str] = ..., dirs: Iterable[str] = ...) -> None: ... + def __call__(self) -> None: ... + +class _Helper: + def __call__(self, request: object) -> None: ... diff --git a/mypy/stdlib/_stat.pyi b/mypy/stdlib/_stat.pyi new file mode 100644 index 000000000000..ffd28cb8ad9c --- /dev/null +++ b/mypy/stdlib/_stat.pyi @@ -0,0 +1,69 @@ +"""Stub file for the '_stat' module.""" + +SF_APPEND: int +SF_ARCHIVED: int +SF_IMMUTABLE: int +SF_NOUNLINK: int +SF_SNAPSHOT: int +ST_ATIME: int +ST_CTIME: int +ST_DEV: int +ST_GID: int +ST_INO: int +ST_MODE: int +ST_MTIME: int +ST_NLINK: int +ST_SIZE: int +ST_UID: int +S_ENFMT: int +S_IEXEC: int +S_IFBLK: int +S_IFCHR: int +S_IFDIR: int +S_IFDOOR: int +S_IFIFO: int +S_IFLNK: int +S_IFPORT: int +S_IFREG: int +S_IFSOCK: int +S_IFWHT: int +S_IREAD: int +S_IRGRP: int +S_IROTH: int +S_IRUSR: int +S_IRWXG: int +S_IRWXO: int +S_IRWXU: int +S_ISGID: int +S_ISUID: int +S_ISVTX: int +S_IWGRP: int +S_IWOTH: int +S_IWRITE: int +S_IWUSR: int +S_IXGRP: int +S_IXOTH: int +S_IXUSR: int +UF_APPEND: int +UF_COMPRESSED: int +UF_HIDDEN: int +UF_IMMUTABLE: int +UF_NODUMP: int +UF_NOUNLINK: int +UF_OPAQUE: int + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +def S_ISBLK(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISDIR(mode: int) -> bool: ... +def S_ISDOOR(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISPORT(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... +def S_ISWHT(mode: int) -> bool: ... + +def filemode(mode: int) -> str: ... diff --git a/mypy/stdlib/_thread.pyi b/mypy/stdlib/_thread.pyi new file mode 100644 index 000000000000..56f343b5a838 --- /dev/null +++ b/mypy/stdlib/_thread.pyi @@ -0,0 +1,44 @@ +# Stubs for _thread + +import sys +from threading import Thread +from types import TracebackType +from typing import Any, Callable, Dict, NamedTuple, 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 + +if sys.version_info >= (3, 8): + def get_native_id() -> int: ... # only available on some platforms + + class ExceptHookArgs(NamedTuple): + exc_type: Type[BaseException] + exc_value: Optional[BaseException] + exc_traceback: Optional[TracebackType] + thread: Optional[Thread] + def _ExceptHookArgs(args) -> ExceptHookArgs: ... + _excepthook: Callable[[ExceptHookArgs], Any] diff --git a/mypy/stdlib/_threading_local.pyi b/mypy/stdlib/_threading_local.pyi new file mode 100644 index 000000000000..426496b11405 --- /dev/null +++ b/mypy/stdlib/_threading_local.pyi @@ -0,0 +1,17 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/_threading_local.py +from typing import Any, Dict, Tuple +from weakref import ReferenceType + +localdict = Dict[Any, Any] + +class _localimpl: + key: str + dicts: Dict[int, Tuple[ReferenceType[Any], localdict]] + def __init__(self) -> None: ... + def get_dict(self) -> localdict: ... + def create_dict(self) -> localdict: ... + +class local: + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... diff --git a/mypy/stdlib/_tracemalloc.pyi b/mypy/stdlib/_tracemalloc.pyi new file mode 100644 index 000000000000..3651c93198f7 --- /dev/null +++ b/mypy/stdlib/_tracemalloc.pyi @@ -0,0 +1,12 @@ +from typing import Optional, Sequence, Tuple +from tracemalloc import _TraceTupleT, _FrameTupleT + +def _get_object_traceback(__obj) -> Optional[Sequence[_FrameTupleT]]: ... +def _get_traces() -> Sequence[_TraceTupleT]: ... +def clear_traces() -> None: ... +def get_traceback_limit() -> int: ... +def get_traced_memory() -> Tuple[int, int]: ... +def get_tracemalloc_memory() -> int: ... +def is_tracing() -> bool: ... +def start(__nframe: int = ...) -> None: ... +def stop() -> None: ... diff --git a/mypy/stdlib/_typeshed/__init__.pyi b/mypy/stdlib/_typeshed/__init__.pyi new file mode 100644 index 000000000000..5b535d322b2c --- /dev/null +++ b/mypy/stdlib/_typeshed/__init__.pyi @@ -0,0 +1,78 @@ +# 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 +import sys +from typing import Protocol, Text, TypeVar, Union +from typing_extensions import Literal + +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) + +# 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] + +OpenTextMode = Literal[ + 'r', 'r+', '+r', 'rt', 'tr', 'rt+', 'r+t', '+rt', 'tr+', 't+r', '+tr', + 'w', 'w+', '+w', 'wt', 'tw', 'wt+', 'w+t', '+wt', 'tw+', 't+w', '+tw', + 'a', 'a+', '+a', 'at', 'ta', 'at+', 'a+t', '+at', 'ta+', 't+a', '+ta', + 'x', 'x+', '+x', 'xt', 'tx', 'xt+', 'x+t', '+xt', 'tx+', 't+x', '+tx', + 'U', 'rU', 'Ur', 'rtU', 'rUt', 'Urt', 'trU', 'tUr', 'Utr', +] +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 SupportsWrite(Protocol[_T_contra]): + def write(self, __s: _T_contra) -> int: ... + +if sys.version_info >= (3,): + ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap] + WriteableBuffer = Union[bytearray, memoryview, array.array, mmap.mmap] +else: + ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap, buffer] + WriteableBuffer = Union[bytearray, memoryview, array.array, mmap.mmap, buffer] diff --git a/mypy/stdlib/_typeshed/wsgi.pyi b/mypy/stdlib/_typeshed/wsgi.pyi new file mode 100644 index 000000000000..f79d54d3bb33 --- /dev/null +++ b/mypy/stdlib/_typeshed/wsgi.pyi @@ -0,0 +1,32 @@ +# 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 Callable, Dict, Iterable, List, Any, Text, Protocol, Tuple, Optional + +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/stdlib/_warnings.pyi b/mypy/stdlib/_warnings.pyi new file mode 100644 index 000000000000..6c8906e091cf --- /dev/null +++ b/mypy/stdlib/_warnings.pyi @@ -0,0 +1,64 @@ +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] + +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: ... diff --git a/mypy/stdlib/_weakref.pyi b/mypy/stdlib/_weakref.pyi new file mode 100644 index 000000000000..6a527c1894a6 --- /dev/null +++ b/mypy/stdlib/_weakref.pyi @@ -0,0 +1,28 @@ +import sys +from typing import Any, Callable, Generic, Optional, TypeVar, overload + +_C = TypeVar('_C', bound=Callable[..., Any]) +_T = TypeVar('_T') + +class CallableProxyType(object): # "weakcallableproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ProxyType(object): # "weakproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ReferenceType(Generic[_T]): + if sys.version_info >= (3, 4): + __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: ... + +ref = ReferenceType + +def getweakrefcount(object: Any) -> int: ... +def getweakrefs(object: Any) -> int: ... +@overload +def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType: ... +# Return CallableProxyType if object is callable, ProxyType otherwise +@overload +def proxy(object: _T, callback: Optional[Callable[[_T], Any]] = ...) -> Any: ... diff --git a/mypy/stdlib/_weakrefset.pyi b/mypy/stdlib/_weakrefset.pyi new file mode 100644 index 000000000000..f7dc56ec3295 --- /dev/null +++ b/mypy/stdlib/_weakrefset.pyi @@ -0,0 +1,43 @@ +from typing import Iterator, Any, Iterable, MutableSet, Optional, TypeVar, Generic, 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: _SelfT, 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[_S]) -> 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/stdlib/_winapi.pyi b/mypy/stdlib/_winapi.pyi new file mode 100644 index 000000000000..6a8990c4f9b8 --- /dev/null +++ b/mypy/stdlib/_winapi.pyi @@ -0,0 +1,103 @@ +import sys +from typing import Any, Union, Tuple, Optional, overload, Dict, NoReturn, Sequence +from typing_extensions import Literal + +CREATE_NEW_CONSOLE: int +CREATE_NEW_PROCESS_GROUP: int +DUPLICATE_CLOSE_SOURCE: int +DUPLICATE_SAME_ACCESS: int +ERROR_ALREADY_EXISTS: int +ERROR_BROKEN_PIPE: int +ERROR_IO_PENDING: int +ERROR_MORE_DATA: int +ERROR_NETNAME_DELETED: int +ERROR_NO_DATA: int +ERROR_NO_SYSTEM_RESOURCES: int +ERROR_OPERATION_ABORTED: int +ERROR_PIPE_BUSY: int +ERROR_PIPE_CONNECTED: int +ERROR_SEM_TIMEOUT: int +FILE_FLAG_FIRST_PIPE_INSTANCE: int +FILE_FLAG_OVERLAPPED: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +GENERIC_READ: int +GENERIC_WRITE: int +INFINITE: int +NMPWAIT_WAIT_FOREVER: int +NULL: int +OPEN_EXISTING: int +PIPE_ACCESS_DUPLEX: int +PIPE_ACCESS_INBOUND: int +PIPE_READMODE_MESSAGE: int +PIPE_TYPE_MESSAGE: int +PIPE_UNLIMITED_INSTANCES: int +PIPE_WAIT: int +PROCESS_ALL_ACCESS: int +PROCESS_DUP_HANDLE: int +STARTF_USESHOWWINDOW: int +STARTF_USESTDHANDLES: int +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +STILL_ACTIVE: int +SW_HIDE: int +WAIT_ABANDONED_0: int +WAIT_OBJECT_0: int +WAIT_TIMEOUT: int + +def CloseHandle(__handle: int) -> None: ... + +@overload +def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... +@overload +def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... +@overload +def ConnectNamedPipe(handle: int, overlapped: bool) -> Optional[Overlapped]: ... + +def CreateFile(__file_name: str, __desired_access: int, __share_mode: int, __security_attributes: int, __creation_disposition: int, __flags_and_attributes: int, __template_file: int) -> int: ... +def CreateJunction(__src_path: str, __dst_path: str) -> None: ... +def CreateNamedPipe(__name: str, __open_mode: int, __pipe_mode: int, __max_instances: int, __out_buffer_size: int, __in_buffer_size: int, __default_timeout: int, __security_attributes: int) -> int: ... +def CreatePipe(__pipe_attrs: Any, __size: int) -> Tuple[int, int]: ... +def CreateProcess(__application_name: Optional[str], __command_line: Optional[str], __proc_attrs: Any, __thread_attrs: Any, __inherit_handles: bool, __creation_flags: int, __env_mapping: Dict[str, str], __current_directory: Optional[str], __startup_info: Any) -> Tuple[int, int, int, int]: ... +def DuplicateHandle(__source_process_handle: int, __source_handle: int, __target_process_handle: int, __desired_access: int, __inherit_handle: bool, __options: int = ...) -> int: ... +def ExitProcess(__ExitCode: int) -> NoReturn: ... +if sys.version_info >= (3, 7): + def GetACP() -> int: ... + def GetFileType(handle: int) -> int: ... +def GetCurrentProcess() -> int: ... +def GetExitCodeProcess(__process: int) -> int: ... +def GetLastError() -> int: ... +def GetModuleFileName(__module_handle: int) -> str: ... +def GetStdHandle(__std_handle: int) -> int: ... +def GetVersion() -> int: ... +def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... +def PeekNamedPipe(__handle: int, __size: int = ...) -> Union[Tuple[int, int], Tuple[bytes, int, int]]: ... + +@overload +def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... +@overload +def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> Tuple[bytes, int]: ... +@overload +def ReadFile(handle: int, size: int, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... + +def SetNamedPipeHandleState(__named_pipe: int, __mode: Optional[int], __max_collection_count: Optional[int], __collect_data_timeout: Optional[int]) -> None: ... +def TerminateProcess(__handle: int, __exit_code: int) -> None: ... +def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... +def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... +def WaitNamedPipe(__name: str, __timeout: int) -> None: ... + + +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Literal[False] = ...) -> Tuple[int, int]: ... +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... + + +class Overlapped: + event: int = ... + def GetOverlappedResult(self, __wait: bool) -> Tuple[int, int]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> Optional[bytes]: ... diff --git a/mypy/stdlib/abc.pyi b/mypy/stdlib/abc.pyi new file mode 100644 index 000000000000..e9c530d20f83 --- /dev/null +++ b/mypy/stdlib/abc.pyi @@ -0,0 +1,19 @@ +from typing import Any, Callable, Type, TypeVar +# Stubs for abc. + +_T = TypeVar('_T') +_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) + +# Thesee definitions have special processing in mypy +class ABCMeta(type): + def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... + +def abstractmethod(callable: _FuncT) -> _FuncT: ... +class abstractproperty(property): ... +# These two are deprecated and not supported by mypy +def abstractstaticmethod(callable: _FuncT) -> _FuncT: ... +def abstractclassmethod(callable: _FuncT) -> _FuncT: ... + +class ABC(metaclass=ABCMeta): ... + +def get_cache_token() -> object: ... diff --git a/mypy/stdlib/aifc.pyi b/mypy/stdlib/aifc.pyi new file mode 100644 index 000000000000..696ae4c5255f --- /dev/null +++ b/mypy/stdlib/aifc.pyi @@ -0,0 +1,86 @@ +from typing import Union, IO, Optional, Type, NamedTuple, List, Tuple, Any, Text, overload +from typing_extensions import Literal +from types import TracebackType +import sys + +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: ... + 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 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: ... + 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 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: ... + +if sys.version_info < (3, 9): + @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/stdlib/antigravity.pyi b/mypy/stdlib/antigravity.pyi new file mode 100644 index 000000000000..94e67addd477 --- /dev/null +++ b/mypy/stdlib/antigravity.pyi @@ -0,0 +1,5 @@ + +import sys + +if sys.version_info >= (3, 0): + def geohash(latitude: float, longitude: float, datedow: bytes) -> None: ... diff --git a/mypy/stdlib/argparse.pyi b/mypy/stdlib/argparse.pyi new file mode 100644 index 000000000000..20202f17b2ed --- /dev/null +++ b/mypy/stdlib/argparse.pyi @@ -0,0 +1,447 @@ +from typing import ( + Any, Callable, Dict, Generator, Iterable, List, IO, NoReturn, Optional, + Pattern, Protocol, Sequence, Text, Tuple, Type, Union, TypeVar, overload +) +import sys + +_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 +REMAINDER: str +SUPPRESS: str +ZERO_OR_MORE: str +_UNRECOGNIZED_ARGS_ATTR: str # undocumented + +class ArgumentError(Exception): + 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: Optional[_Text] + 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: Optional[Text], 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 + + if sys.version_info >= (3, 5): + allow_abbrev: bool + + # undocumented + _positionals: _ArgumentGroup + _optionals: _ArgumentGroup + _subparsers: Optional[_ArgumentGroup] + + if sys.version_info >= (3, 9): + def __init__(self, + prog: Optional[str] = ..., + usage: Optional[str] = ..., + description: Optional[str] = ..., + epilog: Optional[str] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: Optional[str] = ..., + argument_default: Optional[str] = ..., + conflict_handler: str = ..., + add_help: bool = ..., + allow_abbrev: bool = ..., + exit_on_error: bool = ...) -> None: ... + elif sys.version_info >= (3, 5): + def __init__(self, + prog: Optional[str] = ..., + usage: Optional[str] = ..., + description: Optional[str] = ..., + epilog: Optional[str] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: Optional[str] = ..., + argument_default: Optional[str] = ..., + conflict_handler: str = ..., + 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: Optional[Text] = ..., + 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: ... + + if sys.version_info >= (3, 7): + def add_subparsers(self, *, title: str = ..., + description: Optional[str] = ..., + prog: str = ..., + parser_class: Type[ArgumentParser] = ..., + action: Type[Action] = ..., + option_string: str = ..., + dest: Optional[str] = ..., + required: bool = ..., + help: Optional[str] = ..., + metavar: Optional[str] = ...) -> _SubParsersAction: ... + else: + 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: ... + if sys.version_info >= (3, 7): + def parse_intermixed_args(self, args: Optional[Sequence[str]] = ..., + namespace: Optional[Namespace] = ...) -> Namespace: ... + def parse_known_intermixed_args(self, + args: Optional[Sequence[str]] = ..., + namespace: Optional[Namespace] = ...) -> Tuple[Namespace, List[str]]: ... + # 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: 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): ... +if sys.version_info >= (3,): + class MetavarTypeHelpFormatter(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: ... + if sys.version_info >= (3, 9): + def format_usage(self) -> str: ... + +if sys.version_info >= (3, 9): + class BooleanOptionalAction(Action): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: None = ..., # unused in implementation + 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: ... + +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 + 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]: ... + +# 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] + if sys.version_info >= (3, 7): + def __init__(self, + option_strings: Sequence[Text], + prog: Text, + parser_class: Type[ArgumentParser], + dest: Text = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ...) -> None: ... + else: + 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): ... + +if sys.version_info < (3, 7): + # 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/stdlib/array.pyi b/mypy/stdlib/array.pyi new file mode 100644 index 000000000000..1ca55c8526cd --- /dev/null +++ b/mypy/stdlib/array.pyi @@ -0,0 +1,90 @@ +# Stubs for array + +# Based on http://docs.python.org/3.6/library/array.html + +import sys +from typing import (Any, BinaryIO, Generic, Iterable, Iterator, List, MutableSequence, + overload, Text, Tuple, TypeVar, Union) +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) + +if sys.version_info >= (3,): + typecodes: str + +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: ... + if sys.version_info >= (3, 2): + 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: ... + 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 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: ... + + 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]: ... + 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/stdlib/ast.pyi b/mypy/stdlib/ast.pyi new file mode 100644 index 000000000000..d798376a6180 --- /dev/null +++ b/mypy/stdlib/ast.pyi @@ -0,0 +1,195 @@ +# Rename typing to _typing, as not to conflict with typing imported +# from _ast below when loaded in an unorthodox way by the Dropbox +# internal Bazel integration. + +# The same unorthodox Bazel integration causes issues with sys, which +# is imported in both modules. unfortunately we can't just rename sys, +# since mypy only supports version checks with a sys that is named +# sys. +import sys +import typing as _typing +from typing import Any, Iterator, Optional, TypeVar, Union, overload +from typing_extensions import Literal + +from _ast import * # type: ignore + +if sys.version_info >= (3, 8): + class Num(Constant): ... + class Str(Constant): ... + class Bytes(Constant): ... + class NameConstant(Constant): ... + class Ellipsis(Constant): ... +if sys.version_info >= (3, 9): + class slice(AST): ... + class ExtSlice(slice): ... + class Index(slice): ... + class Suite(mod): ... + class AugLoad(expr_context): ... + class AugStore(expr_context): ... + class Param(expr_context): ... + +class NodeVisitor: + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + def visit_Module(self, node: Module) -> Any: ... + def visit_Interactive(self, node: Interactive) -> Any: ... + def visit_Expression(self, node: Expression) -> Any: ... + def visit_FunctionDef(self, node: FunctionDef) -> Any: ... + def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any: ... + def visit_ClassDef(self, node: ClassDef) -> Any: ... + def visit_Return(self, node: Return) -> Any: ... + def visit_Delete(self, node: Delete) -> Any: ... + def visit_Assign(self, node: Assign) -> Any: ... + def visit_AugAssign(self, node: AugAssign) -> Any: ... + if sys.version_info >= (3, 6): + def visit_AnnAssign(self, node: AnnAssign) -> Any: ... + def visit_For(self, node: For) -> Any: ... + def visit_AsyncFor(self, node: AsyncFor) -> Any: ... + def visit_While(self, node: While) -> Any: ... + def visit_If(self, node: If) -> Any: ... + def visit_With(self, node: With) -> Any: ... + def visit_AsyncWith(self, node: AsyncWith) -> Any: ... + def visit_Raise(self, node: Raise) -> Any: ... + def visit_Try(self, node: Try) -> Any: ... + def visit_Assert(self, node: Assert) -> Any: ... + def visit_Import(self, node: Import) -> Any: ... + def visit_ImportFrom(self, node: ImportFrom) -> Any: ... + def visit_Global(self, node: Global) -> Any: ... + def visit_Nonlocal(self, node: Nonlocal) -> Any: ... + def visit_Expr(self, node: Expr) -> Any: ... + def visit_Pass(self, node: Pass) -> Any: ... + def visit_Break(self, node: Break) -> Any: ... + def visit_Continue(self, node: Continue) -> Any: ... + def visit_Slice(self, node: Slice) -> Any: ... + def visit_BoolOp(self, node: BoolOp) -> Any: ... + def visit_BinOp(self, node: BinOp) -> Any: ... + def visit_UnaryOp(self, node: UnaryOp) -> Any: ... + def visit_Lambda(self, node: Lambda) -> Any: ... + def visit_IfExp(self, node: IfExp) -> Any: ... + def visit_Dict(self, node: Dict) -> Any: ... + def visit_Set(self, node: Set) -> Any: ... + def visit_ListComp(self, node: ListComp) -> Any: ... + def visit_SetComp(self, node: SetComp) -> Any: ... + def visit_DictComp(self, node: DictComp) -> Any: ... + def visit_GeneratorExp(self, node: GeneratorExp) -> Any: ... + def visit_Await(self, node: Await) -> Any: ... + def visit_Yield(self, node: Yield) -> Any: ... + def visit_YieldFrom(self, node: YieldFrom) -> Any: ... + def visit_Compare(self, node: Compare) -> Any: ... + def visit_Call(self, node: Call) -> Any: ... + if sys.version_info >= (3, 6): + def visit_FormattedValue(self, node: FormattedValue) -> Any: ... + def visit_JoinedStr(self, node: JoinedStr) -> Any: ... + if sys.version_info >= (3, 6): + def visit_Constant(self, node: Constant) -> Any: ... + if sys.version_info >= (3, 8): + def visit_NamedExpr(self, node: NamedExpr) -> Any: ... + def visit_Attribute(self, node: Attribute) -> Any: ... + def visit_Subscript(self, node: Subscript) -> Any: ... + def visit_Starred(self, node: Starred) -> Any: ... + def visit_Name(self, node: Name) -> Any: ... + def visit_List(self, node: List) -> Any: ... + def visit_Tuple(self, node: Tuple) -> Any: ... + def visit_Del(self, node: Del) -> Any: ... + def visit_Load(self, node: Load) -> Any: ... + def visit_Store(self, node: Store) -> Any: ... + def visit_And(self, node: And) -> Any: ... + def visit_Or(self, node: Or) -> Any: ... + def visit_Add(self, node: Add) -> Any: ... + def visit_BitAnd(self, node: BitAnd) -> Any: ... + def visit_BitOr(self, node: BitOr) -> Any: ... + def visit_BitXor(self, node: BitXor) -> Any: ... + def visit_Div(self, node: Div) -> Any: ... + def visit_FloorDiv(self, node: FloorDiv) -> Any: ... + def visit_LShift(self, node: LShift) -> Any: ... + def visit_Mod(self, node: Mod) -> Any: ... + def visit_Mult(self, node: Mult) -> Any: ... + def visit_MatMult(self, node: MatMult) -> Any: ... + def visit_Pow(self, node: Pow) -> Any: ... + def visit_RShift(self, node: RShift) -> Any: ... + def visit_Sub(self, node: Sub) -> Any: ... + def visit_Invert(self, node: Invert) -> Any: ... + def visit_Not(self, node: Not) -> Any: ... + def visit_UAdd(self, node: UAdd) -> Any: ... + def visit_USub(self, node: USub) -> Any: ... + def visit_Eq(self, node: Eq) -> Any: ... + def visit_Gt(self, node: Gt) -> Any: ... + def visit_GtE(self, node: GtE) -> Any: ... + def visit_In(self, node: In) -> Any: ... + def visit_Is(self, node: Is) -> Any: ... + def visit_IsNot(self, node: IsNot) -> Any: ... + def visit_Lt(self, node: Lt) -> Any: ... + def visit_LtE(self, node: LtE) -> Any: ... + def visit_NotEq(self, node: NotEq) -> Any: ... + def visit_NotIn(self, node: NotIn) -> Any: ... + def visit_comprehension(self, node: comprehension) -> Any: ... + def visit_ExceptHandler(self, node: ExceptHandler) -> Any: ... + def visit_arguments(self, node: arguments) -> Any: ... + def visit_arg(self, node: arg) -> Any: ... + def visit_keyword(self, node: keyword) -> Any: ... + def visit_alias(self, node: alias) -> Any: ... + def visit_withitem(self, node: withitem) -> Any: ... + # visit methods for deprecated nodes + def visit_ExtSlice(self, node: ExtSlice) -> Any: ... + def visit_Index(self, node: Index) -> Any: ... + def visit_Suite(self, node: Suite) -> Any: ... + def visit_AugLoad(self, node: AugLoad) -> Any: ... + def visit_AugStore(self, node: AugStore) -> Any: ... + def visit_Param(self, node: Param) -> Any: ... + def visit_Num(self, node: Num) -> Any: ... + def visit_Str(self, node: Str) -> Any: ... + def visit_Bytes(self, node: Bytes) -> Any: ... + def visit_NameConstant(self, node: NameConstant) -> Any: ... + def visit_Ellipsis(self, node: Ellipsis) -> Any: ... + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> Optional[AST]: ... + # TODO: Override the visit_* methods with better return types. + # The usual return type is Optional[AST], but Iterable[AST] + # is also allowed in some cases -- this needs to be mapped. + +_T = TypeVar("_T", bound=AST) + +if sys.version_info >= (3, 8): + @overload + def parse( + source: Union[str, bytes], + filename: Union[str, bytes] = ..., + mode: Literal["exec"] = ..., + *, + type_comments: bool = ..., + feature_version: Union[None, int, _typing.Tuple[int, int]] = ..., + ) -> Module: ... + @overload + def parse( + source: Union[str, bytes], + filename: Union[str, bytes] = ..., + mode: str = ..., + *, + type_comments: bool = ..., + feature_version: Union[None, int, _typing.Tuple[int, int]] = ..., + ) -> AST: ... + +else: + @overload + def parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: Literal["exec"] = ...) -> Module: ... + @overload + def parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: str = ...) -> AST: ... + +if sys.version_info >= (3, 9): + def unparse(ast_obj: AST) -> str: ... + +def copy_location(new_node: _T, old_node: AST) -> _T: ... +if sys.version_info >= (3, 9): + def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ..., *, indent: Union[int, str, None] = ...) -> str: ... +else: + def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... +def fix_missing_locations(node: _T) -> _T: ... +def get_docstring(node: AST, clean: bool = ...) -> str: ... +def increment_lineno(node: _T, n: int = ...) -> _T: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def literal_eval(node_or_string: Union[str, AST]) -> Any: ... +if sys.version_info >= (3, 8): + def get_source_segment(source: str, node: AST, *, padded: bool = ...) -> Optional[str]: ... +def walk(node: AST) -> Iterator[AST]: ... diff --git a/mypy/stdlib/asynchat.pyi b/mypy/stdlib/asynchat.pyi new file mode 100644 index 000000000000..a359ae7de147 --- /dev/null +++ b/mypy/stdlib/asynchat.pyi @@ -0,0 +1,41 @@ +from abc import abstractmethod +import asyncore +import socket +import sys +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: ... + +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/stdlib/asyncio/__init__.pyi b/mypy/stdlib/asyncio/__init__.pyi new file mode 100644 index 000000000000..147c8b46d4eb --- /dev/null +++ b/mypy/stdlib/asyncio/__init__.pyi @@ -0,0 +1,138 @@ +import sys +from typing import Type + +from asyncio.base_events import BaseEventLoop as BaseEventLoop +from asyncio.coroutines import ( + coroutine as coroutine, + iscoroutinefunction as iscoroutinefunction, + iscoroutine as iscoroutine, +) +from asyncio.events import ( + AbstractEventLoopPolicy as AbstractEventLoopPolicy, + AbstractEventLoop as AbstractEventLoop, + AbstractServer as AbstractServer, + Handle as Handle, + TimerHandle as TimerHandle, + get_event_loop_policy as get_event_loop_policy, + set_event_loop_policy as set_event_loop_policy, + get_event_loop as get_event_loop, + set_event_loop as set_event_loop, + new_event_loop as new_event_loop, + get_child_watcher as get_child_watcher, + set_child_watcher as set_child_watcher, + _set_running_loop as _set_running_loop, + _get_running_loop as _get_running_loop, +) +if sys.version_info >= (3, 7): + from asyncio.events import get_running_loop as get_running_loop +if sys.version_info >= (3, 8): + from asyncio.exceptions import ( + CancelledError as CancelledError, + IncompleteReadError as IncompleteReadError, + InvalidStateError as InvalidStateError, + LimitOverrunError as LimitOverrunError, + SendfileNotAvailableError as SendfileNotAvailableError, + TimeoutError as TimeoutError, + ) +else: + if sys.version_info >= (3, 7): + from asyncio.events import ( + SendfileNotAvailableError as SendfileNotAvailableError + ) + from asyncio.futures import ( + CancelledError as CancelledError, + TimeoutError as TimeoutError, + InvalidStateError as InvalidStateError, + ) + from asyncio.streams import ( + IncompleteReadError as IncompleteReadError, + LimitOverrunError as LimitOverrunError, + ) +from asyncio.futures import ( + Future as Future, + isfuture as isfuture, + wrap_future as wrap_future, +) +from asyncio.locks import ( + Lock as Lock, + Event as Event, + Condition as Condition, + Semaphore as Semaphore, + BoundedSemaphore as BoundedSemaphore, +) +from asyncio.protocols import ( + BaseProtocol as BaseProtocol, + Protocol as Protocol, + DatagramProtocol as DatagramProtocol, + SubprocessProtocol as SubprocessProtocol, +) +if sys.version_info >= (3, 7): + from asyncio.protocols import BufferedProtocol as BufferedProtocol +from asyncio.queues import ( + Queue as Queue, + PriorityQueue as PriorityQueue, + LifoQueue as LifoQueue, + QueueFull as QueueFull, + QueueEmpty as QueueEmpty, +) +if sys.version_info >= (3, 7): + from asyncio.runners import run as run +from asyncio.streams import ( + StreamReader as StreamReader, + StreamWriter as StreamWriter, + StreamReaderProtocol as StreamReaderProtocol, + open_connection as open_connection, + start_server as start_server, +) +from asyncio.subprocess import ( + create_subprocess_exec as create_subprocess_exec, + create_subprocess_shell as create_subprocess_shell, +) +from asyncio.tasks import ( + FIRST_COMPLETED as FIRST_COMPLETED, + FIRST_EXCEPTION as FIRST_EXCEPTION, + ALL_COMPLETED as ALL_COMPLETED, + as_completed as as_completed, + ensure_future as ensure_future, + gather as gather, + run_coroutine_threadsafe as run_coroutine_threadsafe, + shield as shield, + sleep as sleep, + wait as wait, + wait_for as wait_for, + Task as Task, +) +if sys.version_info >= (3, 7): + from asyncio.tasks import ( + all_tasks as all_tasks, + create_task as create_task, + current_task as current_task, + ) +if sys.version_info >= (3, 9): + from asyncio.threads import to_thread as to_thread +from asyncio.transports import ( + BaseTransport as BaseTransport, + ReadTransport as ReadTransport, + WriteTransport as WriteTransport, + Transport as Transport, + DatagramTransport as DatagramTransport, + SubprocessTransport as SubprocessTransport, +) + +DefaultEventLoopPolicy: Type[AbstractEventLoopPolicy] +if sys.platform == 'win32': + from asyncio.windows_events import * + +if sys.platform != 'win32': + from asyncio.streams import ( + open_unix_connection as open_unix_connection, + start_unix_server as start_unix_server, + ) + from .unix_events import ( + AbstractChildWatcher as AbstractChildWatcher, + FastChildWatcher as FastChildWatcher, + SafeChildWatcher as SafeChildWatcher, + SelectorEventLoop as SelectorEventLoop, + ) + if sys.version_info >= (3, 8): + from .unix_events import MultiLoopChildWatcher as MultiLoopChildWatcher, ThreadedChildWatcher as ThreadedChildWatcher diff --git a/mypy/stdlib/asyncio/base_events.pyi b/mypy/stdlib/asyncio/base_events.pyi new file mode 100644 index 000000000000..0be834bab326 --- /dev/null +++ b/mypy/stdlib/asyncio/base_events.pyi @@ -0,0 +1,218 @@ +from socket import socket, _Address, _RetAddress +import ssl +import sys +from typing import Any, Awaitable, Callable, Dict, Generator, IO, List, Optional, Sequence, Tuple, TypeVar, Union, overload +from typing_extensions import Literal +from abc import ABCMeta +from asyncio.futures import Future +from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle +from asyncio.protocols import BaseProtocol +from asyncio.tasks import Task +from asyncio.transports import BaseTransport +from _typeshed import FileDescriptorLike + +if sys.version_info >= (3, 7): + from contextvars import Context + +_T = TypeVar('_T') +_Context = Dict[str, Any] +_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] +_ProtocolFactory = Callable[[], BaseProtocol] +_SSLContext = Union[bool, None, ssl.SSLContext] +_TransProtPair = Tuple[BaseTransport, BaseProtocol] + +class Server(AbstractServer): ... + +class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): + def run_forever(self) -> None: ... + + # Can't use a union, see mypy issue # 1873. + @overload + def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... + @overload + def run_until_complete(self, future: Awaitable[_T]) -> _T: ... + + def stop(self) -> None: ... + def is_running(self) -> bool: ... + def is_closed(self) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 6): + async def shutdown_asyncgens(self) -> None: ... + # Methods scheduling callbacks. All these return Handles. + if sys.version_info >= (3, 7): + def call_soon(self, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ...) -> Handle: ... + def call_later( + self, delay: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ..., + ) -> TimerHandle: ... + def call_at( + self, when: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ..., + ) -> TimerHandle: ... + else: + def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + def call_later(self, delay: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + def call_at(self, when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + def time(self) -> float: ... + # Future methods + 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]: ... + else: + def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... + def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ... + def get_task_factory(self) -> Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]: ... + # Methods for interacting with threads + if sys.version_info >= (3, 7): + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ...) -> Handle: ... + else: + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + # run_in_executor is defined as a coroutine in AbstractEventLoop but returns a Future in concrete implementation. + # Need to ignore mypy Return type error as a result. + def run_in_executor(self, executor: Any, # type: ignore + func: Callable[..., _T], *args: Any) -> Future[_T]: ... + def set_default_executor(self, executor: Any) -> None: ... + # Network I/O methods returning Futures. + # TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers + # https://github.com/python/mypy/issues/2509 + async def getaddrinfo(self, host: Optional[str], port: Union[str, int, None], *, + family: int = ..., type: int = ..., proto: int = ..., + flags: int = ...) -> List[Tuple[int, int, int, str, Tuple[Any, ...]]]: ... + async def getnameinfo(self, sockaddr: Tuple[Any, ...], flags: int = ...) -> Tuple[str, int]: ... + if sys.version_info >= (3, 8): + @overload + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + happy_eyeballs_delay: Optional[float] = ..., + interleave: Optional[int] = ..., + ) -> _TransProtPair: ... + @overload + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + happy_eyeballs_delay: Optional[float] = ..., + interleave: Optional[int] = ..., + ) -> _TransProtPair: ... + elif sys.version_info >= (3, 7): + @overload + async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., + sock: None = ..., local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + @overload + async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., + sock: socket, local_addr: None = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + else: + @overload + async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + @overload + async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: socket, + local_addr: None = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + if sys.version_info >= (3, 7): + async def sock_sendfile(self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, + fallback: bool = ...) -> int: ... + @overload + async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., *, family: int = ..., flags: int = ..., sock: None = ..., backlog: int = ..., + ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> Server: ... + @overload + async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + family: int = ..., flags: int = ..., sock: socket = ..., backlog: int = ..., + ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> Server: ... + async def connect_accepted_socket(self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def sendfile(self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, + fallback: bool = ...) -> int: ... + async def start_tls(self, transport: BaseTransport, protocol: BaseProtocol, sslcontext: ssl.SSLContext, *, + server_side: bool = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> BaseTransport: ... + else: + @overload + async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., port: int = ..., *, + family: int = ..., flags: int = ..., + sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> Server: ... + @overload + async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + family: int = ..., flags: int = ..., + sock: socket, backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> Server: ... + async def connect_accepted_socket(self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ...) -> _TransProtPair: ... + async def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory, + local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *, + family: int = ..., proto: int = ..., flags: int = ..., + reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + allow_broadcast: Optional[bool] = ..., + sock: Optional[socket] = ...) -> _TransProtPair: ... + # Pipes and subprocesses. + async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def subprocess_shell(self, protocol_factory: _ProtocolFactory, cmd: Union[bytes, str], *, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., universal_newlines: Literal[False] = ..., + shell: Literal[True] = ..., bufsize: Literal[0] = ..., encoding: None = ..., + errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any) -> _TransProtPair: ... + async def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., + **kwargs: Any) -> _TransProtPair: ... + def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> None: ... + def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_writer(self, fd: FileDescriptorLike) -> None: ... + # Completion based I/O methods returning Futures prior to 3.7 + if sys.version_info >= (3, 7): + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... + async def sock_sendall(self, sock: socket, data: bytes) -> None: ... + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + async def sock_accept(self, sock: socket) -> Tuple[socket, _RetAddress]: ... + else: + def sock_recv(self, sock: socket, nbytes: int) -> Future[bytes]: ... + def sock_sendall(self, sock: socket, data: bytes) -> Future[None]: ... + def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... + def sock_accept(self, sock: socket) -> Future[Tuple[socket, _RetAddress]]: ... + # Signal handling. + def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_signal_handler(self, sig: int) -> None: ... + # Error handlers. + def set_exception_handler(self, handler: Optional[_ExceptionHandler]) -> None: ... + def get_exception_handler(self) -> Optional[_ExceptionHandler]: ... + def default_exception_handler(self, context: _Context) -> None: ... + def call_exception_handler(self, context: _Context) -> None: ... + # Debug flag management. + def get_debug(self) -> bool: ... + def set_debug(self, enabled: bool) -> None: ... + if sys.version_info >= (3, 9): + async def shutdown_default_executor(self) -> None: ... diff --git a/mypy/stdlib/asyncio/base_futures.pyi b/mypy/stdlib/asyncio/base_futures.pyi new file mode 100644 index 000000000000..2298e500c0e3 --- /dev/null +++ b/mypy/stdlib/asyncio/base_futures.pyi @@ -0,0 +1,13 @@ +import contextvars +from typing import List, Tuple, Callable, Sequence +from typing_extensions import Literal + +from . import futures + +_PENDING: Literal["PENDING"] # undocumented +_CANCELLED: Literal["CANCELLED"] # undocumented +_FINISHED: Literal["FINISHED"] # undocumented + +def isfuture(obj: object) -> bool: ... +def _format_callbacks(cb: Sequence[Tuple[Callable[[futures.Future], None], contextvars.Context]]) -> str: ... # undocumented +def _future_repr_info(future: futures.Future) -> List[str]: ... # undocumented diff --git a/mypy/stdlib/asyncio/base_subprocess.pyi b/mypy/stdlib/asyncio/base_subprocess.pyi new file mode 100644 index 000000000000..31cf24860eff --- /dev/null +++ b/mypy/stdlib/asyncio/base_subprocess.pyi @@ -0,0 +1,59 @@ + +from typing import Optional, Union, Sequence, IO, Any, List, Deque, Dict, Tuple, Callable +import subprocess + +from . import events +from . import protocols +from . import futures +from . import transports + +_File = Optional[Union[int, IO[Any]]] + +class BaseSubprocessTransport(transports.SubprocessTransport): + + _closed: bool # undocumented + _protocol: protocols.SubprocessProtocol # undocumented + _loop: events.AbstractEventLoop # undocumented + _proc: Optional[subprocess.Popen] # undocumented + _pid: Optional[int] # undocumented + _returncode: Optional[int] # undocumented + _exit_waiters: List[futures.Future] # undocumented + _pending_calls: Deque[Tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented + _pipes: Dict[int, _File] # undocumented + _finished: bool # undocumented + + def __init__(self, loop: events.AbstractEventLoop, protocol: protocols.SubprocessProtocol, args: Union[str, bytes, Sequence[Union[str, bytes]]], + shell: bool, stdin: _File, stdout: _File, stderr: _File, bufsize: int, waiter: Optional[futures.Future] = ..., extra: Optional[Any] = ..., **kwargs: Any) -> None: ... + + def _start(self, args: Union[str, bytes, Sequence[Union[str, bytes]]], shell: bool, stdin: _File, stdout: _File, stderr: _File, bufsize: int, **kwargs: Any): ... # undocumented + def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... + def get_protocol(self) -> protocols.BaseProtocol: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + def get_pid(self) -> Optional[int]: ... # type: ignore + def get_returncode(self) -> Optional[int]: ... + def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore + def _check_proc(self) -> None: ... # undocumented + def send_signal(self, signal: int) -> None: ... # type: ignore + def terminate(self) -> None: ... + def kill(self) -> None: ... + async def _connect_pipes(self, waiter: Optional[futures.Future]) -> None: ... # undocumented + def _call(self, cb: Callable[..., Any], *data: Any) -> None: ... # undocumented + def _pipe_connection_lost(self, fd: int, exc: Optional[BaseException]) -> None: ... # undocumented + def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented + def _process_exited(self, returncode: int) -> None: ... # undocumented + async def _wait(self) -> int: ... # undocumented + def _try_finish(self) -> None: ... # undocumented + def _call_connection_lost(self, exc: Optional[BaseException]) -> None: ... # undocumented + +class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented + + def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[BaseException]) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): # undocumented + + def data_received(self, data: bytes) -> None: ... diff --git a/mypy/stdlib/asyncio/base_tasks.pyi b/mypy/stdlib/asyncio/base_tasks.pyi new file mode 100644 index 000000000000..aa9f600e1a16 --- /dev/null +++ b/mypy/stdlib/asyncio/base_tasks.pyi @@ -0,0 +1,8 @@ +from _typeshed import AnyPath +from typing import List, Optional +from types import FrameType +from . import tasks + +def _task_repr_info(task: tasks.Task) -> List[str]: ... # undocumented +def _task_get_stack(task: tasks.Task, limit: Optional[int]) -> List[FrameType]: ... # undocumented +def _task_print_stack(task: tasks.Task, limit: Optional[int], file: AnyPath): ... # undocumented diff --git a/mypy/stdlib/asyncio/compat.pyi b/mypy/stdlib/asyncio/compat.pyi new file mode 100644 index 000000000000..24d448f49dd5 --- /dev/null +++ b/mypy/stdlib/asyncio/compat.pyi @@ -0,0 +1,10 @@ + +import sys +from typing import List + +if sys.version_info < (3, 7): + PY34: bool + PY35: bool + PY352: bool + + def flatten_list_bytes(list_of_data: List[bytes]) -> bytes: ... diff --git a/mypy/stdlib/asyncio/constants.pyi b/mypy/stdlib/asyncio/constants.pyi new file mode 100644 index 000000000000..0b28309e9ff7 --- /dev/null +++ b/mypy/stdlib/asyncio/constants.pyi @@ -0,0 +1,16 @@ + +import enum +import sys + +LOG_THRESHOLD_FOR_CONNLOST_WRITES: int +ACCEPT_RETRY_DELAY: int +if sys.version_info >= (3, 6): + DEBUG_STACK_DEPTH: int +if sys.version_info >= (3, 7): + SSL_HANDSHAKE_TIMEOUT: float + SENDFILE_FALLBACK_READBUFFER_SIZE: int + +class _SendfileMode(enum.Enum): + UNSUPPORTED: int = ... + TRY_NATIVE: int = ... + FALLBACK: int = ... diff --git a/mypy/stdlib/asyncio/coroutines.pyi b/mypy/stdlib/asyncio/coroutines.pyi new file mode 100644 index 000000000000..f75dfe5f63e9 --- /dev/null +++ b/mypy/stdlib/asyncio/coroutines.pyi @@ -0,0 +1,7 @@ +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: ... diff --git a/mypy/stdlib/asyncio/events.pyi b/mypy/stdlib/asyncio/events.pyi new file mode 100644 index 000000000000..9fc466ae5cd5 --- /dev/null +++ b/mypy/stdlib/asyncio/events.pyi @@ -0,0 +1,344 @@ +from socket import socket, _Address, _RetAddress +import ssl +import sys +from typing import Any, Awaitable, Callable, Dict, Generator, IO, List, Optional, Sequence, Tuple, TypeVar, Union, overload +from abc import ABCMeta, abstractmethod +from asyncio.futures import Future +from asyncio.protocols import BaseProtocol +from asyncio.tasks import Task +from asyncio.transports import BaseTransport +from asyncio.unix_events import AbstractChildWatcher +from _typeshed import FileDescriptorLike + +if sys.version_info >= (3, 7): + from contextvars import Context + +_T = TypeVar('_T') +_Context = Dict[str, Any] +_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] +_ProtocolFactory = Callable[[], BaseProtocol] +_SSLContext = Union[bool, None, ssl.SSLContext] +_TransProtPair = Tuple[BaseTransport, BaseProtocol] + +class Handle: + _cancelled = False + _args: Sequence[Any] + if sys.version_info >= (3, 7): + def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context] = ...) -> None: ... + else: + def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... + def __repr__(self) -> str: ... + def cancel(self) -> None: ... + def _run(self) -> None: ... + if sys.version_info >= (3, 7): + def cancelled(self) -> bool: ... + +class TimerHandle(Handle): + if sys.version_info >= (3, 7): + def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], + loop: AbstractEventLoop, context: Optional[Context] = ...) -> None: ... + else: + def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], + loop: AbstractEventLoop) -> None: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3, 7): + def when(self) -> float: ... + +class AbstractServer: + sockets: Optional[List[socket]] + def close(self) -> None: ... + if sys.version_info >= (3, 7): + async def __aenter__(self: _T) -> _T: ... + async def __aexit__(self, *exc: Any) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + def is_serving(self) -> bool: ... + async def start_serving(self) -> None: ... + async def serve_forever(self) -> None: ... + async def wait_closed(self) -> None: ... + +class AbstractEventLoop(metaclass=ABCMeta): + slow_callback_duration: float = ... + @abstractmethod + def run_forever(self) -> None: ... + + # Can't use a union, see mypy issue # 1873. + @overload + @abstractmethod + def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... + @overload + @abstractmethod + def run_until_complete(self, future: Awaitable[_T]) -> _T: ... + + @abstractmethod + def stop(self) -> None: ... + @abstractmethod + def is_running(self) -> bool: ... + @abstractmethod + def is_closed(self) -> bool: ... + @abstractmethod + def close(self) -> None: ... + if sys.version_info >= (3, 6): + @abstractmethod + async def shutdown_asyncgens(self) -> None: ... + # Methods scheduling callbacks. All these return Handles. + @abstractmethod + def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + @abstractmethod + def call_later(self, delay: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + @abstractmethod + def call_at(self, when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + @abstractmethod + def time(self) -> float: ... + # Future methods + @abstractmethod + def create_future(self) -> Future[Any]: ... + # Tasks methods + if sys.version_info >= (3, 8): + @abstractmethod + def create_task( + self, coro: Union[Awaitable[_T], Generator[Any, None, _T]], *, name: Optional[str] = ..., + ) -> Task[_T]: ... + else: + @abstractmethod + def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... + @abstractmethod + def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ... + @abstractmethod + def get_task_factory(self) -> Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]: ... + # Methods for interacting with threads + @abstractmethod + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + @abstractmethod + async def run_in_executor(self, executor: Any, + func: Callable[..., _T], *args: Any) -> _T: ... + @abstractmethod + def set_default_executor(self, executor: Any) -> None: ... + # Network I/O methods returning Futures. + @abstractmethod + # TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers + # https://github.com/python/mypy/issues/2509 + async def getaddrinfo(self, host: Optional[str], port: Union[str, int, None], *, + family: int = ..., type: int = ..., proto: int = ..., + flags: int = ...) -> List[Tuple[int, int, int, str, Tuple[Any, ...]]]: ... + @abstractmethod + async def getnameinfo(self, sockaddr: Tuple[Any, ...], flags: int = ...) -> Tuple[str, int]: ... + if sys.version_info >= (3, 8): + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + happy_eyeballs_delay: Optional[float] = ..., + interleave: Optional[int] = ..., + ) -> _TransProtPair: ... + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + happy_eyeballs_delay: Optional[float] = ..., + interleave: Optional[int] = ..., + ) -> _TransProtPair: ... + elif sys.version_info >= (3, 7): + @overload + @abstractmethod + async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., + sock: None = ..., local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + @overload + @abstractmethod + async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., + sock: socket, local_addr: None = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + else: + @overload + @abstractmethod + async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + @overload + @abstractmethod + async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: socket, + local_addr: None = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + if sys.version_info >= (3, 7): + @abstractmethod + async def sock_sendfile(self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, + fallback: bool = ...) -> int: ... + @overload + @abstractmethod + async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., *, family: int = ..., flags: int = ..., sock: None = ..., backlog: int = ..., + ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> AbstractServer: ... + @overload + @abstractmethod + async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + family: int = ..., flags: int = ..., sock: socket = ..., backlog: int = ..., + ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> AbstractServer: ... + async def create_unix_connection(self, protocol_factory: _ProtocolFactory, path: Optional[str] = ..., *, ssl: _SSLContext = ..., + sock: Optional[socket] = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def create_unix_server(self, protocol_factory: _ProtocolFactory, path: Optional[str] = ..., *, sock: Optional[socket] = ..., + backlog: int = ..., ssl: _SSLContext = ..., ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ...) -> AbstractServer: ... + @abstractmethod + async def sendfile(self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, + fallback: bool = ...) -> int: ... + @abstractmethod + async def start_tls(self, transport: BaseTransport, protocol: BaseProtocol, sslcontext: ssl.SSLContext, *, + server_side: bool = ..., server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ...) -> BaseTransport: ... + else: + @overload + @abstractmethod + async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., port: int = ..., *, + family: int = ..., flags: int = ..., + sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> AbstractServer: ... + @overload + @abstractmethod + async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + family: int = ..., flags: int = ..., + sock: socket, backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> AbstractServer: ... + async def create_unix_connection(self, protocol_factory: _ProtocolFactory, path: str, *, + ssl: _SSLContext = ..., sock: Optional[socket] = ..., + server_hostname: Optional[str] = ...) -> _TransProtPair: ... + async def create_unix_server(self, protocol_factory: _ProtocolFactory, path: str, *, + sock: Optional[socket] = ..., backlog: int = ..., ssl: _SSLContext = ...) -> AbstractServer: ... + @abstractmethod + async def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory, + local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *, + family: int = ..., proto: int = ..., flags: int = ..., + reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + allow_broadcast: Optional[bool] = ..., + sock: Optional[socket] = ...) -> _TransProtPair: ... + # Pipes and subprocesses. + @abstractmethod + async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + @abstractmethod + async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + @abstractmethod + async def subprocess_shell(self, protocol_factory: _ProtocolFactory, cmd: Union[bytes, str], *, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., + **kwargs: Any) -> _TransProtPair: ... + @abstractmethod + async def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., + **kwargs: Any) -> _TransProtPair: ... + @abstractmethod + def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_reader(self, fd: FileDescriptorLike) -> None: ... + @abstractmethod + def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_writer(self, fd: FileDescriptorLike) -> None: ... + # Completion based I/O methods returning Futures prior to 3.7 + if sys.version_info >= (3, 7): + @abstractmethod + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + @abstractmethod + async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... + @abstractmethod + async def sock_sendall(self, sock: socket, data: bytes) -> None: ... + @abstractmethod + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + @abstractmethod + async def sock_accept(self, sock: socket) -> Tuple[socket, _RetAddress]: ... + else: + @abstractmethod + def sock_recv(self, sock: socket, nbytes: int) -> Future[bytes]: ... + @abstractmethod + def sock_sendall(self, sock: socket, data: bytes) -> Future[None]: ... + @abstractmethod + def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... + @abstractmethod + def sock_accept(self, sock: socket) -> Future[Tuple[socket, _RetAddress]]: ... + # Signal handling. + @abstractmethod + def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_signal_handler(self, sig: int) -> None: ... + # Error handlers. + @abstractmethod + def set_exception_handler(self, handler: Optional[_ExceptionHandler]) -> None: ... + @abstractmethod + def get_exception_handler(self) -> Optional[_ExceptionHandler]: ... + @abstractmethod + def default_exception_handler(self, context: _Context) -> None: ... + @abstractmethod + def call_exception_handler(self, context: _Context) -> None: ... + # Debug flag management. + @abstractmethod + def get_debug(self) -> bool: ... + @abstractmethod + def set_debug(self, enabled: bool) -> None: ... + if sys.version_info >= (3, 9): + @abstractmethod + async def shutdown_default_executor(self) -> None: ... + +class AbstractEventLoopPolicy(metaclass=ABCMeta): + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def set_event_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... + # Child processes handling (Unix only). + @abstractmethod + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + +class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): + def __init__(self) -> None: ... + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... + +def get_event_loop_policy() -> AbstractEventLoopPolicy: ... +def set_event_loop_policy(policy: Optional[AbstractEventLoopPolicy]) -> None: ... + +def get_event_loop() -> AbstractEventLoop: ... +def set_event_loop(loop: Optional[AbstractEventLoop]) -> None: ... +def new_event_loop() -> AbstractEventLoop: ... + +def get_child_watcher() -> AbstractChildWatcher: ... +def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... + +def _set_running_loop(__loop: Optional[AbstractEventLoop]) -> None: ... +def _get_running_loop() -> AbstractEventLoop: ... + +if sys.version_info >= (3, 7): + def get_running_loop() -> AbstractEventLoop: ... + if sys.version_info < (3, 8): + class SendfileNotAvailableError(RuntimeError): ... diff --git a/mypy/stdlib/asyncio/exceptions.pyi b/mypy/stdlib/asyncio/exceptions.pyi new file mode 100644 index 000000000000..ecec9560a850 --- /dev/null +++ b/mypy/stdlib/asyncio/exceptions.pyi @@ -0,0 +1,15 @@ +import sys +from typing import Optional + +if sys.version_info >= (3, 8): + class CancelledError(BaseException): ... + class TimeoutError(Exception): ... + class InvalidStateError(Exception): ... + class SendfileNotAvailableError(RuntimeError): ... + class IncompleteReadError(EOFError): + expected: Optional[int] + partial: bytes + def __init__(self, partial: bytes, expected: Optional[int]) -> None: ... + class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... diff --git a/mypy/stdlib/asyncio/format_helpers.pyi b/mypy/stdlib/asyncio/format_helpers.pyi new file mode 100644 index 000000000000..a1b2d09bfad7 --- /dev/null +++ b/mypy/stdlib/asyncio/format_helpers.pyi @@ -0,0 +1,25 @@ + +import sys +import functools +import traceback + +from typing import Optional, Tuple, Union, Iterable, Dict, Any, overload +from types import FunctionType, FrameType + +class _HasWrapper: + __wrapper__: Union[_HasWrapper, FunctionType] + +_FuncType = Union[FunctionType, _HasWrapper, functools.partial, functools.partialmethod] + +if sys.version_info >= (3, 7): + + @overload + def _get_function_source(func: _FuncType) -> Tuple[str, int]: ... + @overload + def _get_function_source(func: object) -> Optional[Tuple[str, int]]: ... + + def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... + def _format_args_and_kwargs(args: Iterable[Any], kwargs: Dict[str, Any]) -> str: ... + def _format_callback(func: object, args: Iterable[Any], kwargs: Dict[str, Any], suffix: str = ...) -> str: ... + + def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> traceback.StackSummary: ... diff --git a/mypy/stdlib/asyncio/futures.pyi b/mypy/stdlib/asyncio/futures.pyi new file mode 100644 index 000000000000..a4f8d6710cf6 --- /dev/null +++ b/mypy/stdlib/asyncio/futures.pyi @@ -0,0 +1,65 @@ +import sys +from typing import Any, Union, Callable, TypeVar, Type, List, Iterable, Generator, Awaitable, Optional, Tuple +from .events import AbstractEventLoop +from concurrent.futures._base import ( + Future as _ConcurrentFuture, + Error, +) + +if sys.version_info < (3, 8): + from concurrent.futures import CancelledError as CancelledError + from concurrent.futures import TimeoutError as TimeoutError + class InvalidStateError(Error): ... + +if sys.version_info >= (3, 7): + from contextvars import Context + +_T = TypeVar('_T') +_S = TypeVar('_S') + +if sys.version_info < (3, 7): + class _TracebackLogger: + exc: BaseException + tb: List[str] + def __init__(self, exc: Any, loop: AbstractEventLoop) -> None: ... + def activate(self) -> None: ... + def clear(self) -> None: ... + def __del__(self) -> None: ... + +def isfuture(obj: object) -> bool: ... + +class Future(Awaitable[_T], Iterable[_T]): + _state: str + _exception: BaseException + _blocking = False + _log_traceback = False + if sys.version_info < (3, 6): + _tb_logger: Type[_TracebackLogger] + def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def __repr__(self) -> str: ... + def __del__(self) -> None: ... + if sys.version_info >= (3, 7): + def get_loop(self) -> AbstractEventLoop: ... + def _callbacks(self: _S) -> List[Tuple[Callable[[_S], Any], Context]]: ... + def add_done_callback(self: _S, __fn: Callable[[_S], Any], *, context: Optional[Context] = ...) -> None: ... + else: + @property + def _callbacks(self: _S) -> List[Callable[[_S], Any]]: ... + def add_done_callback(self: _S, __fn: Callable[[_S], Any]) -> None: ... + if sys.version_info >= (3, 9): + def cancel(self, msg: Optional[str] = ...) -> bool: ... + else: + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def result(self) -> _T: ... + def exception(self) -> Optional[BaseException]: ... + def remove_done_callback(self: _S, __fn: Callable[[_S], Any]) -> int: ... + def set_result(self, __result: _T) -> None: ... + def set_exception(self, __exception: Union[type, BaseException]) -> None: ... + def __iter__(self) -> Generator[Any, None, _T]: ... + def __await__(self) -> Generator[Any, None, _T]: ... + @property + def _loop(self) -> AbstractEventLoop: ... + +def wrap_future(future: Union[_ConcurrentFuture[_T], Future[_T]], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... diff --git a/mypy/stdlib/asyncio/locks.pyi b/mypy/stdlib/asyncio/locks.pyi new file mode 100644 index 000000000000..55eabfffc3a9 --- /dev/null +++ b/mypy/stdlib/asyncio/locks.pyi @@ -0,0 +1,63 @@ +import sys +from typing import Any, Callable, Iterable, Generator, Type, TypeVar, Union, Optional, Awaitable + +from .events import AbstractEventLoop +from .futures import Future +from types import TracebackType + +_T = TypeVar('_T') + + +if sys.version_info >= (3, 9): + class _ContextManagerMixin: + def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... + def __aenter__(self) -> Awaitable[None]: ... + def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ... +else: + class _ContextManager: + def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... + def __enter__(self) -> object: ... + def __exit__(self, *args: Any) -> None: ... + + class _ContextManagerMixin: + def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... + # Apparently this exists to *prohibit* use as a context manager. + def __enter__(self) -> object: ... + def __exit__(self, *args: Any) -> None: ... + def __iter__(self) -> Generator[Any, None, _ContextManager]: ... + def __await__(self) -> Generator[Any, None, _ContextManager]: ... + def __aenter__(self) -> Awaitable[None]: ... + def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ... + + +class Lock(_ContextManagerMixin): + def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> bool: ... + def release(self) -> None: ... + +class Event: + def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + async def wait(self) -> bool: ... + +class Condition(_ContextManagerMixin): + def __init__(self, lock: Optional[Lock] = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> bool: ... + def release(self) -> None: ... + async def wait(self) -> bool: ... + async def wait_for(self, predicate: Callable[[], _T]) -> _T: ... + def notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + +class Semaphore(_ContextManagerMixin): + def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> bool: ... + def release(self) -> None: ... + +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... diff --git a/mypy/stdlib/asyncio/log.pyi b/mypy/stdlib/asyncio/log.pyi new file mode 100644 index 000000000000..5534ebda5802 --- /dev/null +++ b/mypy/stdlib/asyncio/log.pyi @@ -0,0 +1,4 @@ + +import logging + +logger: logging.Logger diff --git a/mypy/stdlib/asyncio/proactor_events.pyi b/mypy/stdlib/asyncio/proactor_events.pyi new file mode 100644 index 000000000000..f5602f6fdab2 --- /dev/null +++ b/mypy/stdlib/asyncio/proactor_events.pyi @@ -0,0 +1,38 @@ +from socket import socket +from typing import Any, Mapping, Optional +from typing_extensions import Literal + +from . import base_events, constants, events, futures, streams, transports + +class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): + + def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __repr__(self) -> str: ... + def __del__(self) -> None: ... + def get_write_buffer_size(self) -> int: ... + +class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): + + def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + +class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): + + def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + +class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): + + def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + +class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ... + +class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): + + _sendfile_compatible: constants._SendfileMode = ... + + def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def _set_extra(self, sock: socket) -> None: ... + def can_write_eof(self) -> Literal[True]: ... + def write_eof(self) -> None: ... + +class BaseProactorEventLoop(base_events.BaseEventLoop): + def __init__(self, proactor: Any) -> None: ... diff --git a/mypy/stdlib/asyncio/protocols.pyi b/mypy/stdlib/asyncio/protocols.pyi new file mode 100644 index 000000000000..710fad75e193 --- /dev/null +++ b/mypy/stdlib/asyncio/protocols.pyi @@ -0,0 +1,27 @@ +import sys +from asyncio import transports +from typing import Optional, Tuple, Union + +class BaseProtocol: + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[Exception]) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class Protocol(BaseProtocol): + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> Optional[bool]: ... + +if sys.version_info >= (3, 7): + class BufferedProtocol(BaseProtocol): + def get_buffer(self, sizehint: int) -> bytearray: ... + def buffer_updated(self, nbytes: int) -> None: ... + +class DatagramProtocol(BaseProtocol): + def datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None: ... + def error_received(self, exc: Exception) -> None: ... + +class SubprocessProtocol(BaseProtocol): + def pipe_data_received(self, fd: int, data: bytes) -> None: ... + def pipe_connection_lost(self, fd: int, exc: Optional[Exception]) -> None: ... + def process_exited(self) -> None: ... diff --git a/mypy/stdlib/asyncio/queues.pyi b/mypy/stdlib/asyncio/queues.pyi new file mode 100644 index 000000000000..75340e67e2e7 --- /dev/null +++ b/mypy/stdlib/asyncio/queues.pyi @@ -0,0 +1,33 @@ +from asyncio.events import AbstractEventLoop +from typing import Generic, TypeVar, Optional + +class QueueEmpty(Exception): ... +class QueueFull(Exception): ... + +_T = TypeVar('_T') + +class Queue(Generic[_T]): + def __init__(self, maxsize: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def _init(self, maxsize: int) -> None: ... + def _get(self) -> _T: ... + def _put(self, item: _T) -> None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def _format(self) -> str: ... + def qsize(self) -> int: ... + @property + def maxsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + async def put(self, item: _T) -> None: ... + def put_nowait(self, item: _T) -> None: ... + async def get(self) -> _T: ... + def get_nowait(self) -> _T: ... + async def join(self) -> bool: ... + def task_done(self) -> None: ... + + +class PriorityQueue(Queue[_T]): ... + + +class LifoQueue(Queue[_T]): ... diff --git a/mypy/stdlib/asyncio/runners.pyi b/mypy/stdlib/asyncio/runners.pyi new file mode 100644 index 000000000000..7d8c28c0d7d4 --- /dev/null +++ b/mypy/stdlib/asyncio/runners.pyi @@ -0,0 +1,9 @@ +import sys + + +if sys.version_info >= (3, 7): + from typing import Awaitable, TypeVar + + _T = TypeVar('_T') + + def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... diff --git a/mypy/stdlib/asyncio/selector_events.pyi b/mypy/stdlib/asyncio/selector_events.pyi new file mode 100644 index 000000000000..8946bb050ac2 --- /dev/null +++ b/mypy/stdlib/asyncio/selector_events.pyi @@ -0,0 +1,7 @@ +import selectors +from typing import Optional + +from . import base_events + +class BaseSelectorEventLoop(base_events.BaseEventLoop): + def __init__(self, selector: Optional[selectors.BaseSelector] = ...) -> None: ... diff --git a/mypy/stdlib/asyncio/sslproto.pyi b/mypy/stdlib/asyncio/sslproto.pyi new file mode 100644 index 000000000000..18bf1d874681 --- /dev/null +++ b/mypy/stdlib/asyncio/sslproto.pyi @@ -0,0 +1,131 @@ + +import sys +import ssl + +from typing import ClassVar, Optional, List, Tuple, Callable, Dict, Any, Deque +from typing_extensions import Literal + +from . import transports +from . import constants +from . import events +from . import protocols +from . import futures + +def _create_transport_context(server_side: bool, server_hostname: Optional[str]) -> ssl.SSLContext: ... + +_UNWRAPPED: Literal["UNWRAPPED"] +_DO_HANDSHAKE: Literal["DO_HANDSHAKE"] +_WRAPPED: Literal["WRAPPED"] +_SHUTDOWN: Literal["SHUTDOWN"] + +class _SSLPipe: + + max_size: ClassVar[int] + + _context: ssl.SSLContext + _server_side: bool + _server_hostname: Optional[str] + _state: str + _incoming: ssl.MemoryBIO + _outgoing: ssl.MemoryBIO + _sslobj: Optional[ssl.SSLObject] + _need_ssldata: bool + _handshake_cb: Optional[Callable[[Optional[BaseException]], None]] + _shutdown_cb: Optional[Callable[[], None]] + + def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: Optional[str] = ...) -> None: ... + + @property + def context(self) -> ssl.SSLContext: ... + @property + def ssl_object(self) -> Optional[ssl.SSLObject]: ... + @property + def need_ssldata(self) -> bool: ... + @property + def wrapped(self) -> bool: ... + + def do_handshake(self, callback: Optional[Callable[[Optional[BaseException]], None]] = ...) -> List[bytes]: ... + def shutdown(self, callback: Optional[Callable[[], None]] = ...) -> List[bytes]: ... + def feed_eof(self) -> None: ... + def feed_ssldata(self, data: bytes, only_handshake: bool = ...) -> Tuple[List[bytes], List[bytes]]: ... + def feed_appdata(self, data: bytes, offset: int = ...) -> Tuple[List[bytes], int]: ... + +class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): + + _sendfile_compatible: ClassVar[constants._SendfileMode] + + _loop: events.AbstractEventLoop + _ssl_protocol: SSLProtocol + _closed: bool + + if sys.version_info >= (3, 6): + def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... + else: + def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol, app_protocol: protocols.BaseProtocol) -> None: ... + + def get_extra_info(self, name: str, default: Optional[Any] = ...) -> Dict[str, Any]: ... + def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... + def get_protocol(self) -> protocols.BaseProtocol: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 7): + def is_reading(self) -> bool: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + def set_write_buffer_limits(self, high: Optional[int] = ..., low: Optional[int] = ...) -> None: ... + def get_write_buffer_size(self) -> int: ... + if sys.version_info >= (3, 7): + @property + def _protocol_paused(self) -> bool: ... + def write(self, data: bytes) -> None: ... + def can_write_eof(self) -> Literal[False]: ... + def abort(self) -> None: ... + +class SSLProtocol(protocols.Protocol): + + _server_side: bool + _server_hostname: Optional[str] + _sslcontext: ssl.SSLContext + _extra: Dict[str, Any] + _write_backlog: Deque[Tuple[bytes, int]] + _write_buffer_size: int + _waiter: futures.Future + _loop: events.AbstractEventLoop + _app_transport: _SSLProtocolTransport + _sslpipe: Optional[_SSLPipe] + _session_established: bool + _in_handshake: bool + _in_shutdown: bool + _transport: Optional[transports.BaseTransport] + _call_connection_made: bool + _ssl_handshake_timeout: Optional[int] + _app_protocol: protocols.BaseProtocol + _app_protocol_is_buffer: bool + + if sys.version_info >= (3, 7): + def __init__(self, loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future, + server_side: bool = ..., server_hostname: Optional[str] = ..., call_connection_made: bool = ..., ssl_handshake_timeout: Optional[int] = ...) -> None: ... + else: + def __init__(self, loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future, + server_side: bool = ..., server_hostname: Optional[str] = ..., call_connection_made: bool = ...) -> None: ... + + if sys.version_info >= (3, 7): + def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... + def _wakeup_waiter(self, exc: Optional[BaseException] = ...) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[BaseException]) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> None: ... + def _get_extra_info(self, name: str, default: Optional[Any] = ...) -> Any: ... + def _start_shutdown(self) -> None: ... + def _write_appdata(self, data: bytes) -> None: ... + def _start_handshake(self) -> None: ... + if sys.version_info >= (3, 7): + def _check_handshake_timeout(self) -> None: ... + def _on_handshake_complete(self, handshake_exc: Optional[BaseException]) -> None: ... + def _process_write_backlog(self) -> None: ... + def _fatal_error(self, exc: BaseException, message: str = ...) -> None: ... + def _finalize(self) -> None: ... + def _abort(self) -> None: ... diff --git a/mypy/stdlib/asyncio/staggered.pyi b/mypy/stdlib/asyncio/staggered.pyi new file mode 100644 index 000000000000..3ba73b11b089 --- /dev/null +++ b/mypy/stdlib/asyncio/staggered.pyi @@ -0,0 +1,7 @@ + +import sys +from typing import Iterable, Callable, Awaitable, Optional, Tuple, Any, List +from . import events + +if sys.version_info >= (3, 8): + async def staggered_race(coro_fns: Iterable[Callable[[], Awaitable]], delay: Optional[float], *, loop: Optional[events.AbstractEventLoop] = ...) -> Tuple[Any, Optional[int], List[Optional[Exception]]]: ... diff --git a/mypy/stdlib/asyncio/streams.pyi b/mypy/stdlib/asyncio/streams.pyi new file mode 100644 index 000000000000..b691798ab454 --- /dev/null +++ b/mypy/stdlib/asyncio/streams.pyi @@ -0,0 +1,108 @@ +import sys +from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union + +from . import events +from . import protocols +from . import transports + +_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] + +if sys.version_info < (3, 8): + class IncompleteReadError(EOFError): + expected: Optional[int] + partial: bytes + def __init__(self, partial: bytes, expected: Optional[int]) -> None: ... + + class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... + +async def open_connection( + host: Optional[str] = ..., + port: Optional[Union[int, str]] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + ssl_handshake_timeout: Optional[float] = ..., + **kwds: Any +) -> Tuple[StreamReader, StreamWriter]: ... + +async def start_server( + client_connected_cb: _ClientConnectedCallback, + host: Optional[str] = ..., + port: Optional[Union[int, str]] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + ssl_handshake_timeout: Optional[float] = ..., + **kwds: Any +) -> events.AbstractServer: ... + +if sys.platform != 'win32': + if sys.version_info >= (3, 7): + from os import PathLike + _PathType = Union[str, PathLike[str]] + else: + _PathType = str + + async def open_unix_connection( + path: Optional[_PathType] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any + ) -> Tuple[StreamReader, StreamWriter]: ... + + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, + path: Optional[_PathType] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any) -> events.AbstractServer: ... + +class FlowControlMixin(protocols.Protocol): ... + +class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): + def __init__(self, + stream_reader: StreamReader, + client_connected_cb: Optional[_ClientConnectedCallback] = ..., + loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[Exception]) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> bool: ... + +class StreamWriter: + def __init__(self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + reader: Optional[StreamReader], + loop: events.AbstractEventLoop) -> None: ... + @property + def transport(self) -> transports.BaseTransport: ... + def write(self, data: bytes) -> None: ... + def writelines(self, data: Iterable[bytes]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 7): + def is_closing(self) -> bool: ... + async def wait_closed(self) -> None: ... + def get_extra_info(self, name: str, default: Any = ...) -> Any: ... + async def drain(self) -> None: ... + +class StreamReader: + def __init__(self, + limit: int = ..., + loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def exception(self) -> Exception: ... + def set_exception(self, exc: Exception) -> None: ... + def set_transport(self, transport: transports.BaseTransport) -> None: ... + def feed_eof(self) -> None: ... + def at_eof(self) -> bool: ... + def feed_data(self, data: bytes) -> None: ... + async def readline(self) -> bytes: ... + async def readuntil(self, separator: bytes = ...) -> bytes: ... + async def read(self, n: int = ...) -> bytes: ... + async def readexactly(self, n: int) -> bytes: ... diff --git a/mypy/stdlib/asyncio/subprocess.pyi b/mypy/stdlib/asyncio/subprocess.pyi new file mode 100644 index 000000000000..ef4544247400 --- /dev/null +++ b/mypy/stdlib/asyncio/subprocess.pyi @@ -0,0 +1,67 @@ +import sys +from asyncio import events +from asyncio import protocols +from asyncio import streams +from asyncio import transports +from typing import Any, Optional, Tuple, Union, IO + +if sys.version_info >= (3, 8): + from os import PathLike + _ExecArg = Union[str, bytes, PathLike[str], PathLike[bytes]] +else: + _ExecArg = Union[str, bytes] # Union used instead of AnyStr due to mypy issue #1236 + +PIPE: int +STDOUT: int +DEVNULL: int + +class SubprocessStreamProtocol(streams.FlowControlMixin, + protocols.SubprocessProtocol): + stdin: Optional[streams.StreamWriter] + stdout: Optional[streams.StreamReader] + stderr: Optional[streams.StreamReader] + def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def pipe_data_received(self, fd: int, data: Union[bytes, str]) -> None: ... + def pipe_connection_lost(self, fd: int, exc: Optional[Exception]) -> None: ... + def process_exited(self) -> None: ... + + +class Process: + stdin: Optional[streams.StreamWriter] + stdout: Optional[streams.StreamReader] + stderr: Optional[streams.StreamReader] + pid: int + def __init__(self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + loop: events.AbstractEventLoop) -> None: ... + @property + def returncode(self) -> Optional[int]: ... + async def wait(self) -> int: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + async def communicate(self, input: Optional[bytes] = ...) -> Tuple[bytes, bytes]: ... + + +async def create_subprocess_shell( + cmd: Union[str, bytes], # Union used instead of AnyStr due to mypy issue #1236 + stdin: Union[int, IO[Any], None] = ..., + stdout: Union[int, IO[Any], None] = ..., + stderr: Union[int, IO[Any], None] = ..., + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any +) -> Process: ... + +async def create_subprocess_exec( + program: _ExecArg, + *args: _ExecArg, + stdin: Union[int, IO[Any], None] = ..., + stdout: Union[int, IO[Any], None] = ..., + stderr: Union[int, IO[Any], None] = ..., + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any +) -> Process: ... diff --git a/mypy/stdlib/asyncio/tasks.pyi b/mypy/stdlib/asyncio/tasks.pyi new file mode 100644 index 000000000000..7f73bb2a4489 --- /dev/null +++ b/mypy/stdlib/asyncio/tasks.pyi @@ -0,0 +1,127 @@ +import concurrent.futures +import sys +from typing import ( + Any, TypeVar, Set, List, TextIO, Union, Tuple, Generic, Generator, Iterable, Awaitable, overload, Iterator, Optional, +) +from typing_extensions import Literal +from types import FrameType +from .events import AbstractEventLoop +from .futures import Future + +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] + +FIRST_EXCEPTION: str +FIRST_COMPLETED: str +ALL_COMPLETED: str + +def as_completed(fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., + timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... +def ensure_future(coro_or_future: _FutureT[_T], + *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +# Prior to Python 3.7 'async' was an alias for 'ensure_future'. +# It became a keyword in 3.7. + +# `gather()` actually returns a list with length equal to the number +# of tasks passed; however, Tuple is used similar to the annotation for +# zip() because typing does not support variadic type variables. See +# typing PR #1550 for discussion. +@overload +def gather(coro_or_future1: _FutureT[_T1], + *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], + *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + *, loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], coro_or_future5: _FutureT[_T5], + *, loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], + coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], + *coros_or_futures: _FutureT[Any], + loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[List[Any]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], + *, loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ...) -> Future[Tuple[Union[_T1, BaseException]]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], + *, loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ...) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException]]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ + Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException]]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ + Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], coro_or_future5: _FutureT[_T5], + *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ + Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException], Union[_T5, BaseException]]]: ... +def run_coroutine_threadsafe(coro: _FutureT[_T], + loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def sleep(delay: float, result: _T = ..., *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def wait(fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., + return_when: str = ...) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... +def wait_for(fut: _FutureT[_T], timeout: Optional[float], + *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... + +class Task(Future[_T], Generic[_T]): + @classmethod + def current_task(cls, loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... + @classmethod + def all_tasks(cls, loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... + if sys.version_info >= (3, 8): + def __init__( + self, + coro: Union[Generator[Any, None, _T], Awaitable[_T]], + *, + loop: AbstractEventLoop = ..., + name: Optional[str] = ..., + ) -> None: ... + else: + def __init__(self, coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ...) -> None: ... + def __repr__(self) -> str: ... + if sys.version_info >= (3, 8): + def get_coro(self) -> Any: ... + def get_name(self) -> str: ... + def set_name(self, __value: object) -> None: ... + def get_stack(self, *, limit: int = ...) -> List[FrameType]: ... + def print_stack(self, *, limit: int = ..., file: TextIO = ...) -> None: ... + if sys.version_info >= (3, 9): + def cancel(self, msg: Optional[str] = ...) -> bool: ... + else: + def cancel(self) -> bool: ... + if sys.version_info < (3, 7): + def _wakeup(self, fut: Future[Any]) -> None: ... + +if sys.version_info >= (3, 7): + def all_tasks(loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... + if sys.version_info >= (3, 8): + def create_task( + coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, name: Optional[str] = ..., + ) -> Task[_T]: ... + else: + def create_task(coro: Union[Generator[Any, None, _T], Awaitable[_T]]) -> Task[_T]: ... + def current_task(loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... diff --git a/mypy/stdlib/asyncio/threads.pyi b/mypy/stdlib/asyncio/threads.pyi new file mode 100644 index 000000000000..52e9a63ac0cc --- /dev/null +++ b/mypy/stdlib/asyncio/threads.pyi @@ -0,0 +1,7 @@ +import sys +from typing import Any, Callable, TypeVar + +_T = TypeVar('_T') + +if sys.version_info >= (3, 9): + async def to_thread(__func: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/stdlib/asyncio/transports.pyi b/mypy/stdlib/asyncio/transports.pyi new file mode 100644 index 000000000000..863da761f20b --- /dev/null +++ b/mypy/stdlib/asyncio/transports.pyi @@ -0,0 +1,49 @@ +import sys +from socket import _Address +from typing import Any, Mapping, List, Optional, Tuple +from asyncio.protocols import BaseProtocol +from asyncio.events import AbstractEventLoop + +class BaseTransport: + def __init__(self, extra: Optional[Mapping[Any, Any]] = ...) -> None: ... + def get_extra_info(self, name: Any, default: Any = ...) -> Any: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 5): + def set_protocol(self, protocol: BaseProtocol) -> None: ... + def get_protocol(self) -> BaseProtocol: ... + +class ReadTransport(BaseTransport): + if sys.version_info >= (3, 7): + def is_reading(self) -> bool: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + +class WriteTransport(BaseTransport): + def set_write_buffer_limits( + self, high: Optional[int] = ..., low: Optional[int] = ... + ) -> None: ... + def get_write_buffer_size(self) -> int: ... + def write(self, data: Any) -> None: ... + def writelines(self, list_of_data: List[Any]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def abort(self) -> None: ... + +class Transport(ReadTransport, WriteTransport): ... + +class DatagramTransport(BaseTransport): + def sendto(self, data: Any, addr: Optional[_Address] = ...) -> None: ... + def abort(self) -> None: ... + +class SubprocessTransport(BaseTransport): + def get_pid(self) -> int: ... + def get_returncode(self) -> Optional[int]: ... + def get_pipe_transport(self, fd: int) -> Optional[BaseTransport]: ... + def send_signal(self, signal: int) -> int: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + +class _FlowControlMixin(Transport): + def __init__(self, extra: Optional[Mapping[Any, Any]] = ..., loop: Optional[AbstractEventLoop] = ...) -> None: ... + def get_write_buffer_limits(self) -> Tuple[int, int]: ... diff --git a/mypy/stdlib/asyncio/trsock.pyi b/mypy/stdlib/asyncio/trsock.pyi new file mode 100644 index 000000000000..9dbefbe8c8c1 --- /dev/null +++ b/mypy/stdlib/asyncio/trsock.pyi @@ -0,0 +1,78 @@ + +import sys +import socket +from typing import Union, NoReturn, Tuple, Optional, Iterable, List, Any, BinaryIO, Type, overload +from types import TracebackType + +if sys.version_info >= (3, 8): + # These are based in socket, maybe move them out into _typeshed.pyi or such + _Address = Union[tuple, str] + _RetAddress = Any + _WriteBuffer = Union[bytearray, memoryview] + _CMSG = Tuple[int, int, bytes] + + class TransportSocket: + def __init__(self, sock: socket.socket) -> None: ... + def _na(self, what: str) -> None: ... + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + def __getstate__(self) -> NoReturn: ... + def fileno(self) -> int: ... + def dup(self) -> socket.socket: ... + def get_inheritable(self) -> bool: ... + def shutdown(self, how: int) -> None: ... + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + @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: ... + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? + def accept(self) -> Tuple[socket.socket, _RetAddress]: ... + def connect(self, address: Union[_Address, bytes]) -> None: ... + def connect_ex(self, address: Union[_Address, bytes]) -> int: ... + def bind(self, address: Union[_Address, bytes]) -> None: ... + if sys.platform == 'win32': + def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> None: ... + else: + def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> NoReturn: ... + def listen(self, __backlog: int = ...) -> None: ... + def makefile(self) -> BinaryIO: ... + def sendfile(self, file, offset: int = ..., count: Optional[int] = ...) -> int: ... + def close(self) -> None: ... + def detach(self) -> int: ... + if sys.platform == "linux": + def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> int: ... + else: + def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> NoReturn: ... + def sendmsg(self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ...) -> int: ... + @overload + def sendto(self, data: bytes, address: _Address) -> int: ... + @overload + def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + def sendall(self, data: bytes, flags: int = ...) -> None: ... + def set_inheritable(self, inheritable: bool) -> None: ... + if sys.platform == 'win32': + def share(self, process_id: int) -> bytes: ... + else: + def share(self, process_id: int) -> NoReturn: ... + def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... + def recvmsg_into(self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ...) -> Tuple[int, List[_CMSG], int, Any]: ... + def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> Tuple[bytes, List[_CMSG], int, Any]: ... + def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def settimeout(self, value: Optional[float]) -> None: ... + def gettimeout(self) -> Optional[float]: ... + def setblocking(self, flag: bool) -> None: ... + def __enter__(self) -> socket.socket: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... diff --git a/mypy/stdlib/asyncio/unix_events.pyi b/mypy/stdlib/asyncio/unix_events.pyi new file mode 100644 index 000000000000..3dddf555ea06 --- /dev/null +++ b/mypy/stdlib/asyncio/unix_events.pyi @@ -0,0 +1,57 @@ +import sys +import types +from typing import Any, Callable, Optional, Type, TypeVar + +from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy +from .selector_events import BaseSelectorEventLoop + +_T1 = TypeVar('_T1', bound=AbstractChildWatcher) +_T2 = TypeVar('_T2', bound=SafeChildWatcher) +_T3 = TypeVar('_T3', bound=FastChildWatcher) + +class AbstractChildWatcher: + def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... + def close(self) -> None: ... + def __enter__(self: _T1) -> _T1: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + if sys.version_info >= (3, 8): + def is_active(self) -> bool: ... + +class BaseChildWatcher(AbstractChildWatcher): + def __init__(self) -> None: ... + +class SafeChildWatcher(BaseChildWatcher): + def __enter__(self: _T2) -> _T2: ... + +class FastChildWatcher(BaseChildWatcher): + def __enter__(self: _T3) -> _T3: ... + +class _UnixSelectorEventLoop(BaseSelectorEventLoop): ... + +class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): + def get_child_watcher(self) -> AbstractChildWatcher: ... + def set_child_watcher(self, watcher: Optional[AbstractChildWatcher]) -> None: ... + +SelectorEventLoop = _UnixSelectorEventLoop + +DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + +if sys.version_info >= (3, 8): + + from typing import Protocol + + _T4 = TypeVar('_T4', bound=MultiLoopChildWatcher) + _T5 = TypeVar('_T5', bound=ThreadedChildWatcher) + class _Warn(Protocol): + def __call__( + self, message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ... + ) -> None: ... + class MultiLoopChildWatcher(AbstractChildWatcher): + def __enter__(self: _T4) -> _T4: ... + class ThreadedChildWatcher(AbstractChildWatcher): + def __enter__(self: _T5) -> _T5: ... + def __del__(self, _warn: _Warn = ...) -> None: ... diff --git a/mypy/stdlib/asyncio/windows_events.pyi b/mypy/stdlib/asyncio/windows_events.pyi new file mode 100644 index 000000000000..8b12a9f3539c --- /dev/null +++ b/mypy/stdlib/asyncio/windows_events.pyi @@ -0,0 +1,76 @@ +import socket +import sys +from typing import IO, Any, Callable, ClassVar, List, NoReturn, Optional, Tuple, Type + +from . import events, futures, proactor_events, selector_events, streams, windows_utils + +__all__ = [ + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", +] + +NULL: int +INFINITE: int +ERROR_CONNECTION_REFUSED: int +ERROR_CONNECTION_ABORTED: int +CONNECT_PIPE_INIT_DELAY: float +CONNECT_PIPE_MAX_DELAY: float + +class PipeServer: + def __init__(self, address: str) -> None: ... + def __del__(self) -> None: ... + def closed(self) -> bool: ... + def close(self) -> None: ... + +class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + +class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + def __init__(self, proactor: Optional[IocpProactor] = ...) -> None: ... + async def create_pipe_connection( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> Tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... + async def start_serving_pipe( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> List[PipeServer]: ... + +class IocpProactor: + def __init__(self, concurrency: int = ...) -> None: ... + def __repr__(self) -> str: ... + def __del__(self) -> None: ... + def set_loop(self, loop: events.AbstractEventLoop) -> None: ... + def select(self, timeout: Optional[int] = ...) -> List[futures.Future[Any]]: ... + def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... + if sys.version_info >= (3, 7): + def recv_into(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... + def send(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... + def accept(self, listener: socket.socket) -> futures.Future[Any]: ... + def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... + if sys.version_info >= (3, 7): + def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... + def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... + async def connect_pipe(self, address: bytes) -> windows_utils.PipeHandle: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: Optional[int] = ...) -> bool: ... + def close(self) -> None: ... + +SelectorEventLoop = _WindowsSelectorEventLoop + +if sys.version_info >= (3, 7): + class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[ProactorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy +else: + class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[Type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy diff --git a/mypy/stdlib/asyncio/windows_utils.pyi b/mypy/stdlib/asyncio/windows_utils.pyi new file mode 100644 index 000000000000..bf7c9380b266 --- /dev/null +++ b/mypy/stdlib/asyncio/windows_utils.pyi @@ -0,0 +1,30 @@ + +import sys +from typing import Tuple, Callable, Optional, Type, Protocol +from types import TracebackType + + +class _WarnFunction(Protocol): + def __call__(self, message: str, category: Type[Warning], source: PipeHandle): ... + + +BUFSIZE: int +PIPE: int +STDOUT: int + +def pipe(*, duplex: bool = ..., overlapped: Tuple[bool, bool] = ..., bufsize: int = ...) -> Tuple[int, int]: ... + +class PipeHandle: + + def __init__(self, handle: int) -> None: ... + def __repr__(self) -> str: ... + if sys.version_info >= (3, 8): + def __del__(self, _warn: _WarnFunction = ...) -> None: ... + else: + def __del__(self) -> None: ... + def __enter__(self) -> PipeHandle: ... + def __exit__(self, t: Optional[type], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... + @property + def handle(self) -> int: ... + def fileno(self) -> int: ... + def close(self, *, CloseHandle: Callable[[int], None] = ...) -> None: ... diff --git a/mypy/stdlib/asyncore.pyi b/mypy/stdlib/asyncore.pyi new file mode 100644 index 000000000000..742ac77e2849 --- /dev/null +++ b/mypy/stdlib/asyncore.pyi @@ -0,0 +1,137 @@ +from typing import Tuple, Union, Any, Dict, overload + +import sys +from socket import SocketType +from typing import Optional +from _typeshed import FileDescriptorLike + +# 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: ... + + 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: ... + 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/stdlib/atexit.pyi b/mypy/stdlib/atexit.pyi new file mode 100644 index 000000000000..24f93899d5d2 --- /dev/null +++ b/mypy/stdlib/atexit.pyi @@ -0,0 +1,9 @@ +"""Stub file for the 'atexit' module.""" + +from typing import Any, Callable + +def _clear() -> None: ... +def _ncallbacks() -> int: ... +def _run_exitfuncs() -> None: ... +def register(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Callable[..., Any]: ... +def unregister(func: Callable[..., Any]) -> None: ... diff --git a/mypy/stdlib/audioop.pyi b/mypy/stdlib/audioop.pyi new file mode 100644 index 000000000000..a6885d277cce --- /dev/null +++ b/mypy/stdlib/audioop.pyi @@ -0,0 +1,42 @@ +from typing import Any, 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/stdlib/base64.pyi b/mypy/stdlib/base64.pyi new file mode 100644 index 000000000000..d61cb3acd895 --- /dev/null +++ b/mypy/stdlib/base64.pyi @@ -0,0 +1,40 @@ +# Stubs for base64 + +from typing import IO, Optional, Text, Union +import sys + +if sys.version_info < (3,): + _encodable = Union[bytes, unicode] + _decodable = Union[bytes, unicode] +else: + _encodable = bytes + _decodable = Union[bytes, str] + +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: ... +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 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: ... +if sys.version_info < (3, 9): + def encodestring(s: bytes) -> bytes: ... + def decodestring(s: bytes) -> bytes: ... diff --git a/mypy/stdlib/bdb.pyi b/mypy/stdlib/bdb.pyi new file mode 100644 index 000000000000..1f7f7f335b16 --- /dev/null +++ b/mypy/stdlib/bdb.pyi @@ -0,0 +1,96 @@ + +from typing import Set, Dict, Iterable, Any, Callable, Mapping, Tuple, Type, SupportsInt, List, Union, TypeVar, Optional, IO +from types import FrameType, TracebackType, CodeType + + +_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/stdlib/binascii.pyi b/mypy/stdlib/binascii.pyi new file mode 100644 index 000000000000..7e023c239f46 --- /dev/null +++ b/mypy/stdlib/binascii.pyi @@ -0,0 +1,45 @@ +# Stubs for binascii + +# Based on http://docs.python.org/3.2/library/binascii.html + +import sys +from typing import Union, Text + +if sys.version_info < (3,): + # Python 2 accepts unicode ascii pretty much everywhere. + _Bytes = Text + _Ascii = Text +else: + # But since Python 3.3 ASCII-only unicode strings are accepted by the + # a2b_* functions. + _Bytes = bytes + _Ascii = Union[bytes, str] + +def a2b_uu(__data: _Ascii) -> 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: ... +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: ... +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 a2b_hex(__hexstr: _Ascii) -> bytes: ... +def unhexlify(__hexstr: _Ascii) -> bytes: ... + +class Error(ValueError): ... +class Incomplete(Exception): ... diff --git a/mypy/stdlib/binhex.pyi b/mypy/stdlib/binhex.pyi new file mode 100644 index 000000000000..c759ba0b6f19 --- /dev/null +++ b/mypy/stdlib/binhex.pyi @@ -0,0 +1,48 @@ +from typing import ( + Any, + IO, + 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/stdlib/bisect.pyi b/mypy/stdlib/bisect.pyi new file mode 100644 index 000000000000..67cf11dd2535 --- /dev/null +++ b/mypy/stdlib/bisect.pyi @@ -0,0 +1,4 @@ +# Stubs for bisect +from _bisect import * +bisect = bisect_right +insort = insort_right diff --git a/mypy/stdlib/builtins.pyi b/mypy/stdlib/builtins.pyi new file mode 100644 index 000000000000..c644038d1446 --- /dev/null +++ b/mypy/stdlib/builtins.pyi @@ -0,0 +1,1842 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from typing import ( + TypeVar, Iterator, Iterable, NoReturn, overload, Container, + Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, + Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, + SupportsComplex, IO, BinaryIO, Union, + ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, + Protocol, +) +from abc import ABCMeta +from ast import mod, AST +from io import ( + TextIOWrapper, FileIO, BufferedRandom, BufferedReader, BufferedWriter +) +from types import TracebackType, CodeType +from _typeshed import ( + AnyPath, OpenBinaryMode, OpenTextMode, + OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenBinaryModeReading, + SupportsWrite, ReadableBuffer, +) +from typing_extensions import Literal +import sys + +if sys.version_info >= (3,): + from typing import SupportsBytes, SupportsRound + +if sys.version_info >= (3, 9): + from types import GenericAlias + +class _SupportsIndex(Protocol): + def __index__(self) -> int: ... + +class _SupportsLessThan(Protocol): + def __lt__(self, other: Any) -> bool: ... + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_S = TypeVar('_S') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_TT = TypeVar('_TT', bound='type') +_LT = TypeVar('_LT', bound=_SupportsLessThan) + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + if sys.version_info >= (3, 6): + __annotations__: Dict[str, Any] + + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... + def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... + if sys.version_info >= (3,): + def __dir__(self) -> Iterable[str]: ... + if sys.version_info >= (3, 6): + def __init_subclass__(cls) -> None: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + if sys.version_info >= (3,): + __qualname__: str + __text_signature__: Optional[str] + __weakrefoffset__: int + + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + if sys.version_info >= (3,): + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class super(object): + if sys.version_info >= (3,): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... + else: + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __init__(self, x: Union[Text, bytes, SupportsInt, _SupportsIndex] = ...) -> None: ... + @overload + def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... + + if sys.version_info >= (3, 8): + def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + + def bit_length(self) -> int: ... + if sys.version_info >= (3,): + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes(cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, + signed: bool = ...) -> int: ... # TODO buffer object argument + + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3,): + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __init__(self, x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> None: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, __s: str) -> float: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__(self, x: float, mod: None = ...) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3,): + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __init__(self, real: float = ..., imag: float = ...) -> None: ... + @overload + def __init__(self, real: Union[str, SupportsComplex, _SupportsIndex]) -> None: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + + def conjugate(self) -> complex: ... + + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex, mod: None = ...) -> complex: ... + if sys.version_info < (3,): + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex, mod: None = ...) -> complex: ... + if sys.version_info < (3,): + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +if sys.version_info >= (3,): + _str_base = object +else: + class basestring(metaclass=ABCMeta): ... + + class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + + def __len__(self) -> int: ... + # The argument type is incompatible with Sequence + def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + + _str_base = basestring + +class _FormatMapMapping(Protocol): + def __getitem__(self, __key: str) -> Any: ... + +class str(Sequence[str], _str_base): + if sys.version_info >= (3,): + @overload + def __init__(self, o: object = ...) -> None: ... + @overload + def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, o: object = ...) -> None: ... + + def capitalize(self) -> str: ... + if sys.version_info >= (3, 3): + def casefold(self) -> str: ... + def center(self, __width: int, __fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info < (3,): + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + if sys.version_info >= (3,): + def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + else: + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> str: ... + if sys.version_info >= (3,): + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + if sys.version_info >= (3,): + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + if sys.version_info >= (3,): + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + if sys.version_info >= (3,): + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, __iterable: Iterable[str]) -> str: ... + else: + def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + if sys.version_info >= (3,): + def lstrip(self, __chars: Optional[str] = ...) -> str: ... + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... + else: + @overload + def lstrip(self, __chars: str = ...) -> str: ... + @overload + def lstrip(self, __chars: unicode) -> unicode: ... + @overload + def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: str) -> str: ... + def removesuffix(self, __suffix: str) -> str: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + if sys.version_info >= (3,): + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, __chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + else: + @overload + def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, __chars: str = ...) -> str: ... + @overload + def rstrip(self, __chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + if sys.version_info >= (3,): + def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + def strip(self, __chars: Optional[str] = ...) -> str: ... + else: + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, __chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + if sys.version_info >= (3,): + def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... + else: + def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, __width: int) -> str: ... + if sys.version_info >= (3,): + @staticmethod + @overload + def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... + + if sys.version_info >= (3,): + def __add__(self, s: str) -> str: ... + else: + def __add__(self, s: AnyStr) -> AnyStr: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +if sys.version_info >= (3,): + class bytes(ByteString): + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, + errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: SupportsBytes) -> None: ... + def capitalize(self) -> bytes: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + elif sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytes: ... + def removesuffix(self, __suffix: bytes) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, __width: int) -> bytes: ... + @classmethod + def fromhex(cls, __s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... +else: + bytes = str + +class bytearray(MutableSequence[int], ByteString): + if sys.version_info >= (3,): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + else: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + if sys.version_info >= (3,): + def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + else: + def count(self, __sub: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + if sys.version_info < (3,): + def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... + if sys.version_info >= (3,): + def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + else: + def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def insert(self, __index: int, __item: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + else: + def join(self, __iterable: Iterable[str]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytearray: ... + def removesuffix(self, __suffix: bytes) -> bytearray: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + else: + def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, + __prefix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[int] = ..., + __end: Optional[int] = ..., + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + if sys.version_info >= (3,): + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... + else: + def translate(self, __table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, __width: int) -> bytearray: ... + @classmethod + def fromhex(cls, __string: str) -> bytearray: ... + if sys.version_info >= (3,): + @classmethod + def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + if sys.version_info >= (3,): + def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3,): + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +if sys.version_info >= (3,): + _mv_container_type = int +else: + _mv_container_type = str + +class memoryview(Sized, Container[_mv_container_type]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + + if sys.version_info >= (3,): + obj: Union[bytes, bytearray] + c_contiguous: bool + f_contiguous: bool + contiguous: bool + nbytes: int + def __init__(self, obj: ReadableBuffer) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... + def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... + else: + def __init__(self, obj: ReadableBuffer) -> None: ... + + @overload + def __getitem__(self, i: int) -> _mv_container_type: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_mv_container_type]: ... + def __len__(self) -> int: ... + + @overload + def __setitem__(self, s: slice, o: memoryview) -> None: ... + @overload + def __setitem__(self, i: int, o: bytes) -> None: ... + @overload + def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... + + if sys.version_info >= (3, 8): + def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... + else: + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + if sys.version_info >= (3, 8): + def toreadonly(self) -> memoryview: ... + + if sys.version_info >= (3, 2): + def release(self) -> None: ... + + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + +class bool(int): + def __init__(self, o: object = ...) -> None: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Any + step: Any + stop: Any + @overload + def __init__(self, stop: Any) -> None: ... + @overload + def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... + __hash__: None # type: ignore + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + @overload + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + @overload + def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, __value: Any) -> int: ... + if sys.version_info >= (3, 5): + def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... + else: + def index(self, __value: Any) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + __code__: CodeType + if sys.version_info >= (3,): + __qualname__: str + __annotations__: Dict[str, Any] + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + if sys.version_info >= (3,): + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: int = ...) -> _T: ... + def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: int, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + def reverse(self) -> None: ... + if sys.version_info >= (3,): + @overload + def sort(self: List[_LT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], _SupportsLessThan], reverse: bool = ...) -> None: ... + else: + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + if sys.version_info >= (3,): + def __imul__(self: _S, n: int) -> _S: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + + if sys.version_info < (3,): + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + if sys.version_info >= (3,): + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... + else: + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + @classmethod + @overload + 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: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class frozenset(AbstractSet[_T_co], Generic[_T_co]): + def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> FrozenSet[_T_co]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + if sys.version_info >= (3,): + def __next__(self) -> Tuple[int, _T]: ... + else: + def next(self) -> Tuple[int, _T]: ... + +if sys.version_info >= (3,): + class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int) -> int: ... # type: ignore + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... +else: + class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: int) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ...) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +if sys.version_info < (3,): + long = int + +class _NotImplementedType(Any): # type: ignore + # A little weird, but typing the __call__ as NotImplemented makes the error message + # for NotImplemented() much better + __call__: NotImplemented # type: ignore + +NotImplemented: _NotImplementedType + +def abs(__x: SupportsAbs[_T]) -> _T: ... +def all(__iterable: Iterable[object]) -> bool: ... +def any(__iterable: Iterable[object]) -> bool: ... +if sys.version_info < (3,): + def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +if sys.version_info >= (3,): + def ascii(__obj: object) -> str: ... + +def bin(__number: Union[int, _SupportsIndex]) -> str: ... + +if sys.version_info >= (3, 7): + def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(__obj: object) -> bool: ... +def chr(__i: int) -> str: ... +if sys.version_info < (3,): + def cmp(__x: Any, __y: Any) -> int: ... + _N1 = TypeVar('_N1', bool, int, float, complex) + def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +if sys.version_info >= (3, 6): + # This class is to be exported as PathLike from os, + # but we define it here as _PathLike to avoid import cycle issues. + # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 + class _PathLike(Generic[AnyStr]): + def __fspath__(self) -> AnyStr: ... + def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes, _PathLike[Any]], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +elif sys.version_info >= (3,): + def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +else: + def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +if sys.version_info >= (3,): + def copyright() -> None: ... + def credits() -> None: ... +def delattr(__obj: Any, __name: Text) -> None: ... +def dir(__o: object = ...) -> List[str]: ... +_N2 = TypeVar('_N2', int, float) +def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def eval(__source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +if sys.version_info >= (3,): + def exec(__source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +else: + def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: object = ...) -> NoReturn: ... +if sys.version_info >= (3,): + @overload + def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... +else: + @overload + def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore + @overload + def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore + @overload + def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore + @overload + 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: ... +def globals() -> Dict[str, Any]: ... +def hasattr(__obj: Any, __name: Text) -> bool: ... +def hash(__obj: object) -> int: ... +if sys.version_info >= (3,): + def help(*args: Any, **kwds: Any) -> None: ... +def hex(__number: Union[int, _SupportsIndex]) -> str: ... +def id(__obj: object) -> int: ... +if sys.version_info >= (3,): + def input(__prompt: Any = ...) -> str: ... +else: + def input(__prompt: Any = ...) -> Any: ... + def intern(__string: str) -> str: ... +@overload +def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +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: ... +def len(__obj: Sized) -> int: ... +if sys.version_info >= (3,): + def license() -> None: ... +def locals() -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[_S]: ... +else: + @overload + def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def map(__func: None, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... + @overload + def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> List[_S]: ... + @overload + def map(__func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[_S]: ... +if sys.version_info >= (3,): + @overload + def max(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... + @overload + def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... + @overload + def max(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... + @overload + def max(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... + @overload + def max(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... + @overload + def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... +else: + @overload + def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +if sys.version_info >= (3,): + @overload + def min(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... + @overload + def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... + @overload + def min(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... + @overload + def min(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... + @overload + def min(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... + @overload + def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... +else: + @overload + def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(__i: Iterator[_T]) -> _T: ... +@overload +def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(__number: Union[int, _SupportsIndex]) -> str: ... + +if sys.version_info >= (3,): + _OpenFile = Union[AnyPath, int] + _Opener = Callable[[str, int], int] + + # Text mode: always returns a TextIOWrapper + @overload + def open( + file: _OpenFile, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> TextIOWrapper: ... + + # Unbuffered binary mode: returns a FileIO + @overload + def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> FileIO: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedRandom: ... + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedWriter: ... + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedReader: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: int, + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BinaryIO: ... + + # Fallback if mode is not specified + @overload + def open( + file: _OpenFile, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> IO[Any]: ... + +else: + def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + +def ord(__c: Union[Text, bytes]) -> int: ... +if sys.version_info >= (3,): + def print( + *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[str]] = ..., flush: bool = ... + ) -> None: ... + +else: + # This is only available after from __future__ import print_function. + def print(*values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ...) -> None: ... + +_E = TypeVar("_E", contravariant=True) +_M = TypeVar("_M", contravariant=True) +class _SupportsPow2(Protocol[_E, _T_co]): + def __pow__(self, __other: _E) -> _T_co: ... +class _SupportsPow3(Protocol[_E, _M, _T_co]): + def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... +if sys.version_info >= (3, 8): + @overload + def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(base: int, exp: int, mod: int) -> int: ... + @overload + def pow(base: float, exp: float, mod: None = ...) -> float: ... + @overload + def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... + @overload + def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... +else: + @overload + def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(__base: int, __exp: int, __mod: int) -> int: ... + @overload + def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... + @overload + def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... + @overload + def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... +def quit(code: object = ...) -> NoReturn: ... +if sys.version_info < (3,): + def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 + def raw_input(__prompt: Any = ...) -> str: ... + @overload + def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... + @overload + def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... + def reload(__module: Any) -> Any: ... +@overload +def reversed(__object: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(__object: Reversible[_T]) -> Iterator[_T]: ... +def repr(__obj: object) -> str: ... +if sys.version_info >= (3,): + @overload + def round(number: float) -> int: ... + @overload + def round(number: float, ndigits: None) -> int: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: None) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +else: + @overload + def round(number: float) -> float: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsFloat) -> float: ... + @overload + def round(number: SupportsFloat, ndigits: int) -> float: ... +def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... +if sys.version_info >= (3,): + @overload + def sorted(__iterable: Iterable[_LT], *, + key: None = ..., + reverse: bool = ...) -> List[_LT]: ... + @overload + def sorted(__iterable: Iterable[_T], *, + key: Callable[[_T], _SupportsLessThan], + reverse: bool = ...) -> List[_T]: ... +else: + def sorted(__iterable: Iterable[_T], *, + cmp: Callable[[_T, _T], int] = ..., + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ...) -> List[_T]: ... +if sys.version_info >= (3, 8): + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... +else: + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... +if sys.version_info < (3,): + def unichr(__i: int) -> unicode: ... +def vars(__object: Any = ...) -> Dict[str, Any]: ... +if sys.version_info >= (3,): + # Some overloads to better support zipping heterogeneous tuples + @overload + def zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3, _T4]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3, _T4, _T5]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...], Tuple[_T5, ...]]: ... # type: ignore + + @overload + def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], + __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +else: + @overload + def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... + @overload + def zip(__iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], + __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... +def __import__(name: Text, globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ...) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... +Ellipsis: ellipsis + +if sys.version_info < (3,): + # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. + _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) + + class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + if sys.version_info < (3,): + message: Any + if sys.version_info >= (3,): + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __suppress_context__: bool + __traceback__: Optional[TracebackType] + def __init__(self, *args: object) -> None: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + if sys.version_info < (3,): + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + if sys.version_info >= (3,): + def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... +class SystemExit(BaseException): + code: int +class Exception(BaseException): ... +class StopIteration(Exception): + if sys.version_info >= (3,): + value: Any +if sys.version_info >= (3,): + _StandardError = Exception + class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + EnvironmentError = OSError + IOError = OSError +else: + class StandardError(Exception): ... + _StandardError = StandardError + class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + class OSError(EnvironmentError): ... + class IOError(EnvironmentError): ... + +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): + if sys.version_info >= (3, 3): + def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... + name: Optional[str] + path: Optional[str] +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... +if sys.version_info >= (3, 5): + class StopAsyncIteration(Exception): + value: Any +class SyntaxError(_StandardError): + msg: str + lineno: Optional[int] + offset: Optional[int] + text: Optional[str] + filename: Optional[str] +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... + +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... + +if sys.version_info >= (3, 6): + class ModuleNotFoundError(ImportError): ... + +class IndexError(LookupError): ... +class KeyError(LookupError): ... + +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int +if sys.version_info >= (3,): + class BlockingIOError(OSError): + characters_written: int + class ChildProcessError(OSError): ... + class ConnectionError(OSError): ... + class BrokenPipeError(ConnectionError): ... + class ConnectionAbortedError(ConnectionError): ... + class ConnectionRefusedError(ConnectionError): ... + class ConnectionResetError(ConnectionError): ... + class FileExistsError(OSError): ... + class FileNotFoundError(OSError): ... + class InterruptedError(OSError): ... + class IsADirectoryError(OSError): ... + class NotADirectoryError(OSError): ... + class PermissionError(OSError): ... + class ProcessLookupError(OSError): ... + class TimeoutError(OSError): ... + +class NotImplementedError(RuntimeError): ... +if sys.version_info >= (3, 5): + class RecursionError(RuntimeError): ... + +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... + +class UnicodeError(ValueError): ... +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeTranslateError(UnicodeError): ... + +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +if sys.version_info >= (3, 2): + class ResourceWarning(Warning): ... + +if sys.version_info < (3,): + class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> Optional[bool]: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/mypy/stdlib/bz2.pyi b/mypy/stdlib/bz2.pyi new file mode 100644 index 000000000000..ce55ca7fee57 --- /dev/null +++ b/mypy/stdlib/bz2.pyi @@ -0,0 +1,76 @@ +import io +import sys +from typing import IO, Any, Optional, TextIO, Union, overload, TypeVar +from _typeshed import AnyPath +from typing_extensions import Literal + +_PathOrFile = Union[AnyPath, 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]: ... + +class BZ2File(io.BufferedIOBase, IO[bytes]): + def __enter__(self: _T) -> _T: ... + if sys.version_info >= (3, 9): + def __init__(self, + filename: _PathOrFile, + mode: str = ..., + *, + compresslevel: int = ...) -> None: ... + else: + def __init__(self, + filename: _PathOrFile, + mode: str = ..., + buffering: Optional[Any] = ..., + compresslevel: int = ...) -> None: ... + +class BZ2Compressor(object): + def __init__(self, compresslevel: int = ...) -> None: ... + def compress(self, data: bytes) -> bytes: ... + 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: ... + @property + def unused_data(self) -> bytes: ... diff --git a/mypy/stdlib/cProfile.pyi b/mypy/stdlib/cProfile.pyi new file mode 100644 index 000000000000..43b21229babb --- /dev/null +++ b/mypy/stdlib/cProfile.pyi @@ -0,0 +1,24 @@ +import sys +from _typeshed import AnyPath +from typing import Any, Callable, Dict, Optional, 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') + +class Profile: + 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: AnyPath) -> 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: ... + if sys.version_info >= (3, 8): + def __enter__(self: _SelfT) -> _SelfT: ... + def __exit__(self, *exc_info: Any) -> None: ... diff --git a/mypy/stdlib/calendar.pyi b/mypy/stdlib/calendar.pyi new file mode 100644 index 000000000000..4b452cc334b9 --- /dev/null +++ b/mypy/stdlib/calendar.pyi @@ -0,0 +1,122 @@ +import datetime +import sys +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: + 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]]: ... + if sys.version_info >= (3, 7): + def itermonthdays3(self, year: int, month: int) -> Iterable[Tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Iterable[Tuple[int, int, int, 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: ... + if sys.version_info >= (3, 7): + cssclasses: List[str] + cssclass_noday: str + cssclasses_weekday_head: List[str] + cssclass_month_head: str + cssclass_month: str + cssclass_year: str + cssclass_year_head: str + +if sys.version_info < (3, 0): + class TimeEncoding: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> _LocaleType: ... + def __exit__(self, *args: Any) -> None: ... +else: + 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: ... + 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/stdlib/cgi.pyi b/mypy/stdlib/cgi.pyi new file mode 100644 index 000000000000..1f69efe3f163 --- /dev/null +++ b/mypy/stdlib/cgi.pyi @@ -0,0 +1,126 @@ +import sys +from typing import Any, AnyStr, Dict, IO, Iterator, List, Mapping, Optional, Tuple, TypeVar, Union + +_T = TypeVar('_T', bound=FieldStorage) + +def parse(fp: Optional[IO[Any]] = ..., environ: Mapping[str, str] = ..., + keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... +if sys.version_info < (3, 8): + def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... + def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... +if sys.version_info >= (3, 7): + def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes], encoding: str = ..., errors: str = ...) -> Dict[str, List[Any]]: ... +else: + def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes]) -> Dict[str, List[bytes]]: ... +def parse_header(line: str) -> Tuple[str, Dict[str, str]]: ... +def test(environ: Mapping[str, str] = ...) -> None: ... +def print_environ(environ: Mapping[str, str] = ...) -> None: ... +def print_form(form: Dict[str, Any]) -> None: ... +def print_directory() -> None: ... +def print_environ_usage() -> None: ... +if sys.version_info < (3,): + def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... +elif sys.version_info < (3, 8): + def escape(s: str, quote: Optional[bool] = ...) -> str: ... + +class MiniFieldStorage: + # The first five "Any" attributes here are always None, but mypy doesn't support that + filename: Any + list: Any + type: Any + file: Optional[IO[bytes]] + type_options: Dict[Any, Any] + disposition: Any + disposition_options: Dict[Any, Any] + headers: Dict[Any, Any] + name: Any + value: Any + + def __init__(self, name: Any, value: Any) -> None: ... + def __repr__(self) -> str: ... + + +class FieldStorage(object): + FieldStorageClass: Optional[type] + keep_blank_values: int + strict_parsing: int + qs_on_post: Optional[str] + headers: Mapping[str, str] + fp: IO[bytes] + encoding: str + errors: str + outerboundary: bytes + bytes_read: int + limit: Optional[int] + disposition: str + disposition_options: Dict[str, str] + filename: Optional[str] + file: Optional[IO[bytes]] + type: str + type_options: Dict[str, str] + innerboundary: bytes + length: int + done: int + list: Optional[List[Any]] + value: Union[None, bytes, List[Any]] + + if sys.version_info >= (3, 6): + def __init__(self, fp: Optional[IO[Any]] = ..., headers: Optional[Mapping[str, str]] = ..., outerboundary: bytes = ..., + environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ..., + limit: Optional[int] = ..., encoding: str = ..., errors: str = ..., max_num_fields: Optional[int] = ...) -> None: ... + elif sys.version_info >= (3, 0): + def __init__(self, fp: Optional[IO[Any]] = ..., headers: Optional[Mapping[str, str]] = ..., outerboundary: bytes = ..., + environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ..., + limit: Optional[int] = ..., encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, fp: IO[Any] = ..., headers: Mapping[str, str] = ..., outerboundary: bytes = ..., + environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... + + if sys.version_info >= (3, 0): + def __enter__(self: _T) -> _T: ... + def __exit__(self, *args: Any) -> None: ... + def __repr__(self) -> str: ... + def __iter__(self) -> Iterator[str]: ... + def __getitem__(self, key: str) -> Any: ... + def getvalue(self, key: str, default: Any = ...) -> Any: ... + def getfirst(self, key: str, default: Any = ...) -> Any: ... + def getlist(self, key: str) -> List[Any]: ... + def keys(self) -> List[str]: ... + if sys.version_info < (3, 0): + def has_key(self, key: str) -> bool: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + if sys.version_info >= (3, 0): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + if sys.version_info >= (3, 0): + # In Python 3 it returns bytes or str IO depending on an internal flag + def make_file(self) -> IO[Any]: ... + else: + # In Python 2 it always returns bytes and ignores the "binary" flag + def make_file(self, binary: Any = ...) -> IO[bytes]: ... + + +if sys.version_info < (3, 0): + from UserDict import UserDict + + class FormContentDict(UserDict[str, List[str]]): + query_string: str + def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... + + class SvFormContentDict(FormContentDict): + def getlist(self, key: Any) -> Any: ... + + class InterpFormContentDict(SvFormContentDict): ... + + class FormContent(FormContentDict): + # TODO this should have + # def values(self, key: Any) -> Any: ... + # but this is incompatible with the supertype, and adding '# type: ignore' triggers + # a parse error in pytype (https://github.com/google/pytype/issues/53) + def indexed_value(self, key: Any, location: int) -> Any: ... + def value(self, key: Any) -> Any: ... + def length(self, key: Any) -> int: ... + def stripped(self, key: Any) -> Any: ... + def pars(self) -> Dict[Any, Any]: ... diff --git a/mypy/stdlib/cgitb.pyi b/mypy/stdlib/cgitb.pyi new file mode 100644 index 000000000000..a20c58a210c2 --- /dev/null +++ b/mypy/stdlib/cgitb.pyi @@ -0,0 +1,23 @@ +from typing import Dict, Any, List, Tuple, Optional, Callable, Type, IO +from types import FrameType, TracebackType +from _typeshed import AnyPath + +_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[AnyPath] = ..., 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[AnyPath] = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/mypy/stdlib/chunk.pyi b/mypy/stdlib/chunk.pyi new file mode 100644 index 000000000000..2337f00cafe1 --- /dev/null +++ b/mypy/stdlib/chunk.pyi @@ -0,0 +1,23 @@ +# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/chunk.py +# Source(py3): https://github.com/python/cpython/blob/master/Lib/chunk.py + +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/stdlib/cmath.pyi b/mypy/stdlib/cmath.pyi new file mode 100644 index 000000000000..97651b324e8e --- /dev/null +++ b/mypy/stdlib/cmath.pyi @@ -0,0 +1,42 @@ +"""Stub file for the 'cmath' module.""" + +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 + +_C = Union[SupportsFloat, SupportsComplex] + +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: ... +if sys.version_info >= (3, 5): + 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: ... +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: ... + +if sys.version_info >= (3,): + def isfinite(__z: _C) -> bool: ... diff --git a/mypy/stdlib/cmd.pyi b/mypy/stdlib/cmd.pyi new file mode 100644 index 000000000000..b8a61e4af951 --- /dev/null +++ b/mypy/stdlib/cmd.pyi @@ -0,0 +1,41 @@ +# Stubs for cmd (Python 2/3) + +from typing import Any, Optional, Text, IO, List, Callable, 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/stdlib/code.pyi b/mypy/stdlib/code.pyi new file mode 100644 index 000000000000..293ab9b98b61 --- /dev/null +++ b/mypy/stdlib/code.pyi @@ -0,0 +1,38 @@ +# Stubs for code + +import sys +from typing import Any, Callable, Mapping, Optional +from types import CodeType + +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: ... + 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 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 compile_command(source: str, filename: str = ..., + symbol: str = ...) -> Optional[CodeType]: ... diff --git a/mypy/stdlib/codecs.pyi b/mypy/stdlib/codecs.pyi new file mode 100644 index 000000000000..e98dee161ec6 --- /dev/null +++ b/mypy/stdlib/codecs.pyi @@ -0,0 +1,277 @@ +import sys +from typing import Any, BinaryIO, Callable, Generator, IO, Iterable, Iterator, List, Optional, Protocol, Text, TextIO, Tuple, Type, TypeVar, Union, overload + +from abc import abstractmethod +import types +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(__obj: _Encoded, __errors: str = ..., __final: bool = ...) -> Tuple[_Decoded, int]: ... # undocumented +def utf_16_be_encode(__obj: _Decoded, __errors: 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 __init__( + self, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader = ..., + streamwriter: _StreamWriter = ..., + incrementalencoder: _IncrementalEncoder = ..., + incrementaldecoder: _IncrementalDecoder = ..., + name: str = ..., + ) -> None: ... + +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: str = ..., errors: str = ..., buffering: int = ...) -> StreamReaderWriter: ... +def EncodedFile(file: IO[_Encoded], data_encoding: str, file_encoding: 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(name: str, error_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, object: _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, object: _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, object: _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, obj: _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) -> 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: int = ..., keepends: bool = ...) -> _Decoded: ... + def readlines(self, sizehint: 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) -> 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]: ... + if sys.version_info >= (3,): + def __next__(self) -> Text: ... + else: + 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]: ... + if sys.version_info >= (3,): + def __next__(self) -> bytes: ... + else: + 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/stdlib/codeop.pyi b/mypy/stdlib/codeop.pyi new file mode 100644 index 000000000000..0e1129e678d4 --- /dev/null +++ b/mypy/stdlib/codeop.pyi @@ -0,0 +1,17 @@ +# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/codeop.py +# Source(py3): https://github.com/python/cpython/blob/master/Lib/codeop.py + +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/stdlib/collections/__init__.pyi b/mypy/stdlib/collections/__init__.pyi new file mode 100644 index 000000000000..17309d3ca3fd --- /dev/null +++ b/mypy/stdlib/collections/__init__.pyi @@ -0,0 +1,343 @@ +# These are not exported. +import sys +import typing +from typing import ( + TypeVar, Generic, Dict, overload, List, Tuple, + Any, Type, Optional, Union +) +# These are exported. +from . import abc + +from typing import ( + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + Callable as Callable, + Container as Container, + Coroutine as Coroutine, + Hashable as Hashable, + Iterable as Iterable, + Iterator as Iterator, + Sized as Sized, + Generator as Generator, + ByteString as ByteString, + Reversible as Reversible, + Mapping as Mapping, + MappingView as MappingView, + ItemsView as ItemsView, + KeysView as KeysView, + ValuesView as ValuesView, + MutableMapping as MutableMapping, + Sequence as Sequence, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + AbstractSet as Set, +) +if sys.version_info >= (3, 6): + from typing import ( + Collection as Collection, + AsyncGenerator as AsyncGenerator, + ) + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + + +# namedtuple is special-cased in the type checker; the initializer is ignored. +if sys.version_info >= (3, 7): + def namedtuple( + typename: str, + field_names: Union[str, Iterable[str]], + *, + rename: bool = ..., + module: Optional[str] = ..., + defaults: Optional[Iterable[Any]] = ..., + ) -> Type[Tuple[Any, ...]]: ... +elif sys.version_info >= (3, 6): + def namedtuple( + typename: str, + field_names: Union[str, Iterable[str]], + *, + verbose: bool = ..., + rename: bool = ..., + module: Optional[str] = ..., + ) -> Type[Tuple[Any, ...]]: ... +else: + def namedtuple( + typename: str, field_names: Union[str, Iterable[str]], verbose: bool = ..., rename: bool = ..., + ) -> Type[Tuple[Any, ...]]: ... + +class UserDict(MutableMapping[_KT, _VT]): + data: Dict[_KT, _VT] + def __init__(self, dict: Optional[Mapping[_KT, _VT]] = ..., **kwargs: _VT) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, item: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __contains__(self, key: object) -> bool: ... + def copy(self: _S) -> _S: ... + @classmethod + def fromkeys(cls: Type[_S], iterable: Iterable[_KT], value: Optional[_VT] = ...) -> _S: ... + +class UserList(MutableSequence[_T]): + data: List[_T] + def __init__(self, initlist: Optional[Iterable[_T]] = ...) -> None: ... + def __lt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, i: slice) -> MutableSequence[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self: _S, other: Iterable[_T]) -> _S: ... + def __iadd__(self: _S, other: Iterable[_T]) -> _S: ... + def __mul__(self: _S, n: int) -> _S: ... + def __imul__(self: _S, n: int) -> _S: ... + def append(self, item: _T) -> None: ... + def insert(self, i: int, item: _T) -> None: ... + def pop(self, i: int = ...) -> _T: ... + def remove(self, item: _T) -> None: ... + def clear(self) -> None: ... + def copy(self: _S) -> _S: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T, *args: Any) -> int: ... + def reverse(self) -> None: ... + def sort(self, *args: Any, **kwds: Any) -> None: ... + def extend(self, other: Iterable[_T]) -> None: ... + +_UserStringT = TypeVar('_UserStringT', bound=UserString) + +class UserString(Sequence[str]): + data: str + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + def __getnewargs__(self) -> Tuple[str]: ... + def __lt__(self, string: Union[str, UserString]) -> bool: ... + def __le__(self, string: Union[str, UserString]) -> bool: ... + def __gt__(self, string: Union[str, UserString]) -> bool: ... + def __ge__(self, string: Union[str, UserString]) -> bool: ... + def __contains__(self, char: object) -> bool: ... + def __len__(self) -> int: ... + # It should return a str to implement Sequence correctly, but it doesn't. + def __getitem__(self: _UserStringT, i: Union[int, slice]) -> _UserStringT: ... # type: ignore + def __add__(self: _UserStringT, other: object) -> _UserStringT: ... + def __mul__(self: _UserStringT, n: int) -> _UserStringT: ... + def __mod__(self: _UserStringT, args: Any) -> _UserStringT: ... + def capitalize(self: _UserStringT) -> _UserStringT: ... + def casefold(self: _UserStringT) -> _UserStringT: ... + def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def count(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UserStringT: ... + def endswith(self, suffix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... + def find(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def format(self, *args: Any, **kwds: Any) -> str: ... + def format_map(self, mapping: Mapping[str, Any]) -> str: ... + def index(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, seq: Iterable[str]) -> str: ... + def ljust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def lower(self: _UserStringT) -> _UserStringT: ... + def lstrip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + @staticmethod + @overload + def maketrans(x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(x: str, y: str, z: str = ...) -> Dict[int, Union[int, None]]: ... + def partition(self, sep: str) -> Tuple[str, str, str]: ... + if sys.version_info >= (3, 9): + def removeprefix(self: _UserStringT, __prefix: Union[str, UserString]) -> _UserStringT: ... + def removesuffix(self: _UserStringT, __suffix: Union[str, UserString]) -> _UserStringT: ... + def replace(self: _UserStringT, old: Union[str, UserString], new: Union[str, UserString], maxsplit: int = ...) -> _UserStringT: ... + def rfind(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + def rstrip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + def startswith(self, prefix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def strip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + def swapcase(self: _UserStringT) -> _UserStringT: ... + def title(self: _UserStringT) -> _UserStringT: ... + def translate(self: _UserStringT, *args: Any) -> _UserStringT: ... + def upper(self: _UserStringT) -> _UserStringT: ... + def zfill(self: _UserStringT, width: int) -> _UserStringT: ... + + +# Technically, deque only derives from MutableSequence in 3.5 (before then, the insert and index +# methods did not exist). +# But in practice it's not worth losing sleep over. +class deque(MutableSequence[_T], Generic[_T]): + @property + def maxlen(self) -> Optional[int]: ... + def __init__(self, iterable: Iterable[_T] = ..., + maxlen: Optional[int] = ...) -> None: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> deque[_T]: ... + def count(self, x: _T) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def extendleft(self, iterable: Iterable[_T]) -> None: ... + def insert(self, i: int, x: _T) -> None: ... + def index(self, x: _T, start: int = ..., stop: int = ...) -> int: ... + def pop(self, i: int = ...) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + + # These methods of deque don't really take slices, but we need to + # define them as taking a slice to satisfy MutableSequence. + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + def __setitem__(self, i: int, x: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + def __delitem__(self, i: int) -> None: ... + @overload + def __delitem__(self, s: slice) -> None: ... + + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + + def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + + def __add__(self, other: deque[_T]) -> deque[_T]: ... + def __mul__(self, other: int) -> deque[_T]: ... + def __imul__(self, other: int) -> None: ... + +class Counter(Dict[_T, int], Generic[_T]): + @overload + def __init__(self, __iterable: None = ..., **kwargs: int) -> None: ... + @overload + def __init__(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def __init__(self, __iterable: Iterable[_T]) -> None: ... + def copy(self: _S) -> _S: ... + def elements(self) -> Iterator[_T]: ... + + def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... + + @overload + def subtract(self, __iterable: None = ...) -> None: ... + @overload + def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def subtract(self, __iterable: Iterable[_T]) -> None: ... + + # The Iterable[Tuple[...]] argument type is not actually desirable + # (the tuples will be added as keys, breaking type safety) but + # it's included so that the signature is compatible with + # Dict.update. Not sure if we should use '# type: ignore' instead + # and omit the type from the union. + @overload + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + @overload + def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... + @overload + def update(self, __m: None = ..., **kwargs: int) -> None: ... + + def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __pos__(self) -> Counter[_T]: ... + def __neg__(self) -> Counter[_T]: ... + def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... + def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + +class _OrderedDictKeysView(KeysView[_KT], Reversible[_KT]): + def __reversed__(self) -> Iterator[_KT]: ... +class _OrderedDictItemsView(ItemsView[_KT, _VT], Reversible[Tuple[_KT, _VT]]): + def __reversed__(self) -> Iterator[Tuple[_KT, _VT]]: ... +class _OrderedDictValuesView(ValuesView[_VT], Reversible[_VT]): + def __reversed__(self) -> Iterator[_VT]: ... + +class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... + def move_to_end(self, key: _KT, last: bool = ...) -> None: ... + def copy(self: _S) -> _S: ... + def __reversed__(self) -> Iterator[_KT]: ... + def keys(self) -> _OrderedDictKeysView[_KT]: ... + def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... + def values(self) -> _OrderedDictValuesView[_VT]: ... + +class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + default_factory: Optional[Callable[[], _VT]] + + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + # TODO __reversed__ + def copy(self: _S) -> _S: ... + +class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ... + + @property + def maps(self) -> List[Mapping[_KT, _VT]]: ... + + def new_child(self, m: Mapping[_KT, _VT] = ...) -> typing.ChainMap[_KT, _VT]: ... + + @property + def parents(self) -> typing.ChainMap[_KT, _VT]: ... + + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... diff --git a/mypy/stdlib/collections/abc.pyi b/mypy/stdlib/collections/abc.pyi new file mode 100644 index 000000000000..11718438832b --- /dev/null +++ b/mypy/stdlib/collections/abc.pyi @@ -0,0 +1,36 @@ +# Stubs for collections.abc (introduced from Python 3.3) +# +# https://docs.python.org/3.3/whatsnew/3.3.html#collections +import sys + +from . import ( + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + ByteString as ByteString, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Hashable as Hashable, + Iterable as Iterable, + Iterator as Iterator, + Sized as Sized, + Callable as Callable, + Mapping as Mapping, + MutableMapping as MutableMapping, + Sequence as Sequence, + MutableSequence as MutableSequence, + Set as Set, + MutableSet as MutableSet, + MappingView as MappingView, + ItemsView as ItemsView, + KeysView as KeysView, + ValuesView as ValuesView, +) + +if sys.version_info >= (3, 6): + from . import ( + Collection as Collection, + Reversible as Reversible, + AsyncGenerator as AsyncGenerator, + ) diff --git a/mypy/stdlib/colorsys.pyi b/mypy/stdlib/colorsys.pyi new file mode 100644 index 000000000000..c8b5591879f6 --- /dev/null +++ b/mypy/stdlib/colorsys.pyi @@ -0,0 +1,15 @@ +# Stubs for colorsys + +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/stdlib/compileall.pyi b/mypy/stdlib/compileall.pyi new file mode 100644 index 000000000000..3be83d5ccd1a --- /dev/null +++ b/mypy/stdlib/compileall.pyi @@ -0,0 +1,109 @@ +import sys +from _typeshed import AnyPath +from typing import Any, Optional, Pattern + +if sys.version_info < (3, 6): + _SuccessType = bool +else: + _SuccessType = int + +if sys.version_info >= (3, 7): + from py_compile import PycInvalidationMode + +if sys.version_info >= (3, 9): + def compile_dir( + dir: AnyPath, + maxlevels: Optional[int] = ..., + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + workers: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + *, + stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved + prependdir: Optional[AnyPath] = ..., + limit_sl_dest: Optional[AnyPath] = ..., + ) -> _SuccessType: ... + def compile_file( + fullname: AnyPath, + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + *, + stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved + prependdir: Optional[AnyPath] = ..., + limit_sl_dest: Optional[AnyPath] = ..., + ) -> _SuccessType: ... +elif sys.version_info >= (3, 7): + def compile_dir( + dir: AnyPath, + maxlevels: int = ..., + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + workers: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + ) -> _SuccessType: ... + def compile_file( + fullname: AnyPath, + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + ) -> _SuccessType: ... + +else: + # rx can be any object with a 'search' method; once we have Protocols we can change the type + def compile_dir( + dir: AnyPath, + maxlevels: int = ..., + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + workers: int = ..., + ) -> _SuccessType: ... + def compile_file( + fullname: AnyPath, + ddir: Optional[AnyPath] = ..., + force: bool = ..., + rx: Optional[Pattern[Any]] = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + ) -> _SuccessType: ... + +if sys.version_info >= (3, 7): + def compile_path( + skip_curdir: bool = ..., + maxlevels: int = ..., + force: bool = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + ) -> _SuccessType: ... +else: + def compile_path( + skip_curdir: bool = ..., + maxlevels: int = ..., + force: bool = ..., + quiet: int = ..., + legacy: bool = ..., + optimize: int = ..., + ) -> _SuccessType: ... diff --git a/mypy/stdlib/concurrent/__init__.pyi b/mypy/stdlib/concurrent/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/concurrent/futures/__init__.pyi b/mypy/stdlib/concurrent/futures/__init__.pyi new file mode 100644 index 000000000000..9dfe12bac79e --- /dev/null +++ b/mypy/stdlib/concurrent/futures/__init__.pyi @@ -0,0 +1,18 @@ +import sys +from ._base import ( + FIRST_COMPLETED as FIRST_COMPLETED, + FIRST_EXCEPTION as FIRST_EXCEPTION, + ALL_COMPLETED as ALL_COMPLETED, + CancelledError as CancelledError, + TimeoutError as TimeoutError, + Future as Future, + Executor as Executor, + wait as wait, + as_completed as as_completed, +) +if sys.version_info >= (3, 8): + from ._base import InvalidStateError as InvalidStateError +if sys.version_info >= (3, 7): + from ._base import BrokenExecutor as BrokenExecutor +from .thread import ThreadPoolExecutor as ThreadPoolExecutor +from .process import ProcessPoolExecutor as ProcessPoolExecutor diff --git a/mypy/stdlib/concurrent/futures/_base.pyi b/mypy/stdlib/concurrent/futures/_base.pyi new file mode 100644 index 000000000000..27caf7c3ccff --- /dev/null +++ b/mypy/stdlib/concurrent/futures/_base.pyi @@ -0,0 +1,102 @@ +import threading +from logging import Logger +from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Tuple, Optional, Set, List +from types import TracebackType +import sys + +FIRST_COMPLETED: str +FIRST_EXCEPTION: str +ALL_COMPLETED: str +PENDING: str +RUNNING: str +CANCELLED: str +CANCELLED_AND_NOTIFIED: str +FINISHED: str +LOGGER: Logger + +class Error(Exception): ... +class CancelledError(Error): ... +class TimeoutError(Error): ... +if sys.version_info >= (3, 8): + class InvalidStateError(Error): ... + +if sys.version_info >= (3, 7): + class BrokenExecutor(RuntimeError): ... + +_T = TypeVar('_T') + +class Future(Generic[_T]): + def __init__(self) -> None: ... + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def running(self) -> bool: ... + def done(self) -> bool: ... + def add_done_callback(self, fn: Callable[[Future[_T]], Any]) -> None: ... + def result(self, timeout: Optional[float] = ...) -> _T: ... + def set_running_or_notify_cancel(self) -> bool: ... + def set_result(self, result: _T) -> None: ... + + if sys.version_info >= (3,): + def exception(self, timeout: Optional[float] = ...) -> Optional[BaseException]: ... + def set_exception(self, exception: Optional[BaseException]) -> None: ... + else: + def exception(self, timeout: Optional[float] = ...) -> Any: ... + def exception_info(self, timeout: Optional[float] = ...) -> Tuple[Any, Optional[TracebackType]]: ... + def set_exception(self, exception: Any) -> None: ... + def set_exception_info(self, exception: Any, traceback: Optional[TracebackType]) -> None: ... + + +class Executor: + def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + if sys.version_info >= (3, 5): + def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ..., + chunksize: int = ...) -> Iterator[_T]: ... + else: + def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ...,) -> Iterator[_T]: ... + def shutdown(self, wait: bool = ...) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Optional[bool]: ... + +def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... + +def wait(fs: Iterable[Future[_T]], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future[_T]], + Set[Future[_T]]]: ... + +class _Waiter: + event: threading.Event + finished_futures: List[Future[Any]] + def __init__(self) -> None: ... + def add_result(self, future: Future[Any]) -> None: ... + def add_exception(self, future: Future[Any]) -> None: ... + def add_cancelled(self, future: Future[Any]) -> None: ... + + +class _AsCompletedWaiter(_Waiter): + lock: threading.Lock + def __init__(self) -> None: ... + def add_result(self, future: Future[Any]) -> None: ... + def add_exception(self, future: Future[Any]) -> None: ... + def add_cancelled(self, future: Future[Any]) -> None: ... + + +class _FirstCompletedWaiter(_Waiter): + def add_result(self, future: Future[Any]) -> None: ... + def add_exception(self, future: Future[Any]) -> None: ... + def add_cancelled(self, future: Future[Any]) -> None: ... + + +class _AllCompletedWaiter(_Waiter): + num_pending_calls: int + stop_on_exception: bool + lock: threading.Lock + def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ... + def add_result(self, future: Future[Any]) -> None: ... + def add_exception(self, future: Future[Any]) -> None: ... + def add_cancelled(self, future: Future[Any]) -> None: ... + + +class _AcquireFutures: + futures: Iterable[Future[Any]] + def __init__(self, futures: Iterable[Future[Any]]) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *args: Any) -> None: ... diff --git a/mypy/stdlib/concurrent/futures/process.pyi b/mypy/stdlib/concurrent/futures/process.pyi new file mode 100644 index 000000000000..960a59f50f0d --- /dev/null +++ b/mypy/stdlib/concurrent/futures/process.pyi @@ -0,0 +1,23 @@ +from typing import Any, Callable, Optional, Tuple +from ._base import Executor +import sys + +EXTRA_QUEUED_CALLS: Any + +if sys.version_info >= (3, 7): + from ._base import BrokenExecutor + class BrokenProcessPool(BrokenExecutor): ... +elif sys.version_info >= (3,): + class BrokenProcessPool(RuntimeError): ... + +if sys.version_info >= (3, 7): + from multiprocessing.context import BaseContext + + class ProcessPoolExecutor(Executor): + def __init__(self, max_workers: Optional[int] = ..., + mp_context: Optional[BaseContext] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Tuple[Any, ...] = ...) -> None: ... +else: + class ProcessPoolExecutor(Executor): + def __init__(self, max_workers: Optional[int] = ...) -> None: ... diff --git a/mypy/stdlib/concurrent/futures/thread.pyi b/mypy/stdlib/concurrent/futures/thread.pyi new file mode 100644 index 000000000000..82c8ddd03d94 --- /dev/null +++ b/mypy/stdlib/concurrent/futures/thread.pyi @@ -0,0 +1,30 @@ +from typing import Any, Callable, Iterable, Mapping, Optional, Tuple, TypeVar, Generic +from ._base import Executor, Future +import sys + +if sys.version_info >= (3, 7): + from ._base import BrokenExecutor + class BrokenThreadPool(BrokenExecutor): ... + +_S = TypeVar('_S') + +class ThreadPoolExecutor(Executor): + if sys.version_info >= (3, 7): + def __init__(self, max_workers: Optional[int] = ..., + thread_name_prefix: str = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Tuple[Any, ...] = ...) -> None: ... + elif sys.version_info >= (3, 6) or sys.version_info < (3,): + def __init__(self, max_workers: Optional[int] = ..., + thread_name_prefix: str = ...) -> None: ... + else: + def __init__(self, max_workers: Optional[int] = ...) -> None: ... + + +class _WorkItem(Generic[_S]): + future: Future[_S] + fn: Callable[..., _S] + args: Iterable[Any] + kwargs: Mapping[str, Any] + def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + def run(self) -> None: ... diff --git a/mypy/stdlib/configparser.pyi b/mypy/stdlib/configparser.pyi new file mode 100644 index 000000000000..93a6393bdd02 --- /dev/null +++ b/mypy/stdlib/configparser.pyi @@ -0,0 +1,243 @@ +from _typeshed import AnyPath, StrPath +import sys +from typing import (AbstractSet, MutableMapping, Mapping, Dict, Sequence, List, + Union, Iterable, Iterator, Callable, Any, IO, overload, + Optional, Pattern, Type, TypeVar, ClassVar, Tuple) + +# Internal type aliases +_section = Mapping[str, str] +_parser = MutableMapping[str, _section] +_converter = Callable[[str], Any] +_converters = Dict[str, _converter] +_T = TypeVar('_T') + +if sys.version_info >= (3, 7): + _Path = AnyPath +else: + _Path = StrPath + +DEFAULTSECT: str +MAX_INTERPOLATION_DEPTH: int + +class Interpolation: + def before_get(self, parser: _parser, + section: str, + option: str, + value: str, + defaults: _section) -> str: ... + + def before_set(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + def before_read(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + def before_write(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + +class BasicInterpolation(Interpolation): ... +class ExtendedInterpolation(Interpolation): ... +class LegacyInterpolation(Interpolation): ... + + +class RawConfigParser(_parser): + BOOLEAN_STATES: ClassVar[Mapping[str, bool]] = ... # Undocumented + def __init__(self, + defaults: Optional[_section] = ..., + dict_type: Type[Mapping[str, str]] = ..., + allow_no_value: bool = ..., + *, + delimiters: Sequence[str] = ..., + comment_prefixes: Sequence[str] = ..., + inline_comment_prefixes: Optional[Sequence[str]] = ..., + strict: bool = ..., + empty_lines_in_values: bool = ..., + default_section: str = ..., + interpolation: Optional[Interpolation] = ..., + converters: _converters = ...) -> None: ... + + def __len__(self) -> int: ... + + def __getitem__(self, section: str) -> SectionProxy: ... + + def __setitem__(self, section: str, options: _section) -> None: ... + + def __delitem__(self, section: str) -> None: ... + + def __iter__(self) -> Iterator[str]: ... + + def defaults(self) -> _section: ... + + def sections(self) -> List[str]: ... + + def add_section(self, section: str) -> None: ... + + def has_section(self, section: str) -> bool: ... + + def options(self, section: str) -> List[str]: ... + + def has_option(self, section: str, option: str) -> bool: ... + + def read(self, filenames: Union[_Path, Iterable[_Path]], + encoding: Optional[str] = ...) -> List[str]: ... + def read_file(self, f: Iterable[str], source: Optional[str] = ...) -> None: ... + def read_string(self, string: str, source: str = ...) -> None: ... + def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], + source: str = ...) -> None: ... + def readfp(self, fp: Iterable[str], filename: Optional[str] = ...) -> None: ... + + # These get* methods are partially applied (with the same names) in + # SectionProxy; the stubs should be kept updated together + + @overload + def getint(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> int: ... + @overload + def getint(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[int, _T]: ... + @overload + def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> float: ... + @overload + def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[float, _T]: ... + @overload + def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> bool: ... + @overload + def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[bool, _T]: ... + + def _get_conv(self, section: str, option: str, conv: Callable[[str], _T], *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> _T: ... + + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore + def get(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> str: ... + + @overload + def get(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T) -> Union[str, _T]: ... + + @overload + def items(self, *, raw: bool = ..., vars: Optional[_section] = ...) -> AbstractSet[Tuple[str, SectionProxy]]: ... + + @overload + def items(self, section: str, raw: bool = ..., vars: Optional[_section] = ...) -> List[Tuple[str, str]]: ... + + def set(self, section: str, option: str, value: Optional[str] = ...) -> None: ... + + def write(self, fp: IO[str], space_around_delimiters: bool = ...) -> None: ... + + def remove_option(self, section: str, option: str) -> bool: ... + + def remove_section(self, section: str) -> bool: ... + + def optionxform(self, optionstr: str) -> str: ... + + +class ConfigParser(RawConfigParser): ... + +class SafeConfigParser(ConfigParser): ... + +class SectionProxy(MutableMapping[str, str]): + def __init__(self, parser: RawConfigParser, name: str) -> None: ... + def __getitem__(self, key: str) -> str: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + @property + def parser(self) -> RawConfigParser: ... + @property + def name(self) -> str: ... + def get(self, option: str, fallback: Optional[str] = ..., *, raw: bool = ..., vars: Optional[_section] = ..., _impl: Optional[Any] = ..., **kwargs: Any) -> str: ... # type: ignore + + # These are partially-applied version of the methods with the same names in + # RawConfigParser; the stubs should be kept updated together + @overload + def getint(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> int: ... + @overload + def getint(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[int, _T]: ... + @overload + def getfloat(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> float: ... + @overload + def getfloat(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[float, _T]: ... + @overload + def getboolean(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> bool: ... + @overload + def getboolean(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[bool, _T]: ... + + # SectionProxy can have arbitrary attributes when custon converters are used + def __getattr__(self, key: str) -> Callable[..., Any]: ... + +class ConverterMapping(MutableMapping[str, Optional[_converter]]): + GETTERCRE: Pattern[Any] + def __init__(self, parser: RawConfigParser) -> None: ... + def __getitem__(self, key: str) -> _converter: ... + def __setitem__(self, key: str, value: Optional[_converter]) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + + +class Error(Exception): + message: str + def __init__(self, msg: str = ...) -> None: ... + + +class NoSectionError(Error): + section: str + def __init__(self, section: str) -> None: ... + + +class DuplicateSectionError(Error): + section: str + source: Optional[str] + lineno: Optional[int] + def __init__(self, section: str, source: Optional[str] = ..., lineno: Optional[int] = ...) -> None: ... + + +class DuplicateOptionError(Error): + section: str + option: str + source: Optional[str] + lineno: Optional[int] + def __init__(self, section: str, option: str, source: Optional[str] = ..., lineno: Optional[str] = ...) -> None: ... + + +class NoOptionError(Error): + section: str + option: str + def __init__(self, option: str, section: str) -> None: ... + + +class InterpolationError(Error): + section: str + option: str + def __init__(self, option: str, section: str, msg: str) -> None: ... + + +class InterpolationDepthError(InterpolationError): + def __init__(self, option: str, section: str, rawval: object) -> None: ... + + +class InterpolationMissingOptionError(InterpolationError): + reference: str + def __init__(self, option: str, section: str, rawval: object, reference: str) -> None: ... + + +class InterpolationSyntaxError(InterpolationError): ... + + +class ParsingError(Error): + source: str + errors: List[Tuple[int, str]] + def __init__(self, source: Optional[str] = ..., filename: Optional[str] = ...) -> None: ... + def append(self, lineno: int, line: str) -> None: ... + + +class MissingSectionHeaderError(ParsingError): + lineno: int + line: str + def __init__(self, filename: str, lineno: int, line: str) -> None: ... diff --git a/mypy/stdlib/contextlib.pyi b/mypy/stdlib/contextlib.pyi new file mode 100644 index 000000000000..f0dec323908a --- /dev/null +++ b/mypy/stdlib/contextlib.pyi @@ -0,0 +1,109 @@ +# ContextManager aliased here for backwards compatibility; TODO eventually remove this +from typing import ( + Any, Callable, Generator, IO, Iterable, Iterator, Optional, Type, + Generic, TypeVar, overload +) +from types import TracebackType +import sys +from typing import ContextManager as ContextManager + +if sys.version_info >= (3, 5): + from typing import AsyncContextManager, AsyncIterator + +if sys.version_info >= (3, 6): + from typing import ContextManager as AbstractContextManager +if sys.version_info >= (3, 7): + from typing import AsyncContextManager as AbstractAsyncContextManager + +_T = TypeVar('_T') +_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], Generic[_T]): + def __call__(self, func: _F) -> _F: ... + def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]: ... +else: + class GeneratorContextManager(ContextManager[_T], Generic[_T]): + def __call__(self, func: _F) -> _F: ... + def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_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 closing(ContextManager[_T], Generic[_T]): + def __init__(self, thing: _T) -> 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[None]): + def __init__(self, new_target: Optional[IO[str]]) -> None: ... + +if sys.version_info >= (3, 5): + class redirect_stderr(ContextManager[None]): + def __init__(self, new_target: Optional[IO[str]]) -> None: ... + +if sys.version_info >= (3,): + class ContextDecorator: + def __call__(self, func: Callable[..., None]) -> Callable[..., ContextManager[None]]: ... + + _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 + + _S = TypeVar('_S', bound=AsyncExitStack) + + _ExitCoroFunc = Callable[[Optional[Type[BaseException]], + Optional[BaseException], + Optional[TracebackType]], Awaitable[bool]] + _CallbackCoroFunc = Callable[..., Awaitable[Any]] + _ACM_EF = TypeVar('_ACM_EF', AsyncContextManager[Any], _ExitCoroFunc) + + class AsyncExitStack(AsyncContextManager[AsyncExitStack]): + def __init__(self) -> None: ... + def enter_context(self, cm: ContextManager[_T]) -> _T: ... + def enter_async_context(self, cm: AsyncContextManager[_T]) -> Awaitable[_T]: ... + def push(self, exit: _CM_EF) -> _CM_EF: ... + def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... + def callback(self, callback: Callable[..., Any], + *args: Any, **kwds: Any) -> Callable[..., Any]: ... + def push_async_callback(self, callback: _CallbackCoroFunc, + *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... + def pop_all(self: _S) -> _S: ... + def aclose(self) -> Awaitable[None]: ... + def __aenter__(self: _S) -> Awaitable[_S]: ... + def __aexit__(self, __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType]) -> Awaitable[bool]: ... + +if sys.version_info >= (3, 7): + @overload + def nullcontext(enter_result: _T) -> ContextManager[_T]: ... + @overload + def nullcontext() -> ContextManager[None]: ... diff --git a/mypy/stdlib/contextvars.pyi b/mypy/stdlib/contextvars.pyi new file mode 100644 index 000000000000..a90c2a8b5f65 --- /dev/null +++ b/mypy/stdlib/contextvars.pyi @@ -0,0 +1,30 @@ +from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar + +_T = TypeVar('_T') + +class ContextVar(Generic[_T]): + def __init__(self, name: str, *, default: _T = ...) -> None: ... + @property + def name(self) -> str: ... + def get(self, default: _T = ...) -> _T: ... + def set(self, value: _T) -> Token[_T]: ... + def reset(self, token: Token[_T]) -> None: ... + +class Token(Generic[_T]): + @property + def var(self) -> ContextVar[_T]: ... + @property + def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express + MISSING: ClassVar[object] + +def copy_context() -> Context: ... + +# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have +# a different value. +class Context(Mapping[ContextVar[Any], Any]): + def __init__(self) -> None: ... + def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... + def copy(self) -> Context: ... + def __getitem__(self, key: ContextVar[Any]) -> Any: ... + def __iter__(self) -> Iterator[ContextVar[Any]]: ... + def __len__(self) -> int: ... diff --git a/mypy/stdlib/copy.pyi b/mypy/stdlib/copy.pyi new file mode 100644 index 000000000000..523802a84ee7 --- /dev/null +++ b/mypy/stdlib/copy.pyi @@ -0,0 +1,14 @@ +# Stubs for copy + +from typing import TypeVar, Optional, Dict, Any + +_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, _T]] = ..., _nil: Any = ...) -> _T: ... +def copy(x: _T) -> _T: ... +class Error(Exception): ... +error = Error diff --git a/mypy/stdlib/copyreg.pyi b/mypy/stdlib/copyreg.pyi new file mode 100644 index 000000000000..a64a82c700d0 --- /dev/null +++ b/mypy/stdlib/copyreg.pyi @@ -0,0 +1,14 @@ + +from typing import TypeVar, Callable, Union, Tuple, Any, Optional, SupportsInt, Hashable, List + + +_Type = TypeVar("_Type", bound=type) +_Reduce = Union[Tuple[Callable[..., _Type], Tuple[Any, ...]], Tuple[Callable[..., _Type], Tuple[Any, ...], Optional[Any]]] + +__all__: List[str] + +def pickle(ob_type: _Type, pickle_function: Callable[[_Type], Union[str, _Reduce[_Type]]], constructor_ob: Optional[Callable[[_Reduce[_Type]], _Type]] = ...) -> None: ... +def constructor(object: Callable[[_Reduce[_Type]], _Type]) -> 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/stdlib/crypt.pyi b/mypy/stdlib/crypt.pyi new file mode 100644 index 000000000000..621ce0bd7150 --- /dev/null +++ b/mypy/stdlib/crypt.pyi @@ -0,0 +1,22 @@ +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 + + methods: List[_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: ... +else: + def crypt(word: str, salt: str) -> str: ... diff --git a/mypy/stdlib/csv.pyi b/mypy/stdlib/csv.pyi new file mode 100644 index 000000000000..1181f231c18d --- /dev/null +++ b/mypy/stdlib/csv.pyi @@ -0,0 +1,101 @@ +import sys +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 collections import OrderedDict +from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Text, Type, Union + +_DictRow = Mapping[str, Any] + +class excel(Dialect): + delimiter: str + quotechar: str + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: int + +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 + +if sys.version_info >= (3, 8): + _DRMapping = Dict[str, str] +elif sys.version_info >= (3, 6): + _DRMapping = OrderedDict[str, str] +else: + _DRMapping = Dict[str, str] + +class DictReader(Iterator[_DRMapping]): + restkey: Optional[str] + restval: Optional[str] + reader: _reader + dialect: _DialectLike + line_num: int + fieldnames: Optional[Sequence[str]] + def __init__( + self, + f: Iterable[Text], + fieldnames: Optional[Sequence[str]] = ..., + restkey: Optional[str] = ..., + restval: Optional[str] = ..., + dialect: _DialectLike = ..., + *args: Any, + **kwds: Any, + ) -> None: ... + def __iter__(self) -> DictReader: ... + if sys.version_info >= (3,): + def __next__(self) -> _DRMapping: ... + else: + def next(self) -> _DRMapping: ... + +class DictWriter(object): + fieldnames: Sequence[str] + restval: Optional[Any] + extrasaction: str + writer: _writer + def __init__( + self, + f: Any, + fieldnames: Iterable[str], + restval: Optional[Any] = ..., + extrasaction: str = ..., + dialect: _DialectLike = ..., + *args: Any, + **kwds: Any, + ) -> None: ... + if sys.version_info >= (3, 8): + def writeheader(self) -> Any: ... + else: + def writeheader(self) -> None: ... + def writerow(self, rowdict: _DictRow) -> Any: ... + def writerows(self, rowdicts: Iterable[_DictRow]) -> 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/stdlib/ctypes/__init__.pyi b/mypy/stdlib/ctypes/__init__.pyi new file mode 100644 index 000000000000..d313e8463b0c --- /dev/null +++ b/mypy/stdlib/ctypes/__init__.pyi @@ -0,0 +1,292 @@ +# Stubs for ctypes + +from array import array +from typing import ( + Any, Callable, ClassVar, Iterator, Iterable, List, Mapping, Optional, Sequence, Sized, Text, + Tuple, Type, Generic, TypeVar, overload, +) +from typing import Union as _UnionT +import sys + +_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 = ..., + winmode: Optional[int] = ..., + ) -> None: ... + def __getattr__(self, name: str) -> _FuncPointer: ... + def __getitem__(self, name: str) -> _FuncPointer: ... +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, _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 _PointerLike(_CData): ... + +_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], None], 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 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: ... +_PT = TypeVar('_PT', bound=_PointerLike) +def cast(obj: _UnionT[_CData, _CArgObject], type: Type[_PT]) -> _PT: ... +def create_string_buffer(init_or_size: _UnionT[int, bytes], + size: Optional[int] = ...) -> Array[c_char]: ... +c_buffer = create_string_buffer +def create_unicode_buffer(init_or_size: _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: ... +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': + 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(_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/stdlib/ctypes/util.pyi b/mypy/stdlib/ctypes/util.pyi new file mode 100644 index 000000000000..7077d9d2f1e9 --- /dev/null +++ b/mypy/stdlib/ctypes/util.pyi @@ -0,0 +1,8 @@ +# Stubs for ctypes.util + +from typing import Optional +import sys + +def find_library(name: str) -> Optional[str]: ... +if sys.platform == 'win32': + def find_msvcrt() -> Optional[str]: ... diff --git a/mypy/stdlib/ctypes/wintypes.pyi b/mypy/stdlib/ctypes/wintypes.pyi new file mode 100644 index 000000000000..c5a6226b25c0 --- /dev/null +++ b/mypy/stdlib/ctypes/wintypes.pyi @@ -0,0 +1,209 @@ +from ctypes import ( + _SimpleCData, Array, Structure, 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/stdlib/curses/__init__.pyi b/mypy/stdlib/curses/__init__.pyi new file mode 100644 index 000000000000..be7362647b2b --- /dev/null +++ b/mypy/stdlib/curses/__init__.pyi @@ -0,0 +1,15 @@ +from _curses import * # noqa: F403 +from _curses import _CursesWindow as _CursesWindow +from typing import TypeVar, Callable, Any + +_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/stdlib/curses/ascii.pyi b/mypy/stdlib/curses/ascii.pyi new file mode 100644 index 000000000000..4033769252c8 --- /dev/null +++ b/mypy/stdlib/curses/ascii.pyi @@ -0,0 +1,62 @@ +from typing import List, Union, overload, TypeVar + +_Ch = TypeVar('_Ch', 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: _Ch) -> _Ch: ... +def ctrl(c: _Ch) -> _Ch: ... +def alt(c: _Ch) -> _Ch: ... +def unctrl(c: Union[str, int]) -> str: ... diff --git a/mypy/stdlib/curses/panel.pyi b/mypy/stdlib/curses/panel.pyi new file mode 100644 index 000000000000..138e4a9f727e --- /dev/null +++ b/mypy/stdlib/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/stdlib/curses/textpad.pyi b/mypy/stdlib/curses/textpad.pyi new file mode 100644 index 000000000000..d2b5766fda26 --- /dev/null +++ b/mypy/stdlib/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/stdlib/dataclasses.pyi b/mypy/stdlib/dataclasses.pyi new file mode 100644 index 000000000000..e0885932d09f --- /dev/null +++ b/mypy/stdlib/dataclasses.pyi @@ -0,0 +1,74 @@ +from typing import overload, Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar, Union + + +_T = TypeVar('_T') + +class _MISSING_TYPE: ... +MISSING: _MISSING_TYPE + +@overload +def asdict(obj: Any) -> Dict[str, Any]: ... +@overload +def asdict(obj: Any, *, dict_factory: Callable[[List[Tuple[str, Any]]], _T]) -> _T: ... + +@overload +def astuple(obj: Any) -> Tuple[Any, ...]: ... +@overload +def astuple(obj: Any, *, tuple_factory: Callable[[List[Any]], _T]) -> _T: ... + + +@overload +def dataclass(_cls: Type[_T]) -> Type[_T]: ... + +@overload +def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + +@overload +def dataclass(*, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., + unsafe_hash: bool = ..., frozen: bool = ...) -> Callable[[Type[_T]], Type[_T]]: ... + + +class Field(Generic[_T]): + name: str + type: Type[_T] + default: _T + default_factory: Callable[[], _T] + repr: bool + hash: Optional[bool] + init: bool + compare: bool + metadata: Mapping[str, Any] + + +# 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: ... + + +def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... + +def is_dataclass(obj: Any) -> bool: ... + +class FrozenInstanceError(AttributeError): ... + +class InitVar(Generic[_T]): ... + +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/stdlib/datetime.pyi b/mypy/stdlib/datetime.pyi new file mode 100644 index 000000000000..e0ae3fa16aa2 --- /dev/null +++ b/mypy/stdlib/datetime.pyi @@ -0,0 +1,333 @@ +import sys +from time import struct_time +from typing import AnyStr, Optional, SupportsAbs, Tuple, Union, overload, ClassVar, Type, TypeVar + +_S = TypeVar("_S") + +if sys.version_info >= (3,): + _Text = str +else: + _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: ... + +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: ... + +_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: ... + if sys.version_info >= (3, 7): + @classmethod + def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... + if sys.version_info >= (3, 8): + @classmethod + def fromisocalendar(cls: Type[_S], year: int, week: int, day: 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: ... + if sys.version_info >= (3,): + def __format__(self, fmt: str) -> str: ... + else: + 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: ... + if sys.version_info >= (3, 8): + def __add__(self: _S, other: timedelta) -> _S: ... + def __radd__(self: _S, other: timedelta) -> _S: ... + else: + 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] + + 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: ... + + @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]: ... + if sys.version_info >= (3, 6): + @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: ... + 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 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: ... + +_date = date +_time = time + +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: ... + + @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: ... + 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: ... + 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] + + 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: ... + + @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]: ... + if sys.version_info >= (3, 6): + @property + def fold(self) -> int: ... + + @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: ... + if sys.version_info >= (3, 8): + @classmethod + def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... + else: + @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: ... + 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: ... + 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 toordinal(self) -> int: ... + def timetuple(self) -> struct_time: ... + if sys.version_info >= (3, 3): + 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: ... + 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 ctime(self) -> str: ... + if sys.version_info >= (3, 6): + def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... + else: + 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 + if sys.version_info >= (3, 8): + def __add__(self: _S, other: timedelta) -> _S: ... + def __radd__(self: _S, other: timedelta) -> _S: ... + else: + 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/stdlib/dbm/__init__.pyi b/mypy/stdlib/dbm/__init__.pyi new file mode 100644 index 000000000000..338fe7744dd0 --- /dev/null +++ b/mypy/stdlib/dbm/__init__.pyi @@ -0,0 +1,25 @@ +import sys +from types import TracebackType +from typing import Iterator, Optional, Type, Union, MutableMapping + +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): ... + +def whichdb(filename: str) -> str: ... + +def open(file: str, flag: Literal['r', 'w', 'c', 'n'] = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/stdlib/dbm/dumb.pyi b/mypy/stdlib/dbm/dumb.pyi new file mode 100644 index 000000000000..c89a96cf5e38 --- /dev/null +++ b/mypy/stdlib/dbm/dumb.pyi @@ -0,0 +1,31 @@ + +import sys +from typing import Union, MutableMapping, Iterator, Optional, Type +from types import TracebackType + +if sys.version_info >= (3, 8): + from typing import Final +else: + from typing_extensions import Final + +_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/stdlib/dbm/gnu.pyi b/mypy/stdlib/dbm/gnu.pyi new file mode 100644 index 000000000000..69c4ffa89b04 --- /dev/null +++ b/mypy/stdlib/dbm/gnu.pyi @@ -0,0 +1,36 @@ + +from typing import Union, Optional, Type, Iterator, overload, List, TypeVar, Generic +from types import TracebackType + +_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/stdlib/dbm/ndbm.pyi b/mypy/stdlib/dbm/ndbm.pyi new file mode 100644 index 000000000000..db7c555be967 --- /dev/null +++ b/mypy/stdlib/dbm/ndbm.pyi @@ -0,0 +1,36 @@ + +from typing import Generic, Union, Iterator, Optional, Type, TypeVar, overload, List +from types import TracebackType + +_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/stdlib/decimal.pyi b/mypy/stdlib/decimal.pyi new file mode 100644 index 000000000000..799894fc1c43 --- /dev/null +++ b/mypy/stdlib/decimal.pyi @@ -0,0 +1,346 @@ +import numbers +import sys +from types import TracebackType +from typing import ( + Any, Container, Dict, List, NamedTuple, Optional, overload, Sequence, Text, Tuple, Type, TypeVar, Union, +) + +_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] +_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 + +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]: ... + +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): ... + +if sys.version_info >= (3,): + class FloatOperation(DecimalException, TypeError): ... + +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: ... + 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 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 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 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: ... + 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: ... + 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 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: ... + if sys.version_info >= (3,): + def canonical(self) -> Decimal: ... + else: + def canonical(self, context: Optional[Context] = ...) -> 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 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 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 + if sys.version_info >= (3,): + clamp: int + else: + _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 clear_flags(self) -> None: ... + if sys.version_info >= (3,): + def clear_traps(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/stdlib/difflib.pyi b/mypy/stdlib/difflib.pyi new file mode 100644 index 000000000000..110abf7a3bf2 --- /dev/null +++ b/mypy/stdlib/difflib.pyi @@ -0,0 +1,98 @@ +# Based on https://docs.python.org/2.7/library/difflib.html and https://docs.python.org/3.2/library/difflib.html + +import sys +from typing import ( + Any, TypeVar, Callable, Iterable, Iterator, List, NamedTuple, Sequence, Tuple, + Generic, Optional, Text, Union, AnyStr, overload +) + +_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]] + +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: ... + if sys.version_info >= (3, 9): + def find_longest_match(self, alo: int = ..., ahi: Optional[int] = ..., blo: int = ..., bhi: Optional[int] = ...) -> Match: ... + else: + 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(word: AnyStr, possibilities: Iterable[AnyStr], # type: ignore + 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: ... + 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_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]: ... + +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]: ... diff --git a/mypy/stdlib/dis.pyi b/mypy/stdlib/dis.pyi new file mode 100644 index 000000000000..682c6851672c --- /dev/null +++ b/mypy/stdlib/dis.pyi @@ -0,0 +1,78 @@ +from typing import Callable, List, Union, Iterator, Tuple, Optional, Any, IO, NamedTuple, Dict + +import sys +import types + +from opcode import (hasconst as hasconst, hasname as hasname, hasjrel as hasjrel, + hasjabs as hasjabs, haslocal as haslocal, hascompare as hascompare, + hasfree as hasfree, cmp_op as cmp_op, opname as opname, opmap as opmap, + HAVE_ARGUMENT as HAVE_ARGUMENT, EXTENDED_ARG as EXTENDED_ARG) + +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: ... + + +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: ... + +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]: ... +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: ... diff --git a/mypy/stdlib/distutils/__init__.pyi b/mypy/stdlib/distutils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/archive_util.pyi b/mypy/stdlib/distutils/archive_util.pyi new file mode 100644 index 000000000000..12172f3f2b01 --- /dev/null +++ b/mypy/stdlib/distutils/archive_util.pyi @@ -0,0 +1,12 @@ +# Stubs for distutils.archive_util + +from typing import Optional + + +def make_archive(base_name: str, format: str, root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., verbose: int = ..., + dry_run: int = ...) -> str: ... +def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., + verbose: int = ..., dry_run: int = ...) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., + dry_run: int = ...) -> str: ... diff --git a/mypy/stdlib/distutils/bcppcompiler.pyi b/mypy/stdlib/distutils/bcppcompiler.pyi new file mode 100644 index 000000000000..9f27a0ae0965 --- /dev/null +++ b/mypy/stdlib/distutils/bcppcompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.bcppcompiler + +from distutils.ccompiler import CCompiler + + +class BCPPCompiler(CCompiler): ... diff --git a/mypy/stdlib/distutils/ccompiler.pyi b/mypy/stdlib/distutils/ccompiler.pyi new file mode 100644 index 000000000000..b4243a176dfe --- /dev/null +++ b/mypy/stdlib/distutils/ccompiler.pyi @@ -0,0 +1,129 @@ +# Stubs for distutils.ccompiler + +from typing import Any, Callable, List, Optional, Tuple, Union + + +_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] + + +def gen_lib_options(compiler: CCompiler, library_dirs: List[str], + runtime_library_dirs: List[str], + libraries: List[str]) -> List[str]: ... +def gen_preprocess_options(macros: List[_Macro], + include_dirs: List[str]) -> List[str]: ... +def get_default_compiler(osname: Optional[str] = ..., + platform: Optional[str] = ...) -> str: ... +def new_compiler(plat: Optional[str] = ..., compiler: Optional[str] = ..., + verbose: int = ..., dry_run: int = ..., + force: int = ...) -> CCompiler: ... +def show_compilers() -> None: ... + +class CCompiler: + dry_run: bool + force: bool + verbose: bool + output_dir: Optional[str] + macros: List[_Macro] + include_dirs: List[str] + libraries: List[str] + library_dirs: List[str] + runtime_library_dirs: List[str] + objects: List[str] + def __init__(self, verbose: int = ..., dry_run: int = ..., + force: int = ...) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: List[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: List[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: List[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: List[str]) -> None: ... + def define_macro(self, name: str, value: Optional[str] = ...) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: List[str]) -> None: ... + def detect_language(self, sources: Union[str, List[str]]) -> Optional[str]: ... + def find_library_file(self, dirs: List[str], lib: str, + debug: bool = ...) -> Optional[str]: ... + def has_function(self, funcname: str, includes: Optional[List[str]] = ..., + include_dirs: Optional[List[str]] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ...) -> bool: ... + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def set_executables(self, **args: str) -> None: ... + def compile(self, sources: List[str], output_dir: Optional[str] = ..., + macros: Optional[_Macro] = ..., + include_dirs: Optional[List[str]] = ..., debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + depends: Optional[List[str]] = ...) -> List[str]: ... + def create_static_lib(self, objects: List[str], output_libname: str, + output_dir: Optional[str] = ..., debug: bool = ..., + target_lang: Optional[str] = ...) -> None: ... + def link(self, target_desc: str, objects: List[str], output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_executable(self, objects: List[str], output_progname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_shared_lib(self, objects: List[str], output_libname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_shared_object(self, objects: List[str], output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def preprocess(self, source: str, output_file: Optional[str] = ..., + macros: Optional[List[_Macro]] = ..., + include_dirs: Optional[List[str]] = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ...) -> None: ... + def executable_filename(self, basename: str, strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def library_filename(self, libname: str, lib_type: str = ..., + strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def object_filenames(self, source_filenames: List[str], + strip_dir: int = ..., + output_dir: str = ...) -> List[str]: ... + def shared_object_filename(self, basename: str, strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def execute(self, func: Callable[..., None], args: Tuple[Any, ...], + msg: Optional[str] = ..., level: int = ...) -> None: ... + def spawn(self, cmd: List[str]) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def move_file(self, src: str, dst: str) -> str: ... + def announce(self, msg: str, level: int = ...) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... diff --git a/mypy/stdlib/distutils/cmd.pyi b/mypy/stdlib/distutils/cmd.pyi new file mode 100644 index 000000000000..3b0d02f49967 --- /dev/null +++ b/mypy/stdlib/distutils/cmd.pyi @@ -0,0 +1,40 @@ +# Stubs for distutils.cmd + +from typing import Callable, List, Tuple, Union, Optional, Iterable, Any, Text +from abc import abstractmethod +from distutils.dist import Distribution + +class Command: + sub_commands: List[Tuple[str, Optional[Callable[[Command], bool]]]] + def __init__(self, dist: Distribution) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + + def announce(self, msg: Text, level: int = ...) -> None: ... + def debug_print(self, msg: Text) -> None: ... + + def ensure_string(self, option: str, default: Optional[str] = ...) -> None: ... + def ensure_string_list(self, option: Union[str, List[str]]) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... + def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... + def reinitialize_command(self, command: Union[Command, Text], reinit_subcommands: int = ...) -> Command: ... + def run_command(self, command: Text) -> None: ... + def get_sub_commands(self) -> List[str]: ... + + def warn(self, msg: Text) -> None: ... + def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[Text] = ..., level: int = ...) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def copy_file(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., link: Optional[str] = ..., level: Any = ...) -> Tuple[str, bool]: ... # level is not used + def copy_tree(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., preserve_symlinks: int = ..., level: Any = ...) -> List[str]: ... # level is not used + def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used + def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used + def make_archive(self, base_name: str, format: str, root_dir: Optional[str] = ..., base_dir: Optional[str] = ..., owner: Optional[str] = ..., group: Optional[str] = ...) -> str: ... + def make_file(self, infiles: Union[str, List[str], Tuple[str]], outfile: str, func: Callable[..., Any], args: List[Any], exec_msg: Optional[str] = ..., skip_msg: Optional[str] = ..., level: Any = ...) -> None: ... # level is not used diff --git a/mypy/stdlib/distutils/command/__init__.pyi b/mypy/stdlib/distutils/command/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/bdist.pyi b/mypy/stdlib/distutils/command/bdist.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/bdist_dumb.pyi b/mypy/stdlib/distutils/command/bdist_dumb.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/bdist_msi.pyi b/mypy/stdlib/distutils/command/bdist_msi.pyi new file mode 100644 index 000000000000..a761792018a9 --- /dev/null +++ b/mypy/stdlib/distutils/command/bdist_msi.pyi @@ -0,0 +1,6 @@ +from distutils.cmd import Command + +class bdist_msi(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/stdlib/distutils/command/bdist_packager.pyi b/mypy/stdlib/distutils/command/bdist_packager.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/bdist_rpm.pyi b/mypy/stdlib/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/bdist_wininst.pyi b/mypy/stdlib/distutils/command/bdist_wininst.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/build.pyi b/mypy/stdlib/distutils/command/build.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/build_clib.pyi b/mypy/stdlib/distutils/command/build_clib.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/build_ext.pyi b/mypy/stdlib/distutils/command/build_ext.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/build_py.pyi b/mypy/stdlib/distutils/command/build_py.pyi new file mode 100644 index 000000000000..34753e4a75b6 --- /dev/null +++ b/mypy/stdlib/distutils/command/build_py.pyi @@ -0,0 +1,10 @@ +from distutils.cmd import Command +import sys + +if sys.version_info >= (3,): + class build_py(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + + class build_py_2to3(build_py): ... diff --git a/mypy/stdlib/distutils/command/build_scripts.pyi b/mypy/stdlib/distutils/command/build_scripts.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/check.pyi b/mypy/stdlib/distutils/command/check.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/clean.pyi b/mypy/stdlib/distutils/command/clean.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/config.pyi b/mypy/stdlib/distutils/command/config.pyi new file mode 100644 index 000000000000..94e97355ea7c --- /dev/null +++ b/mypy/stdlib/distutils/command/config.pyi @@ -0,0 +1,87 @@ +from distutils import log as log +from distutils.ccompiler import CCompiler +from distutils.core import Command as Command +from distutils.errors import DistutilsExecError as DistutilsExecError +from distutils.sysconfig import customize_compiler as customize_compiler +from typing import Any, Dict, List, Match, Optional, Pattern, Sequence, Tuple, Union + +LANG_EXT: Dict[str, str] + +class config(Command): + description: str = ... + # Tuple is full name, short name, description + user_options: Sequence[Tuple[str, Optional[str], str]] = ... + compiler: Optional[Union[str, CCompiler]] = ... + cc: Optional[str] = ... + include_dirs: Optional[Sequence[str]] = ... + libraries: Optional[Sequence[str]] = ... + library_dirs: Optional[Sequence[str]] = ... + noisy: int = ... + dump_source: int = ... + temp_files: Sequence[str] = ... + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def try_cpp( + self, + body: Optional[str] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def search_cpp( + self, + pattern: Union[Pattern[str], str], + body: Optional[str] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def try_compile( + self, body: str, headers: Optional[Sequence[str]] = ..., include_dirs: Optional[Sequence[str]] = ..., lang: str = ... + ) -> bool: ... + def try_link( + self, + body: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def try_run( + self, + body: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def check_func( + self, + func: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + decl: int = ..., + call: int = ..., + ) -> bool: ... + def check_lib( + self, + library: str, + library_dirs: Optional[Sequence[str]] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + other_libraries: List[str] = ..., + ) -> bool: ... + def check_header( + self, + header: str, + include_dirs: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + +def dump_file(filename: str, head: Optional[str] = ...) -> None: ... diff --git a/mypy/stdlib/distutils/command/install.pyi b/mypy/stdlib/distutils/command/install.pyi new file mode 100644 index 000000000000..94a900824686 --- /dev/null +++ b/mypy/stdlib/distutils/command/install.pyi @@ -0,0 +1,14 @@ +from distutils.cmd import Command +from typing import Optional, Text + + +class install(Command): + user: bool + prefix: Optional[Text] + home: Optional[Text] + root: Optional[Text] + install_lib: Optional[Text] + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/stdlib/distutils/command/install_data.pyi b/mypy/stdlib/distutils/command/install_data.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/install_headers.pyi b/mypy/stdlib/distutils/command/install_headers.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/install_lib.pyi b/mypy/stdlib/distutils/command/install_lib.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/install_scripts.pyi b/mypy/stdlib/distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/register.pyi b/mypy/stdlib/distutils/command/register.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/command/sdist.pyi b/mypy/stdlib/distutils/command/sdist.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/distutils/core.pyi b/mypy/stdlib/distutils/core.pyi new file mode 100644 index 000000000000..354eedde68e2 --- /dev/null +++ b/mypy/stdlib/distutils/core.pyi @@ -0,0 +1,50 @@ +# Stubs for distutils.core + +from typing import Any, List, Mapping, Optional, Tuple, Type, Union +from distutils.cmd import Command as Command +from distutils.dist import Distribution as Distribution +from distutils.extension import Extension as Extension + +def setup( + *, + name: str = ..., + version: str = ..., + description: str = ..., + long_description: str = ..., + author: str = ..., + author_email: str = ..., + maintainer: str = ..., + maintainer_email: str = ..., + url: str = ..., + download_url: str = ..., + packages: List[str] = ..., + py_modules: List[str] = ..., + scripts: List[str] = ..., + ext_modules: List[Extension] = ..., + classifiers: List[str] = ..., + distclass: Type[Distribution] = ..., + script_name: str = ..., + script_args: List[str] = ..., + options: Mapping[str, Any] = ..., + license: str = ..., + keywords: Union[List[str], str] = ..., + platforms: Union[List[str], str] = ..., + cmdclass: Mapping[str, Type[Command]] = ..., + data_files: List[Tuple[str, List[str]]] = ..., + package_dir: Mapping[str, str] = ..., + obsoletes: List[str] = ..., + provides: List[str] = ..., + requires: List[str] = ..., + command_packages: List[str] = ..., + command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ..., + package_data: Mapping[str, List[str]] = ..., + include_package_data: bool = ..., + libraries: List[str] = ..., + headers: List[str] = ..., + ext_package: str = ..., + include_dirs: List[str] = ..., + password: str = ..., + fullname: str = ..., + **attrs: Any, +) -> None: ... +def run_setup(script_name: str, script_args: Optional[List[str]] = ..., stop_after: str = ...) -> Distribution: ... diff --git a/mypy/stdlib/distutils/cygwinccompiler.pyi b/mypy/stdlib/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..1bfab90ead47 --- /dev/null +++ b/mypy/stdlib/distutils/cygwinccompiler.pyi @@ -0,0 +1,7 @@ +# Stubs for distutils.cygwinccompiler + +from distutils.unixccompiler import UnixCCompiler + + +class CygwinCCompiler(UnixCCompiler): ... +class Mingw32CCompiler(CygwinCCompiler): ... diff --git a/mypy/stdlib/distutils/debug.pyi b/mypy/stdlib/distutils/debug.pyi new file mode 100644 index 000000000000..76de44772127 --- /dev/null +++ b/mypy/stdlib/distutils/debug.pyi @@ -0,0 +1,3 @@ +# Stubs for distutils.debug + +DEBUG: bool diff --git a/mypy/stdlib/distutils/dep_util.pyi b/mypy/stdlib/distutils/dep_util.pyi new file mode 100644 index 000000000000..7df58478132d --- /dev/null +++ b/mypy/stdlib/distutils/dep_util.pyi @@ -0,0 +1,8 @@ +# Stubs for distutils.dep_util + +from typing import List, Tuple + +def newer(source: str, target: str) -> bool: ... +def newer_pairwise(sources: List[str], + targets: List[str]) -> List[Tuple[str, str]]: ... +def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... diff --git a/mypy/stdlib/distutils/dir_util.pyi b/mypy/stdlib/distutils/dir_util.pyi new file mode 100644 index 000000000000..667ac2fe710a --- /dev/null +++ b/mypy/stdlib/distutils/dir_util.pyi @@ -0,0 +1,15 @@ +# Stubs for distutils.dir_util + +from typing import List + + +def mkpath(name: str, mode: int = ..., verbose: int = ..., + dry_run: int = ...) -> List[str]: ... +def create_tree(base_dir: str, files: List[str], mode: int = ..., + verbose: int = ..., dry_run: int = ...) -> None: ... +def copy_tree(src: str, dst: str, preserve_mode: int = ..., + preserve_times: int = ..., preserve_symlinks: int = ..., + update: int = ..., verbose: int = ..., + dry_run: int = ...) -> List[str]: ... +def remove_tree(directory: str, verbose: int = ..., + dry_run: int = ...) -> None: ... diff --git a/mypy/stdlib/distutils/dist.pyi b/mypy/stdlib/distutils/dist.pyi new file mode 100644 index 000000000000..92ef8ae49054 --- /dev/null +++ b/mypy/stdlib/distutils/dist.pyi @@ -0,0 +1,12 @@ +# Stubs for distutils.dist +from distutils.cmd import Command + +from typing import Any, Dict, Iterable, Mapping, Optional, Text, Tuple, Type + + +class Distribution: + cmdclass: Dict[str, Type[Command]] + def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ... + def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... + def parse_config_files(self, filenames: Optional[Iterable[Text]] = ...) -> None: ... + def get_command_obj(self, command: str, create: bool = ...) -> Optional[Command]: ... diff --git a/mypy/stdlib/distutils/errors.pyi b/mypy/stdlib/distutils/errors.pyi new file mode 100644 index 000000000000..e483362bfbf1 --- /dev/null +++ b/mypy/stdlib/distutils/errors.pyi @@ -0,0 +1,19 @@ +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... +class CCompilerError(Exception): ... +class PreprocessError(CCompilerError): ... +class CompileError(CCompilerError): ... +class LibError(CCompilerError): ... +class LinkError(CCompilerError): ... +class UnknownFileError(CCompilerError): ... diff --git a/mypy/stdlib/distutils/extension.pyi b/mypy/stdlib/distutils/extension.pyi new file mode 100644 index 000000000000..537e983967c2 --- /dev/null +++ b/mypy/stdlib/distutils/extension.pyi @@ -0,0 +1,41 @@ +# Stubs for distutils.extension + +from typing import List, Optional, Tuple +import sys + +class Extension: + if sys.version_info >= (3,): + def __init__(self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + swig_opts: Optional[str] = ..., # undocumented + depends: List[str] = ..., + language: str = ..., + optional: bool = ...) -> None: ... + else: + def __init__(self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + swig_opts: Optional[str] = ..., # undocumented + depends: List[str] = ..., + language: str = ...) -> None: ... diff --git a/mypy/stdlib/distutils/fancy_getopt.pyi b/mypy/stdlib/distutils/fancy_getopt.pyi new file mode 100644 index 000000000000..4d38a75551ea --- /dev/null +++ b/mypy/stdlib/distutils/fancy_getopt.pyi @@ -0,0 +1,27 @@ +# Stubs for distutils.fancy_getopt + +from typing import ( + Any, List, Mapping, Optional, Tuple, Union, + TypeVar, overload, +) + +_Option = Tuple[str, Optional[str], str] +_GR = Tuple[List[str], OptionDummy] + +def fancy_getopt(options: List[_Option], + negative_opt: Mapping[_Option, _Option], + object: Any, + args: Optional[List[str]]) -> Union[List[str], _GR]: ... +def wrap_text(text: str, width: int) -> List[str]: ... + +class FancyGetopt: + def __init__(self, option_table: Optional[List[_Option]] = ...) -> None: ... + # TODO kinda wrong, `getopt(object=object())` is invalid + @overload + def getopt(self, args: Optional[List[str]] = ...) -> _GR: ... + @overload + def getopt(self, args: Optional[List[str]], object: Any) -> List[str]: ... + def get_option_order(self) -> List[Tuple[str, str]]: ... + def generate_help(self, header: Optional[str] = ...) -> List[str]: ... + +class OptionDummy: ... diff --git a/mypy/stdlib/distutils/file_util.pyi b/mypy/stdlib/distutils/file_util.pyi new file mode 100644 index 000000000000..6324d63d4b5d --- /dev/null +++ b/mypy/stdlib/distutils/file_util.pyi @@ -0,0 +1,12 @@ +# Stubs for distutils.file_util + +from typing import Optional, Sequence, Tuple + + +def copy_file(src: str, dst: str, preserve_mode: bool = ..., + preserve_times: bool = ..., update: bool = ..., + link: Optional[str] = ..., verbose: bool = ..., + dry_run: bool = ...) -> Tuple[str, str]: ... +def move_file(src: str, dst: str, verbose: bool = ..., + dry_run: bool = ...) -> str: ... +def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/mypy/stdlib/distutils/filelist.pyi b/mypy/stdlib/distutils/filelist.pyi new file mode 100644 index 000000000000..4ecaebaf714f --- /dev/null +++ b/mypy/stdlib/distutils/filelist.pyi @@ -0,0 +1,3 @@ +# Stubs for distutils.filelist + +class FileList: ... diff --git a/mypy/stdlib/distutils/log.pyi b/mypy/stdlib/distutils/log.pyi new file mode 100644 index 000000000000..6c37cc503b30 --- /dev/null +++ b/mypy/stdlib/distutils/log.pyi @@ -0,0 +1,28 @@ +from typing import Any, Callable, Iterable, Text + +DEBUG: int +INFO: int +WARN: int +ERROR: int +FATAL: int + +class Log: + def __init__(self, threshold: int = ...) -> None: ... + def log(self, level: int, msg: Text, *args: Any) -> None: ... + def debug(self, msg: Text, *args: Any) -> None: ... + def info(self, msg: Text, *args: Any) -> None: ... + def warn(self, msg: Text, *args: Any) -> None: ... + def error(self, msg: Text, *args: Any) -> None: ... + def fatal(self, msg: Text, *args: Any) -> None: ... + +_LogFunc = Callable[[Text, Iterable[Any]], None] + +log: Callable[[int, Text, Iterable[Any]], None] +debug: _LogFunc +info: _LogFunc +warn: _LogFunc +error: _LogFunc +fatal: _LogFunc + +def set_threshold(level: int) -> int: ... +def set_verbosity(v: int) -> None: ... diff --git a/mypy/stdlib/distutils/msvccompiler.pyi b/mypy/stdlib/distutils/msvccompiler.pyi new file mode 100644 index 000000000000..ffc9e4490ce3 --- /dev/null +++ b/mypy/stdlib/distutils/msvccompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.msvccompiler + +from distutils.ccompiler import CCompiler + + +class MSVCCompiler(CCompiler): ... diff --git a/mypy/stdlib/distutils/spawn.pyi b/mypy/stdlib/distutils/spawn.pyi new file mode 100644 index 000000000000..8df9ebab7f23 --- /dev/null +++ b/mypy/stdlib/distutils/spawn.pyi @@ -0,0 +1,8 @@ +# Stubs for distutils.spawn + +from typing import List, Optional + +def spawn(cmd: List[str], search_path: bool = ..., + verbose: bool = ..., dry_run: bool = ...) -> None: ... +def find_executable(executable: str, + path: Optional[str] = ...) -> Optional[str]: ... diff --git a/mypy/stdlib/distutils/sysconfig.pyi b/mypy/stdlib/distutils/sysconfig.pyi new file mode 100644 index 000000000000..62fa9af81757 --- /dev/null +++ b/mypy/stdlib/distutils/sysconfig.pyi @@ -0,0 +1,19 @@ +# Stubs for distutils.sysconfig + +from typing import Mapping, Optional, Union +from distutils.ccompiler import CCompiler + +PREFIX: str +EXEC_PREFIX: str + +def get_config_var(name: str) -> Union[int, str, None]: ... +def get_config_vars(*args: str) -> Mapping[str, Union[int, str]]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool = ..., + prefix: Optional[str] = ...) -> str: ... +def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., + prefix: Optional[str] = ...) -> str: ... + +def customize_compiler(compiler: CCompiler) -> None: ... +def set_python_build() -> None: ... diff --git a/mypy/stdlib/distutils/text_file.pyi b/mypy/stdlib/distutils/text_file.pyi new file mode 100644 index 000000000000..8f90d41d10f6 --- /dev/null +++ b/mypy/stdlib/distutils/text_file.pyi @@ -0,0 +1,18 @@ +# Stubs for distutils.text_file + +from typing import IO, List, Optional, Tuple, Union + +class TextFile: + def __init__(self, filename: Optional[str] = ..., + file: Optional[IO[str]] = ..., + *, strip_comments: bool = ..., + lstrip_ws: bool = ..., rstrip_ws: bool = ..., + skip_blanks: bool = ..., join_lines: bool = ..., + collapse_join: bool = ...) -> None: ... + def open(self, filename: str) -> None: ... + def close(self) -> None: ... + def warn(self, msg: str, + line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... + def readline(self) -> Optional[str]: ... + def readlines(self) -> List[str]: ... + def unreadline(self, line: str) -> str: ... diff --git a/mypy/stdlib/distutils/unixccompiler.pyi b/mypy/stdlib/distutils/unixccompiler.pyi new file mode 100644 index 000000000000..7ab7298bf4c6 --- /dev/null +++ b/mypy/stdlib/distutils/unixccompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.unixccompiler + +from distutils.ccompiler import CCompiler + + +class UnixCCompiler(CCompiler): ... diff --git a/mypy/stdlib/distutils/util.pyi b/mypy/stdlib/distutils/util.pyi new file mode 100644 index 000000000000..942886d77f55 --- /dev/null +++ b/mypy/stdlib/distutils/util.pyi @@ -0,0 +1,20 @@ +# Stubs for distutils.util + +from typing import Any, Callable, List, Mapping, Optional, Tuple + + +def get_platform() -> str: ... +def convert_path(pathname: str) -> str: ... +def change_root(new_root: str, pathname: str) -> str: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... +def split_quoted(s: str) -> List[str]: ... +def execute(func: Callable[..., None], args: Tuple[Any, ...], + msg: Optional[str] = ..., verbose: bool = ..., + dry_run: bool = ...) -> None: ... +def strtobool(val: str) -> bool: ... +def byte_compile(py_files: List[str], optimize: int = ..., force: bool = ..., + prefix: Optional[str] = ..., base_dir: Optional[str] = ..., + verbose: bool = ..., dry_run: bool = ..., + direct: Optional[bool] = ...) -> None: ... +def rfc822_escape(header: str) -> str: ... diff --git a/mypy/stdlib/distutils/version.pyi b/mypy/stdlib/distutils/version.pyi new file mode 100644 index 000000000000..36ee4b84b96a --- /dev/null +++ b/mypy/stdlib/distutils/version.pyi @@ -0,0 +1,54 @@ +import sys +from abc import abstractmethod +from typing import Any, Optional, TypeVar, Union, Pattern, Text, Tuple + +_T = TypeVar('_T', bound=Version) + +class Version: + def __repr__(self) -> str: ... + + if sys.version_info >= (3,): + def __eq__(self, other: object) -> bool: ... + def __lt__(self: _T, other: Union[_T, str]) -> bool: ... + def __le__(self: _T, other: Union[_T, str]) -> bool: ... + def __gt__(self: _T, other: Union[_T, str]) -> bool: ... + def __ge__(self: _T, other: Union[_T, str]) -> bool: ... + + @abstractmethod + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + @abstractmethod + def parse(self: _T, vstring: Text) -> _T: ... + @abstractmethod + def __str__(self) -> str: ... + if sys.version_info >= (3,): + @abstractmethod + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + @abstractmethod + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class StrictVersion(Version): + version_re: Pattern[str] + version: Tuple[int, int, int] + prerelease: Optional[Tuple[Text, int]] + + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + if sys.version_info >= (3,): + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class LooseVersion(Version): + component_re: Pattern[str] + vstring: Text + version: Tuple[Union[Text, int], ...] + + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + if sys.version_info >= (3,): + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... diff --git a/mypy/stdlib/doctest.pyi b/mypy/stdlib/doctest.pyi new file mode 100644 index 000000000000..7349cdc74e55 --- /dev/null +++ b/mypy/stdlib/doctest.pyi @@ -0,0 +1,160 @@ +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union + +import sys +import types +import unittest + +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 +if sys.version_info >= (3, 4): + FAIL_FAST: 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: ... + +if sys.version_info >= (3, 4): + class _DocTestSuite(unittest.TestSuite): ... +else: + _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/stdlib/dummy_threading.pyi b/mypy/stdlib/dummy_threading.pyi new file mode 100644 index 000000000000..d7d12bb70667 --- /dev/null +++ b/mypy/stdlib/dummy_threading.pyi @@ -0,0 +1,3 @@ + +from _dummy_threading import * +from _dummy_threading import __all__ as __all__ diff --git a/mypy/stdlib/email/__init__.pyi b/mypy/stdlib/email/__init__.pyi new file mode 100644 index 000000000000..a69f188d4f7b --- /dev/null +++ b/mypy/stdlib/email/__init__.pyi @@ -0,0 +1,25 @@ +# Stubs for email (Python 3.4) + +from typing import Callable, IO +from email.message import Message +from email.policy import Policy + +def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_file(fp: IO[str], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_binary_file(fp: IO[bytes], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... + +# Names in __all__ with no definition: +# base64mime +# charset +# encoders +# errors +# feedparser +# generator +# header +# iterators +# message +# mime +# parser +# quoprimime +# utils diff --git a/mypy/stdlib/email/charset.pyi b/mypy/stdlib/email/charset.pyi new file mode 100644 index 000000000000..3a6c19d1b91b --- /dev/null +++ b/mypy/stdlib/email/charset.pyi @@ -0,0 +1,31 @@ +# Stubs for email.charset (Python 3.4) + +from typing import List, Optional, Iterator, Any + +QP: int # undocumented +BASE64: int # undocumented +SHORTEST: int # undocumented + +class Charset: + input_charset: str + header_encoding: int + body_encoding: int + output_charset: Optional[str] + input_codec: Optional[str] + output_codec: Optional[str] + def __init__(self, input_charset: str = ...) -> None: ... + def get_body_encoding(self) -> str: ... + def get_output_charset(self) -> Optional[str]: ... + def header_encode(self, string: str) -> str: ... + def header_encode_lines(self, string: str, + maxlengths: Iterator[int]) -> List[str]: ... + def body_encode(self, string: str) -> str: ... + def __str__(self) -> str: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +def add_charset(charset: str, header_enc: Optional[int] = ..., + body_enc: Optional[int] = ..., + output_charset: Optional[str] = ...) -> None: ... +def add_alias(alias: str, canonical: str) -> None: ... +def add_codec(charset: str, codecname: str) -> None: ... diff --git a/mypy/stdlib/email/contentmanager.pyi b/mypy/stdlib/email/contentmanager.pyi new file mode 100644 index 000000000000..ed55ef67dccd --- /dev/null +++ b/mypy/stdlib/email/contentmanager.pyi @@ -0,0 +1,15 @@ +# Stubs for email.contentmanager (Python 3.4) + +from typing import Any, Callable +from email.message import Message + +class ContentManager: + def __init__(self) -> None: ... + def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ... + def set_content(self, msg: Message, obj: Any, *args: Any, + **kw: Any) -> Any: ... + def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ... + def add_set_handler(self, typekey: type, + handler: Callable[..., Any]) -> None: ... + +raw_data_manager: ContentManager diff --git a/mypy/stdlib/email/encoders.pyi b/mypy/stdlib/email/encoders.pyi new file mode 100644 index 000000000000..bb5c84cb136a --- /dev/null +++ b/mypy/stdlib/email/encoders.pyi @@ -0,0 +1,8 @@ +# Stubs for email.encoders (Python 3.4) + +from email.message import Message + +def encode_base64(msg: Message) -> None: ... +def encode_quopri(msg: Message) -> None: ... +def encode_7or8bit(msg: Message) -> None: ... +def encode_noop(msg: Message) -> None: ... diff --git a/mypy/stdlib/email/errors.pyi b/mypy/stdlib/email/errors.pyi new file mode 100644 index 000000000000..73e0b800f343 --- /dev/null +++ b/mypy/stdlib/email/errors.pyi @@ -0,0 +1,20 @@ +# Stubs for email.errors (Python 3.4) + +class MessageError(Exception): ... +class MessageParseError(MessageError): ... +class HeaderParseError(MessageParseError): ... +class BoundaryError(MessageParseError): ... +class MultipartConversionError(MessageError, TypeError): ... + +class MessageDefect(ValueError): ... +class NoBoundaryInMultipartDefect(MessageDefect): ... +class StartBoundaryNotFoundDefect(MessageDefect): ... +class FirstHeaderLineIsContinuationDefect(MessageDefect): ... +class MisplacedEnvelopeHeaderDefect(MessageDefect): ... +class MultipartInvariantViolationDefect(MessageDefect): ... +class InvalidBase64PaddingDefect(MessageDefect): ... +class InvalidBase64CharactersDefect(MessageDefect): ... +class CloseBoundaryNotFoundDefect(MessageDefect): ... +class MissingHeaderBodySeparatorDefect(MessageDefect): ... + +MalformedHeaderDefect = MissingHeaderBodySeparatorDefect diff --git a/mypy/stdlib/email/feedparser.pyi b/mypy/stdlib/email/feedparser.pyi new file mode 100644 index 000000000000..8350d135dc86 --- /dev/null +++ b/mypy/stdlib/email/feedparser.pyi @@ -0,0 +1,17 @@ +# Stubs for email.feedparser (Python 3.4) + +from typing import Callable +from email.message import Message +from email.policy import Policy + +class FeedParser: + def __init__(self, _factory: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def feed(self, data: str) -> None: ... + def close(self) -> Message: ... + +class BytesFeedParser: + def __init__(self, _factory: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def feed(self, data: bytes) -> None: ... + def close(self) -> Message: ... diff --git a/mypy/stdlib/email/generator.pyi b/mypy/stdlib/email/generator.pyi new file mode 100644 index 000000000000..2cf3942d390b --- /dev/null +++ b/mypy/stdlib/email/generator.pyi @@ -0,0 +1,27 @@ +# Stubs for email.generator (Python 3.4) + +from typing import BinaryIO, TextIO, Optional +from email.message import Message +from email.policy import Policy + +class Generator: + def clone(self, fp: TextIO) -> Generator: ... + def write(self, s: str) -> None: ... + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, + policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., + linesep: Optional[str] = ...) -> None: ... + +class BytesGenerator: + def clone(self, fp: BinaryIO) -> BytesGenerator: ... + def write(self, s: str) -> None: ... + def __init__(self, outfp: BinaryIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, + policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., + linesep: Optional[str] = ...) -> None: ... + +class DecodedGenerator(Generator): + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, fmt: Optional[str] = ...) -> None: ... diff --git a/mypy/stdlib/email/header.pyi b/mypy/stdlib/email/header.pyi new file mode 100644 index 000000000000..21b999530154 --- /dev/null +++ b/mypy/stdlib/email/header.pyi @@ -0,0 +1,25 @@ +# Stubs for email.header (Python 3.4) + +from typing import Union, Optional, Any, List, Tuple +from email.charset import Charset + +class Header: + def __init__(self, s: Union[bytes, str, None] = ..., + charset: Union[Charset, str, None] = ..., + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., continuation_ws: str = ..., + errors: str = ...) -> None: ... + def append(self, s: Union[bytes, str], + charset: Union[Charset, str, None] = ..., + errors: str = ...) -> None: ... + def encode(self, splitchars: str = ..., maxlinelen: Optional[int] = ..., + linesep: str = ...) -> str: ... + def __str__(self) -> str: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +def decode_header(header: Union[Header, str]) -> List[Tuple[bytes, Optional[str]]]: ... +def make_header(decoded_seq: List[Tuple[bytes, Optional[str]]], + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., + continuation_ws: str = ...) -> Header: ... diff --git a/mypy/stdlib/email/headerregistry.pyi b/mypy/stdlib/email/headerregistry.pyi new file mode 100644 index 000000000000..6af1abfb517f --- /dev/null +++ b/mypy/stdlib/email/headerregistry.pyi @@ -0,0 +1,97 @@ +# Stubs for email.headerregistry (Python 3.4) + +from datetime import datetime as _datetime +from typing import Dict, Tuple, Optional, Any, Union, Mapping +from email.errors import MessageDefect +from email.policy import Policy + +class BaseHeader(str): + @property + def name(self) -> str: ... + @property + def defects(self) -> Tuple[MessageDefect, ...]: ... + @property + def max_count(self) -> Optional[int]: ... + def __new__(cls, name: str, value: Any) -> BaseHeader: ... + def init(self, *args: Any, **kw: Any) -> None: ... + def fold(self, *, policy: Policy) -> str: ... + +class UnstructuredHeader: + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueUnstructuredHeader(UnstructuredHeader): ... + +class DateHeader: + datetime: _datetime + @classmethod + def parse(cls, string: Union[str, _datetime], + kwds: Dict[str, Any]) -> None: ... + +class UniqueDateHeader(DateHeader): ... + +class AddressHeader: + groups: Tuple[Group, ...] + addresses: Tuple[Address, ...] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueAddressHeader(AddressHeader): ... + +class SingleAddressHeader(AddressHeader): + @property + def address(self) -> Address: ... + +class UniqueSingleAddressHeader(SingleAddressHeader): ... + +class MIMEVersionHeader: + version: Optional[str] + major: Optional[int] + minor: Optional[int] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ParameterizedMIMEHeader: + params: Mapping[str, Any] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ContentTypeHeader(ParameterizedMIMEHeader): + content_type: str + maintype: str + subtype: str + +class ContentDispositionHeader(ParameterizedMIMEHeader): + content_disposition: str + +class ContentTransferEncodingHeader: + cte: str + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class HeaderRegistry: + def __init__(self, base_class: BaseHeader = ..., + default_class: BaseHeader = ..., + use_default_map: bool = ...) -> None: ... + def map_to_type(self, name: str, cls: BaseHeader) -> None: ... + def __getitem__(self, name: str) -> BaseHeader: ... + def __call__(self, name: str, value: Any) -> BaseHeader: ... + +class Address: + display_name: str + username: str + domain: str + @property + def addr_spec(self) -> str: ... + def __init__(self, display_name: str = ..., + username: Optional[str] = ..., + domain: Optional[str] = ..., + addr_spec: Optional[str] = ...) -> None: ... + def __str__(self) -> str: ... + +class Group: + display_name: Optional[str] + addresses: Tuple[Address, ...] + def __init__(self, display_name: Optional[str] = ..., + addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... + def __str__(self) -> str: ... diff --git a/mypy/stdlib/email/iterators.pyi b/mypy/stdlib/email/iterators.pyi new file mode 100644 index 000000000000..6a69f39c9518 --- /dev/null +++ b/mypy/stdlib/email/iterators.pyi @@ -0,0 +1,8 @@ +# Stubs for email.iterators (Python 3.4) + +from typing import Iterator, Optional +from email.message import Message + +def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ... +def typed_subpart_iterator(msg: Message, maintype: str = ..., + subtype: Optional[str] = ...) -> Iterator[str]: ... diff --git a/mypy/stdlib/email/message.pyi b/mypy/stdlib/email/message.pyi new file mode 100644 index 000000000000..85bba630beea --- /dev/null +++ b/mypy/stdlib/email/message.pyi @@ -0,0 +1,103 @@ +# Stubs for email.message (Python 3.4) + +from typing import ( + List, Optional, Union, Tuple, TypeVar, Generator, Sequence, Iterator, Any +) +from email.charset import Charset +from email.errors import MessageDefect +from email.header import Header +from email.policy import Policy +from email.contentmanager import ContentManager + +_T = TypeVar('_T') + +_PayloadType = Union[List[Message], str, bytes] +_CharsetType = Union[Charset, str, None] +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] +_HeaderType = Any + +class Message: + preamble: Optional[str] + epilogue: Optional[str] + defects: List[MessageDefect] + def __str__(self) -> str: ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom: str) -> None: ... + def get_unixfrom(self) -> Optional[str]: ... + def attach(self, payload: Message) -> None: ... + def get_payload(self, i: int = ..., decode: bool = ...) -> Any: ... # returns Optional[_PayloadType] + def set_payload(self, payload: _PayloadType, + charset: _CharsetType = ...) -> None: ... + def set_charset(self, charset: _CharsetType) -> None: ... + def get_charset(self) -> _CharsetType: ... + def __len__(self) -> int: ... + def __contains__(self, name: str) -> bool: ... + def __getitem__(self, name: str) -> _HeaderType: ... + def __setitem__(self, name: str, val: _HeaderType) -> None: ... + def __delitem__(self, name: str) -> None: ... + def keys(self) -> List[str]: ... + def values(self) -> List[_HeaderType]: ... + def items(self) -> List[Tuple[str, _HeaderType]]: ... + def get(self, name: str, failobj: _T = ...) -> Union[_HeaderType, _T]: ... + def get_all(self, name: str, failobj: _T = ...) -> Union[List[_HeaderType], _T]: ... + def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... + def replace_header(self, _name: str, _value: _HeaderType) -> None: ... + def get_content_type(self) -> str: ... + def get_content_maintype(self) -> str: ... + def get_content_subtype(self) -> str: ... + def get_default_type(self) -> str: ... + def set_default_type(self, ctype: str) -> None: ... + def get_params(self, failobj: _T = ..., header: str = ..., + unquote: bool = ...) -> Union[List[Tuple[str, str]], _T]: ... + def get_param(self, param: str, failobj: _T = ..., header: str = ..., + unquote: bool = ...) -> Union[_T, _ParamType]: ... + def del_param(self, param: str, header: str = ..., + requote: bool = ...) -> None: ... + def set_type(self, type: str, header: str = ..., + requote: bool = ...) -> None: ... + def get_filename(self, failobj: _T = ...) -> Union[_T, str]: ... + def get_boundary(self, failobj: _T = ...) -> Union[_T, str]: ... + def set_boundary(self, boundary: str) -> None: ... + def get_content_charset(self, failobj: _T = ...) -> Union[_T, str]: ... + def get_charsets(self, failobj: _T = ...) -> Union[_T, List[str]]: ... + def walk(self) -> Generator[Message, None, None]: ... + def get_content_disposition(self) -> Optional[str]: ... + def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ..., + policy: Optional[Policy] = ...) -> str: ... + def as_bytes(self, unixfrom: bool = ..., + policy: Optional[Policy] = ...) -> bytes: ... + def __bytes__(self) -> bytes: ... + def set_param(self, param: str, value: str, header: str = ..., + requote: bool = ..., charset: str = ..., + language: str = ..., replace: bool = ...) -> None: ... + def __init__(self, policy: Policy = ...) -> None: ... + +class MIMEPart(Message): + def get_body(self, + preferencelist: Sequence[str] = ...) -> Optional[Message]: ... + def iter_attachments(self) -> Iterator[Message]: ... + def iter_parts(self) -> Iterator[Message]: ... + def get_content(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> Any: ... + def set_content(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def make_related(self, boundary: Optional[str] = ...) -> None: ... + def make_alternative(self, boundary: Optional[str] = ...) -> None: ... + def make_mixed(self, boundary: Optional[str] = ...) -> None: ... + def add_related(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def add_alternative(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def add_attachment(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def clear(self) -> None: ... + def clear_content(self) -> None: ... + def is_attachment(self) -> bool: ... + +class EmailMessage(MIMEPart): ... diff --git a/mypy/stdlib/email/mime/__init__.pyi b/mypy/stdlib/email/mime/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/email/mime/application.pyi b/mypy/stdlib/email/mime/application.pyi new file mode 100644 index 000000000000..c27d808a43c6 --- /dev/null +++ b/mypy/stdlib/email/mime/application.pyi @@ -0,0 +1,28 @@ +# Stubs for email.mime.application (Python 3.4) + +import sys +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy +from typing import Callable, Optional, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEApplication(MIMENonMultipart): + if sys.version_info >= (3, 6): + def __init__( + self, + _data: Union[str, bytes], + _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... + else: + def __init__( + self, + _data: Union[str, bytes], + _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/stdlib/email/mime/audio.pyi b/mypy/stdlib/email/mime/audio.pyi new file mode 100644 index 000000000000..71d060bcba5d --- /dev/null +++ b/mypy/stdlib/email/mime/audio.pyi @@ -0,0 +1,28 @@ +# Stubs for email.mime.audio (Python 3.4) + +import sys +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy +from typing import Callable, Optional, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEAudio(MIMENonMultipart): + if sys.version_info >= (3, 6): + def __init__( + self, + _audiodata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEAudio], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... + else: + def __init__( + self, + _audiodata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEAudio], None] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/stdlib/email/mime/base.pyi b/mypy/stdlib/email/mime/base.pyi new file mode 100644 index 000000000000..38c6130de023 --- /dev/null +++ b/mypy/stdlib/email/mime/base.pyi @@ -0,0 +1,14 @@ +# Stubs for email.mime.base (Python 3.4) + +import email.message +import sys +from email.policy import Policy +from typing import Optional, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEBase(email.message.Message): + if sys.version_info >= (3, 6): + def __init__(self, _maintype: str, _subtype: str, *, policy: Optional[Policy] = ..., **_params: _ParamsType) -> None: ... + else: + def __init__(self, _maintype: str, _subtype: str, **_params: _ParamsType) -> None: ... diff --git a/mypy/stdlib/email/mime/image.pyi b/mypy/stdlib/email/mime/image.pyi new file mode 100644 index 000000000000..d6d019ce53cd --- /dev/null +++ b/mypy/stdlib/email/mime/image.pyi @@ -0,0 +1,28 @@ +# Stubs for email.mime.image (Python 3.4) + +import sys +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy +from typing import Callable, Optional, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEImage(MIMENonMultipart): + if sys.version_info >= (3, 6): + def __init__( + self, + _imagedata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEImage], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... + else: + def __init__( + self, + _imagedata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEImage], None] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/stdlib/email/mime/message.pyi b/mypy/stdlib/email/mime/message.pyi new file mode 100644 index 000000000000..1c56208f1183 --- /dev/null +++ b/mypy/stdlib/email/mime/message.pyi @@ -0,0 +1,13 @@ +# Stubs for email.mime.message (Python 3.4) + +import sys +from email.message import Message +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy +from typing import Optional + +class MIMEMessage(MIMENonMultipart): + if sys.version_info >= (3, 6): + def __init__(self, _msg: Message, _subtype: str = ..., *, policy: Optional[Policy] = ...) -> None: ... + else: + def __init__(self, _msg: Message, _subtype: str = ...) -> None: ... diff --git a/mypy/stdlib/email/mime/multipart.pyi b/mypy/stdlib/email/mime/multipart.pyi new file mode 100644 index 000000000000..4c78fd4d5745 --- /dev/null +++ b/mypy/stdlib/email/mime/multipart.pyi @@ -0,0 +1,29 @@ +# Stubs for email.mime.multipart (Python 3.4) + +import sys +from email.message import Message +from email.mime.base import MIMEBase +from email.policy import Policy +from typing import Optional, Sequence, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEMultipart(MIMEBase): + if sys.version_info >= (3, 6): + def __init__( + self, + _subtype: str = ..., + boundary: Optional[str] = ..., + _subparts: Optional[Sequence[Message]] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... + else: + def __init__( + self, + _subtype: str = ..., + boundary: Optional[str] = ..., + _subparts: Optional[Sequence[Message]] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/stdlib/email/mime/nonmultipart.pyi b/mypy/stdlib/email/mime/nonmultipart.pyi new file mode 100644 index 000000000000..1fd3ea98bc62 --- /dev/null +++ b/mypy/stdlib/email/mime/nonmultipart.pyi @@ -0,0 +1,5 @@ +# Stubs for email.mime.nonmultipart (Python 3.4) + +from email.mime.base import MIMEBase + +class MIMENonMultipart(MIMEBase): ... diff --git a/mypy/stdlib/email/mime/text.pyi b/mypy/stdlib/email/mime/text.pyi new file mode 100644 index 000000000000..f219e843b865 --- /dev/null +++ b/mypy/stdlib/email/mime/text.pyi @@ -0,0 +1,14 @@ +# Stubs for email.mime.text (Python 3.4) + +import sys +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy +from typing import Optional + +class MIMEText(MIMENonMultipart): + if sys.version_info >= (3, 6): + def __init__( + self, _text: str, _subtype: str = ..., _charset: Optional[str] = ..., *, policy: Optional[Policy] = ... + ) -> None: ... + else: + def __init__(self, _text: str, _subtype: str = ..., _charset: Optional[str] = ...) -> None: ... diff --git a/mypy/stdlib/email/parser.pyi b/mypy/stdlib/email/parser.pyi new file mode 100644 index 000000000000..89ca2774b34a --- /dev/null +++ b/mypy/stdlib/email/parser.pyi @@ -0,0 +1,33 @@ +# Stubs for email.parser (Python 3.4) + +import email.feedparser +from email.message import Message +from email.policy import Policy +from typing import BinaryIO, Callable, TextIO + +FeedParser = email.feedparser.FeedParser +BytesFeedParser = email.feedparser.BytesFeedParser + +class Parser: + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... + def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... + +class HeaderParser(Parser): + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... + def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... + +class BytesHeaderParser(BytesParser): + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... + def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... + +class BytesParser: + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... + def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... diff --git a/mypy/stdlib/email/policy.pyi b/mypy/stdlib/email/policy.pyi new file mode 100644 index 000000000000..5f3b8977af9d --- /dev/null +++ b/mypy/stdlib/email/policy.pyi @@ -0,0 +1,62 @@ +# Stubs for email.policy (Python 3.4) + +from abc import abstractmethod +from typing import Any, List, Optional, Tuple, Union, Callable +from email.message import Message +from email.errors import MessageDefect +from email.header import Header +from email.contentmanager import ContentManager + +class Policy: + max_line_length: Optional[int] + linesep: str + cte_type: str + raise_on_defect: bool + mange_from: bool + def __init__(self, **kw: Any) -> None: ... + def clone(self, **kw: Any) -> Policy: ... + def handle_defect(self, obj: Message, + defect: MessageDefect) -> None: ... + def register_defect(self, obj: Message, + defect: MessageDefect) -> None: ... + def header_max_count(self, name: str) -> Optional[int]: ... + @abstractmethod + def header_source_parse(self, sourcelines: List[str]) -> str: ... + @abstractmethod + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + @abstractmethod + def header_fetch_parse(self, name: str, + value: str) -> str: ... + @abstractmethod + def fold(self, name: str, value: str) -> str: ... + @abstractmethod + def fold_binary(self, name: str, value: str) -> bytes: ... + +class Compat32(Policy): + def header_source_parse(self, sourcelines: List[str]) -> str: ... + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> Union[str, Header]: ... # type: ignore + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +compat32: Compat32 + +class EmailPolicy(Policy): + utf8: bool + refold_source: str + header_factory: Callable[[str, str], str] + content_manager: ContentManager + def header_source_parse(self, sourcelines: List[str]) -> str: ... + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> str: ... + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +default: EmailPolicy +SMTP: EmailPolicy +SMTPUTF8: EmailPolicy +HTTP: EmailPolicy +strict: EmailPolicy diff --git a/mypy/stdlib/email/utils.pyi b/mypy/stdlib/email/utils.pyi new file mode 100644 index 000000000000..6c0a18319759 --- /dev/null +++ b/mypy/stdlib/email/utils.pyi @@ -0,0 +1,33 @@ +# Stubs for email.utils (Python 3.4) + +from typing import List, Optional, Tuple, Union +from email.charset import Charset +import datetime + +_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] +_PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] + +def quote(str: str) -> str: ... +def unquote(str: str) -> str: ... +def parseaddr(address: Optional[str]) -> Tuple[str, str]: ... +def formataddr(pair: Tuple[Optional[str], str], + charset: Union[str, Charset] = ...) -> str: ... +def getaddresses(fieldvalues: List[str]) -> List[Tuple[str, str]]: ... +def parsedate(date: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ... +def parsedate_tz(date: str) -> Optional[_PDTZ]: ... +def parsedate_to_datetime(date: str) -> datetime.datetime: ... +def mktime_tz(tuple: _PDTZ) -> int: ... +def formatdate(timeval: Optional[float] = ..., localtime: bool = ..., + usegmt: bool = ...) -> str: ... +def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ... +def localtime(dt: Optional[datetime.datetime] = ...) -> datetime.datetime: ... +def make_msgid(idstring: Optional[str] = ..., + domain: Optional[str] = ...) -> str: ... +def decode_rfc2231(s: str) -> Tuple[Optional[str], Optional[str], str]: ... +def encode_rfc2231(s: str, charset: Optional[str] = ..., + language: Optional[str] = ...) -> str: ... +def collapse_rfc2231_value(value: _ParamType, errors: str = ..., + fallback_charset: str = ...) -> str: ... +def decode_params( + params: List[Tuple[str, str]] +) -> List[Tuple[str, _ParamType]]: ... diff --git a/mypy/stdlib/encodings/__init__.pyi b/mypy/stdlib/encodings/__init__.pyi new file mode 100644 index 000000000000..c75fd07c6f33 --- /dev/null +++ b/mypy/stdlib/encodings/__init__.pyi @@ -0,0 +1,11 @@ +# This comment serves as a workaround for timothycrosley/isort#1027 and can +# be removed when a release with a fix was released. + +import codecs + +from typing import Any + +def search_function(encoding: str) -> codecs.CodecInfo: ... + +# Explicitly mark this package as incomplete. +def __getattr__(name: str) -> Any: ... diff --git a/mypy/stdlib/encodings/utf_8.pyi b/mypy/stdlib/encodings/utf_8.pyi new file mode 100644 index 000000000000..67e139c88f60 --- /dev/null +++ b/mypy/stdlib/encodings/utf_8.pyi @@ -0,0 +1,15 @@ +import codecs +from typing import Tuple + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = ...) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): ... +class StreamReader(codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: str, errors: str = ...) -> bytes: ... +def decode(input: bytes, errors: str = ...) -> str: ... diff --git a/mypy/stdlib/ensurepip/__init__.pyi b/mypy/stdlib/ensurepip/__init__.pyi new file mode 100644 index 000000000000..10634f2baa6d --- /dev/null +++ b/mypy/stdlib/ensurepip/__init__.pyi @@ -0,0 +1,10 @@ + +from typing import Optional +import sys + + +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: ... diff --git a/mypy/stdlib/enum.pyi b/mypy/stdlib/enum.pyi new file mode 100644 index 000000000000..8ffaa2b5eb1d --- /dev/null +++ b/mypy/stdlib/enum.pyi @@ -0,0 +1,76 @@ +# NB: third_party/2/enum.pyi and stdlib/3.4/enum.pyi must remain consistent! +import sys +from typing import Any, Dict, Iterator, List, Mapping, Type, TypeVar, Union +from abc import ABCMeta + +_T = TypeVar('_T') +_S = TypeVar('_S', bound=Type[Enum]) + +# Note: EnumMeta actually subclasses type directly, not ABCMeta. +# This is a temporary workaround to allow multiple creation of enums with builtins +# such as str as mixins, which due to the handling of ABCs of builtin types, cause +# spurious inconsistent metaclass structure. See #1595. +# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself +class EnumMeta(ABCMeta): + def __iter__(self: Type[_T]) -> Iterator[_T]: ... + def __reversed__(self: Type[_T]) -> Iterator[_T]: ... + def __contains__(self: Type[_T], member: object) -> bool: ... + def __getitem__(self: Type[_T], name: str) -> _T: ... + @property + def __members__(self: Type[_T]) -> Mapping[str, _T]: ... + def __len__(self) -> int: ... + +class Enum(metaclass=EnumMeta): + name: str + value: Any + _name_: str + _value_: Any + _member_names_: List[str] # undocumented + _member_map_: Dict[str, Enum] # undocumented + _value2member_map_: Dict[int, Enum] # undocumented + if sys.version_info >= (3, 7): + _ignore_: Union[str, List[str]] + if sys.version_info >= (3, 6): + _order_: str + __order__: str + @classmethod + def _missing_(cls, value: object) -> Any: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> Any: ... + def __new__(cls: Type[_T], value: object) -> _T: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __dir__(self) -> List[str]: ... + def __format__(self, format_spec: str) -> str: ... + def __hash__(self) -> Any: ... + def __reduce_ex__(self, proto: object) -> Any: ... + +class IntEnum(int, Enum): + value: int + +def unique(enumeration: _S) -> _S: ... + +if sys.version_info >= (3, 6): + _auto_null: Any + + # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() + class auto(IntFlag): + value: Any + + class Flag(Enum): + def __contains__(self: _T, other: _T) -> bool: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __bool__(self) -> bool: ... + def __or__(self: _T, other: _T) -> _T: ... + def __and__(self: _T, other: _T) -> _T: ... + def __xor__(self: _T, other: _T) -> _T: ... + def __invert__(self: _T) -> _T: ... + + class IntFlag(int, Flag): + def __or__(self: _T, other: Union[int, _T]) -> _T: ... + def __and__(self: _T, other: Union[int, _T]) -> _T: ... + def __xor__(self: _T, other: Union[int, _T]) -> _T: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ diff --git a/mypy/stdlib/errno.pyi b/mypy/stdlib/errno.pyi new file mode 100644 index 000000000000..731681f1c6fd --- /dev/null +++ b/mypy/stdlib/errno.pyi @@ -0,0 +1,140 @@ +# Stubs for errno + +from typing import Mapping +import sys + +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/stdlib/faulthandler.pyi b/mypy/stdlib/faulthandler.pyi new file mode 100644 index 000000000000..ffecf3d5daa6 --- /dev/null +++ b/mypy/stdlib/faulthandler.pyi @@ -0,0 +1,12 @@ +import sys +from _typeshed import FileDescriptorLike + +def cancel_dump_traceback_later() -> None: ... +def disable() -> None: ... +def dump_traceback(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ... +def dump_traceback_later(timeout: float, repeat: bool = ..., file: FileDescriptorLike = ..., exit: bool = ...) -> None: ... +def enable(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ... +def is_enabled() -> bool: ... +if sys.platform != "win32": + def register(signum: int, file: FileDescriptorLike = ..., all_threads: bool = ..., chain: bool = ...) -> None: ... + def unregister(signum: int) -> None: ... diff --git a/mypy/stdlib/fcntl.pyi b/mypy/stdlib/fcntl.pyi new file mode 100644 index 000000000000..cfb13ed9c4ee --- /dev/null +++ b/mypy/stdlib/fcntl.pyi @@ -0,0 +1,114 @@ +from array import array +from typing import Any, Union, overload +from typing_extensions import Literal +from _typeshed import FileDescriptorLike + +FASYNC: int +FD_CLOEXEC: int +DN_ACCESS: int +DN_ATTRIB: int +DN_CREATE: int +DN_DELETE: int +DN_MODIFY: int +DN_MULTISHOT: int +DN_RENAME: int +F_DUPFD: int +F_DUPFD_CLOEXEC: int +F_FULLFSYNC: int +F_EXLCK: int +F_GETFD: int +F_GETFL: int +F_GETLEASE: int +F_GETLK: int +F_GETLK64: int +F_GETOWN: int +F_NOCACHE: int +F_GETSIG: int +F_NOTIFY: int +F_RDLCK: int +F_SETFD: int +F_SETFL: int +F_SETLEASE: int +F_SETLK: int +F_SETLK64: int +F_SETLKW: int +F_SETLKW64: int +F_SETOWN: int +F_SETSIG: int +F_SHLCK: int +F_UNLCK: int +F_WRLCK: int +I_ATMARK: int +I_CANPUT: int +I_CKBAND: int +I_FDINSERT: int +I_FIND: int +I_FLUSH: int +I_FLUSHBAND: int +I_GETBAND: int +I_GETCLTIME: int +I_GETSIG: int +I_GRDOPT: int +I_GWROPT: int +I_LINK: int +I_LIST: int +I_LOOK: int +I_NREAD: int +I_PEEK: int +I_PLINK: int +I_POP: int +I_PUNLINK: int +I_PUSH: int +I_RECVFD: int +I_SENDFD: int +I_SETCLTIME: int +I_SETSIG: int +I_SRDOPT: int +I_STR: int +I_SWROPT: int +I_UNLINK: int +LOCK_EX: int +LOCK_MAND: int +LOCK_NB: int +LOCK_READ: int +LOCK_RW: int +LOCK_SH: int +LOCK_UN: int +LOCK_WRITE: int + +@overload +def fcntl(__fd: FileDescriptorLike, + __cmd: int, + __arg: int = ...) -> int: ... +@overload +def fcntl(__fd: FileDescriptorLike, + __cmd: int, + __arg: bytes) -> bytes: ... +_ReadOnlyBuffer = bytes +_WritableBuffer = Union[bytearray, memoryview, array] +@overload +def ioctl(__fd: FileDescriptorLike, + __request: int, + __arg: int = ..., + __mutate_flag: bool = ...) -> int: ... +@overload +def ioctl(__fd: FileDescriptorLike, + __request: int, + __arg: _WritableBuffer, + __mutate_flag: Literal[True] = ...) -> int: ... +@overload +def ioctl(__fd: FileDescriptorLike, + __request: int, + __arg: _WritableBuffer, + __mutate_flag: Literal[False]) -> bytes: ... +@overload +def ioctl(__fd: FileDescriptorLike, + __request: int, + __arg: _ReadOnlyBuffer, + __mutate_flag: bool = ...) -> bytes: ... +def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... +def lockf(__fd: FileDescriptorLike, + __cmd: int, + __len: int = ..., + __start: int = ..., + __whence: int = ...) -> Any: ... diff --git a/mypy/stdlib/filecmp.pyi b/mypy/stdlib/filecmp.pyi new file mode 100644 index 000000000000..3e28f32a9ebd --- /dev/null +++ b/mypy/stdlib/filecmp.pyi @@ -0,0 +1,61 @@ +# Stubs for filecmp (Python 2/3) +import sys +from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Tuple, Union, Text + +if sys.version_info >= (3, 6): + from os import PathLike + +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]]: ... + +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: ... + + 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: ... + +if sys.version_info >= (3,): + def clear_cache() -> None: ... diff --git a/mypy/stdlib/fileinput.pyi b/mypy/stdlib/fileinput.pyi new file mode 100644 index 000000000000..6a015b25220c --- /dev/null +++ b/mypy/stdlib/fileinput.pyi @@ -0,0 +1,76 @@ +from typing import Iterable, Callable, IO, AnyStr, Generic, Any, Union, Iterator, Optional +from _typeshed import AnyPath +import sys + +if sys.version_info >= (3, 8): + def input( + files: Union[AnyPath, Iterable[AnyPath], None] = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str = ..., + openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., + ) -> FileInput[AnyStr]: ... +else: + def input( + files: Union[AnyPath, Iterable[AnyPath], None] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[AnyPath, 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]): + if sys.version_info >= (3, 8): + def __init__( + self, + files: Union[None, AnyPath, Iterable[AnyPath]] = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str = ..., + openhook: Callable[[AnyPath, str], IO[AnyStr]] = ... + ) -> None: ... + else: + def __init__( + self, + files: Union[None, AnyPath, Iterable[AnyPath]] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[AnyPath, 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 __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: 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]]: ... diff --git a/mypy/stdlib/fnmatch.pyi b/mypy/stdlib/fnmatch.pyi new file mode 100644 index 000000000000..4f99b4aafd6d --- /dev/null +++ b/mypy/stdlib/fnmatch.pyi @@ -0,0 +1,11 @@ +# Stubs for fnmatch + +# Based on http://docs.python.org/3.2/library/fnmatch.html and +# python-lib/fnmatch.py + +from typing import Iterable, List, AnyStr + +def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ... +def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... +def filter(names: Iterable[AnyStr], pat: AnyStr) -> List[AnyStr]: ... +def translate(pat: str) -> str: ... diff --git a/mypy/stdlib/formatter.pyi b/mypy/stdlib/formatter.pyi new file mode 100644 index 000000000000..2ddef2be7580 --- /dev/null +++ b/mypy/stdlib/formatter.pyi @@ -0,0 +1,105 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/formatter.py +# and https://github.com/python/cpython/blob/master/Lib/formatter.py +from typing import Any, IO, List, Optional, Tuple, Iterable + +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/stdlib/fractions.pyi b/mypy/stdlib/fractions.pyi new file mode 100644 index 000000000000..81d056a0756e --- /dev/null +++ b/mypy/stdlib/fractions.pyi @@ -0,0 +1,95 @@ +# Stubs for fractions +# See https://docs.python.org/3/library/fractions.html +# +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. Also see numbers.pyi. + +from typing import Optional, TypeVar, Union, overload, Any, Tuple +from numbers import Real, Integral, Rational +from decimal import Decimal +import sys + +_ComparableNum = Union[int, float, Decimal, Real] + + +if sys.version_info < (3, 9): + @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, + numerator: Union[int, Rational] = ..., + denominator: Optional[Union[int, Rational]] = ..., + *, + _normalize: bool = ...) -> Fraction: ... + @overload + def __new__(cls, __value: Union[float, Decimal, str], *, _normalize: bool = ...) -> Fraction: ... + + @classmethod + def from_float(cls, f: float) -> Fraction: ... + @classmethod + def from_decimal(cls, dec: Decimal) -> Fraction: ... + def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... + + if sys.version_info >= (3, 8): + def as_integer_ratio(self) -> Tuple[int, int]: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + + def __add__(self, other): ... + def __radd__(self, other): ... + def __sub__(self, other): ... + def __rsub__(self, other): ... + def __mul__(self, other): ... + def __rmul__(self, other): ... + def __truediv__(self, other): ... + def __rtruediv__(self, other): ... + if sys.version_info < (3, 0): + def __div__(self, other): ... + def __rdiv__(self, other): ... + def __floordiv__(self, other) -> int: ... + def __rfloordiv__(self, other) -> int: ... + def __mod__(self, other): ... + def __rmod__(self, other): ... + def __divmod__(self, other): ... + def __rdivmod__(self, other): ... + def __pow__(self, other): ... + def __rpow__(self, other): ... + + def __pos__(self) -> Fraction: ... + 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: ... + def __round__(self, ndigits: Optional[Any] = ...): ... + + 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: ... + + # Not actually defined within fractions.py, but provides more useful + # overrides + @property + def real(self) -> Fraction: ... + @property + def imag(self) -> Fraction: ... + def conjugate(self) -> Fraction: ... diff --git a/mypy/stdlib/ftplib.pyi b/mypy/stdlib/ftplib.pyi new file mode 100644 index 000000000000..0c708b3695d2 --- /dev/null +++ b/mypy/stdlib/ftplib.pyi @@ -0,0 +1,168 @@ +import sys +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Generic, + Iterable, + Iterator, + List, + Optional, + Text, + TextIO, + Tuple, + Type, + TypeVar, + Union, +) +from types import TracebackType +from socket import socket +from ssl import SSLContext +from _typeshed import SupportsRead, SupportsReadline + +_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 + +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 + + 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: ... + 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: ... + 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 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: ... + 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, ...]: ... diff --git a/mypy/stdlib/functools.pyi b/mypy/stdlib/functools.pyi new file mode 100644 index 000000000000..beccc37a1f50 --- /dev/null +++ b/mypy/stdlib/functools.pyi @@ -0,0 +1,113 @@ +import sys +from typing import Any, Callable, Generic, Dict, Hashable, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, NamedTuple, Union, overload + +_AnyCallable = Callable[..., Any] + +_T = TypeVar("_T") +_S = TypeVar("_S") + +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... + +class _CacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int + currsize: int + +class _lru_cache_wrapper(Generic[_T]): + __wrapped__: Callable[..., _T] + def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... + def cache_info(self) -> _CacheInfo: ... + def cache_clear(self) -> None: ... + +if sys.version_info >= (3, 8): + @overload + def lru_cache(maxsize: Optional[int] = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... + @overload + def lru_cache(maxsize: Callable[..., _T], typed: bool = ...) -> _lru_cache_wrapper[_T]: ... +else: + def lru_cache(maxsize: Optional[int] = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... + +WRAPPER_ASSIGNMENTS: Sequence[str] +WRAPPER_UPDATES: Sequence[str] + +def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., + updated: Sequence[str] = ...) -> _AnyCallable: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... +def total_ordering(cls: Type[_T]) -> Type[_T]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... + +class partial(Generic[_T]): + func: Callable[..., _T] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + +# With protocols, this could change into a generic protocol that defines __get__ and returns _T +_Descriptor = Any + +class partialmethod(Generic[_T]): + func: Union[Callable[..., _T], _Descriptor] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + + @overload + def __init__(self, func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... + @overload + def __init__(self, func: _Descriptor, *args: Any, **keywords: Any) -> None: ... + def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ... + @property + def __isabstractmethod__(self) -> bool: ... + +class _SingleDispatchCallable(Generic[_T]): + registry: Mapping[Any, Callable[..., _T]] + def dispatch(self, cls: Any) -> Callable[..., _T]: ... + @overload + def register(self, cls: Any) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Any, func: Callable[..., _T]) -> Callable[..., _T]: ... + def _clear_cache(self) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + +def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... + +if sys.version_info >= (3, 8): + class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @overload + def register(self, cls: Any, method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Any, method: Callable[..., _T]) -> Callable[..., _T]: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + + class cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: Optional[str] + def __init__(self, func: Callable[[Any], _T]) -> None: ... + @overload + def __get__(self, instance: None, owner: Optional[Type[Any]] = ...) -> cached_property[_T]: ... + @overload + def __get__(self, instance: _S, owner: Optional[Type[Any]] = ...) -> _T: ... + def __set_name__(self, owner: Type[Any], name: str) -> None: ... + +if sys.version_info >= (3, 9): + class TopologicalSorter(Generic[_T]): + def __init__(self, graph: Optional[Dict[_T, Iterable[_T]]] = ...) -> None: ... + def add(self, node: _T, *predecessors: _T) -> None: ... + def prepare(self) -> None: ... + def is_active(self) -> bool: ... + def done(self, *nodes: _T) -> None: ... + def get_ready(self) -> Tuple[_T, ...]: ... + def static_order(self) -> Iterable[_T]: ... + + class CycleError(ValueError): ... + + def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... diff --git a/mypy/stdlib/gc.pyi b/mypy/stdlib/gc.pyi new file mode 100644 index 000000000000..80398ee2a753 --- /dev/null +++ b/mypy/stdlib/gc.pyi @@ -0,0 +1,32 @@ +# Stubs for gc + +import sys +from typing import Any, Dict, List, Optional, Tuple + + +DEBUG_COLLECTABLE: int +DEBUG_LEAK: int +DEBUG_SAVEALL: int +DEBUG_STATS: int +DEBUG_UNCOLLECTABLE: int +callbacks: List[Any] +garbage: List[Any] + +def collect(generation: int = ...) -> int: ... +def disable() -> None: ... +def enable() -> None: ... +def get_count() -> Tuple[int, int, int]: ... +def get_debug() -> int: ... +if sys.version_info >= (3, 8): + def get_objects(generation: Optional[int] = ...) -> List[Any]: ... +else: + def get_objects() -> List[Any]: ... +def get_referents(*objs: Any) -> List[Any]: ... +def get_referrers(*objs: Any) -> List[Any]: ... +def get_stats() -> List[Dict[str, Any]]: ... +def get_threshold() -> Tuple[int, int, int]: ... +def is_tracked(__obj: Any) -> bool: ... +def isenabled() -> bool: ... +def set_debug(__flags: int) -> None: ... +def set_threshold(threshold0: int, threshold1: int = ..., + threshold2: int = ...) -> None: ... diff --git a/mypy/stdlib/genericpath.pyi b/mypy/stdlib/genericpath.pyi new file mode 100644 index 000000000000..267900c90e5d --- /dev/null +++ b/mypy/stdlib/genericpath.pyi @@ -0,0 +1,24 @@ +from typing import Sequence, AnyStr, Text, Union +import sys + +if sys.version_info >= (3, 0): + def commonprefix(m: Sequence[str]) -> str: ... +else: + def commonprefix(m: Sequence[AnyStr]) -> AnyStr: ... +if sys.version_info >= (3, 6): + from builtins import _PathLike + def exists(path: Union[AnyStr, _PathLike[AnyStr]]) -> bool: ... +else: + def exists(path: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def getsize(filename: Text) -> int: ... +def getmtime(filename: Text) -> float: ... +def getatime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... + + +if sys.version_info >= (3, 4): + def samestat(s1: str, s2: str) -> int: ... + def samefile(f1: str, f2: str) -> int: ... + def sameopenfile(fp1: str, fp2: str) -> int: ... diff --git a/mypy/stdlib/getopt.pyi b/mypy/stdlib/getopt.pyi new file mode 100644 index 000000000000..0417a827ab61 --- /dev/null +++ b/mypy/stdlib/getopt.pyi @@ -0,0 +1,14 @@ +# Stubs for getopt + +# Based on http://docs.python.org/3.2/library/getopt.html + +from typing import List, Tuple + +def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... + +class GetoptError(Exception): + msg: str + opt: str + +error = GetoptError diff --git a/mypy/stdlib/getpass.pyi b/mypy/stdlib/getpass.pyi new file mode 100644 index 000000000000..55a8433fca43 --- /dev/null +++ b/mypy/stdlib/getpass.pyi @@ -0,0 +1,12 @@ +# Stubs for getpass + +from typing import Optional, TextIO + + +def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... + + +def getuser() -> str: ... + + +class GetPassWarning(UserWarning): ... diff --git a/mypy/stdlib/gettext.pyi b/mypy/stdlib/gettext.pyi new file mode 100644 index 000000000000..b28f25b2a8d5 --- /dev/null +++ b/mypy/stdlib/gettext.pyi @@ -0,0 +1,63 @@ +import sys +from typing import overload, Any, Container, IO, Iterable, Optional, Sequence, Type, TypeVar, Union +from _typeshed import StrPath +from typing_extensions import Literal + +class NullTranslations: + def __init__(self, fp: Optional[IO[str]] = ...) -> None: ... + def _parse(self, fp: IO[str]) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def lgettext(self, message: str) -> str: ... + def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... + def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... + if sys.version_info >= (3, 8): + def pgettext(self, context: str, message: str) -> str: ... + def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... + def info(self) -> Any: ... + def charset(self) -> Any: ... + def output_charset(self) -> Any: ... + def set_output_charset(self, charset: str) -> None: ... + def install(self, names: Optional[Container[str]] = ...) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC: int + BE_MAGIC: int + CONTEXT: str + VERSIONS: Sequence[int] + +def find(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., + all: bool = ...) -> Any: ... + +_T = TypeVar('_T') +@overload +def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., + class_: None = ..., fallback: bool = ..., codeset: Optional[str] = ...) -> NullTranslations: ... +@overload +def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., + class_: Type[_T] = ..., fallback: Literal[False] = ..., codeset: Optional[str] = ...) -> _T: ... +@overload +def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., + class_: Type[_T] = ..., fallback: Literal[True] = ..., codeset: Optional[str] = ...) -> Any: ... + +def install(domain: str, localedir: Optional[StrPath] = ..., codeset: Optional[str] = ..., + names: Optional[Container[str]] = ...) -> None: ... + +def textdomain(domain: Optional[str] = ...) -> str: ... +def bindtextdomain(domain: str, localedir: Optional[StrPath] = ...) -> str: ... +def bind_textdomain_codeset(domain: str, codeset: Optional[str] = ...) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def ldgettext(domain: str, message: str) -> str: ... +def dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... +def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... +def gettext(message: str) -> str: ... +def lgettext(message: str) -> str: ... +def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... +def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... +if sys.version_info >= (3, 8): + def pgettext(context: str, message: str) -> str: ... + def dpgettext(domain: str, context: str, message: str) -> str: ... + def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... + def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... + +Catalog = translation diff --git a/mypy/stdlib/glob.pyi b/mypy/stdlib/glob.pyi new file mode 100644 index 000000000000..5e73a79712a1 --- /dev/null +++ b/mypy/stdlib/glob.pyi @@ -0,0 +1,19 @@ +# Stubs for glob +# Based on http://docs.python.org/3/library/glob.html + +from typing import List, Iterator, AnyStr, Union +import sys + +if sys.version_info >= (3, 6): + def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... +else: + def glob0(dirname: AnyStr, basename: AnyStr) -> List[AnyStr]: ... + +def glob1(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... + +def glob(pathname: AnyStr, *, recursive: bool = ...) -> List[AnyStr]: ... +def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ... + +def escape(pathname: AnyStr) -> AnyStr: ... + +def has_magic(s: Union[str, bytes]) -> bool: ... # undocumented diff --git a/mypy/stdlib/grp.pyi b/mypy/stdlib/grp.pyi new file mode 100644 index 000000000000..5b5855583243 --- /dev/null +++ b/mypy/stdlib/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(gid: int) -> struct_group: ... +def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/stdlib/gzip.pyi b/mypy/stdlib/gzip.pyi new file mode 100644 index 000000000000..f2976dcb2ee4 --- /dev/null +++ b/mypy/stdlib/gzip.pyi @@ -0,0 +1,92 @@ +import sys +import zlib +from typing import IO, Optional, TextIO, Union, overload +import _compression +from _typeshed import AnyPath, ReadableBuffer +from typing_extensions import Literal + +_OpenBinaryMode = Literal["r", "rb", "a", "ab", "w", "wb", "x", "xb"] +_OpenTextMode = Literal["rt", "at", "wt", "xt"] + +@overload +def open( + filename: Union[AnyPath, IO[bytes]], + mode: _OpenBinaryMode = ..., + compresslevel: int = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> GzipFile: ... +@overload +def open( + filename: AnyPath, + mode: _OpenTextMode, + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> TextIO: ... +@overload +def open( + filename: Union[AnyPath, IO[bytes]], + mode: str, + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> Union[GzipFile, TextIO]: ... + +class _PaddedFile: + file: IO[bytes] + def __init__(self, f: IO[bytes], prepend: bytes = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def prepend(self, prepend: bytes = ...) -> None: ... + def seek(self, off: int) -> int: ... + def seekable(self) -> bool: ... + +class GzipFile(_compression.BaseStream): + myfileobj: Optional[IO[bytes]] + mode: str + name: str + compress: zlib._Compress + fileobj: IO[bytes] + def __init__( + self, + filename: Optional[AnyPath] = ..., + mode: Optional[str] = ..., + compresslevel: int = ..., + fileobj: Optional[IO[bytes]] = ..., + mtime: Optional[float] = ..., + ) -> None: ... + @property + def filename(self) -> str: ... + @property + def mtime(self) -> Optional[int]: ... + crc: int + def write(self, data: ReadableBuffer) -> int: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def peek(self, n: int) -> bytes: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def flush(self, zlib_mode: int = ...) -> None: ... + def fileno(self) -> int: ... + def rewind(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def readline(self, size: Optional[int] = ...) -> bytes: ... + +class _GzipReader(_compression.DecompressReader): + def __init__(self, fp: IO[bytes]) -> None: ... + def read(self, size: int = ...) -> bytes: ... + +if sys.version_info >= (3, 8): + def compress(data, compresslevel: int = ..., *, mtime: Optional[float] = ...) -> bytes: ... + +else: + def compress(data, compresslevel: int = ...) -> bytes: ... + +def decompress(data: bytes) -> bytes: ... diff --git a/mypy/stdlib/hashlib.pyi b/mypy/stdlib/hashlib.pyi new file mode 100644 index 000000000000..0a15ab0d8651 --- /dev/null +++ b/mypy/stdlib/hashlib.pyi @@ -0,0 +1,86 @@ +# Stubs for hashlib + +import sys +from typing import AbstractSet, Optional, Union +from _typeshed import ReadableBuffer + +class _Hash(object): + digest_size: int + block_size: int + + # [Python documentation note] Changed in version 3.4: The name attribute has + # been present in CPython since its inception, but until Python 3.4 was not + # formally specified, so may not exist on some platforms + name: str + + def __init__(self, data: ReadableBuffer = ...) -> None: ... + + def copy(self) -> _Hash: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, __data: ReadableBuffer) -> None: ... + +if sys.version_info >= (3, 9): + def md5(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha1(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha224(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha256(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha384(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + def sha512(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... +elif sys.version_info >= (3, 8): + def md5(string: ReadableBuffer = ...) -> _Hash: ... + def sha1(string: ReadableBuffer = ...) -> _Hash: ... + def sha224(string: ReadableBuffer = ...) -> _Hash: ... + def sha256(string: ReadableBuffer = ...) -> _Hash: ... + def sha384(string: ReadableBuffer = ...) -> _Hash: ... + def sha512(string: ReadableBuffer = ...) -> _Hash: ... +else: + def md5(__string: ReadableBuffer = ...) -> _Hash: ... + def sha1(__string: ReadableBuffer = ...) -> _Hash: ... + def sha224(__string: ReadableBuffer = ...) -> _Hash: ... + def sha256(__string: ReadableBuffer = ...) -> _Hash: ... + def sha384(__string: ReadableBuffer = ...) -> _Hash: ... + def sha512(__string: ReadableBuffer = ...) -> _Hash: ... + +def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... + +algorithms_guaranteed: AbstractSet[str] +algorithms_available: AbstractSet[str] + +def pbkdf2_hmac(hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: Optional[int] = ...) -> bytes: ... + +if sys.version_info >= (3, 6): + class _VarLenHash(object): + digest_size: int + block_size: int + name: str + + def __init__(self, data: ReadableBuffer = ...) -> None: ... + + def copy(self) -> _VarLenHash: ... + def digest(self, __length: int) -> bytes: ... + def hexdigest(self, __length: int) -> str: ... + def update(self, __data: ReadableBuffer) -> None: ... + + sha3_224 = _Hash + sha3_256 = _Hash + sha3_384 = _Hash + sha3_512 = _Hash + shake_128 = _VarLenHash + shake_256 = _VarLenHash + + def scrypt(password: ReadableBuffer, *, salt: Optional[ReadableBuffer] = ..., n: Optional[int] = ..., r: Optional[int] = ..., p: Optional[int] = ..., maxmem: int = ..., dklen: int = ...) -> bytes: ... + + class _BlakeHash(_Hash): + MAX_DIGEST_SIZE: int + MAX_KEY_SIZE: int + PERSON_SIZE: int + SALT_SIZE: int + + if sys.version_info >= (3, 9): + def __init__(self, __data: ReadableBuffer = ..., *, digest_size: int = ..., key: ReadableBuffer = ..., salt: ReadableBuffer = ..., person: ReadableBuffer = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ..., usedforsecurity: bool = ...) -> None: ... + else: + def __init__(self, __data: ReadableBuffer = ..., *, digest_size: int = ..., key: ReadableBuffer = ..., salt: ReadableBuffer = ..., person: ReadableBuffer = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ...) -> None: ... + + blake2b = _BlakeHash + blake2s = _BlakeHash diff --git a/mypy/stdlib/heapq.pyi b/mypy/stdlib/heapq.pyi new file mode 100644 index 000000000000..1b060188093e --- /dev/null +++ b/mypy/stdlib/heapq.pyi @@ -0,0 +1,18 @@ +# Stubs for heapq + +# Based on http://docs.python.org/3.2/library/heapq.html + +from typing import TypeVar, List, Iterable, Any, Callable, Optional + +_T = TypeVar('_T') + +def heappush(__heap: List[_T], __item: _T) -> None: ... +def heappop(__heap: List[_T]) -> _T: ... +def heappushpop(__heap: List[_T], __item: _T) -> _T: ... +def heapify(__heap: List[_T]) -> None: ... +def heapreplace(__heap: List[_T], __item: _T) -> _T: ... +def merge(*iterables: Iterable[_T], key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> Iterable[_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/stdlib/hmac.pyi b/mypy/stdlib/hmac.pyi new file mode 100644 index 000000000000..d140f1594333 --- /dev/null +++ b/mypy/stdlib/hmac.pyi @@ -0,0 +1,47 @@ +# Stubs for hmac + +from typing import Any, AnyStr, Callable, Optional, Union, overload +from types import ModuleType +import sys +from _typeshed import ReadableBuffer + +_B = Union[bytes, bytearray] + +# TODO more precise type for object of hashlib +_Hash = Any +_DigestMod = Union[str, Callable[[], _Hash], ModuleType] + +digest_size: None + +if sys.version_info >= (3, 8): + # In reality digestmod has a default value, but the function always throws an error + # if the argument is not given, so we pretend it is a required argument. + @overload + def new(key: _B, msg: Optional[ReadableBuffer], digestmod: _DigestMod) -> HMAC: ... + @overload + def new(key: _B, *, digestmod: _DigestMod) -> HMAC: ... +elif sys.version_info >= (3, 4): + def new(key: _B, msg: Optional[ReadableBuffer] = ..., + digestmod: Optional[_DigestMod] = ...) -> HMAC: ... +else: + def new(key: _B, 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 + 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: ... + +if sys.version_info >= (3, 7): + def digest(key: _B, msg: ReadableBuffer, digest: str) -> bytes: ... diff --git a/mypy/stdlib/html/__init__.pyi b/mypy/stdlib/html/__init__.pyi new file mode 100644 index 000000000000..af2a80021656 --- /dev/null +++ b/mypy/stdlib/html/__init__.pyi @@ -0,0 +1,4 @@ +from typing import AnyStr + +def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... +def unescape(s: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/html/entities.pyi b/mypy/stdlib/html/entities.pyi new file mode 100644 index 000000000000..97d9b2d320bc --- /dev/null +++ b/mypy/stdlib/html/entities.pyi @@ -0,0 +1,6 @@ +from typing import Dict + +name2codepoint: Dict[str, int] +html5: Dict[str, str] +codepoint2name: Dict[int, str] +entitydefs: Dict[str, str] diff --git a/mypy/stdlib/html/parser.pyi b/mypy/stdlib/html/parser.pyi new file mode 100644 index 000000000000..4c037845a3b0 --- /dev/null +++ b/mypy/stdlib/html/parser.pyi @@ -0,0 +1,23 @@ +from typing import List, Optional, Tuple +from _markupbase import ParserBase + +class HTMLParser(ParserBase): + def __init__(self, *, convert_charrefs: bool = ...) -> None: ... + def feed(self, feed: str) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + def getpos(self) -> Tuple[int, int]: ... + def get_starttag_text(self) -> Optional[str]: ... + + def handle_starttag(self, tag: str, + attrs: List[Tuple[str, Optional[str]]]) -> None: ... + def handle_endtag(self, tag: str) -> None: ... + def handle_startendtag(self, tag: str, + attrs: List[Tuple[str, Optional[str]]]) -> None: ... + def handle_data(self, data: str) -> None: ... + def handle_entityref(self, name: str) -> None: ... + def handle_charref(self, name: str) -> None: ... + def handle_comment(self, data: str) -> None: ... + def handle_decl(self, decl: str) -> None: ... + def handle_pi(self, data: str) -> None: ... + def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/stdlib/http/__init__.pyi b/mypy/stdlib/http/__init__.pyi new file mode 100644 index 000000000000..93895549cb2a --- /dev/null +++ b/mypy/stdlib/http/__init__.pyi @@ -0,0 +1,74 @@ +import sys +from enum import IntEnum +from typing_extensions import Literal + +class HTTPStatus(IntEnum): + @property + def phrase(self) -> str: ... + @property + def description(self) -> str: ... + CONTINUE: int + SWITCHING_PROTOCOLS: int + PROCESSING: int + OK: int + CREATED: int + ACCEPTED: int + NON_AUTHORITATIVE_INFORMATION: int + NO_CONTENT: int + RESET_CONTENT: int + PARTIAL_CONTENT: int + MULTI_STATUS: int + ALREADY_REPORTED: int + IM_USED: int + MULTIPLE_CHOICES: int + MOVED_PERMANENTLY: int + FOUND: int + SEE_OTHER: int + NOT_MODIFIED: int + USE_PROXY: int + TEMPORARY_REDIRECT: int + PERMANENT_REDIRECT: int + BAD_REQUEST: int + UNAUTHORIZED: int + PAYMENT_REQUIRED: int + FORBIDDEN: int + NOT_FOUND: int + METHOD_NOT_ALLOWED: int + NOT_ACCEPTABLE: int + PROXY_AUTHENTICATION_REQUIRED: int + REQUEST_TIMEOUT: int + CONFLICT: int + GONE: int + LENGTH_REQUIRED: int + PRECONDITION_FAILED: int + REQUEST_ENTITY_TOO_LARGE: int + REQUEST_URI_TOO_LONG: int + UNSUPPORTED_MEDIA_TYPE: int + REQUESTED_RANGE_NOT_SATISFIABLE: int + EXPECTATION_FAILED: int + UNPROCESSABLE_ENTITY: int + LOCKED: int + FAILED_DEPENDENCY: int + UPGRADE_REQUIRED: int + PRECONDITION_REQUIRED: int + TOO_MANY_REQUESTS: int + REQUEST_HEADER_FIELDS_TOO_LARGE: int + INTERNAL_SERVER_ERROR: int + NOT_IMPLEMENTED: int + BAD_GATEWAY: int + SERVICE_UNAVAILABLE: int + GATEWAY_TIMEOUT: int + HTTP_VERSION_NOT_SUPPORTED: int + VARIANT_ALSO_NEGOTIATES: int + INSUFFICIENT_STORAGE: int + LOOP_DETECTED: int + NOT_EXTENDED: int + NETWORK_AUTHENTICATION_REQUIRED: int + if sys.version_info >= (3, 7): + MISDIRECTED_REQUEST: int + if sys.version_info >= (3, 8): + UNAVAILABLE_FOR_LEGAL_REASONS: int + if sys.version_info >= (3, 9): + EARLY_HINTS: Literal[103] + IM_A_TEAPOT: Literal[418] + TOO_EARLY: Literal[425] diff --git a/mypy/stdlib/http/client.pyi b/mypy/stdlib/http/client.pyi new file mode 100644 index 000000000000..8b1007e40df3 --- /dev/null +++ b/mypy/stdlib/http/client.pyi @@ -0,0 +1,200 @@ +from typing import ( + Any, Dict, IO, Iterable, List, Iterator, Mapping, Optional, + Protocol, Tuple, Type, TypeVar, + Union, + overload, + BinaryIO, +) +import email.message +import io +from socket import socket +import sys +import ssl +import types + +_DataType = Union[bytes, IO[Any], Iterable[bytes], str] +_T = TypeVar('_T') + +HTTP_PORT: int +HTTPS_PORT: int + +CONTINUE: int +SWITCHING_PROTOCOLS: int +PROCESSING: int + +OK: int +CREATED: int +ACCEPTED: int +NON_AUTHORITATIVE_INFORMATION: int +NO_CONTENT: int +RESET_CONTENT: int +PARTIAL_CONTENT: int +MULTI_STATUS: int +IM_USED: int + +MULTIPLE_CHOICES: int +MOVED_PERMANENTLY: int +FOUND: int +SEE_OTHER: int +NOT_MODIFIED: int +USE_PROXY: int +TEMPORARY_REDIRECT: int + +BAD_REQUEST: int +UNAUTHORIZED: int +PAYMENT_REQUIRED: int +FORBIDDEN: int +NOT_FOUND: int +METHOD_NOT_ALLOWED: int +NOT_ACCEPTABLE: int +PROXY_AUTHENTICATION_REQUIRED: int +REQUEST_TIMEOUT: int +CONFLICT: int +GONE: int +LENGTH_REQUIRED: int +PRECONDITION_FAILED: int +REQUEST_ENTITY_TOO_LARGE: int +REQUEST_URI_TOO_LONG: int +UNSUPPORTED_MEDIA_TYPE: int +REQUESTED_RANGE_NOT_SATISFIABLE: int +EXPECTATION_FAILED: int +UNPROCESSABLE_ENTITY: int +LOCKED: int +FAILED_DEPENDENCY: int +UPGRADE_REQUIRED: int +PRECONDITION_REQUIRED: int +TOO_MANY_REQUESTS: int +REQUEST_HEADER_FIELDS_TOO_LARGE: int + +INTERNAL_SERVER_ERROR: int +NOT_IMPLEMENTED: int +BAD_GATEWAY: int +SERVICE_UNAVAILABLE: int +GATEWAY_TIMEOUT: int +HTTP_VERSION_NOT_SUPPORTED: int +INSUFFICIENT_STORAGE: int +NOT_EXTENDED: int +NETWORK_AUTHENTICATION_REQUIRED: int + +responses: Dict[int, str] + +class HTTPMessage(email.message.Message): ... + +class HTTPResponse(io.BufferedIOBase, BinaryIO): + msg: HTTPMessage + headers: HTTPMessage + version: int + debuglevel: int + closed: bool + status: int + reason: str + def __init__(self, sock: socket, debuglevel: int = ..., + method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... + def read(self, amt: Optional[int] = ...) -> bytes: ... + @overload + def getheader(self, name: str) -> Optional[str]: ... + @overload + def getheader(self, name: str, default: _T) -> Union[str, _T]: ... + def getheaders(self) -> List[Tuple[str, str]]: ... + def fileno(self) -> int: ... + def isclosed(self) -> bool: ... + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> HTTPResponse: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> Optional[bool]: ... + def info(self) -> email.message.Message: ... + def geturl(self) -> str: ... + def getcode(self) -> int: ... + def begin(self) -> None: ... + +# This is an API stub only for the class below, not a class itself. +# urllib.request uses it for a parameter. +class _HTTPConnectionProtocol(Protocol): + if sys.version_info >= (3, 7): + def __call__( + self, + host: str, + port: Optional[int] = ..., + timeout: float = ..., + source_address: Optional[Tuple[str, int]] = ..., + blocksize: int = ..., + ) -> HTTPConnection: ... + else: + def __call__( + self, host: str, port: Optional[int] = ..., timeout: float = ..., source_address: Optional[Tuple[str, int]] = ..., + ) -> HTTPConnection: ... + +class HTTPConnection: + timeout: Optional[float] + host: str + port: int + sock: Any + if sys.version_info >= (3, 7): + def __init__( + self, + host: str, port: Optional[int] = ..., + timeout: Optional[float] = ..., + source_address: Optional[Tuple[str, int]] = ..., blocksize: int = ... + ) -> None: ... + else: + def __init__( + self, + host: str, port: Optional[int] = ..., + timeout: Optional[float] = ..., + source_address: Optional[Tuple[str, int]] = ... + ) -> None: ... + if sys.version_info >= (3, 6): + def request(self, method: str, url: str, + body: Optional[_DataType] = ..., + headers: Mapping[str, str] = ..., + *, encode_chunked: bool = ...) -> None: ... + else: + def request(self, method: str, url: str, + body: Optional[_DataType] = ..., + headers: Mapping[str, str] = ...) -> None: ... + def getresponse(self) -> HTTPResponse: ... + def set_debuglevel(self, level: int) -> None: ... + def set_tunnel(self, host: str, port: Optional[int] = ..., + headers: Optional[Mapping[str, str]] = ...) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def putrequest(self, method: str, url: str, skip_host: bool = ..., + skip_accept_encoding: bool = ...) -> None: ... + def putheader(self, header: str, *argument: str) -> None: ... + if sys.version_info >= (3, 6): + def endheaders(self, message_body: Optional[_DataType] = ..., + *, encode_chunked: bool = ...) -> None: ... + else: + def endheaders(self, message_body: Optional[_DataType] = ...) -> None: ... + def send(self, data: _DataType) -> None: ... + +class HTTPSConnection(HTTPConnection): + def __init__(self, + host: str, port: Optional[int] = ..., + key_file: Optional[str] = ..., + cert_file: Optional[str] = ..., + timeout: Optional[float] = ..., + source_address: Optional[Tuple[str, int]] = ..., + *, context: Optional[ssl.SSLContext] = ..., + check_hostname: Optional[bool] = ...) -> None: ... + +class HTTPException(Exception): ... +error = HTTPException + +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... +class UnknownProtocol(HTTPException): ... +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... +class IncompleteRead(HTTPException): ... + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): ... +class LineTooLong(HTTPException): ... + +class RemoteDisconnected(ConnectionResetError, BadStatusLine): ... diff --git a/mypy/stdlib/http/cookiejar.pyi b/mypy/stdlib/http/cookiejar.pyi new file mode 100644 index 000000000000..44d7b51345ab --- /dev/null +++ b/mypy/stdlib/http/cookiejar.pyi @@ -0,0 +1,123 @@ +import sys +from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload +from http.client import HTTPResponse +from urllib.request import Request +if sys.version_info >= (3, 6): + from os import PathLike + +_T = TypeVar('_T') + +class LoadError(OSError): ... + + +class CookieJar(Iterable[Cookie]): + def __init__(self, policy: Optional[CookiePolicy] = ...) -> None: ... + def add_cookie_header(self, request: Request) -> None: ... + def extract_cookies(self, response: HTTPResponse, + request: Request) -> None: ... + def set_policy(self, policy: CookiePolicy) -> None: ... + def make_cookies(self, response: HTTPResponse, + request: Request) -> Sequence[Cookie]: ... + def set_cookie(self, cookie: Cookie) -> None: ... + def set_cookie_if_ok(self, cookie: Cookie, + request: Request) -> None: ... + def clear(self, domain: str = ..., path: str = ..., + name: str = ...) -> None: ... + def clear_session_cookies(self) -> None: ... + def __iter__(self) -> Iterator[Cookie]: ... + def __len__(self) -> int: ... + +class FileCookieJar(CookieJar): + filename: str + delayload: bool + if sys.version_info >= (3, 8): + def __init__(self, filename: Union[str, PathLike[str]] = ..., delayload: bool = ..., + policy: Optional[CookiePolicy] = ...) -> None: ... + else: + def __init__(self, filename: str = ..., delayload: bool = ..., + policy: Optional[CookiePolicy] = ...) -> None: ... + def save(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + +class MozillaCookieJar(FileCookieJar): ... + +class LWPCookieJar(FileCookieJar): + def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented + +class CookiePolicy: + netscape: bool + rfc2965: bool + hide_cookie2: bool + def set_ok(self, cookie: Cookie, request: Request) -> bool: ... + def return_ok(self, cookie: Cookie, request: Request) -> bool: ... + def domain_return_ok(self, domain: str, request: Request) -> bool: ... + def path_return_ok(self, path: str, request: Request) -> bool: ... + + +class DefaultCookiePolicy(CookiePolicy): + rfc2109_as_netscape: bool + strict_domain: bool + strict_rfc2965_unverifiable: bool + strict_ns_unverifiable: bool + strict_ns_domain: int + strict_ns_set_initial_dollar: bool + strict_ns_set_path: bool + DomainStrictNoDots: int + DomainStrictNonDomain: int + DomainRFC2965Match: int + DomainLiberal: int + DomainStrict: int + def __init__(self, blocked_domains: Optional[Sequence[str]] = ..., + allowed_domains: Optional[Sequence[str]] = ..., + netscape: bool = ..., + rfc2965: bool = ..., + rfc2109_as_netscape: Optional[bool] = ..., + hide_cookie2: bool = ..., strict_domain: bool = ..., + strict_rfc2965_unverifiable: bool = ..., + strict_ns_unverifiable: bool = ..., + strict_ns_domain: int = ..., + strict_ns_set_initial_dollar: bool = ..., + strict_ns_set_path: bool = ...) -> None: ... + def blocked_domains(self) -> Tuple[str, ...]: ... + def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... + def is_blocked(self, domain: str) -> bool: ... + def allowed_domains(self) -> Optional[Tuple[str, ...]]: ... + def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) -> None: ... + def is_not_allowed(self, domain: str) -> bool: ... + + +class Cookie: + version: Optional[int] + name: str + value: Optional[str] + port: Optional[str] + path: str + secure: bool + expires: Optional[int] + discard: bool + comment: Optional[str] + comment_url: Optional[str] + rfc2109: bool + port_specified: bool + domain: str # undocumented + domain_specified: bool + domain_initial_dot: bool + def __init__(self, version: Optional[int], name: str, value: Optional[str], # undocumented + port: Optional[str], port_specified: bool, + domain: str, domain_specified: bool, domain_initial_dot: bool, + path: str, path_specified: bool, + secure: bool, expires: Optional[int], discard: bool, + comment: Optional[str], comment_url: Optional[str], + rest: Dict[str, str], + rfc2109: bool = ...) -> None: ... + def has_nonstandard_attr(self, name: str) -> bool: ... + @overload + def get_nonstandard_attr(self, name: str) -> Optional[str]: ... + @overload + def get_nonstandard_attr(self, name: str, default: _T = ...) -> Union[str, _T]: ... + def set_nonstandard_attr(self, name: str, value: str) -> None: ... + def is_expired(self, now: int = ...) -> bool: ... diff --git a/mypy/stdlib/http/cookies.pyi b/mypy/stdlib/http/cookies.pyi new file mode 100644 index 000000000000..b2fb13907caf --- /dev/null +++ b/mypy/stdlib/http/cookies.pyi @@ -0,0 +1,35 @@ +# Stubs for http.cookies (Python 3.5) + +import sys +from typing import Generic, Dict, List, Mapping, Optional, TypeVar, Union, Any + +_DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] +_T = TypeVar('_T') + +class CookieError(Exception): ... + +class Morsel(Dict[str, Any], Generic[_T]): + value: str + coded_value: _T + key: str + if sys.version_info >= (3, 7): + def set(self, key: str, val: str, coded_val: _T) -> None: ... + else: + def set(self, key: str, val: str, coded_val: _T, LegalChars: str = ...) -> None: ... + def isReservedKey(self, K: str) -> bool: ... + def output(self, attrs: Optional[List[str]] = ..., + header: str = ...) -> str: ... + def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... + def OutputString(self, attrs: Optional[List[str]] = ...) -> str: ... + +class BaseCookie(Dict[str, Morsel[_T]], Generic[_T]): + def __init__(self, input: Optional[_DataType] = ...) -> None: ... + def value_decode(self, val: str) -> _T: ... + def value_encode(self, val: _T) -> str: ... + def output(self, attrs: Optional[List[str]] = ..., header: str = ..., + sep: str = ...) -> str: ... + def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... + def load(self, rawdata: _DataType) -> None: ... + def __setitem__(self, key: str, value: Union[str, Morsel[_T]]) -> None: ... + +class SimpleCookie(BaseCookie[_T], Generic[_T]): ... diff --git a/mypy/stdlib/http/server.pyi b/mypy/stdlib/http/server.pyi new file mode 100644 index 000000000000..fe9fc238409b --- /dev/null +++ b/mypy/stdlib/http/server.pyi @@ -0,0 +1,76 @@ +# Stubs for http.server (Python 3.4) + +import sys +from typing import Any, BinaryIO, Callable, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union +import socketserver +import email.message + +if sys.version_info >= (3, 7): + from builtins import _PathLike + +class HTTPServer(socketserver.TCPServer): + server_name: str + server_port: int + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + +if sys.version_info >= (3, 7): + class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): + daemon_threads: bool # undocumented + +class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): + client_address: Tuple[str, int] + server: socketserver.BaseServer + close_connection: bool + requestline: str + command: str + path: str + request_version: str + headers: email.message.Message + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, Tuple[str, str]] + weekdayname: ClassVar[Sequence[str]] = ... # Undocumented + monthname: ClassVar[Sequence[Optional[str]]] = ... # Undocumented + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def handle_expect_100(self) -> bool: ... + def send_error(self, code: int, message: Optional[str] = ..., + explain: Optional[str] = ...) -> None: ... + def send_response(self, code: int, + message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def send_response_only(self, code: int, + message: Optional[str] = ...) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., + size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... + def parse_request(self) -> bool: ... # Undocumented + +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + extensions_map: Dict[str, str] + if sys.version_info >= (3, 7): + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer, directory: Optional[Union[str, _PathLike[str]]]) -> None: ... + else: + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer) -> None: ... + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + +class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + cgi_directories: List[str] + def do_POST(self) -> None: ... diff --git a/mypy/stdlib/imaplib.pyi b/mypy/stdlib/imaplib.pyi new file mode 100644 index 000000000000..a5962a8365a6 --- /dev/null +++ b/mypy/stdlib/imaplib.pyi @@ -0,0 +1,141 @@ +import subprocess +import sys +import time +from socket import socket as _socket +from ssl import SSLSocket, SSLContext +from typing import Any, Callable, Dict, IO, 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 __getattr__(self, attr: str) -> Any: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: Union[IO[Text], IO[bytes]] = ... + def open(self, host: str = ..., port: 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 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: ... + if sys.version_info >= (3, 5): + def enable(self, capability: str) -> _CommandResults: ... + def __enter__(self) -> IMAP4: ... + def __exit__(self, *args) -> None: ... + 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: ... + if sys.version_info >= (3,): + 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: ... + 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 = ... + if sys.version_info >= (3, 3): + def __init__(self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., 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 = ... + 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: 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/stdlib/imghdr.pyi b/mypy/stdlib/imghdr.pyi new file mode 100644 index 000000000000..2906298297e3 --- /dev/null +++ b/mypy/stdlib/imghdr.pyi @@ -0,0 +1,21 @@ +import os +import sys +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: ... + + +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]: ... +@overload +def what(file: Any, h: bytes) -> Optional[str]: ... +tests: List[Callable[[bytes, Optional[BinaryIO]], Optional[str]]] diff --git a/mypy/stdlib/imp.pyi b/mypy/stdlib/imp.pyi new file mode 100644 index 000000000000..ded2a160b725 --- /dev/null +++ b/mypy/stdlib/imp.pyi @@ -0,0 +1,48 @@ +import os +import sys +from _typeshed import StrPath +import types +from typing import Any, IO, List, Optional, Tuple, TypeVar, Union + +from _imp import (lock_held as lock_held, acquire_lock as acquire_lock, release_lock as release_lock, + get_frozen_object as get_frozen_object, is_frozen_package as is_frozen_package, + init_frozen as init_frozen, is_builtin as is_builtin, is_frozen as is_frozen) + +from _imp import create_dynamic as create_dynamic + +_T = TypeVar('_T') + +SEARCH_ERROR: int +PY_SOURCE: int +PY_COMPILED: int +C_EXTENSION: int +PY_RESOURCE: int +PKG_DIRECTORY: int +C_BUILTIN: int +PY_FROZEN: int +PY_CODERESOURCE: int +IMP_HOOK: int + +def new_module(name: str) -> types.ModuleType: ... +def get_magic() -> bytes: ... +def get_tag() -> str: ... +def cache_from_source(path: StrPath, debug_override: Optional[bool] = ...) -> str: ... +def source_from_cache(path: StrPath) -> str: ... +def get_suffixes() -> List[Tuple[str, str, int]]: ... + +class NullImporter: + def __init__(self, path: StrPath) -> None: ... + def find_module(self, fullname: Any) -> None: ... + +# PathLike doesn't work for the pathname argument here +def load_source(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_compiled(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_package(name: str, path: StrPath) -> types.ModuleType: ... +def load_module(name: str, file: IO[Any], filename: str, details: Tuple[str, str, int]) -> types.ModuleType: ... +if sys.version_info >= (3, 6): + def find_module(name: str, path: Union[None, List[str], List[os.PathLike[str]], List[StrPath]] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... +else: + def find_module(name: str, path: Optional[List[str]] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... +def reload(module: types.ModuleType) -> types.ModuleType: ... +def init_builtin(name: str) -> Optional[types.ModuleType]: ... +def load_dynamic(name: str, path: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... diff --git a/mypy/stdlib/importlib/__init__.pyi b/mypy/stdlib/importlib/__init__.pyi new file mode 100644 index 000000000000..e44f424164af --- /dev/null +++ b/mypy/stdlib/importlib/__init__.pyi @@ -0,0 +1,16 @@ +from importlib.abc import Loader +import types +from typing import Any, Mapping, Optional, Sequence + +def __import__(name: str, globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ...) -> types.ModuleType: ... + +def import_module(name: str, package: Optional[str] = ...) -> types.ModuleType: ... + +def find_loader(name: str, path: Optional[str] = ...) -> Optional[Loader]: ... + +def invalidate_caches() -> None: ... + +def reload(module: types.ModuleType) -> types.ModuleType: ... diff --git a/mypy/stdlib/importlib/abc.pyi b/mypy/stdlib/importlib/abc.pyi new file mode 100644 index 000000000000..709ba44f723b --- /dev/null +++ b/mypy/stdlib/importlib/abc.pyi @@ -0,0 +1,92 @@ +from abc import ABCMeta, abstractmethod +import os +import sys +import types +from typing import Any, IO, Iterator, Mapping, Optional, Sequence, Tuple, Union + +# Loader is exported from this module, but for circular import reasons +# exists in its own stub file (with ModuleSpec and ModuleType). +from _importlib_modulespec import Loader as Loader # Exported + +from _importlib_modulespec import ModuleSpec + +_Path = Union[bytes, str] + +class Finder(metaclass=ABCMeta): + ... + # Technically this class defines the following method, but its subclasses + # in this module violate its signature. Since this class is deprecated, it's + # easier to simply ignore that this method exists. + # @abstractmethod + # def find_module(self, fullname: str, + # path: Optional[Sequence[_Path]] = ...) -> Optional[Loader]: ... + +class ResourceLoader(Loader): + @abstractmethod + def get_data(self, path: _Path) -> bytes: ... + +class InspectLoader(Loader): + def is_package(self, fullname: str) -> bool: ... + def get_code(self, fullname: str) -> Optional[types.CodeType]: ... + def load_module(self, fullname: str) -> types.ModuleType: ... + @abstractmethod + def get_source(self, fullname: str) -> Optional[str]: ... + def exec_module(self, module: types.ModuleType) -> None: ... + @staticmethod + def source_to_code(data: Union[bytes, str], path: str = ...) -> types.CodeType: ... + +class ExecutionLoader(InspectLoader): + @abstractmethod + def get_filename(self, fullname: str) -> _Path: ... + def get_code(self, fullname: str) -> Optional[types.CodeType]: ... + +class SourceLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): + def path_mtime(self, path: _Path) -> float: ... + def set_data(self, path: _Path, data: bytes) -> None: ... + def get_source(self, fullname: str) -> Optional[str]: ... + def path_stats(self, path: _Path) -> Mapping[str, Any]: ... + + +class MetaPathFinder(Finder): + def find_module(self, fullname: str, + path: Optional[Sequence[_Path]]) -> Optional[Loader]: + ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Optional[Sequence[_Path]], + target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: + ... + +class PathEntryFinder(Finder): + def find_module(self, fullname: str) -> Optional[Loader]: ... + def find_loader( + self, fullname: str + ) -> Tuple[Optional[Loader], Sequence[_Path]]: ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, + target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... + +class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): + name: str + path: _Path + def __init__(self, fullname: str, path: _Path) -> None: ... + def get_data(self, path: _Path) -> bytes: ... + def get_filename(self, fullname: str) -> _Path: ... + +if sys.version_info >= (3, 7): + _PathLike = Union[bytes, str, os.PathLike[Any]] + + class ResourceReader(metaclass=ABCMeta): + @abstractmethod + def open_resource(self, resource: _PathLike) -> IO[bytes]: ... + @abstractmethod + def resource_path(self, resource: _PathLike) -> str: ... + @abstractmethod + def is_resource(self, name: str) -> bool: ... + @abstractmethod + def contents(self) -> Iterator[str]: ... diff --git a/mypy/stdlib/importlib/machinery.pyi b/mypy/stdlib/importlib/machinery.pyi new file mode 100644 index 000000000000..07521adb2bd3 --- /dev/null +++ b/mypy/stdlib/importlib/machinery.pyi @@ -0,0 +1,125 @@ +import importlib.abc +import types +from typing import Any, Callable, List, Optional, Sequence, Tuple, Union + +# ModuleSpec is exported from this module, but for circular import +# reasons exists in its own stub file (with Loader and ModuleType). +from _importlib_modulespec import ModuleSpec as ModuleSpec, Loader # Exported + +class BuiltinImporter(importlib.abc.MetaPathFinder, + importlib.abc.InspectLoader): + # MetaPathFinder + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + @staticmethod + def module_repr(module: types.ModuleType) -> str: ... + @classmethod + def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: ... + @classmethod + def exec_module(cls, module: types.ModuleType) -> None: ... + +class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + @staticmethod + def module_repr(module: types.ModuleType) -> str: ... + @classmethod + def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: + ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... + +class WindowsRegistryFinder(importlib.abc.MetaPathFinder): + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + +class PathFinder: + @classmethod + def invalidate_caches(cls) -> None: ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[Union[bytes, str]]] = ..., + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: ... + @classmethod + def find_module(cls, fullname: str, + path: Optional[Sequence[Union[bytes, str]]] = ...) -> Optional[Loader]: ... + + +SOURCE_SUFFIXES: List[str] +DEBUG_BYTECODE_SUFFIXES: List[str] +OPTIMIZED_BYTECODE_SUFFIXES: List[str] +BYTECODE_SUFFIXES: List[str] +EXTENSION_SUFFIXES: List[str] + +def all_suffixes() -> List[str]: ... + +class FileFinder(importlib.abc.PathEntryFinder): + path: str + def __init__( + self, path: str, + *loader_details: Tuple[importlib.abc.Loader, List[str]] + ) -> None: ... + @classmethod + def path_hook( + cls, *loader_details: Tuple[importlib.abc.Loader, List[str]] + ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... + +class SourceFileLoader(importlib.abc.FileLoader, + importlib.abc.SourceLoader): + ... + +class SourcelessFileLoader(importlib.abc.FileLoader, + importlib.abc.SourceLoader): + ... + +class ExtensionFileLoader(importlib.abc.ExecutionLoader): + def get_filename(self, fullname: str) -> importlib.abc._Path: ... + def get_source(self, fullname: str) -> None: ... diff --git a/mypy/stdlib/importlib/metadata.pyi b/mypy/stdlib/importlib/metadata.pyi new file mode 100644 index 000000000000..995118597c04 --- /dev/null +++ b/mypy/stdlib/importlib/metadata.pyi @@ -0,0 +1,87 @@ +import abc +import os +import pathlib +import sys +from email.message import Message +from importlib.abc import MetaPathFinder +from pathlib import Path +from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union, overload + +if sys.version_info >= (3, 8): + class PackageNotFoundError(ModuleNotFoundError): ... + class EntryPointBase(NamedTuple): + name: str + value: str + group: str + class EntryPoint(EntryPointBase): + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> List[str]: ... + class PackagePath(pathlib.PurePosixPath): + def read_text(self, encoding: str = ...) -> str: ... + def read_binary(self) -> bytes: ... + def locate(self) -> os.PathLike[str]: ... + # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: + hash: Optional[FileHash] + size: Optional[int] + dist: Distribution + class FileHash: + mode: str + value: str + def __init__(self, spec: str) -> None: ... + class Distribution: + @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]: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + @overload + @classmethod + def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + @classmethod + def discover( + cls, *, context: None = ..., name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + @staticmethod + def at(path: Union[str, os.PathLike[str]]) -> PathDistribution: ... + @property + def metadata(self) -> Message: ... + @property + def version(self) -> str: ... + @property + def entry_points(self) -> List[EntryPoint]: ... + @property + def files(self) -> Optional[List[PackagePath]]: ... + @property + def requires(self) -> Optional[List[str]]: ... + class DistributionFinder(MetaPathFinder): + class Context: + name: Optional[str] + def __init__(self, *, name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any) -> None: ... + @property + def path(self) -> List[str]: ... + @property + def pattern(self) -> str: ... + @abc.abstractmethod + def find_distributions(self, context: Context = ...) -> Iterable[Distribution]: ... + class MetadataPathFinder(DistributionFinder): + @classmethod + 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 distribution(distribution_name: str) -> Distribution: ... + @overload + def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + def distributions( + *, context: None = ..., name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + def metadata(distribution_name: str) -> Message: ... + def version(distribution_name: str) -> str: ... + def entry_points() -> Dict[str, Tuple[EntryPoint, ...]]: ... + def files(distribution_name: str) -> Optional[List[PackagePath]]: ... + def requires(distribution_name: str) -> Optional[List[str]]: ... diff --git a/mypy/stdlib/importlib/resources.pyi b/mypy/stdlib/importlib/resources.pyi new file mode 100644 index 000000000000..007477d51b26 --- /dev/null +++ b/mypy/stdlib/importlib/resources.pyi @@ -0,0 +1,25 @@ +import sys +# This is a >=3.7 module, so we conditionally include its source. +if sys.version_info >= (3, 7): + import os + + from pathlib import Path + from types import ModuleType + from typing import ContextManager, Iterator, Union, BinaryIO, TextIO + + Package = Union[str, ModuleType] + Resource = Union[str, os.PathLike] + + def open_binary(package: Package, resource: Resource) -> BinaryIO: ... + def open_text(package: Package, + resource: Resource, + encoding: str = ..., + errors: str = ...) -> TextIO: ... + def read_binary(package: Package, resource: Resource) -> bytes: ... + def read_text(package: Package, + resource: Resource, + encoding: str = ..., + errors: str = ...) -> str: ... + def path(package: Package, resource: Resource) -> ContextManager[Path]: ... + def is_resource(package: Package, name: str) -> bool: ... + def contents(package: Package) -> Iterator[str]: ... diff --git a/mypy/stdlib/importlib/util.pyi b/mypy/stdlib/importlib/util.pyi new file mode 100644 index 000000000000..878d0652ee81 --- /dev/null +++ b/mypy/stdlib/importlib/util.pyi @@ -0,0 +1,53 @@ +import importlib.abc +import importlib.machinery +import sys +import types +from typing import Any, Callable, List, Optional, Union + +def module_for_loader( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... +def set_loader( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... +def set_package( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... + +def resolve_name(name: str, package: str) -> str: ... + +MAGIC_NUMBER: bytes + +def cache_from_source(path: str, debug_override: Optional[bool] = ..., *, + optimization: Optional[Any] = ...) -> str: ... +def source_from_cache(path: str) -> str: ... +def decode_source(source_bytes: bytes) -> str: ... +def find_spec( + name: str, package: Optional[str] = ... +) -> Optional[importlib.machinery.ModuleSpec]: ... +def spec_from_loader( + name: str, loader: Optional[importlib.abc.Loader], *, + origin: Optional[str] = ..., loader_state: Optional[Any] = ..., + is_package: Optional[bool] = ... +) -> importlib.machinery.ModuleSpec: ... + +if sys.version_info >= (3, 6): + import os + _Path = Union[str, bytes, os.PathLike] +else: + _Path = str + +def spec_from_file_location( + name: str, location: _Path, *, + loader: Optional[importlib.abc.Loader] = ..., + submodule_search_locations: Optional[List[str]] = ... +) -> importlib.machinery.ModuleSpec: ... + +def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... + +class LazyLoader(importlib.abc.Loader): + def __init__(self, loader: importlib.abc.Loader) -> None: ... + @classmethod + def factory(cls, loader: importlib.abc.Loader) -> Callable[..., LazyLoader]: ... + def create_module(self, spec: importlib.machinery.ModuleSpec) -> Optional[types.ModuleType]: ... + def exec_module(self, module: types.ModuleType) -> None: ... diff --git a/mypy/stdlib/inspect.pyi b/mypy/stdlib/inspect.pyi new file mode 100644 index 000000000000..9696067ccacb --- /dev/null +++ b/mypy/stdlib/inspect.pyi @@ -0,0 +1,316 @@ +import sys +import enum +from typing import (AbstractSet, Any, Callable, Dict, Generator, List, Mapping, + NamedTuple, Optional, Sequence, Tuple, Type, Union, + ) +from types import (CodeType, FrameType, FunctionType, MethodType, ModuleType, + TracebackType, + ) +from collections import OrderedDict + +# +# Types and members +# +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + indecorator: bool + decoratorhasargs: bool + last: int + def tokeneater(self, type: int, token: str, srowcol: Tuple[int, int], + erowcol: Tuple[int, int], line: str) -> None: ... + +CO_OPTIMIZED: int +CO_NEWLOCALS: int +CO_VARARGS: int +CO_VARKEYWORDS: int +CO_NESTED: int +CO_GENERATOR: int +CO_NOFREE: int +CO_COROUTINE: int +CO_ITERABLE_COROUTINE: int +if sys.version_info >= (3, 6): + CO_ASYNC_GENERATOR: int +TPFLAGS_IS_ABSTRACT: int + +if sys.version_info < (3, 6): + class ModuleInfo(NamedTuple): + name: str + suffix: str + mode: str + module_type: int + def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ... + +def getmembers(object: object, + predicate: Optional[Callable[[Any], bool]] = ..., + ) -> List[Tuple[str, Any]]: ... +def getmodulename(path: str) -> Optional[str]: ... + +def ismodule(object: object) -> bool: ... +def isclass(object: object) -> bool: ... +def ismethod(object: object) -> bool: ... +def isfunction(object: object) -> bool: ... +def isgeneratorfunction(object: object) -> bool: ... +def isgenerator(object: object) -> bool: ... + +def iscoroutinefunction(object: object) -> bool: ... +def iscoroutine(object: object) -> bool: ... +def isawaitable(object: object) -> bool: ... +if sys.version_info >= (3, 6): + def isasyncgenfunction(object: object) -> bool: ... + def isasyncgen(object: object) -> bool: ... +def istraceback(object: object) -> bool: ... +def isframe(object: object) -> bool: ... +def iscode(object: object) -> bool: ... +def isbuiltin(object: object) -> bool: ... +def isroutine(object: object) -> bool: ... +def isabstract(object: object) -> bool: ... +def ismethoddescriptor(object: object) -> bool: ... +def isdatadescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> bool: ... +def ismemberdescriptor(object: object) -> bool: ... + + +# +# Retrieving source code +# +_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] + +def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getabsfile(object: _SourceObjectType) -> str: ... +def getblock(lines: Sequence[str]) -> Sequence[str]: ... +def getdoc(object: object) -> Optional[str]: ... +def getcomments(object: object) -> Optional[str]: ... +def getfile(object: _SourceObjectType) -> str: ... +def getmodule(object: object) -> Optional[ModuleType]: ... +def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... +def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsource(object: _SourceObjectType) -> str: ... +def cleandoc(doc: str) -> str: ... +def indentsize(line: str) -> int: ... + + +# +# Introspecting callables with the Signature object +# +def signature(obj: Callable[..., Any], + *, + follow_wrapped: bool = ...) -> Signature: ... + +class Signature: + def __init__(self, + parameters: Optional[Sequence[Parameter]] = ..., + *, + return_annotation: Any = ...) -> None: ... + # TODO: can we be more specific here? + empty: object = ... + + parameters: Mapping[str, Parameter] + + # TODO: can we be more specific here? + return_annotation: Any + + def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def replace(self, + *, + parameters: Optional[Sequence[Parameter]] = ..., + return_annotation: Any = ...) -> Signature: ... + + @classmethod + def from_callable(cls, obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... + +# The name is the same as the enum's name in CPython +class _ParameterKind(enum.IntEnum): + if sys.version_info >= (3, 8): + description: str + +class Parameter: + def __init__(self, + name: str, + kind: _ParameterKind, + *, + default: Any = ..., + annotation: Any = ...) -> None: ... + empty: Any = ... + name: str + default: Any + annotation: Any + + kind: _ParameterKind + POSITIONAL_ONLY: _ParameterKind = ... + POSITIONAL_OR_KEYWORD: _ParameterKind = ... + VAR_POSITIONAL: _ParameterKind = ... + KEYWORD_ONLY: _ParameterKind = ... + VAR_KEYWORD: _ParameterKind = ... + + def replace(self, + *, + name: Optional[str] = ..., + kind: Optional[_ParameterKind] = ..., + default: Any = ..., + annotation: Any = ...) -> Parameter: ... + +class BoundArguments: + arguments: OrderedDict[str, Any] + args: Tuple[Any, ...] + kwargs: Dict[str, Any] + signature: Signature + + def apply_defaults(self) -> None: ... + + +# +# Classes and functions +# + +# TODO: The actual return type should be List[_ClassTreeItem] but mypy doesn't +# seem to be supporting this at the moment: +# _ClassTreeItem = Union[List[_ClassTreeItem], Tuple[type, Tuple[type, ...]]] +def getclasstree(classes: List[type], unique: bool = ...) -> Any: ... + +class ArgSpec(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + defaults: Tuple[Any, ...] + +class Arguments(NamedTuple): + args: List[str] + varargs: Optional[str] + varkw: Optional[str] + +def getargs(co: CodeType) -> Arguments: ... +def getargspec(func: object) -> ArgSpec: ... + +class FullArgSpec(NamedTuple): + args: List[str] + varargs: Optional[str] + varkw: Optional[str] + defaults: Optional[Tuple[Any, ...]] + kwonlyargs: List[str] + kwonlydefaults: Optional[Dict[str, Any]] + annotations: Dict[str, Any] + +def getfullargspec(func: object) -> FullArgSpec: ... + +class ArgInfo(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + locals: Dict[str, Any] + +def getargvalues(frame: FrameType) -> ArgInfo: ... +def formatannotation(annotation: object, base_module: Optional[str] = ...) -> str: ... +def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... +def formatargspec(args: List[str], + varargs: Optional[str] = ..., + varkw: Optional[str] = ..., + defaults: Optional[Tuple[Any, ...]] = ..., + kwonlyargs: Optional[Sequence[str]] = ..., + kwonlydefaults: Optional[Dict[str, Any]] = ..., + annotations: Dict[str, Any] = ..., + formatarg: Callable[[str], str] = ..., + formatvarargs: Callable[[str], str] = ..., + formatvarkw: Callable[[str], str] = ..., + formatvalue: Callable[[Any], str] = ..., + formatreturns: Callable[[Any], str] = ..., + formatannotation: Callable[[Any], str] = ..., + ) -> str: ... +def formatargvalues(args: List[str], + varargs: Optional[str], + varkw: Optional[str], + locals: Optional[Dict[str, Any]], + formatarg: Optional[Callable[[str], str]] = ..., + formatvarargs: Optional[Callable[[str], str]] = ..., + formatvarkw: Optional[Callable[[str], str]] = ..., + formatvalue: Optional[Callable[[Any], str]] = ..., + ) -> str: ... +def getmro(cls: type) -> Tuple[type, ...]: ... + +def getcallargs(__func: Callable[..., Any], + *args: Any, + **kwds: Any) -> Dict[str, Any]: ... + +class ClosureVars(NamedTuple): + nonlocals: Mapping[str, Any] + globals: Mapping[str, Any] + builtins: Mapping[str, Any] + unbound: AbstractSet[str] +def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... + +def unwrap(func: Callable[..., Any], + *, + stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... + + +# +# The interpreter stack +# + +class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: Optional[List[str]] + index: Optional[int] # type: ignore + +class FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: Optional[List[str]] + index: Optional[int] # type: ignore + +def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... +def getouterframes(frame: Any, context: int = ...) -> List[FrameInfo]: ... +def getinnerframes(tb: TracebackType, context: int = ...) -> List[FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... +def currentframe() -> Optional[FrameType]: ... +def stack(context: int = ...) -> List[FrameInfo]: ... +def trace(context: int = ...) -> List[FrameInfo]: ... + +# +# Fetching attributes statically +# + +def getattr_static(obj: object, attr: str, default: Optional[Any] = ...) -> Any: ... + + +# +# Current State of Generators and Coroutines +# + +# TODO In the next two blocks of code, can we be more specific regarding the +# type of the "enums"? + +GEN_CREATED: str +GEN_RUNNING: str +GEN_SUSPENDED: str +GEN_CLOSED: str +def getgeneratorstate(generator: Generator[Any, Any, Any]) -> str: ... + +CORO_CREATED: str +CORO_RUNNING: str +CORO_SUSPENDED: str +CORO_CLOSED: str +# TODO can we be more specific than "object"? +def getcoroutinestate(coroutine: object) -> str: ... + +def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> Dict[str, Any]: ... + +# TODO can we be more specific than "object"? +def getcoroutinelocals(coroutine: object) -> Dict[str, Any]: ... + +class Attribute(NamedTuple): + name: str + kind: str + defining_class: type + object: object + +def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/mypy/stdlib/io.pyi b/mypy/stdlib/io.pyi new file mode 100644 index 000000000000..e1e732c9e677 --- /dev/null +++ b/mypy/stdlib/io.pyi @@ -0,0 +1,182 @@ +from typing import ( + List, BinaryIO, TextIO, Iterator, Union, Optional, Callable, Tuple, Type, Any, IO, Iterable, TypeVar +) +import builtins +import codecs +import sys +from mmap import mmap +from types import TracebackType +from _typeshed import ReadableBuffer, WriteableBuffer + +DEFAULT_BUFFER_SIZE: int + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int + +_T = TypeVar('_T', bound=IOBase) + +open = builtins.open + +if sys.version_info >= (3, 8): + def open_code(path: str) -> IO[bytes]: ... + +BlockingIOError = builtins.BlockingIOError +class UnsupportedOperation(OSError, ValueError): ... + +class IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readlines(self, __hint: int = ...) -> List[bytes]: ... + 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 writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ... + def readline(self, __size: Optional[int] = ...) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + def _checkClosed(self, msg: Optional[str] = ...) -> None: ... # undocumented + +class RawIOBase(IOBase): + def readall(self) -> bytes: ... + def readinto(self, __buffer: WriteableBuffer) -> Optional[int]: ... + def write(self, __b: ReadableBuffer) -> Optional[int]: ... + def read(self, __size: int = ...) -> Optional[bytes]: ... + +class BufferedIOBase(IOBase): + raw: RawIOBase # This is not part of the BufferedIOBase API and may not exist on some implementations. + def detach(self) -> RawIOBase: ... + def readinto(self, __buffer: WriteableBuffer) -> int: ... + def write(self, __buffer: ReadableBuffer) -> int: ... + def readinto1(self, __buffer: WriteableBuffer) -> int: ... + def read(self, __size: Optional[int] = ...) -> bytes: ... + def read1(self, __size: int = ...) -> bytes: ... + +class FileIO(RawIOBase, BinaryIO): + mode: str + # Technically this is whatever is passed in as file, either a str, a bytes, or an int. + name: Union[int, str] # type: ignore + def __init__( + self, + file: Union[str, bytes, int], + mode: str = ..., + closefd: bool = ..., + opener: Optional[Callable[[Union[int, str], str], int]] = ... + ) -> None: ... + def write(self, __b: ReadableBuffer) -> int: ... + def read(self, __size: int = ...) -> bytes: ... + def __enter__(self: _T) -> _T: ... + +class BytesIO(BufferedIOBase, BinaryIO): + def __init__(self, initial_bytes: bytes = ...) -> None: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def __enter__(self: _T) -> _T: ... + def getvalue(self) -> bytes: ... + def getbuffer(self) -> memoryview: ... + if sys.version_info >= (3, 7): + def read1(self, __size: Optional[int] = ...) -> bytes: ... + else: + def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore + +class BufferedReader(BufferedIOBase, BinaryIO): + def __enter__(self: _T) -> _T: ... + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def peek(self, __size: int = ...) -> bytes: ... + if sys.version_info >= (3, 7): + def read1(self, __size: int = ...) -> bytes: ... + else: + def read1(self, __size: int) -> bytes: ... # type: ignore + +class BufferedWriter(BufferedIOBase, BinaryIO): + def __enter__(self: _T) -> _T: ... + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def write(self, __buffer: ReadableBuffer) -> int: ... + +class BufferedRandom(BufferedReader, BufferedWriter): + def __enter__(self: _T) -> _T: ... + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def seek(self, __target: int, __whence: int = ...) -> int: ... + if sys.version_info >= (3, 7): + def read1(self, __size: int = ...) -> bytes: ... + else: + def read1(self, __size: int) -> bytes: ... # type: ignore + +class BufferedRWPair(BufferedIOBase): + def __init__(self, reader: RawIOBase, writer: RawIOBase, + buffer_size: int = ...) -> None: ... + + +class TextIOBase(IOBase): + encoding: str + errors: Optional[str] + newlines: Union[str, Tuple[str, ...], None] + def __iter__(self) -> Iterator[str]: ... # type: ignore + def __next__(self) -> str: ... # type: ignore + def detach(self) -> BinaryIO: ... + def write(self, __s: str) -> int: ... + def writelines(self, __lines: List[str]) -> None: ... # type: ignore + def readline(self, __size: int = ...) -> str: ... # type: ignore + def readlines(self, __hint: int = ...) -> List[str]: ... # type: ignore + def read(self, __size: Optional[int] = ...) -> str: ... + def tell(self) -> int: ... + +class TextIOWrapper(TextIOBase, TextIO): + line_buffering: bool + def __init__( + self, + buffer: IO[bytes], + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + line_buffering: bool = ..., + write_through: bool = ... + ) -> None: ... + @property + def buffer(self) -> BinaryIO: ... + if sys.version_info >= (3, 7): + def reconfigure( + self, + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + line_buffering: Optional[bool] = ..., + write_through: Optional[bool] = ... + ) -> None: ... + closed: bool + # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy. + def __enter__(self: _T) -> _T: ... + def __iter__(self) -> Iterator[str]: ... # type: ignore + def __next__(self) -> str: ... # type: ignore + def writelines(self, __lines: List[str]) -> None: ... # type: ignore + def readline(self, __size: int = ...) -> str: ... # type: ignore + def readlines(self, __hint: int = ...) -> List[str]: ... # type: ignore + def seek(self, __cookie: int, __whence: int = ...) -> int: ... + +class StringIO(TextIOWrapper): + def __init__(self, initial_value: Optional[str] = ..., + newline: Optional[str] = ...) -> None: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> str: ... + +class IncrementalNewlineDecoder(codecs.IncrementalDecoder): + def __init__(self, decoder: Optional[codecs.IncrementalDecoder], + translate: bool, errors: str = ...) -> None: ... + def decode(self, input: Union[bytes, str], final: bool = ...) -> str: ... diff --git a/mypy/stdlib/ipaddress.pyi b/mypy/stdlib/ipaddress.pyi new file mode 100644 index 000000000000..5c7d9a2db225 --- /dev/null +++ b/mypy/stdlib/ipaddress.pyi @@ -0,0 +1,154 @@ +from typing import (Any, Container, Generic, Iterable, Iterator, Optional, + overload, SupportsInt, Text, Tuple, TypeVar) + +import sys + +# Undocumented length constants +IPV4LENGTH: int +IPV6LENGTH: int + +_A = TypeVar("_A", IPv4Address, IPv6Address) +_N = TypeVar("_N", IPv4Network, IPv6Network) +_T = TypeVar("_T") + +def ip_address(address: object) -> Any: ... # morally Union[IPv4Address, IPv6Address] +def ip_network(address: object, strict: bool = ...) -> Any: ... # morally Union[IPv4Network, IPv6Network] +def ip_interface(address: object) -> Any: ... # morally Union[IPv4Interface, IPv6Interface] + +class _IPAddressBase: + def __eq__(self, other: Any) -> bool: ... + def __ge__(self: _T, other: _T) -> bool: ... + def __gt__(self: _T, other: _T) -> bool: ... + def __le__(self: _T, other: _T) -> bool: ... + def __lt__(self: _T, other: _T) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + @property + def compressed(self) -> Text: ... + @property + def exploded(self) -> Text: ... + @property + def reverse_pointer(self) -> Text: ... + @property + def version(self) -> int: ... + +class _BaseAddress(_IPAddressBase, SupportsInt): + def __init__(self, address: object) -> None: ... + def __add__(self: _T, other: int) -> _T: ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def __sub__(self: _T, other: int) -> _T: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def max_prefixlen(self) -> int: ... + @property + def packed(self) -> bytes: ... + +class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): + network_address: _A + netmask: _A + def __init__(self, address: object, strict: bool = ...) -> None: ... + def __contains__(self, other: Any) -> bool: ... + def __getitem__(self, n: int) -> _A: ... + def __iter__(self) -> Iterator[_A]: ... + def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... + @property + def broadcast_address(self) -> _A: ... + def compare_networks(self: _T, other: _T) -> int: ... + def hosts(self) -> Iterator[_A]: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def max_prefixlen(self) -> int: ... + @property + def num_addresses(self) -> int: ... + def overlaps(self, other: _BaseNetwork) -> bool: ... + @property + def prefixlen(self) -> int: ... + if sys.version_info >= (3, 7): + def subnet_of(self: _T, other: _T) -> bool: ... + def supernet_of(self: _T, other: _T) -> bool: ... + def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> Iterator[_T]: ... + def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> _T: ... + @property + def with_hostmask(self) -> Text: ... + @property + def with_netmask(self) -> Text: ... + @property + def with_prefixlen(self) -> Text: ... + @property + def hostmask(self) -> _A: ... + +class _BaseInterface(_BaseAddress, Generic[_A, _N]): + hostmask: _A + netmask: _A + network: _N + @property + def ip(self) -> _A: ... + @property + def with_hostmask(self) -> Text: ... + @property + def with_netmask(self) -> Text: ... + @property + def with_prefixlen(self) -> Text: ... + +class IPv4Address(_BaseAddress): ... +class IPv4Network(_BaseNetwork[IPv4Address]): ... +class IPv4Interface(IPv4Address, _BaseInterface[IPv4Address, IPv4Network]): ... + +class IPv6Address(_BaseAddress): + @property + def ipv4_mapped(self) -> Optional[IPv4Address]: ... + @property + def is_site_local(self) -> bool: ... + @property + def sixtofour(self) -> Optional[IPv4Address]: ... + @property + def teredo(self) -> Optional[Tuple[IPv4Address, IPv4Address]]: ... + +class IPv6Network(_BaseNetwork[IPv6Address]): + @property + def is_site_local(self) -> bool: ... + +class IPv6Interface(IPv6Address, _BaseInterface[IPv6Address, IPv6Network]): ... + +def v4_int_to_packed(address: int) -> bytes: ... +def v6_int_to_packed(address: int) -> bytes: ... +@overload +def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ... +@overload +def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ... +def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... +@overload +def get_mixed_type_key(obj: _A) -> Tuple[int, _A]: ... +@overload +def get_mixed_type_key(obj: IPv4Network) -> Tuple[int, IPv4Address, IPv4Address]: ... +@overload +def get_mixed_type_key(obj: IPv6Network) -> Tuple[int, IPv6Address, IPv6Address]: ... + +class AddressValueError(ValueError): ... +class NetmaskValueError(ValueError): ... diff --git a/mypy/stdlib/itertools.pyi b/mypy/stdlib/itertools.pyi new file mode 100644 index 000000000000..b5f75fe1cc9d --- /dev/null +++ b/mypy/stdlib/itertools.pyi @@ -0,0 +1,121 @@ +# Stubs for itertools + +# Based on http://docs.python.org/3.2/library/itertools.html + +from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, + Generic, Optional) +import sys + +_T = TypeVar('_T') +_S = TypeVar('_S') +_N = TypeVar('_N', int, float) +Predicate = Callable[[_T], object] + +def count(start: _N = ..., + step: _N = ...) -> Iterator[_N]: ... # more general types? + +class cycle(Iterator[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + +@overload +def repeat(object: _T) -> Iterator[_T]: ... +@overload +def repeat(object: _T, times: int) -> Iterator[_T]: ... + +if sys.version_info >= (3, 8): + @overload + def accumulate(iterable: Iterable[_T], + func: Callable[[_T, _T], _T] = ...) -> Iterator[_T]: ... + @overload + def accumulate(iterable: Iterable[_T], + func: Callable[[_S, _T], _S], + initial: Optional[_S]) -> Iterator[_S]: ... +else: + def accumulate(iterable: Iterable[_T], + func: Callable[[_T, _T], _T] = ...) -> Iterator[_T]: ... + +class chain(Iterator[_T], Generic[_T]): + def __init__(self, *iterables: Iterable[_T]) -> None: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + @staticmethod + def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + +def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... +def dropwhile(predicate: Predicate[_T], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def filterfalse(predicate: Optional[Predicate[_T]], + iterable: Iterable[_T]) -> Iterator[_T]: ... + +@overload +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +@overload +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... + +@overload +def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +@overload +def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], + step: Optional[int] = ...) -> Iterator[_T]: ... + +def starmap(func: Callable[..., _S], iterable: Iterable[Iterable[Any]]) -> Iterator[_S]: ... +def takewhile(predicate: Predicate[_T], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def zip_longest(*p: Iterable[Any], + fillvalue: Any = ...) -> Iterator[Any]: ... + +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_T6 = TypeVar('_T6') + +@overload +def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product(iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[Any], repeat: int = ...) -> Iterator[Tuple[Any, ...]]: ... + +def permutations(iterable: Iterable[_T], + r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ... +def combinations(iterable: Iterable[_T], + r: int) -> Iterator[Tuple[_T, ...]]: ... +def combinations_with_replacement(iterable: Iterable[_T], + r: int) -> Iterator[Tuple[_T, ...]]: ... diff --git a/mypy/stdlib/json/__init__.pyi b/mypy/stdlib/json/__init__.pyi new file mode 100644 index 000000000000..37147330bfaa --- /dev/null +++ b/mypy/stdlib/json/__init__.pyi @@ -0,0 +1,58 @@ +import sys +from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Type +from _typeshed import SupportsRead + +from .decoder import JSONDecoder as JSONDecoder +from .encoder import JSONEncoder as JSONEncoder +from .decoder import JSONDecodeError as JSONDecodeError + +def dumps(obj: Any, + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> str: ... + +def dump(obj: Any, + fp: IO[str], + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> None: ... + +if sys.version_info >= (3, 6): + _LoadsString = Union[str, bytes] +else: + _LoadsString = str +def loads(s: _LoadsString, + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +def load(fp: SupportsRead[_LoadsString], + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... diff --git a/mypy/stdlib/json/decoder.pyi b/mypy/stdlib/json/decoder.pyi new file mode 100644 index 000000000000..3eb4cf5d9625 --- /dev/null +++ b/mypy/stdlib/json/decoder.pyi @@ -0,0 +1,42 @@ +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple + +class JSONDecodeError(ValueError): + msg: str + doc: str + pos: int + lineno: int + colno: int + def __init__(self, msg: str, doc: str, pos: int) -> None: ... + +class JSONDecoder: + object_hook: Callable[[Dict[str, Any]], Any] + parse_float: Callable[[str], Any] + parse_int: Callable[[str], Any] + parse_constant = ... # Callable[[str], Any] + strict: bool + object_pairs_hook: Callable[[List[Tuple[str, Any]]], Any] + + if sys.version_info >= (3, 6): + def __init__( + self, + *, + object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + strict: bool = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ... + ) -> None: ... + else: + def __init__( + self, + object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + strict: bool = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ..., + ) -> None: ... + def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ... # _w is undocumented + def raw_decode(self, s: str, idx: int = ...) -> Tuple[Any, int]: ... diff --git a/mypy/stdlib/json/encoder.pyi b/mypy/stdlib/json/encoder.pyi new file mode 100644 index 000000000000..69e11e102904 --- /dev/null +++ b/mypy/stdlib/json/encoder.pyi @@ -0,0 +1,42 @@ +import sys +from typing import Any, Callable, Iterator, Optional, Tuple + +class JSONEncoder: + item_separator: str + key_separator: str + + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: int + + if sys.version_info >= (3, 6): + def __init__( + self, + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[..., Any]] = ... + ) -> None: ... + else: + def __init__( + self, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[..., Any]] = ..., + ) -> None: ... + def default(self, o: Any) -> Any: ... + def encode(self, o: Any) -> str: ... + def iterencode(self, o: Any, _one_shot: bool = ...) -> Iterator[str]: ... diff --git a/mypy/stdlib/keyword.pyi b/mypy/stdlib/keyword.pyi new file mode 100644 index 000000000000..f9e3376eeca0 --- /dev/null +++ b/mypy/stdlib/keyword.pyi @@ -0,0 +1,6 @@ +# Stubs for keyword + +from typing import Sequence, Text, Union + +def iskeyword(s: Union[Text, bytes]) -> bool: ... +kwlist: Sequence[str] diff --git a/mypy/stdlib/lib2to3/__init__.pyi b/mypy/stdlib/lib2to3/__init__.pyi new file mode 100644 index 000000000000..145e31b1dec8 --- /dev/null +++ b/mypy/stdlib/lib2to3/__init__.pyi @@ -0,0 +1 @@ +# Stubs for lib2to3 (Python 3.6) diff --git a/mypy/stdlib/lib2to3/pgen2/__init__.pyi b/mypy/stdlib/lib2to3/pgen2/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/lib2to3/pgen2/driver.pyi b/mypy/stdlib/lib2to3/pgen2/driver.pyi new file mode 100644 index 000000000000..a97dd5169c03 --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/driver.pyi @@ -0,0 +1,20 @@ +from _typeshed import StrPath +from typing import Any, IO, Iterable, Optional, Text + +from logging import Logger +from lib2to3.pytree import _Convert, _NL +from lib2to3.pgen2.grammar import Grammar + + +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/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/stdlib/lib2to3/pgen2/grammar.pyi new file mode 100644 index 000000000000..c5fd030e59da --- /dev/null +++ b/mypy/stdlib/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/stdlib/lib2to3/pgen2/literals.pyi b/mypy/stdlib/lib2to3/pgen2/literals.pyi new file mode 100644 index 000000000000..3166ffbf304c --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/literals.pyi @@ -0,0 +1,9 @@ +# Stubs for lib2to3.pgen2.literals (Python 3.6) + +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/stdlib/lib2to3/pgen2/parse.pyi b/mypy/stdlib/lib2to3/pgen2/parse.pyi new file mode 100644 index 000000000000..101d4760a60c --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/parse.pyi @@ -0,0 +1,29 @@ +# Stubs for lib2to3.pgen2.parse (Python 3.6) + +from typing import Any, Dict, List, Optional, Sequence, Set, Text, Tuple + +from lib2to3.pgen2.grammar import Grammar, _DFAS +from lib2to3.pytree import _NL, _Convert, _RawNode + +_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/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/stdlib/lib2to3/pgen2/pgen.pyi new file mode 100644 index 000000000000..2b9f5eaaa759 --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/pgen.pyi @@ -0,0 +1,49 @@ +from _typeshed import StrPath +from typing import ( + Any, Dict, IO, Iterable, Iterator, List, NoReturn, Optional, Text, Tuple +) + +from lib2to3.pgen2 import grammar +from lib2to3.pgen2.tokenize import _TokenInfo + +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/stdlib/lib2to3/pgen2/token.pyi b/mypy/stdlib/lib2to3/pgen2/token.pyi new file mode 100644 index 000000000000..c256af8f27fe --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/token.pyi @@ -0,0 +1,73 @@ +# Stubs for lib2to3.pgen2.token (Python 3.6) + +import sys +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 +if sys.version_info >= (3,): + RARROW: int +if sys.version_info >= (3, 5): + AT: int + ATEQUAL: int + AWAIT: int + ASYNC: 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/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/stdlib/lib2to3/pgen2/tokenize.pyi new file mode 100644 index 000000000000..c10305ffdda0 --- /dev/null +++ b/mypy/stdlib/lib2to3/pgen2/tokenize.pyi @@ -0,0 +1,30 @@ +# Stubs for lib2to3.pgen2.tokenize (Python 3.6) +# NOTE: Only elements from __all__ are present. + +from typing import Callable, Iterable, Iterator, List, Text, Tuple +from lib2to3.pgen2.token import * # noqa + + +_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/stdlib/lib2to3/pygram.pyi b/mypy/stdlib/lib2to3/pygram.pyi new file mode 100644 index 000000000000..aeb7b93bf870 --- /dev/null +++ b/mypy/stdlib/lib2to3/pygram.pyi @@ -0,0 +1,116 @@ +# Stubs for lib2to3.pygram (Python 3.6) + +from typing import Any +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/stdlib/lib2to3/pytree.pyi b/mypy/stdlib/lib2to3/pytree.pyi new file mode 100644 index 000000000000..06a7c1229c40 --- /dev/null +++ b/mypy/stdlib/lib2to3/pytree.pyi @@ -0,0 +1,86 @@ +# Stubs for lib2to3.pytree (Python 3.6) + +import sys +from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union + +from lib2to3.pgen2.grammar import Grammar + +_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: ... + if sys.version_info < (3,): + 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/stdlib/linecache.pyi b/mypy/stdlib/linecache.pyi new file mode 100644 index 000000000000..3f35f469eb3f --- /dev/null +++ b/mypy/stdlib/linecache.pyi @@ -0,0 +1,12 @@ +import sys +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]: ... +if sys.version_info >= (3, 5): + def lazycache(filename: Text, module_globals: _ModuleGlobals) -> bool: ... diff --git a/mypy/stdlib/locale.pyi b/mypy/stdlib/locale.pyi new file mode 100644 index 000000000000..c4703f7f0e1c --- /dev/null +++ b/mypy/stdlib/locale.pyi @@ -0,0 +1,113 @@ +# Stubs for locale + +from decimal import Decimal +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union +import sys + +# workaround for mypy#2010 +if sys.version_info < (3,): + from __builtin__ import str as _str +else: + from builtins import str as _str + +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(option: 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: ... +if sys.version_info >= (3, 7): + def format_string(f: _str, val: Any, + grouping: bool = ..., monetary: bool = ...) -> _str: ... +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 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/stdlib/logging/__init__.pyi b/mypy/stdlib/logging/__init__.pyi new file mode 100644 index 000000000000..2a480b967e28 --- /dev/null +++ b/mypy/stdlib/logging/__init__.pyi @@ -0,0 +1,556 @@ +from _typeshed import StrPath +from typing import ( + Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, IO, + Sequence, Tuple, Text, Union, overload, +) +from string import Template +from time import struct_time +from types import TracebackType, FrameType +import sys +import threading + +_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], + Tuple[None, None, None]] +if sys.version_info >= (3, 5): + _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] +else: + _ExcInfoType = Union[None, bool, _SysExcInfoType] +_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] +_FilterType = Union[Filter, Callable[[LogRecord], int]] +_Level = Union[int, Text] + +raiseExceptions: bool +logThreads: bool +logMultiprocessing: bool +logProcesses: bool +_srcfile: Optional[str] + +def currentframe() -> FrameType: ... + +if sys.version_info >= (3,): + _levelToName: Dict[int, str] + _nameToLevel: Dict[str, int] +else: + _levelNames: Dict[Union[int, str], Union[str, int]] # Union[int:str, str:int] + +class Filterer(object): + filters: List[Filter] + def __init__(self) -> None: ... + def addFilter(self, filter: _FilterType) -> None: ... + def removeFilter(self, filter: _FilterType) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + +class Logger(Filterer): + name: str + level: int + parent: Union[Logger, PlaceHolder] + propagate: bool + handlers: List[Handler] + disabled: int + def __init__(self, name: str, level: _Level = ...) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def getChild(self, suffix: str) -> Logger: ... + if sys.version_info >= (3, 8): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[Dict[str, Any]] = ..., + stack_info: bool = ..., + stacklevel: int = ..., + ) -> None: ... # undocumented + elif sys.version_info >= (3,): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + fatal = critical + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[Dict[str, Any]] = ..., + stack_info: bool = ..., + ) -> None: ... # undocumented + else: + def debug(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + warn = warning + def error(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + fatal = critical + def log(self, + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[Dict[str, Any]] = ..., + ) -> None: ... # undocumented + def filter(self, record: LogRecord) -> bool: ... + def addHandler(self, hdlr: Handler) -> None: ... + def removeHandler(self, hdlr: Handler) -> None: ... + if sys.version_info >= (3, 8): + def findCaller(self, stack_info: bool = ..., stacklevel: int = ...) -> Tuple[str, int, str, Optional[str]]: ... + elif sys.version_info >= (3,): + def findCaller(self, stack_info: bool = ...) -> Tuple[str, int, str, Optional[str]]: ... + else: + def findCaller(self) -> Tuple[str, int, str]: ... + def handle(self, record: LogRecord) -> None: ... + if sys.version_info >= (3,): + def makeRecord(self, name: str, level: int, fn: str, lno: int, msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + sinfo: Optional[str] = ...) -> LogRecord: ... + else: + def makeRecord(self, + name: str, level: int, fn: str, lno: int, msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ...) -> LogRecord: ... + if sys.version_info >= (3,): + def hasHandlers(self) -> bool: ... + + +CRITICAL: int +FATAL: int +ERROR: int +WARNING: int +WARN: int +INFO: int +DEBUG: int +NOTSET: int + + +class Handler(Filterer): + level: int # undocumented + formatter: Optional[Formatter] # undocumented + lock: Optional[threading.Lock] # undocumented + name: Optional[str] # undocumented + def __init__(self, level: _Level = ...) -> None: ... + def createLock(self) -> None: ... + def acquire(self) -> None: ... + def release(self) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def setFormatter(self, fmt: Formatter) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def handle(self, record: LogRecord) -> None: ... + def handleError(self, record: LogRecord) -> None: ... + def format(self, record: LogRecord) -> str: ... + def emit(self, record: LogRecord) -> None: ... + + +class Formatter: + converter: Callable[[Optional[float]], struct_time] + _fmt: Optional[str] + datefmt: Optional[str] + if sys.version_info >= (3,): + _style: PercentStyle + default_time_format: str + default_msec_format: str + + if sys.version_info >= (3, 8): + def __init__(self, fmt: Optional[str] = ..., + datefmt: Optional[str] = ..., + style: str = ..., validate: bool = ...) -> None: ... + elif sys.version_info >= (3,): + def __init__(self, fmt: Optional[str] = ..., + datefmt: Optional[str] = ..., + style: str = ...) -> None: ... + else: + def __init__(self, + fmt: Optional[str] = ..., + datefmt: Optional[str] = ...) -> None: ... + + def format(self, record: LogRecord) -> str: ... + def formatTime(self, record: LogRecord, datefmt: Optional[str] = ...) -> str: ... + def formatException(self, ei: _SysExcInfoType) -> str: ... + if sys.version_info >= (3,): + def formatMessage(self, record: LogRecord) -> str: ... # undocumented + def formatStack(self, stack_info: str) -> str: ... + + +class Filter: + def __init__(self, name: str = ...) -> None: ... + def filter(self, record: LogRecord) -> int: ... + + +class LogRecord: + args: _ArgsType + asctime: str + created: int + exc_info: Optional[_SysExcInfoType] + exc_text: Optional[str] + filename: str + funcName: str + levelname: str + levelno: int + lineno: int + module: str + msecs: int + message: str + msg: str + name: str + pathname: str + process: int + processName: str + relativeCreated: int + if sys.version_info >= (3,): + stack_info: Optional[str] + thread: int + threadName: str + if sys.version_info >= (3,): + def __init__(self, name: str, level: int, pathname: str, lineno: int, + msg: Any, args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + sinfo: Optional[str] = ...) -> None: ... + else: + def __init__(self, + name: str, level: int, pathname: str, lineno: int, + msg: Any, args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ...) -> None: ... + def getMessage(self) -> str: ... + + +class LoggerAdapter: + logger: Logger + extra: Mapping[str, Any] + def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... + if sys.version_info >= (3, 8): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + elif sys.version_info >= (3,): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + else: + def debug(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def error(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def log(self, + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + if sys.version_info >= (3,): + def getEffectiveLevel(self) -> int: ... + def setLevel(self, level: Union[int, str]) -> None: ... + def hasHandlers(self) -> bool: ... + if sys.version_info >= (3, 6): + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[Dict[str, Any]] = ..., + stack_info: bool = ..., + ) -> None: ... # undocumented + +if sys.version_info >= (3,): + def getLogger(name: Optional[str] = ...) -> Logger: ... +else: + @overload + def getLogger() -> Logger: ... + @overload + def getLogger(name: Union[Text, str]) -> Logger: ... +def getLoggerClass() -> type: ... +if sys.version_info >= (3,): + def getLogRecordFactory() -> Callable[..., LogRecord]: ... + +if sys.version_info >= (3, 8): + def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... +elif sys.version_info >= (3,): + def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... +else: + def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + warn = warning + def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... +fatal = critical + +if sys.version_info >= (3, 7): + def disable(level: int = ...) -> None: ... +else: + def disable(level: int) -> None: ... +def addLevelName(level: int, levelName: str) -> None: ... +def getLevelName(level: Union[int, str]) -> Any: ... + +def makeLogRecord(dict: Mapping[str, Any]) -> LogRecord: ... + +if sys.version_info >= (3, 8): + def basicConfig(*, filename: Optional[StrPath] = ..., filemode: str = ..., + format: str = ..., datefmt: Optional[str] = ..., style: str = ..., + level: Optional[_Level] = ..., stream: Optional[IO[str]] = ..., + handlers: Optional[Iterable[Handler]] = ..., force: bool = ...) -> None: ... +elif sys.version_info >= (3,): + def basicConfig(*, filename: Optional[StrPath] = ..., filemode: str = ..., + format: str = ..., datefmt: Optional[str] = ..., style: str = ..., + level: Optional[_Level] = ..., stream: Optional[IO[str]] = ..., + handlers: Optional[Iterable[Handler]] = ...) -> None: ... +else: + @overload + def basicConfig() -> None: ... + @overload + def basicConfig(*, filename: Optional[str] = ..., filemode: str = ..., + format: str = ..., datefmt: Optional[str] = ..., + level: Optional[_Level] = ..., stream: IO[str] = ...) -> None: ... +def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented + +def setLoggerClass(klass: type) -> None: ... + +def captureWarnings(capture: bool) -> None: ... + +if sys.version_info >= (3,): + def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... + + +if sys.version_info >= (3,): + lastResort: Optional[StreamHandler] + + +class StreamHandler(Handler): + stream: IO[str] # undocumented + if sys.version_info >= (3, 2): + terminator: str + def __init__(self, stream: Optional[IO[str]] = ...) -> None: ... + if sys.version_info >= (3, 7): + def setStream(self, stream: IO[str]) -> Optional[IO[str]]: ... + + +class FileHandler(StreamHandler): + baseFilename: str # undocumented + mode: str # undocumented + encoding: Optional[str] # undocumented + delay: bool # undocumented + def __init__(self, filename: StrPath, mode: str = ..., + encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + def _open(self) -> IO[Any]: ... + + +class NullHandler(Handler): ... + + +class PlaceHolder: + def __init__(self, alogger: Logger) -> None: ... + def append(self, alogger: Logger) -> None: ... + + +# Below aren't in module docs but still visible + +class RootLogger(Logger): + def __init__(self, level: int) -> None: ... + +root: RootLogger + + +if sys.version_info >= (3,): + class PercentStyle(object): + default_format: str + asctime_format: str + asctime_search: str + _fmt: str + + def __init__(self, fmt: str) -> None: ... + def usesTime(self) -> bool: ... + def format(self, record: Any) -> str: ... + + class StrFormatStyle(PercentStyle): + ... + + class StringTemplateStyle(PercentStyle): + _tpl: Template + + _STYLES: Dict[str, Tuple[PercentStyle, str]] + + +BASIC_FORMAT: str diff --git a/mypy/stdlib/logging/config.pyi b/mypy/stdlib/logging/config.pyi new file mode 100644 index 000000000000..76420aba7747 --- /dev/null +++ b/mypy/stdlib/logging/config.pyi @@ -0,0 +1,28 @@ +from _typeshed import AnyPath, StrPath +from typing import Any, Callable, Dict, Optional, IO, Union +from threading import Thread +import sys +if sys.version_info >= (3,): + from configparser import RawConfigParser +else: + from ConfigParser import RawConfigParser + +if sys.version_info >= (3, 7): + _Path = AnyPath +else: + _Path = StrPath + + +def dictConfig(config: Dict[str, Any]) -> None: ... +if sys.version_info >= (3, 4): + def fileConfig(fname: Union[_Path, IO[str], RawConfigParser], + defaults: Optional[Dict[str, str]] = ..., + disable_existing_loggers: bool = ...) -> None: ... + def listen(port: int = ..., + verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> Thread: ... +else: + def fileConfig(fname: Union[str, IO[str]], + defaults: Optional[Dict[str, str]] = ..., + disable_existing_loggers: bool = ...) -> None: ... + def listen(port: int = ...) -> Thread: ... +def stopListening() -> None: ... diff --git a/mypy/stdlib/logging/handlers.pyi b/mypy/stdlib/logging/handlers.pyi new file mode 100644 index 000000000000..b93d201160e4 --- /dev/null +++ b/mypy/stdlib/logging/handlers.pyi @@ -0,0 +1,217 @@ +from _typeshed import StrPath +import datetime +from logging import Handler, FileHandler, LogRecord +from socket import SocketType +import ssl +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload +if sys.version_info >= (3, 7): + from queue import SimpleQueue, Queue +elif sys.version_info >= (3,): + from queue import Queue +else: + from Queue import Queue + +# TODO update socket stubs to add SocketKind +_SocketKind = int + +DEFAULT_TCP_LOGGING_PORT: int +DEFAULT_UDP_LOGGING_PORT: int +DEFAULT_HTTP_LOGGING_PORT: int +DEFAULT_SOAP_LOGGING_PORT: int +SYSLOG_UDP_PORT: int +SYSLOG_TCP_PORT: int + +class WatchedFileHandler(FileHandler): + dev: int + ino: int + def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def _statstream(self) -> None: ... + + +if sys.version_info >= (3,): + class BaseRotatingHandler(FileHandler): + terminator: str + namer: Optional[Callable[[str], str]] + rotator: Optional[Callable[[str, str], None]] + def __init__(self, filename: StrPath, mode: str, + encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def rotation_filename(self, default_name: str) -> None: ... + def rotate(self, source: str, dest: str) -> None: ... + + +if sys.version_info >= (3,): + class RotatingFileHandler(BaseRotatingHandler): + def __init__(self, filename: StrPath, mode: str = ..., maxBytes: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def doRollover(self) -> None: ... +else: + class RotatingFileHandler(Handler): + def __init__(self, filename: str, mode: str = ..., maxBytes: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def doRollover(self) -> None: ... + + +if sys.version_info >= (3,): + class TimedRotatingFileHandler(BaseRotatingHandler): + if sys.version_info >= (3, 4): + def __init__(self, filename: StrPath, when: str = ..., + interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ..., + atTime: Optional[datetime.datetime] = ...) -> None: ... + else: + def __init__(self, + filename: str, when: str = ..., interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ...) -> None: ... + def doRollover(self) -> None: ... +else: + class TimedRotatingFileHandler(Handler): + def __init__(self, + filename: str, when: str = ..., interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ...) -> None: ... + def doRollover(self) -> None: ... + + +class SocketHandler(Handler): + retryStart: float + retryFactor: float + retryMax: float + if sys.version_info >= (3, 4): + def __init__(self, host: str, port: Optional[int]) -> None: ... + else: + def __init__(self, host: str, port: int) -> None: ... + def makeSocket(self, timeout: float = ...) -> SocketType: ... # timeout is undocumented + def makePickle(self, record: LogRecord) -> bytes: ... + def send(self, s: bytes) -> None: ... + def createSocket(self) -> None: ... + + +class DatagramHandler(SocketHandler): + def makeSocket(self) -> SocketType: ... # type: ignore + + +class SysLogHandler(Handler): + LOG_ALERT: int + LOG_CRIT: int + LOG_DEBUG: int + LOG_EMERG: int + LOG_ERR: int + LOG_INFO: int + LOG_NOTICE: int + LOG_WARNING: int + LOG_AUTH: int + LOG_AUTHPRIV: int + LOG_CRON: int + LOG_DAEMON: int + LOG_FTP: int + LOG_KERN: int + LOG_LPR: int + LOG_MAIL: int + LOG_NEWS: int + LOG_SYSLOG: int + LOG_USER: int + LOG_UUCP: 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 + def __init__(self, address: Union[Tuple[str, int], str] = ..., + facility: int = ..., socktype: Optional[_SocketKind] = ...) -> None: ... + def encodePriority(self, facility: Union[int, str], + priority: Union[int, str]) -> int: ... + def mapPriority(self, levelName: str) -> str: ... + + +class NTEventLogHandler(Handler): + def __init__(self, appname: str, dllname: Optional[str] = ..., + logtype: str = ...) -> None: ... + def getEventCategory(self, record: LogRecord) -> int: ... + # TODO correct return value? + def getEventType(self, record: LogRecord) -> int: ... + def getMessageID(self, record: LogRecord) -> int: ... + + +class SMTPHandler(Handler): + # TODO `secure` can also be an empty tuple + if sys.version_info >= (3,): + def __init__(self, mailhost: Union[str, Tuple[str, int]], fromaddr: str, + toaddrs: List[str], subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ..., + timeout: float = ...) -> None: ... + else: + def __init__(self, + mailhost: Union[str, Tuple[str, int]], fromaddr: str, + toaddrs: List[str], subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ...) -> None: ... + def getSubject(self, record: LogRecord) -> str: ... + + +class BufferingHandler(Handler): + buffer: List[LogRecord] + def __init__(self, capacity: int) -> None: ... + def shouldFlush(self, record: LogRecord) -> bool: ... + +class MemoryHandler(BufferingHandler): + if sys.version_info >= (3, 6): + def __init__(self, capacity: int, flushLevel: int = ..., + target: Optional[Handler] = ..., flushOnClose: bool = ...) -> None: ... + else: + def __init__(self, capacity: int, flushLevel: int = ..., + target: Optional[Handler] = ...) -> None: ... + def setTarget(self, target: Handler) -> None: ... + + +class HTTPHandler(Handler): + if sys.version_info >= (3, 5): + def __init__(self, host: str, url: str, method: str = ..., + secure: bool = ..., + credentials: Optional[Tuple[str, str]] = ..., + context: Optional[ssl.SSLContext] = ...) -> None: ... + elif sys.version_info >= (3,): + def __init__(self, + host: str, url: str, method: str = ..., secure: bool = ..., + credentials: Optional[Tuple[str, str]] = ...) -> None: ... + else: + def __init__(self, + host: str, url: str, method: str = ...) -> None: ... + def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... + + +if sys.version_info >= (3,): + class QueueHandler(Handler): + if sys.version_info >= (3, 7): + def __init__(self, queue: Union[SimpleQueue[Any], Queue[Any]]) -> None: ... + else: + def __init__(self, queue: Queue[Any]) -> None: ... + def prepare(self, record: LogRecord) -> Any: ... + def enqueue(self, record: LogRecord) -> None: ... + + class QueueListener: + if sys.version_info >= (3, 7): + def __init__(self, queue: Union[SimpleQueue[Any], Queue[Any]], + *handlers: Handler, + respect_handler_level: bool = ...) -> None: ... + elif sys.version_info >= (3, 5): + def __init__(self, queue: Queue[Any], *handlers: Handler, + respect_handler_level: bool = ...) -> None: ... + else: + def __init__(self, + queue: Queue, *handlers: Handler) -> None: ... + def dequeue(self, block: bool) -> LogRecord: ... + def prepare(self, record: LogRecord) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def enqueue_sentinel(self) -> None: ... diff --git a/mypy/stdlib/lzma.pyi b/mypy/stdlib/lzma.pyi new file mode 100644 index 000000000000..30e71e0ec8da --- /dev/null +++ b/mypy/stdlib/lzma.pyi @@ -0,0 +1,164 @@ +import io +from typing import IO, Any, Mapping, Optional, Sequence, TextIO, TypeVar, Union, overload +from _typeshed import AnyPath, ReadableBuffer +from typing_extensions import Literal + +_OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] +_OpenTextWritingMode = Literal["wt", "xt", "at"] + +_PathOrFile = Union[AnyPath, IO[bytes]] + +_FilterChain = Sequence[Mapping[str, Any]] +_T = TypeVar("_T") + +FORMAT_AUTO: int +FORMAT_XZ: int +FORMAT_ALONE: int +FORMAT_RAW: int +CHECK_NONE: int +CHECK_CRC32: int +CHECK_CRC64: int +CHECK_SHA256: int +CHECK_ID_MAX: int +CHECK_UNKNOWN: int +FILTER_LZMA1: int +FILTER_LZMA2: int +FILTER_DELTA: int +FILTER_X86: int +FILTER_IA64: int +FILTER_ARM: int +FILTER_ARMTHUMB: int +FILTER_SPARC: int +FILTER_POWERPC: int +MF_HC3: int +MF_HC4: int +MF_BT2: int +MF_BT3: int +MF_BT4: int +MODE_FAST: int +MODE_NORMAL: int +PRESET_DEFAULT: int +PRESET_EXTREME: int + +# from _lzma.c +class LZMADecompressor(object): + def __init__( + self, format: Optional[int] = ..., memlimit: Optional[int] = ..., filters: Optional[_FilterChain] = ... + ) -> None: ... + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + @property + def check(self) -> int: ... + @property + def eof(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + @property + def needs_input(self) -> bool: ... + +# from _lzma.c +class LZMACompressor(object): + def __init__( + self, format: Optional[int] = ..., check: int = ..., preset: Optional[int] = ..., filters: Optional[_FilterChain] = ... + ) -> None: ... + def compress(self, data: bytes) -> bytes: ... + def flush(self) -> bytes: ... + +class LZMAError(Exception): ... + +class LZMAFile(io.BufferedIOBase, IO[bytes]): + def __init__( + self, + filename: Optional[_PathOrFile] = ..., + mode: str = ..., + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ..., + ) -> None: ... + def __enter__(self: _T) -> _T: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def fileno(self) -> int: ... + def seekable(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def peek(self, size: int = ...) -> bytes: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def readline(self, size: Optional[int] = ...) -> bytes: ... + def write(self, data: ReadableBuffer) -> int: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + +@overload +def open( + filename: _PathOrFile, + mode: Literal["r", "rb"] = ..., + *, + format: Optional[int] = ..., + check: Literal[-1] = ..., + preset: None = ..., + filters: Optional[_FilterChain] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> LZMAFile: ... +@overload +def open( + filename: _PathOrFile, + mode: _OpenBinaryWritingMode, + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> LZMAFile: ... +@overload +def open( + filename: AnyPath, + mode: Literal["rt"], + *, + format: Optional[int] = ..., + check: Literal[-1] = ..., + preset: None = ..., + filters: Optional[_FilterChain] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> TextIO: ... +@overload +def open( + filename: AnyPath, + mode: _OpenTextWritingMode, + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> TextIO: ... +@overload +def open( + filename: _PathOrFile, + mode: str, + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> Union[LZMAFile, TextIO]: ... +def compress( + data: bytes, format: int = ..., check: int = ..., preset: Optional[int] = ..., filters: Optional[_FilterChain] = ... +) -> bytes: ... +def decompress(data: bytes, format: int = ..., memlimit: Optional[int] = ..., filters: Optional[_FilterChain] = ...) -> bytes: ... +def is_check_supported(check: int) -> bool: ... diff --git a/mypy/stdlib/macpath.pyi b/mypy/stdlib/macpath.pyi new file mode 100644 index 000000000000..65b0aa572467 --- /dev/null +++ b/mypy/stdlib/macpath.pyi @@ -0,0 +1,144 @@ +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Union, Text, Callable, Optional +from _typeshed import StrPath, BytesPath, AnyPath + +if sys.version_info < (3, 8): + _T = TypeVar('_T') + + if sys.version_info >= (3, 6): + from builtins import _PathLike + + # ----- os.path variables ----- + supports_unicode_filenames: bool + # aliases (also in os) + curdir: str + pardir: str + sep: str + altsep: Optional[str] + extsep: str + pathsep: str + defpath: str + devnull: str + + # ----- os.path function stubs ----- + if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: 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 expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: 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 abspath(path: AnyStr) -> AnyStr: ... + def basename(s: AnyStr) -> AnyStr: ... + def dirname(s: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(s: AnyStr) -> AnyStr: ... + def realpath(path: AnyStr) -> AnyStr: ... + + # 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: ... + + if sys.version_info >= (3, 3): + def exists(path: Union[AnyPath, int]) -> bool: ... + else: + def exists(path: AnyPath) -> bool: ... + def lexists(path: AnyPath) -> 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(s: AnyPath) -> bool: ... + def ismount(s: AnyPath) -> bool: ... + + if sys.version_info < (3, 0): + # 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: ... + elif 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: ... + else: + def join(s: AnyStr, *paths: AnyStr) -> AnyStr: ... + + 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: ... + + 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 splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + else: + def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + + if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/macurl2path.pyi b/mypy/stdlib/macurl2path.pyi new file mode 100644 index 000000000000..95ee888fb564 --- /dev/null +++ b/mypy/stdlib/macurl2path.pyi @@ -0,0 +1,9 @@ + +import sys + +from typing import Union + +if sys.version_info < (3, 7): + def url2pathname(pathname: str) -> str: ... + def pathname2url(pathname: str) -> str: ... + def _pncomp2url(component: Union[str, bytes]) -> str: ... diff --git a/mypy/stdlib/mailbox.pyi b/mypy/stdlib/mailbox.pyi new file mode 100644 index 000000000000..78bc22482532 --- /dev/null +++ b/mypy/stdlib/mailbox.pyi @@ -0,0 +1,188 @@ +from typing import Optional, Union, Text, AnyStr, Callable, IO, Any, Iterator, List, Tuple, TypeVar, Protocol, Dict, Sequence, Iterable, Generic, Type, Mapping, overload +from types import TracebackType +import email +from _typeshed import AnyPath +from typing_extensions import Literal + +_T = TypeVar("_T") +_MessageType = TypeVar("_MessageType", 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[_MessageType]): + + _path: Union[bytes, str] # undocumented + _factory: Optional[Callable[[IO[Any]], _MessageType]] # undocumented + + def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], _MessageType]] = ..., 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[_MessageType]: ... + @overload + def get(self, key: str, default: _T) -> Union[_MessageType, _T]: ... + def __getitem__(self, key: str) -> _MessageType: ... + def get_message(self, key: str) -> _MessageType: ... + 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[_MessageType]: ... + def __iter__(self) -> Iterator[_MessageType]: ... + def values(self) -> List[_MessageType]: ... + def iteritems(self) -> Iterator[Tuple[str, _MessageType]]: ... + def items(self) -> List[Tuple[str, _MessageType]]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def clear(self) -> None: ... + @overload + def pop(self, key: str, default: None = ...) -> Optional[_MessageType]: ... + @overload + def pop(self, key: str, default: _T = ...) -> Union[_MessageType, _T]: ... + def popitem(self) -> Tuple[str, _MessageType]: ... + 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: AnyPath, 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[_MessageType]): ... + +class _mboxMMDF(_singlefileMailbox[_MessageType]): + + def get_file(self, key: str) -> _PartialFile[bytes]: ... + +class mbox(_mboxMMDF[mboxMessage]): + + def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ...) -> None: ... + +class MMDF(_mboxMMDF[MMDFMessage]): + + def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ...) -> None: ... + +class MH(Mailbox[MHMessage]): + + def __init__(self, dirname: AnyPath, 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_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, dirname: AnyPath, 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/stdlib/mailcap.pyi b/mypy/stdlib/mailcap.pyi new file mode 100644 index 000000000000..8f9689d9faf2 --- /dev/null +++ b/mypy/stdlib/mailcap.pyi @@ -0,0 +1,7 @@ + +from typing import Sequence, Dict, List, Union, Tuple, Optional, Mapping + +_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/stdlib/marshal.pyi b/mypy/stdlib/marshal.pyi new file mode 100644 index 000000000000..b6c19b805f84 --- /dev/null +++ b/mypy/stdlib/marshal.pyi @@ -0,0 +1,8 @@ +from typing import Any, IO + +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/stdlib/math.pyi b/mypy/stdlib/math.pyi new file mode 100644 index 000000000000..7e2686c02f8d --- /dev/null +++ b/mypy/stdlib/math.pyi @@ -0,0 +1,83 @@ +# Stubs for math +# See: http://docs.python.org/2/library/math.html + +from typing import Tuple, Iterable, SupportsFloat, SupportsInt, overload + +import sys + +e: float +pi: float +if sys.version_info >= (3, 5): + inf: float + nan: float +if sys.version_info >= (3, 6): + tau: 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: ... +if sys.version_info >= (3,): + def ceil(__x: SupportsFloat) -> int: ... +else: + 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: ... +if sys.version_info >= (3, 8): + def dist(__p: Iterable[SupportsFloat], __q: Iterable[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: ... +if sys.version_info >= (3,): + def floor(__x: SupportsFloat) -> int: ... +else: + 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: ... +if sys.version_info >= (3, 5): + def gcd(__x: int, __y: int) -> int: ... +if sys.version_info >= (3, 8): + def hypot(*coordinates: SupportsFloat) -> float: ... +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 isinf(__x: SupportsFloat) -> bool: ... +if sys.version_info >= (3,): + def isfinite(__x: SupportsFloat) -> bool: ... +def isnan(__x: SupportsFloat) -> bool: ... +if sys.version_info >= (3, 8): + def isqrt(__n: int) -> int: ... +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: ... +if sys.version_info >= (3, 3): + def log2(__x: SupportsFloat) -> float: ... +def modf(__x: SupportsFloat) -> Tuple[float, float]: ... +def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... +if sys.version_info >= (3, 8): + @overload + def prod(__iterable: Iterable[int], *, start: int = ...) -> int: ... # type: ignore + @overload + def prod(__iterable: Iterable[SupportsFloat], *, start: SupportsFloat = ...) -> float: ... +def radians(__x: SupportsFloat) -> float: ... +if sys.version_info >= (3, 7): + def remainder(__x: SupportsFloat, __y: 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/stdlib/mimetypes.pyi b/mypy/stdlib/mimetypes.pyi new file mode 100644 index 000000000000..0d5a528d0b87 --- /dev/null +++ b/mypy/stdlib/mimetypes.pyi @@ -0,0 +1,44 @@ +# Stubs for mimetypes + +from typing import Dict, IO, List, Optional, Sequence, Text, Tuple, AnyStr, Union +import sys + +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]]: ... +else: + 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(filename: 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/stdlib/mmap.pyi b/mypy/stdlib/mmap.pyi new file mode 100644 index 000000000000..fd60907128cc --- /dev/null +++ b/mypy/stdlib/mmap.pyi @@ -0,0 +1,108 @@ +import sys +from typing import (Optional, Sequence, Union, Generic, overload, + Iterable, Iterator, Sized, ContextManager, AnyStr) +from _typeshed import ReadableBuffer + +ACCESS_DEFAULT: int +ACCESS_READ: int +ACCESS_WRITE: int +ACCESS_COPY: int + +ALLOCATIONGRANULARITY: int + +if sys.platform != 'win32': + MAP_ANON: int + MAP_ANONYMOUS: int + MAP_DENYWRITE: int + MAP_EXECUTABLE: 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: ... + if sys.version_info >= (3, 8): + def flush(self, offset: int = ..., size: int = ...) -> None: ... + else: + 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: ... + +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: ... + +if sys.version_info >= (3, 8): + MADV_NORMAL: int + MADV_RANDOM: int + MADV_SEQUENTIAL: int + MADV_WILLNEED: int + MADV_DONTNEED: int + MADV_REMOVE: int + MADV_DONTFORK: int + MADV_DOFORK: int + MADV_HWPOISON: int + MADV_MERGEABLE: int + MADV_UNMERGEABLE: int + MADV_SOFT_OFFLINE: int + MADV_HUGEPAGE: int + MADV_NOHUGEPAGE: int + MADV_DONTDUMP: int + MADV_DODUMP: int + MADV_FREE: int + MADV_NOSYNC: int + MADV_AUTOSYNC: int + MADV_NOCORE: int + MADV_CORE: int + MADV_PROTECT: int diff --git a/mypy/stdlib/modulefinder.pyi b/mypy/stdlib/modulefinder.pyi new file mode 100644 index 000000000000..a3df358b5a45 --- /dev/null +++ b/mypy/stdlib/modulefinder.pyi @@ -0,0 +1,58 @@ +import sys +from typing import Optional, Container, Dict, Sequence, Tuple, List, Any, Iterator, IO, Iterable +from types import CodeType + +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 + + if sys.version_info >= (3, 8): + def __init__(self, path: Optional[List[str]] = ..., debug: int = ..., excludes: Optional[Container[str]] = ..., replace_paths: Optional[Sequence[Tuple[str, str]]] = ...) -> None: ... + else: + 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 + if sys.version_info >= (3, 6): + 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 + 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/stdlib/msilib/__init__.pyi b/mypy/stdlib/msilib/__init__.pyi new file mode 100644 index 000000000000..0cfe0dc27c20 --- /dev/null +++ b/mypy/stdlib/msilib/__init__.pyi @@ -0,0 +1,129 @@ +import sys +from typing import List, Tuple, Union, Set, Optional, Dict, Container, Any, Type, Iterable, Sequence +from types import ModuleType +from typing_extensions import Literal + +if sys.platform == 'win32': + from _msi import _Database + + AMD64: bool + if sys.version_info < (3, 7): + 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/stdlib/msilib/schema.pyi b/mypy/stdlib/msilib/schema.pyi new file mode 100644 index 000000000000..251e1ea394ec --- /dev/null +++ b/mypy/stdlib/msilib/schema.pyi @@ -0,0 +1,96 @@ + +import sys +from typing import List, Tuple, Optional + +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/stdlib/msilib/sequence.pyi b/mypy/stdlib/msilib/sequence.pyi new file mode 100644 index 000000000000..4f75d0dd34ef --- /dev/null +++ b/mypy/stdlib/msilib/sequence.pyi @@ -0,0 +1,15 @@ + +import sys +from typing import List, Tuple, Optional + +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/stdlib/msilib/text.pyi b/mypy/stdlib/msilib/text.pyi new file mode 100644 index 000000000000..c27aebb524c0 --- /dev/null +++ b/mypy/stdlib/msilib/text.pyi @@ -0,0 +1,10 @@ + +import sys +from typing import List, Tuple, Optional + +if sys.platform == 'win32': + + ActionText: List[Tuple[str, str, Optional[str]]] + UIText: List[Tuple[str, Optional[str]]] + + tables: List[str] diff --git a/mypy/stdlib/msvcrt.pyi b/mypy/stdlib/msvcrt.pyi new file mode 100644 index 000000000000..bfbb67a2872c --- /dev/null +++ b/mypy/stdlib/msvcrt.pyi @@ -0,0 +1,14 @@ +# Stubs for msvcrt + +# NOTE: These are incomplete! + +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 get_osfhandle(__fd: int) -> int: ... +def open_osfhandle(__handle: int, __flags: int) -> int: ... diff --git a/mypy/stdlib/multiprocessing/__init__.pyi b/mypy/stdlib/multiprocessing/__init__.pyi new file mode 100644 index 000000000000..fb8021ffe6d8 --- /dev/null +++ b/mypy/stdlib/multiprocessing/__init__.pyi @@ -0,0 +1,107 @@ +import sys +from typing import Any, Callable, Iterable, Optional, List, Union, Sequence, Tuple, Type, overload +from typing_extensions import Literal +from ctypes import _CData +from logging import Logger +from multiprocessing import connection, pool, spawn, synchronize +from multiprocessing.context import ( + AuthenticationError as AuthenticationError, + BaseContext, + BufferTooShort as BufferTooShort, + DefaultContext, + Process as Process, + ProcessError as ProcessError, + SpawnContext, + TimeoutError as TimeoutError, +) +from multiprocessing.managers import SyncManager +from multiprocessing.process import active_children as active_children, current_process as current_process +from multiprocessing.queues import Queue as Queue, SimpleQueue as SimpleQueue, JoinableQueue as JoinableQueue +from multiprocessing.spawn import freeze_support as freeze_support +from multiprocessing.spawn import set_executable as set_executable + +if sys.version_info >= (3, 8): + from multiprocessing.process import parent_process as parent_process + +if sys.platform != "win32": + from multiprocessing.context import ForkContext, ForkServerContext + + +# 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). + +# Sychronization primitives +_LockLike = Union[synchronize.Lock, synchronize.RLock] +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(lock: Optional[_LockLike] = ...) -> synchronize.Event: ... +def Lock() -> synchronize.Lock: ... +def RLock() -> synchronize.RLock: ... +def Semaphore(value: int = ...) -> synchronize.Semaphore: ... + +def Pipe(duplex: bool = ...) -> Tuple[connection.Connection, connection.Connection]: ... + +def Pool(processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... + +class Array: + value: Any = ... + + def __init__(self, typecode_or_type: Union[str, Type[_CData]], size_or_initializer: Union[int, Sequence[Any]], *, lock: Union[bool, _LockLike] = ...) -> None: ... + def acquire(self) -> bool: ... + def release(self) -> bool: ... + def get_lock(self) -> _LockLike: ... + def get_obj(self) -> Any: ... + + @overload + def __getitem__(self, key: int) -> Any: ... + @overload + def __getitem__(self, key: slice) -> List[Any]: ... + def __getslice__(self, start: int, stop: int) -> Any: ... + def __setitem__(self, key: int, value: Any) -> None: ... + + +class Value(): + value: Any = ... + def __init__(self, typecode_or_type: Union[str, Type[_CData]], *args: Any, lock: Union[bool, _LockLike] = ...) -> None: ... + def get_lock(self) -> _LockLike: ... + def get_obj(self) -> Any: ... + def acquire(self) -> bool: ... + def release(self) -> bool: ... + +# ----- multiprocessing function stubs ----- +def allow_connection_pickling() -> None: ... +def cpu_count() -> int: ... +def get_logger() -> Logger: ... +def log_to_stderr(level: Optional[Union[str, int]] = ...) -> Logger: ... +def Manager() -> SyncManager: ... +def set_forkserver_preload(module_names: List[str]) -> None: ... +def get_all_start_methods() -> List[str]: ... +def get_start_method(allow_none: bool = ...) -> Optional[str]: ... +def set_start_method(method: str, force: Optional[bool] = ...) -> None: ... + + +if sys.platform != "win32": + @overload + def get_context(method: None = ...) -> DefaultContext: ... + @overload + def get_context(method: Literal["spawn"]) -> SpawnContext: ... + @overload + def get_context(method: Literal["fork"]) -> ForkContext: ... + @overload + def get_context(method: Literal["forkserver"]) -> ForkServerContext: ... + @overload + def get_context(method: str) -> BaseContext: ... +else: + @overload + def get_context(method: None = ...) -> DefaultContext: ... + @overload + def get_context(method: Literal["spawn"]) -> SpawnContext: ... + @overload + def get_context(method: str) -> BaseContext: ... diff --git a/mypy/stdlib/multiprocessing/connection.pyi b/mypy/stdlib/multiprocessing/connection.pyi new file mode 100644 index 000000000000..0fb97b107a9f --- /dev/null +++ b/mypy/stdlib/multiprocessing/connection.pyi @@ -0,0 +1,58 @@ +from typing import Any, Iterable, List, Optional, Tuple, Type, Union +import socket +import sys +import types + +if sys.version_info >= (3, 8): + from typing import SupportsIndex + +# https://docs.python.org/3/library/multiprocessing.html#address-formats +_Address = Union[str, Tuple[str, int]] + +class _ConnectionBase: + if sys.version_info >= (3, 8): + def __init__(self, handle: SupportsIndex, readable: bool = ..., writable: bool = ...) -> None: ... + else: + def __init__(self, handle: int, readable: bool = ..., writable: bool = ...) -> None: ... + + @property + def closed(self) -> bool: ... # undocumented + @property + def readable(self) -> bool: ... # undocumented + @property + def writable(self) -> bool: ... # undocumented + def fileno(self) -> int: ... + def close(self) -> None: ... + def send_bytes(self, + buf: bytes, + offset: int = ..., + size: Optional[int] = ...) -> None: ... + def send(self, obj: Any) -> None: ... + def recv_bytes(self, maxlength: Optional[int] = ...) -> bytes: ... + def recv_bytes_into(self, buf: Any, offset: int = ...) -> int: ... + def recv(self) -> Any: ... + def poll(self, timeout: Optional[float] = ...) -> bool: ... + def __enter__(self) -> _ConnectionBase: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType]) -> None: ... + +class Connection(_ConnectionBase): ... + +if sys.platform == "win32": + class PipeConnection(_ConnectionBase): ... + +class Listener: + def __init__(self, address: Optional[_Address] = ..., family: Optional[str] = ..., backlog: int = ..., authkey: Optional[bytes] = ...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + @property + def address(self) -> _Address: ... + @property + def last_accepted(self) -> Optional[_Address]: ... + def __enter__(self) -> Listener: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType]) -> None: ... + +def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... +def answer_challenge(connection: Connection, authkey: bytes) -> None: ... +def wait(object_list: Iterable[Union[Connection, socket.socket, int]], timeout: Optional[float] = ...) -> List[Union[Connection, socket.socket, int]]: ... +def Client(address: _Address, family: Optional[str] = ..., authkey: Optional[bytes] = ...) -> Connection: ... +def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/stdlib/multiprocessing/context.pyi b/mypy/stdlib/multiprocessing/context.pyi new file mode 100644 index 000000000000..ced1d26ebae2 --- /dev/null +++ b/mypy/stdlib/multiprocessing/context.pyi @@ -0,0 +1,180 @@ +from logging import Logger +import multiprocessing +from multiprocessing import synchronize +from multiprocessing import queues +from multiprocessing.process import BaseProcess +import sys +from typing import Any, Callable, Iterable, Optional, List, Sequence, Type, Union, overload +from typing_extensions import Literal + +_LockLike = Union[synchronize.Lock, synchronize.RLock] + +class ProcessError(Exception): ... + +class BufferTooShort(ProcessError): ... + +class TimeoutError(ProcessError): ... + +class AuthenticationError(ProcessError): ... + +class BaseContext(object): + Process: Type[BaseProcess] + ProcessError: Type[Exception] + BufferTooShort: Type[Exception] + TimeoutError: Type[Exception] + AuthenticationError: Type[Exception] + + # N.B. The methods below are applied at runtime to generate + # multiprocessing.*, so the signatures should be identical (modulo self). + + @staticmethod + def current_process() -> BaseProcess: ... + if sys.version_info >= (3, 8): + @staticmethod + def parent_process() -> Optional[BaseProcess]: ... + @staticmethod + def active_children() -> List[BaseProcess]: ... + def cpu_count(self) -> int: ... + # TODO: change return to SyncManager once a stub exists in multiprocessing.managers + def Manager(self) -> Any: ... + # TODO: change return to Pipe once a stub exists in multiprocessing.connection + def Pipe(self, duplex: bool = ...) -> Any: ... + + def Barrier(self, + parties: int, + action: Optional[Callable[..., Any]] = ..., + timeout: Optional[float] = ...) -> synchronize.Barrier: ... + def BoundedSemaphore(self, + value: int = ...) -> synchronize.BoundedSemaphore: ... + def Condition(self, + lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... + def Event(self, lock: Optional[_LockLike] = ...) -> synchronize.Event: ... + def Lock(self) -> synchronize.Lock: ... + def RLock(self) -> synchronize.RLock: ... + def Semaphore(self, value: int = ...) -> synchronize.Semaphore: ... + + def Queue(self, maxsize: int = ...) -> queues.Queue[Any]: ... + def JoinableQueue(self, maxsize: int = ...) -> queues.JoinableQueue[Any]: ... + def SimpleQueue(self) -> queues.SimpleQueue[Any]: ... + def Pool( + self, + processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ... + ) -> multiprocessing.pool.Pool: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to RawValue once a stub exists in multiprocessing.sharedctypes + def RawValue(self, typecode_or_type: Any, *args: Any) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to RawArray once a stub exists in multiprocessing.sharedctypes + def RawArray(self, typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]]) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to Value once a stub exists in multiprocessing.sharedctypes + def Value( + self, + typecode_or_type: Any, + *args: Any, + lock: bool = ... + ) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to Array once a stub exists in multiprocessing.sharedctypes + def Array( + self, + typecode_or_type: Any, + size_or_initializer: Union[int, Sequence[Any]], + *, + lock: bool = ... + ) -> Any: ... + def freeze_support(self) -> None: ... + def get_logger(self) -> Logger: ... + def log_to_stderr(self, level: Optional[str] = ...) -> Logger: ... + def allow_connection_pickling(self) -> None: ... + def set_executable(self, executable: str) -> None: ... + def set_forkserver_preload(self, module_names: List[str]) -> None: ... + + if sys.platform != "win32": + @overload + def get_context(self, method: None = ...) -> DefaultContext: ... + @overload + def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... + @overload + def get_context(self, method: Literal["fork"]) -> ForkContext: ... + @overload + def get_context(self, method: Literal["forkserver"]) -> ForkServerContext: ... + @overload + def get_context(self, method: str) -> BaseContext: ... + else: + @overload + def get_context(self, method: None = ...) -> DefaultContext: ... + @overload + def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... + @overload + def get_context(self, method: str) -> BaseContext: ... + + def get_start_method(self, allow_none: bool = ...) -> str: ... + def set_start_method(self, method: Optional[str], force: bool = ...) -> None: ... + @property + def reducer(self) -> str: ... + @reducer.setter + def reducer(self, reduction: str) -> None: ... + def _check_available(self) -> None: ... + +class Process(BaseProcess): + _start_method: Optional[str] + @staticmethod + def _Popen(process_obj: BaseProcess) -> DefaultContext: ... + +class DefaultContext(BaseContext): + Process: Type[multiprocessing.Process] + + def __init__(self, context: BaseContext) -> None: ... + def set_start_method(self, method: Optional[str], force: bool = ...) -> None: ... + def get_start_method(self, allow_none: bool = ...) -> str: ... + def get_all_start_methods(self) -> List[str]: ... + +if sys.platform != 'win32': + class ForkProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> Any: ... + + class SpawnProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> SpawnProcess: ... + + class ForkServerProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> Any: ... + + class ForkContext(BaseContext): + _name: str + Process: Type[ForkProcess] + + class SpawnContext(BaseContext): + _name: str + Process: Type[SpawnProcess] + + class ForkServerContext(BaseContext): + _name: str + Process: Type[ForkServerProcess] +else: + class SpawnProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> Any: ... + + class SpawnContext(BaseContext): + _name: str + Process: Type[SpawnProcess] + +def _force_start_method(method: str) -> None: ... +def get_spawning_popen() -> Optional[Any]: ... +def set_spawning_popen(popen: Any) -> None: ... +def assert_spawning(obj: Any) -> None: ... diff --git a/mypy/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/stdlib/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000000..5d07f6d9c93c --- /dev/null +++ b/mypy/stdlib/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,46 @@ +from typing import Any, Optional, List + +import array +import threading +import weakref + +from queue import Queue as Queue + +JoinableQueue = Queue +Barrier = threading.Barrier +BoundedSemaphore = threading.BoundedSemaphore +Condition = threading.Condition +Event = threading.Event +Lock = threading.Lock +RLock = threading.RLock +Semaphore = threading.Semaphore + +class DummyProcess(threading.Thread): + _children: weakref.WeakKeyDictionary[Any, Any] + _parent: threading.Thread + _pid: None + _start_called: int + exitcode: Optional[int] + def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + +Process = DummyProcess + +class Namespace: + def __init__(self, **kwds: Any) -> None: ... + def __getattr__(self, __name: str) -> Any: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + +class Value: + _typecode: Any + _value: Any + value: Any + def __init__(self, typecode, value, lock=...) -> None: ... + + +def Array(typecode, sequence, lock=...) -> array.array[Any]: ... +def Manager() -> Any: ... +def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def active_children() -> List[Any]: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/mypy/stdlib/multiprocessing/dummy/connection.pyi b/mypy/stdlib/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000000..d465a5b4f434 --- /dev/null +++ b/mypy/stdlib/multiprocessing/dummy/connection.pyi @@ -0,0 +1,35 @@ +from typing import Any, List, Optional, Tuple, TypeVar + +from queue import Queue + +families: List[None] + +_TConnection = TypeVar('_TConnection', bound=Connection) +_TListener = TypeVar('_TListener', bound=Listener) + +class Connection(object): + _in: Any + _out: Any + recv: Any + recv_bytes: Any + send: Any + send_bytes: Any + def __enter__(self: _TConnection) -> _TConnection: ... + def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout: float = ...) -> bool: ... + +class Listener(object): + _backlog_queue: Optional[Queue[Any]] + @property + def address(self) -> Optional[Queue[Any]]: ... + def __enter__(self: _TListener) -> _TListener: ... + def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + + +def Client(address) -> Connection: ... +def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/stdlib/multiprocessing/managers.pyi b/mypy/stdlib/multiprocessing/managers.pyi new file mode 100644 index 000000000000..528a18038041 --- /dev/null +++ b/mypy/stdlib/multiprocessing/managers.pyi @@ -0,0 +1,110 @@ +# Stubs for multiprocessing.managers + +# NOTE: These are incomplete! + +import queue +import sys +import threading +from typing import ( + Any, Callable, ContextManager, Dict, Iterable, Generic, List, Mapping, Optional, + Sequence, Tuple, TypeVar, Union, AnyStr, +) +from .context import BaseContext + +if sys.version_info >= (3, 8): + from .shared_memory import ShareableList, SharedMemory, _SLT + +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +class Namespace: + def __init__(self, **kwds: Any) -> None: ... + def __getattr__(self, __name: str) -> Any: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + +_Namespace = Namespace + +class Token(object): + typeid: Optional[Union[str, bytes]] + address: Tuple[Union[str, bytes], int] + id: Optional[Union[str, bytes, int]] + def __init__(self, typeid: Optional[Union[bytes, str]], address: Tuple[Union[str, bytes], int], + id: Optional[Union[str, bytes, int]]) -> None: ... + def __repr__(self) -> str: ... + def __getstate__(self) -> Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], + Optional[Union[str, bytes, int]]]: ... + def __setstate__(self, state: Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], + Optional[Union[str, bytes, int]]]) -> None: ... + +class BaseProxy(object): + _address_to_local: Dict[Any, Any] + _mutex: Any + if sys.version_info >= (3, 6): + def __init__(self, token: Any, serializer: str, manager: Any = ..., + authkey: Optional[AnyStr] = ..., exposed: Any = ..., + incref: bool = ..., manager_owned: bool = ...) -> None: ... + else: + def __init__(self, token: Any, serializer: str, manager: Any = ..., + authkey: Optional[AnyStr] = ..., exposed: Any = ..., + incref: bool = ...) -> None: ... + def __deepcopy__(self, memo: Optional[Any]) -> Any: ... + def _callmethod(self, methodname: str, args: Tuple[Any, ...] = ..., + kwds: Dict[Any, Any] = ...) -> None: ... + def _getvalue(self) -> Any: ... + def __reduce__(self) -> Tuple[Any, Tuple[Any, Any, str, Dict[Any, Any]]]: ... + +class ValueProxy(BaseProxy, Generic[_T]): + def get(self) -> _T: ... + def set(self, value: _T) -> None: ... + value: _T + +# Returned by BaseManager.get_server() +class Server: + address: Any + def serve_forever(self) -> None: ... + +class BaseManager(ContextManager[BaseManager]): + def __init__( + self, + address: Optional[Any] = ..., + authkey: Optional[bytes] = ..., + serializer: str = ..., + ctx: Optional[BaseContext] = ..., + ) -> None: ... + def get_server(self) -> Server: ... + def connect(self) -> None: ... + def start(self, initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ...) -> None: ... + def shutdown(self) -> None: ... # only available after start() was called + def join(self, timeout: Optional[float] = ...) -> None: ... # undocumented + @property + def address(self) -> Any: ... + @classmethod + def register(cls, typeid: str, callable: Optional[Callable[..., Any]] = ..., + proxytype: Any = ..., + exposed: Optional[Sequence[str]] = ..., + method_to_typeid: Optional[Mapping[str, str]] = ..., + create_method: bool = ...) -> None: ... + +class SyncManager(BaseManager, ContextManager[SyncManager]): + def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... + def Condition(self, lock: Any = ...) -> threading.Condition: ... + def Event(self) -> threading.Event: ... + def Lock(self) -> threading.Lock: ... + def Namespace(self) -> _Namespace: ... + def Queue(self, maxsize: int = ...) -> queue.Queue[Any]: ... + def RLock(self) -> threading.RLock: ... + def Semaphore(self, value: Any = ...) -> threading.Semaphore: ... + def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... + def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ... + def dict(self, sequence: Mapping[_KT, _VT] = ...) -> Dict[_KT, _VT]: ... + def list(self, sequence: Sequence[_T] = ...) -> List[_T]: ... + +class RemoteError(Exception): ... + +if sys.version_info >= (3, 8): + class SharedMemoryServer(Server): ... + class SharedMemoryManager(BaseManager): + def get_server(self) -> SharedMemoryServer: ... + def SharedMemory(self, size: int) -> SharedMemory: ... # noqa: F811 + def ShareableList(self, sequence: Optional[Iterable[_SLT]]) -> ShareableList[_SLT]: ... # noqa: F811 diff --git a/mypy/stdlib/multiprocessing/pool.pyi b/mypy/stdlib/multiprocessing/pool.pyi new file mode 100644 index 000000000000..5d37644306e7 --- /dev/null +++ b/mypy/stdlib/multiprocessing/pool.pyi @@ -0,0 +1,83 @@ +from typing import Any, Callable, ContextManager, Iterable, Mapping, Optional, List, TypeVar, Generic, Iterator + +_PT = TypeVar('_PT', bound=Pool) +_S = TypeVar('_S') +_T = TypeVar('_T') + +class ApplyResult(Generic[_T]): + def get(self, timeout: Optional[float] = ...) -> _T: ... + def wait(self, timeout: Optional[float] = ...) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + +# alias created during issue #17805 +AsyncResult = ApplyResult + +class MapResult(ApplyResult[List[_T]]): ... + +class IMapIterator(Iterator[_T]): + def __iter__(self: _S) -> _S: ... + def next(self, timeout: Optional[float] = ...) -> _T: ... + def __next__(self, timeout: Optional[float] = ...) -> _T: ... + +class IMapUnorderedIterator(IMapIterator[_T]): ... + +class Pool(ContextManager[Pool]): + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., + context: Optional[Any] = ...) -> None: ... + def apply(self, + func: Callable[..., _T], + args: Iterable[Any] = ..., + kwds: Mapping[str, Any] = ...) -> _T: ... + def apply_async(self, + func: Callable[..., _T], + args: Iterable[Any] = ..., + kwds: Mapping[str, Any] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[_T]: ... + def map(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> List[_T]: ... + def map_async(self, func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> MapResult[_T]: ... + def imap(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... + def imap_unordered(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... + def starmap(self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]] = ..., + chunksize: Optional[int] = ...) -> List[_T]: ... + def starmap_async(self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[List[_T]]: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + def __enter__(self: _PT) -> _PT: ... + + +class ThreadPool(Pool, ContextManager[ThreadPool]): + + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ...) -> None: ... + +# undocumented +RUN: int +CLOSE: int +TERMINATE: int diff --git a/mypy/stdlib/multiprocessing/process.pyi b/mypy/stdlib/multiprocessing/process.pyi new file mode 100644 index 000000000000..a979ee7b283d --- /dev/null +++ b/mypy/stdlib/multiprocessing/process.pyi @@ -0,0 +1,38 @@ +import sys +from typing import Any, Callable, List, Mapping, Optional, Tuple + +class BaseProcess: + name: str + daemon: bool + authkey: bytes + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Tuple[Any, ...] = ..., + kwargs: Mapping[str, Any] = ..., + *, + daemon: Optional[bool] = ..., + ) -> None: ... + def run(self) -> None: ... + def start(self) -> None: ... + def terminate(self) -> None: ... + if sys.version_info >= (3, 7): + def kill(self) -> None: ... + def close(self) -> None: ... + def join(self, timeout: Optional[float] = ...) -> None: ... + def is_alive(self) -> bool: ... + @property + def exitcode(self) -> Optional[int]: ... + @property + def ident(self) -> Optional[int]: ... + @property + def pid(self) -> Optional[int]: ... + @property + def sentinel(self) -> int: ... + +def current_process() -> BaseProcess: ... +def active_children() -> List[BaseProcess]: ... +if sys.version_info >= (3, 8): + def parent_process() -> Optional[BaseProcess]: ... diff --git a/mypy/stdlib/multiprocessing/queues.pyi b/mypy/stdlib/multiprocessing/queues.pyi new file mode 100644 index 000000000000..c6dd0f20d631 --- /dev/null +++ b/mypy/stdlib/multiprocessing/queues.pyi @@ -0,0 +1,30 @@ +from typing import Any, Generic, Optional, TypeVar + +import queue + +_T = TypeVar('_T') + +class Queue(queue.Queue[_T]): + # FIXME: `ctx` is a circular dependency and it's not actually optional. + # It's marked as such to be able to use the generic Queue in __init__.pyi. + def __init__(self, maxsize: int = ..., *, ctx: Any = ...) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def put(self, obj: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put_nowait(self, item: _T) -> None: ... + def get_nowait(self) -> _T: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + +class JoinableQueue(Queue[_T]): + def task_done(self) -> None: ... + def join(self) -> None: ... + +class SimpleQueue(Generic[_T]): + def __init__(self, *, ctx: Any = ...) -> None: ... + def empty(self) -> bool: ... + def get(self) -> _T: ... + def put(self, item: _T) -> None: ... diff --git a/mypy/stdlib/multiprocessing/shared_memory.pyi b/mypy/stdlib/multiprocessing/shared_memory.pyi new file mode 100644 index 000000000000..6a16a09a60ef --- /dev/null +++ b/mypy/stdlib/multiprocessing/shared_memory.pyi @@ -0,0 +1,29 @@ +import sys +from typing import Generic, Iterable, Optional, Tuple, TypeVar + +_S = TypeVar("_S") +_SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) + +if sys.version_info >= (3, 8): + class SharedMemory: + def __init__(self, name: Optional[str] = ..., create: bool = ..., size: int = ...) -> None: ... + @property + def buf(self) -> memoryview: ... + @property + def name(self) -> str: ... + @property + def size(self) -> int: ... + def close(self) -> None: ... + def unlink(self) -> None: ... + + class ShareableList(Generic[_SLT]): + shm: SharedMemory + def __init__(self, sequence: Optional[Iterable[_SLT]] = ..., *, name: Optional[str] = ...) -> None: ... + def __getitem__(self, position: int) -> _SLT: ... + def __setitem__(self, position: int, value: _SLT) -> None: ... + def __reduce__(self: _S) -> Tuple[_S, Tuple[_SLT, ...]]: ... + def __len__(self) -> int: ... + @property + def format(self) -> str: ... + def count(self, value: _SLT) -> int: ... + def index(self, value: _SLT) -> int: ... diff --git a/mypy/stdlib/multiprocessing/spawn.pyi b/mypy/stdlib/multiprocessing/spawn.pyi new file mode 100644 index 000000000000..9d170f6f2cc4 --- /dev/null +++ b/mypy/stdlib/multiprocessing/spawn.pyi @@ -0,0 +1,18 @@ +from typing import Any, Dict, List, Mapping, Optional, Sequence +from types import ModuleType + +WINEXE: bool +WINSERVICE: bool + +def set_executable(exe: str) -> None: ... +def get_executable() -> str: ... +def is_forking(argv: Sequence[str]) -> bool: ... +def freeze_support() -> None: ... +def get_command_line(**kwds: Any) -> List[str]: ... +def spawn_main(pipe_handle: int, parent_pid: Optional[int] = ..., tracker_fd: Optional[int] = ...) -> None: ... +# undocumented +def _main(fd: int) -> Any: ... +def get_preparation_data(name: str) -> Dict[str, Any]: ... +old_main_modules: List[ModuleType] +def prepare(data: Mapping[str, Any]) -> None: ... +def import_main_path(main_path: str) -> None: ... diff --git a/mypy/stdlib/multiprocessing/synchronize.pyi b/mypy/stdlib/multiprocessing/synchronize.pyi new file mode 100644 index 000000000000..224485b317ba --- /dev/null +++ b/mypy/stdlib/multiprocessing/synchronize.pyi @@ -0,0 +1,63 @@ +from typing import Any, Callable, ContextManager, Optional, Union + +from multiprocessing.context import BaseContext +import threading +import sys + +_LockLike = Union[Lock, RLock] + +class Barrier(threading.Barrier): + def __init__(self, + parties: int, + action: Optional[Callable[..., Any]] = ..., + timeout: Optional[float] = ..., + * + ctx: BaseContext) -> None: ... + +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... + +class Condition(ContextManager[bool]): + def __init__(self, + lock: Optional[_LockLike] = ..., + *, + ctx: BaseContext) -> None: ... + if sys.version_info >= (3, 7): + def notify(self, n: int = ...) -> None: ... + else: + def notify(self) -> None: ... + def notify_all(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + def wait_for(self, + predicate: Callable[[], bool], + timeout: Optional[float] = ...) -> bool: ... + def acquire(self, + block: bool = ..., + timeout: Optional[float] = ...) -> bool: ... + def release(self) -> None: ... + +class Event(ContextManager[bool]): + def __init__(self, + lock: Optional[_LockLike] = ..., + *, + ctx: BaseContext) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + +class Lock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class RLock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class Semaphore(SemLock): + def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... + +# Not part of public API +class SemLock(ContextManager[bool]): + def acquire(self, + block: bool = ..., + timeout: Optional[float] = ...) -> bool: ... + def release(self) -> None: ... diff --git a/mypy/stdlib/netrc.pyi b/mypy/stdlib/netrc.pyi new file mode 100644 index 000000000000..3ceae889963b --- /dev/null +++ b/mypy/stdlib/netrc.pyi @@ -0,0 +1,19 @@ +from typing import AnyStr, Dict, List, Optional, Tuple, overload + + +class NetrcParseError(Exception): + filename: Optional[str] + lineno: Optional[int] + msg: str + + +# (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: str = ...) -> None: ... + def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/mypy/stdlib/nis.pyi b/mypy/stdlib/nis.pyi new file mode 100644 index 000000000000..87223caf2e39 --- /dev/null +++ b/mypy/stdlib/nis.pyi @@ -0,0 +1,10 @@ +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/stdlib/nntplib.pyi b/mypy/stdlib/nntplib.pyi new file mode 100644 index 000000000000..0a88ff150b5c --- /dev/null +++ b/mypy/stdlib/nntplib.pyi @@ -0,0 +1,102 @@ +# Stubs for nntplib (Python 3) + +import datetime +import socket +import ssl +import sys +from typing import Any, Dict, IO, 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]]]]: ... + if sys.version_info < (3, 9): + 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, ssl_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/stdlib/ntpath.pyi b/mypy/stdlib/ntpath.pyi new file mode 100644 index 000000000000..ef4b48331d89 --- /dev/null +++ b/mypy/stdlib/ntpath.pyi @@ -0,0 +1,164 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from genericpath import exists as exists +from _typeshed import StrPath, BytesPath, AnyPath + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyStr) -> AnyStr: ... + @overload + def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(p: AnyStr) -> AnyStr: ... + def dirname(p: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(s: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of StrPath and bytes for sequences + # of BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[AnyPath]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# 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: ... + +# 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: ... + +if sys.version_info < (3, 0): + # 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: ... +elif sys.version_info >= (3, 6): + @overload + def join(a: StrPath, *paths: StrPath) -> Text: ... + @overload + def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +else: + def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... + +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: ... + +if sys.version_info >= (3, 6): + @overload + def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.version_info < (3, 7) and sys.platform == 'win32': + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/nturl2path.pyi b/mypy/stdlib/nturl2path.pyi new file mode 100644 index 000000000000..b8ad8d682155 --- /dev/null +++ b/mypy/stdlib/nturl2path.pyi @@ -0,0 +1,2 @@ +def url2pathname(url: str) -> str: ... +def pathname2url(p: str) -> str: ... diff --git a/mypy/stdlib/numbers.pyi b/mypy/stdlib/numbers.pyi new file mode 100644 index 000000000000..befe7d53a781 --- /dev/null +++ b/mypy/stdlib/numbers.pyi @@ -0,0 +1,144 @@ +# Stubs for numbers (Python 3.5) +# See https://docs.python.org/2.7/library/numbers.html +# and https://docs.python.org/3/library/numbers.html +# +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. + +from typing import Any, Optional, SupportsFloat, overload +from abc import ABCMeta, abstractmethod +import sys + +class Number(metaclass=ABCMeta): + @abstractmethod + def __hash__(self) -> int: ... + +class Complex(Number): + @abstractmethod + def __complex__(self) -> complex: ... + if sys.version_info >= (3, 0): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + @property + @abstractmethod + def real(self): ... + @property + @abstractmethod + def imag(self): ... + @abstractmethod + def __add__(self, other): ... + @abstractmethod + def __radd__(self, other): ... + @abstractmethod + def __neg__(self): ... + @abstractmethod + def __pos__(self): ... + def __sub__(self, other): ... + def __rsub__(self, other): ... + @abstractmethod + def __mul__(self, other): ... + @abstractmethod + def __rmul__(self, other): ... + if sys.version_info < (3, 0): + @abstractmethod + def __div__(self, other): ... + @abstractmethod + def __rdiv__(self, other): ... + @abstractmethod + def __truediv__(self, other): ... + @abstractmethod + def __rtruediv__(self, other): ... + @abstractmethod + def __pow__(self, exponent): ... + @abstractmethod + def __rpow__(self, base): ... + def __abs__(self): ... + def conjugate(self): ... + def __eq__(self, other: object) -> bool: ... + if sys.version_info < (3, 0): + def __ne__(self, other: object) -> 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 = ...): ... + @abstractmethod + @overload + def __round__(self, ndigits: int): ... + def __divmod__(self, other): ... + def __rdivmod__(self, other): ... + @abstractmethod + def __floordiv__(self, other): ... + @abstractmethod + def __rfloordiv__(self, other): ... + @abstractmethod + def __mod__(self, other): ... + @abstractmethod + def __rmod__(self, other): ... + @abstractmethod + def __lt__(self, other) -> bool: ... + @abstractmethod + def __le__(self, other) -> bool: ... + def __complex__(self) -> complex: ... + @property + def real(self): ... + @property + def imag(self): ... + def conjugate(self): ... + +class Rational(Real): + @property + @abstractmethod + def numerator(self) -> int: ... + @property + @abstractmethod + def denominator(self) -> int: ... + def __float__(self) -> float: ... + +class Integral(Rational): + if sys.version_info >= (3, 0): + @abstractmethod + def __int__(self) -> int: ... + else: + @abstractmethod + def __long__(self) -> long: ... + def __index__(self) -> int: ... + @abstractmethod + def __pow__(self, exponent, modulus: Optional[Any] = ...): ... + @abstractmethod + def __lshift__(self, other): ... + @abstractmethod + def __rlshift__(self, other): ... + @abstractmethod + def __rshift__(self, other): ... + @abstractmethod + def __rrshift__(self, other): ... + @abstractmethod + def __and__(self, other): ... + @abstractmethod + def __rand__(self, other): ... + @abstractmethod + def __xor__(self, other): ... + @abstractmethod + def __rxor__(self, other): ... + @abstractmethod + def __or__(self, other): ... + @abstractmethod + def __ror__(self, other): ... + @abstractmethod + def __invert__(self): ... + def __float__(self) -> float: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... diff --git a/mypy/stdlib/opcode.pyi b/mypy/stdlib/opcode.pyi new file mode 100644 index 000000000000..b219670f5dec --- /dev/null +++ b/mypy/stdlib/opcode.pyi @@ -0,0 +1,25 @@ +from typing import List, Dict, Optional, Sequence + +import sys + +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 + +if sys.version_info >= (3, 8): + def stack_effect(__opcode: int, __oparg: Optional[int] = ..., *, jump: Optional[bool] = ...) -> int: ... +elif sys.version_info >= (3, 4): + def stack_effect(__opcode: int, __oparg: Optional[int] = ...) -> int: ... + +if sys.version_info >= (3, 6): + hasnargs: List[int] diff --git a/mypy/stdlib/operator.pyi b/mypy/stdlib/operator.pyi new file mode 100644 index 000000000000..e301b0df3480 --- /dev/null +++ b/mypy/stdlib/operator.pyi @@ -0,0 +1,239 @@ +# Stubs for operator + +from typing import ( + Any, Callable, Container, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, Tuple, + TypeVar, overload, +) +import sys + + +_T = TypeVar('_T') +_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: ... + +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: ... +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: ... + +if sys.version_info >= (3, 5): + 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: ... +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[_T], __b: int) -> None: ... +@overload +def delitem(__a: MutableSequence[_T], __b: slice) -> None: ... +@overload +def delitem(__a: MutableMapping[_K, _V], __b: _K) -> None: ... +@overload +def __delitem__(a: MutableSequence[_T], b: int) -> None: ... +@overload +def __delitem__(a: MutableSequence[_T], b: slice) -> None: ... +@overload +def __delitem__(a: MutableMapping[_K, _V], 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 +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: ... + +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 +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: ... + +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: ... + +@overload +def attrgetter(attr: str) -> Callable[[Any], Any]: ... +@overload +def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ... + +@overload +def itemgetter(item: Any) -> Callable[[Any], Any]: ... +@overload +def itemgetter(*items: Any) -> Callable[[Any], Tuple[Any, ...]]: ... + +def methodcaller(name: str, *args: Any, **kwargs: Any) -> Callable[..., 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: ... + +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: ... +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: ... + +if sys.version_info >= (3, 5): + 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: ... +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: ... + + +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/stdlib/optparse.pyi b/mypy/stdlib/optparse.pyi new file mode 100644 index 000000000000..9c96030d31d4 --- /dev/null +++ b/mypy/stdlib/optparse.pyi @@ -0,0 +1,234 @@ +# Generated by pytype, with only minor tweaks. Might be incomplete. +import sys +from typing import Any, AnyStr, Callable, Dict, IO, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, 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[_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: ... + +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 _format__Text(self, _Text: _Text) -> _Text: ... + 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: OptionParser) -> _Text: ... + def format_option_strings(self, option: OptionParser) -> Any: ... + 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] + nargs: int + type: Any + 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: Any, value: Any) -> Any: ... + def convert_value(self, opt: Any, 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: Any + def __init__(self, option_class: 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[OptionParser] + 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: Iterable[Option] = ..., + option_class: 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) -> OptionParser: ... + @overload + def add_option_group(self, *args: Any, **kwargs: Any) -> OptionParser: ... + 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/stdlib/os/__init__.pyi b/mypy/stdlib/os/__init__.pyi new file mode 100644 index 000000000000..4219794a2d0e --- /dev/null +++ b/mypy/stdlib/os/__init__.pyi @@ -0,0 +1,717 @@ +from io import TextIOWrapper as _TextIOWrapper +from posix import listdir as listdir, times_result +import sys +from typing import ( + Mapping, MutableMapping, Dict, List, Any, Tuple, Iterable, Iterator, NoReturn, overload, Union, AnyStr, + Optional, Generic, Set, Callable, Sequence, NamedTuple, ContextManager, TypeVar +) +from _typeshed import AnyPath + +from builtins import OSError as error +from . import path as path + +# We need to use something from path, or flake8 and pytype get unhappy +_supports_unicode_filenames = path.supports_unicode_filenames + +_T = TypeVar("_T") + +# ----- os variables ----- + +supports_bytes_environ: bool + +supports_dir_fd: Set[Callable[..., Any]] +supports_fd: Set[Callable[..., Any]] +supports_effective_ids: Set[Callable[..., Any]] +supports_follow_symlinks: Set[Callable[..., Any]] + +if sys.platform != 'win32': + # Unix only + PRIO_PROCESS: int + PRIO_PGRP: int + PRIO_USER: int + + F_LOCK: int + F_TLOCK: int + F_ULOCK: int + F_TEST: int + + if sys.platform != "darwin": + POSIX_FADV_NORMAL: int + POSIX_FADV_SEQUENTIAL: int + POSIX_FADV_RANDOM: int + POSIX_FADV_NOREUSE: int + POSIX_FADV_WILLNEED: int + POSIX_FADV_DONTNEED: int + + SF_NODISKIO: int + SF_MNOWAIT: int + SF_SYNC: int + + if sys.platform == "linux": + XATTR_SIZE_MAX: int + XATTR_CREATE: int + XATTR_REPLACE: int + + P_PID: int + P_PGID: int + P_ALL: int + + WEXITED: int + WSTOPPED: int + WNOWAIT: int + + CLD_EXITED: int + CLD_DUMPED: int + CLD_TRAPPED: int + CLD_CONTINUED: int + + SCHED_OTHER: int # some flavors of Unix + SCHED_BATCH: int # some flavors of Unix + SCHED_IDLE: int # some flavors of Unix + SCHED_SPORADIC: int # some flavors of Unix + SCHED_FIFO: int # some flavors of Unix + SCHED_RR: int # some flavors of Unix + SCHED_RESET_ON_FORK: int # some flavors of Unix + +if sys.platform != "win32": + RTLD_LAZY: int + RTLD_NOW: int + RTLD_GLOBAL: int + RTLD_LOCAL: int + RTLD_NODELETE: int + RTLD_NOLOAD: int + RTLD_DEEPBIND: int + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int +if sys.platform != 'win32': + SEEK_DATA: int # some flavors of Unix + SEEK_HOLE: int # some flavors of Unix + +O_RDONLY: int +O_WRONLY: int +O_RDWR: int +O_APPEND: int +O_CREAT: int +O_EXCL: int +O_TRUNC: int +# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, +# including tests for mypy, use a more finer way than sys.platform before using these APIs +# See https://github.com/python/typeshed/pull/2286 for discussions +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only +O_NONBLOCK: int # Unix only +O_NOCTTY: int # Unix only +O_CLOEXEC: int # Unix only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only +O_NOINHERIT: int # Windows only +O_SHORT_LIVED: int # Windows only +O_TEMPORARY: int # Windows only +O_RANDOM: int # Windows only +O_SEQUENTIAL: int # Windows only +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library +O_DIRECTORY: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library +O_PATH: int # Gnu extension if in C library +O_TMPFILE: int # Gnu extension if in C library +O_LARGEFILE: int # Gnu extension if in C library + +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +linesep: str +devnull: str +name: str + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + def copy(self) -> Dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __len__(self) -> int: ... + +environ: _Environ[str] +if sys.platform != "win32": + environb: _Environ[bytes] + +if sys.platform != 'win32': + confstr_names: Dict[str, int] + pathconf_names: Dict[str, int] + sysconf_names: Dict[str, int] + + EX_OK: int + EX_USAGE: int + EX_DATAERR: int + EX_NOINPUT: int + EX_NOUSER: int + EX_NOHOST: int + EX_UNAVAILABLE: int + EX_SOFTWARE: int + EX_OSERR: int + EX_OSFILE: int + EX_CANTCREAT: int + EX_IOERR: int + EX_TEMPFAIL: int + EX_PROTOCOL: int + EX_NOPERM: int + EX_CONFIG: int + EX_NOTFOUND: int + +P_NOWAIT: int +P_NOWAITO: int +P_WAIT: int +if sys.platform == 'win32': + P_DETACH: int + P_OVERLAY: int + +# wait()/waitpid() options +if sys.platform != 'win32': + WNOHANG: int # Unix only + WCONTINUED: int # some Unix systems + WUNTRACED: int # Unix only + +TMP_MAX: int # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +class stat_result: + # For backward compatibility, the return value of stat() is also + # accessible as a tuple of at least 10 integers giving the most important + # (and portable) members of the stat structure, in the order st_mode, + # st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, + # st_ctime. More items may be added at the end by some implementations. + + st_mode: int # protection bits, + st_ino: int # inode number, + st_dev: int # device, + st_nlink: int # number of hard links, + st_uid: int # user id of owner, + st_gid: int # group id of owner, + st_size: int # size of file, in bytes, + st_atime: float # time of most recent access, + st_mtime: float # time of most recent content modification, + st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) + st_atime_ns: int # time of most recent access, in nanoseconds + st_mtime_ns: int # time of most recent content modification in nanoseconds + st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds + if sys.version_info >= (3, 8) and sys.platform == "win32": + st_reparse_tag: int + if sys.version_info >= (3, 5) and sys.platform == "win32": + st_file_attributes: int + + def __getitem__(self, i: int) -> int: ... + + # not documented + def __init__(self, tuple: Tuple[int, ...]) -> None: ... + + # On some Unix systems (such as Linux), the following attributes may also + # be available: + st_blocks: int # number of blocks allocated for file + st_blksize: int # filesystem blocksize + st_rdev: int # type of device if an inode device + st_flags: int # user defined flags for file + + # On other Unix systems (such as FreeBSD), the following attributes may be + # available (but may be only filled out if root tries to use them): + st_gen: int # file generation number + st_birthtime: int # time of file creation + + # On Mac OS systems, the following attributes may also be available: + st_rsize: int + st_creator: int + st_type: int + +if sys.version_info >= (3, 6): + from builtins import _PathLike as PathLike # See comment in builtins + +_FdOrAnyPath = Union[int, AnyPath] + +if sys.version_info >= (3, 6): + class DirEntry(PathLike[AnyStr]): + # This is what the scandir interator yields + # The constructor is hidden + + name: AnyStr + path: AnyStr + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + + def __fspath__(self) -> AnyStr: ... +else: + class DirEntry(Generic[AnyStr]): + # This is what the scandir interator yields + # The constructor is hidden + + name: AnyStr + path: AnyStr + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + + +if sys.platform != 'win32': + if sys.version_info >= (3, 7): + # f_fsid was added in https://github.com/python/cpython/pull/4571 + class statvfs_result(NamedTuple): # Unix only + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + f_fsid: int + else: + class statvfs_result(NamedTuple): # Unix only + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + + +# ----- os function stubs ----- +if sys.version_info >= (3, 6): + def fsencode(filename: Union[str, bytes, PathLike[Any]]) -> bytes: ... +else: + def fsencode(filename: Union[str, bytes]) -> bytes: ... + +if sys.version_info >= (3, 6): + def fsdecode(filename: Union[str, bytes, PathLike[Any]]) -> str: ... +else: + def fsdecode(filename: Union[str, bytes]) -> str: ... + +if sys.version_info >= (3, 6): + @overload + def fspath(path: str) -> str: ... + @overload + def fspath(path: bytes) -> bytes: ... + @overload + def fspath(path: PathLike[AnyStr]) -> AnyStr: ... + +def get_exec_path(env: Optional[Mapping[str, str]] = ...) -> List[str]: ... +# NOTE: get_exec_path(): returns List[bytes] when env not None +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(__code: int) -> str: ... +def umask(__mask: int) -> int: ... + +if sys.platform != 'win32': + # Unix only + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + def getgrouplist(user: str, gid: int) -> List[int]: ... + def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + def getpriority(which: int, who: int) -> int: ... + def setpriority(which: int, who: int, priority: int) -> None: ... + if sys.platform != "darwin": + def getresuid() -> Tuple[int, int, int]: ... + def getresgid() -> Tuple[int, int, int]: ... + def getuid() -> int: ... + def setegid(__egid: int) -> None: ... + def seteuid(__euid: int) -> None: ... + def setgid(__gid: int) -> None: ... + def setgroups(__groups: Sequence[int]) -> None: ... + def setpgrp() -> None: ... + def setpgid(__pid: int, __pgrp: int) -> None: ... + def setregid(__rgid: int, __egid: int) -> None: ... + if sys.platform != "darwin": + def setresgid(rgid: int, egid: int, sgid: int) -> None: ... + def setresuid(ruid: int, euid: int, suid: int) -> None: ... + def setreuid(__ruid: int, __euid: int) -> None: ... + def getsid(__pid: int) -> int: ... + def setsid() -> None: ... + def setuid(__uid: int) -> None: ... + from posix import uname_result + def uname() -> uname_result: ... + +@overload +def getenv(key: str) -> Optional[str]: ... +@overload +def getenv(key: str, default: _T) -> Union[str, _T]: ... + +if sys.platform != "win32": + @overload + def getenvb(key: bytes) -> Optional[bytes]: ... + @overload + def getenvb(key: bytes, default: _T = ...) -> Union[bytes, _T]: ... +def putenv(__name: Union[bytes, str], __value: Union[bytes, str]) -> None: ... +if sys.platform != "win32": + def unsetenv(__name: Union[bytes, str]) -> None: ... + +# Return IO or TextIO +def fdopen(fd: int, mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: str = ..., newline: str = ..., closefd: bool = ...) -> Any: ... +def close(fd: int) -> None: ... +def closerange(__fd_low: int, __fd_high: int) -> None: ... +def device_encoding(fd: int) -> Optional[str]: ... +def dup(__fd: int) -> int: ... +if sys.version_info >= (3, 7): + def dup2(fd: int, fd2: int, inheritable: bool = ...) -> int: ... +else: + def dup2(fd: int, fd2: int, inheritable: bool = ...) -> None: ... +def fstat(fd: int) -> stat_result: ... +def fsync(fd: int) -> None: ... +def lseek(__fd: int, __position: int, __how: int) -> int: ... +def open(path: AnyPath, flags: int, mode: int = ..., *, dir_fd: Optional[int] = ...) -> int: ... +def pipe() -> Tuple[int, int]: ... +def read(__fd: int, __length: int) -> bytes: ... + +if sys.platform != 'win32': + # Unix only + def fchmod(fd: int, mode: int) -> None: ... + def fchown(fd: int, uid: int, gid: int) -> None: ... + if sys.platform != "darwin": + def fdatasync(fd: int) -> None: ... # Unix only, not Mac + def fpathconf(__fd: int, __name: Union[str, int]) -> int: ... + def fstatvfs(__fd: int) -> statvfs_result: ... + def ftruncate(__fd: int, __length: int) -> None: ... + def get_blocking(__fd: int) -> bool: ... + def set_blocking(__fd: int, __blocking: bool) -> None: ... + def isatty(__fd: int) -> bool: ... + def lockf(__fd: int, __command: int, __length: int) -> None: ... + def openpty() -> Tuple[int, int]: ... # some flavors of Unix + if sys.platform != "darwin": + def pipe2(flags: int) -> Tuple[int, int]: ... # some flavors of Unix + def posix_fallocate(fd: int, offset: int, length: int) -> None: ... + def posix_fadvise(fd: int, offset: int, length: int, advice: int) -> None: ... + def pread(__fd: int, __length: int, __offset: int) -> bytes: ... + def pwrite(__fd: int, __buffer: bytes, __offset: int) -> int: ... + @overload + def sendfile(__out_fd: int, __in_fd: int, offset: Optional[int], count: int) -> int: ... + @overload + def sendfile(__out_fd: int, __in_fd: int, offset: int, count: int, + headers: Sequence[bytes] = ..., trailers: Sequence[bytes] = ..., flags: int = ...) -> int: ... # FreeBSD and Mac OS X only + def readv(__fd: int, __buffers: Sequence[bytearray]) -> int: ... + def writev(__fd: int, __buffers: Sequence[bytes]) -> int: ... + +class terminal_size(Tuple[int, int]): + columns: int + lines: int +def get_terminal_size(fd: int = ...) -> terminal_size: ... + +def get_inheritable(__fd: int) -> bool: ... +def set_inheritable(__fd: int, __inheritable: bool) -> None: ... + +if sys.platform != 'win32': + # Unix only + def tcgetpgrp(__fd: int) -> int: ... + def tcsetpgrp(__fd: int, __pgid: int) -> None: ... + def ttyname(__fd: int) -> str: ... +def write(__fd: int, __data: bytes) -> int: ... +def access( + path: _FdOrAnyPath, + mode: int, + *, + dir_fd: Optional[int] = ..., + effective_ids: bool = ..., + follow_symlinks: bool = ..., +) -> bool: ... +def chdir(path: _FdOrAnyPath) -> None: ... + +if sys.platform != "win32": + def fchdir(fd: int) -> None: ... +def getcwd() -> str: ... +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 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 link( + src: AnyPath, + dst: AnyPath, + *, + 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: ... +if sys.platform != 'win32': + def mkfifo(path: AnyPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... # Unix only +def makedirs(name: AnyPath, mode: int = ..., exist_ok: bool = ...) -> None: ... +if sys.platform != "win32": + def mknod(path: AnyPath, 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 +if sys.version_info >= (3, 6): + def readlink(path: Union[AnyStr, PathLike[AnyStr]], *, dir_fd: Optional[int] = ...) -> AnyStr: ... +else: + def readlink(path: 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: ... +if sys.version_info >= (3, 7): + class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): + def __next__(self) -> DirEntry[AnyStr]: ... + def close(self) -> None: ... + @overload + def scandir(path: None = ...) -> _ScandirIterator[str]: ... + @overload + def scandir(path: int) -> _ScandirIterator[str]: ... + @overload + def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... +elif sys.version_info >= (3, 6): + class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): + def __next__(self) -> DirEntry[AnyStr]: ... + def close(self) -> None: ... + @overload + def scandir(path: None = ...) -> _ScandirIterator[str]: ... + @overload + def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... +else: + @overload + def scandir(path: None = ...) -> Iterator[DirEntry[str]]: ... + @overload + def scandir(path: AnyStr) -> Iterator[DirEntry[AnyStr]]: ... +def stat(path: _FdOrAnyPath, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> stat_result: ... +if sys.version_info < (3, 7): + @overload + def stat_float_times() -> bool: ... + @overload + def stat_float_times(__newvalue: bool) -> None: ... +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: ... +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 utime( + path: _FdOrAnyPath, + times: Optional[Union[Tuple[int, int], Tuple[float, float]]] = ..., + *, + ns: Tuple[int, int] = ..., + dir_fd: Optional[int] = ..., + follow_symlinks: bool = ..., +) -> None: ... + +_OnError = Callable[[OSError], Any] + +if sys.version_info >= (3, 6): + def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ..., + onerror: Optional[_OnError] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... +else: + def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[_OnError] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... +if sys.platform != 'win32': + if sys.version_info >= (3, 7): + @overload + def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., + onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + @overload + def fwalk(top: bytes, topdown: bool = ..., + onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[bytes, List[bytes], List[bytes], int]]: ... + elif sys.version_info >= (3, 6): + def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., + onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + else: + def fwalk(top: str = ..., topdown: bool = ..., + onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., + 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 listxattr(path: _FdOrAnyPath, *, follow_symlinks: bool = ...) -> List[str]: ... + def removexattr(path: _FdOrAnyPath, attribute: AnyPath, *, follow_symlinks: bool = ...) -> None: ... + def setxattr(path: _FdOrAnyPath, attribute: AnyPath, 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: ... + +# 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: ... + +# The docs say `args: tuple or list of strings` +# The implementation enforces tuple or list so we can't use Sequence. +if sys.version_info >= (3, 6): + # Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference + # 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, ...], List[bytes], List[str], List[PathLike[Any]], List[Union[bytes, str]], + List[Union[bytes, PathLike[Any]]], List[Union[str, PathLike[Any]]], List[Union[bytes, str, PathLike[Any]]] + ] +else: + _ExecVArgs = Union[Tuple[AnyPath, ...], List[bytes], List[str], List[Union[bytes, str]]] + +_ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] +def execv(__path: AnyPath, __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 _exit(status: int) -> NoReturn: ... +def kill(__pid: int, __signal: int) -> None: ... +if sys.platform != 'win32': + # Unix only + def fork() -> int: ... + def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def killpg(__pgid: int, __signal: int) -> None: ... + def nice(__increment: int) -> int: ... + if sys.platform != "darwin": + def plock(op: int) -> None: ... # ???op is int? + +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 +if sys.platform != "win32": + def spawnv(mode: int, file: AnyPath, args: _ExecVArgs) -> int: ... + def spawnve(mode: int, file: AnyPath, 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 system(command: AnyPath) -> 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: ... +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 wait() -> Tuple[int, int]: ... # Unix only + from posix import waitid_result + def waitid(idtype: int, ident: int, options: int) -> waitid_result: ... + def wait3(options: int) -> Tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def WCOREDUMP(__status: int) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + +if sys.platform != 'win32': + from posix import sched_param + def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix + def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix + def sched_setscheduler(pid: int, policy: int, param: sched_param) -> None: ... # some flavors of Unix + def sched_getscheduler(pid: int) -> int: ... # some flavors of Unix + def sched_setparam(pid: int, param: sched_param) -> None: ... # some flavors of Unix + def sched_getparam(pid: int) -> sched_param: ... # some flavors of Unix + def sched_rr_get_interval(pid: int) -> float: ... # some flavors of Unix + def sched_yield() -> None: ... # some flavors of Unix + def sched_setaffinity(pid: int, mask: Iterable[int]) -> None: ... # some flavors of Unix + def sched_getaffinity(pid: int) -> Set[int]: ... # some flavors of Unix + +def cpu_count() -> Optional[int]: ... +if sys.platform != 'win32': + # Unix only + def confstr(__name: Union[str, int]) -> Optional[str]: ... + def getloadavg() -> Tuple[float, float, float]: ... + def sysconf(__name: Union[str, int]) -> int: ... +if sys.version_info >= (3, 6): + if sys.platform == "linux": + def getrandom(size: int, flags: int = ...) -> bytes: ... +def urandom(__size: int) -> bytes: ... + +if sys.version_info >= (3, 7) and sys.platform != "win32": + def register_at_fork( + *, + before: Optional[Callable[..., Any]] = ..., + after_in_parent: Optional[Callable[..., Any]] = ..., + after_in_child: Optional[Callable[..., Any]] = ..., + ) -> None: ... + +if sys.version_info >= (3, 8): + if sys.platform == "win32": + class _AddedDllDirectory: + path: Optional[str] + def close(self) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, *args: Any) -> None: ... + def add_dll_directory(path: str) -> _AddedDllDirectory: ... + if sys.platform == "linux": + MFD_CLOEXEC: int + MFD_ALLOW_SEALING: int + MFD_HUGETLB: int + MFD_HUGE_SHIFT: int + MFD_HUGE_MASK: int + MFD_HUGE_64KB: int + MFD_HUGE_512KB: int + MFD_HUGE_1MB: int + MFD_HUGE_2MB: int + MFD_HUGE_8MB: int + MFD_HUGE_16MB: int + MFD_HUGE_32MB: int + MFD_HUGE_256MB: int + MFD_HUGE_512MB: int + MFD_HUGE_1GB: int + MFD_HUGE_2GB: int + MFD_HUGE_16GB: int + def memfd_create(name: str, flags: int = ...) -> int: ... diff --git a/mypy/stdlib/os/path.pyi b/mypy/stdlib/os/path.pyi new file mode 100644 index 000000000000..ef4b48331d89 --- /dev/null +++ b/mypy/stdlib/os/path.pyi @@ -0,0 +1,164 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from genericpath import exists as exists +from _typeshed import StrPath, BytesPath, AnyPath + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyStr) -> AnyStr: ... + @overload + def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(p: AnyStr) -> AnyStr: ... + def dirname(p: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(s: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of StrPath and bytes for sequences + # of BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[AnyPath]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# 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: ... + +# 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: ... + +if sys.version_info < (3, 0): + # 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: ... +elif sys.version_info >= (3, 6): + @overload + def join(a: StrPath, *paths: StrPath) -> Text: ... + @overload + def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +else: + def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... + +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: ... + +if sys.version_info >= (3, 6): + @overload + def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.version_info < (3, 7) and sys.platform == 'win32': + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/parser.pyi b/mypy/stdlib/parser.pyi new file mode 100644 index 000000000000..ca1cd4d526e7 --- /dev/null +++ b/mypy/stdlib/parser.pyi @@ -0,0 +1,22 @@ +from typing import Any, List, Sequence, Text, Tuple +from types import CodeType +from _typeshed import AnyPath + +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: AnyPath = ...) -> CodeType: ... +def isexpr(st: STType) -> bool: ... +def issuite(st: STType) -> bool: ... + +class ParserError(Exception): ... + +class STType: + def compile(self, filename: AnyPath = ...) -> 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/stdlib/pathlib.pyi b/mypy/stdlib/pathlib.pyi new file mode 100644 index 000000000000..fd7d55b8b175 --- /dev/null +++ b/mypy/stdlib/pathlib.pyi @@ -0,0 +1,158 @@ +from _typeshed import OpenBinaryMode, OpenTextMode +from typing import (Any, BinaryIO, Generator, IO, List, Optional, Sequence, + TextIO, Tuple, Type, TypeVar, Union, overload) +from types import TracebackType +import os +import sys + +_P = TypeVar('_P', bound=PurePath) + +if sys.version_info >= (3, 6): + _PurePathBase = os.PathLike[str] +else: + _PurePathBase = object + +class PurePath(_PurePathBase): + parts: Tuple[str, ...] + drive: str + root: str + anchor: str + name: str + suffix: str + suffixes: List[str] + stem: str + if sys.version_info < (3, 5): + def __init__(self, *pathsegments: str) -> None: ... + elif sys.version_info < (3, 6): + def __new__(cls: Type[_P], *args: Union[str, PurePath]) -> _P: ... + else: + def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]]) -> _P: ... + def __hash__(self) -> int: ... + def __lt__(self, other: PurePath) -> bool: ... + def __le__(self, other: PurePath) -> bool: ... + def __gt__(self, other: PurePath) -> bool: ... + def __ge__(self, other: PurePath) -> bool: ... + if sys.version_info < (3, 6): + def __truediv__(self: _P, key: Union[str, PurePath]) -> _P: ... + def __rtruediv__(self: _P, key: Union[str, PurePath]) -> _P: ... + else: + def __truediv__(self: _P, key: Union[str, os.PathLike[str]]) -> _P: ... + def __rtruediv__(self: _P, key: Union[str, os.PathLike[str]]) -> _P: ... + if sys.version_info < (3,): + def __div__(self: _P, key: Union[str, PurePath]) -> _P: ... + def __bytes__(self) -> bytes: ... + def as_posix(self) -> str: ... + def as_uri(self) -> str: ... + def is_absolute(self) -> bool: ... + def is_reserved(self) -> bool: ... + if sys.version_info >= (3, 9): + def is_relative_to(self, *other: Union[str, os.PathLike[str]]) -> bool: ... + def match(self, path_pattern: str) -> bool: ... + if sys.version_info < (3, 6): + def relative_to(self: _P, *other: Union[str, PurePath]) -> _P: ... + else: + def relative_to(self: _P, *other: Union[str, os.PathLike[str]]) -> _P: ... + def with_name(self: _P, name: str) -> _P: ... + if sys.version_info >= (3, 9): + def with_stem(self: _P, stem: str) -> _P: ... + def with_suffix(self: _P, suffix: str) -> _P: ... + if sys.version_info < (3, 6): + def joinpath(self: _P, *other: Union[str, PurePath]) -> _P: ... + else: + def joinpath(self: _P, *other: Union[str, os.PathLike[str]]) -> _P: ... + + @property + def parents(self: _P) -> Sequence[_P]: ... + @property + def parent(self: _P) -> _P: ... + +class PurePosixPath(PurePath): ... +class PureWindowsPath(PurePath): ... + +class Path(PurePath): + def __enter__(self) -> Path: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + @classmethod + def cwd(cls: Type[_P]) -> _P: ... + def stat(self) -> os.stat_result: ... + def chmod(self, mode: int) -> None: ... + def exists(self) -> bool: ... + def glob(self, pattern: str) -> Generator[Path, None, None]: ... + def group(self) -> str: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + if sys.version_info >= (3, 7): + def is_mount(self) -> bool: ... + def is_symlink(self) -> bool: ... + def is_socket(self) -> bool: ... + def is_fifo(self) -> bool: ... + def is_block_device(self) -> bool: ... + def is_char_device(self) -> bool: ... + def iterdir(self) -> Generator[Path, None, None]: ... + def lchmod(self, mode: int) -> None: ... + def lstat(self) -> os.stat_result: ... + if sys.version_info < (3, 5): + def mkdir(self, mode: int = ..., + parents: bool = ...) -> None: ... + else: + def mkdir(self, mode: int = ..., parents: bool = ..., + exist_ok: bool = ...) -> None: ... + @overload + def open(self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., + newline: Optional[str] = ...) -> TextIO: ... + @overload + def open(self, mode: OpenBinaryMode, buffering: int = ..., encoding: None = ..., errors: None = ..., + newline: None = ...) -> BinaryIO: ... + @overload + def open(self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., + newline: Optional[str] = ...) -> IO[Any]: ... + def owner(self) -> str: ... + if sys.version_info >= (3, 9): + def readlink(self: _P) -> _P: ... + if sys.version_info >= (3, 8): + def rename(self: _P, target: Union[str, PurePath]) -> _P: ... + def replace(self: _P, target: Union[str, PurePath]) -> _P: ... + else: + def rename(self, target: Union[str, PurePath]) -> None: ... + def replace(self, target: Union[str, PurePath]) -> None: ... + if sys.version_info < (3, 6): + def resolve(self: _P) -> _P: ... + else: + def resolve(self: _P, strict: bool = ...) -> _P: ... + def rglob(self, pattern: str) -> Generator[Path, None, None]: ... + def rmdir(self) -> None: ... + def symlink_to(self, target: Union[str, Path], + target_is_directory: bool = ...) -> None: ... + def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... + if sys.version_info >= (3, 8): + def unlink(self, missing_ok: bool = ...) -> None: ... + else: + def unlink(self) -> None: ... + + if sys.version_info >= (3, 5): + @classmethod + def home(cls: Type[_P]) -> _P: ... + if sys.version_info < (3, 6): + def __new__(cls: Type[_P], *args: Union[str, PurePath], + **kwargs: Any) -> _P: ... + else: + def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]], + **kwargs: Any) -> _P: ... + + def absolute(self: _P) -> _P: ... + def expanduser(self: _P) -> _P: ... + def read_bytes(self) -> bytes: ... + def read_text(self, encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> str: ... + def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... + def write_bytes(self, data: bytes) -> int: ... + def write_text(self, data: str, encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> int: ... + if sys.version_info >= (3, 8): + def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... + + +class PosixPath(Path, PurePosixPath): ... +class WindowsPath(Path, PureWindowsPath): ... diff --git a/mypy/stdlib/pdb.pyi b/mypy/stdlib/pdb.pyi new file mode 100644 index 000000000000..3913a43aec60 --- /dev/null +++ b/mypy/stdlib/pdb.pyi @@ -0,0 +1,252 @@ +from bdb import Bdb +from cmd import Cmd +from inspect import _SourceObjectType +import signal +import sys +from types import CodeType, FrameType, TracebackType +from typing import Any, Callable, ClassVar, Dict, IO, Iterable, List, Mapping, Optional, Sequence, 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]: ... + +if sys.version_info >= (3, 7): + def set_trace(*, header: Optional[str] = ...) -> None: ... +else: + 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] + + 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 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: ... + 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 + + 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: ... + +class _rstr(str): + def __repr__(self) -> _rstr: ... diff --git a/mypy/stdlib/pickle.pyi b/mypy/stdlib/pickle.pyi new file mode 100644 index 000000000000..2b0124274a8a --- /dev/null +++ b/mypy/stdlib/pickle.pyi @@ -0,0 +1,177 @@ +import sys +from typing import Any, IO, Mapping, Union, Tuple, Callable, Optional, Iterable, Iterator + +HIGHEST_PROTOCOL: int +if sys.version_info >= (3, 0): + DEFAULT_PROTOCOL: int + + +if sys.version_info >= (3, 8): + # TODO: holistic design for buffer interface (typing.Buffer?) + + class PickleBuffer: + # buffer must be a buffer-providing object + def __init__(self, buffer: Any) -> None: ... + def raw(self) -> memoryview: ... + def release(self) -> None: ... + + _BufferCallback = Optional[Callable[[PickleBuffer], Any]] + + def dump( + obj: Any, file: IO[bytes], protocol: Optional[int] = ..., *, + fix_imports: bool = ..., + buffer_callback: _BufferCallback = ... + ) -> None: ... + def dumps( + obj: Any, protocol: Optional[int] = ..., *, + fix_imports: bool = ..., + buffer_callback: _BufferCallback = ... + ) -> bytes: ... + def load( + file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., + errors: str = ..., buffers: Optional[Iterable[Any]] = ... + ) -> Any: ... + def loads( + data: bytes, *, fix_imports: bool = ..., encoding: str = ..., + errors: str = ..., buffers: Optional[Iterable[Any]] = ... + ) -> Any: ... +elif sys.version_info >= (3, 0): + 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): ... + +_reducedtype = Union[str, + Tuple[Callable[..., Any], Tuple[Any, ...]], + Tuple[Callable[..., Any], Tuple[Any, ...], Any], + Tuple[Callable[..., Any], Tuple[Any, ...], Any, + Optional[Iterator]], + Tuple[Callable[..., Any], Tuple[Any, ...], Any, + Optional[Iterator], Optional[Iterator]]] + + +class Pickler: + fast: bool + if sys.version_info >= (3, 3): + dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] + + if sys.version_info >= (3, 8): + def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *, + fix_imports: bool = ..., 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 dump(self, obj: Any) -> None: ... + def clear_memo(self) -> None: ... + def persistent_id(self, obj: Any) -> Any: ... + +class Unpickler: + if sys.version_info >= (3, 8): + def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., + encoding: str = ..., 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 load(self) -> Any: ... + def find_class(self, module: str, name: str) -> Any: ... + if sys.version_info >= (3, 0): + def persistent_load(self, pid: Any) -> 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 + +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 diff --git a/mypy/stdlib/pickletools.pyi b/mypy/stdlib/pickletools.pyi new file mode 100644 index 000000000000..c03664697bab --- /dev/null +++ b/mypy/stdlib/pickletools.pyi @@ -0,0 +1,145 @@ +# Stubs for pickletools (Python 2 and 3) +import sys +from typing import Any, Callable, IO, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union + +_Reader = Callable[[IO[bytes]], Any] + +if sys.version_info >= (3, 0): + 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 + +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 + +if sys.version_info >= (3, 3): + 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_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 + +if sys.version_info >= (3, 3): + def read_bytes1(f: IO[bytes]) -> bytes: ... + bytes1: ArgumentDescriptor + + def read_bytes4(f: IO[bytes]) -> bytes: ... + bytes4: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_bytes8(f: IO[bytes]) -> bytes: ... + bytes8: ArgumentDescriptor + +def read_unicodestringnl(f: IO[bytes]) -> Text: ... +unicodestringnl: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_unicodestring1(f: IO[bytes]) -> Text: ... + unicodestring1: ArgumentDescriptor + +def read_unicodestring4(f: IO[bytes]) -> Text: ... +unicodestring4: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_unicodestring8(f: IO[bytes]) -> Text: ... + unicodestring8: 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 +if sys.version_info >= (3, 4): + pybytes_or_str: StackObject +pystring: StackObject +if sys.version_info >= (3, 0): + pybytes: StackObject +pyunicode: StackObject +pynone: StackObject +pytuple: StackObject +pylist: StackObject +pydict: StackObject +if sys.version_info >= (3, 4): + pyset: StackObject + pyfrozenset: 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: ... +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: ... diff --git a/mypy/stdlib/pipes.pyi b/mypy/stdlib/pipes.pyi new file mode 100644 index 000000000000..658373e4cdb3 --- /dev/null +++ b/mypy/stdlib/pipes.pyi @@ -0,0 +1,19 @@ +# Stubs for pipes + +# Based on http://docs.python.org/3.5/library/pipes.html + +import os + +class Template: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, rw: str) -> os._wrap_close: ... + def copy(self, file: str, rw: str) -> os._wrap_close: ... + +# Not documented, but widely used. +# Documented as shlex.quote since 3.3. +def quote(s: str) -> str: ... diff --git a/mypy/stdlib/pkgutil.pyi b/mypy/stdlib/pkgutil.pyi new file mode 100644 index 000000000000..138a0f8b52d7 --- /dev/null +++ b/mypy/stdlib/pkgutil.pyi @@ -0,0 +1,38 @@ +# Stubs for pkgutil + +from typing import Any, Callable, Generator, IO, Iterable, Optional, Tuple, NamedTuple +import sys + +if sys.version_info >= (3,): + from importlib.abc import Loader +else: + Loader = Any + +if sys.version_info >= (3, 6): + class ModuleInfo(NamedTuple): + module_finder: Any + name: str + ispkg: bool + _YMFNI = Generator[ModuleInfo, None, None] +else: + _YMFNI = Generator[Tuple[Any, str, bool], None, None] + + +def extend_path(path: Iterable[str], name: str) -> Iterable[str]: ... + +class ImpImporter: + def __init__(self, dirname: 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) -> Any: ... # TODO precise type +def get_loader(module_or_name: str) -> Loader: ... +def iter_importers(fullname: str = ...) -> Generator[Any, None, None]: ... # TODO precise type +def iter_modules(path: Optional[Iterable[str]] = ..., + prefix: str = ...) -> _YMFNI: ... # TODO precise type +def walk_packages(path: Optional[Iterable[str]] = ..., prefix: str = ..., + onerror: Optional[Callable[[str], None]] = ...) -> _YMFNI: ... +def get_data(package: str, resource: str) -> Optional[bytes]: ... diff --git a/mypy/stdlib/platform.pyi b/mypy/stdlib/platform.pyi new file mode 100644 index 000000000000..c854930cd800 --- /dev/null +++ b/mypy/stdlib/platform.pyi @@ -0,0 +1,47 @@ +# Stubs for platform (Python 3.5) + +from os import devnull as DEV_NULL +from typing import Optional, Tuple, NamedTuple +import sys + +if sys.version_info >= (3, 8): + def libc_ver(executable: Optional[str] = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> Tuple[str, str]: ... +else: + def libc_ver(executable: str = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> Tuple[str, str]: ... +if sys.version_info < (3, 8): + def linux_distribution(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ..., full_distribution_name: bool = ...) -> Tuple[str, str, str]: ... + def dist(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ...) -> Tuple[str, str, str]: ... +def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... +if sys.version_info >= (3, 8): + def win32_edition() -> str: ... + def win32_is_iot() -> bool: ... +def mac_ver(release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ...) -> Tuple[str, Tuple[str, str, str], str]: ... +def java_ver(release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ...) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... +def system_alias(system: str, release: str, version: str) -> Tuple[str, str, str]: ... +def architecture(executable: str = ..., bits: str = ..., linkage: str = ...) -> Tuple[str, str]: ... + +class uname_result(NamedTuple): + system: str + node: str + release: str + version: str + machine: str + processor: str + +def uname() -> uname_result: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... + +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> Tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> Tuple[str, str]: ... +def python_compiler() -> str: ... + +def platform(aliased: bool = ..., terse: bool = ...) -> str: ... diff --git a/mypy/stdlib/plistlib.pyi b/mypy/stdlib/plistlib.pyi new file mode 100644 index 000000000000..e3f542d26ea2 --- /dev/null +++ b/mypy/stdlib/plistlib.pyi @@ -0,0 +1,84 @@ +from typing import ( + Any, IO, Mapping, MutableMapping, Optional, overload, Union, + Type, TypeVar, Text +) +from typing import Dict as DictT +import sys +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 + +mm = MutableMapping[str, Any] +_D = TypeVar('_D', bound=mm) +_Path = Union[str, Text] + +if sys.version_info >= (3, 9): + @overload + def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ...) -> DictT[str, Any]: ... + @overload + def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., dict_type: Type[_D]) -> _D: ... + @overload + def loads(value: bytes, *, fmt: Optional[PlistFormat] = ...) -> DictT[str, Any]: ... + @overload + def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., dict_type: Type[_D]) -> _D: ... +elif sys.version_info >= (3, 4): + @overload + def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ...) -> DictT[str, Any]: ... + @overload + def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., dict_type: Type[_D]) -> _D: ... + @overload + def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ...) -> DictT[str, Any]: ... + @overload + def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., dict_type: Type[_D]) -> _D: ... + +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: ... + +if sys.version_info < (3, 9): + def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> DictT[str, Any]: ... + def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ... + def readPlistFromBytes(data: bytes) -> DictT[str, Any]: ... + def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... +if sys.version_info < (3,): + def readPlistFromResource(path: _Path, restype: str = ..., + resid: int = ...) -> DictT[str, Any]: ... + def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, + restype: str = ..., + resid: int = ...) -> None: ... + def readPlistFromString(data: str) -> DictT[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: ... + def __setattr__(self, attr: str, value: Any) -> None: ... + def __delattr__(self, attr: str) -> None: ... + +if sys.version_info < (3, 9): + class Data: + data: bytes + def __init__(self, data: bytes) -> None: ... + +if sys.version_info >= (3, 8): + class UID: + data: int + def __init__(self, data: int) -> None: ... + def __index__(self) -> int: ... + def __reduce__(self) -> Any: ... + def __hash__(self) -> int: ... + +class InvalidFileException(ValueError): + def __init__(self, message: str = ...) -> None: ... diff --git a/mypy/stdlib/poplib.pyi b/mypy/stdlib/poplib.pyi new file mode 100644 index 000000000000..d2b7dab6cf5c --- /dev/null +++ b/mypy/stdlib/poplib.pyi @@ -0,0 +1,77 @@ +# Stubs for poplib (Python 2 and 3) + +import socket +import ssl +import sys +from typing import ( + Any, BinaryIO, Dict, List, NoReturn, Optional, overload, Pattern, Text, + Tuple, +) + +_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: + if sys.version_info >= (3, 0): + encoding: Text + + 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] + + if sys.version_info < (3, 0): + def apop(self, user: Text, secret: Text) -> bytes: ... + else: + def apop(self, user: Text, password: Text) -> 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: ... + + +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: ... diff --git a/mypy/stdlib/posix.pyi b/mypy/stdlib/posix.pyi new file mode 100644 index 000000000000..c6092ead447c --- /dev/null +++ b/mypy/stdlib/posix.pyi @@ -0,0 +1,126 @@ +# Stubs for posix + +# NOTE: These are incomplete! + +import sys +from typing import List, NamedTuple, Optional, overload + +from os import stat_result as stat_result + +if sys.version_info >= (3, 6): + from builtins import _PathLike # See comment in builtins + +class uname_result(NamedTuple): + sysname: str + nodename: str + release: str + version: str + machine: str + +class times_result(NamedTuple): + user: float + system: float + children_user: float + children_system: float + elapsed: float + +class waitid_result(NamedTuple): + si_pid: int + si_uid: int + si_signo: int + si_status: int + si_code: int + +class sched_param(NamedTuple): + sched_priority: int + +EX_CANTCREAT: int +EX_CONFIG: int +EX_DATAERR: int +EX_IOERR: int +EX_NOHOST: int +EX_NOINPUT: int +EX_NOPERM: int +EX_NOTFOUND: int +EX_NOUSER: int +EX_OK: int +EX_OSERR: int +EX_OSFILE: int +EX_PROTOCOL: int +EX_SOFTWARE: int +EX_TEMPFAIL: int +EX_UNAVAILABLE: int +EX_USAGE: int + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +if sys.version_info >= (3, 6): + GRND_NONBLOCK: int + GRND_RANDOM: int +NGROUPS_MAX: int + +O_APPEND: int +O_ACCMODE: int +O_ASYNC: int +O_CREAT: int +O_DIRECT: int +O_DIRECTORY: int +O_DSYNC: int +O_EXCL: int +O_LARGEFILE: int +O_NDELAY: int +O_NOATIME: int +O_NOCTTY: int +O_NOFOLLOW: int +O_NONBLOCK: int +O_RDONLY: int +O_RDWR: int +O_RSYNC: int +O_SYNC: int +O_TRUNC: int +O_WRONLY: int + +ST_APPEND: int +ST_MANDLOCK: int +ST_NOATIME: int +ST_NODEV: int +ST_NODIRATIME: int +ST_NOEXEC: int +ST_NOSUID: int +ST_RDONLY: int +ST_RELATIME: int +ST_SYNCHRONOUS: int +ST_WRITE: int + +TMP_MAX: int +WCONTINUED: int +WCOREDUMP: int +WEXITSTATUS: int +WIFCONTINUED: int +WIFEXITED: int +WIFSIGNALED: int +WIFSTOPPED: int +WNOHANG: int +WSTOPSIG: int +WTERMSIG: int +WUNTRACED: int + +if sys.version_info >= (3, 6): + @overload + def listdir(path: Optional[str] = ...) -> List[str]: ... + @overload + def listdir(path: bytes) -> List[bytes]: ... + @overload + def listdir(path: int) -> List[str]: ... + @overload + def listdir(path: _PathLike[str]) -> List[str]: ... +else: + @overload + def listdir(path: Optional[str] = ...) -> List[str]: ... + @overload + def listdir(path: bytes) -> List[bytes]: ... + @overload + def listdir(path: int) -> List[str]: ... diff --git a/mypy/stdlib/posixpath.pyi b/mypy/stdlib/posixpath.pyi new file mode 100644 index 000000000000..ef4b48331d89 --- /dev/null +++ b/mypy/stdlib/posixpath.pyi @@ -0,0 +1,164 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from genericpath import exists as exists +from _typeshed import StrPath, BytesPath, AnyPath + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyStr) -> AnyStr: ... + @overload + def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(p: AnyStr) -> AnyStr: ... + def dirname(p: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(s: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of StrPath and bytes for sequences + # of BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[AnyPath]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# 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: ... + +# 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: ... + +if sys.version_info < (3, 0): + # 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: ... +elif sys.version_info >= (3, 6): + @overload + def join(a: StrPath, *paths: StrPath) -> Text: ... + @overload + def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +else: + def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... + +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: ... + +if sys.version_info >= (3, 6): + @overload + def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.version_info < (3, 7) and sys.platform == 'win32': + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/pprint.pyi b/mypy/stdlib/pprint.pyi new file mode 100644 index 000000000000..6b14e7d8ac8b --- /dev/null +++ b/mypy/stdlib/pprint.pyi @@ -0,0 +1,80 @@ +# Stubs for pprint + +# Based on http://docs.python.org/2/library/pprint.html +# Based on http://docs.python.org/3/library/pprint.html + +import sys +from typing import Any, Dict, Tuple, IO, Optional + +if sys.version_info >= (3, 8): + def pformat( + object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ..., *, compact: bool = ..., sort_dicts: bool = ... + ) -> str: ... + +elif sys.version_info >= (3, 4): + 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, 8): + def pp( + object: object, + stream: Optional[IO[str]] = ..., + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + *, + compact: bool = ..., + sort_dicts: bool = ..., + ) -> None: ... + +if sys.version_info >= (3, 8): + def pprint( + object: object, + stream: Optional[IO[str]] = ..., + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + *, + compact: bool = ..., + sort_dicts: bool = ..., + ) -> None: ... + +elif sys.version_info >= (3, 4): + def pprint(object: object, stream: Optional[IO[str]] = ..., indent: int = ..., width: int = ..., + depth: Optional[int] = ..., *, 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: ... + +class PrettyPrinter: + if sys.version_info >= (3, 8): + def __init__( + self, + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + stream: Optional[IO[str]] = ..., + *, + compact: bool = ..., + sort_dicts: bool = ..., + ) -> None: ... + elif sys.version_info >= (3, 4): + def __init__(self, indent: int = ..., width: int = ..., depth: Optional[int] = ..., + stream: Optional[IO[str]] = ..., *, 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: ... + 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/stdlib/profile.pyi b/mypy/stdlib/profile.pyi new file mode 100644 index 000000000000..d32c8b67abdb --- /dev/null +++ b/mypy/stdlib/profile.pyi @@ -0,0 +1,24 @@ +from _typeshed import AnyPath +from typing import Any, Callable, Dict, Optional, 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') + +class Profile: + bias: int + + 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: AnyPath) -> 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/stdlib/pstats.pyi b/mypy/stdlib/pstats.pyi new file mode 100644 index 000000000000..53c8e6755fca --- /dev/null +++ b/mypy/stdlib/pstats.pyi @@ -0,0 +1,35 @@ +from profile import Profile +from cProfile import Profile as _cProfile +from _typeshed import AnyPath +from typing import Any, Dict, IO, 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: AnyPath) -> 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/stdlib/pty.pyi b/mypy/stdlib/pty.pyi new file mode 100644 index 000000000000..3931bb0a91e2 --- /dev/null +++ b/mypy/stdlib/pty.pyi @@ -0,0 +1,20 @@ +# Stubs for pty (Python 2 and 3) +import sys +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]: ... +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: ... diff --git a/mypy/stdlib/pwd.pyi b/mypy/stdlib/pwd.pyi new file mode 100644 index 000000000000..ea5845200613 --- /dev/null +++ b/mypy/stdlib/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/stdlib/py_compile.pyi b/mypy/stdlib/py_compile.pyi new file mode 100644 index 000000000000..7613fd511320 --- /dev/null +++ b/mypy/stdlib/py_compile.pyi @@ -0,0 +1,32 @@ +# Stubs for py_compile (Python 2 and 3) +import enum +import sys + +from typing import Optional, List, Text, AnyStr, Union, Type + +_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: ... + +if sys.version_info >= (3, 7): + class PycInvalidationMode(enum.Enum): + TIMESTAMP: int = ... + CHECKED_HASH: int = ... + UNCHECKED_HASH: int = ... + def _get_default_invalidation_mode() -> PycInvalidationMode: ... + +if sys.version_info >= (3, 8): + def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., quiet: int = ...) -> Optional[AnyStr]: ... +elif sys.version_info >= (3, 7): + def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ...) -> Optional[AnyStr]: ... +elif sys.version_info >= (3, 2): + 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: ... diff --git a/mypy/stdlib/pyclbr.pyi b/mypy/stdlib/pyclbr.pyi new file mode 100644 index 000000000000..0e2936058fc2 --- /dev/null +++ b/mypy/stdlib/pyclbr.pyi @@ -0,0 +1,38 @@ +import sys +from typing import List, Union, Sequence, Optional, Dict + + +class Class: + module: str + name: str + super: Optional[List[Union[Class, str]]] + methods: Dict[str, int] + file: int + lineno: int + + if sys.version_info >= (3, 7): + def __init__(self, module: str, name: str, super: Optional[List[Union[Class, str]]], file: str, lineno: int, parent: Optional[Class] = ...) -> None: ... + else: + 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 + + if sys.version_info >= (3, 7): + def __init__(self, module: str, name: str, file: str, lineno: int, parent: Optional[Function] = ...) -> None: ... + else: + 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/stdlib/pydoc.pyi b/mypy/stdlib/pydoc.pyi new file mode 100644 index 000000000000..c3254dfefab9 --- /dev/null +++ b/mypy/stdlib/pydoc.pyi @@ -0,0 +1,185 @@ +import sys +from typing import Any, AnyStr, Callable, Container, Dict, IO, List, Mapping, MutableMapping, NoReturn, Optional, Text, Tuple, Type, Union +from types import FunctionType, MethodType, ModuleType, TracebackType +from _typeshed import SupportsWrite +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]] + +__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) -> 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) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., *ignored) -> 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) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> 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) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docroutine(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., parent: Optional[str] = ..., maxlen: Optional[int] = ..., doc: Optional[Any] = ..., *ignored) -> 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: ... + +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/stdlib/pyexpat/__init__.pyi b/mypy/stdlib/pyexpat/__init__.pyi new file mode 100644 index 000000000000..edefe954b30f --- /dev/null +++ b/mypy/stdlib/pyexpat/__init__.pyi @@ -0,0 +1,74 @@ +from typing import List, Tuple, Optional, Callable, Any, Union, Dict, Text +from _typeshed import SupportsRead + +import pyexpat.errors as errors +import pyexpat.model as model + +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] + +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/stdlib/pyexpat/errors.pyi b/mypy/stdlib/pyexpat/errors.pyi new file mode 100644 index 000000000000..6cde43e3b61f --- /dev/null +++ b/mypy/stdlib/pyexpat/errors.pyi @@ -0,0 +1,44 @@ +import sys +from typing import Dict + +if sys.version_info >= (3, 2): + codes: Dict[str, int] + messages: Dict[int, str] + +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/stdlib/pyexpat/model.pyi b/mypy/stdlib/pyexpat/model.pyi new file mode 100644 index 000000000000..f357cf6511a2 --- /dev/null +++ b/mypy/stdlib/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/stdlib/python2/BaseHTTPServer.pyi b/mypy/stdlib/python2/BaseHTTPServer.pyi new file mode 100644 index 000000000000..ad5f24e21ad1 --- /dev/null +++ b/mypy/stdlib/python2/BaseHTTPServer.pyi @@ -0,0 +1,47 @@ +# Stubs for BaseHTTPServer (Python 2.7) + +from typing import Any, BinaryIO, Callable, Mapping, Optional, Tuple, Union +import SocketServer +import mimetools + +class HTTPServer(SocketServer.TCPServer): + server_name: str + server_port: int + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + +class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): + client_address: Tuple[str, int] + server: SocketServer.BaseServer + close_connection: bool + command: str + path: str + request_version: str + headers: mimetools.Message + rfile: BinaryIO + wfile: BinaryIO + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, Tuple[str, str]] + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: SocketServer.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def send_error(self, code: int, message: Optional[str] = ...) -> None: ... + def send_response(self, code: int, + message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., + size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... diff --git a/mypy/stdlib/python2/CGIHTTPServer.pyi b/mypy/stdlib/python2/CGIHTTPServer.pyi new file mode 100644 index 000000000000..4eae666d86d0 --- /dev/null +++ b/mypy/stdlib/python2/CGIHTTPServer.pyi @@ -0,0 +1,8 @@ +# Stubs for CGIHTTPServer (Python 2.7) + +from typing import List +import SimpleHTTPServer + +class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): + cgi_directories: List[str] + def do_POST(self) -> None: ... diff --git a/mypy/stdlib/python2/ConfigParser.pyi b/mypy/stdlib/python2/ConfigParser.pyi new file mode 100644 index 000000000000..d727ded105b8 --- /dev/null +++ b/mypy/stdlib/python2/ConfigParser.pyi @@ -0,0 +1,97 @@ +from typing import Any, IO, Sequence, Tuple, Union, List, Dict, Optional +from _typeshed import SupportsReadline + +DEFAULTSECT: str +MAX_INTERPOLATION_DEPTH: int + +class Error(Exception): + message: Any + def __init__(self, msg: str = ...) -> None: ... + def _get_message(self) -> None: ... + def _set_message(self, value: str) -> None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + +class NoSectionError(Error): + section: str + def __init__(self, section: str) -> None: ... + +class DuplicateSectionError(Error): + section: str + def __init__(self, section: str) -> None: ... + +class NoOptionError(Error): + section: str + option: str + def __init__(self, option: str, section: str) -> None: ... + +class InterpolationError(Error): + section: str + option: str + msg: str + def __init__(self, option: str, section: str, msg: str) -> None: ... + +class InterpolationMissingOptionError(InterpolationError): + reference: str + def __init__(self, option: str, section: str, rawval: str, reference: str) -> None: ... + +class InterpolationSyntaxError(InterpolationError): ... + +class InterpolationDepthError(InterpolationError): + def __init__(self, option: str, section: str, rawval: str) -> None: ... + +class ParsingError(Error): + filename: str + errors: List[Tuple[Any, Any]] + def __init__(self, filename: str) -> None: ... + def append(self, lineno: Any, line: Any) -> None: ... + +class MissingSectionHeaderError(ParsingError): + lineno: Any + line: Any + def __init__(self, filename: str, lineno: Any, line: Any) -> None: ... + +class RawConfigParser: + _dict: Any + _sections: Dict[Any, Any] + _defaults: Dict[Any, Any] + _optcre: Any + SECTCRE: Any + OPTCRE: Any + OPTCRE_NV: Any + def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... + def defaults(self) -> Dict[Any, Any]: ... + def sections(self) -> List[str]: ... + def add_section(self, section: str) -> None: ... + def has_section(self, section: str) -> bool: ... + def options(self, section: str) -> List[str]: ... + def read(self, filenames: Union[str, Sequence[str]]) -> List[str]: ... + def readfp(self, fp: SupportsReadline[str], filename: str = ...) -> None: ... + def get(self, section: str, option: str) -> str: ... + def items(self, section: str) -> List[Tuple[Any, Any]]: ... + def _get(self, section: str, conv: type, option: str) -> Any: ... + def getint(self, section: str, option: str) -> int: ... + def getfloat(self, section: str, option: str) -> float: ... + _boolean_states: Dict[str, bool] + def getboolean(self, section: str, option: str) -> bool: ... + def optionxform(self, optionstr: str) -> str: ... + def has_option(self, section: str, option: str) -> bool: ... + def set(self, section: str, option: str, value: Any = ...) -> None: ... + def write(self, fp: IO[str]) -> None: ... + def remove_option(self, section: str, option: Any) -> bool: ... + def remove_section(self, section: str) -> bool: ... + def _read(self, fp: IO[str], fpname: str) -> None: ... + +class ConfigParser(RawConfigParser): + _KEYCRE: Any + def get(self, section: str, option: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> Any: ... + def items(self, section: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> List[Tuple[str, Any]]: ... + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolation_replace(self, match: Any) -> str: ... + +class SafeConfigParser(ConfigParser): + _interpvar_re: Any + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolate_some( + self, option: str, accum: List[Any], rest: str, section: str, map: Dict[Any, Any], depth: int, + ) -> None: ... diff --git a/mypy/stdlib/python2/Cookie.pyi b/mypy/stdlib/python2/Cookie.pyi new file mode 100644 index 000000000000..91dd93221c73 --- /dev/null +++ b/mypy/stdlib/python2/Cookie.pyi @@ -0,0 +1,40 @@ +from typing import Any, Dict, Optional + +class CookieError(Exception): ... + +class Morsel(Dict[Any, Any]): + key: Any + def __init__(self): ... + def __setitem__(self, K, V): ... + def isReservedKey(self, K): ... + value: Any + coded_value: Any + def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ... + def output(self, attrs: Optional[Any] = ..., header=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def OutputString(self, attrs: Optional[Any] = ...): ... + +class BaseCookie(Dict[Any, Any]): + def value_decode(self, val): ... + def value_encode(self, val): ... + def __init__(self, input: Optional[Any] = ...): ... + def __setitem__(self, key, value): ... + def output(self, attrs: Optional[Any] = ..., header=..., sep=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def load(self, rawdata): ... + +class SimpleCookie(BaseCookie): + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SerialCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SmartCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +Cookie: Any diff --git a/mypy/stdlib/python2/HTMLParser.pyi b/mypy/stdlib/python2/HTMLParser.pyi new file mode 100644 index 000000000000..0f6c7e399a9c --- /dev/null +++ b/mypy/stdlib/python2/HTMLParser.pyi @@ -0,0 +1,31 @@ +from typing import List, Tuple, AnyStr +from markupbase import ParserBase + +class HTMLParser(ParserBase): + def __init__(self) -> None: ... + def feed(self, feed: AnyStr) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + + def get_starttag_text(self) -> AnyStr: ... + def set_cdata_mode(self, AnyStr) -> None: ... + def clear_cdata_mode(self) -> None: ... + + def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_endtag(self, tag: AnyStr): ... + def handle_charref(self, name: AnyStr): ... + def handle_entityref(self, name: AnyStr): ... + def handle_data(self, data: AnyStr): ... + def handle_comment(self, data: AnyStr): ... + def handle_decl(self, decl: AnyStr): ... + def handle_pi(self, data: AnyStr): ... + + def unknown_decl(self, data: AnyStr): ... + + def unescape(self, s: AnyStr) -> AnyStr: ... + +class HTMLParseError(Exception): + msg: str + lineno: int + offset: int diff --git a/mypy/stdlib/python2/Queue.pyi b/mypy/stdlib/python2/Queue.pyi new file mode 100644 index 000000000000..76e3dcb5024f --- /dev/null +++ b/mypy/stdlib/python2/Queue.pyi @@ -0,0 +1,31 @@ +# Stubs for Queue (Python 2) + +from collections import deque +from typing import Any, Deque, TypeVar, Generic, Optional + +_T = TypeVar('_T') + +class Empty(Exception): ... +class Full(Exception): ... + +class Queue(Generic[_T]): + maxsize: Any + mutex: Any + not_empty: Any + not_full: Any + all_tasks_done: Any + unfinished_tasks: Any + queue: Deque[Any] # undocumented + def __init__(self, maxsize: int = ...) -> None: ... + def task_done(self) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + +class PriorityQueue(Queue[_T]): ... +class LifoQueue(Queue[_T]): ... diff --git a/mypy/stdlib/python2/SimpleHTTPServer.pyi b/mypy/stdlib/python2/SimpleHTTPServer.pyi new file mode 100644 index 000000000000..4a36cc5bdfe4 --- /dev/null +++ b/mypy/stdlib/python2/SimpleHTTPServer.pyi @@ -0,0 +1,16 @@ +# Stubs for SimpleHTTPServer (Python 2) + +from typing import Any, AnyStr, IO, Mapping, Optional, Union +import BaseHTTPServer +from StringIO import StringIO + +class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): + server_version: str + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + def send_head(self) -> Optional[IO[str]]: ... + def list_directory(self, path: Union[str, unicode]) -> Optional[StringIO[Any]]: ... + def translate_path(self, path: AnyStr) -> AnyStr: ... + def copyfile(self, source: IO[AnyStr], outputfile: IO[AnyStr]): ... + def guess_type(self, path: Union[str, unicode]) -> str: ... + extensions_map: Mapping[str, str] diff --git a/mypy/stdlib/python2/SocketServer.pyi b/mypy/stdlib/python2/SocketServer.pyi new file mode 100644 index 000000000000..3f57efbe9766 --- /dev/null +++ b/mypy/stdlib/python2/SocketServer.pyi @@ -0,0 +1,135 @@ +# NB: SocketServer.pyi and socketserver.pyi must remain consistent! +# Stubs for socketserver + +from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, Text, Union +from socket import SocketType +import sys +import types + +class BaseServer: + address_family: int + RequestHandlerClass: Callable[..., BaseRequestHandler] + server_address: Tuple[str, int] + socket: SocketType + allow_reuse_address: bool + request_queue_size: int + socket_type: int + timeout: Optional[float] + def __init__(self, server_address: Any, + RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... + def fileno(self) -> int: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = ...) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> None: ... + def handle_error(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def server_activate(self) -> None: ... + def server_bind(self) -> None: ... + def verify_request(self, request: bytes, + client_address: Tuple[str, int]) -> bool: ... + if sys.version_info >= (3, 6): + def __enter__(self) -> BaseServer: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> None: ... + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... + +class TCPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +class UDPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != 'win32': + class UnixStreamServer(BaseServer): + def __init__(self, server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + + class UnixDatagramServer(BaseServer): + def __init__(self, server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != "win32": + class ForkingMixIn: + timeout: Optional[float] # undocumented + active_children: Optional[List[int]] # undocumented + max_children: int # undocumented + if sys.version_info >= (3, 7): + block_on_close: bool + if sys.version_info >= (3, 6): + def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented + else: + def collect_children(self) -> None: ... # undocumented + def handle_timeout(self) -> None: ... # undocumented + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... # undocumented + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + if sys.version_info >= (3, 6): + def server_close(self) -> None: ... + +class ThreadingMixIn: + daemon_threads: bool + if sys.version_info >= (3, 7): + block_on_close: bool + def process_request_thread(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... # undocumented + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + if sys.version_info >= (3, 6): + def server_close(self) -> None: ... + +if sys.platform != "win32": + class ForkingTCPServer(ForkingMixIn, TCPServer): ... + class ForkingUDPServer(ForkingMixIn, UDPServer): ... +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... +if sys.platform != 'win32': + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + + +class BaseRequestHandler: + # Those are technically of types, respectively: + # * Union[SocketType, Tuple[bytes, SocketType]] + # * Union[Tuple[str, int], str] + # But there are some concerns that having unions here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + request: Any + client_address: Any + server: BaseServer + + def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rbufsize: ClassVar[int] # Undocumented + wbufsize: ClassVar[int] # Undocumented + timeout: ClassVar[Optional[float]] # Undocumented + disable_nagle_algorithm: ClassVar[bool] # Undocumented + connection: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO + +class DatagramRequestHandler(BaseRequestHandler): + packet: SocketType # Undocumented + socket: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO diff --git a/mypy/stdlib/python2/StringIO.pyi b/mypy/stdlib/python2/StringIO.pyi new file mode 100644 index 000000000000..de17f6abadfa --- /dev/null +++ b/mypy/stdlib/python2/StringIO.pyi @@ -0,0 +1,30 @@ +# Stubs for StringIO (Python 2) + +from typing import Any, IO, AnyStr, Iterator, Iterable, Generic, List, Optional + +class StringIO(IO[AnyStr], Generic[AnyStr]): + closed: bool + softspace: int + len: int + name: str + def __init__(self, buf: AnyStr = ...) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def next(self) -> AnyStr: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, mode: int = ...) -> int: ... + def tell(self) -> int: ... + def read(self, n: int = ...) -> AnyStr: ... + def readline(self, length: int = ...) -> AnyStr: ... + def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + def flush(self) -> None: ... + def getvalue(self) -> AnyStr: ... + def __enter__(self) -> Any: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> Any: ... + def fileno(self) -> int: ... + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + def writable(self) -> bool: ... diff --git a/mypy/stdlib/python2/UserDict.pyi b/mypy/stdlib/python2/UserDict.pyi new file mode 100644 index 000000000000..1d850cfc2750 --- /dev/null +++ b/mypy/stdlib/python2/UserDict.pyi @@ -0,0 +1,44 @@ +from typing import (Any, Container, Dict, Generic, Iterable, Iterator, List, + Mapping, Optional, Sized, Tuple, TypeVar, Union, overload) + +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_T = TypeVar('_T') + +class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): + data: Dict[_KT, _VT] + + def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... + + # TODO: __iter__ is not available for UserDict + +class IterableUserDict(UserDict[_KT, _VT], Generic[_KT, _VT]): + ... + +class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): + def has_key(self, key: _KT) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_KT]: ... + + # From typing.Mapping[_KT, _VT] + # (can't inherit because of keys()) + @overload + def get(self, k: _KT) -> Optional[_VT]: ... + @overload + def get(self, k: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ... + 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 __contains__(self, o: Any) -> bool: ... + + # From typing.MutableMapping[_KT, _VT] + def clear(self) -> None: ... + def pop(self, k: _KT, default: _VT = ...) -> _VT: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/mypy/stdlib/python2/UserList.pyi b/mypy/stdlib/python2/UserList.pyi new file mode 100644 index 000000000000..3c71e8292e3f --- /dev/null +++ b/mypy/stdlib/python2/UserList.pyi @@ -0,0 +1,19 @@ +from typing import Iterable, MutableSequence, TypeVar, Union, overload, List + +_T = TypeVar("_T") +_S = TypeVar("_S") + +class UserList(MutableSequence[_T]): + data: List[_T] + def insert(self, index: int, object: _T) -> None: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self: _S, s: slice) -> _S: ... + def sort(self) -> None: ... diff --git a/mypy/stdlib/python2/UserString.pyi b/mypy/stdlib/python2/UserString.pyi new file mode 100644 index 000000000000..704a93bc0962 --- /dev/null +++ b/mypy/stdlib/python2/UserString.pyi @@ -0,0 +1,75 @@ +import collections +from typing import Any, Iterable, List, MutableSequence, Sequence, Optional, overload, Text, TypeVar, Tuple, Union + +_UST = TypeVar("_UST", bound=UserString) +_MST = TypeVar("_MST", bound=MutableString) + +class UserString(Sequence[UserString]): + data: unicode + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __long__(self) -> long: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self: _UST, i: int) -> _UST: ... + @overload + def __getitem__(self: _UST, s: slice) -> _UST: ... + def __add__(self: _UST, other: Any) -> _UST: ... + def __radd__(self: _UST, other: Any) -> _UST: ... + def __mul__(self: _UST, other: int) -> _UST: ... + def __rmul__(self: _UST, other: int) -> _UST: ... + def __mod__(self: _UST, args: Any) -> _UST: ... + def capitalize(self: _UST) -> _UST: ... + def center(self: _UST, width: int, *args: Any) -> _UST: ... + def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... + def decode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def encode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def endswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... + def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, seq: Iterable[Text]) -> Text: ... + def ljust(self: _UST, width: int, *args: Any) -> _UST: ... + def lower(self: _UST) -> _UST: ... + def lstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... + def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rjust(self: _UST, width: int, *args: Any) -> _UST: ... + def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def rstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def split(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def rsplit(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def splitlines(self, keepends: int = ...) -> List[Text]: ... + def startswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def strip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def swapcase(self: _UST) -> _UST: ... + def title(self: _UST) -> _UST: ... + def translate(self: _UST, *args: Any) -> _UST: ... + def upper(self: _UST) -> _UST: ... + def zfill(self: _UST, width: int) -> _UST: ... + +class MutableString(UserString, MutableSequence[MutableString]): + @overload + def __getitem__(self: _MST, i: int) -> _MST: ... + @overload + def __getitem__(self: _MST, s: slice) -> _MST: ... + def __setitem__(self, index: Union[int, slice], sub: Any) -> None: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def immutable(self) -> UserString: ... + def __iadd__(self: _MST, other: Any) -> _MST: ... + def __imul__(self, n: int) -> _MST: ... + def insert(self, index: int, value: Any) -> None: ... diff --git a/mypy/stdlib/python2/__builtin__.pyi b/mypy/stdlib/python2/__builtin__.pyi new file mode 100644 index 000000000000..c644038d1446 --- /dev/null +++ b/mypy/stdlib/python2/__builtin__.pyi @@ -0,0 +1,1842 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from typing import ( + TypeVar, Iterator, Iterable, NoReturn, overload, Container, + Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, + Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, + SupportsComplex, IO, BinaryIO, Union, + ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, + Protocol, +) +from abc import ABCMeta +from ast import mod, AST +from io import ( + TextIOWrapper, FileIO, BufferedRandom, BufferedReader, BufferedWriter +) +from types import TracebackType, CodeType +from _typeshed import ( + AnyPath, OpenBinaryMode, OpenTextMode, + OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenBinaryModeReading, + SupportsWrite, ReadableBuffer, +) +from typing_extensions import Literal +import sys + +if sys.version_info >= (3,): + from typing import SupportsBytes, SupportsRound + +if sys.version_info >= (3, 9): + from types import GenericAlias + +class _SupportsIndex(Protocol): + def __index__(self) -> int: ... + +class _SupportsLessThan(Protocol): + def __lt__(self, other: Any) -> bool: ... + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_S = TypeVar('_S') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_TT = TypeVar('_TT', bound='type') +_LT = TypeVar('_LT', bound=_SupportsLessThan) + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + if sys.version_info >= (3, 6): + __annotations__: Dict[str, Any] + + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... + def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... + if sys.version_info >= (3,): + def __dir__(self) -> Iterable[str]: ... + if sys.version_info >= (3, 6): + def __init_subclass__(cls) -> None: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + if sys.version_info >= (3,): + __qualname__: str + __text_signature__: Optional[str] + __weakrefoffset__: int + + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + if sys.version_info >= (3,): + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class super(object): + if sys.version_info >= (3,): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... + else: + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __init__(self, x: Union[Text, bytes, SupportsInt, _SupportsIndex] = ...) -> None: ... + @overload + def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... + + if sys.version_info >= (3, 8): + def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + + def bit_length(self) -> int: ... + if sys.version_info >= (3,): + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes(cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, + signed: bool = ...) -> int: ... # TODO buffer object argument + + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3,): + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __init__(self, x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> None: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, __s: str) -> float: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__(self, x: float, mod: None = ...) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3,): + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __init__(self, real: float = ..., imag: float = ...) -> None: ... + @overload + def __init__(self, real: Union[str, SupportsComplex, _SupportsIndex]) -> None: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + + def conjugate(self) -> complex: ... + + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex, mod: None = ...) -> complex: ... + if sys.version_info < (3,): + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex, mod: None = ...) -> complex: ... + if sys.version_info < (3,): + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +if sys.version_info >= (3,): + _str_base = object +else: + class basestring(metaclass=ABCMeta): ... + + class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + + def __len__(self) -> int: ... + # The argument type is incompatible with Sequence + def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + + _str_base = basestring + +class _FormatMapMapping(Protocol): + def __getitem__(self, __key: str) -> Any: ... + +class str(Sequence[str], _str_base): + if sys.version_info >= (3,): + @overload + def __init__(self, o: object = ...) -> None: ... + @overload + def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, o: object = ...) -> None: ... + + def capitalize(self) -> str: ... + if sys.version_info >= (3, 3): + def casefold(self) -> str: ... + def center(self, __width: int, __fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info < (3,): + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + if sys.version_info >= (3,): + def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + else: + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> str: ... + if sys.version_info >= (3,): + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + if sys.version_info >= (3,): + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + if sys.version_info >= (3,): + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + if sys.version_info >= (3,): + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, __iterable: Iterable[str]) -> str: ... + else: + def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + if sys.version_info >= (3,): + def lstrip(self, __chars: Optional[str] = ...) -> str: ... + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... + else: + @overload + def lstrip(self, __chars: str = ...) -> str: ... + @overload + def lstrip(self, __chars: unicode) -> unicode: ... + @overload + def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: str) -> str: ... + def removesuffix(self, __suffix: str) -> str: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + if sys.version_info >= (3,): + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, __chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + else: + @overload + def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, __chars: str = ...) -> str: ... + @overload + def rstrip(self, __chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + if sys.version_info >= (3,): + def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + def strip(self, __chars: Optional[str] = ...) -> str: ... + else: + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, __chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + if sys.version_info >= (3,): + def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... + else: + def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, __width: int) -> str: ... + if sys.version_info >= (3,): + @staticmethod + @overload + def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... + + if sys.version_info >= (3,): + def __add__(self, s: str) -> str: ... + else: + def __add__(self, s: AnyStr) -> AnyStr: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +if sys.version_info >= (3,): + class bytes(ByteString): + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, + errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: SupportsBytes) -> None: ... + def capitalize(self) -> bytes: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + elif sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytes: ... + def removesuffix(self, __suffix: bytes) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, __width: int) -> bytes: ... + @classmethod + def fromhex(cls, __s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... +else: + bytes = str + +class bytearray(MutableSequence[int], ByteString): + if sys.version_info >= (3,): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + else: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + if sys.version_info >= (3,): + def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + else: + def count(self, __sub: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + if sys.version_info < (3,): + def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... + if sys.version_info >= (3,): + def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + else: + def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def insert(self, __index: int, __item: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + else: + def join(self, __iterable: Iterable[str]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytearray: ... + def removesuffix(self, __suffix: bytes) -> bytearray: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + else: + def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, + __prefix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[int] = ..., + __end: Optional[int] = ..., + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + if sys.version_info >= (3,): + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... + else: + def translate(self, __table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, __width: int) -> bytearray: ... + @classmethod + def fromhex(cls, __string: str) -> bytearray: ... + if sys.version_info >= (3,): + @classmethod + def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + if sys.version_info >= (3,): + def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3,): + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +if sys.version_info >= (3,): + _mv_container_type = int +else: + _mv_container_type = str + +class memoryview(Sized, Container[_mv_container_type]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + + if sys.version_info >= (3,): + obj: Union[bytes, bytearray] + c_contiguous: bool + f_contiguous: bool + contiguous: bool + nbytes: int + def __init__(self, obj: ReadableBuffer) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... + def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... + else: + def __init__(self, obj: ReadableBuffer) -> None: ... + + @overload + def __getitem__(self, i: int) -> _mv_container_type: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_mv_container_type]: ... + def __len__(self) -> int: ... + + @overload + def __setitem__(self, s: slice, o: memoryview) -> None: ... + @overload + def __setitem__(self, i: int, o: bytes) -> None: ... + @overload + def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... + + if sys.version_info >= (3, 8): + def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... + else: + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + if sys.version_info >= (3, 8): + def toreadonly(self) -> memoryview: ... + + if sys.version_info >= (3, 2): + def release(self) -> None: ... + + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + +class bool(int): + def __init__(self, o: object = ...) -> None: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Any + step: Any + stop: Any + @overload + def __init__(self, stop: Any) -> None: ... + @overload + def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... + __hash__: None # type: ignore + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + @overload + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + @overload + def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, __value: Any) -> int: ... + if sys.version_info >= (3, 5): + def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... + else: + def index(self, __value: Any) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + __code__: CodeType + if sys.version_info >= (3,): + __qualname__: str + __annotations__: Dict[str, Any] + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + if sys.version_info >= (3,): + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: int = ...) -> _T: ... + def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: int, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + def reverse(self) -> None: ... + if sys.version_info >= (3,): + @overload + def sort(self: List[_LT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], _SupportsLessThan], reverse: bool = ...) -> None: ... + else: + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + if sys.version_info >= (3,): + def __imul__(self: _S, n: int) -> _S: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + + if sys.version_info < (3,): + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + if sys.version_info >= (3,): + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... + else: + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + @classmethod + @overload + 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: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class frozenset(AbstractSet[_T_co], Generic[_T_co]): + def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> FrozenSet[_T_co]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + if sys.version_info >= (3,): + def __next__(self) -> Tuple[int, _T]: ... + else: + def next(self) -> Tuple[int, _T]: ... + +if sys.version_info >= (3,): + class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int) -> int: ... # type: ignore + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... +else: + class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: int) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ...) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +if sys.version_info < (3,): + long = int + +class _NotImplementedType(Any): # type: ignore + # A little weird, but typing the __call__ as NotImplemented makes the error message + # for NotImplemented() much better + __call__: NotImplemented # type: ignore + +NotImplemented: _NotImplementedType + +def abs(__x: SupportsAbs[_T]) -> _T: ... +def all(__iterable: Iterable[object]) -> bool: ... +def any(__iterable: Iterable[object]) -> bool: ... +if sys.version_info < (3,): + def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +if sys.version_info >= (3,): + def ascii(__obj: object) -> str: ... + +def bin(__number: Union[int, _SupportsIndex]) -> str: ... + +if sys.version_info >= (3, 7): + def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(__obj: object) -> bool: ... +def chr(__i: int) -> str: ... +if sys.version_info < (3,): + def cmp(__x: Any, __y: Any) -> int: ... + _N1 = TypeVar('_N1', bool, int, float, complex) + def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +if sys.version_info >= (3, 6): + # This class is to be exported as PathLike from os, + # but we define it here as _PathLike to avoid import cycle issues. + # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 + class _PathLike(Generic[AnyStr]): + def __fspath__(self) -> AnyStr: ... + def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes, _PathLike[Any]], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +elif sys.version_info >= (3,): + def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +else: + def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +if sys.version_info >= (3,): + def copyright() -> None: ... + def credits() -> None: ... +def delattr(__obj: Any, __name: Text) -> None: ... +def dir(__o: object = ...) -> List[str]: ... +_N2 = TypeVar('_N2', int, float) +def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def eval(__source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +if sys.version_info >= (3,): + def exec(__source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +else: + def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: object = ...) -> NoReturn: ... +if sys.version_info >= (3,): + @overload + def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... +else: + @overload + def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore + @overload + def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore + @overload + def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore + @overload + 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: ... +def globals() -> Dict[str, Any]: ... +def hasattr(__obj: Any, __name: Text) -> bool: ... +def hash(__obj: object) -> int: ... +if sys.version_info >= (3,): + def help(*args: Any, **kwds: Any) -> None: ... +def hex(__number: Union[int, _SupportsIndex]) -> str: ... +def id(__obj: object) -> int: ... +if sys.version_info >= (3,): + def input(__prompt: Any = ...) -> str: ... +else: + def input(__prompt: Any = ...) -> Any: ... + def intern(__string: str) -> str: ... +@overload +def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +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: ... +def len(__obj: Sized) -> int: ... +if sys.version_info >= (3,): + def license() -> None: ... +def locals() -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> Iterator[_S]: ... + @overload + def map(__func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[_S]: ... +else: + @overload + def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def map(__func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def map(__func: None, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... + @overload + def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[_S]: ... + @overload + def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5]) -> List[_S]: ... + @overload + def map(__func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[_S]: ... +if sys.version_info >= (3,): + @overload + def max(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... + @overload + def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... + @overload + def max(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... + @overload + def max(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... + @overload + def max(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... + @overload + def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... +else: + @overload + def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +if sys.version_info >= (3,): + @overload + def min(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... + @overload + def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... + @overload + def min(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... + @overload + def min(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... + @overload + def min(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... + @overload + def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... +else: + @overload + def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(__i: Iterator[_T]) -> _T: ... +@overload +def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(__number: Union[int, _SupportsIndex]) -> str: ... + +if sys.version_info >= (3,): + _OpenFile = Union[AnyPath, int] + _Opener = Callable[[str, int], int] + + # Text mode: always returns a TextIOWrapper + @overload + def open( + file: _OpenFile, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> TextIOWrapper: ... + + # Unbuffered binary mode: returns a FileIO + @overload + def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> FileIO: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedRandom: ... + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedWriter: ... + @overload + def open( + file: _OpenFile, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BufferedReader: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: int, + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> BinaryIO: ... + + # Fallback if mode is not specified + @overload + def open( + file: _OpenFile, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., + ) -> IO[Any]: ... + +else: + def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + +def ord(__c: Union[Text, bytes]) -> int: ... +if sys.version_info >= (3,): + def print( + *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[str]] = ..., flush: bool = ... + ) -> None: ... + +else: + # This is only available after from __future__ import print_function. + def print(*values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ...) -> None: ... + +_E = TypeVar("_E", contravariant=True) +_M = TypeVar("_M", contravariant=True) +class _SupportsPow2(Protocol[_E, _T_co]): + def __pow__(self, __other: _E) -> _T_co: ... +class _SupportsPow3(Protocol[_E, _M, _T_co]): + def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... +if sys.version_info >= (3, 8): + @overload + def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(base: int, exp: int, mod: int) -> int: ... + @overload + def pow(base: float, exp: float, mod: None = ...) -> float: ... + @overload + def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... + @overload + def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... +else: + @overload + def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + @overload + def pow(__base: int, __exp: int, __mod: int) -> int: ... + @overload + def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... + @overload + def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... + @overload + def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... +def quit(code: object = ...) -> NoReturn: ... +if sys.version_info < (3,): + def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 + def raw_input(__prompt: Any = ...) -> str: ... + @overload + def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... + @overload + def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... + def reload(__module: Any) -> Any: ... +@overload +def reversed(__object: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(__object: Reversible[_T]) -> Iterator[_T]: ... +def repr(__obj: object) -> str: ... +if sys.version_info >= (3,): + @overload + def round(number: float) -> int: ... + @overload + def round(number: float, ndigits: None) -> int: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: None) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +else: + @overload + def round(number: float) -> float: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsFloat) -> float: ... + @overload + def round(number: SupportsFloat, ndigits: int) -> float: ... +def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... +if sys.version_info >= (3,): + @overload + def sorted(__iterable: Iterable[_LT], *, + key: None = ..., + reverse: bool = ...) -> List[_LT]: ... + @overload + def sorted(__iterable: Iterable[_T], *, + key: Callable[[_T], _SupportsLessThan], + reverse: bool = ...) -> List[_T]: ... +else: + def sorted(__iterable: Iterable[_T], *, + cmp: Callable[[_T, _T], int] = ..., + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ...) -> List[_T]: ... +if sys.version_info >= (3, 8): + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... +else: + @overload + def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... + @overload + def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... +if sys.version_info < (3,): + def unichr(__i: int) -> unicode: ... +def vars(__object: Any = ...) -> Dict[str, Any]: ... +if sys.version_info >= (3,): + # Some overloads to better support zipping heterogeneous tuples + @overload + def zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3, _T4]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...]]: ... # type: ignore + @overload + def zip(*iterables: Tuple[_T1, _T2, _T3, _T4, _T5]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...], Tuple[_T5, ...]]: ... # type: ignore + + @overload + def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], + __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +else: + @overload + def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... + @overload + def zip(__iter1: Iterable[_T1], + __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], + __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], + __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], + __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... +def __import__(name: Text, globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ...) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... +Ellipsis: ellipsis + +if sys.version_info < (3,): + # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. + _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) + + class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + if sys.version_info < (3,): + message: Any + if sys.version_info >= (3,): + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __suppress_context__: bool + __traceback__: Optional[TracebackType] + def __init__(self, *args: object) -> None: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + if sys.version_info < (3,): + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + if sys.version_info >= (3,): + def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... +class SystemExit(BaseException): + code: int +class Exception(BaseException): ... +class StopIteration(Exception): + if sys.version_info >= (3,): + value: Any +if sys.version_info >= (3,): + _StandardError = Exception + class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + EnvironmentError = OSError + IOError = OSError +else: + class StandardError(Exception): ... + _StandardError = StandardError + class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + class OSError(EnvironmentError): ... + class IOError(EnvironmentError): ... + +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): + if sys.version_info >= (3, 3): + def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... + name: Optional[str] + path: Optional[str] +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... +if sys.version_info >= (3, 5): + class StopAsyncIteration(Exception): + value: Any +class SyntaxError(_StandardError): + msg: str + lineno: Optional[int] + offset: Optional[int] + text: Optional[str] + filename: Optional[str] +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... + +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... + +if sys.version_info >= (3, 6): + class ModuleNotFoundError(ImportError): ... + +class IndexError(LookupError): ... +class KeyError(LookupError): ... + +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int +if sys.version_info >= (3,): + class BlockingIOError(OSError): + characters_written: int + class ChildProcessError(OSError): ... + class ConnectionError(OSError): ... + class BrokenPipeError(ConnectionError): ... + class ConnectionAbortedError(ConnectionError): ... + class ConnectionRefusedError(ConnectionError): ... + class ConnectionResetError(ConnectionError): ... + class FileExistsError(OSError): ... + class FileNotFoundError(OSError): ... + class InterruptedError(OSError): ... + class IsADirectoryError(OSError): ... + class NotADirectoryError(OSError): ... + class PermissionError(OSError): ... + class ProcessLookupError(OSError): ... + class TimeoutError(OSError): ... + +class NotImplementedError(RuntimeError): ... +if sys.version_info >= (3, 5): + class RecursionError(RuntimeError): ... + +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... + +class UnicodeError(ValueError): ... +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeTranslateError(UnicodeError): ... + +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +if sys.version_info >= (3, 2): + class ResourceWarning(Warning): ... + +if sys.version_info < (3,): + class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> Optional[bool]: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/mypy/stdlib/python2/_ast.pyi b/mypy/stdlib/python2/_ast.pyi new file mode 100644 index 000000000000..c461bb412805 --- /dev/null +++ b/mypy/stdlib/python2/_ast.pyi @@ -0,0 +1,330 @@ +import typing +from typing import Optional + +__version__: str +PyCF_ONLY_AST: int +_identifier = str + +class AST: + _attributes: typing.Tuple[str, ...] + _fields: typing.Tuple[str, ...] + def __init__(self, *args, **kwargs) -> None: ... + +class mod(AST): + ... + +class Module(mod): + body: typing.List[stmt] + +class Interactive(mod): + body: typing.List[stmt] + +class Expression(mod): + body: expr + +class Suite(mod): + body: typing.List[stmt] + + +class stmt(AST): + lineno: int + col_offset: int + +class FunctionDef(stmt): + name: _identifier + args: arguments + body: typing.List[stmt] + decorator_list: typing.List[expr] + +class ClassDef(stmt): + name: _identifier + bases: typing.List[expr] + body: typing.List[stmt] + decorator_list: typing.List[expr] + +class Return(stmt): + value: Optional[expr] + +class Delete(stmt): + targets: typing.List[expr] + +class Assign(stmt): + targets: typing.List[expr] + value: expr + +class AugAssign(stmt): + target: expr + op: operator + value: expr + +class Print(stmt): + dest: Optional[expr] + values: typing.List[expr] + nl: bool + +class For(stmt): + target: expr + iter: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class While(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class If(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class With(stmt): + context_expr: expr + optional_vars: Optional[expr] + body: typing.List[stmt] + +class Raise(stmt): + type: Optional[expr] + inst: Optional[expr] + tback: Optional[expr] + +class TryExcept(stmt): + body: typing.List[stmt] + handlers: typing.List[ExceptHandler] + orelse: typing.List[stmt] + +class TryFinally(stmt): + body: typing.List[stmt] + finalbody: typing.List[stmt] + +class Assert(stmt): + test: expr + msg: Optional[expr] + +class Import(stmt): + names: typing.List[alias] + +class ImportFrom(stmt): + module: Optional[_identifier] + names: typing.List[alias] + level: Optional[int] + +class Exec(stmt): + body: expr + globals: Optional[expr] + locals: Optional[expr] + +class Global(stmt): + names: typing.List[_identifier] + +class Expr(stmt): + value: expr + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + + +class slice(AST): + ... + +_slice = slice # this lets us type the variable named 'slice' below + +class Slice(slice): + lower: Optional[expr] + upper: Optional[expr] + step: Optional[expr] + +class ExtSlice(slice): + dims: typing.List[slice] + +class Index(slice): + value: expr + +class Ellipsis(slice): ... + + +class expr(AST): + lineno: int + col_offset: int + +class BoolOp(expr): + op: boolop + values: typing.List[expr] + +class BinOp(expr): + left: expr + op: operator + right: expr + +class UnaryOp(expr): + op: unaryop + operand: expr + +class Lambda(expr): + args: arguments + body: expr + +class IfExp(expr): + test: expr + body: expr + orelse: expr + +class Dict(expr): + keys: typing.List[expr] + values: typing.List[expr] + +class Set(expr): + elts: typing.List[expr] + +class ListComp(expr): + elt: expr + generators: typing.List[comprehension] + +class SetComp(expr): + elt: expr + generators: typing.List[comprehension] + +class DictComp(expr): + key: expr + value: expr + generators: typing.List[comprehension] + +class GeneratorExp(expr): + elt: expr + generators: typing.List[comprehension] + +class Yield(expr): + value: Optional[expr] + +class Compare(expr): + left: expr + ops: typing.List[cmpop] + comparators: typing.List[expr] + +class Call(expr): + func: expr + args: typing.List[expr] + keywords: typing.List[keyword] + starargs: Optional[expr] + kwargs: Optional[expr] + +class Repr(expr): + value: expr + +class Num(expr): + n: float + +class Str(expr): + s: str + +class Attribute(expr): + value: expr + attr: _identifier + ctx: expr_context + +class Subscript(expr): + value: expr + slice: _slice + ctx: expr_context + +class Name(expr): + id: _identifier + ctx: expr_context + +class List(expr): + elts: typing.List[expr] + ctx: expr_context + +class Tuple(expr): + elts: typing.List[expr] + ctx: expr_context + + +class expr_context(AST): + ... + +class AugLoad(expr_context): ... +class AugStore(expr_context): ... +class Del(expr_context): ... +class Load(expr_context): ... +class Param(expr_context): ... +class Store(expr_context): ... + + +class boolop(AST): + ... + +class And(boolop): ... +class Or(boolop): ... + +class operator(AST): + ... + +class Add(operator): ... +class BitAnd(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class Div(operator): ... +class FloorDiv(operator): ... +class LShift(operator): ... +class Mod(operator): ... +class Mult(operator): ... +class Pow(operator): ... +class RShift(operator): ... +class Sub(operator): ... + +class unaryop(AST): + ... + +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... + +class cmpop(AST): + ... + +class Eq(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class In(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class NotEq(cmpop): ... +class NotIn(cmpop): ... + + +class comprehension(AST): + target: expr + iter: expr + ifs: typing.List[expr] + + +class excepthandler(AST): + ... + + +class ExceptHandler(excepthandler): + type: Optional[expr] + name: Optional[expr] + body: typing.List[stmt] + lineno: int + col_offset: int + + +class arguments(AST): + args: typing.List[expr] + vararg: Optional[_identifier] + kwarg: Optional[_identifier] + defaults: typing.List[expr] + +class keyword(AST): + arg: _identifier + value: expr + +class alias(AST): + name: _identifier + asname: Optional[_identifier] diff --git a/mypy/stdlib/python2/_collections.pyi b/mypy/stdlib/python2/_collections.pyi new file mode 100644 index 000000000000..bee5d67b0918 --- /dev/null +++ b/mypy/stdlib/python2/_collections.pyi @@ -0,0 +1,38 @@ +"""Stub file for the '_collections' module.""" + +from typing import Any, Callable, Dict, Generic, Iterator, TypeVar, Optional, Union + +_K = TypeVar("_K") +_V = TypeVar("_V") +_T = TypeVar('_T') +_T2 = TypeVar('_T2') + +class defaultdict(Dict[_K, _V]): + default_factory: None + def __init__(self, __default_factory: Callable[[], _V] = ..., init: Any = ...) -> None: ... + def __missing__(self, key: _K) -> _V: ... + def __copy__(self: _T) -> _T: ... + def copy(self: _T) -> _T: ... + +class deque(Generic[_T]): + maxlen: Optional[int] + def __init__(self, iterable: Iterator[_T] = ..., maxlen: int = ...) -> None: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: Any) -> int: ... + def extend(self, iterable: Iterator[_T]) -> None: ... + def extendleft(self, iterable: Iterator[_T]) -> None: ... + def pop(self) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int = ...) -> None: ... + def __contains__(self, o: Any) -> bool: ... + def __copy__(self) -> deque[_T]: ... + def __getitem__(self, i: int) -> _T: ... + def __iadd__(self, other: deque[_T2]) -> deque[Union[_T, _T2]]: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def __reversed__(self) -> Iterator[_T]: ... + def __setitem__(self, i: int, x: _T) -> None: ... diff --git a/mypy/stdlib/python2/_functools.pyi b/mypy/stdlib/python2/_functools.pyi new file mode 100644 index 000000000000..876974e45429 --- /dev/null +++ b/mypy/stdlib/python2/_functools.pyi @@ -0,0 +1,20 @@ +"""Stub file for the '_functools' module.""" + +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Tuple, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") + +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... + +class partial(object): + func: Callable[..., Any] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/mypy/stdlib/python2/_hotshot.pyi b/mypy/stdlib/python2/_hotshot.pyi new file mode 100644 index 000000000000..a4404b0c7f8d --- /dev/null +++ b/mypy/stdlib/python2/_hotshot.pyi @@ -0,0 +1,24 @@ +"""Stub file for the '_hotshot' module.""" +# This is an autogenerated file. It serves as a starting point +# for a more precise manual annotation of this module. +# Feel free to edit the source below, but remove this header when you do. + +from typing import Any, List, Tuple, Dict, Generic + +def coverage(a: str) -> Any: ... +def logreader(a: str) -> LogReaderType: ... +def profiler(a: str, *args, **kwargs) -> Any: ... +def resolution() -> Tuple[Any, ...]: ... + +class LogReaderType(object): + def close(self) -> None: ... + def fileno(self) -> int: ... + +class ProfilerType(object): + def addinfo(self, a: str, b: str) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def runcall(self, *args, **kwargs) -> Any: ... + def runcode(self, a, b, *args, **kwargs) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... diff --git a/mypy/stdlib/python2/_io.pyi b/mypy/stdlib/python2/_io.pyi new file mode 100644 index 000000000000..e8e448f2c8ed --- /dev/null +++ b/mypy/stdlib/python2/_io.pyi @@ -0,0 +1,186 @@ +from typing import Any, AnyStr, BinaryIO, IO, Text, TextIO, Iterable, Iterator, List, Optional, Type, Tuple, TypeVar, Union +from mmap import mmap +from types import TracebackType + +_bytearray_like = Union[bytearray, mmap] + +DEFAULT_BUFFER_SIZE: int + +class BlockingIOError(IOError): + characters_written: int + +class UnsupportedOperation(ValueError, IOError): ... + +_T = TypeVar("_T") + +class _IOBase(BinaryIO): + @property + def closed(self) -> bool: ... + def _checkClosed(self, msg: Optional[str] = ...) -> None: ... # undocumented + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + # All these methods are concrete here (you can instantiate this) + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + 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 __enter__(self: _T) -> _T: ... + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> Optional[bool]: ... + def __iter__(self: _T) -> _T: ... + # The parameter type of writelines[s]() is determined by that of write(): + def writelines(self, lines: Iterable[bytes]) -> None: ... + # The return type of readline[s]() and next() is determined by that of read(): + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def next(self) -> bytes: ... + # These don't actually exist but we need to pretend that it does + # so that this class is concrete. + def write(self, s: bytes) -> int: ... + def read(self, n: int = ...) -> bytes: ... + +class _BufferedIOBase(_IOBase): + def read1(self, n: int) -> bytes: ... + def read(self, size: int = ...) -> bytes: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, s: bytes) -> int: ... + def detach(self) -> _IOBase: ... + +class BufferedRWPair(_BufferedIOBase): + def __init__(self, reader: _RawIOBase, writer: _RawIOBase, + buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + def __enter__(self) -> BufferedRWPair: ... + +class BufferedRandom(_BufferedIOBase): + mode: str + name: str + raw: _IOBase + def __init__(self, raw: _IOBase, + buffer_size: int = ..., + max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedReader(_BufferedIOBase): + mode: str + name: str + raw: _IOBase + def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedWriter(_BufferedIOBase): + name: str + raw: _IOBase + mode: str + def __init__(self, raw: _IOBase, + buffer_size: int = ..., + max_buffer_size: int = ...) -> None: ... + +class BytesIO(_BufferedIOBase): + def __init__(self, initial_bytes: bytes = ...) -> None: ... + def __setstate__(self, state: Tuple[Any, ...]) -> None: ... + def __getstate__(self) -> Tuple[Any, ...]: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def write(self, s: bytes) -> int: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + def read1(self, size: int) -> bytes: ... + def next(self) -> bytes: ... + +class _RawIOBase(_IOBase): + def readall(self) -> str: ... + def read(self, n: int = ...) -> str: ... + +class FileIO(_RawIOBase, BytesIO): + mode: str + closefd: bool + def __init__(self, file: Union[str, int], mode: str = ..., closefd: bool = ...) -> None: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, pbuf: str) -> int: ... + +class IncrementalNewlineDecoder(object): + newlines: Union[str, unicode] + def __init__(self, decoder, translate, z=...) -> None: ... + def decode(self, input, final) -> Any: ... + def getstate(self) -> Tuple[Any, int]: ... + def setstate(self, state: Tuple[Any, int]) -> None: ... + def reset(self) -> None: ... + + +# Note: In the actual _io.py, _TextIOBase inherits from _IOBase. +class _TextIOBase(TextIO): + errors: Optional[str] + # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses. + newlines: Union[None, unicode, bytes] + encoding: str + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + def close(self) -> None: ... + def detach(self) -> IO[Any]: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> unicode: ... + def read(self, size: int = ...) -> unicode: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> unicode: ... + def readlines(self, hint: int = ...) -> list[unicode]: ... + 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, pbuf: unicode) -> int: ... + def writelines(self, lines: Iterable[unicode]) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> Optional[bool]: ... + def __iter__(self: _T) -> _T: ... + +class StringIO(_TextIOBase): + line_buffering: bool + def __init__(self, + initial_value: Optional[unicode] = ..., + newline: Optional[unicode] = ...) -> None: ... + def __setstate__(self, state: Tuple[Any, ...]) -> None: ... + def __getstate__(self) -> Tuple[Any, ...]: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> unicode: ... + +class TextIOWrapper(_TextIOBase): + name: str + line_buffering: bool + buffer: BinaryIO + _CHUNK_SIZE: int + def __init__( + self, + buffer: IO[Any], + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + line_buffering: bool = ..., + write_through: bool = ..., + ) -> None: ... + +def open(file: Union[str, unicode, int], + mode: Text = ..., + buffering: int = ..., + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + closefd: bool = ...) -> IO[Any]: ... diff --git a/mypy/stdlib/python2/_json.pyi b/mypy/stdlib/python2/_json.pyi new file mode 100644 index 000000000000..1c8e0409feaf --- /dev/null +++ b/mypy/stdlib/python2/_json.pyi @@ -0,0 +1,7 @@ +from typing import Any, Dict, Generic, List, Tuple + +def encode_basestring_ascii(*args, **kwargs) -> str: ... +def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... + +class Encoder(object): ... +class Scanner(object): ... diff --git a/mypy/stdlib/python2/_md5.pyi b/mypy/stdlib/python2/_md5.pyi new file mode 100644 index 000000000000..96111b70af9b --- /dev/null +++ b/mypy/stdlib/python2/_md5.pyi @@ -0,0 +1,13 @@ +blocksize: int +digest_size: int + +class MD5Type(object): + name: str + block_size: int + digest_size: int + def copy(self) -> MD5Type: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> MD5Type: ... diff --git a/mypy/stdlib/python2/_sha.pyi b/mypy/stdlib/python2/_sha.pyi new file mode 100644 index 000000000000..7c472562fc17 --- /dev/null +++ b/mypy/stdlib/python2/_sha.pyi @@ -0,0 +1,15 @@ +blocksize: int +block_size: int +digest_size: int + +class sha(object): # not actually exposed + name: str + block_size: int + digest_size: int + digestsize: int + def copy(self) -> sha: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> sha: ... diff --git a/mypy/stdlib/python2/_sha256.pyi b/mypy/stdlib/python2/_sha256.pyi new file mode 100644 index 000000000000..b6eb47d4bc83 --- /dev/null +++ b/mypy/stdlib/python2/_sha256.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha224(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha224: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha256(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha256: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/mypy/stdlib/python2/_sha512.pyi b/mypy/stdlib/python2/_sha512.pyi new file mode 100644 index 000000000000..b1ca9aee004c --- /dev/null +++ b/mypy/stdlib/python2/_sha512.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha384(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha384: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha512(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha512: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/mypy/stdlib/python2/_socket.pyi b/mypy/stdlib/python2/_socket.pyi new file mode 100644 index 000000000000..f6a058acac2f --- /dev/null +++ b/mypy/stdlib/python2/_socket.pyi @@ -0,0 +1,283 @@ +from typing import Tuple, Union, IO, Any, Optional, overload + +AF_APPLETALK: int +AF_ASH: int +AF_ATMPVC: int +AF_ATMSVC: int +AF_AX25: int +AF_BLUETOOTH: int +AF_BRIDGE: int +AF_DECnet: int +AF_ECONET: int +AF_INET: int +AF_INET6: int +AF_IPX: int +AF_IRDA: int +AF_KEY: int +AF_LLC: int +AF_NETBEUI: int +AF_NETLINK: int +AF_NETROM: int +AF_PACKET: int +AF_PPPOX: int +AF_ROSE: int +AF_ROUTE: int +AF_SECURITY: int +AF_SNA: int +AF_TIPC: int +AF_UNIX: int +AF_UNSPEC: int +AF_WANPIPE: int +AF_X25: int +AI_ADDRCONFIG: int +AI_ALL: int +AI_CANONNAME: int +AI_NUMERICHOST: int +AI_NUMERICSERV: int +AI_PASSIVE: int +AI_V4MAPPED: int +BDADDR_ANY: str +BDADDR_LOCAL: str +BTPROTO_HCI: int +BTPROTO_L2CAP: int +BTPROTO_RFCOMM: int +BTPROTO_SCO: int +EAI_ADDRFAMILY: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_OVERFLOW: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +EAI_SYSTEM: int +EBADF: int +EINTR: int +HCI_DATA_DIR: int +HCI_FILTER: int +HCI_TIME_STAMP: 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_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GRE: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMP: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IP: int +IPPROTO_IPIP: int +IPPROTO_IPV6: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_RAW: int +IPPROTO_ROUTING: int +IPPROTO_RSVP: int +IPPROTO_TCP: int +IPPROTO_TP: int +IPPROTO_UDP: int +IPV6_CHECKSUM: 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_PKTINFO: int +IPV6_RECVDSTOPTS: int +IPV6_RECVHOPLIMIT: int +IPV6_RECVHOPOPTS: 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_V6ONLY: 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_RECVOPTS: int +IP_RECVRETOPTS: int +IP_RETOPTS: int +IP_TOS: int +IP_TTL: int +MSG_CTRUNC: int +MSG_DONTROUTE: int +MSG_DONTWAIT: int +MSG_EOR: int +MSG_OOB: int +MSG_PEEK: int +MSG_TRUNC: int +MSG_WAITALL: int +MethodType: type +NETLINK_DNRTMSG: int +NETLINK_FIREWALL: int +NETLINK_IP6_FW: int +NETLINK_NFLOG: int +NETLINK_ROUTE: int +NETLINK_USERSOCK: int +NETLINK_XFRM: int +NI_DGRAM: int +NI_MAXHOST: int +NI_MAXSERV: int +NI_NAMEREQD: int +NI_NOFQDN: int +NI_NUMERICHOST: int +NI_NUMERICSERV: int +PACKET_BROADCAST: int +PACKET_FASTROUTE: int +PACKET_HOST: int +PACKET_LOOPBACK: int +PACKET_MULTICAST: int +PACKET_OTHERHOST: int +PACKET_OUTGOING: int +PF_PACKET: int +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int +SOCK_DGRAM: int +SOCK_RAW: int +SOCK_RDM: int +SOCK_SEQPACKET: int +SOCK_STREAM: int +SOL_HCI: int +SOL_IP: int +SOL_SOCKET: int +SOL_TCP: int +SOL_TIPC: int +SOL_UDP: int +SOMAXCONN: int +SO_ACCEPTCONN: int +SO_BROADCAST: int +SO_DEBUG: int +SO_DONTROUTE: int +SO_ERROR: int +SO_KEEPALIVE: int +SO_LINGER: int +SO_OOBINLINE: int +SO_RCVBUF: int +SO_RCVLOWAT: int +SO_RCVTIMEO: int +SO_REUSEADDR: int +SO_REUSEPORT: int +SO_SNDBUF: int +SO_SNDLOWAT: int +SO_SNDTIMEO: int +SO_TYPE: int +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 +TCP_CORK: int +TCP_DEFER_ACCEPT: 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 +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 + +# PyCapsule +CAPI: Any + +has_ipv6: bool + +class error(IOError): ... +class gaierror(error): ... +class timeout(error): ... + +class SocketType(object): + family: int + type: int + proto: int + timeout: float + + def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... + def accept(self) -> Tuple[SocketType, Tuple[Any, ...]]: ... + def bind(self, address: Tuple[Any, ...]) -> None: ... + def close(self) -> None: ... + def connect(self, address: Tuple[Any, ...]) -> None: ... + def connect_ex(self, address: Tuple[Any, ...]) -> int: ... + def dup(self) -> SocketType: ... + def fileno(self) -> int: ... + def getpeername(self) -> Tuple[Any, ...]: ... + def getsockname(self) -> Tuple[Any, ...]: ... + def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... + def gettimeout(self) -> float: ... + def listen(self, backlog: int) -> None: ... + def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... + def recv(self, buffersize: int, flags: int = ...) -> str: ... + def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... + def recvfrom(self, buffersize: int, flags: int = ...) -> Tuple[Any, ...]: ... + def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., + flags: int = ...) -> int: ... + def send(self, data: str, flags: int = ...) -> int: ... + def sendall(self, data: str, flags: int = ...) -> None: ... + @overload + def sendto(self, data: str, address: Tuple[Any, ...]) -> int: ... + @overload + def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def setsockopt(self, level: int, option: int, value: Union[int, str]) -> None: ... + def settimeout(self, value: Optional[float]) -> None: ... + def shutdown(self, flag: int) -> None: ... diff --git a/mypy/stdlib/python2/_sre.pyi b/mypy/stdlib/python2/_sre.pyi new file mode 100644 index 000000000000..93300f0f2999 --- /dev/null +++ b/mypy/stdlib/python2/_sre.pyi @@ -0,0 +1,55 @@ +"""Stub file for the '_sre' module.""" + +from typing import Any, Union, Iterable, Optional, Mapping, Sequence, Dict, List, Tuple, overload + +CODESIZE: int +MAGIC: int +MAXREPEAT: long +copyright: str + +class SRE_Match(object): + def start(self, group: int = ...) -> int: ... + def end(self, group: int = ...) -> int: ... + def expand(self, s: str) -> Any: ... + @overload + def group(self) -> str: ... + @overload + def group(self, group: int = ...) -> Optional[str]: ... + def groupdict(self) -> Dict[int, Optional[str]]: ... + def groups(self) -> Tuple[Optional[str], ...]: ... + def span(self) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + +class SRE_Scanner(object): + pattern: str + def match(self) -> SRE_Match: ... + def search(self) -> SRE_Match: ... + +class SRE_Pattern(object): + pattern: str + flags: int + groups: int + groupindex: Mapping[str, int] + indexgroup: Sequence[int] + def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Union[Tuple[Any, ...], str]]: ... + def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Union[Tuple[Any, ...], str]]: ... + def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... + def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def split(self, source: str, maxsplit: int = ...) -> List[Optional[str]]: ... + def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + +def compile( + pattern: str, + flags: int, + code: List[int], + groups: int = ..., + groupindex: Mapping[str, int] = ..., + indexgroup: Sequence[int] = ..., +) -> SRE_Pattern: ... + +def getcodesize() -> int: ... + +def getlower(a: int, b: int) -> int: ... diff --git a/mypy/stdlib/python2/_struct.pyi b/mypy/stdlib/python2/_struct.pyi new file mode 100644 index 000000000000..49f44f2c58a3 --- /dev/null +++ b/mypy/stdlib/python2/_struct.pyi @@ -0,0 +1,22 @@ +"""Stub file for the '_struct' module.""" + +from typing import Any, AnyStr, Tuple + +class error(Exception): ... + +class Struct(object): + size: int + format: str + + def __init__(self, fmt: str) -> None: ... + def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... + def pack(self, *args) -> str: ... + def unpack(self, s: str) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... + +def _clearcache() -> None: ... +def calcsize(fmt: str) -> int: ... +def pack(fmt: AnyStr, obj: Any) -> str: ... +def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... +def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... +def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/mypy/stdlib/python2/_symtable.pyi b/mypy/stdlib/python2/_symtable.pyi new file mode 100644 index 000000000000..fbf5424405ca --- /dev/null +++ b/mypy/stdlib/python2/_symtable.pyi @@ -0,0 +1,39 @@ +from typing import List, Dict + +CELL: int +DEF_BOUND: int +DEF_FREE: int +DEF_FREE_CLASS: int +DEF_GLOBAL: int +DEF_IMPORT: int +DEF_LOCAL: int +DEF_PARAM: int +FREE: int +GLOBAL_EXPLICIT: int +GLOBAL_IMPLICIT: int +LOCAL: int +OPT_BARE_EXEC: int +OPT_EXEC: int +OPT_IMPORT_STAR: int +SCOPE_MASK: int +SCOPE_OFF: int +TYPE_CLASS: int +TYPE_FUNCTION: int +TYPE_MODULE: int +USE: int + +class _symtable_entry(object): + ... + +class symtable(object): + children: List[_symtable_entry] + id: int + lineno: int + name: str + nested: int + optimized: int + symbols: Dict[str, int] + type: int + varnames: List[str] + + def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/mypy/stdlib/python2/_threading_local.pyi b/mypy/stdlib/python2/_threading_local.pyi new file mode 100644 index 000000000000..1a7e03de4967 --- /dev/null +++ b/mypy/stdlib/python2/_threading_local.pyi @@ -0,0 +1,12 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/_threading_local.py +from typing import Any + +class _localbase(object): ... + +class local(_localbase): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __del__(self) -> None: ... + +def _patch(self: local) -> None: ... diff --git a/mypy/stdlib/python2/_winreg.pyi b/mypy/stdlib/python2/_winreg.pyi new file mode 100644 index 000000000000..d1ed6a67d499 --- /dev/null +++ b/mypy/stdlib/python2/_winreg.pyi @@ -0,0 +1,99 @@ + +import sys + +from typing import Optional, Type, Union, Tuple, Any +from types import TracebackType + +_KeyType = Union[HKEYType, int] + +def CloseKey(__hkey: _KeyType): ... +def ConnectRegistry(__computer_name: Optional[str], __key: _KeyType) -> HKEYType: ... +def CreateKey(__key: _KeyType, __sub_key: Optional[str]) -> HKEYType: ... +def CreateKeyEx(key: _KeyType, sub_key: Optional[str], reserved: int = ..., access: int = ...) -> HKEYType: ... +def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... +def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... +def DeleteValue(__key: _KeyType, __value: str) -> None: ... +def EnumKey(__key: _KeyType, __index: int) -> str: ... +def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... +def ExpandEnvironmentStrings(__str: str) -> str: ... +def FlushKey(__key: _KeyType) -> None: ... +def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... +def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... +def QueryValue(__key: _KeyType, __sub_key: Optional[str]) -> str: ... +def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... +def SaveKey(__key: _KeyType, __file_name: str) -> None: ... +def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... +def SetValueEx(__key: _KeyType, __value_name: str, __reserved: Any, __type: int, __value: str) -> None: ... # reserved is ignored +def DisableReflectionKey(__key: _KeyType) -> None: ... +def EnableReflectionKey(__key: _KeyType) -> None: ... +def QueryReflectionKey(__key: _KeyType) -> bool: ... + +HKEY_CLASSES_ROOT: int +HKEY_CURRENT_USER: int +HKEY_LOCAL_MACHINE: int +HKEY_USERS: int +HKEY_PERFORMANCE_DATA: int +HKEY_CURRENT_CONFIG: int +HKEY_DYN_DATA: int + +KEY_ALL_ACCESS: int +KEY_WRITE: int +KEY_READ: int +KEY_EXECUTE: int +KEY_QUERY_VALUE: int +KEY_SET_VALUE: int +KEY_CREATE_SUB_KEY: int +KEY_ENUMERATE_SUB_KEYS: int +KEY_NOTIFY: int +KEY_CREATE_LINK: int + +KEY_WOW64_64KEY: int +KEY_WOW64_32KEY: int + +REG_BINARY: int +REG_DWORD: int +REG_DWORD_LITTLE_ENDIAN: int +REG_DWORD_BIG_ENDIAN: int +REG_EXPAND_SZ: int +REG_LINK: int +REG_MULTI_SZ: int +REG_NONE: int +if sys.version_info >= (3, 6): + REG_QWORD: int + REG_QWORD_LITTLE_ENDIAN: int +REG_RESOURCE_LIST: int +REG_FULL_RESOURCE_DESCRIPTOR: int +REG_RESOURCE_REQUIREMENTS_LIST: int +REG_SZ: int + +REG_CREATED_NEW_KEY: int # undocumented +REG_LEGAL_CHANGE_FILTER: int # undocumented +REG_LEGAL_OPTION: int # undocumented +REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented +REG_NOTIFY_CHANGE_LAST_SET: int # undocumented +REG_NOTIFY_CHANGE_NAME: int # undocumented +REG_NOTIFY_CHANGE_SECURITY: int # undocumented +REG_NO_LAZY_FLUSH: int # undocumented +REG_OPENED_EXISTING_KEY: int # undocumented +REG_OPTION_BACKUP_RESTORE: int # undocumented +REG_OPTION_CREATE_LINK: int # undocumented +REG_OPTION_NON_VOLATILE: int # undocumented +REG_OPTION_OPEN_LINK: int # undocumented +REG_OPTION_RESERVED: int # undocumented +REG_OPTION_VOLATILE: int # undocumented +REG_REFRESH_HIVE: int # undocumented +REG_WHOLE_HIVE_VOLATILE: int # undocumented + +error = OSError + +# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason +class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> HKEYType: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + + def Close(self) -> None: ... + def Detach(self) -> int: ... diff --git a/mypy/stdlib/python2/abc.pyi b/mypy/stdlib/python2/abc.pyi new file mode 100644 index 000000000000..64fbb50bc706 --- /dev/null +++ b/mypy/stdlib/python2/abc.pyi @@ -0,0 +1,31 @@ +from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar +import _weakrefset + +_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) + +# NOTE: mypy has special processing for ABCMeta and abstractmethod. + +def abstractmethod(funcobj: _FuncT) -> _FuncT: ... + +class ABCMeta(type): + # TODO: FrozenSet + __abstractmethods__: Set[Any] + _abc_cache: _weakrefset.WeakSet[Any] + _abc_invalidation_counter: int + _abc_negative_cache: _weakrefset.WeakSet[Any] + _abc_negative_cache_version: int + _abc_registry: _weakrefset.WeakSet[Any] + def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[Any, Any]) -> None: ... + def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... + def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... + def _dump_registry(cls: ABCMeta, *args: Any, **kwargs: Any) -> None: ... + def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... + +# TODO: The real abc.abstractproperty inherits from "property". +class abstractproperty(object): + def __new__(cls, func: Any) -> Any: ... + __isabstractmethod__: bool + doc: Any + fdel: Any + fget: Any + fset: Any diff --git a/mypy/stdlib/python2/ast.pyi b/mypy/stdlib/python2/ast.pyi new file mode 100644 index 000000000000..c5ffd65562b9 --- /dev/null +++ b/mypy/stdlib/python2/ast.pyi @@ -0,0 +1,28 @@ +# Python 2.7 ast + +# Rename typing to _typing, as not to conflict with typing imported +# from _ast below when loaded in an unorthodox way by the Dropbox +# internal Bazel integration. +import typing as _typing +from typing import Any, Iterator, Optional, Union + +from _ast import * +from _ast import AST, Module + +def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ... +def copy_location(new_node: AST, old_node: AST) -> AST: ... +def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... +def fix_missing_locations(node: AST) -> AST: ... +def get_docstring(node: AST, clean: bool = ...) -> str: ... +def increment_lineno(node: AST, n: int = ...) -> AST: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def literal_eval(node_or_string: Union[str, unicode, AST]) -> Any: ... +def walk(node: AST) -> Iterator[AST]: ... + +class NodeVisitor(): + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> Optional[AST]: ... diff --git a/mypy/stdlib/python2/atexit.pyi b/mypy/stdlib/python2/atexit.pyi new file mode 100644 index 000000000000..13d2602b0dc4 --- /dev/null +++ b/mypy/stdlib/python2/atexit.pyi @@ -0,0 +1,5 @@ +from typing import TypeVar, Any + +_FT = TypeVar('_FT') + +def register(func: _FT, *args: Any, **kargs: Any) -> _FT: ... diff --git a/mypy/stdlib/python2/cPickle.pyi b/mypy/stdlib/python2/cPickle.pyi new file mode 100644 index 000000000000..0421c50efe17 --- /dev/null +++ b/mypy/stdlib/python2/cPickle.pyi @@ -0,0 +1,32 @@ +from typing import Any, IO, List + +HIGHEST_PROTOCOL: int +compatible_formats: List[str] +format_version: str + +class Pickler: + def __init__(self, file: IO[str], protocol: int = ...) -> None: ... + + def dump(self, obj: Any) -> None: ... + + def clear_memo(self) -> None: ... + + +class Unpickler: + def __init__(self, file: IO[str]) -> None: ... + + def load(self) -> Any: ... + + def noload(self) -> Any: ... + + +def dump(obj: Any, file: IO[str], protocol: int = ...) -> None: ... +def dumps(obj: Any, protocol: int = ...) -> str: ... +def load(file: IO[str]) -> Any: ... +def loads(str: str) -> Any: ... + +class PickleError(Exception): ... +class UnpicklingError(PickleError): ... +class BadPickleGet(UnpicklingError): ... +class PicklingError(PickleError): ... +class UnpickleableError(PicklingError): ... diff --git a/mypy/stdlib/python2/cStringIO.pyi b/mypy/stdlib/python2/cStringIO.pyi new file mode 100644 index 000000000000..380e3a4be269 --- /dev/null +++ b/mypy/stdlib/python2/cStringIO.pyi @@ -0,0 +1,54 @@ +# Stubs for cStringIO (Python 2.7) +# See https://docs.python.org/2/library/stringio.html + +from abc import ABCMeta +from typing import overload, IO, List, Iterable, Iterator, Optional, Union +from types import TracebackType + +# TODO the typing.IO[] generics should be split into input and output. + +# This class isn't actually abstract, but you can't instantiate it +# directly, so we might as well treat it as abstract in the stub. +class InputType(IO[str], Iterator[str], metaclass=ABCMeta): + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> InputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + + +class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): + @property + def softspace(self) -> int: ... + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> OutputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + def write(self, b: Union[str, unicode]) -> int: ... + def writelines(self, lines: Iterable[Union[str, unicode]]) -> None: ... + +@overload +def StringIO() -> OutputType: ... +@overload +def StringIO(s: str) -> InputType: ... diff --git a/mypy/stdlib/python2/collections.pyi b/mypy/stdlib/python2/collections.pyi new file mode 100644 index 000000000000..988e9202f674 --- /dev/null +++ b/mypy/stdlib/python2/collections.pyi @@ -0,0 +1,120 @@ +# These are not exported. +from typing import Any, Dict, Generic, TypeVar, Tuple, overload, Type, Optional, List, Union, Reversible + +# These are exported. +from typing import ( + Callable as Callable, + Container as Container, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Sequence as Sequence, + AbstractSet as Set, + Sized as Sized, + ValuesView as ValuesView, +) + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +# namedtuple is special-cased in the type checker; the initializer is ignored. +def namedtuple(typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], + verbose: bool = ..., rename: bool = ...) -> Type[Tuple[Any, ...]]: ... + +class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ..., + maxlen: int = ...) -> None: ... + @property + def maxlen(self) -> Optional[int]: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: _T) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def extendleft(self, iterable: Iterable[_T]) -> None: ... + def pop(self) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + def __getitem__(self, i: int) -> _T: ... + def __setitem__(self, i: int, x: _T) -> None: ... + def __contains__(self, o: _T) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + +class Counter(Dict[_T, int], Generic[_T]): + @overload + def __init__(self, **kwargs: int) -> None: ... + @overload + def __init__(self, mapping: Mapping[_T, int]) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def copy(self: _S) -> _S: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... + @overload + def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def subtract(self, iterable: Iterable[_T]) -> None: ... + # The Iterable[Tuple[...]] argument type is not actually desirable + # (the tuples will be added as keys, breaking type safety) but + # it's included so that the signature is compatible with + # Dict.update. Not sure if we should use '# type: ignore' instead + # and omit the type from the union. + @overload + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + @overload + def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... + @overload + def update(self, **kwargs: int) -> None: ... + + def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... + def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + +class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... + def copy(self: _S) -> _S: ... + def __reversed__(self) -> Iterator[_KT]: ... + +class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + default_factory: Callable[[], _VT] + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + def copy(self: _S) -> _S: ... diff --git a/mypy/stdlib/python2/commands.pyi b/mypy/stdlib/python2/commands.pyi new file mode 100644 index 000000000000..e321f0844349 --- /dev/null +++ b/mypy/stdlib/python2/commands.pyi @@ -0,0 +1,12 @@ +from typing import overload, AnyStr, Text, Tuple + +def getstatus(file: Text) -> str: ... +def getoutput(cmd: Text) -> str: ... +def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... + +@overload +def mk2arg(head: bytes, x: bytes) -> bytes: ... +@overload +def mk2arg(head: Text, x: Text) -> Text: ... + +def mkarg(x: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/python2/compileall.pyi b/mypy/stdlib/python2/compileall.pyi new file mode 100644 index 000000000000..22662f46023d --- /dev/null +++ b/mypy/stdlib/python2/compileall.pyi @@ -0,0 +1,16 @@ +from _typeshed import AnyPath +from typing import Any, Optional, Pattern + +# rx can be any object with a 'search' method; once we have Protocols we can change the type +def compile_dir( + dir: AnyPath, + maxlevels: int = ..., + ddir: Optional[AnyPath] = ..., + 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 = ..., +) -> int: ... +def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/mypy/stdlib/python2/cookielib.pyi b/mypy/stdlib/python2/cookielib.pyi new file mode 100644 index 000000000000..abbf29894635 --- /dev/null +++ b/mypy/stdlib/python2/cookielib.pyi @@ -0,0 +1,112 @@ +from typing import Any, Optional + +class Cookie: + version: Any + name: Any + value: Any + port: Any + port_specified: Any + domain: Any + domain_specified: Any + domain_initial_dot: Any + path: Any + path_specified: Any + secure: Any + expires: Any + discard: Any + comment: Any + comment_url: Any + rfc2109: Any + def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, + path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109: bool = ...): ... + def has_nonstandard_attr(self, name): ... + def get_nonstandard_attr(self, name, default: Optional[Any] = ...): ... + def set_nonstandard_attr(self, name, value): ... + def is_expired(self, now: Optional[Any] = ...): ... + +class CookiePolicy: + def set_ok(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class DefaultCookiePolicy(CookiePolicy): + DomainStrictNoDots: Any + DomainStrictNonDomain: Any + DomainRFC2965Match: Any + DomainLiberal: Any + DomainStrict: Any + netscape: Any + rfc2965: Any + rfc2109_as_netscape: Any + hide_cookie2: Any + strict_domain: Any + strict_rfc2965_unverifiable: Any + strict_ns_unverifiable: Any + strict_ns_domain: Any + strict_ns_set_initial_dollar: Any + strict_ns_set_path: Any + def __init__(self, blocked_domains: Optional[Any] = ..., allowed_domains: Optional[Any] = ..., netscape: bool = ..., + rfc2965: bool = ..., rfc2109_as_netscape: Optional[Any] = ..., hide_cookie2: bool = ..., + strict_domain: bool = ..., strict_rfc2965_unverifiable: bool = ..., strict_ns_unverifiable: bool = ..., + strict_ns_domain=..., strict_ns_set_initial_dollar: bool = ..., strict_ns_set_path: bool = ...): ... + def blocked_domains(self): ... + def set_blocked_domains(self, blocked_domains): ... + def is_blocked(self, domain): ... + def allowed_domains(self): ... + def set_allowed_domains(self, allowed_domains): ... + def is_not_allowed(self, domain): ... + def set_ok(self, cookie, request): ... + def set_ok_version(self, cookie, request): ... + def set_ok_verifiability(self, cookie, request): ... + def set_ok_name(self, cookie, request): ... + def set_ok_path(self, cookie, request): ... + def set_ok_domain(self, cookie, request): ... + def set_ok_port(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def return_ok_version(self, cookie, request): ... + def return_ok_verifiability(self, cookie, request): ... + def return_ok_secure(self, cookie, request): ... + def return_ok_expires(self, cookie, request): ... + def return_ok_port(self, cookie, request): ... + def return_ok_domain(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class Absent: ... + +class CookieJar: + non_word_re: Any + quote_re: Any + strict_domain_re: Any + domain_re: Any + dots_re: Any + magic_re: Any + def __init__(self, policy: Optional[Any] = ...): ... + def set_policy(self, policy): ... + def add_cookie_header(self, request): ... + def make_cookies(self, response, request): ... + def set_cookie_if_ok(self, cookie, request): ... + def set_cookie(self, cookie): ... + def extract_cookies(self, response, request): ... + def clear(self, domain: Optional[Any] = ..., path: Optional[Any] = ..., name: Optional[Any] = ...): ... + def clear_session_cookies(self): ... + def clear_expired_cookies(self): ... + def __iter__(self): ... + def __len__(self): ... + +class LoadError(IOError): ... + +class FileCookieJar(CookieJar): + filename: Any + delayload: Any + def __init__(self, filename: Optional[Any] = ..., delayload: bool = ..., policy: Optional[Any] = ...): ... + def save(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def load(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def revert(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + +class LWPCookieJar(FileCookieJar): + def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented + +MozillaCookieJar = FileCookieJar +def lwp_cookie_str(cookie: Cookie) -> str: ... diff --git a/mypy/stdlib/python2/copy_reg.pyi b/mypy/stdlib/python2/copy_reg.pyi new file mode 100644 index 000000000000..a64a82c700d0 --- /dev/null +++ b/mypy/stdlib/python2/copy_reg.pyi @@ -0,0 +1,14 @@ + +from typing import TypeVar, Callable, Union, Tuple, Any, Optional, SupportsInt, Hashable, List + + +_Type = TypeVar("_Type", bound=type) +_Reduce = Union[Tuple[Callable[..., _Type], Tuple[Any, ...]], Tuple[Callable[..., _Type], Tuple[Any, ...], Optional[Any]]] + +__all__: List[str] + +def pickle(ob_type: _Type, pickle_function: Callable[[_Type], Union[str, _Reduce[_Type]]], constructor_ob: Optional[Callable[[_Reduce[_Type]], _Type]] = ...) -> None: ... +def constructor(object: Callable[[_Reduce[_Type]], _Type]) -> 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/stdlib/python2/dircache.pyi b/mypy/stdlib/python2/dircache.pyi new file mode 100644 index 000000000000..ac6732b6c16a --- /dev/null +++ b/mypy/stdlib/python2/dircache.pyi @@ -0,0 +1,10 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/dircache.py + +from typing import List, MutableSequence, Text, Union + +def reset() -> None: ... +def listdir(path: Text) -> List[str]: ... + +opendir = listdir + +def annotate(head: Text, list: Union[MutableSequence[str], MutableSequence[Text], MutableSequence[Union[str, Text]]]) -> None: ... diff --git a/mypy/stdlib/python2/distutils/__init__.pyi b/mypy/stdlib/python2/distutils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/python2/distutils/emxccompiler.pyi b/mypy/stdlib/python2/distutils/emxccompiler.pyi new file mode 100644 index 000000000000..97e4a29adda8 --- /dev/null +++ b/mypy/stdlib/python2/distutils/emxccompiler.pyi @@ -0,0 +1,5 @@ +# Stubs for emxccompiler + +from distutils.unixccompiler import UnixCCompiler + +class EMXCCompiler(UnixCCompiler): ... diff --git a/mypy/stdlib/python2/dummy_thread.pyi b/mypy/stdlib/python2/dummy_thread.pyi new file mode 100644 index 000000000000..28041002a708 --- /dev/null +++ b/mypy/stdlib/python2/dummy_thread.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +class error(Exception): + def __init__(self, *args: Any) -> None: ... + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/mypy/stdlib/python2/email/MIMEText.pyi b/mypy/stdlib/python2/email/MIMEText.pyi new file mode 100644 index 000000000000..3b059778aa66 --- /dev/null +++ b/mypy/stdlib/python2/email/MIMEText.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/stdlib/python2/email/__init__.pyi b/mypy/stdlib/python2/email/__init__.pyi new file mode 100644 index 000000000000..384d9567f7b0 --- /dev/null +++ b/mypy/stdlib/python2/email/__init__.pyi @@ -0,0 +1,6 @@ +from typing import IO, Any, AnyStr + +def message_from_string(s: AnyStr, *args, **kwargs): ... +def message_from_bytes(s: str, *args, **kwargs): ... +def message_from_file(fp: IO[AnyStr], *args, **kwargs): ... +def message_from_binary_file(fp: IO[str], *args, **kwargs): ... diff --git a/mypy/stdlib/python2/email/_parseaddr.pyi b/mypy/stdlib/python2/email/_parseaddr.pyi new file mode 100644 index 000000000000..424ade705f77 --- /dev/null +++ b/mypy/stdlib/python2/email/_parseaddr.pyi @@ -0,0 +1,40 @@ +from typing import Any, Optional + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... +def quote(str): ... + +class AddrlistClass: + specials: Any + pos: Any + LWS: Any + CR: Any + FWS: Any + atomends: Any + phraseends: Any + field: Any + commentlist: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: bool = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... diff --git a/mypy/stdlib/python2/email/base64mime.pyi b/mypy/stdlib/python2/email/base64mime.pyi new file mode 100644 index 000000000000..f05003b8d5a7 --- /dev/null +++ b/mypy/stdlib/python2/email/base64mime.pyi @@ -0,0 +1,8 @@ +def base64_len(s: bytes) -> int: ... +def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ... +def encode(s, binary=..., maxlinelen=..., eol=...): ... +body_encode = encode +encodestring = encode +def decode(s, convert_eols=...): ... +body_decode = decode +decodestring = decode diff --git a/mypy/stdlib/python2/email/charset.pyi b/mypy/stdlib/python2/email/charset.pyi new file mode 100644 index 000000000000..88b5f88d1843 --- /dev/null +++ b/mypy/stdlib/python2/email/charset.pyi @@ -0,0 +1,26 @@ +def add_charset(charset, header_enc=..., body_enc=..., output_charset=...) -> None: ... +def add_alias(alias, canonical) -> None: ... +def add_codec(charset, codecname) -> None: ... + +QP: int # undocumented +BASE64: int # undocumented +SHORTEST: int # undocumented + +class Charset: + input_charset = ... + header_encoding = ... + body_encoding = ... + output_charset = ... + input_codec = ... + output_codec = ... + def __init__(self, input_charset=...) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def get_body_encoding(self): ... + def convert(self, s): ... + def to_splittable(self, s): ... + def from_splittable(self, ustr, to_output: bool = ...): ... + def get_output_charset(self): ... + def encoded_header_len(self, s): ... + def header_encode(self, s, convert: bool = ...): ... + def body_encode(self, s, convert: bool = ...): ... diff --git a/mypy/stdlib/python2/email/encoders.pyi b/mypy/stdlib/python2/email/encoders.pyi new file mode 100644 index 000000000000..5670cbaf08ed --- /dev/null +++ b/mypy/stdlib/python2/email/encoders.pyi @@ -0,0 +1,4 @@ +def encode_base64(msg) -> None: ... +def encode_quopri(msg) -> None: ... +def encode_7or8bit(msg) -> None: ... +def encode_noop(msg) -> None: ... diff --git a/mypy/stdlib/python2/email/feedparser.pyi b/mypy/stdlib/python2/email/feedparser.pyi new file mode 100644 index 000000000000..51f825939347 --- /dev/null +++ b/mypy/stdlib/python2/email/feedparser.pyi @@ -0,0 +1,18 @@ +class BufferedSubFile: + def __init__(self) -> None: ... + def push_eof_matcher(self, pred) -> None: ... + def pop_eof_matcher(self): ... + def close(self) -> None: ... + def readline(self): ... + def unreadline(self, line) -> None: ... + def push(self, data): ... + def pushlines(self, lines) -> None: ... + def is_closed(self): ... + def __iter__(self): ... + def next(self): ... + + +class FeedParser: + def __init__(self, _factory=...) -> None: ... + def feed(self, data) -> None: ... + def close(self): ... diff --git a/mypy/stdlib/python2/email/generator.pyi b/mypy/stdlib/python2/email/generator.pyi new file mode 100644 index 000000000000..96cfe2d214a5 --- /dev/null +++ b/mypy/stdlib/python2/email/generator.pyi @@ -0,0 +1,9 @@ +class Generator: + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ...) -> None: ... + def write(self, s) -> None: ... + def flatten(self, msg, unixfrom: bool = ...) -> None: ... + def clone(self, fp): ... + + +class DecodedGenerator(Generator): + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ..., fmt=...) -> None: ... diff --git a/mypy/stdlib/python2/email/header.pyi b/mypy/stdlib/python2/email/header.pyi new file mode 100644 index 000000000000..69c936300cce --- /dev/null +++ b/mypy/stdlib/python2/email/header.pyi @@ -0,0 +1,11 @@ +def decode_header(header): ... +def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ... + +class Header: + def __init__(self, s=..., charset=..., maxlinelen=..., header_name=..., continuation_ws=..., + errors=...) -> None: ... + def __unicode__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def append(self, s, charset=..., errors=...) -> None: ... + def encode(self, splitchars=...): ... diff --git a/mypy/stdlib/python2/email/iterators.pyi b/mypy/stdlib/python2/email/iterators.pyi new file mode 100644 index 000000000000..5002644117a4 --- /dev/null +++ b/mypy/stdlib/python2/email/iterators.pyi @@ -0,0 +1,5 @@ +from typing import Any, Generator + +def walk(self) -> Generator[Any, Any, Any]: ... +def body_line_iterator(msg, decode: bool = ...) -> Generator[Any, Any, Any]: ... +def typed_subpart_iterator(msg, maintype=..., subtype=...) -> Generator[Any, Any, Any]: ... diff --git a/mypy/stdlib/python2/email/message.pyi b/mypy/stdlib/python2/email/message.pyi new file mode 100644 index 000000000000..642bba7c0102 --- /dev/null +++ b/mypy/stdlib/python2/email/message.pyi @@ -0,0 +1,45 @@ +from typing import Any, Generator + +class Message: + preamble = ... + epilogue = ... + defects = ... + def __init__(self): ... + def as_string(self, unixfrom=...): ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom) -> None: ... + def get_unixfrom(self): ... + def attach(self, payload) -> None: ... + def get_payload(self, i=..., decode: bool = ...): ... + def set_payload(self, payload, charset=...) -> None: ... + def set_charset(self, charset): ... + def get_charset(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, val) -> None: ... + def __delitem__(self, name) -> None: ... + def __contains__(self, name): ... + def has_key(self, name) -> bool: ... + def keys(self): ... + def values(self): ... + def items(self): ... + def get(self, name, failobj=...): ... + def get_all(self, name, failobj=...): ... + def add_header(self, _name, _value, **_params) -> None: ... + def replace_header(self, _name, _value) -> None: ... + def get_content_type(self): ... + def get_content_maintype(self): ... + def get_content_subtype(self): ... + def get_default_type(self): ... + def set_default_type(self, ctype) -> None: ... + def get_params(self, failobj=..., header=..., unquote: bool = ...): ... + def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... + def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... + def del_param(self, param, header=..., requote: bool = ...): ... + def set_type(self, type, header=..., requote: bool = ...): ... + def get_filename(self, failobj=...): ... + def get_boundary(self, failobj=...): ... + def set_boundary(self, boundary) -> None: ... + def get_content_charset(self, failobj=...): ... + def get_charsets(self, failobj=...): ... + def walk(self) -> Generator[Any, Any, Any]: ... diff --git a/mypy/stdlib/python2/email/mime/__init__.pyi b/mypy/stdlib/python2/email/mime/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/python2/email/mime/application.pyi b/mypy/stdlib/python2/email/mime/application.pyi new file mode 100644 index 000000000000..99da67287bd5 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/application.pyi @@ -0,0 +1,11 @@ +# Stubs for email.mime.application + +from typing import Callable, Optional, Tuple, Union +from email.mime.nonmultipart import MIMENonMultipart + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEApplication(MIMENonMultipart): + def __init__(self, _data: bytes, _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + **_params: _ParamsType) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/audio.pyi b/mypy/stdlib/python2/email/mime/audio.pyi new file mode 100644 index 000000000000..406ade11b362 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/audio.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEAudio(MIMENonMultipart): + def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/base.pyi b/mypy/stdlib/python2/email/mime/base.pyi new file mode 100644 index 000000000000..4bde4f073395 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/base.pyi @@ -0,0 +1,4 @@ +from email import message + +class MIMEBase(message.Message): + def __init__(self, _maintype, _subtype, **_params) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/image.pyi b/mypy/stdlib/python2/email/mime/image.pyi new file mode 100644 index 000000000000..2dfb098b8567 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/image.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEImage(MIMENonMultipart): + def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/message.pyi b/mypy/stdlib/python2/email/mime/message.pyi new file mode 100644 index 000000000000..33552faf2ca6 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/message.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEMessage(MIMENonMultipart): + def __init__(self, _msg, _subtype=...) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/multipart.pyi b/mypy/stdlib/python2/email/mime/multipart.pyi new file mode 100644 index 000000000000..0a7d3fa8acb0 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/multipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMEMultipart(MIMEBase): + def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ... diff --git a/mypy/stdlib/python2/email/mime/nonmultipart.pyi b/mypy/stdlib/python2/email/mime/nonmultipart.pyi new file mode 100644 index 000000000000..04d130e3da88 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/nonmultipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMENonMultipart(MIMEBase): + def attach(self, payload): ... diff --git a/mypy/stdlib/python2/email/mime/text.pyi b/mypy/stdlib/python2/email/mime/text.pyi new file mode 100644 index 000000000000..3b059778aa66 --- /dev/null +++ b/mypy/stdlib/python2/email/mime/text.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/stdlib/python2/email/parser.pyi b/mypy/stdlib/python2/email/parser.pyi new file mode 100644 index 000000000000..4f2282834ca5 --- /dev/null +++ b/mypy/stdlib/python2/email/parser.pyi @@ -0,0 +1,10 @@ +from .feedparser import FeedParser as FeedParser # not in __all__ but listed in documentation + +class Parser: + def __init__(self, *args, **kws) -> None: ... + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... + +class HeaderParser(Parser): + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... diff --git a/mypy/stdlib/python2/email/quoprimime.pyi b/mypy/stdlib/python2/email/quoprimime.pyi new file mode 100644 index 000000000000..3f2963c06e6d --- /dev/null +++ b/mypy/stdlib/python2/email/quoprimime.pyi @@ -0,0 +1,18 @@ +def header_quopri_check(c): ... +def body_quopri_check(c): ... +def header_quopri_len(s): ... +def body_quopri_len(str): ... +def unquote(s): ... +def quote(c): ... +def header_encode(header, charset: str = ..., keep_eols: bool = ..., maxlinelen: int = ..., eol=...): ... +def encode(body, binary: bool = ..., maxlinelen: int = ..., eol=...): ... + +body_encode = encode +encodestring = encode + +def decode(encoded, eol=...): ... + +body_decode = decode +decodestring = decode + +def header_decode(s): ... diff --git a/mypy/stdlib/python2/email/utils.pyi b/mypy/stdlib/python2/email/utils.pyi new file mode 100644 index 000000000000..7b868efce86c --- /dev/null +++ b/mypy/stdlib/python2/email/utils.pyi @@ -0,0 +1,19 @@ +from email._parseaddr import AddressList as _AddressList +from email._parseaddr import mktime_tz as mktime_tz +from email._parseaddr import parsedate as _parsedate +from email._parseaddr import parsedate_tz as _parsedate_tz +from quopri import decodestring as _qdecode +from typing import Optional, Any + +def formataddr(pair): ... +def getaddresses(fieldvalues): ... +def formatdate(timeval: Optional[Any] = ..., localtime: bool = ..., usegmt: bool = ...): ... +def make_msgid(idstring: Optional[Any] = ...): ... +def parsedate(data): ... +def parsedate_tz(data): ... +def parseaddr(addr): ... +def unquote(str): ... +def decode_rfc2231(s): ... +def encode_rfc2231(s, charset: Optional[Any] = ..., language: Optional[Any] = ...): ... +def decode_params(params): ... +def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ... diff --git a/mypy/stdlib/python2/encodings/__init__.pyi b/mypy/stdlib/python2/encodings/__init__.pyi new file mode 100644 index 000000000000..23e7ea7003f1 --- /dev/null +++ b/mypy/stdlib/python2/encodings/__init__.pyi @@ -0,0 +1,8 @@ +import codecs + +from typing import Any + +def search_function(encoding: str) -> codecs.CodecInfo: ... + +# Explicitly mark this package as incomplete. +def __getattr__(name: str) -> Any: ... diff --git a/mypy/stdlib/python2/encodings/utf_8.pyi b/mypy/stdlib/python2/encodings/utf_8.pyi new file mode 100644 index 000000000000..d38bd58d0e43 --- /dev/null +++ b/mypy/stdlib/python2/encodings/utf_8.pyi @@ -0,0 +1,15 @@ +import codecs +from typing import Text, Tuple + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: Text, final: bool = ...) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... + +class StreamWriter(codecs.StreamWriter): ... +class StreamReader(codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: Text, errors: Text = ...) -> bytes: ... +def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/mypy/stdlib/python2/exceptions.pyi b/mypy/stdlib/python2/exceptions.pyi new file mode 100644 index 000000000000..6e4bafc9a00f --- /dev/null +++ b/mypy/stdlib/python2/exceptions.pyi @@ -0,0 +1,48 @@ +from __builtin__ import ArithmeticError as ArithmeticError +from __builtin__ import AssertionError as AssertionError +from __builtin__ import AttributeError as AttributeError +from __builtin__ import BaseException as BaseException +from __builtin__ import BufferError as BufferError +from __builtin__ import BytesWarning as BytesWarning +from __builtin__ import DeprecationWarning as DeprecationWarning +from __builtin__ import EOFError as EOFError +from __builtin__ import EnvironmentError as EnvironmentError +from __builtin__ import Exception as Exception +from __builtin__ import FloatingPointError as FloatingPointError +from __builtin__ import FutureWarning as FutureWarning +from __builtin__ import GeneratorExit as GeneratorExit +from __builtin__ import IOError as IOError +from __builtin__ import ImportError as ImportError +from __builtin__ import ImportWarning as ImportWarning +from __builtin__ import IndentationError as IndentationError +from __builtin__ import IndexError as IndexError +from __builtin__ import KeyError as KeyError +from __builtin__ import KeyboardInterrupt as KeyboardInterrupt +from __builtin__ import LookupError as LookupError +from __builtin__ import MemoryError as MemoryError +from __builtin__ import NameError as NameError +from __builtin__ import NotImplementedError as NotImplementedError +from __builtin__ import OSError as OSError +from __builtin__ import OverflowError as OverflowError +from __builtin__ import PendingDeprecationWarning as PendingDeprecationWarning +from __builtin__ import ReferenceError as ReferenceError +from __builtin__ import RuntimeError as RuntimeError +from __builtin__ import RuntimeWarning as RuntimeWarning +from __builtin__ import StandardError as StandardError +from __builtin__ import StopIteration as StopIteration +from __builtin__ import SyntaxError as SyntaxError +from __builtin__ import SyntaxWarning as SyntaxWarning +from __builtin__ import SystemError as SystemError +from __builtin__ import SystemExit as SystemExit +from __builtin__ import TabError as TabError +from __builtin__ import TypeError as TypeError +from __builtin__ import UnboundLocalError as UnboundLocalError +from __builtin__ import UnicodeError as UnicodeError +from __builtin__ import UnicodeDecodeError as UnicodeDecodeError +from __builtin__ import UnicodeEncodeError as UnicodeEncodeError +from __builtin__ import UnicodeTranslateError as UnicodeTranslateError +from __builtin__ import UnicodeWarning as UnicodeWarning +from __builtin__ import UserWarning as UserWarning +from __builtin__ import ValueError as ValueError +from __builtin__ import Warning as Warning +from __builtin__ import ZeroDivisionError as ZeroDivisionError diff --git a/mypy/stdlib/python2/fcntl.pyi b/mypy/stdlib/python2/fcntl.pyi new file mode 100644 index 000000000000..a8f054cc81e0 --- /dev/null +++ b/mypy/stdlib/python2/fcntl.pyi @@ -0,0 +1,85 @@ +from typing import Any, Union +from _typeshed import FileDescriptorLike + +FASYNC: int +FD_CLOEXEC: int + +DN_ACCESS: int +DN_ATTRIB: int +DN_CREATE: int +DN_DELETE: int +DN_MODIFY: int +DN_MULTISHOT: int +DN_RENAME: int +F_DUPFD: int +F_EXLCK: int +F_GETFD: int +F_GETFL: int +F_GETLEASE: int +F_GETLK: int +F_GETLK64: int +F_GETOWN: int +F_GETSIG: int +F_NOTIFY: int +F_RDLCK: int +F_SETFD: int +F_SETFL: int +F_SETLEASE: int +F_SETLK: int +F_SETLK64: int +F_SETLKW: int +F_SETLKW64: int +F_SETOWN: int +F_SETSIG: int +F_SHLCK: int +F_UNLCK: int +F_WRLCK: int +I_ATMARK: int +I_CANPUT: int +I_CKBAND: int +I_FDINSERT: int +I_FIND: int +I_FLUSH: int +I_FLUSHBAND: int +I_GETBAND: int +I_GETCLTIME: int +I_GETSIG: int +I_GRDOPT: int +I_GWROPT: int +I_LINK: int +I_LIST: int +I_LOOK: int +I_NREAD: int +I_PEEK: int +I_PLINK: int +I_POP: int +I_PUNLINK: int +I_PUSH: int +I_RECVFD: int +I_SENDFD: int +I_SETCLTIME: int +I_SETSIG: int +I_SRDOPT: int +I_STR: int +I_SWROPT: int +I_UNLINK: int +LOCK_EX: int +LOCK_MAND: int +LOCK_NB: int +LOCK_READ: int +LOCK_RW: int +LOCK_SH: int +LOCK_UN: int +LOCK_WRITE: int + +# TODO All these return either int or bytes depending on the value of +# cmd (not on the type of arg). +def fcntl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ...) -> Any: ... + +# TODO: arg: int or read-only buffer interface or read-write buffer interface +def ioctl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ..., + mutate_flag: bool = ...) -> Any: ... + +def flock(fd: FileDescriptorLike, op: int) -> None: ... +def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., + whence: int = ...) -> Any: ... diff --git a/mypy/stdlib/python2/fnmatch.pyi b/mypy/stdlib/python2/fnmatch.pyi new file mode 100644 index 000000000000..e933b7b2cb62 --- /dev/null +++ b/mypy/stdlib/python2/fnmatch.pyi @@ -0,0 +1,8 @@ +from typing import AnyStr, Iterable, List, Union + +_EitherStr = Union[str, unicode] + +def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... +def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/python2/functools.pyi b/mypy/stdlib/python2/functools.pyi new file mode 100644 index 000000000000..42bc622ebd1a --- /dev/null +++ b/mypy/stdlib/python2/functools.pyi @@ -0,0 +1,33 @@ +# Stubs for functools (Python 2.7) + +# NOTE: These are incomplete! + +from abc import ABCMeta, abstractmethod +from typing import Any, Callable, Generic, Dict, Iterable, Optional, Sequence, Tuple, Type, TypeVar, overload + +_AnyCallable = Callable[..., Any] + +_T = TypeVar("_T") +_S = TypeVar("_S") +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... + +WRAPPER_ASSIGNMENTS: Sequence[str] +WRAPPER_UPDATES: Sequence[str] + +def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., + updated: Sequence[str] = ...) -> _AnyCallable: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... +def total_ordering(cls: Type[_T]) -> Type[_T]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... + +class partial(Generic[_T]): + func = ... # Callable[..., _T] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/stdlib/python2/future_builtins.pyi b/mypy/stdlib/python2/future_builtins.pyi new file mode 100644 index 000000000000..a9b25b2fec6e --- /dev/null +++ b/mypy/stdlib/python2/future_builtins.pyi @@ -0,0 +1,14 @@ +from typing import Any + +from itertools import ifilter as filter +from itertools import imap as map +from itertools import izip as zip + + +def ascii(obj: Any) -> str: ... + + +def hex(x: int) -> str: ... + + +def oct(x: int) -> str: ... diff --git a/mypy/stdlib/python2/gc.pyi b/mypy/stdlib/python2/gc.pyi new file mode 100644 index 000000000000..cdfae7491dfb --- /dev/null +++ b/mypy/stdlib/python2/gc.pyi @@ -0,0 +1,29 @@ +# Stubs for gc + +from typing import Any, List, Tuple + + +def enable() -> None: ... +def disable() -> None: ... +def isenabled() -> bool: ... +def collect(generation: int = ...) -> int: ... +def set_debug(flags: int) -> None: ... +def get_debug() -> int: ... +def get_objects() -> List[Any]: ... +def set_threshold(threshold0: int, threshold1: int = ..., + threshold2: int = ...) -> None: ... +def get_count() -> Tuple[int, int, int]: ... +def get_threshold() -> Tuple[int, int, int]: ... +def get_referrers(*objs: Any) -> List[Any]: ... +def get_referents(*objs: Any) -> List[Any]: ... +def is_tracked(obj: Any) -> bool: ... + +garbage: List[Any] + +DEBUG_STATS: int +DEBUG_COLLECTABLE: int +DEBUG_UNCOLLECTABLE: int +DEBUG_INSTANCES: int +DEBUG_OBJECTS: int +DEBUG_SAVEALL: int +DEBUG_LEAK: int diff --git a/mypy/stdlib/python2/getopt.pyi b/mypy/stdlib/python2/getopt.pyi new file mode 100644 index 000000000000..370d4d5c1cba --- /dev/null +++ b/mypy/stdlib/python2/getopt.pyi @@ -0,0 +1,12 @@ +from typing import List, Tuple + +class GetoptError(Exception): + opt: str + msg: str + def __init__(self, msg: str, opt: str = ...) -> None: ... + def __str__(self) -> str: ... + +error = GetoptError + +def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/mypy/stdlib/python2/getpass.pyi b/mypy/stdlib/python2/getpass.pyi new file mode 100644 index 000000000000..011fc8e7924c --- /dev/null +++ b/mypy/stdlib/python2/getpass.pyi @@ -0,0 +1,8 @@ +# Stubs for getpass (Python 2) + +from typing import Any, IO + +class GetPassWarning(UserWarning): ... + +def getpass(prompt: str = ..., stream: IO[Any] = ...) -> str: ... +def getuser() -> str: ... diff --git a/mypy/stdlib/python2/gettext.pyi b/mypy/stdlib/python2/gettext.pyi new file mode 100644 index 000000000000..c7bfceb7b82c --- /dev/null +++ b/mypy/stdlib/python2/gettext.pyi @@ -0,0 +1,41 @@ +from typing import Any, Container, Dict, IO, List, Optional, Sequence, Type, Union + +def bindtextdomain(domain: str, localedir: str = ...) -> str: ... +def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... +def textdomain(domain: str = ...) -> str: ... +def gettext(message: str) -> str: ... +def lgettext(message: str) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def ldgettext(domain: str, message: str) -> str: ... +def ngettext(singular: str, plural: str, n: int) -> str: ... +def lngettext(singular: str, plural: str, n: int) -> str: ... +def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... +def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... + +class NullTranslations(object): + def __init__(self, fp: IO[str] = ...) -> None: ... + def _parse(self, fp: IO[str]) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def lgettext(self, message: str) -> str: ... + def ugettext(self, message: Union[str, unicode]) -> unicode: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def lngettext(self, singular: str, plural: str, n: int) -> str: ... + def ungettext(self, singular: Union[str, unicode], plural: Union[str, unicode], n: int) -> unicode: ... + def info(self) -> Dict[str, str]: ... + def charset(self) -> Optional[str]: ... + def output_charset(self) -> Optional[str]: ... + def set_output_charset(self, charset: Optional[str]) -> None: ... + def install(self, unicode: bool = ..., names: Container[str] = ...) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC: int + BE_MAGIC: int + +def find(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., + all: Any = ...) -> Optional[Union[str, List[str]]]: ... + +def translation(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., + class_: Optional[Type[NullTranslations]] = ..., fallback: bool = ..., codeset: Optional[str] = ...) -> NullTranslations: ... +def install(domain: str, localedir: Optional[str] = ..., unicode: bool = ..., codeset: Optional[str] = ..., + names: Container[str] = ...) -> None: ... diff --git a/mypy/stdlib/python2/glob.pyi b/mypy/stdlib/python2/glob.pyi new file mode 100644 index 000000000000..5caa166f8e26 --- /dev/null +++ b/mypy/stdlib/python2/glob.pyi @@ -0,0 +1,7 @@ +from typing import List, Iterator, Union, AnyStr + +def glob(pathname: AnyStr) -> List[AnyStr]: ... +def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... +def glob1(dirname: Union[str, unicode], pattern: AnyStr) -> List[AnyStr]: ... +def glob0(dirname: Union[str, unicode], basename: AnyStr) -> List[AnyStr]: ... +def has_magic(s: Union[str, unicode]) -> bool: ... # undocumented diff --git a/mypy/stdlib/python2/gzip.pyi b/mypy/stdlib/python2/gzip.pyi new file mode 100644 index 000000000000..50c38e426208 --- /dev/null +++ b/mypy/stdlib/python2/gzip.pyi @@ -0,0 +1,37 @@ +from typing import Any, IO, Text +import io + +class GzipFile(io.BufferedIOBase): + myfileobj: Any + max_read_chunk: Any + mode: Any + extrabuf: Any + extrasize: Any + extrastart: Any + name: Any + min_readsize: Any + compress: Any + fileobj: Any + offset: Any + mtime: Any + def __init__(self, filename: str = ..., mode: Text = ..., compresslevel: int = ..., + fileobj: IO[str] = ..., mtime: float = ...) -> None: ... + @property + def filename(self): ... + size: Any + crc: Any + def write(self, data): ... + def read(self, size=...): ... + @property + def closed(self): ... + def close(self): ... + def flush(self, zlib_mode=...): ... + def fileno(self): ... + def rewind(self): ... + def readable(self): ... + def writable(self): ... + def seekable(self): ... + def seek(self, offset, whence=...): ... + def readline(self, size=...): ... + +def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ... diff --git a/mypy/stdlib/python2/hashlib.pyi b/mypy/stdlib/python2/hashlib.pyi new file mode 100644 index 000000000000..70423742ea61 --- /dev/null +++ b/mypy/stdlib/python2/hashlib.pyi @@ -0,0 +1,31 @@ +# Stubs for hashlib (Python 2) + +from typing import Tuple, Union + +_DataType = Union[str, unicode, bytearray, buffer, memoryview] + +class _hash(object): # This is not actually in the module namespace. + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, arg: _DataType = ...) -> None: ... + def update(self, arg: _DataType) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> _hash: ... + +def new(name: str, data: str = ...) -> _hash: ... + +def md5(s: _DataType = ...) -> _hash: ... +def sha1(s: _DataType = ...) -> _hash: ... +def sha224(s: _DataType = ...) -> _hash: ... +def sha256(s: _DataType = ...) -> _hash: ... +def sha384(s: _DataType = ...) -> _hash: ... +def sha512(s: _DataType = ...) -> _hash: ... + +algorithms: Tuple[str, ...] +algorithms_guaranteed: Tuple[str, ...] +algorithms_available: Tuple[str, ...] + +def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/mypy/stdlib/python2/heapq.pyi b/mypy/stdlib/python2/heapq.pyi new file mode 100644 index 000000000000..0e706c5f6ca3 --- /dev/null +++ b/mypy/stdlib/python2/heapq.pyi @@ -0,0 +1,18 @@ +from typing import TypeVar, List, Iterable, Any, Callable, Optional, Protocol + +_T = TypeVar('_T') + +class _Sortable(Protocol): + def __lt__(self: _T, other: _T) -> bool: ... + +def cmp_lt(x, y) -> bool: ... +def heappush(heap: List[_T], item: _T) -> None: ... +def heappop(heap: List[_T]) -> _T: ... +def heappushpop(heap: List[_T], item: _T) -> _T: ... +def heapify(x: List[_T]) -> None: ... +def heapreplace(heap: List[_T], item: _T) -> _T: ... +def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... +def nlargest(n: int, iterable: Iterable[_T], + key: Optional[Callable[[_T], _Sortable]] = ...) -> List[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], + key: Optional[Callable[[_T], _Sortable]] = ...) -> List[_T]: ... diff --git a/mypy/stdlib/python2/htmlentitydefs.pyi b/mypy/stdlib/python2/htmlentitydefs.pyi new file mode 100644 index 000000000000..749b3039dfc3 --- /dev/null +++ b/mypy/stdlib/python2/htmlentitydefs.pyi @@ -0,0 +1,5 @@ +from typing import Dict + +name2codepoint: Dict[str, int] +codepoint2name: Dict[int, str] +entitydefs: Dict[str, str] diff --git a/mypy/stdlib/python2/httplib.pyi b/mypy/stdlib/python2/httplib.pyi new file mode 100644 index 000000000000..4e3843c1414d --- /dev/null +++ b/mypy/stdlib/python2/httplib.pyi @@ -0,0 +1,205 @@ +# Stubs for httplib (Python 2) +# +# Generated by stubgen and manually massaged a bit. +# Needs lots more work! + +from typing import Any, Dict, Optional, Protocol +import mimetools +import ssl + +class HTTPMessage(mimetools.Message): + def addcontinue(self, key: str, more: str) -> None: ... + dict: Dict[str, str] + def addheader(self, key: str, value: str) -> None: ... + unixfrom: str + headers: Any + status: str + seekable: bool + def readheaders(self) -> None: ... + +class HTTPResponse: + fp: Any + debuglevel: Any + strict: Any + msg: Any + version: Any + status: Any + reason: Any + chunked: Any + chunk_left: Any + length: Any + will_close: Any + def __init__(self, sock, debuglevel: int = ..., strict: int = ..., method: Optional[Any] = ..., + buffering: bool = ...) -> None: ... + def begin(self): ... + def close(self): ... + def isclosed(self): ... + def read(self, amt: Optional[Any] = ...): ... + def fileno(self): ... + def getheader(self, name, default: Optional[Any] = ...): ... + def getheaders(self): ... + +# This is an API stub only for HTTPConnection and HTTPSConnection, as used in +# urllib2.AbstractHTTPHandler.do_open, which takes either the class +# HTTPConnection or the class HTTPSConnection, *not* an instance of either +# class. do_open does not use all of the parameters of HTTPConnection.__init__ +# or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the +# parameters that do_open does use. +class HTTPConnectionProtocol(Protocol): + def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ... + +class HTTPConnection: + response_class: Any + default_port: Any + auto_open: Any + debuglevel: Any + strict: Any + timeout: Any + source_address: Any + sock: Any + host: str = ... + port: int = ... + def __init__(self, host, port: Optional[Any] = ..., strict: Optional[Any] = ..., timeout=..., + source_address: Optional[Any] = ...) -> None: ... + def set_tunnel(self, host, port: Optional[Any] = ..., headers: Optional[Any] = ...): ... + def set_debuglevel(self, level): ... + def connect(self): ... + def close(self): ... + def send(self, data): ... + def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ... + def putheader(self, header, *values): ... + def endheaders(self, message_body: Optional[Any] = ...): ... + def request(self, method, url, body: Optional[Any] = ..., headers=...): ... + def getresponse(self, buffering: bool = ...): ... + +class HTTP: + debuglevel: Any + def __init__(self, host: str = ..., port: Optional[Any] = ..., strict: Optional[Any] = ...) -> None: ... + def connect(self, host: Optional[Any] = ..., port: Optional[Any] = ...): ... + def getfile(self): ... + file: Any + headers: Any + def getreply(self, buffering: bool = ...): ... + def close(self): ... + +class HTTPSConnection(HTTPConnection): + default_port: Any + key_file: Any + cert_file: Any + def __init__(self, host, port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., + strict: Optional[Any] = ..., timeout=..., source_address: Optional[Any] = ..., + context: Optional[Any] = ...) -> None: ... + sock: Any + def connect(self): ... + +class HTTPS(HTTP): + key_file: Any + cert_file: Any + def __init__(self, host: str = ..., port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., strict: Optional[Any] = ..., context: Optional[Any] = ...) -> None: ... + +class HTTPException(Exception): ... +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... + +class UnknownProtocol(HTTPException): + args: Any + version: Any + def __init__(self, version) -> None: ... + +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... + +class IncompleteRead(HTTPException): + args: Any + partial: Any + expected: Any + def __init__(self, partial, expected: Optional[Any] = ...) -> None: ... + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): + args: Any + line: Any + def __init__(self, line) -> None: ... + +class LineTooLong(HTTPException): + def __init__(self, line_type) -> None: ... + +error: Any + +class LineAndFileWrapper: + def __init__(self, line, file) -> None: ... + def __getattr__(self, attr): ... + def read(self, amt: Optional[Any] = ...): ... + def readline(self): ... + def readlines(self, size: Optional[Any] = ...): ... + +# Constants + +responses: Dict[int, str] + +HTTP_PORT: int +HTTPS_PORT: int + +# status codes +# informational +CONTINUE: int +SWITCHING_PROTOCOLS: int +PROCESSING: int + +# successful +OK: int +CREATED: int +ACCEPTED: int +NON_AUTHORITATIVE_INFORMATION: int +NO_CONTENT: int +RESET_CONTENT: int +PARTIAL_CONTENT: int +MULTI_STATUS: int +IM_USED: int + +# redirection +MULTIPLE_CHOICES: int +MOVED_PERMANENTLY: int +FOUND: int +SEE_OTHER: int +NOT_MODIFIED: int +USE_PROXY: int +TEMPORARY_REDIRECT: int + +# client error +BAD_REQUEST: int +UNAUTHORIZED: int +PAYMENT_REQUIRED: int +FORBIDDEN: int +NOT_FOUND: int +METHOD_NOT_ALLOWED: int +NOT_ACCEPTABLE: int +PROXY_AUTHENTICATION_REQUIRED: int +REQUEST_TIMEOUT: int +CONFLICT: int +GONE: int +LENGTH_REQUIRED: int +PRECONDITION_FAILED: int +REQUEST_ENTITY_TOO_LARGE: int +REQUEST_URI_TOO_LONG: int +UNSUPPORTED_MEDIA_TYPE: int +REQUESTED_RANGE_NOT_SATISFIABLE: int +EXPECTATION_FAILED: int +UNPROCESSABLE_ENTITY: int +LOCKED: int +FAILED_DEPENDENCY: int +UPGRADE_REQUIRED: int + +# server error +INTERNAL_SERVER_ERROR: int +NOT_IMPLEMENTED: int +BAD_GATEWAY: int +SERVICE_UNAVAILABLE: int +GATEWAY_TIMEOUT: int +HTTP_VERSION_NOT_SUPPORTED: int +INSUFFICIENT_STORAGE: int +NOT_EXTENDED: int diff --git a/mypy/stdlib/python2/imp.pyi b/mypy/stdlib/python2/imp.pyi new file mode 100644 index 000000000000..8ff9e1aed52b --- /dev/null +++ b/mypy/stdlib/python2/imp.pyi @@ -0,0 +1,35 @@ +"""Stubs for the 'imp' module.""" + +from typing import List, Optional, Tuple, Iterable, IO, Any +import types + +C_BUILTIN: int +C_EXTENSION: int +IMP_HOOK: int +PKG_DIRECTORY: int +PY_CODERESOURCE: int +PY_COMPILED: int +PY_FROZEN: int +PY_RESOURCE: int +PY_SOURCE: int +SEARCH_ERROR: int + +def acquire_lock() -> None: ... +def find_module(name: str, path: Iterable[str] = ...) -> Optional[Tuple[IO[Any], str, Tuple[str, str, int]]]: ... +def get_magic() -> str: ... +def get_suffixes() -> List[Tuple[str, str, int]]: ... +def init_builtin(name: str) -> types.ModuleType: ... +def init_frozen(name: str) -> types.ModuleType: ... +def is_builtin(name: str) -> int: ... +def is_frozen(name: str) -> bool: ... +def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... +def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def lock_held() -> bool: ... +def new_module(name: str) -> types.ModuleType: ... +def release_lock() -> None: ... + +class NullImporter: + def __init__(self, path_string: str) -> None: ... + def find_module(self, fullname: str, path: str = ...) -> None: ... diff --git a/mypy/stdlib/python2/importlib.pyi b/mypy/stdlib/python2/importlib.pyi new file mode 100644 index 000000000000..8bb179a4bd9a --- /dev/null +++ b/mypy/stdlib/python2/importlib.pyi @@ -0,0 +1,4 @@ +import types +from typing import Optional, Text + +def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ... diff --git a/mypy/stdlib/python2/inspect.pyi b/mypy/stdlib/python2/inspect.pyi new file mode 100644 index 000000000000..6f6fea49cae7 --- /dev/null +++ b/mypy/stdlib/python2/inspect.pyi @@ -0,0 +1,129 @@ +from types import CodeType, TracebackType, FrameType, FunctionType, MethodType, ModuleType +from typing import Any, Dict, Callable, List, NamedTuple, Optional, Sequence, Tuple, Type, Union, AnyStr + +# Types and members +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + last: int + def tokeneater(self, type: int, token: AnyStr, srow_scol: Tuple[int, int], + erow_ecol: Tuple[int, int], line: AnyStr) -> None: ... + +CO_GENERATOR: int +CO_NESTED: int +CO_NEWLOCALS: int +CO_NOFREE: int +CO_OPTIMIZED: int +CO_VARARGS: int +CO_VARKEYWORDS: int +TPFLAGS_IS_ABSTRACT: int + +class ModuleInfo(NamedTuple): + name: str + suffix: str + mode: str + module_type: int + +def getmembers( + object: object, + predicate: Optional[Callable[[Any], bool]] = ... +) -> List[Tuple[str, Any]]: ... +def getmoduleinfo(path: Union[str, unicode]) -> Optional[ModuleInfo]: ... +def getmodulename(path: AnyStr) -> Optional[AnyStr]: ... + +def ismodule(object: object) -> bool: ... +def isclass(object: object) -> bool: ... +def ismethod(object: object) -> bool: ... +def isfunction(object: object) -> bool: ... +def isgeneratorfunction(object: object) -> bool: ... +def isgenerator(object: object) -> bool: ... +def istraceback(object: object) -> bool: ... +def isframe(object: object) -> bool: ... +def iscode(object: object) -> bool: ... +def isbuiltin(object: object) -> bool: ... +def isroutine(object: object) -> bool: ... +def isabstract(object: object) -> bool: ... +def ismethoddescriptor(object: object) -> bool: ... +def isdatadescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> bool: ... +def ismemberdescriptor(object: object) -> bool: ... + +# Retrieving source code +_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] + +def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getabsfile(object: _SourceObjectType) -> str: ... +def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... +def getdoc(object: object) -> Optional[str]: ... +def getcomments(object: object) -> Optional[str]: ... +def getfile(object: _SourceObjectType) -> str: ... +def getmodule(object: object) -> Optional[ModuleType]: ... +def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... +def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsource(object: _SourceObjectType) -> str: ... +def cleandoc(doc: AnyStr) -> AnyStr: ... +def indentsize(line: Union[str, unicode]) -> int: ... + +# Classes and functions +def getclasstree(classes: List[type], unique: bool = ...) -> List[Union[Tuple[type, Tuple[type, ...]], List[Any]]]: ... + +class ArgSpec(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + defaults: Tuple[Any, ...] + +class ArgInfo(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + locals: Dict[str, Any] + +class Arguments(NamedTuple): + args: List[Union[str, List[Any]]] + varargs: Optional[str] + keywords: Optional[str] + +def getargs(co: CodeType) -> Arguments: ... +def getargspec(func: object) -> ArgSpec: ... +def getargvalues(frame: FrameType) -> ArgInfo: ... +def formatargspec(args, varargs=..., varkw=..., defaults=..., + formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., + join=...) -> str: ... +def formatargvalues(args, varargs=..., varkw=..., defaults=..., + formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., + join=...) -> str: ... +def getmro(cls: type) -> Tuple[type, ...]: ... +def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... + +# The interpreter stack + +class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: Optional[List[str]] + index: Optional[int] # type: ignore + +_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] + +def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... +def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... +def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... + +def currentframe(depth: int = ...) -> FrameType: ... +def stack(context: int = ...) -> List[_FrameInfo]: ... +def trace(context: int = ...) -> List[_FrameInfo]: ... + +class Attribute(NamedTuple): + name: str + kind: str + defining_class: type + object: object + +def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/mypy/stdlib/python2/io.pyi b/mypy/stdlib/python2/io.pyi new file mode 100644 index 000000000000..e6cfb36b41f0 --- /dev/null +++ b/mypy/stdlib/python2/io.pyi @@ -0,0 +1,42 @@ +# Stubs for io + +# Based on https://docs.python.org/2/library/io.html + +# Only a subset of functionality is included. + +from typing import IO, Any, Union +import _io + +from _io import BlockingIOError as BlockingIOError +from _io import BufferedRWPair as BufferedRWPair +from _io import BufferedRandom as BufferedRandom +from _io import BufferedReader as BufferedReader +from _io import BufferedWriter as BufferedWriter +from _io import BytesIO as BytesIO +from _io import DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE +from _io import FileIO as FileIO +from _io import IncrementalNewlineDecoder as IncrementalNewlineDecoder +from _io import StringIO as StringIO +from _io import TextIOWrapper as TextIOWrapper +from _io import UnsupportedOperation as UnsupportedOperation +from _io import open as open + +def _OpenWrapper(file: Union[str, unicode, int], + mode: unicode = ..., buffering: int = ..., encoding: unicode = ..., + errors: unicode = ..., newline: unicode = ..., + closefd: bool = ...) -> IO[Any]: ... + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int + + +class IOBase(_io._IOBase): ... + +class RawIOBase(_io._RawIOBase, IOBase): ... + +class BufferedIOBase(_io._BufferedIOBase, IOBase): ... + +# Note: In the actual io.py, TextIOBase subclasses IOBase. +# (Which we don't do here because we don't want to subclass both TextIO and BinaryIO.) +class TextIOBase(_io._TextIOBase): ... diff --git a/mypy/stdlib/python2/itertools.pyi b/mypy/stdlib/python2/itertools.pyi new file mode 100644 index 000000000000..97e69f8027c1 --- /dev/null +++ b/mypy/stdlib/python2/itertools.pyi @@ -0,0 +1,167 @@ +# Stubs for itertools + +# Based on https://docs.python.org/2/library/itertools.html + +from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, + Union, Sequence, Generic, Optional) + +_T = TypeVar('_T') +_S = TypeVar('_S') + +def count(start: int = ..., + step: int = ...) -> Iterator[int]: ... # more general types? + +class cycle(Iterator[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def next(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + +def repeat(object: _T, times: int = ...) -> Iterator[_T]: ... + +class chain(Iterator[_T], Generic[_T]): + def __init__(self, *iterables: Iterable[_T]) -> None: ... + def next(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + @staticmethod + def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + +def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... +def dropwhile(predicate: Callable[[_T], Any], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilter(predicate: Optional[Callable[[_T], Any]], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilterfalse(predicate: Optional[Callable[[_T], Any]], + iterable: Iterable[_T]) -> Iterator[_T]: ... + +@overload +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +@overload +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... + +@overload +def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +@overload +def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], + step: Optional[int] = ...) -> Iterator[_T]: ... + +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_T6 = TypeVar('_T6') + +@overload +def imap(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... +@overload +def imap(func: Callable[[_T1, _T2], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[_S]: ... +@overload +def imap(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5, _T6], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[..., _S], + iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[_S]: ... + +def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... +def takewhile(predicate: Callable[[_T], Any], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... + +@overload +def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def izip(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, + _T3, _T4]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3], iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, + _T3, _T4, _T5]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3], iter4: Iterable[_T4], + iter5: Iterable[_T5], iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, + _T4, _T5, _T6]]: ... +@overload +def izip(iter1: Iterable[Any], iter2: Iterable[Any], + iter3: Iterable[Any], iter4: Iterable[Any], + iter5: Iterable[Any], iter6: Iterable[Any], + iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... + +def izip_longest(*p: Iterable[Any], + fillvalue: Any = ...) -> Iterator[Any]: ... + +@overload +def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product(iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... + +def permutations(iterable: Iterable[_T], + r: int = ...) -> Iterator[Sequence[_T]]: ... +def combinations(iterable: Iterable[_T], + r: int) -> Iterator[Sequence[_T]]: ... +def combinations_with_replacement(iterable: Iterable[_T], + r: int) -> Iterator[Sequence[_T]]: ... diff --git a/mypy/stdlib/python2/json.pyi b/mypy/stdlib/python2/json.pyi new file mode 100644 index 000000000000..949e3daf7f23 --- /dev/null +++ b/mypy/stdlib/python2/json.pyi @@ -0,0 +1,94 @@ +from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Text, Type +from _typeshed import SupportsRead + +class JSONDecodeError(ValueError): + def dumps(self, obj: Any) -> str: ... + def dump(self, obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... + def loads(self, s: str) -> Any: ... + def load(self, fp: IO[str]) -> Any: ... + +def dumps(obj: Any, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> str: ... + +def dump(obj: Any, + fp: Union[IO[str], IO[Text]], + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> None: ... + +def loads(s: Union[Text, bytes], + encoding: Any = ..., + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +def load(fp: SupportsRead[Union[Text, bytes]], + encoding: Optional[str] = ..., + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +class JSONDecoder(object): + def __init__(self, + encoding: Union[Text, bytes] = ..., + object_hook: Callable[..., Any] = ..., + parse_float: Callable[[str], float] = ..., + parse_int: Callable[[str], int] = ..., + parse_constant: Callable[[str], Any] = ..., + strict: bool = ..., + object_pairs_hook: Callable[..., Any] = ...) -> None: ... + def decode(self, s: Union[Text, bytes], _w: Any = ...) -> Any: ... + def raw_decode(self, s: Union[Text, bytes], idx: int = ...) -> Tuple[Any, Any]: ... + +class JSONEncoder(object): + item_separator: str + key_separator: str + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: Optional[int] + + def __init__(self, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Tuple[Union[Text, bytes], Union[Text, bytes]] = ..., + encoding: Union[Text, bytes] = ..., + default: Callable[..., Any] = ...) -> None: ... + + def default(self, o: Any) -> Any: ... + + def encode(self, o: Any) -> str: ... + + def iterencode(self, o: Any, _one_shot: bool = ...) -> str: ... diff --git a/mypy/stdlib/python2/markupbase.pyi b/mypy/stdlib/python2/markupbase.pyi new file mode 100644 index 000000000000..358ba16c3487 --- /dev/null +++ b/mypy/stdlib/python2/markupbase.pyi @@ -0,0 +1,9 @@ +from typing import Tuple + +class ParserBase(object): + 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/stdlib/python2/md5.pyi b/mypy/stdlib/python2/md5.pyi new file mode 100644 index 000000000000..96eabd146acd --- /dev/null +++ b/mypy/stdlib/python2/md5.pyi @@ -0,0 +1,6 @@ +# Stubs for Python 2.7 md5 stdlib module + +from hashlib import md5 as md5, md5 as new + +blocksize: int +digest_size: int diff --git a/mypy/stdlib/python2/mimetools.pyi b/mypy/stdlib/python2/mimetools.pyi new file mode 100644 index 000000000000..f565202f4f80 --- /dev/null +++ b/mypy/stdlib/python2/mimetools.pyi @@ -0,0 +1,27 @@ +from typing import Any +import rfc822 + +class Message(rfc822.Message): + encodingheader: Any + typeheader: Any + def __init__(self, fp, seekable: int = ...): ... + plisttext: Any + type: Any + maintype: Any + subtype: Any + def parsetype(self): ... + plist: Any + def parseplist(self): ... + def getplist(self): ... + def getparam(self, name): ... + def getparamnames(self): ... + def getencoding(self): ... + def gettype(self): ... + def getmaintype(self): ... + def getsubtype(self): ... + +def choose_boundary(): ... +def decode(input, output, encoding): ... +def encode(input, output, encoding): ... +def copyliteral(input, output): ... +def copybinary(input, output): ... diff --git a/mypy/stdlib/python2/multiprocessing/__init__.pyi b/mypy/stdlib/python2/multiprocessing/__init__.pyi new file mode 100644 index 000000000000..fb00b245c2e5 --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/__init__.pyi @@ -0,0 +1,50 @@ +from typing import Any, Callable, Optional, TypeVar, Iterable + +from multiprocessing import pool +from multiprocessing.process import Process as Process, current_process as current_process, active_children as active_children +from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING +from Queue import Queue as _BaseQueue + +class ProcessError(Exception): ... +class BufferTooShort(ProcessError): ... +class TimeoutError(ProcessError): ... +class AuthenticationError(ProcessError): ... + +_T = TypeVar('_T') + +class Queue(_BaseQueue[_T]): + def __init__(self, maxsize: int = ...) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put_nowait(self, item: _T) -> None: ... + def get_nowait(self) -> _T: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + +def Manager(): ... +def Pipe(duplex: bool = ...): ... +def cpu_count() -> int: ... +def freeze_support(): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def allow_connection_pickling(): ... +def Lock(): ... +def RLock(): ... +def Condition(lock: Optional[Any] = ...): ... +def Semaphore(value: int = ...): ... +def BoundedSemaphore(value: int = ...): ... +def Event(): ... +def JoinableQueue(maxsize: int = ...): ... +def RawValue(typecode_or_type, *args): ... +def RawArray(typecode_or_type, size_or_initializer): ... +def Value(typecode_or_type, *args, **kwds): ... +def Array(typecode_or_type, size_or_initializer, **kwds): ... + +def Pool(processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... diff --git a/mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi b/mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000000..ea41a4cf8ada --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,51 @@ +from typing import Any, Optional, List, Type + +import threading +import sys +import weakref +import array +import itertools + +from multiprocessing import TimeoutError, cpu_count +from multiprocessing.dummy.connection import Pipe +from threading import Lock, RLock, Semaphore, BoundedSemaphore +from threading import Event +from Queue import Queue + + +class DummyProcess(threading.Thread): + _children: weakref.WeakKeyDictionary[Any, Any] + _parent: threading.Thread + _pid: None + _start_called: bool + def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + @property + def exitcode(self) -> Optional[int]: ... + + +Process = DummyProcess + +# This should be threading._Condition but threading.pyi exports it as Condition +class Condition(threading.Condition): + notify_all: Any + +class Namespace(object): + def __init__(self, **kwds) -> None: ... + +class Value(object): + _typecode: Any + _value: Any + value: Any + def __init__(self, typecode, value, lock=...) -> None: ... + def _get(self) -> Any: ... + def _set(self, value) -> None: ... + +JoinableQueue = Queue + +def Array(typecode, sequence, lock=...) -> array.array[Any]: ... +def Manager() -> Any: ... +def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def active_children() -> List[Any]: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/mypy/stdlib/python2/multiprocessing/dummy/connection.pyi b/mypy/stdlib/python2/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000000..663d39434cef --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/dummy/connection.pyi @@ -0,0 +1,26 @@ +from Queue import Queue +from typing import Any, List, Optional, Tuple, Type + +families: List[None] + +class Connection(object): + _in: Any + _out: Any + recv: Any + recv_bytes: Any + send: Any + send_bytes: Any + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout=...) -> Any: ... + +class Listener(object): + _backlog_queue: Optional[Queue[Any]] + address: Any + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + + +def Client(address) -> Connection: ... +def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/stdlib/python2/multiprocessing/pool.pyi b/mypy/stdlib/python2/multiprocessing/pool.pyi new file mode 100644 index 000000000000..014efd452b7a --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/pool.pyi @@ -0,0 +1,54 @@ +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar + +_T = TypeVar('_T', bound=Pool) + +class AsyncResult(): + def get(self, timeout: Optional[float] = ...) -> Any: ... + def wait(self, timeout: Optional[float] = ...) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + +class IMapIterator(Iterator[Any]): + def __iter__(self) -> Iterator[Any]: ... + def next(self, timeout: Optional[float] = ...) -> Any: ... + +class IMapUnorderedIterator(IMapIterator): ... + +class Pool(object): + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> None: ... + def apply(self, + func: Callable[..., Any], + args: Iterable[Any] = ..., + kwds: Dict[str, Any] = ...) -> Any: ... + def apply_async(self, + func: Callable[..., Any], + args: Iterable[Any] = ..., + kwds: Dict[str, Any] = ..., + callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... + def map(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> List[Any]: ... + def map_async(self, func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... + def imap(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> IMapIterator: ... + def imap_unordered(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> IMapIterator: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + +class ThreadPool(Pool): + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ...) -> None: ... diff --git a/mypy/stdlib/python2/multiprocessing/process.pyi b/mypy/stdlib/python2/multiprocessing/process.pyi new file mode 100644 index 000000000000..476b40324fd2 --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/process.pyi @@ -0,0 +1,36 @@ +from typing import Any, Optional + +def current_process(): ... +def active_children(): ... + +class Process: + def __init__(self, group: Optional[Any] = ..., target: Optional[Any] = ..., name: Optional[Any] = ..., args=..., + kwargs=...): ... + def run(self): ... + def start(self): ... + def terminate(self): ... + def join(self, timeout: Optional[Any] = ...): ... + def is_alive(self): ... + @property + def name(self): ... + @name.setter + def name(self, name): ... + @property + def daemon(self): ... + @daemon.setter + def daemon(self, daemonic): ... + @property + def authkey(self): ... + @authkey.setter + def authkey(self, authkey): ... + @property + def exitcode(self): ... + @property + def ident(self): ... + pid: Any + +class AuthenticationString(bytes): + def __reduce__(self): ... + +class _MainProcess(Process): + def __init__(self): ... diff --git a/mypy/stdlib/python2/multiprocessing/util.pyi b/mypy/stdlib/python2/multiprocessing/util.pyi new file mode 100644 index 000000000000..14d44f6e3929 --- /dev/null +++ b/mypy/stdlib/python2/multiprocessing/util.pyi @@ -0,0 +1,29 @@ +from typing import Any, Optional +import threading + +SUBDEBUG: Any +SUBWARNING: Any + +def sub_debug(msg, *args): ... +def debug(msg, *args): ... +def info(msg, *args): ... +def sub_warning(msg, *args): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def get_temp_dir(): ... +def register_after_fork(obj, func): ... + +class Finalize: + def __init__(self, obj, callback, args=..., kwargs: Optional[Any] = ..., exitpriority: Optional[Any] = ...): ... + def __call__(self, wr: Optional[Any] = ...): ... + def cancel(self): ... + def still_active(self): ... + +def is_exiting(): ... + +class ForkAwareThreadLock: + def __init__(self): ... + +class ForkAwareLocal(threading.local): + def __init__(self): ... + def __reduce__(self): ... diff --git a/mypy/stdlib/python2/mutex.pyi b/mypy/stdlib/python2/mutex.pyi new file mode 100644 index 000000000000..fa41bbb4fcec --- /dev/null +++ b/mypy/stdlib/python2/mutex.pyi @@ -0,0 +1,14 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/mutex.py + +from typing import Any, Callable, Deque, TypeVar + +_ArgType = TypeVar('_ArgType') + +class mutex: + locked: bool + queue: Deque[Any] + def __init__(self) -> None: ... + def test(self) -> bool: ... + def testandset(self) -> bool: ... + def lock(self, function: Callable[[_ArgType], Any], argument: _ArgType) -> None: ... + def unlock(self) -> None: ... diff --git a/mypy/stdlib/python2/nturl2path.pyi b/mypy/stdlib/python2/nturl2path.pyi new file mode 100644 index 000000000000..b87b008e4cec --- /dev/null +++ b/mypy/stdlib/python2/nturl2path.pyi @@ -0,0 +1,4 @@ +from typing import AnyStr + +def url2pathname(url: AnyStr) -> AnyStr: ... +def pathname2url(p: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/python2/os/__init__.pyi b/mypy/stdlib/python2/os/__init__.pyi new file mode 100644 index 000000000000..7de81929d4fb --- /dev/null +++ b/mypy/stdlib/python2/os/__init__.pyi @@ -0,0 +1,357 @@ +from builtins import OSError as error +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 +import sys +from typing import ( + Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr, + Optional, Generic, Set, Callable, Text, Sequence, IO, NamedTuple, NoReturn, TypeVar +) +from _typeshed import AnyPath +from . import path as path + +# We need to use something from path, or flake8 and pytype get unhappy +_supports_unicode_filenames = path.supports_unicode_filenames + +_T = TypeVar("_T") + +# ----- os variables ----- + +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 + +O_RDONLY: int +O_WRONLY: int +O_RDWR: int +O_APPEND: int +O_CREAT: int +O_EXCL: int +O_TRUNC: int +# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, +# including tests for mypy, use a more finer way than sys.platform before using these APIs +# See https://github.com/python/typeshed/pull/2286 for discussions +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only +O_NONBLOCK: int # Unix only +O_NOCTTY: int # Unix only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only +O_NOINHERIT: int # Windows only +O_SHORT_LIVED: int # Windows only +O_TEMPORARY: int # Windows only +O_RANDOM: int # Windows only +O_SEQUENTIAL: int # Windows only +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library +O_DIRECTORY: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library +O_LARGEFILE: int # Gnu extension if in C library + +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +linesep: str +devnull: str +name: str + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + def copy(self) -> Dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[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] + pathconf_names: Dict[str, int] + sysconf_names: Dict[str, int] + + EX_OK: int + EX_USAGE: int + EX_DATAERR: int + EX_NOINPUT: int + EX_NOUSER: int + EX_NOHOST: int + EX_UNAVAILABLE: int + EX_SOFTWARE: int + EX_OSERR: int + EX_OSFILE: int + EX_CANTCREAT: int + EX_IOERR: int + EX_TEMPFAIL: int + EX_PROTOCOL: int + EX_NOPERM: int + EX_CONFIG: int + EX_NOTFOUND: int + +P_NOWAIT: int +P_NOWAITO: int +P_WAIT: int +if sys.platform == 'win32': + P_DETACH: int + P_OVERLAY: int + +# wait()/waitpid() options +if sys.platform != 'win32': + WNOHANG: int # Unix only + WCONTINUED: int # some Unix systems + WUNTRACED: int # Unix only + +TMP_MAX: int # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +if sys.version_info >= (3, 6): + from builtins import _PathLike as PathLike # See comment in builtins + +class _StatVFS(NamedTuple): + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(code: int) -> str: ... +def umask(mask: int) -> int: ... + +if sys.platform != 'win32': + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + def getresuid() -> Tuple[int, int, int]: ... + def getresgid() -> Tuple[int, int, int]: ... + def getuid() -> int: ... + def setegid(egid: int) -> None: ... + def seteuid(euid: int) -> None: ... + def setgid(gid: int) -> None: ... + def setgroups(groups: Sequence[int]) -> None: ... + def setpgrp() -> None: ... + def setpgid(pid: int, pgrp: int) -> None: ... + def setregid(rgid: int, egid: int) -> None: ... + def setresgid(rgid: int, egid: int, sgid: int) -> None: ... + def setresuid(ruid: int, euid: int, suid: int) -> None: ... + def setreuid(ruid: int, euid: int) -> None: ... + def getsid(pid: int) -> int: ... + def setsid() -> None: ... + def setuid(uid: int) -> None: ... + def uname() -> Tuple[str, str, str, str, str]: ... + +@overload +def getenv(key: Text) -> Optional[str]: ... +@overload +def getenv(key: Text, default: _T) -> Union[str, _T]: ... +def putenv(key: Union[bytes, Text], value: Union[bytes, Text]) -> None: ... +def unsetenv(key: Union[bytes, Text]) -> None: ... + +def fdopen(fd: int, *args, **kwargs) -> IO[Any]: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def dup(fd: int) -> int: ... +def dup2(fd: int, fd2: int) -> None: ... +def fstat(fd: int) -> Any: ... +def fsync(fd: int) -> None: ... +def lseek(fd: int, pos: int, how: int) -> int: ... +def open(file: AnyPath, 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 fchdir(fd: int) -> 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 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 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: ... +@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: ... +# 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: ... + +if sys.platform != 'win32': + # Unix only + def fchmod(fd: int, mode: int) -> None: ... + def fchown(fd: int, uid: int, gid: int) -> None: ... + if sys.platform != 'darwin': + def fdatasync(fd: int) -> None: ... # Unix only, not Mac + def fpathconf(fd: int, name: Union[str, int]) -> int: ... + def fstatvfs(fd: int) -> _StatVFS: ... + def ftruncate(fd: int, length: int) -> None: ... + def isatty(fd: int) -> bool: ... + def openpty() -> Tuple[int, int]: ... # some flavors of Unix + 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 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: ... + +# 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: ... + +# 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 _exit(n: int) -> NoReturn: ... +def kill(pid: int, sig: int) -> None: ... + +if sys.platform != 'win32': + # Unix only + def fork() -> int: ... + def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def killpg(__pgid: int, __signal: int) -> None: ... + 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 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: ... +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 wait() -> Tuple[int, int]: ... + def wait3(options: int) -> Tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def WCOREDUMP(status: int) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + def confstr(name: Union[str, int]) -> Optional[str]: ... + 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: ... + +P_ALL: int +WEXITED: int +WNOWAIT: int diff --git a/mypy/stdlib/python2/os/path.pyi b/mypy/stdlib/python2/os/path.pyi new file mode 100644 index 000000000000..ef4b48331d89 --- /dev/null +++ b/mypy/stdlib/python2/os/path.pyi @@ -0,0 +1,164 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from genericpath import exists as exists +from _typeshed import StrPath, BytesPath, AnyPath + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyStr) -> AnyStr: ... + @overload + def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(p: AnyStr) -> AnyStr: ... + def dirname(p: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(s: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of StrPath and bytes for sequences + # of BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[AnyPath]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# 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: ... + +# 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: ... + +if sys.version_info < (3, 0): + # 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: ... +elif sys.version_info >= (3, 6): + @overload + def join(a: StrPath, *paths: StrPath) -> Text: ... + @overload + def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +else: + def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... + +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: ... + +if sys.version_info >= (3, 6): + @overload + def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.version_info < (3, 7) and sys.platform == 'win32': + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/python2/os2emxpath.pyi b/mypy/stdlib/python2/os2emxpath.pyi new file mode 100644 index 000000000000..ef4b48331d89 --- /dev/null +++ b/mypy/stdlib/python2/os2emxpath.pyi @@ -0,0 +1,164 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +import os +import sys +from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from genericpath import exists as exists +from _typeshed import StrPath, BytesPath, AnyPath + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == 'win32': + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyStr) -> AnyStr: ... + @overload + def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(p: AnyStr) -> AnyStr: ... + def dirname(p: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(s: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of StrPath and bytes for sequences + # of BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[AnyPath]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# 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: ... + +# 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: ... + +if sys.version_info < (3, 0): + # 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: ... +elif sys.version_info >= (3, 6): + @overload + def join(a: StrPath, *paths: StrPath) -> Text: ... + @overload + def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +else: + def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... + +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: ... + +if sys.version_info >= (3, 6): + @overload + def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.version_info < (3, 7) and sys.platform == 'win32': + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/stdlib/python2/pipes.pyi b/mypy/stdlib/python2/pipes.pyi new file mode 100644 index 000000000000..e25ef3ad945f --- /dev/null +++ b/mypy/stdlib/python2/pipes.pyi @@ -0,0 +1,13 @@ +from typing import Any, IO, AnyStr + +class Template: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, mode: str) -> IO[Any]: ... + def copy(self, infile: str, outfile: str) -> None: ... + +def quote(s: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/python2/platform.pyi b/mypy/stdlib/python2/platform.pyi new file mode 100644 index 000000000000..e6e037804ae2 --- /dev/null +++ b/mypy/stdlib/python2/platform.pyi @@ -0,0 +1,45 @@ +# Stubs for platform (Python 2) +# +# Based on stub generated by stubgen. + +from typing import Any, Optional, Tuple + +__copyright__: Any +DEV_NULL: Any + +def libc_ver(executable=..., lib=..., version=..., chunksize: int = ...): ... +def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name: int = ...): ... +def dist(distname=..., version=..., id=..., supported_dists=...): ... + +class _popen: + tmpfile: Any + pipe: Any + bufsize: Any + mode: Any + def __init__(self, cmd, mode=..., bufsize: Optional[Any] = ...): ... + def read(self): ... + def readlines(self): ... + def close(self, remove=..., error=...): ... + __del__: Any + +def popen(cmd, mode=..., bufsize: Optional[Any] = ...): ... +def win32_ver(release=..., version=..., csd=..., ptype=...): ... +def mac_ver(release=..., versioninfo=..., machine=...): ... +def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ... +def system_alias(system, release, version): ... +def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... +def uname() -> Tuple[str, str, str, str, str, str]: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> Tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> Tuple[str, str]: ... +def python_compiler() -> str: ... +def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/mypy/stdlib/python2/popen2.pyi b/mypy/stdlib/python2/popen2.pyi new file mode 100644 index 000000000000..b39ba5f074b0 --- /dev/null +++ b/mypy/stdlib/python2/popen2.pyi @@ -0,0 +1,28 @@ +from typing import Any, Iterable, List, Optional, Union, TextIO, Tuple, TypeVar + +_T = TypeVar('_T') + + +class Popen3: + sts: int + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + childerr: Optional[TextIO] + def __init__(self, cmd: Iterable[Any] = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... + def __del__(self) -> None: ... + def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ... + def wait(self) -> int: ... + +class Popen4(Popen3): + childerr: None + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... + +def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... +def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... +def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/mypy/stdlib/python2/posix.pyi b/mypy/stdlib/python2/posix.pyi new file mode 100644 index 000000000000..e85a2a55f4c9 --- /dev/null +++ b/mypy/stdlib/python2/posix.pyi @@ -0,0 +1,198 @@ +from typing import AnyStr, Dict, IO, List, Mapping, NamedTuple, Optional, Sequence, Tuple, TypeVar, Union + +error = OSError + +confstr_names: Dict[str, int] +environ: Dict[str, str] +pathconf_names: Dict[str, int] +sysconf_names: Dict[str, int] + +_T = TypeVar("_T") + +EX_CANTCREAT: int +EX_CONFIG: int +EX_DATAERR: int +EX_IOERR: int +EX_NOHOST: int +EX_NOINPUT: int +EX_NOPERM: int +EX_NOUSER: int +EX_OK: int +EX_OSERR: int +EX_OSFILE: int +EX_PROTOCOL: int +EX_SOFTWARE: int +EX_TEMPFAIL: int +EX_UNAVAILABLE: int +EX_USAGE: int +F_OK: int +NGROUPS_MAX: int +O_APPEND: int +O_ASYNC: int +O_CREAT: int +O_DIRECT: int +O_DIRECTORY: int +O_DSYNC: int +O_EXCL: int +O_LARGEFILE: int +O_NDELAY: int +O_NOATIME: int +O_NOCTTY: int +O_NOFOLLOW: int +O_NONBLOCK: int +O_RDONLY: int +O_RDWR: int +O_RSYNC: int +O_SYNC: int +O_TRUNC: int +O_WRONLY: int +R_OK: int +TMP_MAX: int +WCONTINUED: int +WNOHANG: int +WUNTRACED: int +W_OK: int +X_OK: int + +def WCOREDUMP(status: int) -> bool: ... +def WEXITSTATUS(status: int) -> bool: ... +def WIFCONTINUED(status: int) -> bool: ... +def WIFEXITED(status: int) -> bool: ... +def WIFSIGNALED(status: int) -> bool: ... +def WIFSTOPPED(status: int) -> bool: ... +def WSTOPSIG(status: int) -> bool: ... +def WTERMSIG(status: int) -> bool: ... + +class stat_result(object): + n_fields: int + n_sequence_fields: int + n_unnamed_fields: int + st_mode: int + st_ino: int + st_dev: int + st_nlink: int + st_uid: int + st_gid: int + st_size: int + st_atime: int + st_mtime: int + st_ctime: int + +class statvfs_result(NamedTuple): + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + +def _exit(status: int) -> None: ... +def abort() -> None: ... +def access(path: unicode, mode: int) -> bool: ... +def chdir(path: unicode) -> None: ... +def chmod(path: unicode, mode: int) -> None: ... +def chown(path: unicode, uid: int, gid: int) -> None: ... +def chroot(path: unicode) -> None: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def confstr(name: Union[str, int]) -> str: ... +def ctermid() -> str: ... +def dup(fd: int) -> int: ... +def dup2(fd: int, fd2: int) -> None: ... +def execv(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def execve(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def fchdir(fd: int) -> None: ... +def fchmod(fd: int, mode: int) -> None: ... +def fchown(fd: int, uid: int, gid: int) -> None: ... +def fdatasync(fd: int) -> None: ... +def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def fork() -> int: ... +def forkpty() -> Tuple[int, int]: ... +def fpathconf(fd: int, name: str) -> None: ... +def fstat(fd: int) -> stat_result: ... +def fstatvfs(fd: int) -> statvfs_result: ... +def fsync(fd: int) -> None: ... +def ftruncate(fd: int, length: int) -> None: ... +def getcwd() -> str: ... +def getcwdu() -> unicode: ... +def getegid() -> int: ... +def geteuid() -> int: ... +def getgid() -> int: ... +def getgroups() -> List[int]: ... +def getloadavg() -> Tuple[float, float, float]: ... +def getlogin() -> str: ... +def getpgid(pid: int) -> int: ... +def getpgrp() -> int: ... +def getpid() -> int: ... +def getppid() -> int: ... +def getresgid() -> Tuple[int, int, int]: ... +def getresuid() -> Tuple[int, int, int]: ... +def getsid(pid: int) -> int: ... +def getuid() -> int: ... +def initgroups(username: str, gid: int) -> None: ... +def isatty(fd: int) -> bool: ... +def kill(pid: int, sig: int) -> None: ... +def killpg(pgid: int, sig: int) -> None: ... +def lchown(path: unicode, uid: int, gid: int) -> None: ... +def link(source: unicode, link_name: str) -> None: ... +def listdir(path: AnyStr) -> List[AnyStr]: ... +def lseek(fd: int, pos: int, how: int) -> None: ... +def lstat(path: unicode) -> stat_result: ... +def major(device: int) -> int: ... +def makedev(major: int, minor: int) -> int: ... +def minor(device: int) -> int: ... +def mkdir(path: unicode, mode: int = ...) -> None: ... +def mkfifo(path: unicode, mode: int = ...) -> None: ... +def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... +def nice(increment: int) -> int: ... +def open(file: unicode, flags: int, mode: int = ...) -> int: ... +def openpty() -> Tuple[int, int]: ... +def pathconf(path: unicode, name: str) -> str: ... +def pipe() -> Tuple[int, int]: ... +def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def putenv(varname: str, value: str) -> None: ... +def read(fd: int, n: int) -> str: ... +def readlink(path: _T) -> _T: ... +def remove(path: unicode) -> None: ... +def rename(src: unicode, dst: unicode) -> None: ... +def rmdir(path: unicode) -> None: ... +def setegid(egid: int) -> None: ... +def seteuid(euid: int) -> None: ... +def setgid(gid: int) -> None: ... +def setgroups(groups: Sequence[int]) -> None: ... +def setpgid(pid: int, pgrp: int) -> None: ... +def setpgrp() -> None: ... +def setregid(rgid: int, egid: int) -> None: ... +def setresgid(rgid: int, egid: int, sgid: int) -> None: ... +def setresuid(ruid: int, euid: int, suid: int) -> None: ... +def setreuid(ruid: int, euid: int) -> None: ... +def setsid() -> None: ... +def setuid(pid: int) -> None: ... +def stat(path: unicode) -> stat_result: ... +def statvfs(path: unicode) -> statvfs_result: ... +def stat_float_times(fd: int) -> None: ... +def strerror(code: int) -> str: ... +def symlink(source: unicode, link_name: unicode) -> None: ... +def sysconf(name: Union[str, int]) -> int: ... +def system(command: unicode) -> int: ... +def tcgetpgrp(fd: int) -> int: ... +def tcsetpgrp(fd: int, pg: int) -> None: ... +def times() -> Tuple[float, float, float, float, float]: ... +def tmpfile() -> IO[str]: ... +def ttyname(fd: int) -> str: ... +def umask(mask: int) -> int: ... +def uname() -> Tuple[str, str, str, str, str]: ... +def unlink(path: unicode) -> None: ... +def unsetenv(varname: str) -> None: ... +def urandom(n: int) -> str: ... +def utime(path: unicode, times: Optional[Tuple[int, int]]) -> None: ... +def wait() -> int: ... +_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] +def wait3(options: int) -> Tuple[int, int, _r]: ... +def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... +def waitpid(pid: int, options: int) -> int: ... +def write(fd: int, str: str) -> int: ... diff --git a/mypy/stdlib/python2/random.pyi b/mypy/stdlib/python2/random.pyi new file mode 100644 index 000000000000..65d323db1d35 --- /dev/null +++ b/mypy/stdlib/python2/random.pyi @@ -0,0 +1,77 @@ +# Stubs for random +# Ron Murawski +# Updated by Jukka Lehtosalo + +# based on https://docs.python.org/2/library/random.html + +# ----- random classes ----- + +import _random +from typing import AbstractSet, Any, Callable, Iterator, List, Protocol, Sequence, TypeVar, Union, overload + +_T = TypeVar("_T") +_T_co = TypeVar('_T_co', covariant=True) + +class _Sampleable(Protocol[_T_co]): + def __iter__(self) -> Iterator[_T_co]: ... + def __len__(self) -> int: ... + +class Random(_random.Random): + def __init__(self, x: object = ...) -> None: ... + def seed(self, x: object = ...) -> None: ... + def getstate(self) -> _random._State: ... + def setstate(self, state: _random._State) -> None: ... + def jumpahead(self, n: int) -> None: ... + def getrandbits(self, k: int) -> int: ... + @overload + def randrange(self, stop: int) -> int: ... + @overload + def randrange(self, start: int, stop: int, step: int = ...) -> int: ... + def randint(self, a: int, b: int) -> int: ... + def choice(self, seq: Sequence[_T]) -> _T: ... + def shuffle(self, x: List[Any], random: Callable[[], None] = ...) -> None: ... + def sample(self, population: _Sampleable[_T], k: int) -> List[_T]: ... + def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... + def betavariate(self, alpha: float, beta: float) -> float: ... + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... + def gauss(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): + ... + +# ----- random function stubs ----- +def seed(x: object = ...) -> None: ... +def getstate() -> object: ... +def setstate(state: object) -> None: ... +def jumpahead(n: int) -> None: ... +def getrandbits(k: int) -> int: ... +@overload +def randrange(stop: int) -> int: ... +@overload +def randrange(start: int, stop: int, step: int = ...) -> int: ... +def randint(a: int, b: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +def shuffle(x: List[Any], random: Callable[[], float] = ...) -> None: ... +def sample(population: _Sampleable[_T], k: int) -> List[_T]: ... +def random() -> float: ... +def uniform(a: float, b: float) -> float: ... +def triangular(low: float = ..., high: float = ..., + mode: float = ...) -> float: ... +def betavariate(alpha: float, beta: float) -> float: ... +def expovariate(lambd: float) -> float: ... +def gammavariate(alpha: float, beta: float) -> float: ... +def gauss(mu: float, sigma: float) -> float: ... +def lognormvariate(mu: float, sigma: float) -> float: ... +def normalvariate(mu: float, sigma: float) -> float: ... +def vonmisesvariate(mu: float, kappa: float) -> float: ... +def paretovariate(alpha: float) -> float: ... +def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/mypy/stdlib/python2/re.pyi b/mypy/stdlib/python2/re.pyi new file mode 100644 index 000000000000..71486692f9fd --- /dev/null +++ b/mypy/stdlib/python2/re.pyi @@ -0,0 +1,100 @@ +# Stubs for re +# Ron Murawski +# 'bytes' support added by Jukka Lehtosalo + +# based on: http: //docs.python.org/2.7/library/re.html + +from typing import ( + List, Iterator, overload, Callable, Tuple, Sequence, Dict, + Generic, AnyStr, Match, Pattern, Any, Optional, Union +) + +# ----- re variables and constants ----- +DEBUG: int +I: int +IGNORECASE: int +L: int +LOCALE: int +M: int +MULTILINE: int +S: int +DOTALL: int +X: int +VERBOSE: int +U: int +UNICODE: int +T: int +TEMPLATE: int + +class error(Exception): ... + +@overload +def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... + +@overload +def search(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def search(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def match(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def split(pattern: Union[str, unicode], string: AnyStr, + maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +@overload +def split(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, + maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... + +@overload +def findall(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... +@overload +def findall(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> List[Any]: ... + +# Return an iterator yielding match objects over all non-overlapping matches +# for the RE pattern in string. The string is scanned left-to-right, and +# matches are returned in the order found. Empty matches are included in the +# result unless they touch the beginning of another match. +@overload +def finditer(pattern: Union[str, unicode], string: AnyStr, + flags: int = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def finditer(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, + flags: int = ...) -> Iterator[Match[AnyStr]]: ... + +@overload +def sub(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... + +@overload +def subn(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... + +def escape(string: AnyStr) -> AnyStr: ... + +def purge() -> None: ... +def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/stdlib/python2/repr.pyi b/mypy/stdlib/python2/repr.pyi new file mode 100644 index 000000000000..a24e59bc9fec --- /dev/null +++ b/mypy/stdlib/python2/repr.pyi @@ -0,0 +1,33 @@ +from typing import Any, List + +class Repr: + maxarray: int + maxdeque: int + maxdict: int + maxfrozenset: int + maxlevel: int + maxlist: int + maxlong: int + maxother: int + maxset: int + maxstring: int + maxtuple: int + def __init__(self) -> None: ... + def _repr_iterable(self, x, level: complex, left, right, maxiter, trail=...) -> str: ... + def repr(self, x) -> str: ... + def repr1(self, x, level: complex) -> str: ... + def repr_array(self, x, level: complex) -> str: ... + def repr_deque(self, x, level: complex) -> str: ... + def repr_dict(self, x, level: complex) -> str: ... + def repr_frozenset(self, x, level: complex) -> str: ... + def repr_instance(self, x, level: complex) -> str: ... + def repr_list(self, x, level: complex) -> str: ... + def repr_long(self, x, level: complex) -> str: ... + def repr_set(self, x, level: complex) -> str: ... + def repr_str(self, x, level: complex) -> str: ... + def repr_tuple(self, x, level: complex) -> str: ... + +def _possibly_sorted(x) -> List[Any]: ... + +aRepr: Repr +def repr(x) -> str: ... diff --git a/mypy/stdlib/python2/resource.pyi b/mypy/stdlib/python2/resource.pyi new file mode 100644 index 000000000000..3763bc25b91d --- /dev/null +++ b/mypy/stdlib/python2/resource.pyi @@ -0,0 +1,45 @@ +from typing import Tuple, NamedTuple + +class error(Exception): ... + +RLIM_INFINITY: int +def getrlimit(resource: int) -> Tuple[int, int]: ... +def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... + +RLIMIT_CORE: int +RLIMIT_CPU: int +RLIMIT_FSIZE: int +RLIMIT_DATA: int +RLIMIT_STACK: int +RLIMIT_RSS: int +RLIMIT_NPROC: int +RLIMIT_NOFILE: int +RLIMIT_OFILE: int +RLIMIT_MEMLOCK: int +RLIMIT_VMEM: int +RLIMIT_AS: int + +class _RUsage(NamedTuple): + ru_utime: float + ru_stime: float + ru_maxrss: int + ru_ixrss: int + ru_idrss: int + ru_isrss: int + ru_minflt: int + ru_majflt: int + ru_nswap: int + ru_inblock: int + ru_oublock: int + ru_msgsnd: int + ru_msgrcv: int + ru_nsignals: int + ru_nvcsw: int + ru_nivcsw: int + +def getrusage(who: int) -> _RUsage: ... +def getpagesize() -> int: ... + +RUSAGE_SELF: int +RUSAGE_CHILDREN: int +RUSAGE_BOTH: int diff --git a/mypy/stdlib/python2/rfc822.pyi b/mypy/stdlib/python2/rfc822.pyi new file mode 100644 index 000000000000..20cd1d6394fa --- /dev/null +++ b/mypy/stdlib/python2/rfc822.pyi @@ -0,0 +1,79 @@ +# Stubs for rfc822 (Python 2) +# +# Based on stub generated by stubgen. + +from typing import Any, Optional + +class Message: + fp: Any + seekable: Any + startofheaders: Any + startofbody: Any + def __init__(self, fp, seekable: int = ...): ... + def rewindbody(self): ... + dict: Any + unixfrom: Any + headers: Any + status: Any + def readheaders(self): ... + def isheader(self, line): ... + def islast(self, line): ... + def iscomment(self, line): ... + def getallmatchingheaders(self, name): ... + def getfirstmatchingheader(self, name): ... + def getrawheader(self, name): ... + def getheader(self, name, default: Optional[Any] = ...): ... + get: Any + def getheaders(self, name): ... + def getaddr(self, name): ... + def getaddrlist(self, name): ... + def getdate(self, name): ... + def getdate_tz(self, name): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, value): ... + def __delitem__(self, name): ... + def setdefault(self, name, default=...): ... + def has_key(self, name): ... + def __contains__(self, name): ... + def __iter__(self): ... + def keys(self): ... + def values(self): ... + def items(self): ... + +class AddrlistClass: + specials: Any + pos: Any + LWS: Any + CR: Any + atomends: Any + phraseends: Any + field: Any + commentlist: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: int = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... diff --git a/mypy/stdlib/python2/robotparser.pyi b/mypy/stdlib/python2/robotparser.pyi new file mode 100644 index 000000000000..403039ae91c9 --- /dev/null +++ b/mypy/stdlib/python2/robotparser.pyi @@ -0,0 +1,7 @@ +class RobotFileParser: + def set_url(self, url: str): ... + def read(self): ... + def parse(self, lines: str): ... + def can_fetch(self, user_agent: str, url: str): ... + def mtime(self): ... + def modified(self): ... diff --git a/mypy/stdlib/python2/runpy.pyi b/mypy/stdlib/python2/runpy.pyi new file mode 100644 index 000000000000..6674af077d5d --- /dev/null +++ b/mypy/stdlib/python2/runpy.pyi @@ -0,0 +1,17 @@ +from typing import Any, Optional + +class _TempModule: + mod_name: Any + module: Any + def __init__(self, mod_name): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +class _ModifiedArgv0: + value: Any + def __init__(self, value): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +def run_module(mod_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ..., alter_sys: bool = ...): ... +def run_path(path_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ...): ... diff --git a/mypy/stdlib/python2/sets.pyi b/mypy/stdlib/python2/sets.pyi new file mode 100644 index 000000000000..3ec4cae2fc44 --- /dev/null +++ b/mypy/stdlib/python2/sets.pyi @@ -0,0 +1,61 @@ +# Stubs for sets (Python 2) +from typing import Any, Callable, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union + +_T = TypeVar('_T') +_Setlike = Union[BaseSet[_T], Iterable[_T]] +_SelfT = TypeVar('_SelfT') + +class BaseSet(Iterable[_T]): + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __iter__(self) -> Iterator[_T]: ... + def __cmp__(self, other: Any) -> int: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + def copy(self: _SelfT) -> _SelfT: ... + def __copy__(self: _SelfT) -> _SelfT: ... + def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... + def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def union(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... + def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def intersection(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... + def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def symmetric_difference(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... + def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def difference(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... + def __contains__(self, element: Any) -> bool: ... + def issubset(self, other: BaseSet[_T]) -> bool: ... + def issuperset(self, other: BaseSet[_T]) -> bool: ... + def __le__(self, other: BaseSet[_T]) -> bool: ... + def __ge__(self, other: BaseSet[_T]) -> bool: ... + def __lt__(self, other: BaseSet[_T]) -> bool: ... + def __gt__(self, other: BaseSet[_T]) -> bool: ... + +class ImmutableSet(BaseSet[_T], Hashable): + def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... + def __hash__(self) -> int: ... + +class Set(BaseSet[_T]): + def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... + def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def union_update(self, other: _Setlike[_T]) -> None: ... + def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def intersection_update(self, other: _Setlike[Any]) -> None: ... + def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... + def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def difference_update(self, other: _Setlike[Any]) -> None: ... + def update(self, iterable: _Setlike[_T]) -> None: ... + def clear(self) -> None: ... + def add(self, element: _T) -> None: ... + def remove(self, element: _T) -> None: ... + def discard(self, element: _T) -> None: ... + def pop(self) -> _T: ... + def __as_immutable__(self) -> ImmutableSet[_T]: ... + def __as_temporarily_immutable__(self) -> _TemporarilyImmutableSet[_T]: ... + +class _TemporarilyImmutableSet(BaseSet[_T]): + def __init__(self, set: BaseSet[_T]) -> None: ... + def __hash__(self) -> int: ... diff --git a/mypy/stdlib/python2/sha.pyi b/mypy/stdlib/python2/sha.pyi new file mode 100644 index 000000000000..00ad4d9f49a8 --- /dev/null +++ b/mypy/stdlib/python2/sha.pyi @@ -0,0 +1,11 @@ +# Stubs for Python 2.7 sha stdlib module + +class sha(object): + def update(self, arg: str) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> sha: ... + +def new(string: str = ...) -> sha: ... +blocksize: int +digest_size: int diff --git a/mypy/stdlib/python2/shelve.pyi b/mypy/stdlib/python2/shelve.pyi new file mode 100644 index 000000000000..15828bc1793a --- /dev/null +++ b/mypy/stdlib/python2/shelve.pyi @@ -0,0 +1,33 @@ +from typing import Any, Dict, Iterator, List, Optional, Tuple +import collections + + +class Shelf(collections.MutableMapping[Any, Any]): + def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> List[Any]: ... + def __len__(self) -> int: ... + def has_key(self, key: Any) -> bool: ... + def __contains__(self, key: Any) -> bool: ... + def get(self, key: Any, default: Any = ...) -> Any: ... + def __getitem__(self, key: Any) -> Any: ... + def __setitem__(self, key: Any, value: Any) -> None: ... + def __delitem__(self, key: Any) -> None: ... + def __enter__(self) -> Shelf: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + def sync(self) -> None: ... + +class BsdDbShelf(Shelf): + def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def set_location(self, key: Any) -> Tuple[str, Any]: ... + def next(self) -> Tuple[str, Any]: ... + def previous(self) -> Tuple[str, Any]: ... + def first(self) -> Tuple[str, Any]: ... + def last(self) -> Tuple[str, Any]: ... + +class DbfilenameShelf(Shelf): + def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... + +def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/mypy/stdlib/python2/shlex.pyi b/mypy/stdlib/python2/shlex.pyi new file mode 100644 index 000000000000..a29b83eb1362 --- /dev/null +++ b/mypy/stdlib/python2/shlex.pyi @@ -0,0 +1,31 @@ +from typing import Any, IO, List, Optional, TypeVar + +def split(s: Optional[str], comments: bool = ..., posix: bool = ...) -> List[str]: ... + +_SLT = TypeVar('_SLT', bound=shlex) + +class shlex: + def __init__(self, instream: IO[Any] = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... + def __iter__(self: _SLT) -> _SLT: ... + def next(self) -> str: ... + def get_token(self) -> Optional[str]: ... + def push_token(self, _str: str) -> None: ... + def read_token(self) -> str: ... + def sourcehook(self, filename: str) -> None: ... + def push_source(self, stream: IO[Any], filename: str = ...) -> None: ... + def pop_source(self) -> IO[Any]: ... + def error_leader(self, file: str = ..., line: int = ...) -> str: ... + + commenters: str + wordchars: str + whitespace: str + escape: str + quotes: str + escapedquotes: str + whitespace_split: bool + infile: IO[Any] + source: Optional[str] + debug: int + lineno: int + token: Any + eof: Optional[str] diff --git a/mypy/stdlib/python2/signal.pyi b/mypy/stdlib/python2/signal.pyi new file mode 100644 index 000000000000..24bfbf07789a --- /dev/null +++ b/mypy/stdlib/python2/signal.pyi @@ -0,0 +1,68 @@ +from typing import Callable, Any, Tuple, Union +from types import FrameType + +SIG_DFL: int = ... +SIG_IGN: int = ... + +ITIMER_REAL: int = ... +ITIMER_VIRTUAL: int = ... +ITIMER_PROF: int = ... + +NSIG: int = ... + +SIGABRT: int = ... +SIGALRM: int = ... +SIGBREAK: int = ... # Windows +SIGBUS: int = ... +SIGCHLD: int = ... +SIGCLD: int = ... +SIGCONT: int = ... +SIGEMT: int = ... +SIGFPE: int = ... +SIGHUP: int = ... +SIGILL: int = ... +SIGINFO: int = ... +SIGINT: int = ... +SIGIO: int = ... +SIGIOT: int = ... +SIGKILL: int = ... +SIGPIPE: int = ... +SIGPOLL: int = ... +SIGPROF: int = ... +SIGPWR: int = ... +SIGQUIT: int = ... +SIGRTMAX: int = ... +SIGRTMIN: int = ... +SIGSEGV: int = ... +SIGSTOP: int = ... +SIGSYS: int = ... +SIGTERM: int = ... +SIGTRAP: int = ... +SIGTSTP: int = ... +SIGTTIN: int = ... +SIGTTOU: int = ... +SIGURG: int = ... +SIGUSR1: int = ... +SIGUSR2: int = ... +SIGVTALRM: int = ... +SIGWINCH: int = ... +SIGXCPU: int = ... +SIGXFSZ: int = ... + +# Windows +CTRL_C_EVENT: int = ... +CTRL_BREAK_EVENT: int = ... + +class ItimerError(IOError): ... + +_HANDLER = Union[Callable[[int, FrameType], None], int, None] + +def alarm(time: int) -> int: ... +def getsignal(signalnum: int) -> _HANDLER: ... +def pause() -> None: ... +def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... +def getitimer(which: int) -> Tuple[float, float]: ... +def set_wakeup_fd(fd: int) -> int: ... +def siginterrupt(signalnum: int, flag: bool) -> None: ... +def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: ... +def default_int_handler(signum: int, frame: FrameType) -> None: ... diff --git a/mypy/stdlib/python2/smtplib.pyi b/mypy/stdlib/python2/smtplib.pyi new file mode 100644 index 000000000000..438221a439b7 --- /dev/null +++ b/mypy/stdlib/python2/smtplib.pyi @@ -0,0 +1,86 @@ +from typing import Any + +class SMTPException(Exception): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code: Any + smtp_error: Any + args: Any + def __init__(self, code, msg) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_code: Any + smtp_error: Any + sender: Any + args: Any + def __init__(self, code, msg, sender) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients: Any + args: Any + def __init__(self, recipients) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addr): ... +def quotedata(data): ... + +class SSLFakeFile: + sslobj: Any + def __init__(self, sslobj) -> None: ... + def readline(self, size=...): ... + def close(self): ... + +class SMTP: + debuglevel: Any + file: Any + helo_resp: Any + ehlo_msg: Any + ehlo_resp: Any + does_esmtp: Any + default_port: Any + timeout: Any + esmtp_features: Any + local_hostname: Any + def __init__(self, host: str = ..., port: int = ..., local_hostname=..., timeout=...) -> None: ... + def set_debuglevel(self, debuglevel): ... + sock: Any + def connect(self, host=..., port=...): ... + def send(self, str): ... + def putcmd(self, cmd, args=...): ... + def getreply(self): ... + def docmd(self, cmd, args=...): ... + def helo(self, name=...): ... + def ehlo(self, name=...): ... + def has_extn(self, opt): ... + def help(self, args=...): ... + def rset(self): ... + def noop(self): ... + def mail(self, sender, options=...): ... + def rcpt(self, recip, options=...): ... + def data(self, msg): ... + def verify(self, address): ... + vrfy: Any + def expn(self, address): ... + def ehlo_or_helo_if_needed(self): ... + def login(self, user, password): ... + def starttls(self, keyfile=..., certfile=...): ... + def sendmail(self, from_addr, to_addrs, msg, mail_options=..., rcpt_options=...): ... + def close(self): ... + def quit(self): ... + +class SMTP_SSL(SMTP): + default_port: Any + keyfile: Any + certfile: Any + def __init__(self, host=..., port=..., local_hostname=..., keyfile=..., certfile=..., timeout=...) -> None: ... + +class LMTP(SMTP): + ehlo_msg: Any + def __init__(self, host=..., port=..., local_hostname=...) -> None: ... + sock: Any + def connect(self, host=..., port=...): ... diff --git a/mypy/stdlib/python2/spwd.pyi b/mypy/stdlib/python2/spwd.pyi new file mode 100644 index 000000000000..756c142a61da --- /dev/null +++ b/mypy/stdlib/python2/spwd.pyi @@ -0,0 +1,15 @@ +from typing import List, NamedTuple + +class struct_spwd(NamedTuple): + sp_nam: str + sp_pwd: str + sp_lstchg: int + sp_min: int + sp_max: int + sp_warn: int + sp_inact: int + sp_expire: int + sp_flag: int + +def getspall() -> List[struct_spwd]: ... +def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/stdlib/python2/sre_constants.pyi b/mypy/stdlib/python2/sre_constants.pyi new file mode 100644 index 000000000000..89d453ea22da --- /dev/null +++ b/mypy/stdlib/python2/sre_constants.pyi @@ -0,0 +1,94 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_constants.py + +from typing import Dict, List, TypeVar + +MAGIC: int +MAXREPEAT: int + +class error(Exception): ... + +FAILURE: str +SUCCESS: str +ANY: str +ANY_ALL: str +ASSERT: str +ASSERT_NOT: str +AT: str +BIGCHARSET: str +BRANCH: str +CALL: str +CATEGORY: str +CHARSET: str +GROUPREF: str +GROUPREF_IGNORE: str +GROUPREF_EXISTS: str +IN: str +IN_IGNORE: str +INFO: str +JUMP: str +LITERAL: str +LITERAL_IGNORE: str +MARK: str +MAX_REPEAT: str +MAX_UNTIL: str +MIN_REPEAT: str +MIN_UNTIL: str +NEGATE: str +NOT_LITERAL: str +NOT_LITERAL_IGNORE: str +RANGE: str +REPEAT: str +REPEAT_ONE: str +SUBPATTERN: str +MIN_REPEAT_ONE: str +AT_BEGINNING: str +AT_BEGINNING_LINE: str +AT_BEGINNING_STRING: str +AT_BOUNDARY: str +AT_NON_BOUNDARY: str +AT_END: str +AT_END_LINE: str +AT_END_STRING: str +AT_LOC_BOUNDARY: str +AT_LOC_NON_BOUNDARY: str +AT_UNI_BOUNDARY: str +AT_UNI_NON_BOUNDARY: str +CATEGORY_DIGIT: str +CATEGORY_NOT_DIGIT: str +CATEGORY_SPACE: str +CATEGORY_NOT_SPACE: str +CATEGORY_WORD: str +CATEGORY_NOT_WORD: str +CATEGORY_LINEBREAK: str +CATEGORY_NOT_LINEBREAK: str +CATEGORY_LOC_WORD: str +CATEGORY_LOC_NOT_WORD: str +CATEGORY_UNI_DIGIT: str +CATEGORY_UNI_NOT_DIGIT: str +CATEGORY_UNI_SPACE: str +CATEGORY_UNI_NOT_SPACE: str +CATEGORY_UNI_WORD: str +CATEGORY_UNI_NOT_WORD: str +CATEGORY_UNI_LINEBREAK: str +CATEGORY_UNI_NOT_LINEBREAK: str + +_T = TypeVar('_T') +def makedict(list: List[_T]) -> Dict[_T, int]: ... + +OP_IGNORE: Dict[str, str] +AT_MULTILINE: Dict[str, str] +AT_LOCALE: Dict[str, str] +AT_UNICODE: Dict[str, str] +CH_LOCALE: Dict[str, str] +CH_UNICODE: Dict[str, str] +SRE_FLAG_TEMPLATE: int +SRE_FLAG_IGNORECASE: int +SRE_FLAG_LOCALE: int +SRE_FLAG_MULTILINE: int +SRE_FLAG_DOTALL: int +SRE_FLAG_UNICODE: int +SRE_FLAG_VERBOSE: int +SRE_FLAG_DEBUG: int +SRE_INFO_PREFIX: int +SRE_INFO_LITERAL: int +SRE_INFO_CHARSET: int diff --git a/mypy/stdlib/python2/sre_parse.pyi b/mypy/stdlib/python2/sre_parse.pyi new file mode 100644 index 000000000000..d23753527d12 --- /dev/null +++ b/mypy/stdlib/python2/sre_parse.pyi @@ -0,0 +1,63 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_parse.py + +from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union + +SPECIAL_CHARS: str +REPEAT_CHARS: str +DIGITS: Set[Any] +OCTDIGITS: Set[Any] +HEXDIGITS: Set[Any] +WHITESPACE: Set[Any] +ESCAPES: Dict[str, Tuple[str, int]] +CATEGORIES: Dict[str, Union[Tuple[str, str], Tuple[str, List[Tuple[str, str]]]]] +FLAGS: Dict[str, int] + +class Pattern: + flags: int + open: List[int] + groups: int + groupdict: Dict[str, int] + lookbehind: int + def __init__(self) -> None: ... + def opengroup(self, name: str = ...) -> int: ... + def closegroup(self, gid: int) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + + +_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] +_OpInType = List[Tuple[str, int]] +_OpBranchType = Tuple[None, List[SubPattern]] +_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_CodeType = Union[str, _AvType] + +class SubPattern: + pattern: str + data: List[_CodeType] + width: Optional[int] + def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... + def dump(self, level: int = ...) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... + def __setitem__(self, index: Union[int, slice], code: _CodeType): ... + def insert(self, index, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> int: ... + +class Tokenizer: + string: str + index: int + def __init__(self, string: str) -> None: ... + def match(self, char: str, skip: int = ...) -> int: ... + def get(self) -> Optional[str]: ... + def tell(self) -> Tuple[int, Optional[str]]: ... + def seek(self, index: int) -> None: ... + +def isident(char: str) -> bool: ... +def isdigit(char: str) -> bool: ... +def isname(name: str) -> bool: ... +def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... +_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] +def parse_template(source: str, pattern: _Pattern[Any]) -> _Template: ... +def expand_template(template: _Template, match: Match[Any]) -> str: ... diff --git a/mypy/stdlib/python2/stat.pyi b/mypy/stdlib/python2/stat.pyi new file mode 100644 index 000000000000..5230d670f080 --- /dev/null +++ b/mypy/stdlib/python2/stat.pyi @@ -0,0 +1,59 @@ +def S_ISDIR(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISBLK(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +ST_MODE: int +ST_INO: int +ST_DEV: int +ST_NLINK: int +ST_UID: int +ST_GID: int +ST_SIZE: int +ST_ATIME: int +ST_MTIME: int +ST_CTIME: int +S_IFSOCK: int +S_IFLNK: int +S_IFREG: int +S_IFBLK: int +S_IFDIR: int +S_IFCHR: int +S_IFIFO: int +S_ISUID: int +S_ISGID: int +S_ISVTX: int +S_IRWXU: int +S_IRUSR: int +S_IWUSR: int +S_IXUSR: int +S_IRWXG: int +S_IRGRP: int +S_IWGRP: int +S_IXGRP: int +S_IRWXO: int +S_IROTH: int +S_IWOTH: int +S_IXOTH: int +S_ENFMT: int +S_IREAD: int +S_IWRITE: int +S_IEXEC: int +UF_NODUMP: int +UF_IMMUTABLE: int +UF_APPEND: int +UF_OPAQUE: int +UF_NOUNLINK: int +UF_COMPRESSED: int +UF_HIDDEN: int +SF_ARCHIVED: int +SF_IMMUTABLE: int +SF_APPEND: int +SF_NOUNLINK: int +SF_SNAPSHOT: int diff --git a/mypy/stdlib/python2/string.pyi b/mypy/stdlib/python2/string.pyi new file mode 100644 index 000000000000..bf55e922a408 --- /dev/null +++ b/mypy/stdlib/python2/string.pyi @@ -0,0 +1,75 @@ +# Stubs for string + +# Based on http://docs.python.org/3.2/library/string.html + +from typing import Any, AnyStr, Iterable, List, Mapping, Optional, overload, Sequence, Text, Tuple, Union + +ascii_letters: str +ascii_lowercase: str +ascii_uppercase: str +digits: str +hexdigits: str +letters: str +lowercase: str +octdigits: str +punctuation: str +printable: str +uppercase: str +whitespace: str + +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +# TODO: originally named 'from' +def maketrans(_from: str, to: str) -> str: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> int: ... +def capitalize(word: AnyStr) -> AnyStr: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def lower(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def rstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def strip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def translate(s: str, table: str, deletechars: str = ...) -> str: ... +def upper(s: AnyStr) -> AnyStr: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... + +class Template: + template: Text + + def __init__(self, template: Text) -> None: ... + @overload + def substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... + @overload + def substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]] = ..., **kwds: Text) -> Text: ... + @overload + def safe_substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... + @overload + def safe_substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]], **kwds: Text) -> Text: ... + +# TODO(MichalPokorny): This is probably badly and/or loosely typed. +class Formatter(object): + def format(self, format_string: str, *args, **kwargs) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> str: ... + def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... + def get_field(self, field_name: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: Union[int, str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/mypy/stdlib/python2/stringold.pyi b/mypy/stdlib/python2/stringold.pyi new file mode 100644 index 000000000000..ab3e764ed213 --- /dev/null +++ b/mypy/stdlib/python2/stringold.pyi @@ -0,0 +1,46 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/stringold.py +from typing import AnyStr, Iterable, List, Optional, Type + +whitespace: str +lowercase: str +uppercase: str +letters: str +digits: str +hexdigits: str +octdigits: str +_idmap: str +_idmapL: Optional[List[str]] +index_error = ValueError +atoi_error = ValueError +atof_error = ValueError +atol_error = ValueError + + +def lower(s: AnyStr) -> AnyStr: ... +def upper(s: AnyStr) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def strip(s: AnyStr) -> AnyStr: ... +def lstrip(s: AnyStr) -> AnyStr: ... +def rstrip(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> long: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... +def translate(s: str, table: str, deletions: str = ...) -> str: ... +def capitalize(s: AnyStr) -> AnyStr: ... +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +def maketrans(fromstr: str, tostr: str) -> str: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/mypy/stdlib/python2/strop.pyi b/mypy/stdlib/python2/strop.pyi new file mode 100644 index 000000000000..578a47758df5 --- /dev/null +++ b/mypy/stdlib/python2/strop.pyi @@ -0,0 +1,29 @@ +"""Stub file for the 'strop' module.""" + +from typing import List, Sequence + +lowercase: str +uppercase: str +whitespace: str + +def atof(a: str) -> float: ... +def atoi(a: str, base: int = ...) -> int: ... +def atol(a: str, base: int = ...) -> long: ... +def capitalize(s: str) -> str: ... +def count(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def expandtabs(string: str, tabsize: int = ...) -> str: ... +def find(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def join(list: Sequence[str], sep: str = ...) -> str: ... +def joinfields(list: Sequence[str], sep: str = ...) -> str: ... +def lower(s: str) -> str: ... +def lstrip(s: str) -> str: ... +def maketrans(frm: str, to: str) -> str: ... +def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: ... +def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def rstrip(s: str) -> str: ... +def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... +def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... +def strip(s: str) -> str: ... +def swapcase(s: str) -> str: ... +def translate(s: str, table: str, deletechars: str = ...) -> str: ... +def upper(s: str) -> str: ... diff --git a/mypy/stdlib/python2/subprocess.pyi b/mypy/stdlib/python2/subprocess.pyi new file mode 100644 index 000000000000..4c2f2d8c2f6a --- /dev/null +++ b/mypy/stdlib/python2/subprocess.pyi @@ -0,0 +1,120 @@ +# Stubs for subprocess + +# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub + +from typing import ( + Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text, TypeVar, Generic, +) + +_FILE = Union[None, int, IO[Any]] +_TXT = Union[bytes, Text] +_CMD = Union[_TXT, Sequence[_TXT]] +_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] + +# Same args as Popen.__init__ +def call(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> int: ... + +def check_call(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> int: ... + +# Same args as Popen.__init__ except for stdout +def check_output(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> bytes: ... + +PIPE: int +STDOUT: int + +class CalledProcessError(Exception): + returncode: int + # morally: _CMD + cmd: Any + # morally: Optional[bytes] + output: bytes + + def __init__(self, + returncode: int, + cmd: _CMD, + output: Optional[bytes] = ...) -> None: ... + +# We use a dummy type variable used to make Popen generic like it is in python 3 +_T = TypeVar('_T', bound=bytes) + +class Popen(Generic[_T]): + stdin: Optional[IO[bytes]] + stdout: Optional[IO[bytes]] + stderr: Optional[IO[bytes]] + pid: int + returncode: int + + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[_TXT] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ...) -> Popen[bytes]: ... + + def poll(self) -> Optional[int]: ... + def wait(self) -> int: ... + # morally: -> Tuple[Optional[bytes], Optional[bytes]] + def communicate(self, input: Optional[_TXT] = ...) -> Tuple[bytes, bytes]: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + +def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented + +# Windows-only: STARTUPINFO etc. + +STD_INPUT_HANDLE: Any +STD_OUTPUT_HANDLE: Any +STD_ERROR_HANDLE: Any +SW_HIDE: Any +STARTF_USESTDHANDLES: Any +STARTF_USESHOWWINDOW: Any +CREATE_NEW_CONSOLE: Any +CREATE_NEW_PROCESS_GROUP: Any diff --git a/mypy/stdlib/python2/symbol.pyi b/mypy/stdlib/python2/symbol.pyi new file mode 100644 index 000000000000..55d25a6b2ee8 --- /dev/null +++ b/mypy/stdlib/python2/symbol.pyi @@ -0,0 +1,91 @@ +# Stubs for symbol (Python 2) + +from typing import Dict + +single_input: int +file_input: int +eval_input: int +decorator: int +decorators: int +decorated: int +funcdef: int +parameters: int +varargslist: int +fpdef: int +fplist: int +stmt: int +simple_stmt: int +small_stmt: int +expr_stmt: int +augassign: int +print_stmt: int +del_stmt: int +pass_stmt: int +flow_stmt: int +break_stmt: int +continue_stmt: int +return_stmt: int +yield_stmt: int +raise_stmt: int +import_stmt: int +import_name: int +import_from: int +import_as_name: int +dotted_as_name: int +import_as_names: int +dotted_as_names: int +dotted_name: int +global_stmt: int +exec_stmt: int +assert_stmt: int +compound_stmt: int +if_stmt: int +while_stmt: int +for_stmt: int +try_stmt: int +with_stmt: int +with_item: int +except_clause: int +suite: int +testlist_safe: int +old_test: int +old_lambdef: int +test: int +or_test: int +and_test: int +not_test: int +comparison: int +comp_op: int +expr: int +xor_expr: int +and_expr: int +shift_expr: int +arith_expr: int +term: int +factor: int +power: int +atom: int +listmaker: int +testlist_comp: int +lambdef: int +trailer: int +subscriptlist: int +subscript: int +sliceop: int +exprlist: int +testlist: int +dictorsetmaker: int +classdef: int +arglist: int +argument: int +list_iter: int +list_for: int +list_if: int +comp_iter: int +comp_for: int +comp_if: int +testlist1: int +encoding_decl: int +yield_expr: int + +sym_name: Dict[int, str] diff --git a/mypy/stdlib/python2/sys.pyi b/mypy/stdlib/python2/sys.pyi new file mode 100644 index 000000000000..f8651abdb506 --- /dev/null +++ b/mypy/stdlib/python2/sys.pyi @@ -0,0 +1,136 @@ +"""Stubs for the 'sys' module.""" + +from typing import ( + IO, NoReturn, Union, List, Sequence, Any, Dict, Tuple, BinaryIO, Optional, + Callable, overload, Text, Type, +) +from types import FrameType, ModuleType, TracebackType, ClassType + +# The following type alias are stub-only and do not exist during runtime +_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] + +class _flags: + bytes_warning: int + debug: int + division_new: int + division_warning: int + dont_write_bytecode: int + hash_randomization: int + ignore_environment: int + inspect: int + interactive: int + no_site: int + no_user_site: int + optimize: int + py3k_warning: int + tabcheck: int + unicode: int + verbose: int + +class _float_info: + max: float + max_exp: int + max_10_exp: int + min: float + min_exp: int + min_10_exp: int + dig: int + mant_dig: int + epsilon: float + radix: int + rounds: int + +class _version_info(Tuple[int, int, int, str, int]): + major: int + minor: int + micro: int + releaselevel: str + serial: int + +_mercurial: Tuple[str, str, str] +api_version: int +argv: List[str] +builtin_module_names: Tuple[str, ...] +byteorder: str +copyright: str +dont_write_bytecode: bool +exec_prefix: str +executable: str +flags: _flags +float_repr_style: str +hexversion: int +long_info: object +maxint: int +maxsize: int +maxunicode: int +modules: Dict[str, Any] +path: List[str] +platform: str +prefix: str +py3kwarning: bool +__stderr__: IO[str] +__stdin__: IO[str] +__stdout__: IO[str] +stderr: IO[str] +stdin: IO[str] +stdout: IO[str] +subversion: Tuple[str, str, str] +version: str +warnoptions: object +float_info: _float_info +version_info: _version_info +ps1: str +ps2: str +last_type: type +last_value: BaseException +last_traceback: TracebackType +# TODO precise types +meta_path: List[Any] +path_hooks: List[Any] +path_importer_cache: Dict[str, Any] +displayhook: Callable[[object], Any] +excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] +exc_type: Optional[type] +exc_value: Union[BaseException, ClassType] +exc_traceback: TracebackType + +class _WindowsVersionType: + major: Any + minor: Any + build: Any + platform: Any + service_pack: Any + service_pack_major: Any + service_pack_minor: Any + suite_mask: Any + product_type: Any + +def getwindowsversion() -> _WindowsVersionType: ... + +def _clear_type_cache() -> None: ... +def _current_frames() -> Dict[int, FrameType]: ... +def _getframe(depth: int = ...) -> FrameType: ... +def call_tracing(fn: Any, args: Any) -> Any: ... +def __displayhook__(value: object) -> None: ... +def __excepthook__(type_: type, value: BaseException, traceback: TracebackType) -> None: ... +def exc_clear() -> None: ... +def exc_info() -> _OptExcInfo: ... + +# sys.exit() accepts an optional argument of anything printable +def exit(arg: Any = ...) -> NoReturn: ... +def getcheckinterval() -> int: ... # deprecated +def getdefaultencoding() -> str: ... +def getdlopenflags() -> int: ... +def getfilesystemencoding() -> str: ... # In practice, never returns None +def getrefcount(arg: Any) -> int: ... +def getrecursionlimit() -> int: ... +def getsizeof(obj: object, default: int = ...) -> int: ... +def getprofile() -> Optional[Any]: ... +def gettrace() -> Optional[Any]: ... +def setcheckinterval(interval: int) -> None: ... # deprecated +def setdlopenflags(n: int) -> None: ... +def setdefaultencoding(encoding: Text) -> None: ... # only exists after reload(sys) +def setprofile(profilefunc: Any) -> None: ... # TODO type +def setrecursionlimit(limit: int) -> None: ... +def settrace(tracefunc: Any) -> None: ... # TODO type diff --git a/mypy/stdlib/python2/tempfile.pyi b/mypy/stdlib/python2/tempfile.pyi new file mode 100644 index 000000000000..536b391ad4d0 --- /dev/null +++ b/mypy/stdlib/python2/tempfile.pyi @@ -0,0 +1,111 @@ +from typing import Any, AnyStr, IO, Iterable, Iterator, List, Optional, overload, Text, Tuple, Union +from thread import LockType +from random import Random + +TMP_MAX: int +tempdir: str +template: str +_name_sequence: Optional[_RandomNameSequence] + +class _RandomNameSequence: + characters: str = ... + mutex: LockType + @property + def rng(self) -> Random: ... + def __iter__(self) -> _RandomNameSequence: ... + def next(self) -> str: ... + # from os.path: + def normcase(self, path: AnyStr) -> AnyStr: ... + +class _TemporaryFileWrapper(IO[str]): + delete: bool + file: IO[str] + name: Any + def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> _TemporaryFileWrapper: ... + def __exit__(self, exc, value, tb) -> Optional[bool]: ... + def __getattr__(self, name: unicode) -> Any: ... + def close(self) -> None: ... + def unlink(self, path: unicode) -> 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 fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + 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: Text) -> int: ... + def writelines(self, lines: Iterable[str]) -> None: ... + + +# TODO text files + +def TemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ... +) -> _TemporaryFileWrapper: + ... + +def NamedTemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ..., + delete: bool = ... +) -> _TemporaryFileWrapper: + ... + +def SpooledTemporaryFile( + max_size: int = ..., + mode: Union[bytes, unicode] = ..., + buffering: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ... +) -> _TemporaryFileWrapper: + ... + +class TemporaryDirectory: + name: Any + def __init__(self, + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ...) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> Any: ... # Can be str or unicode + def __exit__(self, type, value, traceback) -> None: ... + +@overload +def mkstemp() -> Tuple[int, str]: ... +@overload +def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ..., + text: bool = ...) -> Tuple[int, AnyStr]: ... +@overload +def mkdtemp() -> str: ... +@overload +def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +@overload +def mktemp() -> str: ... +@overload +def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +def gettempdir() -> str: ... +def gettempprefix() -> str: ... + +def _candidate_tempdir_list() -> List[str]: ... +def _get_candidate_names() -> Optional[_RandomNameSequence]: ... +def _get_default_tempdir() -> str: ... diff --git a/mypy/stdlib/python2/textwrap.pyi b/mypy/stdlib/python2/textwrap.pyi new file mode 100644 index 000000000000..60498a65acd0 --- /dev/null +++ b/mypy/stdlib/python2/textwrap.pyi @@ -0,0 +1,61 @@ +from typing import AnyStr, List, Dict, Pattern + +class TextWrapper(object): + width: int = ... + initial_indent: str = ... + subsequent_indent: str = ... + expand_tabs: bool = ... + replace_whitespace: bool = ... + fix_sentence_endings: bool = ... + drop_whitespace: bool = ... + break_long_words: bool = ... + break_on_hyphens: bool = ... + + # Attributes not present in documentation + sentence_end_re: Pattern[str] = ... + wordsep_re: Pattern[str] = ... + wordsep_simple_re: Pattern[str] = ... + whitespace_trans: str = ... + unicode_whitespace_trans: Dict[int, int] = ... + uspace: int = ... + x: int = ... + + def __init__( + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> None: + ... + + def wrap(self, text: AnyStr) -> List[AnyStr]: ... + def fill(self, text: AnyStr) -> AnyStr: ... + +def wrap(text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> List[AnyStr]: ... + +def fill(text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> AnyStr: ... + +def dedent(text: AnyStr) -> AnyStr: ... diff --git a/mypy/stdlib/python2/thread.pyi b/mypy/stdlib/python2/thread.pyi new file mode 100644 index 000000000000..5bc40f4ba8a8 --- /dev/null +++ b/mypy/stdlib/python2/thread.pyi @@ -0,0 +1,28 @@ +"""Stubs for the "thread" module.""" +from typing import Callable, Any + +def _count() -> int: ... + +class error(Exception): ... + +class LockType: + def acquire(self, waitflag: int = ...) -> bool: ... + def acquire_lock(self, waitflag: int = ...) -> bool: ... + def release(self) -> None: ... + def release_lock(self) -> None: ... + def locked(self) -> bool: ... + def locked_lock(self) -> bool: ... + def __enter__(self) -> LockType: ... + def __exit__(self, typ: Any, value: Any, traceback: Any) -> None: ... + +class _local(object): ... +class _localdummy(object): ... + +def start_new(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def start_new_thread(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def interrupt_main() -> None: ... +def exit() -> None: ... +def exit_thread() -> Any: ... +def allocate_lock() -> LockType: ... +def get_ident() -> int: ... +def stack_size(size: int = ...) -> int: ... diff --git a/mypy/stdlib/python2/toaiff.pyi b/mypy/stdlib/python2/toaiff.pyi new file mode 100644 index 000000000000..f3e1b29d50b3 --- /dev/null +++ b/mypy/stdlib/python2/toaiff.pyi @@ -0,0 +1,14 @@ +# Stubs for toaiff (Python 2) + +# Source: https://hg.python.org/cpython/file/2.7/Lib/toaiff.py +from pipes import Template +from typing import Dict, List + +table: Dict[str, Template] +t: Template +uncompress: Template + +class error(Exception): ... + +def toaiff(filename: str) -> str: ... +def _toaiff(filename: str, temps: List[str]) -> str: ... diff --git a/mypy/stdlib/python2/tokenize.pyi b/mypy/stdlib/python2/tokenize.pyi new file mode 100644 index 000000000000..43457b6a95de --- /dev/null +++ b/mypy/stdlib/python2/tokenize.pyi @@ -0,0 +1,136 @@ +# Automatically generated by pytype, manually fixed up. May still contain errors. + +from typing import Any, Callable, Dict, Generator, Iterator, List, Tuple, Union, Iterable + +__author__: str +__credits__: str + +AMPER: int +AMPEREQUAL: int +AT: int +BACKQUOTE: int +Binnumber: str +Bracket: str +CIRCUMFLEX: int +CIRCUMFLEXEQUAL: int +COLON: int +COMMA: int +COMMENT: int +Comment: str +ContStr: str +DEDENT: int +DOT: int +DOUBLESLASH: int +DOUBLESLASHEQUAL: int +DOUBLESTAR: int +DOUBLESTAREQUAL: int +Decnumber: str +Double: str +Double3: str +ENDMARKER: int +EQEQUAL: int +EQUAL: int +ERRORTOKEN: int +Expfloat: str +Exponent: str +Floatnumber: str +Funny: str +GREATER: int +GREATEREQUAL: int +Hexnumber: str +INDENT: int + +def ISEOF(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISTERMINAL(x: int) -> bool: ... + +Ignore: str +Imagnumber: str +Intnumber: str +LBRACE: int +LEFTSHIFT: int +LEFTSHIFTEQUAL: int +LESS: int +LESSEQUAL: int +LPAR: int +LSQB: int +MINEQUAL: int +MINUS: int +NAME: int +NEWLINE: int +NL: int +NOTEQUAL: int +NT_OFFSET: int +NUMBER: int +N_TOKENS: int +Name: str +Number: str +OP: int +Octnumber: str +Operator: str +PERCENT: int +PERCENTEQUAL: int +PLUS: int +PLUSEQUAL: int +PlainToken: str +Pointfloat: str +PseudoExtras: str +PseudoToken: str +RBRACE: int +RIGHTSHIFT: int +RIGHTSHIFTEQUAL: int +RPAR: int +RSQB: int +SEMI: int +SLASH: int +SLASHEQUAL: int +STAR: int +STAREQUAL: int +STRING: int +Single: str +Single3: str +Special: str +String: str +TILDE: int +Token: str +Triple: str +VBAR: int +VBAREQUAL: int +Whitespace: str +chain: type +double3prog: type +endprogs: Dict[str, Any] +pseudoprog: type +single3prog: type +single_quoted: Dict[str, str] +t: str +tabsize: int +tok_name: Dict[int, str] +tokenprog: type +triple_quoted: Dict[str, str] +x: str + +_Pos = Tuple[int, int] +_TokenType = Tuple[int, str, _Pos, _Pos, str] + +def any(*args, **kwargs) -> str: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... +def group(*args: str) -> str: ... +def maybe(*args: str) -> str: ... +def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... +def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def untokenize(iterable: Iterable[_TokenType]) -> str: ... + +class StopTokenizing(Exception): ... + +class TokenError(Exception): ... + +class Untokenizer: + prev_col: int + prev_row: int + tokens: List[str] + def __init__(self) -> None: ... + def add_whitespace(self, _Pos) -> None: ... + def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... + def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/mypy/stdlib/python2/types.pyi b/mypy/stdlib/python2/types.pyi new file mode 100644 index 000000000000..63b296b7030a --- /dev/null +++ b/mypy/stdlib/python2/types.pyi @@ -0,0 +1,187 @@ +# Stubs for types +# Note, all classes "defined" here require special handling. + +from typing import ( + Any, Callable, Dict, Iterable, Iterator, List, Optional, + Tuple, Type, TypeVar, Union, overload, +) + +_T = TypeVar('_T') + +class NoneType: ... +TypeType = type +ObjectType = object + +IntType = int +LongType = int # Really long, but can't reference that due to a mypy import cycle +FloatType = float +BooleanType = bool +ComplexType = complex +StringType = str +UnicodeType = unicode +StringTypes: Tuple[Type[StringType], Type[UnicodeType]] +BufferType = buffer +TupleType = tuple +ListType = list +DictType = dict +DictionaryType = dict + +class _Cell: + cell_contents: Any + +class FunctionType: + func_closure: Optional[Tuple[_Cell, ...]] = ... + func_code: CodeType = ... + func_defaults: Optional[Tuple[Any, ...]] = ... + func_dict: Dict[str, Any] = ... + func_doc: Optional[str] = ... + func_globals: Dict[str, Any] = ... + func_name: str = ... + __closure__ = func_closure + __code__ = func_code + __defaults__ = func_defaults + __dict__ = func_dict + __globals__ = func_globals + __name__ = func_name + def __init__(self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ...) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Optional[object], type: Optional[type]) -> UnboundMethodType: ... + +LambdaType = FunctionType + +class CodeType: + co_argcount: int + co_cellvars: Tuple[str, ...] + co_code: str + co_consts: Tuple[Any, ...] + co_filename: str + co_firstlineno: int + co_flags: int + co_freevars: Tuple[str, ...] + co_lnotab: str + co_name: str + co_names: Tuple[str, ...] + co_nlocals: int + co_stacksize: int + co_varnames: Tuple[str, ...] + def __init__( + self, + argcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: str, + constants: Tuple[Any, ...], + names: Tuple[str, ...], + varnames: Tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: str, + freevars: Tuple[str, ...] = ..., + cellvars: Tuple[str, ...] = ..., + ) -> None: ... + +class GeneratorType: + gi_code: CodeType + gi_frame: FrameType + gi_running: int + def __iter__(self) -> GeneratorType: ... + def close(self) -> None: ... + def next(self) -> Any: ... + def send(self, __arg: Any) -> Any: ... + @overload + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + @overload + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + +class ClassType: ... +class UnboundMethodType: + im_class: type = ... + im_func: FunctionType = ... + im_self: object = ... + __name__: str + __func__ = im_func + __self__ = im_self + def __init__(self, func: Callable[..., Any], obj: object) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class InstanceType(object): ... + +MethodType = UnboundMethodType + +class BuiltinFunctionType: + __self__: Optional[object] + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +BuiltinMethodType = BuiltinFunctionType + +class ModuleType: + __doc__: Optional[str] + __file__: Optional[str] + __name__: str + __package__: Optional[str] + __path__: Optional[Iterable[str]] + __dict__: Dict[str, Any] + def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... +FileType = file +XRangeType = xrange + +class TracebackType: + tb_frame: FrameType + tb_lasti: int + tb_lineno: int + tb_next: TracebackType + +class FrameType: + f_back: FrameType + f_builtins: Dict[str, Any] + f_code: CodeType + f_exc_type: None + f_exc_value: None + f_exc_traceback: None + f_globals: Dict[str, Any] + f_lasti: int + f_lineno: int + f_locals: Dict[str, Any] + f_restricted: bool + f_trace: Callable[[], None] + + def clear(self) -> None: ... + +SliceType = slice +class EllipsisType: ... + +class DictProxyType: + # TODO is it possible to have non-string keys? + # no __init__ + def copy(self) -> Dict[Any, Any]: ... + def get(self, key: str, default: _T = ...) -> Union[Any, _T]: ... + def has_key(self, key: str) -> bool: ... + def items(self) -> List[Tuple[str, Any]]: ... + def iteritems(self) -> Iterator[Tuple[str, Any]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[Any]: ... + def keys(self) -> List[str]: ... + def values(self) -> List[Any]: ... + def __contains__(self, key: str) -> bool: ... + def __getitem__(self, key: str) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class NotImplementedType: ... + +class GetSetDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... +# Same type on Jython, different on CPython and PyPy, unknown on IronPython. +class MemberDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... diff --git a/mypy/stdlib/python2/typing.pyi b/mypy/stdlib/python2/typing.pyi new file mode 100644 index 000000000000..7f677ec858fe --- /dev/null +++ b/mypy/stdlib/python2/typing.pyi @@ -0,0 +1,510 @@ +# Stubs for typing (Python 2.7) + +from abc import abstractmethod, ABCMeta +from types import CodeType, FrameType, TracebackType +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 + +# Definitions of special type checking related constructs. Their definitions +# are not used, so their value does not matter. + +overload = object() +Any = object() + +class TypeVar: + __name__: str + __bound__: Optional[Type[Any]] + __constraints__: Tuple[Type[Any], ...] + __covariant__: bool + __contravariant__: bool + def __init__(self, name: str, *constraints: Type[Any], bound: Optional[Type[Any]] = ..., covariant: bool = ..., contravariant: bool = ...) -> None: ... + +_promote = object() + +class _SpecialForm(object): + def __getitem__(self, typeargs: Any) -> object: ... + +Union: _SpecialForm = ... +Optional: _SpecialForm = ... +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... +Final: _SpecialForm = ... +_F = TypeVar('_F', bound=Callable[..., Any]) +def final(f: _F) -> _F: ... +Literal: _SpecialForm = ... +# TypedDict is a (non-subscriptable) special form. +TypedDict: object = ... + +class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# These type variables are used by the container types. +_T = TypeVar('_T') +_S = TypeVar('_S') +_KT = TypeVar('_KT') # Key type. +_VT = TypeVar('_VT') # Value type. +_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. +_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. +_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. +_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. +_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. +_TC = TypeVar('_TC', bound=Type[object]) +_C = TypeVar("_C", bound=Callable[..., Any]) + +no_type_check = object() +def no_type_check_decorator(decorator: _C) -> _C: ... + +# Type aliases and type constructors + +class _Alias: + # Class for defining generic aliases for library types. + def __getitem__(self, typeargs: Any) -> Any: ... + +List = _Alias() +Dict = _Alias() +DefaultDict = _Alias() +Set = _Alias() +FrozenSet = _Alias() +Counter = _Alias() +Deque = _Alias() + +# Predefined type variables. +AnyStr = TypeVar('AnyStr', str, unicode) + +# Abstract base classes. + +def runtime_checkable(cls: _TC) -> _TC: ... + +@runtime_checkable +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime_checkable +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime_checkable +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime_checkable +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime_checkable +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime_checkable +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime_checkable +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def next(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def next(self) -> _T_co: ... + + @abstractmethod + def send(self, __value: _T_contra) -> _T_co: ... + + @overload + @abstractmethod + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + @overload + @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + + @abstractmethod + def close(self) -> None: ... + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + +@runtime_checkable +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + +class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + def index(self, x: Any) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + # TODO: argument can be any container? + def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView(object): + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +@runtime_checkable +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__(self, __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType]) -> Optional[bool]: ... + +class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: + ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT_co]: ... + def items(self) -> list[Tuple[_KT, _VT_co]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT_co]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... + def __contains__(self, o: object) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = unicode + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + + @abstractmethod + def next(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + +class BinaryIO(IO[str]): + # TODO readinto + # TODO read1? + # TODO peek? + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[unicode]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> bool: ... + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos: int + endpos: int + lastindex: Optional[int] + string: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. This should not be Pattern[AnyStr] because the type + # of the pattern is independent of the type of the matched string in + # Python 2. Strictly speaking Match should be generic over AnyStr twice: + # once for the type of the pattern and once for the type of the matched + # string. + re: Pattern[Any] + # Can be None if there are no groups or if the last group was unnamed; + # otherwise matches the type of the pattern. + lastgroup: Optional[Any] + + def expand(self, template: Union[str, Text]) -> Any: ... + + @overload + def group(self, group1: int = ...) -> AnyStr: ... + @overload + def group(self, group1: str) -> AnyStr: ... + @overload + def group(self, group1: int, group2: int, + *groups: int) -> Tuple[AnyStr, ...]: ... + @overload + def group(self, group1: str, group2: str, + *groups: str) -> Tuple[AnyStr, ...]: ... + + def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... + def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... + def start(self, __group: Union[int, str] = ...) -> int: ... + def end(self, __group: Union[int, str] = ...) -> int: ... + def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + +# We need a second TypeVar with the same definition as AnyStr, because +# Pattern is generic over AnyStr (determining the type of its .pattern +# attribute), but at the same time its methods take either bytes or +# Text and return the same type, regardless of the type of the pattern. +_AnyStr2 = TypeVar('_AnyStr2', bytes, Text) + +class Pattern(Generic[AnyStr]): + flags: int + groupindex: Dict[AnyStr, int] + groups: int + pattern: AnyStr + + def search(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def match(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... + # Returns either a list of _AnyStr2 or a list of tuples, depending on + # whether there are groups in the pattern. + def findall(self, string: Union[bytes, Text], pos: int = ..., + endpos: int = ...) -> List[Any]: ... + def finditer(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... + + @overload + def sub(self, repl: _AnyStr2, string: _AnyStr2, + count: int = ...) -> _AnyStr2: ... + @overload + def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, + count: int = ...) -> _AnyStr2: ... + + @overload + def subn(self, repl: _AnyStr2, string: _AnyStr2, + count: int = ...) -> Tuple[_AnyStr2, int]: ... + @overload + def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, + count: int = ...) -> Tuple[_AnyStr2, int]: ... + +# Functions + +def get_type_hints( + obj: Callable[..., Any], globalns: Optional[Dict[Text, Any]] = ..., localns: Optional[Dict[Text, Any]] = ..., +) -> None: ... + +@overload +def cast(tp: Type[_T], obj: Any) -> _T: ... +@overload +def cast(tp: str, obj: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(Tuple[Any, ...]): + _fields: Tuple[str, ...] + + def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., + **kwargs: Any) -> None: ... + + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + + def _asdict(self) -> Dict[str, Any]: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +class _TypedDict(Mapping[str, object], metaclass=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: ... + 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: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _C) -> _C: ... diff --git a/mypy/stdlib/python2/unittest.pyi b/mypy/stdlib/python2/unittest.pyi new file mode 100644 index 000000000000..b138216feaf1 --- /dev/null +++ b/mypy/stdlib/python2/unittest.pyi @@ -0,0 +1,290 @@ +# Stubs for unittest + +# Based on http://docs.python.org/2.7/library/unittest.html + +from typing import (Any, Callable, Dict, FrozenSet, Iterable, Iterator, + List, Mapping, NoReturn, Optional, overload, Pattern, + Sequence, Set, Text, TextIO, Tuple, Type, TypeVar, Union) +from abc import abstractmethod, ABCMeta +import datetime +import types + +_T = TypeVar('_T') +_FT = TypeVar('_FT') + +_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_Regexp = Union[Text, Pattern[Text]] + +_SysExcInfoType = Union[ + Tuple[Type[BaseException], BaseException, types.TracebackType], + Tuple[None, None, None], +] + +class Testable(metaclass=ABCMeta): + @abstractmethod + def run(self, result: TestResult) -> None: ... + @abstractmethod + def debug(self) -> None: ... + @abstractmethod + def countTestCases(self) -> int: ... + +# TODO ABC for test runners? + +class TestResult: + errors: List[Tuple[TestCase, str]] + failures: List[Tuple[TestCase, str]] + skipped: List[Tuple[TestCase, str]] + expectedFailures: List[Tuple[TestCase, str]] + unexpectedSuccesses: List[TestCase] + shouldStop: bool + testsRun: int + buffer: bool + failfast: bool + + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: TestCase) -> None: ... + def stopTest(self, test: TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addSuccess(self, test: TestCase) -> None: ... + def addSkip(self, test: TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: TestCase, err: str) -> None: ... + def addUnexpectedSuccess(self, test: TestCase) -> None: ... + +class _AssertRaisesBaseContext: + expected: Any + failureException: Type[BaseException] + obj_name: str + expected_regex: Pattern[str] + +class _AssertRaisesContext(_AssertRaisesBaseContext): + exception: Any + def __enter__(self) -> _AssertRaisesContext: ... + def __exit__(self, exc_type, exc_value, tb) -> bool: ... + +class TestCase(Testable): + failureException: Type[BaseException] + longMessage: bool + maxDiff: Optional[int] + # undocumented + _testMethodName: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: TestResult = ...) -> None: ... + def debug(self) -> None: ... + def assert_(self, expr: Any, msg: object = ...) -> None: ... + def failUnless(self, expr: Any, msg: object = ...) -> None: ... + def assertTrue(self, expr: Any, msg: object = ...) -> None: ... + def assertEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def failUnlessEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, *, + msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: datetime.datetime, + second: datetime.datetime, *, + msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, *, + msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEquals(self, first: datetime.datetime, + second: datetime.datetime, *, + msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, + msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: datetime.datetime, + second: datetime.datetime, *, + msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, *, + msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEquals(self, first: datetime.datetime, + second: datetime.datetime, *, + msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def assertGreater(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertGreaterEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, + msg: object = ...) -> None: ... + def assertSequenceEqual(self, first: Sequence[Any], second: Sequence[Any], + msg: object = ..., seq_type: type = ...) -> None: ... + def assertListEqual(self, first: List[Any], second: List[Any], + msg: object = ...) -> None: ... + def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], + msg: object = ...) -> None: ... + def assertSetEqual(self, first: Union[Set[Any], FrozenSet[Any]], + second: Union[Set[Any], FrozenSet[Any]], msg: object = ...) -> None: ... + def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], + msg: object = ...) -> None: ... + def assertLess(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertLessEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... + def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... + def assertDictContainsSubset(self, + expected: Mapping[Any, Any], + actual: Mapping[Any, Any], + msg: object = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + def failIf(self, expr: Any, msg: object = ...) -> None: ... + def assertFalse(self, expr: Any, msg: object = ...) -> None: ... + def assertIs(self, first: object, second: object, + msg: object = ...) -> None: ... + def assertIsNot(self, first: object, second: object, + msg: object = ...) -> None: ... + def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIn(self, first: _T, second: Iterable[_T], + msg: object = ...) -> None: ... + def assertNotIn(self, first: _T, second: Iterable[_T], + msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], + msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], + msg: object = ...) -> None: ... + def fail(self, msg: object = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> str: ... # May return None + def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... + def doCleanups(self) -> bool: ... + def skipTest(self, reason: Any) -> None: ... + def _formatMessage(self, msg: Optional[Text], standardMsg: Text) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + +class FunctionTestCase(TestCase): + def __init__(self, testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ...) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + +class TestSuite(Testable): + def __init__(self, tests: Iterable[Testable] = ...) -> None: ... + def addTest(self, test: Testable) -> None: ... + def addTests(self, tests: Iterable[Testable]) -> None: ... + def run(self, result: TestResult) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[Testable]: ... + +class TestLoader: + testMethodPrefix: str + sortTestMethodsUsing: Optional[Callable[[str, str], int]] + suiteClass: Callable[[List[TestCase]], TestSuite] + def loadTestsFromTestCase(self, + testCaseClass: Type[TestCase]) -> TestSuite: ... + def loadTestsFromModule(self, module: types.ModuleType = ..., + use_load_tests: bool = ...) -> TestSuite: ... + def loadTestsFromName(self, name: str = ..., + module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: List[str] = ..., + module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def discover(self, start_dir: str, pattern: str = ..., + top_level_dir: Optional[str] = ...) -> TestSuite: ... + def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + +defaultTestLoader: TestLoader + +class TextTestResult(TestResult): + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + def getDescription(self, test: TestCase) -> str: ... # undocumented + def printErrors(self) -> None: ... # undocumented + def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented + +class TextTestRunner: + def __init__(self, stream: Optional[TextIO] = ..., descriptions: bool = ..., + verbosity: int = ..., failfast: bool = ..., buffer: bool = ..., + resultclass: Optional[Type[TestResult]] = ...) -> None: ... + def _makeResult(self) -> TestResult: ... + def run(self, test: Testable) -> TestResult: ... # undocumented + +class SkipTest(Exception): + ... + +# TODO precise types +def skipUnless(condition: Any, reason: Union[str, unicode]) -> Any: ... +def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ... +def expectedFailure(func: _FT) -> _FT: ... +def skip(reason: Union[str, unicode]) -> Any: ... + +# not really documented +class TestProgram: + result: TestResult + def runTests(self) -> None: ... # undocumented + +def main(module: Union[None, Text, types.ModuleType] = ..., defaultTest: Optional[str] = ..., + argv: Optional[Sequence[str]] = ..., + testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ..., + testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., + failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ...) -> TestProgram: ... + +def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[Text]) -> TestSuite: ... + +def installHandler() -> None: ... +def registerResult(result: TestResult) -> None: ... +def removeResult(result: TestResult) -> bool: ... +@overload +def removeHandler() -> None: ... +@overload +def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... + +# private but occasionally used +util: types.ModuleType diff --git a/mypy/stdlib/python2/urllib.pyi b/mypy/stdlib/python2/urllib.pyi new file mode 100644 index 000000000000..fe04494897cb --- /dev/null +++ b/mypy/stdlib/python2/urllib.pyi @@ -0,0 +1,134 @@ +from typing import Any, AnyStr, IO, List, Mapping, Sequence, Text, Tuple, TypeVar, Union + +def url2pathname(pathname: AnyStr) -> AnyStr: ... +def pathname2url(pathname: AnyStr) -> AnyStr: ... +def urlopen(url: str, data=..., proxies: Mapping[str, str] = ..., context=...) -> IO[Any]: ... +def urlretrieve(url, filename=..., reporthook=..., data=..., context=...): ... +def urlcleanup() -> None: ... + +class ContentTooShortError(IOError): + content: Any + def __init__(self, message, content) -> None: ... + +class URLopener: + version: Any + proxies: Any + key_file: Any + cert_file: Any + context: Any + addheaders: Any + tempcache: Any + ftpcache: Any + def __init__(self, proxies: Mapping[str, str] = ..., context=..., **x509) -> None: ... + def __del__(self): ... + def close(self): ... + def cleanup(self): ... + def addheader(self, *args): ... + type: Any + def open(self, fullurl: str, data=...): ... + def open_unknown(self, fullurl, data=...): ... + def open_unknown_proxy(self, proxy, fullurl, data=...): ... + def retrieve(self, url, filename=..., reporthook=..., data=...): ... + def open_http(self, url, data=...): ... + def http_error(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def open_https(self, url, data=...): ... + def open_file(self, url): ... + def open_local_file(self, url): ... + def open_ftp(self, url): ... + def open_data(self, url, data=...): ... + +class FancyURLopener(URLopener): + auth_cache: Any + tries: Any + maxtries: Any + def __init__(self, *args, **kwargs) -> None: ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def http_error_302(self, url, fp, errcode, errmsg, headers, data=...): ... + def redirect_internal(self, url, fp, errcode, errmsg, headers, data): ... + def http_error_301(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_303(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_307(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_401(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_407(self, url, fp, errcode, errmsg, headers, data=...): ... + def retry_proxy_http_basic_auth(self, url, realm, data=...): ... + def retry_proxy_https_basic_auth(self, url, realm, data=...): ... + def retry_http_basic_auth(self, url, realm, data=...): ... + def retry_https_basic_auth(self, url, realm, data=...): ... + def get_user_passwd(self, host, realm, clear_cache=...): ... + def prompt_user_passwd(self, host, realm): ... + +class ftpwrapper: + user: Any + passwd: Any + host: Any + port: Any + dirs: Any + timeout: Any + refcount: Any + keepalive: Any + def __init__(self, user, passwd, host, port, dirs, timeout=..., persistent=...) -> None: ... + busy: Any + ftp: Any + def init(self): ... + def retrfile(self, file, type): ... + def endtransfer(self): ... + def close(self): ... + def file_close(self): ... + def real_close(self): ... + +_AIUT = TypeVar("_AIUT", bound=addbase) + +class addbase: + fp: Any + def read(self, n: int = ...) -> bytes: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def fileno(self) -> int: ... # Optional[int], but that is rare + def __iter__(self: _AIUT) -> _AIUT: ... + def next(self) -> bytes: ... + def __init__(self, fp) -> None: ... + def close(self) -> None: ... + +class addclosehook(addbase): + closehook: Any + hookargs: Any + def __init__(self, fp, closehook, *hookargs) -> None: ... + def close(self): ... + +class addinfo(addbase): + headers: Any + def __init__(self, fp, headers) -> None: ... + def info(self): ... + +class addinfourl(addbase): + headers: Any + url: Any + code: Any + def __init__(self, fp, headers, url, code=...) -> None: ... + def info(self): ... + def getcode(self): ... + def geturl(self): ... + +def unwrap(url): ... +def splittype(url): ... +def splithost(url): ... +def splituser(host): ... +def splitpasswd(user): ... +def splitport(host): ... +def splitnport(host, defport=...): ... +def splitquery(url): ... +def splittag(url): ... +def splitattr(url): ... +def splitvalue(attr): ... +def unquote(s: AnyStr) -> AnyStr: ... +def unquote_plus(s: AnyStr) -> AnyStr: ... +def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def urlencode(query: Union[Sequence[Tuple[Any, Any]], Mapping[Any, Any]], doseq=...) -> str: ... + +def getproxies() -> Mapping[str, str]: ... +def proxy_bypass(host: str) -> Any: ... # Undocumented + +# Names in __all__ with no definition: +# basejoin diff --git a/mypy/stdlib/python2/urllib2.pyi b/mypy/stdlib/python2/urllib2.pyi new file mode 100644 index 000000000000..6611ad240a96 --- /dev/null +++ b/mypy/stdlib/python2/urllib2.pyi @@ -0,0 +1,182 @@ + +import ssl +from typing import Any, AnyStr, Dict, List, Union, Optional, Mapping, Callable, Sequence, Text, Tuple, Type +from urllib import addinfourl +from httplib import HTTPConnectionProtocol, HTTPResponse + +_string = Union[str, unicode] + +class URLError(IOError): + reason: Union[str, BaseException] + +class HTTPError(URLError, addinfourl): + code: int + headers: Mapping[str, str] + def __init__(self, url, code: int, msg: str, hdrs: Mapping[str, str], fp: addinfourl) -> None: ... + +class Request(object): + host: str + port: str + data: str + headers: Dict[str, str] + unverifiable: bool + type: Optional[str] + origin_req_host = ... + unredirected_hdrs: Dict[str, str] + + def __init__(self, url: str, data: Optional[str] = ..., headers: Dict[str, str] = ..., + origin_req_host: Optional[str] = ..., unverifiable: bool = ...) -> None: ... + def __getattr__(self, attr): ... + def get_method(self) -> str: ... + def add_data(self, data) -> None: ... + def has_data(self) -> bool: ... + def get_data(self) -> str: ... + def get_full_url(self) -> str: ... + def get_type(self): ... + def get_host(self) -> str: ... + def get_selector(self): ... + def set_proxy(self, host, type) -> None: ... + def has_proxy(self) -> bool: ... + def get_origin_req_host(self) -> str: ... + def is_unverifiable(self) -> bool: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def get_header(self, header_name: str, default: Optional[str] = ...) -> str: ... + def header_items(self): ... + +class OpenerDirector(object): + addheaders: List[Tuple[str, str]] + + def add_handler(self, handler: BaseHandler) -> None: ... + def open(self, fullurl: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ...) -> Optional[addinfourl]: ... + def error(self, proto: _string, *args: Any): ... + +# Note that this type is somewhat a lie. The return *can* be None if +# a custom opener has been installed that fails to handle the request. +def urlopen(url: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ..., + cafile: Optional[_string] = ..., capath: Optional[_string] = ..., cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ...) -> addinfourl: ... +def install_opener(opener: OpenerDirector) -> None: ... +def build_opener(*handlers: Union[BaseHandler, Type[BaseHandler]]) -> OpenerDirector: ... + +class BaseHandler: + handler_order: int + parent: OpenerDirector + + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def __lt__(self, other: Any) -> bool: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request, response): ... + +class HTTPDefaultErrorHandler(BaseHandler): + def http_error_default(self, req: Request, fp: addinfourl, code: int, msg: str, hdrs: Mapping[str, str]): ... + +class HTTPRedirectHandler(BaseHandler): + max_repeats: int + max_redirections: int + def redirect_request(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str], newurl): ... + def http_error_301(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_302(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_303(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_307(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + inf_msg: str + + +class ProxyHandler(BaseHandler): + proxies: Mapping[str, str] + + def __init__(self, proxies: Optional[Mapping[str, str]] = ...): ... + def proxy_open(self, req: Request, proxy, type): ... + +class HTTPPasswordMgr: + def __init__(self) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def find_user_password(self, realm: Optional[Text], authuri: Text) -> Tuple[Any, Any]: ... + def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... + def is_suburi(self, base: _string, test: _string) -> bool: ... + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... + +class AbstractBasicAuthHandler: + def __init__(self, password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def http_error_auth_reqed(self, authreq, host, req: Request, headers: Mapping[str, str]): ... + def retry_http_basic_auth(self, host, req: Request, realm): ... + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: str + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: str + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[HTTPResponse]: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: str + handler_order: int + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: str + handler_order: int + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + def __init__(self, debuglevel: int = ...) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, + http_class: HTTPConnectionProtocol, + req: Request, + **http_conn_args: Optional[Any]) -> addinfourl: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> addinfourl: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + def __init__(self, debuglevel: int = ..., context: Optional[ssl.SSLContext] = ...) -> None: ... + def https_open(self, req: Request) -> addinfourl: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class HTTPCookieProcessor(BaseHandler): + def __init__(self, cookiejar: Optional[Any] = ...): ... + def http_request(self, request: Request): ... + def http_response(self, request: Request, response): ... + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request): ... + +class FileHandler(BaseHandler): + def file_open(self, req: Request): ... + def get_names(self): ... + def open_local_file(self, req: Request): ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request): ... + def connect_ftp(self, user, passwd, host, port, dirs, timeout): ... + +class CacheFTPHandler(FTPHandler): + def __init__(self) -> None: ... + def setTimeout(self, t: Optional[float]): ... + def setMaxConns(self, m: int): ... + def check_cache(self): ... + def clear_cache(self): ... + +def parse_http_list(s: AnyStr) -> List[AnyStr]: ... +def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... diff --git a/mypy/stdlib/python2/urlparse.pyi b/mypy/stdlib/python2/urlparse.pyi new file mode 100644 index 000000000000..12a04529ad9e --- /dev/null +++ b/mypy/stdlib/python2/urlparse.pyi @@ -0,0 +1,66 @@ +# Stubs for urlparse (Python 2) + +from typing import AnyStr, Dict, List, NamedTuple, Tuple, Sequence, Union, overload, Optional + +_String = Union[str, unicode] + +uses_relative: List[str] +uses_netloc: List[str] +uses_params: List[str] +non_hierarchical: List[str] +uses_query: List[str] +uses_fragment: List[str] +scheme_chars: str +MAX_CACHE_SIZE: int + +def clear_cache() -> None: ... + +class ResultMixin(object): + @property + def username(self) -> Optional[_String]: ... + @property + def password(self) -> Optional[_String]: ... + @property + def hostname(self) -> Optional[_String]: ... + @property + def port(self) -> Optional[int]: ... + +class _SplitResult(NamedTuple): + scheme: _String + netloc: _String + path: _String + query: _String + fragment: _String +class SplitResult(_SplitResult, ResultMixin): + def geturl(self) -> _String: ... + +class _ParseResult(NamedTuple): + scheme: _String + netloc: _String + path: _String + params: _String + query: _String + fragment: _String +class ParseResult(_ParseResult, ResultMixin): + def geturl(self) -> _String: ... + +def urlparse(url: _String, scheme: _String = ..., + allow_fragments: bool = ...) -> ParseResult: ... +def urlsplit(url: _String, scheme: _String = ..., + allow_fragments: bool = ...) -> SplitResult: ... +@overload +def urlunparse(data: Tuple[_String, _String, _String, _String, _String, _String]) -> _String: ... +@overload +def urlunparse(data: Sequence[_String]) -> _String: ... +@overload +def urlunsplit(data: Tuple[_String, _String, _String, _String, _String]) -> _String: ... +@overload +def urlunsplit(data: Sequence[_String]) -> _String: ... +def urljoin(base: _String, url: _String, + allow_fragments: bool = ...) -> _String: ... +def urldefrag(url: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def unquote(s: AnyStr) -> AnyStr: ... +def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., + strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... +def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., + strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... diff --git a/mypy/stdlib/python2/user.pyi b/mypy/stdlib/python2/user.pyi new file mode 100644 index 000000000000..e857a3a9516e --- /dev/null +++ b/mypy/stdlib/python2/user.pyi @@ -0,0 +1,9 @@ +# Stubs for user (Python 2) + +# Docs: https://docs.python.org/2/library/user.html +# Source: https://hg.python.org/cpython/file/2.7/Lib/user.py +from typing import Any + +def __getattr__(name) -> Any: ... +home: str +pythonrc: str diff --git a/mypy/stdlib/python2/whichdb.pyi b/mypy/stdlib/python2/whichdb.pyi new file mode 100644 index 000000000000..b1a69f4816c4 --- /dev/null +++ b/mypy/stdlib/python2/whichdb.pyi @@ -0,0 +1,5 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/whichdb.py + +from typing import Optional, Text + +def whichdb(filename: Text) -> Optional[str]: ... diff --git a/mypy/stdlib/python2/xmlrpclib.pyi b/mypy/stdlib/python2/xmlrpclib.pyi new file mode 100644 index 000000000000..d1d293718dae --- /dev/null +++ b/mypy/stdlib/python2/xmlrpclib.pyi @@ -0,0 +1,231 @@ +# Stubs for xmlrpclib (Python 2) + +from typing import Any, AnyStr, Callable, IO, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, TypeVar, Union +from types import InstanceType +from datetime import datetime +from time import struct_time +from httplib import HTTPConnection, HTTPResponse, HTTPSConnection +from ssl import SSLContext +from StringIO import StringIO +from gzip import GzipFile + +_Unmarshaller = Any +_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] +# Represents types that can be compared against a DateTime object +_dateTimeComp = Union[unicode, DateTime, datetime] +# A "host description" used by Transport factories +_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] + +def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... + +MAXINT: int +MININT: int +PARSE_ERROR: int +SERVER_ERROR: int +APPLICATION_ERROR: int +SYSTEM_ERROR: int +TRANSPORT_ERROR: int +NOT_WELLFORMED_ERROR: int +UNSUPPORTED_ENCODING: int +INVALID_ENCODING_CHAR: int +INVALID_XMLRPC: int +METHOD_NOT_FOUND: int +INVALID_METHOD_PARAMS: int +INTERNAL_ERROR: int + +class Error(Exception): ... + +class ProtocolError(Error): + url: str + errcode: int + errmsg: str + headers: Any + def __init__(self, url: str, errcode: int, errmsg: str, headers: Any) -> None: ... + +class ResponseError(Error): ... + +class Fault(Error): + faultCode: Any + faultString: str + def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... + +boolean: Type[bool] +Boolean: Type[bool] + +class DateTime: + value: str + def __init__(self, value: Union[str, unicode, datetime, float, int, _timeTuple, struct_time] = ...) -> None: ... + def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... + def __lt__(self, other: _dateTimeComp) -> bool: ... + def __le__(self, other: _dateTimeComp) -> bool: ... + def __gt__(self, other: _dateTimeComp) -> bool: ... + def __ge__(self, other: _dateTimeComp) -> bool: ... + def __eq__(self, other: _dateTimeComp) -> bool: ... # type: ignore + def __ne__(self, other: _dateTimeComp) -> bool: ... # type: ignore + def timetuple(self) -> struct_time: ... + def __cmp__(self, other: _dateTimeComp) -> int: ... + def decode(self, data: Any) -> None: ... + def encode(self, out: IO[str]) -> None: ... + +class Binary: + data: str + def __init__(self, data: Optional[str] = ...) -> None: ... + def __cmp__(self, other: Any) -> int: ... + def decode(self, data: str) -> None: ... + def encode(self, out: IO[str]) -> None: ... + +WRAPPERS: Tuple[Type[Any], ...] + +# Still part of the public API, but see http://bugs.python.org/issue1773632 +FastParser: None +FastUnmarshaller: None +FastMarshaller: None + +# xmlrpclib.py will leave ExpatParser undefined if it can't import expat from +# xml.parsers. Because this is Python 2.7, the import will succeed. +class ExpatParser: + def __init__(self, target: _Unmarshaller) -> None: ... + def feed(self, data: str): ... + def close(self): ... + +# TODO: Add xmllib.XMLParser as base class +class SlowParser: + handle_xml: Callable[[str, bool], None] + unknown_starttag: Callable[[str, Any], None] + handle_data: Callable[[str], None] + handle_cdata: Callable[[str], None] + unknown_endtag: Callable[[str, Callable[[Iterable[str], str], str]], None] + def __init__(self, target: _Unmarshaller) -> None: ... + +class Marshaller: + memo: MutableMapping[int, Any] + data: Optional[str] + encoding: Optional[str] + allow_none: bool + def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... + dispatch: Mapping[type, Callable[[Marshaller, str, Callable[[str], None]], None]] + def dumps( + self, + values: Union[ + Iterable[ + Union[ + None, + int, + bool, + long, + float, + str, + unicode, + List[Any], + Tuple[Any, ...], + Mapping[Any, Any], + datetime, + InstanceType, + ], + ], + Fault, + ], + ) -> str: ... + def dump_nil(self, value: None, write: Callable[[str], None]) -> None: ... + def dump_int(self, value: int, write: Callable[[str], None]) -> None: ... + def dump_bool(self, value: bool, write: Callable[[str], None]) -> None: ... + def dump_long(self, value: long, write: Callable[[str], None]) -> None: ... + def dump_double(self, value: float, write: Callable[[str], None]) -> None: ... + def dump_string(self, value: str, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... + def dump_unicode(self, value: unicode, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... + def dump_array(self, value: Iterable[Any], write: Callable[[str], None]) -> None: ... + def dump_struct( + self, + value: Mapping[unicode, Any], + write: Callable[[str], None], + escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., + ) -> None: ... + def dump_datetime(self, value: datetime, write: Callable[[str], None]) -> None: ... + def dump_instance(self, value: InstanceType, write: Callable[[str], None]) -> None: ... + +class Unmarshaller: + def append(self, object: Any) -> None: ... + def __init__(self, use_datetime: bool = ...) -> None: ... + def close(self) -> Tuple[Any, ...]: ... + def getmethodname(self) -> Optional[str]: ... + def xml(self, encoding: str, standalone: bool) -> None: ... + def start(self, tag: str, attrs: Any) -> None: ... + def data(self, text: str) -> None: ... + def end(self, tag: str, join: Callable[[Iterable[str], str], str] = ...) -> None: ... + def end_dispatch(self, tag: str, data: str) -> None: ... + dispatch: Mapping[str, Callable[[Unmarshaller, str], None]] + def end_nil(self, data: str): ... + def end_boolean(self, data: str) -> None: ... + def end_int(self, data: str) -> None: ... + def end_double(self, data: str) -> None: ... + def end_string(self, data: str) -> None: ... + def end_array(self, data: str) -> None: ... + def end_struct(self, data: str) -> None: ... + def end_base64(self, data: str) -> None: ... + def end_dateTime(self, data: str) -> None: ... + def end_value(self, data: str) -> None: ... + def end_params(self, data: str) -> None: ... + def end_fault(self, data: str) -> None: ... + def end_methodName(self, data: str) -> None: ... + +class _MultiCallMethod: + def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... +class MultiCallIterator: + def __init__(self, results: List[Any]) -> None: ... + +class MultiCall: + def __init__(self, server: ServerProxy) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self) -> MultiCallIterator: ... + +def getparser(use_datetime: bool = ...) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... +def dumps( + params: Union[Tuple[Any, ...], Fault], + methodname: Optional[str] = ..., + methodresponse: Optional[bool] = ..., + encoding: Optional[str] = ..., + allow_none: bool = ..., +) -> str: ... +def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], Optional[str]]: ... + +def gzip_encode(data: str) -> str: ... +def gzip_decode(data: str, max_decode: int = ...) -> str: ... + +class GzipDecodedResponse(GzipFile): + stringio: StringIO[Any] + def __init__(self, response: HTTPResponse) -> None: ... + def close(self): ... + +class _Method: + def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, *args: Any) -> Any: ... + +class Transport: + user_agent: str + accept_gzip_encoding: bool + encode_threshold: Optional[int] + def __init__(self, use_datetime: bool = ...) -> None: ... + def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + verbose: bool + def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + def getparser(self) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... + def get_host_info(self, host: _hostDesc) -> Tuple[str, Optional[List[Tuple[str, str]]], Optional[Mapping[Any, Any]]]: ... + def make_connection(self, host: _hostDesc) -> HTTPConnection: ... + def close(self) -> None: ... + def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... + def send_host(self, connection: HTTPConnection, host: str) -> None: ... + def send_user_agent(self, connection: HTTPConnection) -> None: ... + def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... + def parse_response(self, response: HTTPResponse) -> Tuple[Any, ...]: ... + +class SafeTransport(Transport): + def __init__(self, use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... + def make_connection(self, host: _hostDesc) -> HTTPSConnection: ... + +class ServerProxy: + def __init__(self, uri: str, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, attr: str) -> Optional[Transport]: ... + +Server = ServerProxy diff --git a/mypy/stdlib/queue.pyi b/mypy/stdlib/queue.pyi new file mode 100644 index 000000000000..ba995e743dee --- /dev/null +++ b/mypy/stdlib/queue.pyi @@ -0,0 +1,50 @@ +# Stubs for queue + +# NOTE: These are incomplete! + +from threading import Condition, Lock +from typing import Any, TypeVar, Generic, Optional +import sys + +_T = TypeVar('_T') + +class Empty(Exception): ... +class Full(Exception): ... + +class Queue(Generic[_T]): + maxsize: int + + mutex: Lock # undocumented + not_empty: Condition # undocumented + not_full: Condition # undocumented + all_tasks_done: Condition # undocumented + unfinished_tasks: int # undocumented + queue: Any # undocumented + + def __init__(self, maxsize: int = ...) -> None: ... + def _init(self, maxsize: int) -> None: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + def _get(self) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def _put(self, item: _T) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def _qsize(self) -> int: ... + def task_done(self) -> None: ... + +class PriorityQueue(Queue[_T]): ... +class LifoQueue(Queue[_T]): ... + +if sys.version_info >= (3, 7): + class SimpleQueue(Generic[_T]): + def __init__(self) -> None: ... + def empty(self) -> bool: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def qsize(self) -> int: ... diff --git a/mypy/stdlib/quopri.pyi b/mypy/stdlib/quopri.pyi new file mode 100644 index 000000000000..2823f8c40b53 --- /dev/null +++ b/mypy/stdlib/quopri.pyi @@ -0,0 +1,8 @@ +# Stubs for quopri (Python 2 and 3) + +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/stdlib/random.pyi b/mypy/stdlib/random.pyi new file mode 100644 index 000000000000..fab7770a4dd9 --- /dev/null +++ b/mypy/stdlib/random.pyi @@ -0,0 +1,79 @@ +# Stubs for random +# Ron Murawski +# Updated by Jukka Lehtosalo + +# based on http://docs.python.org/3.2/library/random.html + +# ----- random classes ----- + +import _random +import sys +from typing import Any, TypeVar, Sequence, Iterable, List, Callable, AbstractSet, Union, Optional, Tuple + +_T = TypeVar('_T') + +class Random(_random.Random): + def __init__(self, x: Any = ...) -> None: ... + def seed(self, a: Any = ..., version: int = ...) -> None: ... + def getstate(self) -> Tuple[Any, ...]: ... + def setstate(self, state: Tuple[Any, ...]) -> None: ... + def getrandbits(self, __k: int) -> int: ... + def randrange(self, start: int, stop: Union[int, None] = ..., step: int = ...) -> int: ... + def randint(self, a: int, b: int) -> int: ... + if sys.version_info >= (3, 9): + def randbytes(self, n: int) -> bytes: ... + def choice(self, seq: Sequence[_T]) -> _T: ... + if sys.version_info >= (3, 6): + def choices(self, population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... + def shuffle(self, x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... + if sys.version_info >= (3, 9): + def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> List[_T]: ... + else: + def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = ..., high: float = ..., mode: Optional[float] = ...) -> float: ... + def betavariate(self, alpha: float, beta: float) -> float: ... + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... + def gauss(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): + ... + +# ----- random function stubs ----- +def seed(a: Any = ..., version: int = ...) -> None: ... +def getstate() -> object: ... +def setstate(state: object) -> None: ... +def getrandbits(__k: int) -> int: ... +def randrange(start: int, stop: Union[None, int] = ..., step: int = ...) -> int: ... +def randint(a: int, b: int) -> int: ... +if sys.version_info >= (3, 9): + def randbytes(n: int) -> bytes: ... +def choice(seq: Sequence[_T]) -> _T: ... +if sys.version_info >= (3, 6): + def choices(population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... +def shuffle(x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... +if sys.version_info >= (3, 9): + def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> List[_T]: ... +else: + def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... +def random() -> float: ... +def uniform(a: float, b: float) -> float: ... +def triangular(low: float = ..., high: float = ..., + mode: Optional[float] = ...) -> float: ... +def betavariate(alpha: float, beta: float) -> float: ... +def expovariate(lambd: float) -> float: ... +def gammavariate(alpha: float, beta: float) -> float: ... +def gauss(mu: float, sigma: float) -> float: ... +def lognormvariate(mu: float, sigma: float) -> float: ... +def normalvariate(mu: float, sigma: float) -> float: ... +def vonmisesvariate(mu: float, kappa: float) -> float: ... +def paretovariate(alpha: float) -> float: ... +def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/mypy/stdlib/re.pyi b/mypy/stdlib/re.pyi new file mode 100644 index 000000000000..bfab4819a78c --- /dev/null +++ b/mypy/stdlib/re.pyi @@ -0,0 +1,160 @@ +# Stubs for re +# Ron Murawski +# 'bytes' support added by Jukka Lehtosalo + +# based on: http://docs.python.org/3.2/library/re.html +# and http://hg.python.org/cpython/file/618ea5612e83/Lib/re.py + +import sys +from typing import ( + List, Iterator, overload, Callable, Tuple, + AnyStr, Any, Optional, Union +) + +# ----- re variables and constants ----- +if sys.version_info >= (3, 7): + from typing import Pattern as Pattern, Match as Match +else: + from typing import Pattern, Match + +if sys.version_info >= (3, 6): + import enum + class RegexFlag(enum.IntFlag): + A: int + ASCII: int + DEBUG: int + I: int + IGNORECASE: int + L: int + LOCALE: int + M: int + MULTILINE: int + S: int + DOTALL: int + X: int + VERBOSE: int + U: int + UNICODE: int + T: int + TEMPLATE: int + + A = RegexFlag.A + ASCII = RegexFlag.ASCII + DEBUG = RegexFlag.DEBUG + I = RegexFlag.I + IGNORECASE = RegexFlag.IGNORECASE + L = RegexFlag.L + LOCALE = RegexFlag.LOCALE + M = RegexFlag.M + MULTILINE = RegexFlag.MULTILINE + S = RegexFlag.S + DOTALL = RegexFlag.DOTALL + X = RegexFlag.X + VERBOSE = RegexFlag.VERBOSE + U = RegexFlag.U + UNICODE = RegexFlag.UNICODE + T = RegexFlag.T + TEMPLATE = RegexFlag.TEMPLATE + _FlagsType = Union[int, RegexFlag] +else: + A: int + ASCII: int + DEBUG: int + I: int + IGNORECASE: int + L: int + LOCALE: int + M: int + MULTILINE: int + S: int + DOTALL: int + X: int + VERBOSE: int + U: int + UNICODE: int + T: int + TEMPLATE: int + _FlagsType = int + +if sys.version_info < (3, 7): + # undocumented + _pattern_type: type + +class error(Exception): ... + +@overload +def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... + +@overload +def search(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +# New in Python 3.4 +@overload +def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def split(pattern: AnyStr, string: AnyStr, + maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... +@overload +def split(pattern: Pattern[AnyStr], string: AnyStr, + maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... + +@overload +def findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> List[Any]: ... +@overload +def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> List[Any]: ... + +# Return an iterator yielding match objects over all non-overlapping matches +# for the RE pattern in string. The string is scanned left-to-right, and +# matches are returned in the order found. Empty matches are included in the +# result unless they touch the beginning of another match. +@overload +def finditer(pattern: AnyStr, string: AnyStr, + flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def finditer(pattern: Pattern[AnyStr], string: AnyStr, + flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... + +@overload +def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... + +@overload +def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... + +def escape(pattern: AnyStr) -> AnyStr: ... + +def purge() -> None: ... +def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/stdlib/readline.pyi b/mypy/stdlib/readline.pyi new file mode 100644 index 000000000000..aff2debf266a --- /dev/null +++ b/mypy/stdlib/readline.pyi @@ -0,0 +1,41 @@ +# Stubs for readline + +from typing import Callable, Optional, Sequence +import sys + +_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: str = ...) -> None: ... + +def get_line_buffer() -> str: ... +def insert_text(string: str) -> None: ... +def redisplay() -> None: ... + +def read_history_file(filename: str = ...) -> None: ... +def write_history_file(filename: str = ...) -> None: ... +if sys.version_info >= (3, 5): + def append_history_file(nelements: int, filename: str = ...) -> 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/stdlib/reprlib.pyi b/mypy/stdlib/reprlib.pyi new file mode 100644 index 000000000000..7ff879bc7704 --- /dev/null +++ b/mypy/stdlib/reprlib.pyi @@ -0,0 +1,37 @@ +# Stubs for reprlib (Python 3) + +from array import array +from typing import Any, Callable, Deque, Dict, FrozenSet, List, Set, Tuple + +_ReprFunc = Callable[[Any], str] + +def recursive_repr(fillvalue: str = ...) -> Callable[[_ReprFunc], _ReprFunc]: ... + +class Repr: + maxlevel: int + maxdict: int + maxlist: int + maxtuple: int + maxset: int + maxfrozenset: int + maxdeque: int + maxarray: int + maxlong: int + maxstring: int + maxother: int + def __init__(self) -> None: ... + def repr(self, x: Any) -> str: ... + def repr1(self, x: Any, level: int) -> str: ... + def repr_tuple(self, x: Tuple[Any, ...], level: int) -> str: ... + def repr_list(self, x: List[Any], level: int) -> str: ... + def repr_array(self, x: array[Any], level: int) -> str: ... + def repr_set(self, x: Set[Any], level: int) -> str: ... + def repr_frozenset(self, x: FrozenSet[Any], level: int) -> str: ... + def repr_deque(self, x: Deque[Any], level: int) -> str: ... + def repr_dict(self, x: Dict[Any, Any], level: int) -> str: ... + def repr_str(self, x: str, level: int) -> str: ... + def repr_int(self, x: int, level: int) -> str: ... + def repr_instance(self, x: Any, level: int) -> str: ... + +aRepr: Repr +def repr(x: object) -> str: ... diff --git a/mypy/stdlib/resource.pyi b/mypy/stdlib/resource.pyi new file mode 100644 index 000000000000..280b581d0291 --- /dev/null +++ b/mypy/stdlib/resource.pyi @@ -0,0 +1,53 @@ +# Stubs for resource + +import sys +from typing import Tuple, Optional, NamedTuple + +RLIMIT_AS: int +RLIMIT_CORE: int +RLIMIT_CPU: int +RLIMIT_DATA: int +RLIMIT_FSIZE: int +RLIMIT_MEMLOCK: int +RLIMIT_NOFILE: int +RLIMIT_NPROC: int +RLIMIT_RSS: int +RLIMIT_STACK: int +RLIM_INFINITY: int +RUSAGE_CHILDREN: int +RUSAGE_SELF: int +if sys.platform == "linux": + RLIMIT_MSGQUEUE: int + RLIMIT_NICE: int + RLIMIT_OFILE: int + RLIMIT_RTPRIO: int + RLIMIT_RTTIME: int + RLIMIT_SIGPENDING: int + RUSAGE_THREAD: int + +class _RUsage(NamedTuple): + ru_utime: float + ru_stime: float + ru_maxrss: int + ru_ixrss: int + ru_idrss: int + ru_isrss: int + ru_minflt: int + ru_majflt: int + ru_nswap: int + ru_inblock: int + ru_oublock: int + ru_msgsnd: int + ru_msgrcv: int + ru_nsignals: int + ru_nvcsw: int + ru_nivcsw: int + +def getpagesize() -> int: ... +def getrlimit(__resource: int) -> Tuple[int, int]: ... +def getrusage(__who: int) -> _RUsage: ... +def setrlimit(__resource: int, __limits: Tuple[int, int]) -> None: ... +if sys.platform == "linux": + def prlimit(pid: int, resource: int, limits: Optional[Tuple[int, int]]) -> Tuple[int, int]: ... + +error = OSError diff --git a/mypy/stdlib/rlcompleter.pyi b/mypy/stdlib/rlcompleter.pyi new file mode 100644 index 000000000000..3db9d0c40799 --- /dev/null +++ b/mypy/stdlib/rlcompleter.pyi @@ -0,0 +1,14 @@ +# Stubs for rlcompleter + +from typing import Any, Dict, Optional, Union +import sys + +if sys.version_info >= (3,): + _Text = str +else: + _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/stdlib/runpy.pyi b/mypy/stdlib/runpy.pyi new file mode 100644 index 000000000000..654c53c8ebb3 --- /dev/null +++ b/mypy/stdlib/runpy.pyi @@ -0,0 +1,23 @@ +from types import ModuleType +from typing import Dict, Optional, Any + +class _TempModule: + mod_name: str = ... + module: ModuleType = ... + def __init__(self, mod_name): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +class _ModifiedArgv0: + value: Any = ... + def __init__(self, value): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +def run_module(mod_name: str, + init_globals: Optional[Dict[str, Any]] = ..., + run_name: Optional[str] = ..., + alter_sys: bool = ...): ... +def run_path(path_name: str, + init_globals: Optional[Dict[str, Any]] = ..., + run_name: str = ...): ... diff --git a/mypy/stdlib/sched.pyi b/mypy/stdlib/sched.pyi new file mode 100644 index 000000000000..6a820c836ae9 --- /dev/null +++ b/mypy/stdlib/sched.pyi @@ -0,0 +1,26 @@ +import sys +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Text, Tuple + +class Event(NamedTuple): + time: float + priority: Any + action: Callable[..., Any] + argument: Tuple[Any, ...] + kwargs: Dict[Text, 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 cancel(self, event: Event) -> None: ... + def empty(self) -> bool: ... + @property + def queue(self) -> List[Event]: ... diff --git a/mypy/stdlib/secrets.pyi b/mypy/stdlib/secrets.pyi new file mode 100644 index 000000000000..5069dba25c67 --- /dev/null +++ b/mypy/stdlib/secrets.pyi @@ -0,0 +1,14 @@ +# Stubs for secrets (Python 3.6) + +from typing import Optional, Sequence, TypeVar +from hmac import compare_digest as compare_digest +from random import SystemRandom as SystemRandom + +_T = TypeVar('_T') + +def randbelow(exclusive_upper_bound: int) -> int: ... +def randbits(k: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +def token_bytes(nbytes: Optional[int] = ...) -> bytes: ... +def token_hex(nbytes: Optional[int] = ...) -> str: ... +def token_urlsafe(nbytes: Optional[int] = ...) -> str: ... diff --git a/mypy/stdlib/select.pyi b/mypy/stdlib/select.pyi new file mode 100644 index 000000000000..697e867b419d --- /dev/null +++ b/mypy/stdlib/select.pyi @@ -0,0 +1,140 @@ +import sys +from typing import Any, Iterable, List, Optional, Tuple, Type +from types import TracebackType +from _typeshed import FileDescriptorLike + + +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]]: ... + +if sys.version_info >= (3, 3): + error = OSError +else: + 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): + 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 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 + +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]]: ... diff --git a/mypy/stdlib/selectors.pyi b/mypy/stdlib/selectors.pyi new file mode 100644 index 000000000000..9f55e853f61e --- /dev/null +++ b/mypy/stdlib/selectors.pyi @@ -0,0 +1,79 @@ +import sys +from abc import ABCMeta, abstractmethod +from typing import Any, List, Mapping, NamedTuple, Optional, Tuple +from _typeshed import FileDescriptor, FileDescriptorLike + +_EventMask = int + +EVENT_READ: _EventMask +EVENT_WRITE: _EventMask + +class SelectorKey(NamedTuple): + fileobj: FileDescriptorLike + fd: FileDescriptor + events: _EventMask + data: Any + +class BaseSelector(metaclass=ABCMeta): + @abstractmethod + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + + @abstractmethod + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + + def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + + @abstractmethod + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + + def close(self) -> None: ... + + def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + + @abstractmethod + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + + def __enter__(self) -> BaseSelector: ... + + def __exit__(self, *args: Any) -> None: ... + +class SelectSelector(BaseSelector): + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +if sys.platform != "win32": + + class PollSelector(BaseSelector): + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + + class EpollSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +class DevpollSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +class KqueueSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +class DefaultSelector(BaseSelector): + def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... diff --git a/mypy/stdlib/shelve.pyi b/mypy/stdlib/shelve.pyi new file mode 100644 index 000000000000..97a045e0e849 --- /dev/null +++ b/mypy/stdlib/shelve.pyi @@ -0,0 +1,31 @@ +from typing import Any, Dict, Iterator, Optional, Tuple +import collections + + +class Shelf(collections.MutableMapping[Any, Any]): + def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: Any) -> bool: ... # key should be str, but it would conflict with superclass's type signature + def get(self, key: str, default: Any = ...) -> Any: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, value: Any) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __enter__(self) -> Shelf: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + def sync(self) -> None: ... + +class BsdDbShelf(Shelf): + def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def set_location(self, key: Any) -> Tuple[str, Any]: ... + def next(self) -> Tuple[str, Any]: ... + def previous(self) -> Tuple[str, Any]: ... + def first(self) -> Tuple[str, Any]: ... + def last(self) -> Tuple[str, Any]: ... + +class DbfilenameShelf(Shelf): + def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... + +def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/mypy/stdlib/shlex.pyi b/mypy/stdlib/shlex.pyi new file mode 100644 index 000000000000..51ed42d94172 --- /dev/null +++ b/mypy/stdlib/shlex.pyi @@ -0,0 +1,45 @@ +from typing import List, Tuple, Any, TextIO, Union, Optional, Iterable, TypeVar +import sys + +def split(s: str, comments: bool = ..., posix: bool = ...) -> List[str]: ... +if sys.version_info >= (3, 8): + def join(split_command: Iterable[str]) -> str: ... +def quote(s: str) -> str: ... + +_SLT = TypeVar('_SLT', bound=shlex) + +class shlex(Iterable[str]): + commenters: str + wordchars: str + whitespace: str + escape: str + quotes: str + escapedquotes: str + whitespace_split: bool + infile: str + instream: TextIO + source: str + debug: int + lineno: int + token: str + eof: str + if sys.version_info >= (3, 6): + punctuation_chars: str + + if sys.version_info >= (3, 6): + def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., + posix: bool = ..., punctuation_chars: Union[bool, str] = ...) -> None: ... + else: + def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., + posix: bool = ...) -> None: ... + def get_token(self) -> str: ... + def push_token(self, tok: str) -> None: ... + def read_token(self) -> str: ... + def sourcehook(self, filename: str) -> Tuple[str, TextIO]: ... + # TODO argument types + def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... + def pop_source(self) -> None: ... + def error_leader(self, infile: str = ..., + lineno: int = ...) -> None: ... + def __iter__(self: _SLT) -> _SLT: ... + def __next__(self) -> str: ... diff --git a/mypy/stdlib/shutil.pyi b/mypy/stdlib/shutil.pyi new file mode 100644 index 000000000000..780a52e3cb79 --- /dev/null +++ b/mypy/stdlib/shutil.pyi @@ -0,0 +1,143 @@ +import os +import sys + +from typing import ( + List, Iterable, Callable, Any, Tuple, Sequence, NamedTuple, + AnyStr, Optional, Union, Set, TypeVar, overload, Type, Text +) +from _typeshed import StrPath, SupportsRead, SupportsWrite + +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): ... + +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: ... +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: ... + +def ignore_patterns(*patterns: StrPath) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... + +if sys.version_info >= (3, 8): + def copytree( + src: StrPath, + dst: StrPath, + symlinks: bool = ..., + ignore: Union[None, Callable[[str, List[str]], Iterable[str]], Callable[[StrPath, List[str]], Iterable[str]]] = ..., + copy_function: Callable[[str, str], None] = ..., + ignore_dangling_symlinks: bool = ..., + dirs_exist_ok: bool = ..., + ) -> _PathReturn: ... +elif sys.version_info >= (3,): + def copytree(src: StrPath, dst: StrPath, symlinks: bool = ..., + ignore: Union[None, + Callable[[str, List[str]], Iterable[str]], + Callable[[StrPath, List[str]], Iterable[str]]] = ..., + copy_function: Callable[[str, str], None] = ..., + 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: ... + +_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): + # See https://bugs.python.org/issue32689 + def move(src: str, dst: StrPath, + copy_function: _CopyFn = ...) -> _PathReturn: ... +else: + def move(src: StrPath, dst: StrPath) -> _PathReturn: ... + +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[str] = ..., + group: Optional[str] = ...) -> None: ... +if sys.version_info >= (3, 8): + @overload + def which(cmd: StrPath, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[str]: ... + @overload + def which(cmd: bytes, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[bytes]: ... +elif sys.version_info >= (3,): + def which(cmd: StrPath, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[str]: ... + +def make_archive(base_name: _AnyStr, format: str, root_dir: Optional[StrPath] = ..., + base_dir: Optional[StrPath] = ..., 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: ... + +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: 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/stdlib/signal.pyi b/mypy/stdlib/signal.pyi new file mode 100644 index 000000000000..26fa36f5b23b --- /dev/null +++ b/mypy/stdlib/signal.pyi @@ -0,0 +1,185 @@ +"""Stub file for the 'signal' module.""" + +import sys +from enum import IntEnum +from typing import Any, Callable, Tuple, Union, Optional, Iterable, Set +from types import FrameType + +if sys.platform != "win32": + class ItimerError(IOError): ... + + ITIMER_PROF: int + ITIMER_REAL: int + ITIMER_VIRTUAL: int + +NSIG: int + +class Signals(IntEnum): + SIGABRT: int + if sys.platform != "win32": + SIGALRM: int + if sys.platform == "win32": + SIGBREAK: int + if sys.platform != "win32": + SIGBUS: int + SIGCHLD: int + if sys.platform != "darwin" and sys.platform != "win32": + SIGCLD: int + if sys.platform != "win32": + SIGCONT: int + SIGEMT: int + SIGFPE: int + if sys.platform != "win32": + SIGHUP: int + SIGILL: int + SIGINFO: int + SIGINT: int + if sys.platform != "win32": + SIGIO: int + SIGIOT: int + SIGKILL: int + SIGPIPE: int + if sys.platform != "darwin" and sys.platform != "win32": + SIGPOLL: int + SIGPWR: int + if sys.platform != "win32": + SIGPROF: int + SIGQUIT: int + if sys.platform != "darwin" and sys.platform != "win32": + SIGRTMAX: int + SIGRTMIN: int + SIGSEGV: int + if sys.platform != "win32": + SIGSTOP: int + SIGSYS: int + SIGTERM: int + if sys.platform != "win32": + SIGTRAP: int + SIGTSTP: int + SIGTTIN: int + SIGTTOU: int + SIGURG: int + SIGUSR1: int + SIGUSR2: int + SIGVTALRM: int + SIGWINCH: int + SIGXCPU: int + SIGXFSZ: int + +class Handlers(IntEnum): + SIG_DFL: int + SIG_IGN: int + +SIG_DFL = Handlers.SIG_DFL +SIG_IGN = Handlers.SIG_IGN + +if sys.platform != "win32": + class Sigmasks(IntEnum): + SIG_BLOCK: int + SIG_UNBLOCK: int + SIG_SETMASK: int + + SIG_BLOCK = Sigmasks.SIG_BLOCK + SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK + SIG_SETMASK = Sigmasks.SIG_SETMASK + +_SIGNUM = Union[int, Signals] +_HANDLER = Union[Callable[[Signals, FrameType], None], int, Handlers, None] + +SIGABRT: Signals +if sys.platform != "win32": + SIGALRM: Signals +if sys.platform == "win32": + SIGBREAK: Signals +if sys.platform != "win32": + SIGBUS: Signals + SIGCHLD: Signals +if sys.platform != "darwin" and sys.platform != "win32": + SIGCLD: Signals +if sys.platform != "win32": + SIGCONT: Signals +SIGEMT: Signals +SIGFPE: Signals +if sys.platform != "win32": + SIGHUP: Signals +SIGILL: Signals +SIGINFO: Signals +SIGINT: Signals +if sys.platform != "win32": + SIGIO: Signals + SIGIOT: Signals + SIGKILL: Signals + SIGPIPE: Signals +if sys.platform != "darwin" and sys.platform != "win32": + SIGPOLL: Signals + SIGPWR: Signals +if sys.platform != "win32": + SIGPROF: Signals + SIGQUIT: Signals +if sys.platform != "darwin" and sys.platform != "win32": + SIGRTMAX: Signals + SIGRTMIN: Signals +SIGSEGV: Signals +if sys.platform != "win32": + SIGSTOP: Signals + SIGSYS: Signals +SIGTERM: Signals +if sys.platform != "win32": + SIGTRAP: Signals + SIGTSTP: Signals + SIGTTIN: Signals + SIGTTOU: Signals + SIGURG: Signals + SIGUSR1: Signals + SIGUSR2: Signals + SIGVTALRM: Signals + SIGWINCH: Signals + SIGXCPU: Signals + SIGXFSZ: Signals + +if sys.platform == "win32": + CTRL_C_EVENT: int + CTRL_BREAK_EVENT: int + +if sys.platform != "win32": + class struct_siginfo(Tuple[int, int, int, int, int, int, int]): + def __init__(self, sequence: Iterable[int]) -> None: ... + @property + def si_signo(self) -> int: ... + @property + def si_code(self) -> int: ... + @property + def si_errno(self) -> int: ... + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_band(self) -> int: ... + +if sys.platform != "win32": + def alarm(__seconds: int) -> int: ... +def default_int_handler(signum: int, frame: FrameType) -> None: ... +if sys.platform != "win32": + def getitimer(__which: int) -> Tuple[float, float]: ... +def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... +if sys.version_info >= (3, 8): + def strsignal(__signalnum: _SIGNUM) -> Optional[str]: ... + def valid_signals() -> Set[Signals]: ... + def raise_signal(__signalnum: _SIGNUM) -> None: ... +if sys.platform != "win32": + def pause() -> None: ... + def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... + def pthread_sigmask(__how: int, __mask: Iterable[int]) -> Set[_SIGNUM]: ... +def set_wakeup_fd(fd: int) -> int: ... +if sys.platform != "win32": + def setitimer(__which: int, __seconds: float, __interval: float = ...) -> Tuple[float, float]: ... + def siginterrupt(__signalnum: int, __flag: bool) -> None: ... +def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... +if sys.platform != "win32": + def sigpending() -> Any: ... + def sigtimedwait(sigset: Iterable[int], timeout: float) -> Optional[struct_siginfo]: ... + def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... + def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... diff --git a/mypy/stdlib/site.pyi b/mypy/stdlib/site.pyi new file mode 100644 index 000000000000..4fdbad8ee3cf --- /dev/null +++ b/mypy/stdlib/site.pyi @@ -0,0 +1,17 @@ +# Stubs for site + +from typing import List, Iterable, Optional +import sys + +PREFIXES: List[str] +ENABLE_USER_SITE: Optional[bool] +USER_SITE: Optional[str] +USER_BASE: Optional[str] + +if sys.version_info < (3,): + 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/stdlib/smtpd.pyi b/mypy/stdlib/smtpd.pyi new file mode 100644 index 000000000000..870a50147a1a --- /dev/null +++ b/mypy/stdlib/smtpd.pyi @@ -0,0 +1,78 @@ +# Stubs for smtpd (Python 2 and 3) +import sys +import socket +import asyncore +import asynchat + +from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type + +_Address = Tuple[str, int] # (host, port) + + +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_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: ... + # 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: ... + 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: ... + +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 handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: str, **kwargs: Any) -> Optional[str]: ... + +class DebuggingServer(SMTPServer): ... +class PureProxy(SMTPServer): ... +class MailmanProxy(PureProxy): ... diff --git a/mypy/stdlib/smtplib.pyi b/mypy/stdlib/smtplib.pyi new file mode 100644 index 000000000000..60e3a35b83ba --- /dev/null +++ b/mypy/stdlib/smtplib.pyi @@ -0,0 +1,136 @@ +from email.message import Message as _Message +from socket import socket +from ssl import SSLContext +from types import TracebackType +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, Pattern, Type, Protocol, overload + +_Reply = Tuple[int, bytes] +_SendErrs = Dict[str, _Reply] +# Should match source_address for socket.create_connection +_SourceAddress = Tuple[Union[bytearray, bytes, str], int] + +SMTP_PORT: int +SMTP_SSL_PORT: int +CRLF: str +bCRLF: bytes + +OLDSTYLE_AUTH: Pattern[str] + +class SMTPException(OSError): ... +class SMTPNotSupportedError(SMTPException): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code: int + smtp_error: Union[bytes, str] + args: Union[Tuple[int, Union[bytes, str]], Tuple[int, bytes, str]] + def __init__(self, code: int, msg: Union[bytes, str]) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_code: int + smtp_error: bytes + sender: str + args: Tuple[int, bytes, str] + def __init__(self, code: int, msg: bytes, sender: str) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients: _SendErrs + args: Tuple[_SendErrs] + def __init__(self, recipients: _SendErrs) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addrstring: str) -> str: ... +def quotedata(data: str) -> str: ... + +class _AuthObject(Protocol): + @overload + def __call__(self, challenge: None = ...) -> Optional[str]: ... + @overload + def __call__(self, challenge: bytes) -> str: ... + +class SMTP: + debuglevel: int = ... + sock: Optional[socket] = ... + # Type of file should match what socket.makefile() returns + file: Optional[Any] = ... + helo_resp: Optional[bytes] = ... + ehlo_msg: str = ... + ehlo_resp: Optional[bytes] = ... + does_esmtp: bool = ... + default_port: int = ... + timeout: float + esmtp_features: Dict[str, str] + command_encoding: str + source_address: Optional[_SourceAddress] + local_hostname: str + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., timeout: float = ..., + source_address: Optional[_SourceAddress] = ...) -> None: ... + def __enter__(self) -> SMTP: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + tb: Optional[TracebackType]) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + def connect(self, host: str = ..., port: int = ..., + source_address: Optional[_SourceAddress] = ...) -> _Reply: ... + def send(self, s: Union[bytes, str]) -> None: ... + def putcmd(self, cmd: str, args: str = ...) -> None: ... + def getreply(self) -> _Reply: ... + def docmd(self, cmd: str, args: str = ...) -> _Reply: ... + def helo(self, name: str = ...) -> _Reply: ... + def ehlo(self, name: str = ...) -> _Reply: ... + def has_extn(self, opt: str) -> bool: ... + def help(self, args: str = ...) -> bytes: ... + def rset(self) -> _Reply: ... + def noop(self) -> _Reply: ... + def mail(self, sender: str, options: Sequence[str] = ...) -> _Reply: ... + def rcpt(self, recip: str, options: Sequence[str] = ...) -> _Reply: ... + def data(self, msg: Union[bytes, str]) -> _Reply: ... + def verify(self, address: str) -> _Reply: ... + vrfy = verify + def expn(self, address: str) -> _Reply: ... + def ehlo_or_helo_if_needed(self) -> None: ... + user: str + password: str + def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = ...) -> _Reply: ... + @overload + def auth_cram_md5(self, challenge: None = ...) -> None: ... + @overload + def auth_cram_md5(self, challenge: bytes) -> str: ... + def auth_plain(self, challenge: Optional[bytes] = ...) -> str: ... + def auth_login(self, challenge: Optional[bytes] = ...) -> str: ... + def login(self, user: str, password: str, *, initial_response_ok: bool = ...) -> _Reply: ... + def starttls(self, keyfile: Optional[str] = ..., certfile: Optional[str] = ..., + context: Optional[SSLContext] = ...) -> _Reply: ... + def sendmail(self, from_addr: str, to_addrs: Union[str, Sequence[str]], + msg: Union[bytes, str], mail_options: Sequence[str] = ..., + rcpt_options: List[str] = ...) -> _SendErrs: ... + def send_message(self, msg: _Message, from_addr: Optional[str] = ..., + to_addrs: Optional[Union[str, Sequence[str]]] = ..., + mail_options: List[str] = ..., + rcpt_options: Sequence[str] = ...) -> _SendErrs: ... + def close(self) -> None: ... + def quit(self) -> _Reply: ... + +class SMTP_SSL(SMTP): + default_port: int = ... + keyfile: Optional[str] + certfile: Optional[str] + context: SSLContext + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., + keyfile: Optional[str] = ..., certfile: Optional[str] = ..., + timeout: float = ..., + source_address: Optional[_SourceAddress] = ..., + context: Optional[SSLContext] = ...) -> None: ... + +LMTP_PORT: int + +class LMTP(SMTP): + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., + source_address: Optional[_SourceAddress] = ...) -> None: ... diff --git a/mypy/stdlib/sndhdr.pyi b/mypy/stdlib/sndhdr.pyi new file mode 100644 index 000000000000..ef025ac571a7 --- /dev/null +++ b/mypy/stdlib/sndhdr.pyi @@ -0,0 +1,17 @@ +import sys +from _typeshed import AnyPath +from typing import NamedTuple, Optional, Tuple, 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]] + +def what(filename: AnyPath) -> Optional[_SndHeaders]: ... +def whathdr(filename: AnyPath) -> Optional[_SndHeaders]: ... diff --git a/mypy/stdlib/socket.pyi b/mypy/stdlib/socket.pyi new file mode 100644 index 000000000000..d74101fe36be --- /dev/null +++ b/mypy/stdlib/socket.pyi @@ -0,0 +1,822 @@ +"""Stub for the socket module + +This file is organized to mirror the module's documentation, with a very small +number of exceptions. + +To avoid requiring tests on all platforms, platform checks are included only +where the documentation notes platform availability (as opposed to following +actual availability), with one or two exceptions. + +Module documentation: https://docs.python.org/3/library/socket.html +CPython module source: https://github.com/python/cpython/blob/master/Lib/socket.py +CPython C source: https://github.com/python/cpython/blob/master/Modules/socketmodule.c +""" +# Authorship from original mypy stubs (not in typeshed git history): +# Ron Murawski +# adapted for Python 2.7 by Michal Pokorny +import sys +from typing import Any, BinaryIO, Iterable, List, Optional, Text, TextIO, Tuple, TypeVar, Union, overload +from typing_extensions import Literal + + +# ----- 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 +if sys.version_info >= (3,): + SocketIO: 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 + +if sys.platform == 'linux' and sys.version_info >= (3,): + SOCK_CLOEXEC: SocketKind + SOCK_NONBLOCK: 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 +EAIEAI_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 +if sys.version_info >= (3, 7): + TCP_NOTSENT_LOWAT: int + +# Specifically-documented constants + +if sys.platform == 'linux' and sys.version_info >= (3,): + AF_CAN: AddressFamily + PF_CAN: int + SOL_CAN_BASE: int + SOL_CAN_RAW: int + CAN_EFF_FLAG: int + CAN_EFF_MASK: int + CAN_ERR_FLAG: int + CAN_ERR_MASK: int + CAN_RAW: int + CAN_RAW_ERR_FILTER: int + CAN_RAW_FILTER: int + CAN_RAW_LOOPBACK: int + CAN_RAW_RECV_OWN_MSGS: int + CAN_RTR_FLAG: int + CAN_SFF_MASK: int + + CAN_BCM: int + CAN_BCM_TX_SETUP: int + CAN_BCM_TX_DELETE: int + CAN_BCM_TX_READ: int + CAN_BCM_TX_SEND: int + CAN_BCM_RX_SETUP: int + CAN_BCM_RX_DELETE: int + CAN_BCM_RX_READ: int + CAN_BCM_TX_STATUS: int + CAN_BCM_TX_EXPIRED: int + CAN_BCM_RX_STATUS: int + CAN_BCM_RX_TIMEOUT: int + CAN_BCM_RX_CHANGED: int + + CAN_RAW_FD_FRAMES: int + +if sys.platform == 'linux' and sys.version_info >= (3, 8): + CAN_BCM_SETTIMER: int + CAN_BCM_STARTTIMER: int + CAN_BCM_TX_COUNTEVT: int + CAN_BCM_TX_ANNOUNCE: int + CAN_BCM_TX_CP_CAN_ID: int + CAN_BCM_RX_FILTER_ID: int + CAN_BCM_RX_CHECK_DLC: int + CAN_BCM_RX_NO_AUTOTIMER: int + CAN_BCM_RX_ANNOUNCE_RESUME: int + CAN_BCM_TX_RESET_MULTI_IDX: int + CAN_BCM_RX_RTR_FRAME: int + CAN_BCM_CAN_FD_FRAME: int + +if sys.platform == 'linux' and sys.version_info >= (3, 7): + CAN_ISOTP: int + +if sys.platform == 'linux' and sys.version_info >= (3, 9): + CAN_J1939: int + + J1939_MAX_UNICAST_ADDR: int + J1939_IDLE_ADDR: int + J1939_NO_ADDR: int + J1939_NO_NAME: int + J1939_PGN_REQUEST: int + J1939_PGN_ADDRESS_CLAIMED: int + J1939_PGN_ADDRESS_COMMANDED: int + J1939_PGN_PDU1_MAX: int + J1939_PGN_MAX: int + J1939_NO_PGN: int + + SO_J1939_FILTER: int + SO_J1939_PROMISC: int + SO_J1939_SEND_PRIO: int + SO_J1939_ERRQUEUE: int + + SCM_J1939_DEST_ADDR: int + SCM_J1939_DEST_NAME: int + SCM_J1939_PRIO: int + SCM_J1939_ERRQUEUE: int + + J1939_NLA_PAD: int + J1939_NLA_BYTES_ACKED: int + + J1939_EE_INFO_NONE: int + J1939_EE_INFO_TX_ABORT: int + + J1939_FILTER_MAX: int + +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 == 'linux' and sys.version_info >= (3,): + AF_RDS: AddressFamily + PF_RDS: int + SOL_RDS: int + RDS_CANCEL_SENT_TO: int + RDS_CMSG_RDMA_ARGS: int + RDS_CMSG_RDMA_DEST: int + RDS_CMSG_RDMA_MAP: int + RDS_CMSG_RDMA_STATUS: int + RDS_CMSG_RDMA_UPDATE: int + RDS_CONG_MONITOR: int + RDS_FREE_MR: int + RDS_GET_MR: int + RDS_GET_MR_FOR_DEST: int + RDS_RDMA_DONTWAIT: int + RDS_RDMA_FENCE: int + RDS_RDMA_INVALIDATE: int + RDS_RDMA_NOTIFY_ME: int + RDS_RDMA_READWRITE: int + RDS_RDMA_SILENT: int + RDS_RDMA_USE_ONCE: int + RDS_RECVERR: int + +if sys.platform == 'win32': + SIO_RCVALL: int + SIO_KEEPALIVE_VALS: int + if sys.version_info >= (3, 6): + SIO_LOOPBACK_FAST_PATH: 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 + +if sys.platform == 'linux' and sys.version_info >= (3, 6): + AF_ALG: AddressFamily + SOL_ALG: int + ALG_OP_DECRYPT: int + ALG_OP_ENCRYPT: int + ALG_OP_SIGN: int + ALG_OP_VERIFY: int + ALG_SET_AEAD_ASSOCLEN: int + ALG_SET_AEAD_AUTHSIZE: int + ALG_SET_IV: int + ALG_SET_KEY: int + ALG_SET_OP: int + ALG_SET_PUBKEY: int + +if sys.platform == 'linux' and sys.version_info >= (3, 7): + AF_VSOCK: AddressFamily + IOCTL_VM_SOCKETS_GET_LOCAL_CID: int + VMADDR_CID_ANY: int + VMADDR_CID_HOST: int + VMADDR_PORT_ANY: int + SO_VM_SOCKETS_BUFFER_MAX_SIZE: int + SO_VM_SOCKETS_BUFFER_SIZE: int + SO_VM_SOCKETS_BUFFER_MIN_SIZE: int + VM_SOCKETS_INVALID_VERSION: int + +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 + +if sys.platform == 'linux' and sys.version_info >= (3, 8): + AF_QIPCRTR: AddressFamily + + +# 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 +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 + + +# ----- Exceptions ----- + +if sys.version_info < (3,): + class error(IOError): ... +else: + error = OSError + +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, 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 + + 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: ... + + # --- 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: ... + if sys.version_info >= (3, 4): + def get_inheritable(self) -> bool: ... + 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: ... + + 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): + 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: ... + # 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: ... + 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": + 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 = ...) -> Tuple[int, List[_CMSG], int, Any]: ... + 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: ... + if sys.version_info >= (3, 3) and 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): + # TODO add the parameter types for sendmsg_afalg + def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> int: ... + + if sys.version_info >= (3,): + # TODO determine legal types for file parameter + def sendfile(self, file, 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: ... + + if sys.platform == 'win32': + def share(self, process_id: int) -> bytes: ... + + def shutdown(self, how: int) -> None: ... + + +# ----- Functions ----- + +if sys.version_info >= (3, 7): + def close(fd: int) -> None: ... + +def create_connection(address: Tuple[Optional[str], int], + timeout: Optional[float] = ..., + source_address: Optional[Tuple[Union[bytearray, bytes, Text], int]] = ...) -> socket: ... + +if sys.version_info >= (3, 8): + def create_server(address: _Address, + *, + family: int = ..., + backlog: Optional[int] = ..., + reuse_port: bool = ..., + dualstack_ipv6: bool = ...) -> socket: ... + def has_dualstack_ipv6() -> bool: ... + +def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... + +if sys.platform == 'win32' and sys.version_info >= (3, 3): + def fromshare(info: bytes) -> socket: ... + +# the 5th tuple item is an address +# TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers +# https://github.com/python/mypy/issues/2509 +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, Tuple[Any, ...]]]: ... +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 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, int]: ... +def getprotobyname(protocolname: str) -> int: ... +def getservbyname(servicename: str, protocolname: str = ...) -> int: ... +def getservbyport(port: int, protocolname: str = ...) -> str: ... +def socketpair(family: 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: ... +if sys.version_info >= (3, 3): + 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: ... diff --git a/mypy/stdlib/socketserver.pyi b/mypy/stdlib/socketserver.pyi new file mode 100644 index 000000000000..3f57efbe9766 --- /dev/null +++ b/mypy/stdlib/socketserver.pyi @@ -0,0 +1,135 @@ +# NB: SocketServer.pyi and socketserver.pyi must remain consistent! +# Stubs for socketserver + +from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, Text, Union +from socket import SocketType +import sys +import types + +class BaseServer: + address_family: int + RequestHandlerClass: Callable[..., BaseRequestHandler] + server_address: Tuple[str, int] + socket: SocketType + allow_reuse_address: bool + request_queue_size: int + socket_type: int + timeout: Optional[float] + def __init__(self, server_address: Any, + RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... + def fileno(self) -> int: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = ...) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> None: ... + def handle_error(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def server_activate(self) -> None: ... + def server_bind(self) -> None: ... + def verify_request(self, request: bytes, + client_address: Tuple[str, int]) -> bool: ... + if sys.version_info >= (3, 6): + def __enter__(self) -> BaseServer: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> None: ... + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... + +class TCPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +class UDPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != 'win32': + class UnixStreamServer(BaseServer): + def __init__(self, server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + + class UnixDatagramServer(BaseServer): + def __init__(self, server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != "win32": + class ForkingMixIn: + timeout: Optional[float] # undocumented + active_children: Optional[List[int]] # undocumented + max_children: int # undocumented + if sys.version_info >= (3, 7): + block_on_close: bool + if sys.version_info >= (3, 6): + def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented + else: + def collect_children(self) -> None: ... # undocumented + def handle_timeout(self) -> None: ... # undocumented + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... # undocumented + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + if sys.version_info >= (3, 6): + def server_close(self) -> None: ... + +class ThreadingMixIn: + daemon_threads: bool + if sys.version_info >= (3, 7): + block_on_close: bool + def process_request_thread(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... # undocumented + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + if sys.version_info >= (3, 6): + def server_close(self) -> None: ... + +if sys.platform != "win32": + class ForkingTCPServer(ForkingMixIn, TCPServer): ... + class ForkingUDPServer(ForkingMixIn, UDPServer): ... +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... +if sys.platform != 'win32': + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + + +class BaseRequestHandler: + # Those are technically of types, respectively: + # * Union[SocketType, Tuple[bytes, SocketType]] + # * Union[Tuple[str, int], str] + # But there are some concerns that having unions here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + request: Any + client_address: Any + server: BaseServer + + def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rbufsize: ClassVar[int] # Undocumented + wbufsize: ClassVar[int] # Undocumented + timeout: ClassVar[Optional[float]] # Undocumented + disable_nagle_algorithm: ClassVar[bool] # Undocumented + connection: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO + +class DatagramRequestHandler(BaseRequestHandler): + packet: SocketType # Undocumented + socket: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO diff --git a/mypy/stdlib/spwd.pyi b/mypy/stdlib/spwd.pyi new file mode 100644 index 000000000000..1fb972f6d990 --- /dev/null +++ b/mypy/stdlib/spwd.pyi @@ -0,0 +1,15 @@ +from typing import List, NamedTuple + +class struct_spwd(NamedTuple): + sp_namp: str + sp_pwdp: str + sp_lstchg: int + sp_min: int + sp_max: int + sp_warn: int + sp_inact: int + sp_expire: int + sp_flag: int + +def getspall() -> List[struct_spwd]: ... +def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/stdlib/sqlite3/__init__.pyi b/mypy/stdlib/sqlite3/__init__.pyi new file mode 100644 index 000000000000..d5d20d67b58e --- /dev/null +++ b/mypy/stdlib/sqlite3/__init__.pyi @@ -0,0 +1 @@ +from sqlite3.dbapi2 import * # noqa: F403 diff --git a/mypy/stdlib/sqlite3/dbapi2.pyi b/mypy/stdlib/sqlite3/dbapi2.pyi new file mode 100644 index 000000000000..13dae97d968d --- /dev/null +++ b/mypy/stdlib/sqlite3/dbapi2.pyi @@ -0,0 +1,297 @@ +# Filip Hron +# based heavily on Andrey Vlasovskikh's python-skeletons https://github.com/JetBrains/python-skeletons/blob/master/sqlite3.py + +import os +import sys +from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Text, Tuple, Type, TypeVar, Union +from datetime import date, time, datetime + +_T = TypeVar('_T') + +paramstyle: str +threadsafety: int +apilevel: str +Date = date +Time = time +Timestamp = datetime + +def DateFromTicks(ticks): ... +def TimeFromTicks(ticks): ... +def TimestampFromTicks(ticks): ... + +version_info: str +sqlite_version_info: Tuple[int, int, int] +if sys.version_info >= (3,): + Binary = memoryview +else: + Binary = buffer + +def register_adapters_and_converters(): ... + +# 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: ... +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], + timeout: float = ..., + detect_types: int = ..., + isolation_level: Optional[str] = ..., + check_same_thread: bool = ..., + factory: Optional[Type[Connection]] = ..., + cached_statements: int = ..., + uri: bool = ...) -> Connection: ... +else: + 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(flag: bool) -> None: ... +def enable_shared_cache(do_enable: int) -> None: ... +def register_adapter(type: Type[_T], callable: Callable[[_T], Union[int, float, str, bytes]]) -> None: ... +def register_converter(typename: str, callable: Callable[[bytes], Any]) -> None: ... + +if sys.version_info < (3, 8): + class Cache(object): + def __init__(self, *args, **kwargs) -> None: ... + def display(self, *args, **kwargs) -> None: ... + def get(self, *args, **kwargs) -> None: ... + +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, **kwargs): ... + def close(self) -> None: ... + def commit(self) -> None: ... + def create_aggregate(self, name: str, num_params: int, aggregate_class: type) -> None: ... + def create_collation(self, name: str, callable: Any) -> None: ... + if sys.version_info >= (3, 8): + def create_function(self, name: str, num_params: int, func: Any, *, deterministic: bool = ...) -> None: ... + else: + 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, seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... + def executescript(self, sql_script: Union[bytes, Text]) -> Cursor: ... + def interrupt(self, *args, **kwargs) -> None: ... + def iterdump(self, *args, **kwargs) -> Generator[str, None, None]: ... + def rollback(self, *args, **kwargs) -> 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, **kwargs) -> 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, **kwargs) -> None: ... + def set_trace_callback(self, *args, **kwargs): ... + # 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: ... + if sys.version_info >= (3, 7): + def backup(self, target: Connection, *, pages: int = ..., + progress: Optional[Callable[[int, int, int], object]] = ..., name: str = ..., + sleep: float = ...) -> None: ... + def __call__(self, *args, **kwargs): ... + def __enter__(self, *args, **kwargs) -> Connection: ... + def __exit__(self, *args, **kwargs): ... + +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, **kwargs) -> None: ... + def close(self, *args, **kwargs) -> 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, **kwargs) -> None: ... + def setoutputsize(self, *args, **kwargs) -> None: ... + def __iter__(self) -> Cursor: ... + if sys.version_info >= (3, 0): + def __next__(self) -> Any: ... + else: + 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): ... + +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): ... + +class PrepareProtocol(object): + def __init__(self, *args, **kwargs): ... + +class ProgrammingError(DatabaseError): ... + +class Row(object): + def __init__(self, *args, **kwargs): ... + def keys(self, *args, **kwargs): ... + 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, *args, **kwargs): ... + def __lt__(self, other): ... + def __ne__(self, other): ... + +if sys.version_info < (3, 8): + class Statement(object): + def __init__(self, *args, **kwargs): ... + +class Warning(Exception): ... diff --git a/mypy/stdlib/sre_compile.pyi b/mypy/stdlib/sre_compile.pyi new file mode 100644 index 000000000000..e6036e205454 --- /dev/null +++ b/mypy/stdlib/sre_compile.pyi @@ -0,0 +1,18 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_compile.py +# and https://github.com/python/cpython/blob/master/Lib/sre_compile.py + +import sys +from sre_parse import SubPattern +from typing import Any, List, Pattern, Tuple, Type, TypeVar, 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 compile(p: Union[str, bytes, SubPattern], flags: int = ...) -> Pattern[Any]: ... diff --git a/mypy/stdlib/sre_constants.pyi b/mypy/stdlib/sre_constants.pyi new file mode 100644 index 000000000000..e51fff5597a9 --- /dev/null +++ b/mypy/stdlib/sre_constants.pyi @@ -0,0 +1,114 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/sre_constants.py + +from typing import Any, Dict, List, Optional, Union + +MAGIC: int + +class error(Exception): + msg: str + pattern: Optional[Union[str, bytes]] + pos: Optional[int] + lineno: int + colno: int + def __init__(self, msg: str, pattern: Union[str, bytes] = ..., pos: int = ...) -> None: ... + +class _NamedIntConstant(int): + name: Any + def __new__(cls, value: int, name: str) -> _NamedIntConstant: ... + +MAXREPEAT: _NamedIntConstant +OPCODES: List[_NamedIntConstant] +ATCODES: List[_NamedIntConstant] +CHCODES: List[_NamedIntConstant] +OP_IGNORE: Dict[_NamedIntConstant, _NamedIntConstant] +AT_MULTILINE: Dict[_NamedIntConstant, _NamedIntConstant] +AT_LOCALE: Dict[_NamedIntConstant, _NamedIntConstant] +AT_UNICODE: Dict[_NamedIntConstant, _NamedIntConstant] +CH_LOCALE: Dict[_NamedIntConstant, _NamedIntConstant] +CH_UNICODE: Dict[_NamedIntConstant, _NamedIntConstant] +SRE_FLAG_TEMPLATE: int +SRE_FLAG_IGNORECASE: int +SRE_FLAG_LOCALE: int +SRE_FLAG_MULTILINE: int +SRE_FLAG_DOTALL: int +SRE_FLAG_UNICODE: int +SRE_FLAG_VERBOSE: int +SRE_FLAG_DEBUG: int +SRE_FLAG_ASCII: int +SRE_INFO_PREFIX: int +SRE_INFO_LITERAL: int +SRE_INFO_CHARSET: int + + +# Stubgen above; manually defined constants below (dynamic at runtime) + +# from OPCODES +FAILURE: _NamedIntConstant +SUCCESS: _NamedIntConstant +ANY: _NamedIntConstant +ANY_ALL: _NamedIntConstant +ASSERT: _NamedIntConstant +ASSERT_NOT: _NamedIntConstant +AT: _NamedIntConstant +BRANCH: _NamedIntConstant +CALL: _NamedIntConstant +CATEGORY: _NamedIntConstant +CHARSET: _NamedIntConstant +BIGCHARSET: _NamedIntConstant +GROUPREF: _NamedIntConstant +GROUPREF_EXISTS: _NamedIntConstant +GROUPREF_IGNORE: _NamedIntConstant +IN: _NamedIntConstant +IN_IGNORE: _NamedIntConstant +INFO: _NamedIntConstant +JUMP: _NamedIntConstant +LITERAL: _NamedIntConstant +LITERAL_IGNORE: _NamedIntConstant +MARK: _NamedIntConstant +MAX_UNTIL: _NamedIntConstant +MIN_UNTIL: _NamedIntConstant +NOT_LITERAL: _NamedIntConstant +NOT_LITERAL_IGNORE: _NamedIntConstant +NEGATE: _NamedIntConstant +RANGE: _NamedIntConstant +REPEAT: _NamedIntConstant +REPEAT_ONE: _NamedIntConstant +SUBPATTERN: _NamedIntConstant +MIN_REPEAT_ONE: _NamedIntConstant +RANGE_IGNORE: _NamedIntConstant +MIN_REPEAT: _NamedIntConstant +MAX_REPEAT: _NamedIntConstant + +# from ATCODES +AT_BEGINNING: _NamedIntConstant +AT_BEGINNING_LINE: _NamedIntConstant +AT_BEGINNING_STRING: _NamedIntConstant +AT_BOUNDARY: _NamedIntConstant +AT_NON_BOUNDARY: _NamedIntConstant +AT_END: _NamedIntConstant +AT_END_LINE: _NamedIntConstant +AT_END_STRING: _NamedIntConstant +AT_LOC_BOUNDARY: _NamedIntConstant +AT_LOC_NON_BOUNDARY: _NamedIntConstant +AT_UNI_BOUNDARY: _NamedIntConstant +AT_UNI_NON_BOUNDARY: _NamedIntConstant + +# from CHCODES +CATEGORY_DIGIT: _NamedIntConstant +CATEGORY_NOT_DIGIT: _NamedIntConstant +CATEGORY_SPACE: _NamedIntConstant +CATEGORY_NOT_SPACE: _NamedIntConstant +CATEGORY_WORD: _NamedIntConstant +CATEGORY_NOT_WORD: _NamedIntConstant +CATEGORY_LINEBREAK: _NamedIntConstant +CATEGORY_NOT_LINEBREAK: _NamedIntConstant +CATEGORY_LOC_WORD: _NamedIntConstant +CATEGORY_LOC_NOT_WORD: _NamedIntConstant +CATEGORY_UNI_DIGIT: _NamedIntConstant +CATEGORY_UNI_NOT_DIGIT: _NamedIntConstant +CATEGORY_UNI_SPACE: _NamedIntConstant +CATEGORY_UNI_NOT_SPACE: _NamedIntConstant +CATEGORY_UNI_WORD: _NamedIntConstant +CATEGORY_UNI_NOT_WORD: _NamedIntConstant +CATEGORY_UNI_LINEBREAK: _NamedIntConstant +CATEGORY_UNI_NOT_LINEBREAK: _NamedIntConstant diff --git a/mypy/stdlib/sre_parse.pyi b/mypy/stdlib/sre_parse.pyi new file mode 100644 index 000000000000..c9c1622377ed --- /dev/null +++ b/mypy/stdlib/sre_parse.pyi @@ -0,0 +1,102 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/sre_parse.py + +from typing import ( + Any, Dict, FrozenSet, Iterable, List, Match, + Optional, Pattern as _Pattern, Tuple, Union +) +import sys +from sre_constants import _NamedIntConstant as _NIC, error as _Error + +SPECIAL_CHARS: str +REPEAT_CHARS: str +DIGITS: FrozenSet[str] +OCTDIGITS: FrozenSet[str] +HEXDIGITS: FrozenSet[str] +ASCIILETTERS: FrozenSet[str] +WHITESPACE: FrozenSet[str] +ESCAPES: Dict[str, Tuple[_NIC, int]] +CATEGORIES: Dict[str, Union[Tuple[_NIC, _NIC], Tuple[_NIC, List[Tuple[_NIC, _NIC]]]]] +FLAGS: Dict[str, int] +if sys.version_info >= (3, 6): + GLOBAL_FLAGS: int + + class Verbose(Exception): ... + +class _State: + flags: int + groupdict: Dict[str, int] + groupwidths: List[Optional[int]] + lookbehindgroups: Optional[int] + def __init__(self) -> None: ... + @property + def groups(self) -> int: ... + def opengroup(self, name: str = ...) -> int: ... + def closegroup(self, gid: int, p: SubPattern) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... + +if sys.version_info >= (3, 8): + State = _State +else: + Pattern = _State + + +_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] +_OpInType = List[Tuple[_NIC, int]] +_OpBranchType = Tuple[None, List[SubPattern]] +_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_CodeType = Tuple[_NIC, _AvType] + + +class SubPattern: + data: List[_CodeType] + width: Optional[int] + + if sys.version_info >= (3, 8): + state: State + def __init__(self, state: State, data: Optional[List[_CodeType]] = ...) -> None: ... + else: + pattern: Pattern + def __init__(self, pattern: Pattern, data: Optional[List[_CodeType]] = ...) -> None: ... + + def dump(self, level: int = ...) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... + def __setitem__(self, index: Union[int, slice], code: _CodeType) -> None: ... + def insert(self, index: int, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> int: ... + + +class Tokenizer: + istext: bool + string: Any + decoded_string: str + index: int + next: Optional[str] + def __init__(self, string: Any) -> None: ... + def match(self, char: str) -> bool: ... + def get(self) -> Optional[str]: ... + def getwhile(self, n: int, charset: Iterable[str]) -> str: ... + if sys.version_info >= (3, 8): + def getuntil(self, terminator: str, name: str) -> str: ... + else: + def getuntil(self, terminator: str) -> str: ... + if sys.version_info >= (3, 6): + @property + def pos(self) -> int: ... + def tell(self) -> int: ... + def seek(self, index: int) -> None: ... + def error(self, msg: str, offset: int = ...) -> _Error: ... + +def fix_flags(src: Union[str, bytes], flags: int) -> int: ... +_TemplateType = Tuple[List[Tuple[int, int]], List[str]] +if sys.version_info >= (3, 8): + def parse(str: str, flags: int = ..., state: Optional[State] = ...) -> SubPattern: ... + def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... +else: + def parse(str: str, flags: int = ..., pattern: Optional[Pattern] = ...) -> SubPattern: ... + def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... +def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... diff --git a/mypy/stdlib/ssl.pyi b/mypy/stdlib/ssl.pyi new file mode 100644 index 000000000000..cc2380abf6de --- /dev/null +++ b/mypy/stdlib/ssl.pyi @@ -0,0 +1,423 @@ +from _typeshed import StrPath +from typing import ( + Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Type, Tuple, Union, + overload +) +from typing_extensions import Literal +import enum +import socket +import sys + +_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] + +if sys.version_info >= (3, 5): + _SC1ArgT = Union[SSLSocket, SSLObject] +else: + _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): ... + +if sys.version_info >= (3, 7): + class SSLCertVerificationError(SSLError, ValueError): + verify_code: int + verify_message: str + + CertificateError = SSLCertVerificationError +else: + 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: ... + +if sys.version_info >= (3, 7): + def _create_unverified_context(protocol: int = ..., *, + cert_reqs: int = ..., + check_hostname: bool = ..., + purpose: Any = ..., + certfile: Optional[str] = ..., + keyfile: Optional[str] = ..., + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Union[Text, bytes, None] = ...) -> SSLContext: ... +else: + 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] + +if sys.version_info >= (3, 3): + 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: ... + + +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 +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_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 + OP_NO_TLSv1_3: 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_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 + OP_NO_TLSv1_3: Options + if sys.version_info >= (3, 8): + OP_ENABLE_MIDDLEBOX_COMPAT: Options +else: + 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 + +if sys.version_info >= (3, 7): + HAS_NEVER_CHECK_COMMON_NAME: bool + HAS_SSLv2: bool + HAS_SSLv3: bool + HAS_TLSv1: bool + HAS_TLSv1_1: bool + HAS_TLSv1_2: bool + HAS_TLSv1_3: bool +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 +if sys.version_info < (3,): + class Purpose(_ASN1Object): + SERVER_AUTH: ClassVar[Purpose] + CLIENT_AUTH: ClassVar[Purpose] +else: + 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] + + 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]]: ... + if sys.version_info >= (3, 5): + 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]: ... + 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: ... + if sys.version_info >= (3, 8): + def verify_client_post_handshake(self) -> None: ... + +if sys.version_info >= (3, 7): + class TLSVersion(enum.IntEnum): + MINIMUM_SUPPORTED: int + MAXIMUM_SUPPORTED: int + SSLv3: int + TLSv1: int + TLSv1_1: int + TLSv1_2: int + TLSv1_3: int + +class SSLContext: + check_hostname: bool + if sys.version_info >= (3, 6): + options: Options + else: + options: int + if sys.version_info >= (3, 8): + post_handshake_auth: bool + @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 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: ... + if sys.version_info >= (3, 7): + sni_callback: Optional[Callable[[SSLObject, str, SSLContext], Union[None, int]]] + sslobject_class: Type[SSLObject] + def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... + if sys.version_info >= (3, 7): + def set_servername_callback(self, server_name_callback: Optional[_SrvnmeCbType]) -> None: ... + else: + 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 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 + 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 + +# 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/stdlib/stat.pyi b/mypy/stdlib/stat.pyi new file mode 100644 index 000000000000..b8cff23ceef7 --- /dev/null +++ b/mypy/stdlib/stat.pyi @@ -0,0 +1,97 @@ +# Stubs for stat + +# Based on http://docs.python.org/3.2/library/stat.html + +import sys + +def S_ISDIR(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISBLK(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +def filemode(mode: int) -> str: ... + +ST_MODE: int +ST_INO: int +ST_DEV: int +ST_NLINK: int +ST_UID: int +ST_GID: int +ST_SIZE: int +ST_ATIME: int +ST_MTIME: int +ST_CTIME: int + +S_IFSOCK: int +S_IFLNK: int +S_IFREG: int +S_IFBLK: int +S_IFDIR: int +S_IFCHR: int +S_IFIFO: int +S_ISUID: int +S_ISGID: int +S_ISVTX: int + +S_IRWXU: int +S_IRUSR: int +S_IWUSR: int +S_IXUSR: int + +S_IRWXG: int +S_IRGRP: int +S_IWGRP: int +S_IXGRP: int + +S_IRWXO: int +S_IROTH: int +S_IWOTH: int +S_IXOTH: int + +S_ENFMT: int +S_IREAD: int +S_IWRITE: int +S_IEXEC: int + +UF_NODUMP: int +UF_IMMUTABLE: int +UF_APPEND: int +UF_OPAQUE: int +UF_NOUNLINK: int +if sys.platform == 'darwin': + UF_COMPRESSED: int # OS X 10.6+ only + UF_HIDDEN: int # OX X 10.5+ only +SF_ARCHIVED: int +SF_IMMUTABLE: int +SF_APPEND: int +SF_NOUNLINK: int +SF_SNAPSHOT: int + +FILE_ATTRIBUTE_ARCHIVE: int +FILE_ATTRIBUTE_COMPRESSED: int +FILE_ATTRIBUTE_DEVICE: int +FILE_ATTRIBUTE_DIRECTORY: int +FILE_ATTRIBUTE_ENCRYPTED: int +FILE_ATTRIBUTE_HIDDEN: int +FILE_ATTRIBUTE_INTEGRITY_STREAM: int +FILE_ATTRIBUTE_NORMAL: int +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: int +FILE_ATTRIBUTE_NO_SCRUB_DATA: int +FILE_ATTRIBUTE_OFFLINE: int +FILE_ATTRIBUTE_READONLY: int +FILE_ATTRIBUTE_REPARSE_POINT: int +FILE_ATTRIBUTE_SPARSE_FILE: int +FILE_ATTRIBUTE_SYSTEM: int +FILE_ATTRIBUTE_TEMPORARY: int +FILE_ATTRIBUTE_VIRTUAL: int + +if sys.platform == "win32" and sys.version_info >= (3, 8): + IO_REPARSE_TAG_SYMLINK: int + IO_REPARSE_TAG_MOUNT_POINT: int + IO_REPARSE_TAG_APPEXECLINK: int diff --git a/mypy/stdlib/statistics.pyi b/mypy/stdlib/statistics.pyi new file mode 100644 index 000000000000..f2165f0ce9c0 --- /dev/null +++ b/mypy/stdlib/statistics.pyi @@ -0,0 +1,74 @@ +# Stubs for statistics + +from decimal import Decimal +from fractions import Fraction +import sys +from typing import Any, Iterable, List, Optional, SupportsFloat, Type, TypeVar, Union, Protocol, Hashable + +_T = TypeVar("_T") +# Most functions in this module accept homogeneous collections of one of these types +_Number = TypeVar('_Number', float, Decimal, Fraction) + +# Used in median_high, median_low +class _Sortable(Protocol): + def __lt__(self, other) -> bool: ... +_SortableT = TypeVar("_SortableT", bound=_Sortable) + +# Used in mode, multimode +_HashableT = TypeVar("_HashableT", bound=Hashable) + +class StatisticsError(ValueError): ... + +if sys.version_info >= (3, 8): + def fmean(data: Iterable[SupportsFloat]) -> float: ... + def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... +def mean(data: Iterable[_Number]) -> _Number: ... +if sys.version_info >= (3, 6): + def harmonic_mean(data: Iterable[_Number]) -> _Number: ... +def median(data: Iterable[_Number]) -> _Number: ... +def median_low(data: Iterable[_SortableT]) -> _SortableT: ... +def median_high(data: Iterable[_SortableT]) -> _SortableT: ... +def median_grouped(data: Iterable[_Number], interval: _Number = ...) -> _Number: ... +def mode(data: Iterable[_HashableT]) -> _HashableT: ... +if sys.version_info >= (3, 8): + def multimode(data: Iterable[_HashableT]) -> List[_HashableT]: ... +def pstdev(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... +def pvariance(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... +if sys.version_info >= (3, 8): + def quantiles(data: Iterable[_Number], *, n: int = ..., method: str = ...) -> List[_Number]: ... +def stdev(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... +def variance(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... + +if sys.version_info >= (3, 8): + class NormalDist: + def __init__(self, mu: float = ..., sigma: float = ...) -> None: ... + @property + def mean(self) -> float: ... + @property + def median(self) -> float: ... + @property + def mode(self) -> float: ... + @property + def stdev(self) -> float: ... + @property + def variance(self) -> float: ... + @classmethod + def from_samples(cls: Type[_T], data: Iterable[SupportsFloat]) -> _T: ... + def samples(self, n: int, *, seed: Optional[Any] = ...) -> List[float]: ... + def pdf(self, x: float) -> float: ... + def cdf(self, x: float) -> float: ... + def inv_cdf(self, p: float) -> float: ... + def overlap(self, other: NormalDist) -> float: ... + def quantiles(self, n: int = ...) -> List[float]: ... + if sys.version_info >= (3, 9): + def zscore(self, x: float) -> float: ... + def __add__(self, x2: Union[float, NormalDist]) -> NormalDist: ... + def __sub__(self, x2: Union[float, NormalDist]) -> NormalDist: ... + def __mul__(self, x2: float) -> NormalDist: ... + def __truediv__(self, x2: float) -> NormalDist: ... + def __pos__(self) -> NormalDist: ... + def __neg__(self) -> NormalDist: ... + __radd__ = __add__ + def __rsub__(self, x2: Union[float, NormalDist]) -> NormalDist: ... + __rmul__ = __mul__ + def __hash__(self) -> int: ... diff --git a/mypy/stdlib/string.pyi b/mypy/stdlib/string.pyi new file mode 100644 index 000000000000..2347d6cd6ee9 --- /dev/null +++ b/mypy/stdlib/string.pyi @@ -0,0 +1,39 @@ +# Stubs for string + +# Based on http://docs.python.org/3.2/library/string.html + +from typing import Mapping, Sequence, Any, Optional, Union, Tuple, Iterable + +ascii_letters: str +ascii_lowercase: str +ascii_uppercase: str +digits: str +hexdigits: str +octdigits: str +punctuation: str +printable: str +whitespace: str + +def capwords(s: str, sep: Optional[str] = ...) -> str: ... + +class Template: + template: str + + def __init__(self, template: str) -> None: ... + def substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... + def safe_substitute(self, __mapping: Mapping[str, object] = ..., + **kwds: object) -> str: ... + +# TODO(MichalPokorny): This is probably badly and/or loosely typed. +class Formatter: + def format(self, __format_string: str, *args: Any, **kwargs: Any) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> str: ... + def parse(self, format_string: str) -> Iterable[Tuple[str, Optional[str], Optional[str], Optional[str]]]: ... + def get_field(self, field_name: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: Union[int, str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/mypy/stdlib/stringprep.pyi b/mypy/stdlib/stringprep.pyi new file mode 100644 index 000000000000..e3b7e9dc2fee --- /dev/null +++ b/mypy/stdlib/stringprep.pyi @@ -0,0 +1,23 @@ +# Stubs for stringprep (Python 2 and 3) + +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/stdlib/struct.pyi b/mypy/stdlib/struct.pyi new file mode 100644 index 000000000000..c672b924fda0 --- /dev/null +++ b/mypy/stdlib/struct.pyi @@ -0,0 +1,44 @@ +# Stubs for struct + +# Based on http://docs.python.org/3.2/library/struct.html +# Based on http://docs.python.org/2/library/struct.html + +import sys +from typing import Any, Tuple, Text, Union, Iterator +from array import array +from mmap import mmap + +class error(Exception): ... + +_FmtType = Union[bytes, Text] +if sys.version_info >= (3,): + _BufferType = Union[array[int], bytes, bytearray, memoryview, mmap] + _WriteBufferType = Union[array, 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: ... + +class Struct: + if sys.version_info >= (3, 7): + format: str + else: + 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, ...]: ... + if sys.version_info >= (3, 4): + def iter_unpack(self, __buffer: _BufferType) -> Iterator[Tuple[Any, ...]]: ... diff --git a/mypy/stdlib/subprocess.pyi b/mypy/stdlib/subprocess.pyi new file mode 100644 index 000000000000..1507079373ee --- /dev/null +++ b/mypy/stdlib/subprocess.pyi @@ -0,0 +1,1204 @@ +import sys +from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union, Type, Generic, TypeVar, AnyStr, overload +from types import TracebackType +from typing_extensions import Literal +from _typeshed import AnyPath + +# We prefer to annotate inputs to methods (eg subprocess.check_call) with these +# union types. +# For outputs we use laborious literal based overloads to try to determine +# which specific return types to use, and prefer to fall back to Any when +# this does not work, so the caller does not have to use an assertion to confirm +# which type. +# +# For example: +# +# try: +# x = subprocess.check_output(["ls", "-l"]) +# reveal_type(x) # bytes, based on the overloads +# except TimeoutError as e: +# reveal_type(e.cmd) # Any, but morally is _CMD +_FILE = Union[None, int, IO[Any]] +_TXT = Union[bytes, str] +# Python 3.6 does't support _CMD being a single PathLike. +# See: https://bugs.python.org/issue31961 +_CMD = Union[_TXT, Sequence[AnyPath]] +_ENV = Union[Mapping[bytes, _TXT], Mapping[str, _TXT]] + +_S = TypeVar('_S') +_T = TypeVar('_T') + +class CompletedProcess(Generic[_T]): + # morally: _CMD + args: Any + returncode: int + # These are really both Optional, but requiring checks would be tedious + # and writing all the overloads would be horrific. + stdout: _T + stderr: _T + def __init__(self, args: _CMD, returncode: int, stdout: Optional[_T] = ..., stderr: Optional[_T] = ...) -> None: ... + def check_returncode(self) -> None: ... + +if sys.version_info >= (3, 7): + # Nearly the same args as for 3.6, except for capture_output and text + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[str] = ..., + text: Literal[True], + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: str, + errors: Optional[str] = ..., + input: Optional[str] = ..., + text: Optional[bool] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: Optional[str] = ..., + errors: str, + input: Optional[str] = ..., + text: Optional[bool] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + capture_output: bool = ..., + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[str] = ..., + text: Optional[bool] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: None = ..., + errors: None = ..., + input: Optional[bytes] = ..., + text: Literal[None, False] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[bytes]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[_TXT] = ..., + text: Optional[bool] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[Any]: ... +elif sys.version_info >= (3, 6): + # Nearly same args as Popen.__init__ except for timeout, input, and check + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + encoding: str, + errors: Optional[str] = ..., + input: Optional[str] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + encoding: Optional[str] = ..., + errors: str, + input: Optional[str] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[str] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + encoding: None = ..., + errors: None = ..., + input: Optional[bytes] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[bytes]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[_TXT] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[Any]: ... +else: + # Nearly same args as Popen.__init__ except for timeout, input, and check + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + check: bool = ..., + input: Optional[str] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[str]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + input: Optional[bytes] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[bytes]: ... + @overload + def run( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + input: Optional[_TXT] = ..., + timeout: Optional[float] = ..., + ) -> CompletedProcess[Any]: ... + +# Same args as Popen.__init__ +def call(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ...) -> int: ... + +# Same args as Popen.__init__ +def check_call(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: Optional[float] = ...) -> int: ... + +if sys.version_info >= (3, 7): + # 3.7 added text + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Literal[True], + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: str, + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: str, + text: Optional[bool] = ..., + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the real keyword only ones start + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: None = ..., + errors: None = ..., + text: Literal[None, False] = ..., + ) -> bytes: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> Any: ... # morally: -> _TXT +elif sys.version_info >= (3, 6): + # 3.6 added encoding and errors + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: str, + errors: Optional[str] = ..., + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: str, + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + universal_newlines: Literal[True], + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: None = ..., + errors: None = ..., + ) -> bytes: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Any: ... # morally: -> _TXT +else: + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + input: _TXT = ..., + *, + timeout: Optional[float] = ..., + universal_newlines: Literal[True], + ) -> str: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + input: _TXT = ..., + *, + timeout: Optional[float] = ..., + ) -> bytes: ... + @overload + def check_output(args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + input: _TXT = ..., + *, + timeout: Optional[float] = ..., + ) -> Any: ... # morally: -> _TXT + + +PIPE: int +STDOUT: int +DEVNULL: int +class SubprocessError(Exception): ... +class TimeoutExpired(SubprocessError): + def __init__(self, cmd: _CMD, timeout: float, output: Optional[_TXT] = ..., stderr: Optional[_TXT] = ...) -> None: ... + # morally: _CMD + cmd: Any + timeout: float + # morally: Optional[_TXT] + output: Any + stdout: Any + stderr: Any + + +class CalledProcessError(SubprocessError): + returncode: int + # morally: _CMD + cmd: Any + # morally: Optional[_TXT] + output: Any + + # morally: Optional[_TXT] + stdout: Any + stderr: Any + + def __init__(self, + returncode: int, + cmd: _CMD, + output: Optional[_TXT] = ..., + stderr: Optional[_TXT] = ...) -> None: ... + +class Popen(Generic[AnyStr]): + args: _CMD + stdin: Optional[IO[AnyStr]] + stdout: Optional[IO[AnyStr]] + stderr: Optional[IO[AnyStr]] + pid: int + returncode: int + universal_newlines: bool + + # Technically it is wrong that Popen provides __new__ instead of __init__ + # but this shouldn't come up hopefully? + + if sys.version_info >= (3, 7): + # text is added in 3.7 + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: str, + errors: Optional[str] = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: str) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[True], + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[None, False] = ..., + encoding: None = ..., + errors: None = ...) -> Popen[bytes]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> Popen[Any]: ... + elif sys.version_info >= (3, 6): + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: str, + errors: Optional[str] = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: Optional[str] = ..., + errors: str) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: None = ..., + errors: None = ...) -> Popen[bytes]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> Popen[Any]: ... + else: + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ...) -> Popen[str]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[False] = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ...) -> Popen[bytes]: ... + @overload + def __new__(cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ...) -> Popen[Any]: ... + + def poll(self) -> Optional[int]: ... + if sys.version_info >= (3, 7): + def wait(self, timeout: Optional[float] = ...) -> int: ... + else: + def wait(self, timeout: Optional[float] = ..., endtime: Optional[float] = ...) -> int: ... + # Return str/bytes + def communicate(self, + input: Optional[AnyStr] = ..., + timeout: Optional[float] = ..., + # morally this should be optional + ) -> Tuple[AnyStr, AnyStr]: ... + def send_signal(self, sig: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def __enter__(self: _S) -> _S: ... + def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: ... + +# The result really is always a str. +def getstatusoutput(cmd: _TXT) -> Tuple[int, str]: ... +def getoutput(cmd: _TXT) -> str: ... + +def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented + +if sys.platform == 'win32': + class STARTUPINFO: + if sys.version_info >= (3, 7): + def __init__(self, *, dwFlags: int = ..., hStdInput: Optional[Any] = ..., hStdOutput: Optional[Any] = ..., hStdError: Optional[Any] = ..., wShowWindow: int = ..., lpAttributeList: Optional[Mapping[str, Any]] = ...) -> None: ... + dwFlags: int + hStdInput: Optional[Any] + hStdOutput: Optional[Any] + hStdError: Optional[Any] + wShowWindow: int + if sys.version_info >= (3, 7): + lpAttributeList: Mapping[str, Any] + + STD_INPUT_HANDLE: Any + STD_OUTPUT_HANDLE: Any + STD_ERROR_HANDLE: Any + SW_HIDE: int + STARTF_USESTDHANDLES: int + STARTF_USESHOWWINDOW: int + CREATE_NEW_CONSOLE: int + CREATE_NEW_PROCESS_GROUP: int + if sys.version_info >= (3, 7): + ABOVE_NORMAL_PRIORITY_CLASS: int + BELOW_NORMAL_PRIORITY_CLASS: int + HIGH_PRIORITY_CLASS: int + IDLE_PRIORITY_CLASS: int + NORMAL_PRIORITY_CLASS: int + REALTIME_PRIORITY_CLASS: int + CREATE_NO_WINDOW: int + DETACHED_PROCESS: int + CREATE_DEFAULT_ERROR_MODE: int + CREATE_BREAKAWAY_FROM_JOB: int diff --git a/mypy/stdlib/sunau.pyi b/mypy/stdlib/sunau.pyi new file mode 100644 index 000000000000..782ff721418a --- /dev/null +++ b/mypy/stdlib/sunau.pyi @@ -0,0 +1,87 @@ +# Stubs for sunau (Python 2 and 3) + +import sys +from typing import Any, NamedTuple, NoReturn, Optional, Text, IO, Union, Tuple + +_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 + +if sys.version_info < (3, 0): + _sunau_params = Tuple[int, int, int, int, str, str] +else: + 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 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: ... + if sys.version_info >= (3, 3): + 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: ... + 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: _sunau_params) -> None: ... + def getparams(self) -> _sunau_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 Au_read if mode is rb and Au_write if mode is wb +def open(f: _File, mode: Optional[str] = ...) -> Any: ... +if sys.version_info < (3, 9): + openfp = open diff --git a/mypy/stdlib/symbol.pyi b/mypy/stdlib/symbol.pyi new file mode 100644 index 000000000000..59be5776560b --- /dev/null +++ b/mypy/stdlib/symbol.pyi @@ -0,0 +1,94 @@ +# Stubs for symbol (Python 3) + +import sys +from typing import Dict + +single_input: int +file_input: int +eval_input: int +decorator: int +decorators: int +decorated: int +async_funcdef: int +funcdef: int +parameters: int +typedargslist: int +tfpdef: int +varargslist: int +vfpdef: int +stmt: int +simple_stmt: int +small_stmt: int +expr_stmt: int +if sys.version_info >= (3, 6): + annassign: int +testlist_star_expr: int +augassign: int +del_stmt: int +pass_stmt: int +flow_stmt: int +break_stmt: int +continue_stmt: int +return_stmt: int +yield_stmt: int +raise_stmt: int +import_stmt: int +import_name: int +import_from: int +import_as_name: int +dotted_as_name: int +import_as_names: int +dotted_as_names: int +dotted_name: int +global_stmt: int +nonlocal_stmt: int +assert_stmt: int +compound_stmt: int +async_stmt: int +if_stmt: int +while_stmt: int +for_stmt: int +try_stmt: int +with_stmt: int +with_item: int +except_clause: int +suite: int +test: int +test_nocond: int +lambdef: int +lambdef_nocond: int +or_test: int +and_test: int +not_test: int +comparison: int +comp_op: int +star_expr: int +expr: int +xor_expr: int +and_expr: int +shift_expr: int +arith_expr: int +term: int +factor: int +power: int +atom_expr: int +atom: int +testlist_comp: int +trailer: int +subscriptlist: int +subscript: int +sliceop: int +exprlist: int +testlist: int +dictorsetmaker: int +classdef: int +arglist: int +argument: int +comp_iter: int +comp_for: int +comp_if: int +encoding_decl: int +yield_expr: int +yield_arg: int + +sym_name: Dict[int, str] diff --git a/mypy/stdlib/symtable.pyi b/mypy/stdlib/symtable.pyi new file mode 100644 index 000000000000..fd8b9ad79bb8 --- /dev/null +++ b/mypy/stdlib/symtable.pyi @@ -0,0 +1,45 @@ +import sys +from typing import List, Sequence, Tuple, Text + +def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... + +class SymbolTable(object): + 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: ... + 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]: ... + 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 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: ... + if sys.version_info >= (3, 6): + def is_annotated(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/stdlib/sys.pyi b/mypy/stdlib/sys.pyi new file mode 100644 index 000000000000..fb53b7b50291 --- /dev/null +++ b/mypy/stdlib/sys.pyi @@ -0,0 +1,225 @@ +# Stubs for sys +# Ron Murawski + +# based on http://docs.python.org/3.2/library/sys.html + +from typing import ( + List, NoReturn, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, + Union, TypeVar, Callable, Type +) +import sys +from types import FrameType, ModuleType, TracebackType + +from importlib.abc import MetaPathFinder + +_T = TypeVar('_T') + +# The following type alias are stub-only and do not exist during runtime +_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] + +# ----- sys variables ----- +if sys.platform != "win32": + abiflags: str +argv: List[str] +base_exec_prefix: str +base_prefix: str +byteorder: str +builtin_module_names: Sequence[str] # actually a tuple of strings +copyright: str +if sys.platform == "win32": + dllhandle: int +dont_write_bytecode: bool +displayhook: Callable[[object], Any] +excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] +exec_prefix: str +executable: str +float_repr_style: str +hexversion: int +last_type: Optional[Type[BaseException]] +last_value: Optional[BaseException] +last_traceback: Optional[TracebackType] +maxsize: int +maxunicode: int +meta_path: List[MetaPathFinder] +modules: Dict[str, ModuleType] +path: List[str] +path_hooks: List[Any] # TODO precise type; function, path to finder +path_importer_cache: Dict[str, Any] # TODO precise type +platform: str +if sys.version_info >= (3, 9): + platlibdir: str +prefix: str +if sys.version_info >= (3, 8): + pycache_prefix: Optional[str] +ps1: str +ps2: str +stdin: TextIO +stdout: TextIO +stderr: TextIO +__stdin__: TextIO +__stdout__: TextIO +__stderr__: TextIO +tracebacklimit: int +version: str +api_version: int +warnoptions: Any +# Each entry is a tuple of the form (action, message, category, module, +# lineno) +if sys.platform == "win32": + winver: str +_xoptions: Dict[Any, Any] + + +flags: _flags +class _flags: + debug: int + division_warning: int + inspect: int + interactive: int + optimize: int + dont_write_bytecode: int + no_user_site: int + no_site: int + ignore_environment: int + verbose: int + bytes_warning: int + quiet: int + hash_randomization: int + if sys.version_info >= (3, 7): + dev_mode: int + utf8_mode: int + +float_info: _float_info +class _float_info: + epsilon: float # DBL_EPSILON + dig: int # DBL_DIG + mant_dig: int # DBL_MANT_DIG + max: float # DBL_MAX + max_exp: int # DBL_MAX_EXP + max_10_exp: int # DBL_MAX_10_EXP + min: float # DBL_MIN + min_exp: int # DBL_MIN_EXP + min_10_exp: int # DBL_MIN_10_EXP + radix: int # FLT_RADIX + rounds: int # FLT_ROUNDS + +hash_info: _hash_info +class _hash_info: + width: int + modulus: int + inf: int + nan: int + imag: int + +implementation: _implementation +class _implementation: + name: str + version: _version_info + hexversion: int + cache_tag: str + +int_info: _int_info +class _int_info: + bits_per_digit: int + sizeof_digit: int + +class _version_info(Tuple[int, int, int, str, int]): + major: int + minor: int + micro: int + releaselevel: str + serial: int +version_info: _version_info + +def call_tracing(__func: Callable[..., _T], __args: Any) -> _T: ... +def _clear_type_cache() -> None: ... +def _current_frames() -> Dict[int, Any]: ... +def _debugmallocstats() -> None: ... +def __displayhook__(value: object) -> None: ... +def __excepthook__(type_: Type[BaseException], value: BaseException, + traceback: TracebackType) -> None: ... +def exc_info() -> _OptExcInfo: ... +# sys.exit() accepts an optional argument of anything printable +def exit(__status: object = ...) -> NoReturn: ... +def getdefaultencoding() -> str: ... +if sys.platform != 'win32': + def getdlopenflags() -> int: ... +def getfilesystemencoding() -> str: ... +def getrefcount(__object: Any) -> int: ... +def getrecursionlimit() -> int: ... + +@overload +def getsizeof(obj: object) -> int: ... +@overload +def getsizeof(obj: object, default: int) -> int: ... + +def getswitchinterval() -> float: ... + +def _getframe(__depth: int = ...) -> FrameType: ... + +_ProfileFunc = Callable[[FrameType, str, Any], Any] +def getprofile() -> Optional[_ProfileFunc]: ... +def setprofile(profilefunc: Optional[_ProfileFunc]) -> None: ... + +_TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] +def gettrace() -> Optional[_TraceFunc]: ... +def settrace(tracefunc: Optional[_TraceFunc]) -> None: ... + + +class _WinVersion(Tuple[int, int, int, int, + str, int, int, int, int, + Tuple[int, int, int]]): + major: int + minor: int + build: int + platform: int + service_pack: str + service_pack_minor: int + service_pack_major: int + suite_mast: int + product_type: int + platform_version: Tuple[int, int, int] + +if sys.platform == "win32": + def getwindowsversion() -> _WinVersion: ... + +def intern(__string: str) -> str: ... + +def is_finalizing() -> bool: ... + +if sys.version_info >= (3, 7): + __breakpointhook__: Any # contains the original value of breakpointhook + def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... + +if sys.platform != "win32": + def setdlopenflags(__flags: int) -> None: ... +def setrecursionlimit(__limit: int) -> None: ... +def setswitchinterval(__interval: float) -> None: ... + +def gettotalrefcount() -> int: ... # Debug builds only + +if sys.version_info < (3, 9): + def getcheckinterval() -> int: ... # deprecated + def setcheckinterval(__n: int) -> None: ... # deprecated + +if sys.version_info >= (3, 8): + # not exported by sys + class UnraisableHookArgs: + exc_type: Type[BaseException] + exc_value: Optional[BaseException] + exc_traceback: Optional[TracebackType] + err_msg: Optional[str] + object: Optional[object] + unraisablehook: Callable[[UnraisableHookArgs], Any] + def addaudithook(hook: Callable[[str, Tuple[Any, ...]], Any]) -> None: ... + def audit(__event: str, *args: Any) -> None: ... + +if sys.version_info >= (3, 6): + from typing import AsyncGenerator + _AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] + class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): + firstiter: _AsyncgenHook + finalizer: _AsyncgenHook + def get_asyncgen_hooks() -> _asyncgen_hooks: ... + def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... diff --git a/mypy/stdlib/sysconfig.pyi b/mypy/stdlib/sysconfig.pyi new file mode 100644 index 000000000000..6548f40588c8 --- /dev/null +++ b/mypy/stdlib/sysconfig.pyi @@ -0,0 +1,17 @@ +from typing import overload, Any, Dict, IO, List, Optional, Tuple, Union + +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() -> 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/stdlib/syslog.pyi b/mypy/stdlib/syslog.pyi new file mode 100644 index 000000000000..1237a6b0b241 --- /dev/null +++ b/mypy/stdlib/syslog.pyi @@ -0,0 +1,44 @@ +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/stdlib/tabnanny.pyi b/mypy/stdlib/tabnanny.pyi new file mode 100644 index 000000000000..7784c9fc8d1b --- /dev/null +++ b/mypy/stdlib/tabnanny.pyi @@ -0,0 +1,14 @@ +from _typeshed import AnyPath +from typing import Iterable, 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: AnyPath) -> None: ... +def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... diff --git a/mypy/stdlib/tarfile.pyi b/mypy/stdlib/tarfile.pyi new file mode 100644 index 000000000000..8a64902de56f --- /dev/null +++ b/mypy/stdlib/tarfile.pyi @@ -0,0 +1,222 @@ +from typing import ( + Callable, IO, Iterable, Iterator, List, Mapping, Optional, Type, + Union, Tuple, Dict, Set +) +import sys +from _typeshed import AnyPath +from types import TracebackType + +# 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] + +if sys.version_info >= (3,): + PAX_NAME_FIELDS: Set[str] + + +ENCODING: str + +if sys.version_info < (3,): + TAR_PLAIN: int + TAR_GZIPPED: int + +def open(name: Optional[AnyPath] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., + *, format: Optional[int] = ..., tarinfo: Optional[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 TarFile(Iterable[TarInfo]): + name: Optional[AnyPath] + mode: str + fileobj: Optional[IO[bytes]] + format: Optional[int] + tarinfo: Optional[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] + if sys.version_info < (3,): + posix: bool + def __init__(self, name: Optional[AnyPath] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + format: Optional[int] = ..., tarinfo: Optional[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] = ...) -> 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[AnyPath] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., + *, format: Optional[int] = ..., tarinfo: Optional[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: ... + 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 next(self) -> Optional[TarInfo]: ... + if sys.version_info >= (3, 5): + def extractall(self, path: AnyPath = ..., + members: Optional[List[TarInfo]] = ..., + *, numeric_owner: bool = ...) -> None: ... + else: + def extractall(self, path: AnyPath = ..., + members: Optional[List[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 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 + if sys.version_info >= (3, 7): + def add(self, name: str, arcname: Optional[str] = ..., + recursive: bool = ..., *, + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + elif sys.version_info >= (3,): + def add(self, name: str, arcname: Optional[str] = ..., + recursive: bool = ..., + exclude: Optional[Callable[[str], bool]] = ..., *, + 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]] = ...) -> TarInfo: ... + def close(self) -> None: ... + +if sys.version_info >= (3, 9): + def is_tarfile(name: Union[AnyPath, IO[bytes]]) -> bool: ... +else: + def is_tarfile(name: AnyPath) -> 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): ... +class StreamError(TarError): ... +class ExtractError(TarError): ... +class HeaderError(TarError): ... + +class TarInfo: + name: str + size: int + mtime: int + 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: ... + 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 fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + def tobuf(self, format: Optional[int] = ..., + encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... + def isfile(self) -> bool: ... + def isreg(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/stdlib/telnetlib.pyi b/mypy/stdlib/telnetlib.pyi new file mode 100644 index 000000000000..50b90b58dfe2 --- /dev/null +++ b/mypy/stdlib/telnetlib.pyi @@ -0,0 +1,115 @@ +# Stubs for telnetlib (Python 2 and 3) + +import socket +import sys +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: + def __init__(self, host: Optional[str] = ..., port: int = ..., + timeout: int = ...) -> None: ... + def open(self, host: str, port: int = ..., timeout: int = ...) -> 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[int] = ...) -> 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[int] = ...) -> 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: ... diff --git a/mypy/stdlib/tempfile.pyi b/mypy/stdlib/tempfile.pyi new file mode 100644 index 000000000000..0f5cdecf4ee6 --- /dev/null +++ b/mypy/stdlib/tempfile.pyi @@ -0,0 +1,302 @@ +import os +import sys +from types import TracebackType +from typing import Any, AnyStr, Generic, IO, Iterable, Iterator, List, Optional, overload, Tuple, Type, TypeVar, Union +from typing_extensions import Literal + +# global variables +TMP_MAX: int +tempdir: Optional[str] +template: str + +_S = TypeVar("_S") +_T = TypeVar("_T") # for pytype, define typevar in same file as alias +if sys.version_info >= (3, 6): + _DirT = Union[_T, os.PathLike[_T]] +else: + _DirT = Union[_T] + +if sys.version_info >= (3, 8): + @overload + def NamedTemporaryFile( + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + *, + errors: Optional[str] = ... + ) -> IO[str]: ... + @overload + def NamedTemporaryFile( + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + *, + errors: Optional[str] = ... + ) -> IO[bytes]: ... + @overload + def NamedTemporaryFile( + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + *, + errors: Optional[str] = ... + ) -> IO[Any]: ... +else: + @overload + def NamedTemporaryFile( + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + ) -> IO[str]: ... + @overload + def NamedTemporaryFile( + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + ) -> IO[bytes]: ... + @overload + def NamedTemporaryFile( + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + delete: bool = ..., + ) -> IO[Any]: ... + +if sys.platform == "win32": + TemporaryFile = NamedTemporaryFile +else: + if sys.version_info >= (3, 8): + @overload + def TemporaryFile( + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + *, + errors: Optional[str] = ... + ) -> IO[str]: ... + @overload + def TemporaryFile( + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + *, + errors: Optional[str] = ... + ) -> IO[bytes]: ... + @overload + def TemporaryFile( + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + *, + errors: Optional[str] = ... + ) -> IO[Any]: ... + else: + @overload + def TemporaryFile( + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + ) -> IO[str]: ... + @overload + def TemporaryFile( + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + ) -> IO[bytes]: ... + @overload + def TemporaryFile( + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[AnyStr] = ..., + prefix: Optional[AnyStr] = ..., + dir: Optional[_DirT[AnyStr]] = ..., + ) -> IO[Any]: ... + +# It does not actually derive from IO[AnyStr], but it does implement the +# protocol. +class SpooledTemporaryFile(IO[AnyStr]): + # bytes needs to go first, as default mode is to open as bytes + if sys.version_info >= (3, 8): + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + *, + errors: Optional[str] = ... + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + *, + errors: Optional[str] = ... + ) -> None: ... + @overload + def __init__( + self, + max_size: int = ..., + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + *, + errors: Optional[str] = ... + ) -> None: ... + + @property + def errors(self) -> Optional[str]: ... + else: + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + ) -> None: ... + @overload + def __init__( + self, + max_size: int = ..., + mode: str = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + newline: Optional[str] = ..., + suffix: Optional[str] = ..., + prefix: Optional[str] = ..., + dir: Optional[str] = ..., + ) -> None: ... + def rollover(self) -> None: ... + def __enter__(self: _S) -> _S: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + # These methods are copied from the abstract methods of IO, because + # SpooledTemporaryFile implements IO. + # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, n: int = ...) -> AnyStr: ... + def readline(self, limit: int = ...) -> AnyStr: ... + def readlines(self, hint: int = ...) -> List[AnyStr]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + # Other than the following methods, which do not exist on SpooledTemporaryFile + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + def writable(self) -> bool: ... + def __next__(self) -> AnyStr: ... + +class TemporaryDirectory(Generic[AnyStr]): + name: str + def __init__( + self, suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ... + ) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> AnyStr: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + +def mkstemp( + suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., text: bool = ... +) -> Tuple[int, AnyStr]: ... +@overload +def mkdtemp() -> str: ... +@overload +def mkdtemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...) -> AnyStr: ... +def mktemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...) -> AnyStr: ... +def gettempdirb() -> bytes: ... +def gettempprefixb() -> bytes: ... +def gettempdir() -> str: ... +def gettempprefix() -> str: ... diff --git a/mypy/stdlib/termios.pyi b/mypy/stdlib/termios.pyi new file mode 100644 index 000000000000..9c8a9553e2af --- /dev/null +++ b/mypy/stdlib/termios.pyi @@ -0,0 +1,246 @@ +from typing import List, Union +from _typeshed import FileDescriptorLike + +_Attr = List[Union[int, List[bytes]]] + +# 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) -> _Attr: ... +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/stdlib/textwrap.pyi b/mypy/stdlib/textwrap.pyi new file mode 100644 index 000000000000..4cec8c50c828 --- /dev/null +++ b/mypy/stdlib/textwrap.pyi @@ -0,0 +1,113 @@ +from typing import Callable, List, Optional, Dict, Pattern + +class TextWrapper: + width: int = ... + initial_indent: str = ... + subsequent_indent: str = ... + expand_tabs: bool = ... + replace_whitespace: bool = ... + fix_sentence_endings: bool = ... + drop_whitespace: bool = ... + break_long_words: bool = ... + break_on_hyphens: bool = ... + tabsize: int = ... + max_lines: Optional[int] = ... + placeholder: str = ... + + # Attributes not present in documentation + sentence_end_re: Pattern[str] = ... + wordsep_re: Pattern[str] = ... + wordsep_simple_re: Pattern[str] = ... + whitespace_trans: str = ... + unicode_whitespace_trans: Dict[int, int] = ... + uspace: int = ... + x: str = ... # leaked loop variable + + def __init__( + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., + tabsize: int = ..., + *, + max_lines: Optional[int] = ..., + placeholder: str = ...) -> None: + ... + + # Private methods *are* part of the documented API for subclasses. + def _munge_whitespace(self, text: str) -> str: ... + def _split(self, text: str) -> List[str]: ... + def _fix_sentence_endings(self, chunks: List[str]) -> None: ... + def _handle_long_word(self, reversed_chunks: List[str], cur_line: List[str], cur_len: int, width: int) -> None: ... + def _wrap_chunks(self, chunks: List[str]) -> List[str]: ... + def _split_chunks(self, text: str) -> List[str]: ... + + def wrap(self, text: str) -> List[str]: ... + def fill(self, text: str) -> str: ... + + +def wrap( + text: str, + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ... +) -> List[str]: + ... + +def fill( + text: str, + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ... +) -> str: + ... + +def shorten( + text: str, + width: int, + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + # Omit `max_lines: int = None`, it is forced to 1 here. + placeholder: str = ... +) -> str: + ... + +def dedent(text: str) -> str: + ... + +def indent(text: str, prefix: str, predicate: Optional[Callable[[str], bool]] = ...) -> str: + ... diff --git a/mypy/stdlib/this.pyi b/mypy/stdlib/this.pyi new file mode 100644 index 000000000000..c347e431d539 --- /dev/null +++ b/mypy/stdlib/this.pyi @@ -0,0 +1,5 @@ + +from typing import Dict + +s: str +d: Dict[str, str] diff --git a/mypy/stdlib/threading.pyi b/mypy/stdlib/threading.pyi new file mode 100644 index 000000000000..ae8997251322 --- /dev/null +++ b/mypy/stdlib/threading.pyi @@ -0,0 +1,190 @@ + +from typing import ( + Any, Callable, Iterable, List, Mapping, Optional, Text, Tuple, Type, Union, + TypeVar, +) +from types import FrameType, TracebackType +import sys + +# 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: ... +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 enumerate() -> List[Thread]: ... + +if sys.version_info >= (3, 4): + def main_thread() -> Thread: ... + +if sys.version_info >= (3, 8): + from _thread import get_native_id as get_native_id + +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 + +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 + if sys.version_info >= (3,): + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + *, daemon: Optional[bool] = ...) -> None: ... + else: + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: 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: ... + if sys.version_info >= (3, 8): + @property + def native_id(self) -> Optional[int]: ... # only available on some platforms + def is_alive(self) -> bool: ... + if sys.version_info < (3, 9): + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + 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]: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> 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 notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + def notifyAll(self) -> None: ... + + +class Semaphore: + def __init__(self, value: int = ...) -> None: ... + def __enter__(self) -> bool: ... + 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: ... + if sys.version_info >= (3, 9): + def release(self, n: int = ...) -> None: ... + else: + def release(self) -> None: ... + +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: ... + +if sys.version_info >= (3, 8): + from _thread import _ExceptHookArgs as ExceptHookArgs, ExceptHookArgs as _ExceptHookArgs # don't ask + excepthook: Callable[[_ExceptHookArgs], Any] + +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 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): ... diff --git a/mypy/stdlib/time.pyi b/mypy/stdlib/time.pyi new file mode 100644 index 000000000000..08703e0a9f82 --- /dev/null +++ b/mypy/stdlib/time.pyi @@ -0,0 +1,113 @@ +"""Stub file for the 'time' module.""" +# See https://docs.python.org/3/library/time.html + +import sys +from typing import Any, NamedTuple, Tuple, Union, Optional +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 +tzname: Tuple[str, str] + +if sys.version_info >= (3, 7) and sys.platform != 'win32': + CLOCK_BOOTTIME: int # Linux + CLOCK_PROF: int # FreeBSD, NetBSD, OpenBSD + CLOCK_UPTIME: int # FreeBSD, OpenBSD + +if sys.version_info >= (3, 3) and sys.platform != 'win32': + CLOCK_HIGHRES: int # Solaris only + CLOCK_MONOTONIC: int # Unix only + CLOCK_MONOTONIC_RAW: int # Linux 2.6.28 or later + CLOCK_PROCESS_CPUTIME_ID: int # Unix only + CLOCK_REALTIME: int # Unix only + CLOCK_THREAD_CPUTIME_ID: int # Unix only + +if sys.version_info >= (3, 8) and sys.platform == "darwin": + CLOCK_UPTIME_RAW: int + +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: ... +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: ... + @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: ... + +def asctime(t: Union[_TimeTuple, struct_time] = ...) -> str: ... +if sys.version_info < (3, 8): + 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 + +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 + +if sys.version_info >= (3, 7): + if sys.platform != "win32": + def clock_gettime_ns(clock_id: int) -> int: ... + def clock_settime_ns(clock_id: int, time: int) -> int: ... + def monotonic_ns() -> int: ... + def perf_counter_ns() -> int: ... + def process_time_ns() -> int: ... + def time_ns() -> int: ... + def thread_time() -> float: ... + def thread_time_ns() -> int: ... diff --git a/mypy/stdlib/timeit.pyi b/mypy/stdlib/timeit.pyi new file mode 100644 index 000000000000..bc4cbba87d36 --- /dev/null +++ b/mypy/stdlib/timeit.pyi @@ -0,0 +1,34 @@ +# Stubs for timeit (Python 2 and 3) + +import sys +from typing import Any, Callable, Dict, IO, List, Optional, Sequence, Text, Tuple, Union + +_str = Union[str, Text] +_Timer = Callable[[], float] +_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 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]: ... + +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 main(args: Optional[Sequence[str]]) -> None: ... diff --git a/mypy/stdlib/tkinter/__init__.pyi b/mypy/stdlib/tkinter/__init__.pyi new file mode 100644 index 000000000000..26b5ffee6bf1 --- /dev/null +++ b/mypy/stdlib/tkinter/__init__.pyi @@ -0,0 +1,743 @@ +import sys +from enum import Enum +from types import TracebackType +from typing import Any, Optional, Dict, Callable, Tuple, Type, Union +from tkinter.constants import * # noqa: F403 + +TclError: Any +wantobjects: Any +TkVersion: Any +TclVersion: Any +READABLE: Any +WRITABLE: Any +EXCEPTION: Any + +if sys.version_info >= (3, 6): + class EventType(str, Enum): + Activate: str = ... + ButtonPress: str = ... + ButtonRelease: str = ... + Circulate: str = ... + CirculateRequest: str = ... + ClientMessage: str = ... + Colormap: str = ... + Configure: str = ... + ConfigureRequest: str = ... + Create: str = ... + Deactivate: str = ... + Destroy: str = ... + Enter: str = ... + Expose: str = ... + FocusIn: str = ... + FocusOut: str = ... + GraphicsExpose: str = ... + Gravity: str = ... + KeyPress: str = ... + KeyRelease: str = ... + Keymap: str = ... + Leave: str = ... + Map: str = ... + MapRequest: str = ... + Mapping: str = ... + Motion: str = ... + MouseWheel: str = ... + NoExpose: str = ... + Property: str = ... + Reparent: str = ... + ResizeRequest: str = ... + Selection: str = ... + SelectionClear: str = ... + SelectionRequest: str = ... + Unmap: str = ... + VirtualEvent: str = ... + Visibility: str = ... + +class Event: + serial: int + num: int + focus: bool + height: int + width: int + keycode: int + state: Union[int, str] + time: int + x: int + y: int + x_root: int + y_root: int + char: str + send_event: bool + keysym: str + keysym_num: int + if sys.version_info >= (3, 6): + type: EventType + else: + type: str + widget: Misc + delta: int + +def NoDefaultRoot(): ... + +class Variable: + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def __del__(self): ... + def set(self, value): ... + initialize: Any + def get(self): ... + def trace_variable(self, mode, callback): ... + trace: Any + def trace_vdelete(self, mode, cbname): ... + def trace_vinfo(self): ... + def __eq__(self, other): ... + if sys.version_info >= (3, 6): + def trace_add(self, mode, callback): ... + def trace_remove(self, mode, cbname) -> None: ... + def trace_info(self): ... + +class StringVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class IntVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class DoubleVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class BooleanVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def set(self, value): ... + initialize: Any + def get(self): ... + +def mainloop(n: int = ...): ... + +getint: Any +getdouble: Any + +def getboolean(s): ... + +class Misc: + def destroy(self): ... + def deletecommand(self, name): ... + def tk_strictMotif(self, boolean: Optional[Any] = ...): ... + def tk_bisque(self): ... + def tk_setPalette(self, *args, **kw): ... + if sys.version_info < (3, 6): + def tk_menuBar(self, *args): ... + def wait_variable(self, name: Union[str, Variable] = ...): ... + waitvar: Any + def wait_window(self, window: Optional[Any] = ...): ... + def wait_visibility(self, window: Optional[Any] = ...): ... + def setvar(self, name: str = ..., value: str = ...): ... + def getvar(self, name: str = ...): ... + def getint(self, s): ... + def getdouble(self, s): ... + def getboolean(self, s): ... + def focus_set(self): ... + focus: Any + def focus_force(self): ... + def focus_get(self): ... + def focus_displayof(self): ... + def focus_lastfor(self): ... + def tk_focusFollowsMouse(self): ... + def tk_focusNext(self): ... + def tk_focusPrev(self): ... + def after(self, ms, func: Optional[Any] = ..., *args): ... + def after_idle(self, func, *args): ... + def after_cancel(self, id): ... + def bell(self, displayof: int = ...): ... + def clipboard_get(self, **kw): ... + def clipboard_clear(self, **kw): ... + def clipboard_append(self, string, **kw): ... + def grab_current(self): ... + def grab_release(self): ... + def grab_set(self): ... + def grab_set_global(self): ... + def grab_status(self): ... + def option_add(self, pattern, value, priority: Optional[Any] = ...): ... + def option_clear(self): ... + def option_get(self, name, className): ... + def option_readfile(self, fileName, priority: Optional[Any] = ...): ... + def selection_clear(self, **kw): ... + def selection_get(self, **kw): ... + def selection_handle(self, command, **kw): ... + def selection_own(self, **kw): ... + def selection_own_get(self, **kw): ... + def send(self, interp, cmd, *args): ... + def lower(self, belowThis: Optional[Any] = ...): ... + def tkraise(self, aboveThis: Optional[Any] = ...): ... + lift: Any + def winfo_atom(self, name, displayof: int = ...): ... + def winfo_atomname(self, id, displayof: int = ...): ... + def winfo_cells(self): ... + def winfo_children(self): ... + def winfo_class(self): ... + def winfo_colormapfull(self): ... + def winfo_containing(self, rootX, rootY, displayof: int = ...): ... + def winfo_depth(self): ... + def winfo_exists(self): ... + def winfo_fpixels(self, number): ... + def winfo_geometry(self): ... + def winfo_height(self): ... + def winfo_id(self): ... + def winfo_interps(self, displayof: int = ...): ... + def winfo_ismapped(self): ... + def winfo_manager(self): ... + def winfo_name(self): ... + def winfo_parent(self): ... + def winfo_pathname(self, id, displayof: int = ...): ... + def winfo_pixels(self, number): ... + def winfo_pointerx(self): ... + def winfo_pointerxy(self): ... + def winfo_pointery(self): ... + def winfo_reqheight(self): ... + def winfo_reqwidth(self): ... + def winfo_rgb(self, color): ... + def winfo_rootx(self): ... + def winfo_rooty(self): ... + def winfo_screen(self): ... + def winfo_screencells(self): ... + def winfo_screendepth(self): ... + def winfo_screenheight(self): ... + def winfo_screenmmheight(self): ... + def winfo_screenmmwidth(self): ... + def winfo_screenvisual(self): ... + def winfo_screenwidth(self): ... + def winfo_server(self): ... + def winfo_toplevel(self): ... + def winfo_viewable(self): ... + def winfo_visual(self): ... + def winfo_visualid(self): ... + def winfo_visualsavailable(self, includeids: int = ...): ... + def winfo_vrootheight(self): ... + def winfo_vrootwidth(self): ... + def winfo_vrootx(self): ... + def winfo_vrooty(self): ... + def winfo_width(self): ... + def winfo_x(self): ... + def winfo_y(self): ... + def update(self): ... + def update_idletasks(self): ... + def bindtags(self, tagList: Optional[Any] = ...): ... + def bind(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind(self, sequence, funcid: Optional[Any] = ...): ... + def bind_all(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind_all(self, sequence): ... + def bind_class(self, className, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind_class(self, className, sequence): ... + def mainloop(self, n: int = ...): ... + def quit(self): ... + def nametowidget(self, name): ... + register: Any + def configure(self, cnf: Optional[Any] = ..., **kw): ... + config: Any + def cget(self, key): ... + __getitem__: Any + def __setitem__(self, key, value): ... + def keys(self): ... + def pack_propagate(self, flag=...): ... + propagate: Any + def pack_slaves(self): ... + slaves: Any + def place_slaves(self): ... + def grid_anchor(self, anchor: Optional[Any] = ...): ... + anchor: Any + def grid_bbox(self, column: Optional[Any] = ..., row: Optional[Any] = ..., col2: Optional[Any] = ..., + row2: Optional[Any] = ...): ... + bbox: Any + def grid_columnconfigure(self, index, cnf=..., **kw): ... + columnconfigure: Any + def grid_location(self, x, y): ... + def grid_propagate(self, flag=...): ... + def grid_rowconfigure(self, index, cnf=..., **kw): ... + rowconfigure: Any + def grid_size(self): ... + size: Any + def grid_slaves(self, row: Optional[Any] = ..., column: Optional[Any] = ...): ... + def event_add(self, virtual, *sequences): ... + def event_delete(self, virtual, *sequences): ... + def event_generate(self, sequence, **kw): ... + def event_info(self, virtual: Optional[Any] = ...): ... + def image_names(self): ... + def image_types(self): ... + +class CallWrapper: + func: Any + subst: Any + widget: Any + def __init__(self, func, subst, widget): ... + def __call__(self, *args): ... + +class XView: + def xview(self, *args): ... + def xview_moveto(self, fraction): ... + def xview_scroll(self, number, what): ... + +class YView: + def yview(self, *args): ... + def yview_moveto(self, fraction): ... + def yview_scroll(self, number, what): ... + +class Wm: + def wm_aspect(self, minNumer: Optional[Any] = ..., minDenom: Optional[Any] = ..., maxNumer: Optional[Any] = ..., + maxDenom: Optional[Any] = ...): ... + aspect: Any + def wm_attributes(self, *args): ... + attributes: Any + def wm_client(self, name: Optional[Any] = ...): ... + client: Any + def wm_colormapwindows(self, *wlist): ... + colormapwindows: Any + def wm_command(self, value: Optional[Any] = ...): ... + command: Any + def wm_deiconify(self): ... + deiconify: Any + def wm_focusmodel(self, model: Optional[Any] = ...): ... + focusmodel: Any + def wm_forget(self, window): ... + forget: Any + def wm_frame(self): ... + frame: Any + def wm_geometry(self, newGeometry: Optional[Any] = ...): ... + geometry: Any + def wm_grid(self, baseWidth: Optional[Any] = ..., baseHeight: Optional[Any] = ..., widthInc: Optional[Any] = ..., + heightInc: Optional[Any] = ...): ... + grid: Any + def wm_group(self, pathName: Optional[Any] = ...): ... + group: Any + def wm_iconbitmap(self, bitmap: Optional[Any] = ..., default: Optional[Any] = ...): ... + iconbitmap: Any + def wm_iconify(self): ... + iconify: Any + def wm_iconmask(self, bitmap: Optional[Any] = ...): ... + iconmask: Any + def wm_iconname(self, newName: Optional[Any] = ...): ... + iconname: Any + def wm_iconphoto(self, default: bool = ..., *args): ... + iconphoto: Any + def wm_iconposition(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... + iconposition: Any + def wm_iconwindow(self, pathName: Optional[Any] = ...): ... + iconwindow: Any + def wm_manage(self, widget): ... + manage: Any + def wm_maxsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + maxsize: Any + def wm_minsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + minsize: Any + def wm_overrideredirect(self, boolean: Optional[Any] = ...): ... + overrideredirect: Any + def wm_positionfrom(self, who: Optional[Any] = ...): ... + positionfrom: Any + def wm_protocol(self, name: Optional[Any] = ..., func: Optional[Any] = ...): ... + protocol: Any + def wm_resizable(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + resizable: Any + def wm_sizefrom(self, who: Optional[Any] = ...): ... + sizefrom: Any + def wm_state(self, newstate: Optional[Any] = ...): ... + state: Any + def wm_title(self, string: Optional[Any] = ...): ... + title: Any + def wm_transient(self, master: Optional[Any] = ...): ... + transient: Any + def wm_withdraw(self): ... + withdraw: Any + +class Tk(Misc, Wm): + master: Optional[Any] + children: Dict[str, Any] + tk: Any + def __init__(self, screenName: Optional[str] = ..., baseName: Optional[str] = ..., className: str = ..., useTk: bool = ..., + sync: bool = ..., use: Optional[str] = ...) -> None: ... + def loadtk(self) -> None: ... + def destroy(self) -> None: ... + def readprofile(self, baseName: str, className: str) -> None: ... + report_callback_exception: Callable[[Type[BaseException], BaseException, TracebackType], Any] + def __getattr__(self, attr: str) -> Any: ... + +def Tcl(screenName: Optional[Any] = ..., baseName: Optional[Any] = ..., className: str = ..., useTk: bool = ...): ... + +class Pack: + def pack_configure(self, cnf=..., **kw): ... + pack: Any + def pack_forget(self): ... + forget: Any + def pack_info(self): ... + info: Any + propagate: Any + slaves: Any + +class Place: + def place_configure(self, cnf=..., **kw): ... + place: Any + def place_forget(self): ... + forget: Any + def place_info(self): ... + info: Any + slaves: Any + +class Grid: + def grid_configure(self, cnf=..., **kw): ... + grid: Any + bbox: Any + columnconfigure: Any + def grid_forget(self): ... + forget: Any + def grid_remove(self): ... + def grid_info(self): ... + info: Any + location: Any + propagate: Any + rowconfigure: Any + size: Any + slaves: Any + +class BaseWidget(Misc): + widgetName: Any + def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ... + def destroy(self): ... + +class Widget(BaseWidget, Pack, Place, Grid): ... + +class Toplevel(BaseWidget, Wm): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Button(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def flash(self): ... + def invoke(self): ... + +class Canvas(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def addtag(self, *args): ... + def addtag_above(self, newtag, tagOrId): ... + def addtag_all(self, newtag): ... + def addtag_below(self, newtag, tagOrId): ... + def addtag_closest(self, newtag, x, y, halo: Optional[Any] = ..., start: Optional[Any] = ...): ... + def addtag_enclosed(self, newtag, x1, y1, x2, y2): ... + def addtag_overlapping(self, newtag, x1, y1, x2, y2): ... + def addtag_withtag(self, newtag, tagOrId): ... + def bbox(self, *args): ... + def tag_unbind(self, tagOrId, sequence, funcid: Optional[Any] = ...): ... + def tag_bind(self, tagOrId, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def canvasx(self, screenx, gridspacing: Optional[Any] = ...): ... + def canvasy(self, screeny, gridspacing: Optional[Any] = ...): ... + def coords(self, *args): ... + def create_arc(self, *args, **kw): ... + def create_bitmap(self, *args, **kw): ... + def create_image(self, *args, **kw): ... + def create_line(self, *args, **kw): ... + def create_oval(self, *args, **kw): ... + def create_polygon(self, *args, **kw): ... + def create_rectangle(self, *args, **kw): ... + def create_text(self, *args, **kw): ... + def create_window(self, *args, **kw): ... + def dchars(self, *args): ... + def delete(self, *args): ... + def dtag(self, *args): ... + def find(self, *args): ... + def find_above(self, tagOrId): ... + def find_all(self): ... + def find_below(self, tagOrId): ... + def find_closest(self, x, y, halo: Optional[Any] = ..., start: Optional[Any] = ...): ... + def find_enclosed(self, x1, y1, x2, y2): ... + def find_overlapping(self, x1, y1, x2, y2): ... + def find_withtag(self, tagOrId): ... + def focus(self, *args): ... + def gettags(self, *args): ... + def icursor(self, *args): ... + def index(self, *args): ... + def insert(self, *args): ... + def itemcget(self, tagOrId, option): ... + def itemconfigure(self, tagOrId, cnf: Optional[Any] = ..., **kw): ... + itemconfig: Any + def tag_lower(self, *args): ... + lower: Any + def move(self, *args): ... + if sys.version_info >= (3, 8): + def moveto(self, tagOrId: Union[int, str], x: str = ..., y: str = ...) -> None: ... + def postscript(self, cnf=..., **kw): ... + def tag_raise(self, *args): ... + lift: Any + def scale(self, *args): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y, gain: int = ...): ... + def select_adjust(self, tagOrId, index): ... + def select_clear(self): ... + def select_from(self, tagOrId, index): ... + def select_item(self): ... + def select_to(self, tagOrId, index): ... + def type(self, tagOrId): ... + +class Checkbutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def deselect(self): ... + def flash(self): ... + def invoke(self): ... + def select(self): ... + def toggle(self): ... + +class Entry(Widget, XView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self): ... + def icursor(self, index): ... + def index(self, index): ... + def insert(self, index, string): ... + def scan_mark(self, x): ... + def scan_dragto(self, x): ... + def selection_adjust(self, index): ... + select_adjust: Any + def selection_clear(self): ... + select_clear: Any + def selection_from(self, index): ... + select_from: Any + def selection_present(self): ... + select_present: Any + def selection_range(self, start, end): ... + select_range: Any + def selection_to(self, index): ... + select_to: Any + +class Frame(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Label(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Listbox(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def activate(self, index): ... + def bbox(self, index): ... + def curselection(self): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self, first, last: Optional[Any] = ...): ... + def index(self, index): ... + def insert(self, index, *elements): ... + def nearest(self, y): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y): ... + def see(self, index): ... + def selection_anchor(self, index): ... + select_anchor: Any + def selection_clear(self, first, last: Optional[Any] = ...): ... # type: ignore + select_clear: Any + def selection_includes(self, index): ... + select_includes: Any + def selection_set(self, first, last: Optional[Any] = ...): ... + select_set: Any + def size(self): ... + def itemcget(self, index, option): ... + def itemconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... + itemconfig: Any + +class Menu(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def tk_popup(self, x, y, entry: str = ...): ... + if sys.version_info < (3, 6): + def tk_bindForTraversal(self): ... + def activate(self, index): ... + def add(self, itemType, cnf=..., **kw): ... + def add_cascade(self, cnf=..., **kw): ... + def add_checkbutton(self, cnf=..., **kw): ... + def add_command(self, cnf=..., **kw): ... + def add_radiobutton(self, cnf=..., **kw): ... + def add_separator(self, cnf=..., **kw): ... + def insert(self, index, itemType, cnf=..., **kw): ... + def insert_cascade(self, index, cnf=..., **kw): ... + def insert_checkbutton(self, index, cnf=..., **kw): ... + def insert_command(self, index, cnf=..., **kw): ... + def insert_radiobutton(self, index, cnf=..., **kw): ... + def insert_separator(self, index, cnf=..., **kw): ... + def delete(self, index1, index2: Optional[Any] = ...): ... + def entrycget(self, index, option): ... + def entryconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... + entryconfig: Any + def index(self, index): ... + def invoke(self, index): ... + def post(self, x, y): ... + def type(self, index): ... + def unpost(self): ... + def xposition(self, index): ... + def yposition(self, index): ... + +class Menubutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Message(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Radiobutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def deselect(self): ... + def flash(self): ... + def invoke(self): ... + def select(self): ... + +class Scale(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def get(self): ... + def set(self, value): ... + def coords(self, value: Optional[Any] = ...): ... + def identify(self, x, y): ... + +class Scrollbar(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def activate(self, index: Optional[Any] = ...): ... + def delta(self, deltax, deltay): ... + def fraction(self, x, y): ... + def identify(self, x, y): ... + def get(self): ... + def set(self, first, last): ... + +class Text(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def bbox(self, index): ... + def compare(self, index1, op, index2): ... + def count(self, index1, index2, *args): ... + def debug(self, boolean: Optional[Any] = ...): ... + def delete(self, index1, index2: Optional[Any] = ...): ... + def dlineinfo(self, index): ... + def dump(self, index1, index2: Optional[Any] = ..., command: Optional[Any] = ..., **kw): ... + def edit(self, *args): ... + def edit_modified(self, arg: Optional[Any] = ...): ... + def edit_redo(self): ... + def edit_reset(self): ... + def edit_separator(self): ... + def edit_undo(self): ... + def get(self, index1, index2: Optional[Any] = ...): ... + def image_cget(self, index, option): ... + def image_configure(self, index, cnf: Optional[Any] = ..., **kw): ... + def image_create(self, index, cnf=..., **kw): ... + def image_names(self): ... + def index(self, index): ... + def insert(self, index, chars, *args): ... + def mark_gravity(self, markName, direction: Optional[Any] = ...): ... + def mark_names(self): ... + def mark_set(self, markName, index): ... + def mark_unset(self, *markNames): ... + def mark_next(self, index): ... + def mark_previous(self, index): ... + def peer_create(self, newPathName, cnf=..., **kw): ... + def peer_names(self): ... + def replace(self, index1, index2, chars, *args): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y): ... + def search(self, pattern, index, stopindex: Optional[Any] = ..., forwards: Optional[Any] = ..., + backwards: Optional[Any] = ..., exact: Optional[Any] = ..., regexp: Optional[Any] = ..., + nocase: Optional[Any] = ..., count: Optional[Any] = ..., elide: Optional[Any] = ...): ... + def see(self, index): ... + def tag_add(self, tagName, index1, *args): ... + def tag_unbind(self, tagName, sequence, funcid: Optional[Any] = ...): ... + def tag_bind(self, tagName, sequence, func, add: Optional[Any] = ...): ... + def tag_cget(self, tagName, option): ... + def tag_configure(self, tagName, cnf: Optional[Any] = ..., **kw): ... + tag_config: Any + def tag_delete(self, *tagNames): ... + def tag_lower(self, tagName, belowThis: Optional[Any] = ...): ... + def tag_names(self, index: Optional[Any] = ...): ... + def tag_nextrange(self, tagName, index1, index2: Optional[Any] = ...): ... + def tag_prevrange(self, tagName, index1, index2: Optional[Any] = ...): ... + def tag_raise(self, tagName, aboveThis: Optional[Any] = ...): ... + def tag_ranges(self, tagName): ... + def tag_remove(self, tagName, index1, index2: Optional[Any] = ...): ... + def window_cget(self, index, option): ... + def window_configure(self, index, cnf: Optional[Any] = ..., **kw): ... + window_config: Any + def window_create(self, index, cnf=..., **kw): ... + def window_names(self): ... + def yview_pickplace(self, *what): ... + +class _setit: + def __init__(self, var, value, callback: Optional[Any] = ...): ... + def __call__(self, *args): ... + +class OptionMenu(Menubutton): + widgetName: Any + menuname: Any + def __init__(self, master, variable, value, *values, **kwargs): ... + def __getitem__(self, name): ... + def destroy(self): ... + +class Image: + name: Any + tk: Any + def __init__(self, imgtype, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + def __del__(self): ... + def __setitem__(self, key, value): ... + def __getitem__(self, key): ... + def configure(self, **kw): ... + config: Any + def height(self): ... + def type(self): ... + def width(self): ... + +class PhotoImage(Image): + def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + def blank(self): ... + def cget(self, option): ... + def __getitem__(self, key): ... + def copy(self): ... + def zoom(self, x, y: str = ...): ... + def subsample(self, x, y: str = ...): ... + def get(self, x, y): ... + def put(self, data, to: Optional[Any] = ...): ... + def write(self, filename, format: Optional[Any] = ..., from_coords: Optional[Any] = ...): ... + 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: ... + +class BitmapImage(Image): + def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + +def image_names(): ... +def image_types(): ... + +class Spinbox(Widget, XView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def bbox(self, index): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self): ... + def icursor(self, index): ... + def identify(self, x, y): ... + def index(self, index): ... + def insert(self, index, s): ... + def invoke(self, element): ... + def scan(self, *args): ... + def scan_mark(self, x): ... + def scan_dragto(self, x): ... + def selection(self, *args: Any) -> Tuple[int, ...]: ... + def selection_adjust(self, index): ... + def selection_clear(self): ... + def selection_element(self, element: Optional[Any] = ...): ... + if sys.version_info >= (3, 8): + def selection_from(self, index: int) -> None: ... + def selection_present(self) -> None: ... + def selection_range(self, start: int, end: int) -> None: ... + def selection_to(self, index: int) -> None: ... + +class LabelFrame(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class PanedWindow(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def add(self, child, **kw): ... + def remove(self, child): ... + forget: Any + def identify(self, x, y): ... + def proxy(self, *args): ... + def proxy_coord(self): ... + def proxy_forget(self): ... + def proxy_place(self, x, y): ... + def sash(self, *args): ... + def sash_coord(self, index): ... + def sash_mark(self, index): ... + def sash_place(self, index, x, y): ... + def panecget(self, child, option): ... + def paneconfigure(self, tagOrId, cnf: Optional[Any] = ..., **kw): ... + paneconfig: Any + def panes(self): ... diff --git a/mypy/stdlib/tkinter/commondialog.pyi b/mypy/stdlib/tkinter/commondialog.pyi new file mode 100644 index 000000000000..d6a8a0d1f5a6 --- /dev/null +++ b/mypy/stdlib/tkinter/commondialog.pyi @@ -0,0 +1,8 @@ +from typing import Any, Mapping, Optional + +class Dialog: + command: Optional[Any] = ... + master: Optional[Any] = ... + options: Mapping[str, Any] = ... + def __init__(self, master: Optional[Any] = ..., **options) -> None: ... + def show(self, **options) -> Any: ... diff --git a/mypy/stdlib/tkinter/constants.pyi b/mypy/stdlib/tkinter/constants.pyi new file mode 100644 index 000000000000..e21a93e69cea --- /dev/null +++ b/mypy/stdlib/tkinter/constants.pyi @@ -0,0 +1,79 @@ +from typing import Any + +NO: Any +YES: Any +TRUE: Any +FALSE: Any +ON: Any +OFF: Any +N: Any +S: Any +W: Any +E: Any +NW: Any +SW: Any +NE: Any +SE: Any +NS: Any +EW: Any +NSEW: Any +CENTER: Any +NONE: Any +X: Any +Y: Any +BOTH: Any +LEFT: Any +TOP: Any +RIGHT: Any +BOTTOM: Any +RAISED: Any +SUNKEN: Any +FLAT: Any +RIDGE: Any +GROOVE: Any +SOLID: Any +HORIZONTAL: Any +VERTICAL: Any +NUMERIC: Any +CHAR: Any +WORD: Any +BASELINE: Any +INSIDE: Any +OUTSIDE: Any +SEL: Any +SEL_FIRST: Any +SEL_LAST: Any +END: Any +INSERT: Any +CURRENT: Any +ANCHOR: Any +ALL: Any +NORMAL: Any +DISABLED: Any +ACTIVE: Any +HIDDEN: Any +CASCADE: Any +CHECKBUTTON: Any +COMMAND: Any +RADIOBUTTON: Any +SEPARATOR: Any +SINGLE: Any +BROWSE: Any +MULTIPLE: Any +EXTENDED: Any +DOTBOX: Any +UNDERLINE: Any +PIESLICE: Any +CHORD: Any +ARC: Any +FIRST: Any +LAST: Any +BUTT: Any +PROJECTING: Any +ROUND: Any +BEVEL: Any +MITER: Any +MOVETO: Any +SCROLL: Any +UNITS: Any +PAGES: Any diff --git a/mypy/stdlib/tkinter/dialog.pyi b/mypy/stdlib/tkinter/dialog.pyi new file mode 100644 index 000000000000..3136f21e663d --- /dev/null +++ b/mypy/stdlib/tkinter/dialog.pyi @@ -0,0 +1,10 @@ +from typing import Any, Mapping, Optional +from tkinter import Widget + +DIALOG_ICON: str + +class Dialog(Widget): + widgetName: str = ... + num: int = ... + def __init__(self, master: Optional[Any] = ..., cnf: Mapping[str, Any] = ..., **kw) -> None: ... + def destroy(self) -> None: ... diff --git a/mypy/stdlib/tkinter/filedialog.pyi b/mypy/stdlib/tkinter/filedialog.pyi new file mode 100644 index 000000000000..6d5f165134b0 --- /dev/null +++ b/mypy/stdlib/tkinter/filedialog.pyi @@ -0,0 +1,65 @@ +from typing import Any, Dict, Optional, Tuple +from tkinter import Button, commondialog, Entry, Frame, Listbox, Scrollbar, Toplevel + +dialogstates: Dict[Any, Tuple[Any, Any]] + +class FileDialog: + title: str = ... + master: Any = ... + directory: Optional[Any] = ... + top: Toplevel = ... + botframe: Frame = ... + selection: Entry = ... + filter: Entry = ... + midframe: Entry = ... + filesbar: Scrollbar = ... + files: Listbox = ... + dirsbar: Scrollbar = ... + dirs: Listbox = ... + ok_button: Button = ... + filter_button: Button = ... + cancel_button: Button = ... + def __init__(self, master, title: Optional[Any] = ...) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either + how: Optional[Any] = ... + def go(self, dir_or_file: Any = ..., pattern: str = ..., default: str = ..., key: Optional[Any] = ...): ... + def quit(self, how: Optional[Any] = ...) -> None: ... + def dirs_double_event(self, event) -> None: ... + def dirs_select_event(self, event) -> None: ... + def files_double_event(self, event) -> None: ... + def files_select_event(self, event) -> None: ... + def ok_event(self, event) -> None: ... + def ok_command(self) -> None: ... + def filter_command(self, event: Optional[Any] = ...) -> None: ... + def get_filter(self): ... + def get_selection(self): ... + def cancel_command(self, event: Optional[Any] = ...) -> None: ... + def set_filter(self, dir, pat) -> None: ... + def set_selection(self, file) -> None: ... + +class LoadFileDialog(FileDialog): + title: str = ... + def ok_command(self) -> None: ... + +class SaveFileDialog(FileDialog): + title: str = ... + def ok_command(self): ... + +class _Dialog(commondialog.Dialog): ... + +class Open(_Dialog): + command: str = ... + +class SaveAs(_Dialog): + command: str = ... + +class Directory(commondialog.Dialog): + command: str = ... + +def askopenfilename(**options): ... +def asksaveasfilename(**options): ... +def askopenfilenames(**options): ... +def askopenfile(mode: str = ..., **options): ... +def askopenfiles(mode: str = ..., **options): ... +def asksaveasfile(mode: str = ..., **options): ... +def askdirectory(**options): ... +def test() -> None: ... diff --git a/mypy/stdlib/tkinter/messagebox.pyi b/mypy/stdlib/tkinter/messagebox.pyi new file mode 100644 index 000000000000..b44e66081fab --- /dev/null +++ b/mypy/stdlib/tkinter/messagebox.pyi @@ -0,0 +1,31 @@ +from tkinter.commondialog import Dialog +from typing import Any, Optional + +ERROR: str +INFO: str +QUESTION: str +WARNING: str +ABORTRETRYIGNORE: str +OK: str +OKCANCEL: str +RETRYCANCEL: str +YESNO: str +YESNOCANCEL: str +ABORT: str +RETRY: str +IGNORE: str +CANCEL: str +YES: str +NO: str + +class Message(Dialog): + command: str = ... + +def showinfo(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def showwarning(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def showerror(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def askquestion(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def askokcancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... +def askyesno(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... +def askyesnocancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> Optional[bool]: ... +def askretrycancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... diff --git a/mypy/stdlib/tkinter/ttk.pyi b/mypy/stdlib/tkinter/ttk.pyi new file mode 100644 index 000000000000..755fb25214dd --- /dev/null +++ b/mypy/stdlib/tkinter/ttk.pyi @@ -0,0 +1,163 @@ +import sys +from typing import Any, List, Optional +import tkinter + +def tclobjs_to_py(adict): ... +def setup_master(master: Optional[Any] = ...): ... + +class Style: + master: Any + tk: Any + def __init__(self, master: Optional[Any] = ...): ... + def configure(self, style, query_opt: Optional[Any] = ..., **kw): ... + def map(self, style, query_opt: Optional[Any] = ..., **kw): ... + def lookup(self, style, option, state: Optional[Any] = ..., default: Optional[Any] = ...): ... + def layout(self, style, layoutspec: Optional[Any] = ...): ... + def element_create(self, elementname, etype, *args, **kw): ... + def element_names(self): ... + def element_options(self, elementname): ... + def theme_create(self, themename, parent: Optional[Any] = ..., settings: Optional[Any] = ...): ... + def theme_settings(self, themename, settings): ... + def theme_names(self): ... + def theme_use(self, themename: Optional[Any] = ...): ... + +class Widget(tkinter.Widget): + def __init__(self, master, widgetname, kw: Optional[Any] = ...): ... + def identify(self, x, y): ... + def instate(self, statespec, callback: Optional[Any] = ..., *args, **kw): ... + def state(self, statespec: Optional[Any] = ...): ... + +class Button(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Checkbutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Entry(Widget, tkinter.Entry): + def __init__(self, master: Optional[Any] = ..., widget: Optional[Any] = ..., **kw): ... + def bbox(self, index): ... + def identify(self, x, y): ... + def validate(self): ... + +class Combobox(Entry): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def current(self, newindex: Optional[Any] = ...): ... + def set(self, value): ... + +class Frame(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Label(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Labelframe(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +LabelFrame: Any + +class Menubutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Notebook(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def add(self, child, **kw): ... + def forget(self, tab_id): ... + def hide(self, tab_id): ... + def identify(self, x, y): ... + def index(self, tab_id): ... + def insert(self, pos, child, **kw): ... + def select(self, tab_id: Optional[Any] = ...): ... + def tab(self, tab_id, option: Optional[Any] = ..., **kw): ... + def tabs(self): ... + def enable_traversal(self): ... + +class Panedwindow(Widget, tkinter.PanedWindow): + def __init__(self, master: Optional[Any] = ..., **kw): ... + forget: Any + def insert(self, pos, child, **kw): ... + def pane(self, pane, option: Optional[Any] = ..., **kw): ... + def sashpos(self, index, newpos: Optional[Any] = ...): ... + +PanedWindow: Any + +class Progressbar(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def start(self, interval: Optional[Any] = ...): ... + def step(self, amount: Optional[Any] = ...): ... + def stop(self): ... + +class Radiobutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Scale(Widget, tkinter.Scale): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def configure(self, cnf: Optional[Any] = ..., **kw): ... + def get(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... + +class Scrollbar(Widget, tkinter.Scrollbar): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Separator(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Sizegrip(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +if sys.version_info >= (3, 7): + class Spinbox(Entry): + def __init__(self, master: Any = ..., **kw: Any) -> None: ... + def set(self, value: Any) -> None: ... + +class Treeview(Widget, tkinter.XView, tkinter.YView): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def bbox(self, item, column: Optional[Any] = ...): ... + def get_children(self, item: Optional[Any] = ...): ... + def set_children(self, item, *newchildren): ... + def column(self, column, option: Optional[Any] = ..., **kw): ... + def delete(self, *items): ... + def detach(self, *items): ... + def exists(self, item): ... + def focus(self, item: Optional[Any] = ...): ... + def heading(self, column, option: Optional[Any] = ..., **kw): ... + def identify(self, component, x, y): ... + def identify_row(self, y): ... + def identify_column(self, x): ... + def identify_region(self, x, y): ... + def identify_element(self, x, y): ... + def index(self, item): ... + def insert(self, parent, index, iid: Optional[Any] = ..., **kw): ... + def item(self, item, option: Optional[Any] = ..., **kw): ... + def move(self, item, parent, index): ... + reattach: Any + def next(self, item): ... + def parent(self, item): ... + def prev(self, item): ... + def see(self, item): ... + if sys.version_info >= (3, 8): + def selection(self) -> List[Any]: ... + else: + def selection(self, selop: Optional[Any] = ..., items: Optional[Any] = ...) -> List[Any]: ... + def selection_set(self, items): ... + def selection_add(self, items): ... + def selection_remove(self, items): ... + def selection_toggle(self, items): ... + def set(self, item, column: Optional[Any] = ..., value: Optional[Any] = ...): ... + def tag_bind(self, tagname, sequence: Optional[Any] = ..., callback: Optional[Any] = ...): ... + def tag_configure(self, tagname, option: Optional[Any] = ..., **kw): ... + def tag_has(self, tagname, item: Optional[Any] = ...): ... + +class LabeledScale(Frame): + label: Any + scale: Any + def __init__(self, master: Optional[Any] = ..., variable: Optional[Any] = ..., from_: int = ..., to: int = ..., **kw): ... + def destroy(self): ... + value: Any + +class OptionMenu(Menubutton): + def __init__(self, master, variable, default: Optional[Any] = ..., *values, **kwargs): ... + def __getitem__(self, item): ... + def set_menu(self, default: Optional[Any] = ..., *values): ... + def destroy(self): ... diff --git a/mypy/stdlib/token.pyi b/mypy/stdlib/token.pyi new file mode 100644 index 000000000000..33e1f80453a3 --- /dev/null +++ b/mypy/stdlib/token.pyi @@ -0,0 +1,84 @@ +import sys +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 +if sys.version_info < (3,): + 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 +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): + AWAIT: int + ASYNC: int +OP: int +ERRORTOKEN: int +N_TOKENS: int +NT_OFFSET: int +tok_name: Dict[int, str] +if sys.version_info >= (3, 7): + COMMENT: int + NL: int + ENCODING: int +if sys.version_info >= (3, 8): + TYPE_COMMENT: int + TYPE_IGNORE: int + COLONEQUAL: int + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/mypy/stdlib/tokenize.pyi b/mypy/stdlib/tokenize.pyi new file mode 100644 index 000000000000..d9b91fa77540 --- /dev/null +++ b/mypy/stdlib/tokenize.pyi @@ -0,0 +1,110 @@ +from typing import Any, Callable, Dict, Generator, Iterable, List, NamedTuple, Optional, Pattern, Union, Sequence, Set, TextIO, Tuple +from builtins import open as _builtin_open +import sys +from token import * # noqa: F403 + +if sys.version_info < (3, 7): + COMMENT: int + NL: int + ENCODING: int + +cookie_re: Pattern[str] +blank_re: Pattern[bytes] + +_Position = Tuple[int, int] + +class _TokenInfo(NamedTuple): + type: int + string: str + start: _Position + end: _Position + line: str + +class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... + +# Backwards compatible tokens can be sequences of a shorter length too +_Token = Union[TokenInfo, Sequence[Union[int, str, _Position]]] + +class TokenError(Exception): ... +class StopTokenizing(Exception): ... # undocumented + +class Untokenizer: + tokens: List[str] + prev_row: int + prev_col: int + encoding: Optional[str] + def __init__(self) -> None: ... + def add_whitespace(self, start: _Position) -> None: ... + def untokenize(self, iterable: Iterable[_Token]) -> str: ... + def compat(self, token: Sequence[Union[int, str]], iterable: Iterable[_Token]) -> None: ... + +# the docstring says "returns bytes" but is incorrect -- +# if the ENCODING token is missing, it skips the encode +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 + +if sys.version_info >= (3, 6): + from os import PathLike + def open(filename: Union[str, bytes, int, PathLike[Any]]) -> TextIO: ... +elif sys.version_info >= (3, 2): + def open(filename: Union[str, bytes, int]) -> TextIO: ... + +def group(*choices: str) -> str: ... # undocumented +def any(*choices: str) -> str: ... # undocumented +def maybe(*choices: str) -> str: ... # undocumented + +Whitespace: str # undocumented +Comment: str # undocumented +Ignore: str # undocumented +Name: str # undocumented + +Hexnumber: str # undocumented +Binnumber: str # undocumented +Octnumber: str # undocumented +Decnumber: str # undocumented +Intnumber: str # undocumented +Exponent: str # undocumented +Pointfloat: str # undocumented +Expfloat: str # undocumented +Floatnumber: str # undocumented +Imagnumber: str # undocumented +Number: str # undocumented + +def _all_string_prefixes() -> Set[str]: ... # undocumented + +StringPrefix: str # undocumented + +Single: str # undocumented +Double: str # undocumented +Single3: str # undocumented +Double3: str # undocumented +Triple: str # undocumented +String: str # undocumented + +if sys.version_info < (3, 7): + Operator: str # undocumented + Bracket: str # undocumented + +Special: str # undocumented +Funny: str # undocumented + +PlainToken: str # undocumented +Token: str # undocumented + +ContStr: str # undocumented +PseudoExtras: str # undocumented +PseudoToken: str # undocumented + +endpats: Dict[str, str] # undocumented +if sys.version_info < (3, 6): + single_quoted: Dict[str, str] # undocumented + triple_quoted: Dict[str, str] # undocumented +else: + single_quoted: Set[str] # undocumented + triple_quoted: Set[str] # undocumented + +tabsize: int # undocumented diff --git a/mypy/stdlib/trace.pyi b/mypy/stdlib/trace.pyi new file mode 100644 index 000000000000..cd90b966a9be --- /dev/null +++ b/mypy/stdlib/trace.pyi @@ -0,0 +1,27 @@ +from _typeshed import StrPath +import types +from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar, Union + +_T = TypeVar('_T') +_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] + +class CoverageResults: + 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) -> Tuple[str, Optional[str], str]: ... + 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/stdlib/traceback.pyi b/mypy/stdlib/traceback.pyi new file mode 100644 index 000000000000..8a507e68e965 --- /dev/null +++ b/mypy/stdlib/traceback.pyi @@ -0,0 +1,117 @@ +from typing import Any, Dict, Generator, IO, Iterator, List, Mapping, Optional, Tuple, Type, Iterable +from types import FrameType, TracebackType +import sys +from _typeshed import SupportsWrite + +_PT = Tuple[str, int, str, Optional[str]] + + +def print_tb(tb: Optional[TracebackType], limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... +if 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: ... + 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_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: ... + +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]: ... +def format_exception_only(etype: Optional[Type[BaseException]], + value: Optional[BaseException]) -> List[str]: ... +if sys.version_info >= (3,): + def format_exception(etype: Optional[Type[BaseException]], value: Optional[BaseException], + tb: Optional[TracebackType], limit: Optional[int] = ..., + chain: bool = ...) -> List[str]: ... + def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ... +else: + 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]: ... +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 + def __init__(self, exc_type: Type[BaseException], + exc_value: BaseException, exc_traceback: TracebackType, + *, limit: Optional[int] = ..., lookup_lines: bool = ..., + capture_locals: bool = ...) -> 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 __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/stdlib/tracemalloc.pyi b/mypy/stdlib/tracemalloc.pyi new file mode 100644 index 000000000000..de9d5150b47f --- /dev/null +++ b/mypy/stdlib/tracemalloc.pyi @@ -0,0 +1,89 @@ +# Stubs for tracemalloc (Python 3.4+) + +import sys +from typing import List, Optional, Sequence, Tuple, Union, overload +from _tracemalloc import * + +def get_object_traceback(obj: object) -> Optional[Traceback]: ... +def take_snapshot() -> Snapshot: ... + +if sys.version_info >= (3, 6): + class DomainFilter: + inclusive: bool + domain: int + def __init__(self, inclusive: bool, domain: int) -> None: ... + +class Filter: + if sys.version_info >= (3, 6): + domain: Optional[int] + inclusive: bool + lineno: Optional[int] + filename_pattern: str + all_frames: bool + if sys.version_info >= (3, 6): + def __init__(self, inclusive: bool, filename_pattern: str, lineno: Optional[int] = ..., all_frames: bool = ..., domain: Optional[int] = ...) -> None: ... + else: + def __init__(self, inclusive: bool, filename_pattern: str, lineno: Optional[int] = ..., all_frames: bool = ...) -> None: ... + +class Statistic: + count: int + size: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, count: int) -> None: ... + +class StatisticDiff: + count: int + count_diff: int + size: int + size_diff: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... + +_FrameTupleT = Tuple[str, int] + +class Frame: + filename: str + lineno: int + def __init__(self, frame: _FrameTupleT) -> None: ... + +if sys.version_info >= (3, 9): + _TraceTupleT = Union[Tuple[int, int, Sequence[_FrameTupleT], Optional[int]], Tuple[int, int, Sequence[_FrameTupleT]]] +else: + _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT]] + +class Trace: + domain: int + size: int + traceback: Traceback + def __init__(self, trace: _TraceTupleT) -> None: ... + +class Traceback(Sequence[Frame]): + if sys.version_info >= (3, 9): + total_nframe: Optional[int] + def __init__(self, frames: Sequence[_FrameTupleT], total_nframe: Optional[int] = ...) -> None: ... + else: + def __init__(self, frames: Sequence[_FrameTupleT]) -> None: ... + if sys.version_info >= (3, 7): + def format(self, limit: Optional[int] = ..., most_recent_first: bool = ...) -> List[str]: ... + else: + def format(self, limit: Optional[int] = ...) -> List[str]: ... + @overload + def __getitem__(self, i: int) -> Frame: ... + @overload + def __getitem__(self, s: slice) -> Sequence[Frame]: ... + def __len__(self) -> int: ... + + +class Snapshot: + def __init__(self, traces: Sequence[_TraceTupleT], traceback_limit: int) -> None: ... + def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = ...) -> List[StatisticDiff]: ... + def dump(self, filename: str) -> None: ... + if sys.version_info >= (3, 6): + def filter_traces(self, filters: Sequence[Union[DomainFilter, Filter]]) -> Snapshot: ... + else: + def filter_traces(self, filters: Sequence[Filter]) -> Snapshot: ... + @staticmethod + def load(filename: str) -> Snapshot: ... + def statistics(self, key_type: str, cumulative: bool = ...) -> List[Statistic]: ... + traceback_limit: int + traces: Sequence[Trace] diff --git a/mypy/stdlib/tty.pyi b/mypy/stdlib/tty.pyi new file mode 100644 index 000000000000..2bce1eca7dca --- /dev/null +++ b/mypy/stdlib/tty.pyi @@ -0,0 +1,17 @@ +# Stubs for tty (Python 3.6) + +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/stdlib/turtle.pyi b/mypy/stdlib/turtle.pyi new file mode 100644 index 000000000000..c3ee65193a40 --- /dev/null +++ b/mypy/stdlib/turtle.pyi @@ -0,0 +1,509 @@ +from typing import Tuple, overload, Optional, Union, Dict, Any, Sequence, TypeVar, List, Callable, Text +import sys +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 + +# 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: ... + 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]: ... + +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 + if sys.version_info >= (3,): + def onkeypress(self, fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... + onkeyrelease = onkey + +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: ... + 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]: ... + 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: ... + +def Screen() -> _Screen: ... + +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: ... +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]: ... + +# 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 +if sys.version_info >= (3,): + def onkeypress(fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... + onkeyrelease = onkey + +# 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: ... +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]: ... +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/stdlib/types.pyi b/mypy/stdlib/types.pyi new file mode 100644 index 000000000000..6c1bbfced061 --- /dev/null +++ b/mypy/stdlib/types.pyi @@ -0,0 +1,302 @@ +# Stubs for types +# Note, all classes "defined" here require special handling. + +# TODO parts of this should be conditional on version + +import sys +from typing import ( + Any, Awaitable, Callable, Dict, Generic, Iterator, Mapping, Optional, Tuple, TypeVar, + Union, overload, Type, Iterable +) + +# ModuleType is exported from this module, but for circular import +# reasons exists in its own stub file (with ModuleSpec and Loader). +from _importlib_modulespec import ModuleType as ModuleType # Exported + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_T_contra = TypeVar('_T_contra', contravariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +class _Cell: + cell_contents: Any + +class FunctionType: + __closure__: Optional[Tuple[_Cell, ...]] + __code__: CodeType + __defaults__: Optional[Tuple[Any, ...]] + __dict__: Dict[str, Any] + __globals__: Dict[str, Any] + __name__: str + __qualname__: str + __annotations__: Dict[str, Any] + __kwdefaults__: Dict[str, Any] + def __init__(self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ...) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... +LambdaType = FunctionType + +class CodeType: + """Create a code object. Not for the faint of heart.""" + co_argcount: int + if sys.version_info >= (3, 8): + co_posonlyargcount: int + co_kwonlyargcount: int + co_nlocals: int + co_stacksize: int + co_flags: int + co_code: bytes + co_consts: Tuple[Any, ...] + co_names: Tuple[str, ...] + co_varnames: Tuple[str, ...] + co_filename: str + co_name: str + co_firstlineno: int + co_lnotab: bytes + co_freevars: Tuple[str, ...] + co_cellvars: Tuple[str, ...] + if sys.version_info >= (3, 8): + def __init__( + self, + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: Tuple[Any, ...], + names: Tuple[str, ...], + varnames: Tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: bytes, + freevars: Tuple[str, ...] = ..., + cellvars: Tuple[str, ...] = ..., + ) -> None: ... + else: + def __init__( + self, + argcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: Tuple[Any, ...], + names: Tuple[str, ...], + varnames: Tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: bytes, + freevars: Tuple[str, ...] = ..., + cellvars: Tuple[str, ...] = ..., + ) -> None: ... + if sys.version_info >= (3, 8): + def replace( + self, + *, + co_argcount: int = ..., + co_posonlyargcount: int = ..., + co_kwonlyargcount: int = ..., + co_nlocals: int = ..., + co_stacksize: int = ..., + co_flags: int = ..., + co_firstlineno: int = ..., + co_code: bytes = ..., + co_consts: Tuple[Any, ...] = ..., + co_names: Tuple[str, ...] = ..., + co_varnames: Tuple[str, ...] = ..., + co_freevars: Tuple[str, ...] = ..., + co_cellvars: Tuple[str, ...] = ..., + co_filename: str = ..., + co_name: str = ..., + co_lnotab: bytes = ..., + ) -> CodeType: ... + +class MappingProxyType(Mapping[_KT, _VT], Generic[_KT, _VT]): + def __init__(self, mapping: Mapping[_KT, _VT]) -> None: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def copy(self) -> Mapping[_KT, _VT]: ... + +class SimpleNamespace: + def __init__(self, **kwargs: Any) -> None: ... + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class GeneratorType: + gi_code: CodeType + gi_frame: FrameType + gi_running: bool + gi_yieldfrom: Optional[GeneratorType] + def __iter__(self) -> GeneratorType: ... + def __next__(self) -> Any: ... + def close(self) -> None: ... + def send(self, __arg: Any) -> Any: ... + @overload + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + @overload + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + +if sys.version_info >= (3, 6): + class AsyncGeneratorType(Generic[_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 __anext__(self) -> Awaitable[_T_co]: ... + def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... + @overload + def athrow(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + @overload + def athrow(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + def aclose(self) -> Awaitable[None]: ... + +class CoroutineType: + cr_await: Optional[Any] + cr_code: CodeType + cr_frame: FrameType + cr_running: bool + def close(self) -> None: ... + def send(self, __arg: Any) -> Any: ... + @overload + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + @overload + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> Any: ... + +class _StaticFunctionType: + """Fictional type to correct the type of MethodType.__func__. + + FunctionType is a descriptor, so mypy follows the descriptor protocol and + converts MethodType.__func__ back to MethodType (the return type of + FunctionType.__get__). But this is actually a special case; MethodType is + implemented in C and its attribute access doesn't go through + __getattribute__. + + By wrapping FunctionType in _StaticFunctionType, we get the right result; + similar to wrapping a function in staticmethod() at runtime to prevent it + being bound as a method. + """ + def __get__(self, obj: Optional[object], type: Optional[type]) -> FunctionType: ... + +class MethodType: + __func__: _StaticFunctionType + __self__: object + __name__: str + __qualname__: str + def __init__(self, func: Callable[..., Any], obj: object) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +class BuiltinFunctionType: + __self__: Union[object, ModuleType] + __name__: str + __qualname__: str + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +BuiltinMethodType = BuiltinFunctionType + +if sys.version_info >= (3, 7): + class WrapperDescriptorType: + __name__: str + __qualname__: str + __objclass__: type + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Any, type: type = ...) -> Any: ... + + class MethodWrapperType: + __self__: object + __name__: str + __qualname__: str + __objclass__: type + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + + class MethodDescriptorType: + __name__: str + __qualname__: str + __objclass__: type + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Any, type: type = ...) -> Any: ... + + class ClassMethodDescriptorType: + __name__: str + __qualname__: str + __objclass__: type + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Any, type: type = ...) -> Any: ... + + +class TracebackType: + if sys.version_info >= (3, 7): + def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ... + tb_next: Optional[TracebackType] + else: + @property + def tb_next(self) -> Optional[TracebackType]: ... + # the rest are read-only even in 3.7 + @property + def tb_frame(self) -> FrameType: ... + @property + def tb_lasti(self) -> int: ... + @property + def tb_lineno(self) -> int: ... + +class FrameType: + f_back: Optional[FrameType] + f_builtins: Dict[str, Any] + f_code: CodeType + f_globals: Dict[str, Any] + f_lasti: int + f_lineno: int + f_locals: Dict[str, Any] + f_trace: Callable[[], None] + if sys.version_info >= (3, 7): + f_trace_lines: bool + f_trace_opcodes: bool + + def clear(self) -> None: ... + +class GetSetDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... +class MemberDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + +if sys.version_info >= (3, 7): + def new_class(name: str, bases: Iterable[object] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ...) -> type: ... + def resolve_bases(bases: Iterable[object]) -> Tuple[Any, ...]: ... +else: + def new_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ...) -> type: ... +def prepare_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ...) -> Tuple[type, Dict[str, Any], Dict[str, Any]]: ... + +# Actually a different type, but `property` is special and we want that too. +DynamicClassAttribute = property + +def coroutine(f: Callable[..., Any]) -> CoroutineType: ... + +if sys.version_info >= (3, 9): + class GenericAlias: + __origin__: type + __args__: Tuple[Any, ...] + __parameters__: Tuple[Any, ...] + def __init__(self, origin: type, args: Any): ... + def __getattr__(self, name: str) -> Any: ... # incomplete diff --git a/mypy/stdlib/typing.pyi b/mypy/stdlib/typing.pyi new file mode 100644 index 000000000000..fc8ccd763749 --- /dev/null +++ b/mypy/stdlib/typing.pyi @@ -0,0 +1,693 @@ +# Stubs for typing + +import sys +from abc import abstractmethod, ABCMeta +from types import CodeType, FrameType, TracebackType +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 + +# Definitions of special type checking related constructs. Their definitions +# are not used, so their value does not matter. + +overload = object() +Any = object() + +class TypeVar: + __name__: str + __bound__: Optional[Type[Any]] + __constraints__: Tuple[Type[Any], ...] + __covariant__: bool + __contravariant__: bool + def __init__(self, name: str, *constraints: Type[Any], bound: Optional[Type[Any]] = ..., covariant: bool = ..., contravariant: bool = ...) -> None: ... + +_promote = object() + +class _SpecialForm: + def __getitem__(self, typeargs: Any) -> object: ... + +Union: _SpecialForm = ... +Optional: _SpecialForm = ... +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +# Protocol is only present in 3.8 and later, but mypy needs it unconditionally +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... +if sys.version_info >= (3, 8): + Final: _SpecialForm = ... + _F = TypeVar('_F', bound=Callable[..., Any]) + def final(f: _F) -> _F: ... + Literal: _SpecialForm = ... + # TypedDict is a (non-subscriptable) special form. + TypedDict: object + +if sys.version_info < (3, 7): + class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# These type variables are used by the container types. +_T = TypeVar('_T') +_S = TypeVar('_S') +_KT = TypeVar('_KT') # Key type. +_VT = TypeVar('_VT') # Value type. +_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. +_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. +_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. +_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. +_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. +_TC = TypeVar('_TC', bound=Type[object]) +_C = TypeVar("_C", bound=Callable[..., Any]) + +no_type_check = object() +def no_type_check_decorator(decorator: _C) -> _C: ... + +# Type aliases and type constructors + +class _Alias: + # Class for defining generic aliases for library types. + def __getitem__(self, typeargs: Any) -> Any: ... + +List = _Alias() +Dict = _Alias() +DefaultDict = _Alias() +Set = _Alias() +FrozenSet = _Alias() +Counter = _Alias() +Deque = _Alias() +ChainMap = _Alias() + +if sys.version_info >= (3, 7): + OrderedDict = _Alias() + +if sys.version_info >= (3, 9): + Annotated: _SpecialForm = ... + +# Predefined type variables. +AnyStr = TypeVar('AnyStr', str, bytes) + +# Abstract base classes. + +def runtime_checkable(cls: _TC) -> _TC: ... + +@runtime_checkable +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime_checkable +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime_checkable +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime_checkable +class SupportsBytes(Protocol, metaclass=ABCMeta): + @abstractmethod + def __bytes__(self) -> bytes: ... + +if sys.version_info >= (3, 8): + @runtime_checkable + class SupportsIndex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __index__(self) -> int: ... + +@runtime_checkable +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime_checkable +class SupportsRound(Protocol[_T_co]): + @overload + @abstractmethod + def __round__(self) -> int: ... + @overload + @abstractmethod + def __round__(self, ndigits: int) -> _T_co: ... + +@runtime_checkable +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime_checkable +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime_checkable +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def __next__(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def __next__(self) -> _T_co: ... + + @abstractmethod + def send(self, __value: _T_contra) -> _T_co: ... + + @overload + @abstractmethod + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + @overload + @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + + @abstractmethod + def close(self) -> None: ... + + @abstractmethod + def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ... + + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + @property + def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ... + +@runtime_checkable +class Awaitable(Protocol[_T_co]): + @abstractmethod + def __await__(self) -> Generator[Any, None, _T_co]: ... + +class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): + @property + def cr_await(self) -> Optional[Any]: ... + @property + def cr_code(self) -> CodeType: ... + @property + def cr_frame(self) -> FrameType: ... + @property + def cr_running(self) -> bool: ... + + @abstractmethod + def send(self, __value: _T_contra) -> _T_co: ... + + @overload + @abstractmethod + def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + @overload + @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> _T_co: ... + + @abstractmethod + def close(self) -> None: ... + + +# NOTE: This type does not exist in typing.py or PEP 484. +# The parameters correspond to Generator, but the 4th is the original type. +class AwaitableGenerator(Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], + Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta): ... + +@runtime_checkable +class AsyncIterable(Protocol[_T_co]): + @abstractmethod + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +@runtime_checkable +class AsyncIterator(AsyncIterable[_T_co], + Protocol[_T_co]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +if sys.version_info >= (3, 6): + class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + + @abstractmethod + def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... + + @overload + @abstractmethod + def athrow(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., + __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + @overload + @abstractmethod + def athrow(self, __typ: BaseException, __val: None = ..., + __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + + @abstractmethod + def aclose(self) -> Awaitable[None]: ... + + @abstractmethod + def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... + + @property + def ag_await(self) -> Any: ... + @property + def ag_code(self) -> CodeType: ... + @property + def ag_frame(self) -> FrameType: ... + @property + def ag_running(self) -> bool: ... + +@runtime_checkable +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, __x: object) -> bool: ... + + +if sys.version_info >= (3, 6): + @runtime_checkable + class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + + _Collection = Collection +else: + @runtime_checkable + class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + def index(self, x: Any, start: int = ..., end: int = ...) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def clear(self) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(_Collection[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView(Sized): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __and__(self, o: Iterable[Any]) -> Set[Tuple[_KT_co, _VT_co]]: ... + def __rand__(self, o: Iterable[_T]) -> Set[_T]: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + def __or__(self, o: Iterable[_T]) -> Set[Union[Tuple[_KT_co, _VT_co], _T]]: ... + def __ror__(self, o: Iterable[_T]) -> Set[Union[Tuple[_KT_co, _VT_co], _T]]: ... + def __sub__(self, o: Iterable[Any]) -> Set[Tuple[_KT_co, _VT_co]]: ... + def __rsub__(self, o: Iterable[_T]) -> Set[_T]: ... + def __xor__(self, o: Iterable[_T]) -> Set[Union[Tuple[_KT_co, _VT_co], _T]]: ... + def __rxor__(self, o: Iterable[_T]) -> Set[Union[Tuple[_KT_co, _VT_co], _T]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __and__(self, o: Iterable[Any]) -> Set[_KT_co]: ... + def __rand__(self, o: Iterable[_T]) -> Set[_T]: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[_KT_co]: ... + def __or__(self, o: Iterable[_T]) -> Set[Union[_KT_co, _T]]: ... + def __ror__(self, o: Iterable[_T]) -> Set[Union[_KT_co, _T]]: ... + def __sub__(self, o: Iterable[Any]) -> Set[_KT_co]: ... + def __rsub__(self, o: Iterable[_T]) -> Set[_T]: ... + def __xor__(self, o: Iterable[_T]) -> Set[Union[_KT_co, _T]]: ... + def __rxor__(self, o: Iterable[_T]) -> Set[Union[_KT_co, _T]]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + if sys.version_info >= (3, 8): + def __reversed__(self) -> Iterator[_VT_co]: ... + +@runtime_checkable +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__(self, __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType]) -> Optional[bool]: ... + +@runtime_checkable +class AsyncContextManager(Protocol[_T_co]): + def __aenter__(self) -> Awaitable[_T_co]: ... + def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> Awaitable[Optional[bool]]: ... + +class Mapping(_Collection[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: + ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def items(self) -> AbstractSet[Tuple[_KT, _VT_co]]: ... + def keys(self) -> AbstractSet[_KT]: ... + def values(self) -> ValuesView[_VT_co]: ... + def __contains__(self, o: object) -> bool: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + # 'update' used to take a Union, but using overloading is better. + # The second overloaded type here is a bit too general, because + # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], + # but will always have the behavior of the first overloaded type + # at runtime, leading to keys of a mix of types _KT and Tuple[_KT, _VT]. + # We don't currently have any way of forcing all Mappings to use + # the first overload, but by using overloading rather than a Union, + # mypy will commit to using the first overload when the argument is + # known to be a Mapping with unknown type parameters, which is closer + # to the behavior we want. See mypy issue #1430. + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = str + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + + @abstractmethod + def __next__(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + +class BinaryIO(IO[bytes]): + # TODO readinto + # TODO read1? + # TODO peek? + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[str]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> int: ... # int on PyPy, bool on CPython + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos: int + endpos: int + lastindex: Optional[int] + lastgroup: Optional[AnyStr] + string: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. + re: Pattern[AnyStr] + + def expand(self, template: AnyStr) -> AnyStr: ... + + # TODO: The return for a group may be None, except if __group is 0 or not given. + @overload + def group(self, __group: Union[str, int] = ...) -> AnyStr: ... + @overload + def group( + self, + __group1: Union[str, int], + __group2: Union[str, int], + *groups: Union[str, int], + ) -> Tuple[AnyStr, ...]: ... + + def groups(self, default: AnyStr = ...) -> Sequence[AnyStr]: ... + def groupdict(self, default: AnyStr = ...) -> dict[str, AnyStr]: ... + def start(self, __group: Union[int, str] = ...) -> int: ... + def end(self, __group: Union[int, str] = ...) -> int: ... + def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + if sys.version_info >= (3, 6): + def __getitem__(self, g: Union[int, str]) -> AnyStr: ... + +class Pattern(Generic[AnyStr]): + flags: int + groupindex: Mapping[str, int] + groups: int + pattern: AnyStr + + def search(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def match(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + # New in Python 3.4 + def fullmatch(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... + def findall(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> list[Any]: ... + def finditer(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Iterator[Match[AnyStr]]: ... + + @overload + def sub(self, repl: AnyStr, string: AnyStr, + count: int = ...) -> AnyStr: ... + @overload + def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, + count: int = ...) -> AnyStr: ... + + @overload + def subn(self, repl: AnyStr, string: AnyStr, + count: int = ...) -> Tuple[AnyStr, int]: ... + @overload + def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, + count: int = ...) -> Tuple[AnyStr, int]: ... + +# Functions + +if sys.version_info >= (3, 9): + def get_type_hints( + obj: Callable[..., Any], globalns: Optional[Dict[str, Any]] = ..., localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ... + ) -> Dict[str, Any]: ... +else: + def get_type_hints( + obj: Callable[..., Any], globalns: Optional[Dict[str, Any]] = ..., localns: Optional[Dict[str, Any]] = ..., + ) -> Dict[str, Any]: ... +if sys.version_info >= (3, 8): + def get_origin(tp: Any) -> Optional[Any]: ... + def get_args(tp: Any) -> Tuple[Any, ...]: ... + +@overload +def cast(typ: Type[_T], val: Any) -> _T: ... +@overload +def cast(typ: str, val: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(Tuple[Any, ...]): + _field_types: collections.OrderedDict[str, Type[Any]] + _field_defaults: Dict[str, Any] = ... + _fields: Tuple[str, ...] + _source: str + + def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., + **kwargs: Any) -> None: ... + + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + + if sys.version_info >= (3, 8): + def _asdict(self) -> Dict[str, Any]: ... + else: + def _asdict(self) -> collections.OrderedDict[str, Any]: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +class _TypedDict(Mapping[str, object], metaclass=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: ... + def update(self: _T, __m: _T) -> None: ... + def __delitem__(self, k: NoReturn) -> None: ... + def items(self) -> ItemsView[str, object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _C) -> _C: ... + +if sys.version_info >= (3, 7): + from types import CodeType + class ForwardRef: + __forward_arg__: str + __forward_code__: CodeType + __forward_evaluated__: bool + __forward_value__: Optional[Any] + __forward_is_argument__: bool + def __init__(self, arg: str, is_argument: bool = ...) -> None: ... + def _evaluate(self, globalns: Optional[Dict[str, Any]], + localns: Optional[Dict[str, Any]]) -> Optional[Any]: ... + def __eq__(self, other: Any) -> bool: ... + def __hash__(self) -> int: ... + def __repr__(self) -> str: ... diff --git a/mypy/stdlib/unicodedata.pyi b/mypy/stdlib/unicodedata.pyi new file mode 100644 index 000000000000..ddd10136158d --- /dev/null +++ b/mypy/stdlib/unicodedata.pyi @@ -0,0 +1,40 @@ +import sys +from typing import Any, Text, TypeVar, Union + +ucd_3_2_0: UCD +ucnhash_CAPI: Any +unidata_version: str + +_default = TypeVar('_default') + +def bidirectional(__chr: Text) -> Text: ... +def category(__chr: Text) -> Text: ... +def combining(__chr: Text) -> int: ... +def decimal(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def decomposition(__chr: Text) -> Text: ... +def digit(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def east_asian_width(__chr: Text) -> Text: ... +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: _default = ...) -> Union[Text, _default]: ... +def normalize(__form: Text, __unistr: Text) -> Text: ... +def numeric(__chr: Text, __default: _default = ...) -> Union[float, _default]: ... + +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: _default = ...) -> Union[int, _default]: ... + def decomposition(self, __chr: Text) -> str: ... + def digit(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + 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: _default = ...) -> Union[Text, _default]: ... + def normalize(self, __form: Text, __unistr: Text) -> Text: ... + def numeric(self, __chr: Text, __default: _default = ...) -> Union[float, _default]: ... diff --git a/mypy/stdlib/unittest/__init__.pyi b/mypy/stdlib/unittest/__init__.pyi new file mode 100644 index 000000000000..1c8c668045d3 --- /dev/null +++ b/mypy/stdlib/unittest/__init__.pyi @@ -0,0 +1,15 @@ +# Stubs for unittest + +from typing import Optional + +from unittest.async_case import * +from unittest.case import * +from unittest.loader import * +from unittest.main import * +from unittest.result import TestResult as TestResult +from unittest.runner import * +from unittest.signals import * +from unittest.suite import * + +def load_tests(loader: TestLoader, tests: TestSuite, + pattern: Optional[str]) -> TestSuite: ... diff --git a/mypy/stdlib/unittest/async_case.pyi b/mypy/stdlib/unittest/async_case.pyi new file mode 100644 index 000000000000..23e1c005c7a1 --- /dev/null +++ b/mypy/stdlib/unittest/async_case.pyi @@ -0,0 +1,9 @@ +import sys +from typing import Any, Awaitable, Callable +from .case import TestCase + +if sys.version_info >= (3, 8): + class IsolatedAsyncioTestCase(TestCase): + async def asyncSetUp(self) -> None: ... + async def asyncTearDown(self) -> None: ... + def addAsyncCleanup(self, __func: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/stdlib/unittest/case.pyi b/mypy/stdlib/unittest/case.pyi new file mode 100644 index 000000000000..2c9de24c4ad8 --- /dev/null +++ b/mypy/stdlib/unittest/case.pyi @@ -0,0 +1,262 @@ +import datetime +import logging +import sys +import unittest.result +import warnings +from types import TracebackType +from typing import ( + Any, AnyStr, Callable, Container, ContextManager, Dict, FrozenSet, Generic, + Iterable, List, Mapping, NoReturn, Optional, overload, Pattern, Sequence, + Set, Tuple, Type, TypeVar, Union, +) + +_E = TypeVar('_E', bound=BaseException) +_FT = TypeVar('_FT', bound=Callable[..., Any]) + +if sys.version_info >= (3, 8): + def addModuleCleanup(__function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def doModuleCleanups() -> None: ... + +def expectedFailure(test_item: _FT) -> _FT: ... +def skip(reason: str) -> Callable[[_FT], _FT]: ... +def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... +def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... + + +class SkipTest(Exception): + def __init__(self, reason: str) -> None: ... + + +class TestCase: + failureException: Type[BaseException] + longMessage: bool + maxDiff: Optional[int] + # undocumented + _testMethodName: str + # undocumented + _testMethodDoc: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: Optional[unittest.result.TestResult] = ...) -> Optional[unittest.result.TestResult]: ... + def __call__(self, result: Optional[unittest.result.TestResult] = ...) -> Optional[unittest.result.TestResult]: ... + def skipTest(self, reason: Any) -> None: ... + def subTest(self, msg: Any = ..., **params: Any) -> ContextManager[None]: ... + def debug(self) -> None: ... + def _addSkip( + self, result: unittest.result.TestResult, test_case: unittest.case.TestCase, reason: str + ) -> None: ... + def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def assertTrue(self, expr: Any, msg: Any = ...) -> None: ... + def assertFalse(self, expr: Any, msg: Any = ...) -> None: ... + def assertIs(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... + def assertIsNot(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... + def assertIsNone(self, obj: Any, msg: Any = ...) -> None: ... + def assertIsNotNone(self, obj: Any, msg: Any = ...) -> None: ... + def assertIn(self, member: Any, + container: Union[Iterable[Any], Container[Any]], + msg: Any = ...) -> None: ... + def assertNotIn(self, member: Any, + container: Union[Iterable[Any], Container[Any]], + msg: Any = ...) -> None: ... + def assertIsInstance(self, obj: Any, + cls: Union[type, Tuple[type, ...]], + msg: Any = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, + cls: Union[type, Tuple[type, ...]], + msg: Any = ...) -> None: ... + def assertGreater(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertGreaterEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertLess(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertLessEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... + @overload + def assertRaises(self, # type: ignore + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, + expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + @overload + def assertRaisesRegex(self, # type: ignore + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegex(self, + expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + @overload + def assertWarns(self, # type: ignore + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertWarns(self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + msg: Any = ...) -> _AssertWarnsContext: ... + @overload + def assertWarnsRegex(self, # type: ignore + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertWarnsRegex(self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ...) -> _AssertWarnsContext: ... + def assertLogs( + self, logger: Optional[Union[str, logging.Logger]] = ..., + level: Union[int, str, None] = ... + ) -> _AssertLogsContext: ... + @overload + def assertAlmostEqual(self, first: float, second: float, places: Optional[int] = ..., + msg: Any = ..., delta: Optional[float] = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: datetime.datetime, second: datetime.datetime, + places: Optional[int] = ..., msg: Any = ..., + delta: Optional[datetime.timedelta] = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, + msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, + places: Optional[int] = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, + msg: Any = ..., delta: Optional[float] = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: datetime.datetime, second: datetime.datetime, + places: Optional[int] = ..., msg: Any = ..., + delta: Optional[datetime.timedelta] = ...) -> None: ... + def assertRegex(self, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + def assertNotRegex(self, text: AnyStr, unexpected_regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], + msg: Any = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: Type[Any], + function: Callable[..., None]) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, + msg: Any = ...) -> None: ... + def assertSequenceEqual(self, seq1: Sequence[Any], seq2: Sequence[Any], + msg: Any = ..., + seq_type: Optional[Type[Sequence[Any]]] = ...) -> None: ... + def assertListEqual(self, list1: List[Any], list2: List[Any], + msg: Any = ...) -> None: ... + def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], + msg: Any = ...) -> None: ... + def assertSetEqual(self, set1: Union[Set[Any], FrozenSet[Any]], + set2: Union[Set[Any], FrozenSet[Any]], msg: Any = ...) -> None: ... + def assertDictEqual(self, d1: Dict[Any, Any], d2: Dict[Any, Any], + msg: Any = ...) -> None: ... + def fail(self, msg: Any = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> unittest.result.TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> Optional[str]: ... + + if sys.version_info >= (3, 8): + def addCleanup(self, __function: Callable[..., Any], *args: Any, + **kwargs: Any) -> None: ... + else: + def addCleanup(self, function: Callable[..., Any], *args: Any, + **kwargs: Any) -> None: ... + + def doCleanups(self) -> None: ... + if sys.version_info >= (3, 8): + @classmethod + def addClassCleanup(cls, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @classmethod + def doClassCleanups(cls) -> None: ... + def _formatMessage(self, msg: Optional[str], standardMsg: str) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + # below is deprecated + def failUnlessEqual(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def failUnless(self, expr: bool, msg: Any = ...) -> None: ... + def assert_(self, expr: bool, msg: Any = ...) -> None: ... + def failIf(self, expr: bool, msg: Any = ...) -> None: ... + @overload + def failUnlessRaises(self, # type: ignore + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any] = ..., + *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, + exception: Union[Type[_E], Tuple[Type[_E], ...]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def failUnlessAlmostEqual(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + def assertAlmostEquals(self, first: float, second: float, places: int = ..., + msg: Any = ..., delta: float = ...) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., + msg: Any = ...) -> None: ... + def assertNotAlmostEquals(self, first: float, second: float, + places: int = ..., msg: Any = ..., + delta: float = ...) -> None: ... + def assertRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + def assertNotRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + @overload + def assertRaisesRegexp(self, # type: ignore + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegexp(self, + exception: Union[Type[_E], Tuple[Type[_E], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertDictContainsSubset(self, + subset: Mapping[Any, Any], + dictionary: Mapping[Any, Any], + msg: object = ...) -> None: ... + +class FunctionTestCase(TestCase): + def __init__(self, testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ...) -> None: ... + def runTest(self) -> None: ... + +class _AssertRaisesContext(Generic[_E]): + exception: _E + def __enter__(self) -> _AssertRaisesContext[_E]: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + +class _AssertWarnsContext: + warning: warnings.WarningMessage + filename: str + lineno: int + warnings: List[warnings.WarningMessage] + def __enter__(self) -> _AssertWarnsContext: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> None: ... + +class _AssertLogsContext: + LOGGING_FORMAT: str + records: List[logging.LogRecord] + output: List[str] + def __init__(self, test_case: unittest.case.TestCase, + logger_name: str, level: int) -> None: ... + def __enter__(self) -> _AssertLogsContext: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> Optional[bool]: ... diff --git a/mypy/stdlib/unittest/loader.pyi b/mypy/stdlib/unittest/loader.pyi new file mode 100644 index 000000000000..b8db7e00759d --- /dev/null +++ b/mypy/stdlib/unittest/loader.pyi @@ -0,0 +1,49 @@ +import sys +import unittest.case +import unittest.suite +import unittest.result +from types import ModuleType +from typing import Any, Callable, List, Optional, Sequence, Type + + +_SortComparisonMethod = Callable[[str, str], int] +_SuiteClass = Callable[[List[unittest.case.TestCase]], unittest.suite.TestSuite] + +class TestLoader: + errors: List[Type[BaseException]] + testMethodPrefix: str + sortTestMethodsUsing: _SortComparisonMethod + + if sys.version_info >= (3, 7): + testNamePatterns: Optional[List[str]] + + suiteClass: _SuiteClass + def loadTestsFromTestCase(self, + testCaseClass: Type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... + def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: Any = ...) -> unittest.suite.TestSuite: ... + def loadTestsFromName(self, name: str, + module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... + def loadTestsFromNames(self, names: Sequence[str], + module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... + def getTestCaseNames(self, + testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... + def discover(self, start_dir: str, pattern: str = ..., + top_level_dir: Optional[str] = ...) -> unittest.suite.TestSuite: ... + +defaultTestLoader: TestLoader + + +if sys.version_info >= (3, 7): + def getTestCaseNames(testCaseClass: Type[unittest.case.TestCase], prefix: str, + sortUsing: _SortComparisonMethod = ..., + testNamePatterns: Optional[List[str]] = ...) -> Sequence[str]: ... +else: + def getTestCaseNames(testCaseClass: Type[unittest.case.TestCase], prefix: str, + sortUsing: _SortComparisonMethod = ...) -> Sequence[str]: ... + +def makeSuite(testCaseClass: Type[unittest.case.TestCase], prefix: str = ..., + sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ...) -> unittest.suite.TestSuite: ... + +def findTestCases(module, prefix: str = ..., sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ...) -> unittest.suite.TestSuite: ... diff --git a/mypy/stdlib/unittest/main.pyi b/mypy/stdlib/unittest/main.pyi new file mode 100644 index 000000000000..d6e1ebdbe1dd --- /dev/null +++ b/mypy/stdlib/unittest/main.pyi @@ -0,0 +1,51 @@ +import sys +from typing import Any, Iterable, List, Optional, Protocol, Type, Union +from types import ModuleType + +import unittest.case +import unittest.loader +import unittest.result +import unittest.suite + +class _TestRunner(Protocol): + def run( + self, test: Union[unittest.suite.TestSuite, unittest.case.TestCase] + ) -> unittest.result.TestResult: ... + + +# not really documented +class TestProgram: + result: unittest.result.TestResult + module: Union[None, str, ModuleType] + verbosity: int + failfast: Optional[bool] + catchbreak: Optional[bool] + buffer: Optional[bool] + progName: Optional[str] + warnings: Optional[str] + + if sys.version_info >= (3, 7): + testNamePatterns: Optional[List[str]] + + def __init__(self, module: Union[None, str, ModuleType] = ..., + defaultTest: Union[str, Iterable[str], None] = ..., + argv: Optional[List[str]] = ..., + testRunner: Union[Type[_TestRunner], _TestRunner, None] = ..., + testLoader: unittest.loader.TestLoader = ..., + exit: bool = ..., verbosity: int = ..., + failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ..., + warnings: Optional[str] = ..., *, + tb_locals: bool = ...) -> None: ... + def usageExit(self, msg: Any = ...) -> None: ... + def parseArgs(self, argv: List[str]) -> None: ... + + if sys.version_info >= (3, 7): + def createTests(self, from_discovery: bool = ..., + Loader: Optional[unittest.loader.TestLoader] = ...) -> None: ... + else: + def createTests(self) -> None: ... + + def runTests(self) -> None: ... # undocumented + +main = TestProgram diff --git a/mypy/stdlib/unittest/mock.pyi b/mypy/stdlib/unittest/mock.pyi new file mode 100644 index 000000000000..1f38f28a0b52 --- /dev/null +++ b/mypy/stdlib/unittest/mock.pyi @@ -0,0 +1,234 @@ +# Stubs for mock + +import sys +from typing import Any, List, Optional, Sequence, Text, Tuple, Type, TypeVar, Union + +_T = TypeVar("_T") + +__all__ = [ + 'Mock', + 'MagicMock', + 'patch', + 'sentinel', + 'DEFAULT', + 'ANY', + 'call', + 'create_autospec', + 'AsyncMock', + 'FILTER_DIR', + 'NonCallableMock', + 'NonCallableMagicMock', + 'mock_open', + 'PropertyMock', + 'seal', +] +__version__: str + +FILTER_DIR: Any + +class _slotted: ... + +class _SentinelObject: + name: Any + def __init__(self, name: Any) -> None: ... + +class _Sentinel: + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +sentinel: Any +DEFAULT: Any + +class _Call(Tuple[Any, ...]): + def __new__(cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> Any: ... + name: Any + parent: Any + from_kall: Any + def __init__(self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> None: ... + def __eq__(self, other: Any) -> bool: ... + __ne__: Any + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __getattr__(self, attr: Any) -> Any: ... + def count(self, *args: Any, **kwargs: Any) -> Any: ... + def index(self, *args: Any, **kwargs: Any) -> Any: ... + def call_list(self) -> Any: ... + +call: Any + + +class _CallList(List[_Call]): + def __contains__(self, value: Any) -> bool: ... + +class _MockIter: + obj: Any + def __init__(self, obj: Any) -> None: ... + def __iter__(self) -> Any: ... + def __next__(self) -> Any: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + + +class NonCallableMock(Base, Any): # type: ignore + def __new__(cls, *args, **kw) -> NonCallableMock: ... + def __init__(self, + spec: Union[List[str], object, Type[object], None] = ..., + wraps: Optional[Any] = ..., + name: Optional[str] = ..., + spec_set: Union[List[str], object, Type[object], None] = ..., + parent: Optional[NonCallableMock] = ..., + _spec_state: Optional[Any] = ..., + _new_name: str = ..., + _new_parent: Optional[NonCallableMock] = ..., + _spec_as_instance: bool = ..., + _eat_self: Optional[bool] = ..., + unsafe: bool = ..., **kwargs) -> None: ... + def __getattr__(self, name: str) -> Any: ... + if sys.version_info >= (3, 8): + def _calls_repr(self, prefix: str = ...) -> str: ... + + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + 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): + 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: ... + + def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... + + if sys.version_info >= (3, 8): + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... + elif sys.version_info >= (3, 6): + def assert_called(_mock_self) -> None: ... + def assert_called_once(_mock_self) -> None: ... + + if sys.version_info >= (3, 6): + def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... + elif sys.version_info >= (3, 5): + def reset_mock(self, visited: Any = ...) -> None: ... + + if sys.version_info >= (3, 7): + def _extract_mock_name(self) -> str: ... + def _get_call_signature_from_name(self, name: str) -> Any: ... + + def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... + def configure_mock(self, **kwargs: Any) -> None: ... + return_value: Any + side_effect: Any + called: bool + call_count: int + call_args: Any + call_args_list: _CallList + mock_calls: _CallList + def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... + def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... + def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + + +class CallableMixin(Base): + side_effect: Any + def __init__(self, spec: Optional[Any] = ..., side_effect: Optional[Any] = ..., return_value: Any = ..., wraps: Optional[Any] = ..., name: Optional[Any] = ..., spec_set: Optional[Any] = ..., parent: Optional[Any] = ..., _spec_state: Optional[Any] = ..., _new_name: Any = ..., _new_parent: Optional[Any] = ..., **kwargs: Any) -> None: ... + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + +class Mock(CallableMixin, NonCallableMock): ... + +class _patch: + attribute_name: Any + getter: Any + attribute: Any + new: Any + new_callable: Any + spec: Any + create: bool + has_local: Any + spec_set: Any + autospec: Any + kwargs: Any + additional_patchers: Any + def __init__(self, getter: Any, attribute: Any, new: Any, spec: Any, create: Any, spec_set: Any, autospec: Any, new_callable: Any, kwargs: Any) -> None: ... + def copy(self) -> Any: ... + def __call__(self, func: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def decorate_callable(self, func: Any) -> Any: ... + def get_original(self) -> Any: ... + target: Any + temp_original: Any + is_local: Any + def __enter__(self) -> Any: ... + def __exit__(self, *exc_info: Any) -> Any: ... + def start(self) -> Any: ... + def stop(self) -> Any: ... + +class _patch_dict: + in_dict: Any + values: Any + clear: Any + def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: Any) -> Any: ... + start: Any + stop: Any + +class _patcher: + TEST_PREFIX: str + dict: Type[_patch_dict] + def __call__(self, target: Any, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def object(self, target: Any, attribute: Text, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def multiple(self, target: Any, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def stopall(self) -> None: ... + +patch: _patcher + +class MagicMixin: + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class NonCallableMagicMock(MagicMixin, NonCallableMock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +class MagicMock(MagicMixin, Mock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +if sys.version_info >= (3, 8): + AsyncMock = Any + +class MagicProxy: + name: Any + parent: Any + def __init__(self, name: Any, parent: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Optional[Any] = ...) -> Any: ... + +class _ANY: + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +ANY: Any + +def create_autospec(spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any) -> Any: ... + +class _SpecState: + spec: Any + ids: Any + spec_set: Any + parent: Any + instance: Any + name: Any + def __init__(self, spec: Any, spec_set: Any = ..., parent: Optional[Any] = ..., name: Optional[Any] = ..., ids: Optional[Any] = ..., instance: Any = ...) -> None: ... + +def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ... + +PropertyMock = Any + +if sys.version_info >= (3, 7): + def seal(mock: Any) -> None: ... diff --git a/mypy/stdlib/unittest/result.pyi b/mypy/stdlib/unittest/result.pyi new file mode 100644 index 000000000000..b6ba1c48bac9 --- /dev/null +++ b/mypy/stdlib/unittest/result.pyi @@ -0,0 +1,46 @@ +from typing import Any, Callable, List, Optional, TextIO, Tuple, Type, TypeVar, Union +from types import TracebackType +import unittest.case + + +_SysExcInfoType = Union[ + Tuple[Type[BaseException], BaseException, TracebackType], + Tuple[None, None, None], +] + +_F = TypeVar("_F", bound=Callable[..., Any]) + +# undocumented +def failfast(method: _F) -> _F: ... + + +class TestResult: + errors: List[Tuple[unittest.case.TestCase, str]] + failures: List[Tuple[unittest.case.TestCase, str]] + skipped: List[Tuple[unittest.case.TestCase, str]] + expectedFailures: List[Tuple[unittest.case.TestCase, str]] + unexpectedSuccesses: List[unittest.case.TestCase] + shouldStop: bool + testsRun: int + buffer: bool + failfast: bool + tb_locals: bool + def __init__(self, stream: Optional[TextIO] = ..., + descriptions: Optional[bool] = ..., + verbosity: Optional[int] = ...) -> None: ... + def printErrors(self) -> None: ... + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: unittest.case.TestCase) -> None: ... + def stopTest(self, test: unittest.case.TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addSuccess(self, test: unittest.case.TestCase) -> None: ... + def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: unittest.case.TestCase, + err: _SysExcInfoType) -> None: ... + def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... + def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, + err: Optional[_SysExcInfoType]) -> None: ... diff --git a/mypy/stdlib/unittest/runner.pyi b/mypy/stdlib/unittest/runner.pyi new file mode 100644 index 000000000000..21423fa998f8 --- /dev/null +++ b/mypy/stdlib/unittest/runner.pyi @@ -0,0 +1,39 @@ +from typing import Callable, Optional, TextIO, Tuple, Type, Union +import unittest.case +import unittest.result +import unittest.suite + + +_ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] + + +class TextTestResult(unittest.result.TestResult): + descriptions: bool # undocumented + dots: bool # undocumented + separator1: str + separator2: str + showall: bool # undocumented + stream: TextIO # undocumented + def __init__(self, stream: TextIO, descriptions: bool, + verbosity: int) -> None: ... + def getDescription(self, test: unittest.case.TestCase) -> str: ... + def printErrors(self) -> None: ... + def printErrorList(self, flavour: str, errors: Tuple[unittest.case.TestCase, str]) -> None: ... + + +class TextTestRunner(object): + resultclass: _ResultClassType + def __init__( + self, + stream: Optional[TextIO] = ..., + descriptions: bool = ..., + verbosity: int = ..., + failfast: bool = ..., + buffer: bool = ..., + resultclass: Optional[_ResultClassType] = ..., + warnings: Optional[Type[Warning]] = ..., + *, + tb_locals: bool = ..., + ) -> None: ... + def _makeResult(self) -> unittest.result.TestResult: ... + def run(self, test: Union[unittest.suite.TestSuite, unittest.case.TestCase]) -> unittest.result.TestResult: ... diff --git a/mypy/stdlib/unittest/signals.pyi b/mypy/stdlib/unittest/signals.pyi new file mode 100644 index 000000000000..b925d45c3d07 --- /dev/null +++ b/mypy/stdlib/unittest/signals.pyi @@ -0,0 +1,14 @@ +from typing import Any, Callable, overload, TypeVar +import unittest.result + + +_F = TypeVar('_F', bound=Callable[..., Any]) + + +def installHandler() -> None: ... +def registerResult(result: unittest.result.TestResult) -> None: ... +def removeResult(result: unittest.result.TestResult) -> bool: ... +@overload +def removeHandler(method: None = ...) -> None: ... +@overload +def removeHandler(method: _F) -> _F: ... diff --git a/mypy/stdlib/unittest/suite.pyi b/mypy/stdlib/unittest/suite.pyi new file mode 100644 index 000000000000..b31804e20a95 --- /dev/null +++ b/mypy/stdlib/unittest/suite.pyi @@ -0,0 +1,24 @@ +from typing import Iterable, Iterator, List, Union +import unittest.case +import unittest.result + + +_TestType = Union[unittest.case.TestCase, TestSuite] + + +class BaseTestSuite(Iterable[_TestType]): + _tests: List[unittest.case.TestCase] + _removed_tests: int + def __init__(self, tests: Iterable[_TestType] = ...) -> None: ... + def __call__(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... + def addTest(self, test: _TestType) -> None: ... + def addTests(self, tests: Iterable[_TestType]) -> None: ... + def run(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[_TestType]: ... + + +class TestSuite(BaseTestSuite): + def run(self, result: unittest.result.TestResult, + debug: bool = ...) -> unittest.result.TestResult: ... diff --git a/mypy/stdlib/unittest/util.pyi b/mypy/stdlib/unittest/util.pyi new file mode 100644 index 000000000000..9b56f8bbfa7d --- /dev/null +++ b/mypy/stdlib/unittest/util.pyi @@ -0,0 +1,22 @@ +# undocumented +from typing import Any, List, Sequence, Tuple, TypeVar + +_T = TypeVar('_T') +_Mismatch = Tuple[_T, _T, int] + +_MAX_LENGTH: int +_PLACEHOLDER_LEN: int +_MIN_BEGIN_LEN: int +_MIN_END_LEN: int +_MIN_COMMON_LEN: int +_MIN_DIFF_LEN: int + +def _shorten(s: str, prefixlen: int, suffixlen: int) -> str: ... +def _common_shorten_repr(*args: str) -> Tuple[str]: ... +def safe_repr(obj: object, short: bool = ...) -> str: ... +def strclass(cls: type) -> str: ... +def sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> Tuple[List[_T], List[_T]]: ... +def unorderable_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> Tuple[List[_T], List[_T]]: ... +def three_way_cmp(x: Any, y: Any) -> int: ... +def _count_diff_all_purpose(actual: Sequence[_T], expected: Sequence[_T]) -> List[_Mismatch[_T]]: ... +def _count_diff_hashable(actual: Sequence[_T], expected: Sequence[_T]) -> List[_Mismatch[_T]]: ... diff --git a/mypy/stdlib/urllib/__init__.pyi b/mypy/stdlib/urllib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/urllib/error.pyi b/mypy/stdlib/urllib/error.pyi new file mode 100644 index 000000000000..16ceae8fc838 --- /dev/null +++ b/mypy/stdlib/urllib/error.pyi @@ -0,0 +1,11 @@ +from typing import Dict, Union +from urllib.response import addinfourl + +# Stubs for urllib.error + +class URLError(IOError): + reason: Union[str, BaseException] +class HTTPError(URLError, addinfourl): + code: int + def __init__(self, url, code, msg, hdrs, fp) -> None: ... +class ContentTooShortError(URLError): ... diff --git a/mypy/stdlib/urllib/parse.pyi b/mypy/stdlib/urllib/parse.pyi new file mode 100644 index 000000000000..42dfee3248ad --- /dev/null +++ b/mypy/stdlib/urllib/parse.pyi @@ -0,0 +1,165 @@ +# Stubs for urllib.parse +from typing import Any, List, Dict, Tuple, AnyStr, Generic, overload, Sequence, Mapping, Union, NamedTuple, Callable, Optional +import sys + +_Str = Union[bytes, str] + + +uses_relative: List[str] +uses_netloc: List[str] +uses_params: List[str] +non_hierarchical: List[str] +uses_query: List[str] +uses_fragment: List[str] +scheme_chars: str +MAX_CACHE_SIZE: int + +class _ResultMixinBase(Generic[AnyStr]): + def geturl(self) -> AnyStr: ... + +class _ResultMixinStr(_ResultMixinBase[str]): + def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... + + +class _ResultMixinBytes(_ResultMixinBase[str]): + def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... + + +class _NetlocResultMixinBase(Generic[AnyStr]): + username: Optional[AnyStr] + password: Optional[AnyStr] + hostname: Optional[AnyStr] + port: Optional[int] + +class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... + +class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... + +class _DefragResultBase(Tuple[Any, ...], Generic[AnyStr]): + url: AnyStr + fragment: AnyStr + + +class _SplitResultBase(NamedTuple): + scheme: str + netloc: str + path: str + query: str + fragment: str +class _SplitResultBytesBase(NamedTuple): + scheme: bytes + netloc: bytes + path: bytes + query: bytes + fragment: bytes + +class _ParseResultBase(NamedTuple): + scheme: str + netloc: str + path: str + params: str + query: str + fragment: str +class _ParseResultBytesBase(NamedTuple): + scheme: bytes + netloc: bytes + path: bytes + params: bytes + query: bytes + fragment: bytes + +# Structured result objects for string data +class DefragResult(_DefragResultBase[str], _ResultMixinStr): ... + +class SplitResult(_SplitResultBase, _NetlocResultMixinStr): ... + +class ParseResult(_ParseResultBase, _NetlocResultMixinStr): ... + +# Structured result objects for bytes data +class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): ... + +class SplitResultBytes(_SplitResultBytesBase, _NetlocResultMixinBytes): ... + +class ParseResultBytes(_ParseResultBytesBase, _NetlocResultMixinBytes): ... + +if sys.version_info >= (3, 8): + def parse_qs( + qs: Optional[AnyStr], + keep_blank_values: bool = ..., + strict_parsing: bool = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + ) -> Dict[AnyStr, List[AnyStr]]: ... + def parse_qsl( + qs: Optional[AnyStr], + keep_blank_values: bool = ..., + strict_parsing: bool = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + ) -> List[Tuple[AnyStr, AnyStr]]: ... + +else: + def parse_qs( + qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ..., + ) -> Dict[AnyStr, List[AnyStr]]: ... + def parse_qsl( + qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ..., + ) -> List[Tuple[AnyStr, AnyStr]]: ... + +@overload +def quote(string: str, safe: _Str = ..., encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... +@overload +def quote(string: bytes, safe: _Str = ...) -> str: ... + +def quote_from_bytes(bs: bytes, safe: _Str = ...) -> str: ... + +@overload +def quote_plus(string: str, safe: _Str = ..., encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... +@overload +def quote_plus(string: bytes, safe: _Str = ...) -> str: ... + +def unquote(string: str, encoding: str = ..., errors: str = ...) -> str: ... + +def unquote_to_bytes(string: _Str) -> bytes: ... + +def unquote_plus(string: str, encoding: str = ..., errors: str = ...) -> str: ... + +@overload +def urldefrag(url: str) -> DefragResult: ... +@overload +def urldefrag(url: Optional[bytes]) -> DefragResultBytes: ... + +def urlencode( + query: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]], Sequence[Tuple[Any, Any]], Sequence[Tuple[Any, Sequence[Any]]]], + doseq: bool = ..., + safe: AnyStr = ..., + encoding: str = ..., + errors: str = ..., + quote_via: Callable[[str, AnyStr, str, str], str] = ..., +) -> str: ... + +def urljoin(base: AnyStr, url: Optional[AnyStr], allow_fragments: bool = ...) -> AnyStr: ... + +@overload +def urlparse(url: str, scheme: Optional[str] = ..., allow_fragments: bool = ...) -> ParseResult: ... +@overload +def urlparse(url: Optional[bytes], scheme: Optional[bytes] = ..., allow_fragments: bool = ...) -> ParseResultBytes: ... + +@overload +def urlsplit(url: str, scheme: Optional[str] = ..., allow_fragments: bool = ...) -> SplitResult: ... +@overload +def urlsplit(url: Optional[bytes], scheme: Optional[bytes] = ..., allow_fragments: bool = ...) -> SplitResultBytes: ... + +@overload +def urlunparse( + components: Tuple[Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr]] +) -> AnyStr: ... +@overload +def urlunparse(components: Sequence[Optional[AnyStr]]) -> AnyStr: ... + +@overload +def urlunsplit(components: Tuple[Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr]]) -> AnyStr: ... +@overload +def urlunsplit(components: Sequence[Optional[AnyStr]]) -> AnyStr: ... diff --git a/mypy/stdlib/urllib/request.pyi b/mypy/stdlib/urllib/request.pyi new file mode 100644 index 000000000000..143b6a8508df --- /dev/null +++ b/mypy/stdlib/urllib/request.pyi @@ -0,0 +1,222 @@ +# Stubs for urllib.request (Python 3.4) + +from typing import ( + Any, Callable, ClassVar, Dict, List, IO, Mapping, Optional, Sequence, Tuple, + TypeVar, Union, overload, NoReturn, +) +from http.client import HTTPResponse, HTTPMessage, _HTTPConnectionProtocol +from http.cookiejar import CookieJar +from email.message import Message +from urllib.response import addinfourl +import ssl +import sys +import os + +_T = TypeVar('_T') +_UrlopenRet = Any + +def urlopen( + url: Union[str, Request], data: Optional[bytes] = ..., + timeout: Optional[float] = ..., *, cafile: Optional[str] = ..., + capath: Optional[str] = ..., cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ... +) -> _UrlopenRet: ... +def install_opener(opener: OpenerDirector) -> None: ... +def build_opener( + *handlers: Union[BaseHandler, Callable[[], BaseHandler]] +) -> OpenerDirector: ... +def url2pathname(pathname: str) -> str: ... +def pathname2url(pathname: str) -> str: ... +def getproxies() -> Dict[str, str]: ... +def parse_http_list(s: str) -> List[str]: ... +def parse_keqv_list(l: List[str]) -> Dict[str, str]: ... +def proxy_bypass(host: str) -> Any: ... # Undocumented + +class Request: + @property + def full_url(self) -> str: ... + @full_url.setter + def full_url(self, value: str) -> None: ... + @full_url.deleter + def full_url(self) -> None: ... + type: str + host: str + origin_req_host: str + selector: str + data: Optional[bytes] + headers: Dict[str, str] + unverifiable: bool + method: Optional[str] + def __init__(self, url: str, data: Optional[bytes] = ..., + headers: Dict[str, str] = ..., origin_req_host: Optional[str] = ..., + unverifiable: bool = ..., method: Optional[str] = ...) -> None: ... + def get_method(self) -> str: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def remove_header(self, header_name: str) -> None: ... + def get_full_url(self) -> str: ... + def set_proxy(self, host: str, type: str) -> None: ... + @overload + def get_header(self, header_name: str) -> Optional[str]: ... + @overload + def get_header(self, header_name: str, default: _T) -> Union[str, _T]: ... + def header_items(self) -> List[Tuple[str, str]]: ... + +class OpenerDirector: + addheaders: List[Tuple[str, str]] + def add_handler(self, handler: BaseHandler) -> None: ... + def open(self, fullurl: Union[str, Request], data: Optional[bytes] = ..., + timeout: Optional[float] = ...) -> _UrlopenRet: ... + def error(self, proto: str, *args: Any) -> _UrlopenRet: ... + + +class BaseHandler: + handler_order: ClassVar[int] + parent: OpenerDirector + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def http_error_nnn(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> _UrlopenRet: ... + +class HTTPDefaultErrorHandler(BaseHandler): ... + +class HTTPRedirectHandler(BaseHandler): + def redirect_request(self, req: Request, fp: IO[str], code: int, msg: str, + headers: Mapping[str, str], + newurl: str) -> Optional[Request]: ... + def http_error_301(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_302(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_303(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_307(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class HTTPCookieProcessor(BaseHandler): + cookiejar: CookieJar + def __init__(self, cookiejar: Optional[CookieJar] = ...) -> None: ... + +class ProxyHandler(BaseHandler): + def __init__(self, proxies: Optional[Dict[str, str]] = ...) -> None: ... + # TODO add a method for every (common) proxy protocol + +class HTTPPasswordMgr: + def add_password(self, realm: str, uri: Union[str, Sequence[str]], + user: str, passwd: str) -> None: ... + def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ... + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): + def add_password(self, realm: Optional[str], uri: Union[str, Sequence[str]], + user: str, passwd: str) -> None: ... + def find_user_password(self, realm: Optional[str], authuri: str) -> Tuple[Optional[str], Optional[str]]: ... + +class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm): + def add_password( + self, + realm: Optional[str], + uri: Union[str, Sequence[str]], + user: str, + passwd: str, + is_authenticated: bool = ..., + ) -> None: ... + def update_authenticated(self, uri: Union[str, Sequence[str]], is_authenticated: bool = ...) -> None: ... + def is_authenticated(self, authuri: str) -> bool: ... + +class AbstractBasicAuthHandler: + def __init__(self, + password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def http_error_auth_reqed(self, authreq: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[_UrlopenRet]: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, + headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + def __init__(self, debuglevel: int = ...) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, + http_class: _HTTPConnectionProtocol, + req: Request, + **http_conn_args: Any) -> HTTPResponse: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> HTTPResponse: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + def __init__(self, debuglevel: int = ..., + context: Optional[ssl.SSLContext] = ..., + check_hostname: Optional[bool] = ...) -> None: ... + def https_open(self, req: Request) -> HTTPResponse: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class FileHandler(BaseHandler): + def file_open(self, req: Request) -> addinfourl: ... + +class DataHandler(BaseHandler): + def data_open(self, req: Request) -> addinfourl: ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request) -> addinfourl: ... + +class CacheFTPHandler(FTPHandler): + def setTimeout(self, t: float) -> None: ... + def setMaxConns(self, m: int) -> None: ... + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request) -> NoReturn: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request, response) -> _UrlopenRet: ... + def https_response(self, request, response) -> _UrlopenRet: ... + +if sys.version_info >= (3, 6): + def urlretrieve(url: str, filename: Optional[Union[str, os.PathLike[Any]]] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... +else: + def urlretrieve(url: str, filename: Optional[str] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... +def urlcleanup() -> None: ... + +class URLopener: + version: ClassVar[str] + def __init__(self, proxies: Optional[Dict[str, str]] = ..., + **x509: str) -> None: ... + def open(self, fullurl: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... + def open_unknown(self, fullurl: str, + data: Optional[bytes] = ...) -> _UrlopenRet: ... + def retrieve(self, url: str, filename: Optional[str] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, Optional[Message]]: ... + +class FancyURLopener(URLopener): + def prompt_user_passwd(self, host: str, realm: str) -> Tuple[str, str]: ... diff --git a/mypy/stdlib/urllib/response.pyi b/mypy/stdlib/urllib/response.pyi new file mode 100644 index 000000000000..970fd743770c --- /dev/null +++ b/mypy/stdlib/urllib/response.pyi @@ -0,0 +1,51 @@ +# private module, we only expose what's needed + +from typing import Any, BinaryIO, Callable, IO, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar +from email.message import Message +from types import TracebackType + +_AIUT = TypeVar("_AIUT", bound=addbase) + +class addbase(BinaryIO): + fp: IO[bytes] + def __init__(self, fp: IO[bytes]) -> None: ... + def __enter__(self: _AIUT) -> _AIUT: ... + def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: ... + def __iter__(self: _AIUT) -> _AIUT: ... + def __next__(self) -> bytes: ... + def close(self) -> None: ... + # These methods don't actually exist, but the class inherits at runtime from + # tempfile._TemporaryFileWrapper, which uses __getattr__ to delegate to the + # underlying file object. To satisfy the BinaryIO interface, we pretend that this + # class has these additional methods. + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, n: int = ...) -> bytes: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + 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: bytes) -> int: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + +class addclosehook(addbase): + closehook: Callable[..., object] + hookargs: Tuple[Any, ...] + def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ... + +class addinfo(addbase): + headers: Message + def __init__(self, fp: IO[bytes], headers: Message) -> None: ... + def info(self) -> Message: ... + +class addinfourl(addinfo): + url: str + code: int + def __init__(self, fp: IO[bytes], headers: Message, url: str, code: Optional[int] = ...) -> None: ... + def geturl(self) -> str: ... + def getcode(self) -> int: ... diff --git a/mypy/stdlib/urllib/robotparser.pyi b/mypy/stdlib/urllib/robotparser.pyi new file mode 100644 index 000000000000..fcf46744f159 --- /dev/null +++ b/mypy/stdlib/urllib/robotparser.pyi @@ -0,0 +1,22 @@ +# Stubs for urllib.robotparser (Python 3.4) + +from typing import Iterable, List, NamedTuple, Optional +import sys + +class _RequestRate(NamedTuple): + requests: int + seconds: int + +class RobotFileParser: + def __init__(self, url: str = ...) -> None: ... + def set_url(self, url: str) -> None: ... + def read(self) -> None: ... + def parse(self, lines: Iterable[str]) -> None: ... + def can_fetch(self, user_agent: str, url: str) -> bool: ... + def mtime(self) -> int: ... + def modified(self) -> None: ... + if sys.version_info >= (3, 6): + def crawl_delay(self, useragent: str) -> Optional[str]: ... + def request_rate(self, useragent: str) -> Optional[_RequestRate]: ... + if sys.version_info >= (3, 8): + def site_maps(self) -> Optional[List[str]]: ... diff --git a/mypy/stdlib/uu.pyi b/mypy/stdlib/uu.pyi new file mode 100644 index 000000000000..3fbbab40ad82 --- /dev/null +++ b/mypy/stdlib/uu.pyi @@ -0,0 +1,13 @@ +# Stubs for uu (Python 2 and 3) +import sys +from typing import BinaryIO, Union, Optional, Text + +_File = Union[Text, BinaryIO] + +class Error(Exception): ... + +if sys.version_info >= (3, 7): + def encode(in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ..., *, backtick: bool = ...) -> None: ... +else: + 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/stdlib/uuid.pyi b/mypy/stdlib/uuid.pyi new file mode 100644 index 000000000000..09f799bcf10b --- /dev/null +++ b/mypy/stdlib/uuid.pyi @@ -0,0 +1,110 @@ +# Stubs for uuid + +import sys +from typing import Tuple, Optional, Any, Text + +# 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] + +if sys.version_info >= (3, 7): + from enum import Enum + class SafeUUID(Enum): + safe: int + unsafe: int + unknown: None + + +class UUID: + if sys.version_info >= (3, 7): + def __init__(self, hex: Optional[Text] = ..., + bytes: Optional[_Bytes] = ..., + bytes_le: Optional[_Bytes] = ..., + fields: Optional[_FieldsType] = ..., + int: Optional[_Int] = ..., + version: Optional[_Int] = ..., + *, + is_safe: SafeUUID = ...) -> None: ... + @property + def is_safe(self) -> SafeUUID: ... + else: + 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: ... + + 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 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/stdlib/venv/__init__.pyi b/mypy/stdlib/venv/__init__.pyi new file mode 100644 index 000000000000..b84d08e72795 --- /dev/null +++ b/mypy/stdlib/venv/__init__.pyi @@ -0,0 +1,42 @@ +import sys +from _typeshed import AnyPath +from typing import Optional, Sequence +from types import SimpleNamespace + +class EnvBuilder: + system_site_packages: bool + clear: bool + symlinks: bool + upgrade: bool + with_pip: bool + if sys.version_info >= (3, 6): + prompt: Optional[str] + + if sys.version_info >= (3, 9): + def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ..., upgrade_deps: bool = ...) -> None: ... + elif sys.version_info >= (3, 6): + def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ...) -> None: ... + else: + def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ...) -> 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_configuration(self, context: SimpleNamespace) -> None: ... + def symlink_or_copy(self, src: AnyPath, dst: AnyPath, 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: ... + def post_setup(self, context: SimpleNamespace) -> None: ... + def replace_variables(self, text: str, context: SimpleNamespace) -> str: ... # undocumented + def install_scripts(self, context: SimpleNamespace, path: str) -> None: ... + if sys.version_info >= (3, 9): + def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... + +if sys.version_info >= (3, 9): + def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ..., upgrade_deps: bool = ...) -> None: ... +elif sys.version_info >= (3, 6): + def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ...) -> None: ... +else: + def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ...) -> None: ... + +def main(args: Optional[Sequence[str]] = ...) -> None: ... diff --git a/mypy/stdlib/warnings.pyi b/mypy/stdlib/warnings.pyi new file mode 100644 index 000000000000..662e91a4c011 --- /dev/null +++ b/mypy/stdlib/warnings.pyi @@ -0,0 +1,67 @@ +import sys +from types import ModuleType, TracebackType +from typing import Any, List, NamedTuple, 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] + 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: ... + +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/stdlib/wave.pyi b/mypy/stdlib/wave.pyi new file mode 100644 index 000000000000..99873e3d87b8 --- /dev/null +++ b/mypy/stdlib/wave.pyi @@ -0,0 +1,76 @@ +# Stubs for wave (Python 2 and 3) + +import sys +from typing import ( + Any, NamedTuple, NoReturn, Optional, Text, BinaryIO, Union, Tuple, IO +) + +_File = Union[Text, IO[bytes]] + +class Error(Exception): ... + +WAVE_FORMAT_PCM: int + +if sys.version_info < (3, 0): + _wave_params = Tuple[int, int, int, int, str, str] +else: + 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 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: ... + if sys.version_info >= (3, 0): + 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: ... + 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: ... +if sys.version_info < (3, 9): + openfp = open diff --git a/mypy/stdlib/weakref.pyi b/mypy/stdlib/weakref.pyi new file mode 100644 index 000000000000..e3ddbf27845e --- /dev/null +++ b/mypy/stdlib/weakref.pyi @@ -0,0 +1,110 @@ +import sys +import types +from typing import ( + TypeVar, Generic, Any, Callable, overload, Mapping, Iterator, Tuple, + Iterable, Optional, Type, MutableMapping, Union, List, Dict +) + +from _weakref import ( + getweakrefcount as getweakrefcount, + getweakrefs as getweakrefs, + ref as ref, + proxy as proxy, + CallableProxyType as CallableProxyType, + ProxyType as ProxyType, + ReferenceType as ReferenceType) +from _weakrefset import WeakSet as WeakSet + +if sys.version_info < (3, 0): + from exceptions import ReferenceError as ReferenceError + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_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 WeakValueDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __map: 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: ... + 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): + 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]]: ... + else: + # 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]]: ... + +class KeyedRef(ref[_T], Generic[_KT, _T]): + key: _KT + def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... + +class WeakKeyDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __map: 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: ... + 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): + 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]]: ... + else: + # 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: _S, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, _: Any = ...) -> Optional[_T]: ... + def detach(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... + def peek(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... + alive: bool + atexit: bool diff --git a/mypy/stdlib/webbrowser.pyi b/mypy/stdlib/webbrowser.pyi new file mode 100644 index 000000000000..977d1363083f --- /dev/null +++ b/mypy/stdlib/webbrowser.pyi @@ -0,0 +1,100 @@ +import sys +from typing import Any, Optional, Callable, List, Text, Union, Sequence + +class Error(Exception): ... + +if sys.version_info >= (3, 7): + def register(name: Text, 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 = ...) -> 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: 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): + raise_opts: List[str] + 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): + raise_opts: List[str] + 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/stdlib/winreg.pyi b/mypy/stdlib/winreg.pyi new file mode 100644 index 000000000000..d1ed6a67d499 --- /dev/null +++ b/mypy/stdlib/winreg.pyi @@ -0,0 +1,99 @@ + +import sys + +from typing import Optional, Type, Union, Tuple, Any +from types import TracebackType + +_KeyType = Union[HKEYType, int] + +def CloseKey(__hkey: _KeyType): ... +def ConnectRegistry(__computer_name: Optional[str], __key: _KeyType) -> HKEYType: ... +def CreateKey(__key: _KeyType, __sub_key: Optional[str]) -> HKEYType: ... +def CreateKeyEx(key: _KeyType, sub_key: Optional[str], reserved: int = ..., access: int = ...) -> HKEYType: ... +def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... +def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... +def DeleteValue(__key: _KeyType, __value: str) -> None: ... +def EnumKey(__key: _KeyType, __index: int) -> str: ... +def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... +def ExpandEnvironmentStrings(__str: str) -> str: ... +def FlushKey(__key: _KeyType) -> None: ... +def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... +def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... +def QueryValue(__key: _KeyType, __sub_key: Optional[str]) -> str: ... +def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... +def SaveKey(__key: _KeyType, __file_name: str) -> None: ... +def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... +def SetValueEx(__key: _KeyType, __value_name: str, __reserved: Any, __type: int, __value: str) -> None: ... # reserved is ignored +def DisableReflectionKey(__key: _KeyType) -> None: ... +def EnableReflectionKey(__key: _KeyType) -> None: ... +def QueryReflectionKey(__key: _KeyType) -> bool: ... + +HKEY_CLASSES_ROOT: int +HKEY_CURRENT_USER: int +HKEY_LOCAL_MACHINE: int +HKEY_USERS: int +HKEY_PERFORMANCE_DATA: int +HKEY_CURRENT_CONFIG: int +HKEY_DYN_DATA: int + +KEY_ALL_ACCESS: int +KEY_WRITE: int +KEY_READ: int +KEY_EXECUTE: int +KEY_QUERY_VALUE: int +KEY_SET_VALUE: int +KEY_CREATE_SUB_KEY: int +KEY_ENUMERATE_SUB_KEYS: int +KEY_NOTIFY: int +KEY_CREATE_LINK: int + +KEY_WOW64_64KEY: int +KEY_WOW64_32KEY: int + +REG_BINARY: int +REG_DWORD: int +REG_DWORD_LITTLE_ENDIAN: int +REG_DWORD_BIG_ENDIAN: int +REG_EXPAND_SZ: int +REG_LINK: int +REG_MULTI_SZ: int +REG_NONE: int +if sys.version_info >= (3, 6): + REG_QWORD: int + REG_QWORD_LITTLE_ENDIAN: int +REG_RESOURCE_LIST: int +REG_FULL_RESOURCE_DESCRIPTOR: int +REG_RESOURCE_REQUIREMENTS_LIST: int +REG_SZ: int + +REG_CREATED_NEW_KEY: int # undocumented +REG_LEGAL_CHANGE_FILTER: int # undocumented +REG_LEGAL_OPTION: int # undocumented +REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented +REG_NOTIFY_CHANGE_LAST_SET: int # undocumented +REG_NOTIFY_CHANGE_NAME: int # undocumented +REG_NOTIFY_CHANGE_SECURITY: int # undocumented +REG_NO_LAZY_FLUSH: int # undocumented +REG_OPENED_EXISTING_KEY: int # undocumented +REG_OPTION_BACKUP_RESTORE: int # undocumented +REG_OPTION_CREATE_LINK: int # undocumented +REG_OPTION_NON_VOLATILE: int # undocumented +REG_OPTION_OPEN_LINK: int # undocumented +REG_OPTION_RESERVED: int # undocumented +REG_OPTION_VOLATILE: int # undocumented +REG_REFRESH_HIVE: int # undocumented +REG_WHOLE_HIVE_VOLATILE: int # undocumented + +error = OSError + +# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason +class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> HKEYType: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + + def Close(self) -> None: ... + def Detach(self) -> int: ... diff --git a/mypy/stdlib/winsound.pyi b/mypy/stdlib/winsound.pyi new file mode 100644 index 000000000000..14ca50993b78 --- /dev/null +++ b/mypy/stdlib/winsound.pyi @@ -0,0 +1,28 @@ +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/stdlib/wsgiref/__init__.pyi b/mypy/stdlib/wsgiref/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/wsgiref/handlers.pyi b/mypy/stdlib/wsgiref/handlers.pyi new file mode 100644 index 000000000000..3271c881a289 --- /dev/null +++ b/mypy/stdlib/wsgiref/handlers.pyi @@ -0,0 +1,87 @@ +import sys +from abc import abstractmethod +from types import TracebackType +from typing import Optional, Dict, MutableMapping, Type, Text, Callable, List, Tuple, IO + +from .headers import Headers +from .types import WSGIApplication, WSGIEnvironment, StartResponse, InputStream, ErrorStream +from .util import FileWrapper, guess_scheme + +_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]: ... + +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/stdlib/wsgiref/headers.pyi b/mypy/stdlib/wsgiref/headers.pyi new file mode 100644 index 000000000000..853922527b5b --- /dev/null +++ b/mypy/stdlib/wsgiref/headers.pyi @@ -0,0 +1,31 @@ +import sys +from typing import overload, Pattern, Optional, List, Tuple + +_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 __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 + 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: ... + if sys.version_info >= (3,): + 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/stdlib/wsgiref/simple_server.pyi b/mypy/stdlib/wsgiref/simple_server.pyi new file mode 100644 index 000000000000..50b8377e549e --- /dev/null +++ b/mypy/stdlib/wsgiref/simple_server.pyi @@ -0,0 +1,40 @@ +import sys +from typing import Optional, List, Type, TypeVar, overload + +from .handlers import SimpleHandler +from .types import WSGIApplication, WSGIEnvironment, StartResponse, ErrorStream + +if sys.version_info < (3,): + from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +else: + from http.server import HTTPServer, BaseHTTPRequestHandler + +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/stdlib/wsgiref/types.pyi b/mypy/stdlib/wsgiref/types.pyi new file mode 100644 index 000000000000..c272ae67c391 --- /dev/null +++ b/mypy/stdlib/wsgiref/types.pyi @@ -0,0 +1,3 @@ +# Obsolete, use _typeshed.wsgi directly. + +from _typeshed.wsgi import * diff --git a/mypy/stdlib/wsgiref/util.pyi b/mypy/stdlib/wsgiref/util.pyi new file mode 100644 index 000000000000..0382fc2854e8 --- /dev/null +++ b/mypy/stdlib/wsgiref/util.pyi @@ -0,0 +1,23 @@ +import sys +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: ... + if sys.version_info < (3,): + def next(self) -> bytes: ... + else: + 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/stdlib/wsgiref/validate.pyi b/mypy/stdlib/wsgiref/validate.pyi new file mode 100644 index 000000000000..b03e7889ffc6 --- /dev/null +++ b/mypy/stdlib/wsgiref/validate.pyi @@ -0,0 +1,53 @@ +import sys +from typing import Any, Iterable, Iterator, Optional, NoReturn, Callable + +from _typeshed.wsgi import WSGIApplication, InputStream, ErrorStream + +class WSGIWarning(Warning): ... + +def validator(application: WSGIApplication) -> WSGIApplication: ... + +class InputWrapper: + input: InputStream + def __init__(self, wsgi_input: InputStream) -> None: ... + if sys.version_info < (3,): + def read(self, size: int = ...) -> bytes: ... + def readline(self) -> bytes: ... + else: + 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: ... + +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: ... + if sys.version_info < (3,): + def next(self) -> bytes: ... + else: + def __next__(self) -> bytes: ... + def close(self) -> None: ... + def __del__(self) -> None: ... diff --git a/mypy/stdlib/xdrlib.pyi b/mypy/stdlib/xdrlib.pyi new file mode 100644 index 000000000000..864aced9c03a --- /dev/null +++ b/mypy/stdlib/xdrlib.pyi @@ -0,0 +1,56 @@ +# Structs for xdrlib (Python 2 and 3) +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/stdlib/xml/__init__.pyi b/mypy/stdlib/xml/__init__.pyi new file mode 100644 index 000000000000..c524ac2b1cfc --- /dev/null +++ b/mypy/stdlib/xml/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers as parsers diff --git a/mypy/stdlib/xml/dom/NodeFilter.pyi b/mypy/stdlib/xml/dom/NodeFilter.pyi new file mode 100644 index 000000000000..9bb2c1e530ff --- /dev/null +++ b/mypy/stdlib/xml/dom/NodeFilter.pyi @@ -0,0 +1,20 @@ +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/stdlib/xml/dom/__init__.pyi b/mypy/stdlib/xml/dom/__init__.pyi new file mode 100644 index 000000000000..91548cd947e8 --- /dev/null +++ b/mypy/stdlib/xml/dom/__init__.pyi @@ -0,0 +1,67 @@ +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, **kw) -> 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/stdlib/xml/dom/minidom.pyi b/mypy/stdlib/xml/dom/minidom.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/stdlib/xml/dom/minidom.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/stdlib/xml/dom/pulldom.pyi b/mypy/stdlib/xml/dom/pulldom.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/stdlib/xml/dom/pulldom.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/stdlib/xml/etree/ElementInclude.pyi b/mypy/stdlib/xml/etree/ElementInclude.pyi new file mode 100644 index 000000000000..eabfb54daf39 --- /dev/null +++ b/mypy/stdlib/xml/etree/ElementInclude.pyi @@ -0,0 +1,19 @@ +import sys +from typing import Union, Optional, Callable +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... +if sys.version_info >= (3, 9): + def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ..., base_url: Optional[str] = ..., max_depth: Optional[int] = ...) -> None: ... +else: + def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ...) -> None: ... diff --git a/mypy/stdlib/xml/etree/ElementPath.pyi b/mypy/stdlib/xml/etree/ElementPath.pyi new file mode 100644 index 000000000000..1250f0da42dd --- /dev/null +++ b/mypy/stdlib/xml/etree/ElementPath.pyi @@ -0,0 +1,33 @@ +# Stubs for xml.etree.ElementPath (Python 3.4) + +from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional +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: 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]] = ...) -> List[Element]: ... +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/stdlib/xml/etree/ElementTree.pyi b/mypy/stdlib/xml/etree/ElementTree.pyi new file mode 100644 index 000000000000..1dfaf45d8980 --- /dev/null +++ b/mypy/stdlib/xml/etree/ElementTree.pyi @@ -0,0 +1,314 @@ +from typing import ( + Any, + Callable, + Dict, + Generator, + IO, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + MutableSequence, + Optional, + Sequence, + Text, + Tuple, + TypeVar, + Union, + overload, +) +from _typeshed import AnyPath, FileDescriptor, SupportsWrite +import sys +from typing_extensions import Literal + +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 +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] = ..., + *, + out: None = ..., + from_file: Optional[_file_or_filename] = ..., + with_comments: bool = ..., + strip_text: bool = ..., + rewrite_prefixes: bool = ..., + qname_aware_tags: Optional[Iterable[str]] = ..., + qname_aware_attrs: Optional[Iterable[str]] = ..., + exclude_attrs: Optional[Iterable[str]] = ..., + exclude_tags: Optional[Iterable[str]] = ..., + ) -> str: ... + @overload + def canonicalize( + xml_data: Optional[_parser_input_type] = ..., + *, + out: SupportsWrite[str], + from_file: Optional[_file_or_filename] = ..., + with_comments: bool = ..., + strip_text: bool = ..., + rewrite_prefixes: bool = ..., + qname_aware_tags: Optional[Iterable[str]] = ..., + qname_aware_attrs: Optional[Iterable[str]] = ..., + exclude_attrs: Optional[Iterable[str]] = ..., + exclude_tags: Optional[Iterable[str]] = ..., + ) -> 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: ... + def append(self, __subelement: Element) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Element: ... + 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 getchildren(self) -> List[Element]: ... + def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + 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]] = ...) -> List[Element]: ... + 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 __bool__(self) -> bool: ... + 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 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]] = ...) -> List[Element]: ... + 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 register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... + +if sys.version_info >= (3, 8): + @overload + def tostring( + element: Element, + encoding: None = ..., + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> bytes: ... + @overload + def tostring( + element: Element, + encoding: Literal["unicode"], + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> str: ... + @overload + def tostring( + element: Element, + encoding: str, + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> Any: ... + + @overload + def tostringlist( + element: Element, + encoding: None = ..., + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> List[bytes]: ... + @overload + def tostringlist( + element: Element, + encoding: Literal["unicode"], + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> List[str]: ... + @overload + def tostringlist( + element: Element, + encoding: str, + method: Optional[str] = ..., + *, + xml_declaration: Optional[bool] = ..., + default_namespace: Optional[_str_argument_type] = ..., + short_empty_elements: bool = ..., + ) -> List[Any]: ... + +elif sys.version_info >= (3,): + @overload + def tostring(element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> bytes: ... + @overload + def tostring(element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> str: ... + @overload + def tostring(element: Element, encoding: str, method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> Any: ... + + @overload + def tostringlist(element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[bytes]: ... + @overload + def tostringlist(element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[str]: ... + @overload + def tostringlist(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: ... +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]]: ... + +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]]: ... + +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: ... + +if sys.version_info >= (3, 8): + class C14NWriterTarget: + def __init__( + self, + write: Callable[[str], Any], + *, + with_comments: bool = ..., + strip_text: bool = ..., + rewrite_prefixes: bool = ..., + qname_aware_tags: Optional[Iterable[str]] = ..., + qname_aware_attrs: Optional[Iterable[str]] = ..., + exclude_attrs: Optional[Iterable[str]] = ..., + exclude_tags: Optional[Iterable[str]] = ..., + ) -> None: ... + + +class XMLParser: + parser: Any + target: TreeBuilder + # TODO-what is entity used for??? + entity: Any + version: str + if sys.version_info >= (3, 8): + def __init__(self, *, target: Optional[TreeBuilder] = ..., encoding: Optional[str] = ...) -> None: ... + else: + def __init__(self, html: int = ..., target: Optional[TreeBuilder] = ..., encoding: Optional[str] = ...) -> None: ... + def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... + def close(self) -> Element: ... + def feed(self, __data: _parser_input_type) -> None: ... diff --git a/mypy/stdlib/xml/etree/__init__.pyi b/mypy/stdlib/xml/etree/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/xml/etree/cElementTree.pyi b/mypy/stdlib/xml/etree/cElementTree.pyi new file mode 100644 index 000000000000..c384968d08ff --- /dev/null +++ b/mypy/stdlib/xml/etree/cElementTree.pyi @@ -0,0 +1,3 @@ +# Stubs for xml.etree.cElementTree (Python 3.4) + +from xml.etree.ElementTree import * # noqa: F403 diff --git a/mypy/stdlib/xml/parsers/__init__.pyi b/mypy/stdlib/xml/parsers/__init__.pyi new file mode 100644 index 000000000000..cac086235cba --- /dev/null +++ b/mypy/stdlib/xml/parsers/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers.expat as expat diff --git a/mypy/stdlib/xml/parsers/expat/__init__.pyi b/mypy/stdlib/xml/parsers/expat/__init__.pyi new file mode 100644 index 000000000000..73f3758c61ec --- /dev/null +++ b/mypy/stdlib/xml/parsers/expat/__init__.pyi @@ -0,0 +1 @@ +from pyexpat import * diff --git a/mypy/stdlib/xml/parsers/expat/errors.pyi b/mypy/stdlib/xml/parsers/expat/errors.pyi new file mode 100644 index 000000000000..e22d769ec340 --- /dev/null +++ b/mypy/stdlib/xml/parsers/expat/errors.pyi @@ -0,0 +1 @@ +from pyexpat.errors import * diff --git a/mypy/stdlib/xml/parsers/expat/model.pyi b/mypy/stdlib/xml/parsers/expat/model.pyi new file mode 100644 index 000000000000..d8f44b47c51b --- /dev/null +++ b/mypy/stdlib/xml/parsers/expat/model.pyi @@ -0,0 +1 @@ +from pyexpat.model import * diff --git a/mypy/stdlib/xml/sax/__init__.pyi b/mypy/stdlib/xml/sax/__init__.pyi new file mode 100644 index 000000000000..faabf4108285 --- /dev/null +++ b/mypy/stdlib/xml/sax/__init__.pyi @@ -0,0 +1,38 @@ +from typing import Any, Iterable, List, NoReturn, Optional, Text, Union, IO + +import sys +import xml.sax +from xml.sax.xmlreader import InputSource, Locator +from xml.sax.handler import ContentHandler, ErrorHandler + +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] + +if sys.version_info >= (3, 8): + def make_parser(parser_list: Iterable[str] = ...) -> xml.sax.xmlreader.XMLReader: ... +else: + def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... + +def parse(source: Union[str, IO[str], IO[bytes]], handler: xml.sax.handler.ContentHandler, + errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... + +def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, + errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... + +def _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ... diff --git a/mypy/stdlib/xml/sax/handler.pyi b/mypy/stdlib/xml/sax/handler.pyi new file mode 100644 index 000000000000..3a5193300981 --- /dev/null +++ b/mypy/stdlib/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/stdlib/xml/sax/saxutils.pyi b/mypy/stdlib/xml/sax/saxutils.pyi new file mode 100644 index 000000000000..d4c9d442b133 --- /dev/null +++ b/mypy/stdlib/xml/sax/saxutils.pyi @@ -0,0 +1,61 @@ +import sys +from typing import Mapping, Text, Optional, Union, TextIO +from io import TextIOBase, RawIOBase +from codecs import StreamWriter, StreamReaderWriter +from _typeshed import SupportsWrite + +from xml.sax import handler +from xml.sax import 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): + 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 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/stdlib/xml/sax/xmlreader.pyi b/mypy/stdlib/xml/sax/xmlreader.pyi new file mode 100644 index 000000000000..d22db4b45fa1 --- /dev/null +++ b/mypy/stdlib/xml/sax/xmlreader.pyi @@ -0,0 +1,74 @@ + +from typing import Tuple, Mapping, Optional + +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 has_key(self, name): ... + 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/stdlib/xmlrpc/__init__.pyi b/mypy/stdlib/xmlrpc/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/stdlib/xmlrpc/client.pyi b/mypy/stdlib/xmlrpc/client.pyi new file mode 100644 index 000000000000..3b392e471001 --- /dev/null +++ b/mypy/stdlib/xmlrpc/client.pyi @@ -0,0 +1,275 @@ +import io +import sys +import time +import gzip +import http.client + +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Protocol, Tuple, Type, Union, overload +from typing_extensions import Literal +from types import TracebackType +from datetime import datetime +from _typeshed import SupportsRead, SupportsWrite + +class _SupportsTimeTuple(Protocol): + def timetuple(self) -> time.struct_time: ... +_DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] +_Marshallable = Union[None, bool, int, float, str, bytes, tuple, list, dict, datetime, DateTime, Binary] +_XMLDate = Union[int, datetime, Tuple[int, ...], time.struct_time] +_HostType = Union[Tuple[str, Dict[str, str]], str] + +def escape(s: str) -> str: ... # undocumented + +PARSE_ERROR: int # undocumented +SERVER_ERROR: int # undocumented +APPLICATION_ERROR: int # undocumented +SYSTEM_ERROR: int # undocumented +TRANSPORT_ERROR: int # undocumented + +NOT_WELLFORMED_ERROR: int # undocumented +UNSUPPORTED_ENCODING: int # undocumented +INVALID_ENCODING_CHAR: int # undocumented +INVALID_XMLRPC: int # undocumented +METHOD_NOT_FOUND: int # undocumented +INVALID_METHOD_PARAMS: int # undocumented +INTERNAL_ERROR: int # undocumented + +class Error(Exception): ... + +class ProtocolError(Error): + + url: str + errcode: int + errmsg: str + headers: Dict[str, str] + + def __init__(self, url: str, errcode: int, errmsg: str, headers: Dict[str, str]) -> None: ... + +class ResponseError(Error): ... + +class Fault(Error): + + faultCode: str + faultString: str + + def __init__(self, faultCode: str, faultString: str, **extra: Any) -> None: ... + + +boolean = bool +Boolean = bool + +def _iso8601_format(value: datetime) -> str: ... # undocumented +def _strftime(value: _XMLDate) -> str: ... # undocumented + +class DateTime: + + value: str # undocumented + + def __init__(self, value: Union[int, str, datetime, time.struct_time, Tuple[int, ...]] = ...): ... + def __lt__(self, other: _DateTimeComparable) -> bool: ... + def __le__(self, other: _DateTimeComparable) -> bool: ... + def __gt__(self, other: _DateTimeComparable) -> bool: ... + def __ge__(self, other: _DateTimeComparable) -> bool: ... + def __eq__(self, other: _DateTimeComparable) -> bool: ... # type: ignore + def make_comparable(self, other: _DateTimeComparable) -> Tuple[str, str]: ... # undocumented + def timetuple(self) -> time.struct_time: ... # undocumented + def decode(self, data: Any) -> None: ... + def encode(self, out: SupportsWrite[str]) -> None: ... + +def _datetime(data: Any) -> DateTime: ... # undocumented +def _datetime_type(data: str) -> datetime: ... # undocumented + +class Binary: + + data: bytes + + def __init__(self, data: Optional[bytes] = ...) -> None: ... + def decode(self, data: bytes) -> None: ... + def encode(self, out: SupportsWrite[str]) -> None: ... + +def _binary(data: bytes) -> Binary: ... # undocumented + +WRAPPERS: Tuple[Type[DateTime], Type[Binary]] # undocumented + +class ExpatParser: # undocumented + + def __init__(self, target: Unmarshaller) -> None: ... + def feed(self, data: Union[str, bytes]) -> None: ... + def close(self) -> None: ... + +class Marshaller: + + dispatch: Dict[Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None]] = ... # TODO: Replace 'Any' with some kind of binding + + memo: Dict[Any, None] + data: None + encoding: Optional[str] + allow_none: bool + + def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... + def dumps(self, values: Union[Fault, Iterable[_Marshallable]]) -> str: ... + def __dump(self, value: Union[_Marshallable], write: Callable[[str], Any]) -> None: ... # undocumented + def dump_nil(self, value: None, write: Callable[[str], Any]) -> None: ... + def dump_bool(self, value: bool, write: Callable[[str], Any]) -> None: ... + def dump_long(self, value: int, write: Callable[[str], Any]) -> None: ... + def dump_int(self, value: int, write: Callable[[str], Any]) -> None: ... + def dump_double(self, value: float, write: Callable[[str], Any]) -> None: ... + def dump_unicode(self, value: str, write: Callable[[str], Any], escape: Callable[[str], str] = ...) -> None: ... + def dump_bytes(self, value: bytes, write: Callable[[str], Any]) -> None: ... + def dump_array(self, value: Iterable[_Marshallable], write: Callable[[str], Any]) -> None: ... + def dump_struct(self, value: Mapping[str, _Marshallable], write: Callable[[str], Any], escape: Callable[[str], str] = ...) -> None: ... + def dump_datetime(self, value: _XMLDate, write: Callable[[str], Any]) -> None: ... + def dump_instance(self, value: object, write: Callable[[str], Any]) -> None: ... + +class Unmarshaller: + + dispatch: Dict[str, Callable[[Unmarshaller, str], None]] = ... + + _type: Optional[str] + _stack: List[_Marshallable] + _marks: List[int] + _data: List[str] + _value: bool + _methodname: Optional[str] + _encoding: str + append: Callable[[Any], None] + _use_datetime: bool + _use_builtin_types: bool + + def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... + def close(self) -> Tuple[_Marshallable, ...]: ... + def getmethodname(self) -> Optional[str]: ... + def xml(self, encoding: str, standalone: Any) -> None: ... # Standalone is ignored + def start(self, tag: str, attrs: Dict[str, str]) -> None: ... + def data(self, text: str) -> None: ... + def end(self, tag: str) -> None: ... + def end_dispatch(self, tag: str, data: str) -> None: ... + def end_nil(self, data: str) -> None: ... + def end_boolean(self, data: str) -> None: ... + def end_int(self, data: str) -> None: ... + def end_double(self, data: str) -> None: ... + if sys.version_info >= (3, 6): + def end_bigdecimal(self, data: str) -> None: ... + def end_string(self, data: str) -> None: ... + def end_array(self, data: str) -> None: ... + def end_struct(self, data: str) -> None: ... + def end_base64(self, data: str) -> None: ... + def end_dateTime(self, data: str) -> None: ... + def end_value(self, data: str) -> None: ... + def end_params(self, data: str) -> None: ... + def end_fault(self, data: str) -> None: ... + def end_methodName(self, data: str) -> None: ... + +class _MultiCallMethod: # undocumented + + __call_list: List[Tuple[str, Tuple[_Marshallable, ...]]] + __name: str + + def __init__(self, call_list: List[Tuple[str, _Marshallable]], name: str) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self, *args: _Marshallable) -> None: ... + +class MultiCallIterator: # undocumented + + results: List[List[_Marshallable]] + + def __init__(self, results: List[List[_Marshallable]]) -> None: ... + def __getitem__(self, i: int) -> _Marshallable: ... + +class MultiCall: + + __server: ServerProxy + __call_list: List[Tuple[str, Tuple[_Marshallable, ...]]] + + def __init__(self, server: ServerProxy) -> None: ... + def __getattr__(self, item: str) -> _MultiCallMethod: ... + def __call__(self) -> MultiCallIterator: ... + +# A little white lie +FastMarshaller: Optional[Marshaller] +FastParser: Optional[ExpatParser] +FastUnmarshaller: Optional[Unmarshaller] + +def getparser(use_datetime: bool = ..., use_builtin_types: bool = ...) -> Tuple[ExpatParser, Unmarshaller]: ... +def dumps(params: Union[Fault, Tuple[_Marshallable, ...]], methodname: Optional[str] = ..., methodresponse: Optional[bool] = ..., encoding: Optional[str] = ..., allow_none: bool = ...) -> str: ... +def loads(data: str, use_datetime: bool = ..., use_builtin_types: bool = ...) -> Tuple[Tuple[_Marshallable, ...], Optional[str]]: ... + +def gzip_encode(data: bytes) -> bytes: ... # undocumented +def gzip_decode(data: bytes, max_decode: int = ...) -> bytes: ... # undocumented + +class GzipDecodedResponse(gzip.GzipFile): # undocumented + + io: io.BytesIO + + def __init__(self, response: SupportsRead[bytes]) -> None: ... + def close(self) -> None: ... + +class _Method: # undocumented + + __send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable] + __name: str + + def __init__(self, send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, *args: _Marshallable) -> _Marshallable: ... + +class Transport: + + user_agent: str = ... + accept_gzip_encoding: bool = ... + encode_threshold: Optional[int] = ... + + _use_datetime: bool + _use_builtin_types: bool + _connection: Tuple[Optional[_HostType], Optional[http.client.HTTPConnection]] + _headers: List[Tuple[str, str]] + _extra_headers: List[Tuple[str, str]] + + if sys.version_info >= (3, 8): + def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ...) -> None: ... + else: + def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... + def request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... + def single_request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... + def getparser(self) -> Tuple[ExpatParser, Unmarshaller]: ... + def get_host_info(self, host: _HostType) -> Tuple[str, List[Tuple[str, str]], Dict[str, str]]: ... + def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ... + def close(self) -> None: ... + def send_request(self, host: _HostType, handler: str, request_body: bytes, debug: bool) -> http.client.HTTPConnection: ... + def send_headers(self, connection: http.client.HTTPConnection, headers: List[Tuple[str, str]]) -> None: ... + def send_content(self, connection: http.client.HTTPConnection, request_body: bytes) -> None: ... + def parse_response(self, response: http.client.HTTPResponse) -> Tuple[_Marshallable, ...]: ... + +class SafeTransport(Transport): + + if sys.version_info >= (3, 8): + def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ..., context: Optional[Any] = ...) -> None: ... + else: + def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Optional[Any] = ...) -> None: ... + def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... + +class ServerProxy: + + __host: str + __handler: str + __transport: Transport + __encoding: str + __verbose: bool + __allow_none: bool + + if sys.version_info >= (3, 8): + def __init__(self, uri, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ..., context: Optional[Any] = ...) -> None: ... + else: + def __init__(self, uri, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Optional[Any] = ...) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + @overload + def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... + @overload + def __call__(self, attr: Literal["transport"]) -> Transport: ... + @overload + def __call__(self, attr: str) -> Union[Callable[[], None], Transport]: ... + def __enter__(self) -> ServerProxy: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... + def __close(self) -> None: ... # undocumented + def __request(self, methodname: str, params: Tuple[_Marshallable, ...]) -> Tuple[_Marshallable, ...]: ... # undocumented + +Server = ServerProxy diff --git a/mypy/stdlib/xmlrpc/server.pyi b/mypy/stdlib/xmlrpc/server.pyi new file mode 100644 index 000000000000..999d58208a6c --- /dev/null +++ b/mypy/stdlib/xmlrpc/server.pyi @@ -0,0 +1,119 @@ +import http.server +import socketserver +import pydoc +import sys + +from xmlrpc.client import Fault +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Pattern, Protocol, Tuple, Type, Union +from datetime import datetime + +_Marshallable = Union[None, bool, int, float, str, bytes, tuple, list, dict, datetime] # TODO: Recursive type on tuple, list, dict + +# The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy +class _DispatchArity0(Protocol): + def __call__(self) -> _Marshallable: ... +class _DispatchArity1(Protocol): + def __call__(self, __arg1: _Marshallable) -> _Marshallable: ... +class _DispatchArity2(Protocol): + def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable) -> _Marshallable: ... +class _DispatchArity3(Protocol): + def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable) -> _Marshallable: ... +class _DispatchArity4(Protocol): + def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable) -> _Marshallable: ... +class _DispatchArityN(Protocol): + def __call__(self, *args: _Marshallable) -> _Marshallable: ... +_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] + + +def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented +def list_public_methods(obj: Any) -> List[str]: ... # undocumented + +class SimpleXMLRPCDispatcher: # undocumented + + funcs: Dict[str, _DispatchProtocol] + instance: Optional[Any] + allow_none: bool + encoding: str + use_builtin_types: bool + + def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... + def register_instance(self, instance: Any, allow_dotted_names: bool = ...) -> None: ... + if sys.version_info >= (3, 7): + def register_function(self, function: Optional[_DispatchProtocol] = ..., name: Optional[str] = ...) -> Callable[..., Any]: ... + else: + def register_function(self, function: _DispatchProtocol, name: Optional[str] = ...) -> Callable[..., Any]: ... + def register_introspection_functions(self) -> None: ... + def register_multicall_functions(self) -> None: ... + def _marshaled_dispatch(self, data: str, dispatch_method: Optional[Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]]] = ..., path: Optional[Any] = ...) -> str: ... # undocumented + def system_listMethods(self) -> List[str]: ... # undocumented + def system_methodSignature(self, method_name: str) -> str: ... # undocumented + def system_methodHelp(self, method_name: str) -> str: ... # undocumented + def system_multicall(self, call_list: List[Dict[str, _Marshallable]]) -> List[_Marshallable]: ... # undocumented + def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ... # undocumented + +class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): + + rpc_paths: Tuple[str, str] = ... + encode_threshold: int = ... # undocumented + aepattern: Pattern[str] # undocumented + + def accept_encodings(self) -> Dict[str, float]: ... + def is_rpc_path_valid(self) -> bool: ... + def do_POST(self) -> None: ... + def decode_request_content(self, data: bytes) -> Optional[bytes]: ... + def report_404(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... + +class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): + + allow_reuse_address: bool = ... + _send_traceback_handler: bool = ... + + def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + +class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented + + dispatchers: Dict[str, SimpleXMLRPCDispatcher] + allow_none: bool + encoding: str + + def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ... + def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... + def _marshaled_dispatch(self, data: str, dispatch_method: Optional[Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]]] = ..., path: Optional[Any] = ...) -> str: ... + +class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): + + def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... + def handle_xmlrpc(self, request_text: str) -> None: ... + def handle_get(self) -> None: ... + def handle_request(self, request_text: Optional[str] = ...) -> None: ... + +class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented + + def docroutine(self, object: object, name: str, mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: Optional[type] = ...) -> str: ... # type: ignore + def docserver(self, server_name: str, package_documentation: str, methods: Dict[str, str]) -> str: ... + +class XMLRPCDocGenerator: # undocumented + + server_name: str + server_documentation: str + server_title: str + + def __init__(self) -> None: ... + def set_server_title(self, server_title: str) -> None: ... + def set_server_name(self, server_name: str) -> None: ... + def set_server_documentation(self, server_documentation: str) -> None: ... + def generate_html_documentation(self) -> str: ... + +class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + + def do_GET(self) -> None: ... + +class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): + + def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + +class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): + + def __init__(self) -> None: ... diff --git a/mypy/stdlib/zipapp.pyi b/mypy/stdlib/zipapp.pyi new file mode 100644 index 000000000000..76354b6ab9d4 --- /dev/null +++ b/mypy/stdlib/zipapp.pyi @@ -0,0 +1,16 @@ +# Stubs for zipapp (Python 3.5+) + +from pathlib import Path +import sys +from typing import BinaryIO, Callable, Optional, Union + +_Path = Union[str, Path, BinaryIO] + +class ZipAppError(ValueError): ... + +if sys.version_info >= (3, 7): + def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ..., + filter: Optional[Callable[[Path], bool]] = ..., compressed: bool = ...) -> None: ... +else: + def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ...) -> None: ... +def get_interpreter(archive: _Path) -> str: ... diff --git a/mypy/stdlib/zipfile.pyi b/mypy/stdlib/zipfile.pyi new file mode 100644 index 000000000000..26547a73cf63 --- /dev/null +++ b/mypy/stdlib/zipfile.pyi @@ -0,0 +1,189 @@ +from _typeshed import StrPath +from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, Protocol, Text, Tuple, Type, Union, Sequence, Pattern +from types import TracebackType +import io +import sys + +_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): ... + +error = BadZipfile + +class LargeZipFile(Exception): ... + +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 = ... + + newlines: Optional[List[bytes]] + mode: str + name: str + if sys.version_info >= (3, 7): + def __init__( + self, + fileobj: IO[bytes], + mode: str, + zipinfo: ZipInfo, + pwd: Optional[bytes] = ..., + close_fileobj: bool = ..., + ) -> None: ... + else: + def __init__( + self, + fileobj: IO[bytes], + mode: str, + zipinfo: ZipInfo, + decrypter: Optional[Callable[[Sequence[int]], bytes]] = ..., + close_fileobj: bool = ..., + ) -> None: ... + 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 + if sys.version_info >= (3, 8): + def __init__( + self, + file: Union[StrPath, IO[bytes]], + mode: str = ..., + compression: int = ..., + allowZip64: bool = ..., + compresslevel: Optional[int] = ..., + *, + strict_timestamps: bool = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): + def __init__( + self, + file: Union[StrPath, IO[bytes]], + mode: str = ..., + compression: int = ..., + allowZip64: bool = ..., + compresslevel: Optional[int] = ..., + ) -> None: ... + else: + 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[_SZI] = ..., pwd: Optional[bytes] = ...) -> str: ... + def extractall( + self, path: Optional[StrPath] = ..., members: Optional[Iterable[Text]] = ..., pwd: Optional[bytes] = ... + ) -> None: ... + if sys.version_info >= (3,): + def printdir(self, file: Optional[_Writer] = ...) -> None: ... + else: + def printdir(self) -> None: ... + def setpassword(self, pwd: bytes) -> None: ... + def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... + def testzip(self) -> Optional[str]: ... + if sys.version_info >= (3, 7): + def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ..., compresslevel: Optional[int] = ...) -> None: ... + else: + def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ...) -> None: ... + if sys.version_info >= (3, 7): + def writestr(self, zinfo_or_arcname: _SZI, 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: ... + +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: ... + +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: ... + 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): + @classmethod + def from_file(cls, filename: StrPath, arcname: Optional[StrPath] = ...) -> ZipInfo: ... + if sys.version_info >= (3, 6): + def is_dir(self) -> bool: ... + def FileHeader(self, zip64: Optional[bool] = ...) -> bytes: ... + +if sys.version_info >= (3, 8): + class Path: + @property + def name(self) -> str: ... + @property + def parent(self) -> Path: ... # undocumented + def __init__(self, root: Union[ZipFile, StrPath, IO[bytes]], at: str = ...) -> None: ... + def open(self, mode: str = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... + def iterdir(self) -> Iterator[Path]: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def exists(self) -> bool: ... + def read_text( + self, + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + line_buffering: bool = ..., + write_through: bool = ..., + ) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, add: StrPath) -> Path: ... # undocumented + def __truediv__(self, add: StrPath) -> Path: ... + +def is_zipfile(filename: Union[StrPath, IO[bytes]]) -> bool: ... + +ZIP_STORED: int +ZIP_DEFLATED: int +if sys.version_info >= (3, 3): + ZIP_BZIP2: int + ZIP_LZMA: int diff --git a/mypy/stdlib/zipimport.pyi b/mypy/stdlib/zipimport.pyi new file mode 100644 index 000000000000..b33a150586ea --- /dev/null +++ b/mypy/stdlib/zipimport.pyi @@ -0,0 +1,29 @@ +"""Stub file for the 'zipimport' module.""" + +import os +import sys +from typing import Any, List, Optional, Tuple, Union +from types import CodeType, ModuleType +if sys.version_info >= (3, 7): + from importlib.abc import ResourceReader + +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 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: ... + if sys.version_info >= (3, 7): + def get_resource_reader(self, fullname: str) -> Optional[ResourceReader]: ... # undocumented + 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/stdlib/zlib.pyi b/mypy/stdlib/zlib.pyi new file mode 100644 index 000000000000..871f621bf703 --- /dev/null +++ b/mypy/stdlib/zlib.pyi @@ -0,0 +1,57 @@ +# Stubs for zlib +import sys +from array import array +from typing import Union, Any + +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_FULL_FLUSH: int +Z_HUFFMAN_ONLY: int +Z_NO_FLUSH: int +Z_SYNC_FLUSH: int +if sys.version_info >= (3,): + DEF_BUF_SIZE: int + ZLIB_RUNTIME_VERSION: str + +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 + if sys.version_info >= (3,): + 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: bytes = ...) -> _Compress: ... +else: + 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: ... +if sys.version_info >= (3,): + def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ... +else: + def decompressobj(wbits: int = ...) -> _Decompress: ... diff --git a/mypy/stdlib/zoneinfo/__init__.pyi b/mypy/stdlib/zoneinfo/__init__.pyi new file mode 100644 index 000000000000..6e56abf2cdcf --- /dev/null +++ b/mypy/stdlib/zoneinfo/__init__.pyi @@ -0,0 +1,45 @@ +import os +import typing +from datetime import datetime, tzinfo +from typing import ( + Any, + Iterable, + Optional, + Protocol, + Sequence, + Set, + Type, + Union, +) + +_T = typing.TypeVar("_T", bound="ZoneInfo") + +class _IOBytes(Protocol): + def read(self, __size: int) -> bytes: ... + def seek(self, __size: int, __whence: int = ...) -> Any: ... + +class ZoneInfo(tzinfo): + @property + def key(self) -> str: ... + def __init__(self, key: str) -> None: ... + @classmethod + def no_cache(cls: Type[_T], key: str) -> _T: ... + @classmethod + def from_file( + cls: Type[_T], __fobj: _IOBytes, key: Optional[str] = ... + ) -> _T: ... + @classmethod + def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... + +# 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, str]]] = ... +) -> None: ... +def available_timezones() -> Set[str]: ... + +TZPATH: Sequence[str] + +class ZoneInfoNotFoundError(KeyError): ... +class InvalidTZPathWarning(RuntimeWarning): ... From c6efa7ae28e42e72bbf1e1735d56823835ce2d6d Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 25 Jun 2020 15:00:49 +0100 Subject: [PATCH 02/50] Move stdlib stubs to typeshed/stdlib --- mypy/{ => typeshed}/stdlib/VERSIONS | 0 mypy/{ => typeshed}/stdlib/__future__.pyi | 0 mypy/{ => typeshed}/stdlib/_ast.pyi | 0 mypy/{ => typeshed}/stdlib/_bisect.pyi | 0 mypy/{ => typeshed}/stdlib/_bootlocale.pyi | 0 mypy/{ => typeshed}/stdlib/_codecs.pyi | 0 mypy/{ => typeshed}/stdlib/_compat_pickle.pyi | 0 mypy/{ => typeshed}/stdlib/_compression.pyi | 0 mypy/{ => typeshed}/stdlib/_csv.pyi | 0 mypy/{ => typeshed}/stdlib/_curses.pyi | 0 mypy/{ => typeshed}/stdlib/_decimal.pyi | 0 mypy/{ => typeshed}/stdlib/_dummy_thread.pyi | 0 mypy/{ => typeshed}/stdlib/_dummy_threading.pyi | 0 mypy/{ => typeshed}/stdlib/_heapq.pyi | 0 mypy/{ => typeshed}/stdlib/_imp.pyi | 0 mypy/{ => typeshed}/stdlib/_importlib_modulespec.pyi | 0 mypy/{ => typeshed}/stdlib/_json.pyi | 0 mypy/{ => typeshed}/stdlib/_markupbase.pyi | 0 mypy/{ => typeshed}/stdlib/_msi.pyi | 0 mypy/{ => typeshed}/stdlib/_operator.pyi | 0 mypy/{ => typeshed}/stdlib/_osx_support.pyi | 0 mypy/{ => typeshed}/stdlib/_posixsubprocess.pyi | 0 mypy/{ => typeshed}/stdlib/_py_abc.pyi | 0 mypy/{ => typeshed}/stdlib/_pydecimal.pyi | 0 mypy/{ => typeshed}/stdlib/_random.pyi | 0 mypy/{ => typeshed}/stdlib/_sitebuiltins.pyi | 0 mypy/{ => typeshed}/stdlib/_stat.pyi | 0 mypy/{ => typeshed}/stdlib/_thread.pyi | 0 mypy/{ => typeshed}/stdlib/_threading_local.pyi | 0 mypy/{ => typeshed}/stdlib/_tracemalloc.pyi | 0 mypy/{ => typeshed}/stdlib/_typeshed/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/_typeshed/wsgi.pyi | 0 mypy/{ => typeshed}/stdlib/_warnings.pyi | 0 mypy/{ => typeshed}/stdlib/_weakref.pyi | 0 mypy/{ => typeshed}/stdlib/_weakrefset.pyi | 0 mypy/{ => typeshed}/stdlib/_winapi.pyi | 0 mypy/{ => typeshed}/stdlib/abc.pyi | 0 mypy/{ => typeshed}/stdlib/aifc.pyi | 0 mypy/{ => typeshed}/stdlib/antigravity.pyi | 0 mypy/{ => typeshed}/stdlib/argparse.pyi | 0 mypy/{ => typeshed}/stdlib/array.pyi | 0 mypy/{ => typeshed}/stdlib/ast.pyi | 0 mypy/{ => typeshed}/stdlib/asynchat.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/base_events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/base_futures.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/base_subprocess.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/base_tasks.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/compat.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/constants.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/coroutines.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/exceptions.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/format_helpers.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/futures.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/locks.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/log.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/proactor_events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/protocols.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/queues.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/runners.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/selector_events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/sslproto.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/staggered.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/streams.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/subprocess.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/tasks.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/threads.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/transports.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/trsock.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/unix_events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/windows_events.pyi | 0 mypy/{ => typeshed}/stdlib/asyncio/windows_utils.pyi | 0 mypy/{ => typeshed}/stdlib/asyncore.pyi | 0 mypy/{ => typeshed}/stdlib/atexit.pyi | 0 mypy/{ => typeshed}/stdlib/audioop.pyi | 0 mypy/{ => typeshed}/stdlib/base64.pyi | 0 mypy/{ => typeshed}/stdlib/bdb.pyi | 0 mypy/{ => typeshed}/stdlib/binascii.pyi | 0 mypy/{ => typeshed}/stdlib/binhex.pyi | 0 mypy/{ => typeshed}/stdlib/bisect.pyi | 0 mypy/{ => typeshed}/stdlib/builtins.pyi | 0 mypy/{ => typeshed}/stdlib/bz2.pyi | 0 mypy/{ => typeshed}/stdlib/cProfile.pyi | 0 mypy/{ => typeshed}/stdlib/calendar.pyi | 0 mypy/{ => typeshed}/stdlib/cgi.pyi | 0 mypy/{ => typeshed}/stdlib/cgitb.pyi | 0 mypy/{ => typeshed}/stdlib/chunk.pyi | 0 mypy/{ => typeshed}/stdlib/cmath.pyi | 0 mypy/{ => typeshed}/stdlib/cmd.pyi | 0 mypy/{ => typeshed}/stdlib/code.pyi | 0 mypy/{ => typeshed}/stdlib/codecs.pyi | 0 mypy/{ => typeshed}/stdlib/codeop.pyi | 0 mypy/{ => typeshed}/stdlib/collections/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/collections/abc.pyi | 0 mypy/{ => typeshed}/stdlib/colorsys.pyi | 0 mypy/{ => typeshed}/stdlib/compileall.pyi | 0 mypy/{ => typeshed}/stdlib/concurrent/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/concurrent/futures/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/concurrent/futures/_base.pyi | 0 mypy/{ => typeshed}/stdlib/concurrent/futures/process.pyi | 0 mypy/{ => typeshed}/stdlib/concurrent/futures/thread.pyi | 0 mypy/{ => typeshed}/stdlib/configparser.pyi | 0 mypy/{ => typeshed}/stdlib/contextlib.pyi | 0 mypy/{ => typeshed}/stdlib/contextvars.pyi | 0 mypy/{ => typeshed}/stdlib/copy.pyi | 0 mypy/{ => typeshed}/stdlib/copyreg.pyi | 0 mypy/{ => typeshed}/stdlib/crypt.pyi | 0 mypy/{ => typeshed}/stdlib/csv.pyi | 0 mypy/{ => typeshed}/stdlib/ctypes/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/ctypes/util.pyi | 0 mypy/{ => typeshed}/stdlib/ctypes/wintypes.pyi | 0 mypy/{ => typeshed}/stdlib/curses/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/curses/ascii.pyi | 0 mypy/{ => typeshed}/stdlib/curses/panel.pyi | 0 mypy/{ => typeshed}/stdlib/curses/textpad.pyi | 0 mypy/{ => typeshed}/stdlib/dataclasses.pyi | 0 mypy/{ => typeshed}/stdlib/datetime.pyi | 0 mypy/{ => typeshed}/stdlib/dbm/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/dbm/dumb.pyi | 0 mypy/{ => typeshed}/stdlib/dbm/gnu.pyi | 0 mypy/{ => typeshed}/stdlib/dbm/ndbm.pyi | 0 mypy/{ => typeshed}/stdlib/decimal.pyi | 0 mypy/{ => typeshed}/stdlib/difflib.pyi | 0 mypy/{ => typeshed}/stdlib/dis.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/archive_util.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/bcppcompiler.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/ccompiler.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/cmd.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist_dumb.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist_msi.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist_packager.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist_rpm.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/bdist_wininst.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/build.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/build_clib.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/build_ext.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/build_py.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/build_scripts.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/check.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/clean.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/config.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/install.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/install_data.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/install_headers.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/install_lib.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/install_scripts.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/register.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/command/sdist.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/core.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/cygwinccompiler.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/debug.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/dep_util.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/dir_util.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/dist.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/errors.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/extension.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/fancy_getopt.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/file_util.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/filelist.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/log.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/msvccompiler.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/spawn.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/sysconfig.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/text_file.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/unixccompiler.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/util.pyi | 0 mypy/{ => typeshed}/stdlib/distutils/version.pyi | 0 mypy/{ => typeshed}/stdlib/doctest.pyi | 0 mypy/{ => typeshed}/stdlib/dummy_threading.pyi | 0 mypy/{ => typeshed}/stdlib/email/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/email/charset.pyi | 0 mypy/{ => typeshed}/stdlib/email/contentmanager.pyi | 0 mypy/{ => typeshed}/stdlib/email/encoders.pyi | 0 mypy/{ => typeshed}/stdlib/email/errors.pyi | 0 mypy/{ => typeshed}/stdlib/email/feedparser.pyi | 0 mypy/{ => typeshed}/stdlib/email/generator.pyi | 0 mypy/{ => typeshed}/stdlib/email/header.pyi | 0 mypy/{ => typeshed}/stdlib/email/headerregistry.pyi | 0 mypy/{ => typeshed}/stdlib/email/iterators.pyi | 0 mypy/{ => typeshed}/stdlib/email/message.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/application.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/audio.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/base.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/image.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/message.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/multipart.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/nonmultipart.pyi | 0 mypy/{ => typeshed}/stdlib/email/mime/text.pyi | 0 mypy/{ => typeshed}/stdlib/email/parser.pyi | 0 mypy/{ => typeshed}/stdlib/email/policy.pyi | 0 mypy/{ => typeshed}/stdlib/email/utils.pyi | 0 mypy/{ => typeshed}/stdlib/encodings/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/encodings/utf_8.pyi | 0 mypy/{ => typeshed}/stdlib/ensurepip/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/enum.pyi | 0 mypy/{ => typeshed}/stdlib/errno.pyi | 0 mypy/{ => typeshed}/stdlib/faulthandler.pyi | 0 mypy/{ => typeshed}/stdlib/fcntl.pyi | 0 mypy/{ => typeshed}/stdlib/filecmp.pyi | 0 mypy/{ => typeshed}/stdlib/fileinput.pyi | 0 mypy/{ => typeshed}/stdlib/fnmatch.pyi | 0 mypy/{ => typeshed}/stdlib/formatter.pyi | 0 mypy/{ => typeshed}/stdlib/fractions.pyi | 0 mypy/{ => typeshed}/stdlib/ftplib.pyi | 0 mypy/{ => typeshed}/stdlib/functools.pyi | 0 mypy/{ => typeshed}/stdlib/gc.pyi | 0 mypy/{ => typeshed}/stdlib/genericpath.pyi | 0 mypy/{ => typeshed}/stdlib/getopt.pyi | 0 mypy/{ => typeshed}/stdlib/getpass.pyi | 0 mypy/{ => typeshed}/stdlib/gettext.pyi | 0 mypy/{ => typeshed}/stdlib/glob.pyi | 0 mypy/{ => typeshed}/stdlib/grp.pyi | 0 mypy/{ => typeshed}/stdlib/gzip.pyi | 0 mypy/{ => typeshed}/stdlib/hashlib.pyi | 0 mypy/{ => typeshed}/stdlib/heapq.pyi | 0 mypy/{ => typeshed}/stdlib/hmac.pyi | 0 mypy/{ => typeshed}/stdlib/html/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/html/entities.pyi | 0 mypy/{ => typeshed}/stdlib/html/parser.pyi | 0 mypy/{ => typeshed}/stdlib/http/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/http/client.pyi | 0 mypy/{ => typeshed}/stdlib/http/cookiejar.pyi | 0 mypy/{ => typeshed}/stdlib/http/cookies.pyi | 0 mypy/{ => typeshed}/stdlib/http/server.pyi | 0 mypy/{ => typeshed}/stdlib/imaplib.pyi | 0 mypy/{ => typeshed}/stdlib/imghdr.pyi | 0 mypy/{ => typeshed}/stdlib/imp.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/abc.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/machinery.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/metadata.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/resources.pyi | 0 mypy/{ => typeshed}/stdlib/importlib/util.pyi | 0 mypy/{ => typeshed}/stdlib/inspect.pyi | 0 mypy/{ => typeshed}/stdlib/io.pyi | 0 mypy/{ => typeshed}/stdlib/ipaddress.pyi | 0 mypy/{ => typeshed}/stdlib/itertools.pyi | 0 mypy/{ => typeshed}/stdlib/json/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/json/decoder.pyi | 0 mypy/{ => typeshed}/stdlib/json/encoder.pyi | 0 mypy/{ => typeshed}/stdlib/keyword.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/driver.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/grammar.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/literals.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/parse.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/pgen.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/token.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pgen2/tokenize.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pygram.pyi | 0 mypy/{ => typeshed}/stdlib/lib2to3/pytree.pyi | 0 mypy/{ => typeshed}/stdlib/linecache.pyi | 0 mypy/{ => typeshed}/stdlib/locale.pyi | 0 mypy/{ => typeshed}/stdlib/logging/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/logging/config.pyi | 0 mypy/{ => typeshed}/stdlib/logging/handlers.pyi | 0 mypy/{ => typeshed}/stdlib/lzma.pyi | 0 mypy/{ => typeshed}/stdlib/macpath.pyi | 0 mypy/{ => typeshed}/stdlib/macurl2path.pyi | 0 mypy/{ => typeshed}/stdlib/mailbox.pyi | 0 mypy/{ => typeshed}/stdlib/mailcap.pyi | 0 mypy/{ => typeshed}/stdlib/marshal.pyi | 0 mypy/{ => typeshed}/stdlib/math.pyi | 0 mypy/{ => typeshed}/stdlib/mimetypes.pyi | 0 mypy/{ => typeshed}/stdlib/mmap.pyi | 0 mypy/{ => typeshed}/stdlib/modulefinder.pyi | 0 mypy/{ => typeshed}/stdlib/msilib/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/msilib/schema.pyi | 0 mypy/{ => typeshed}/stdlib/msilib/sequence.pyi | 0 mypy/{ => typeshed}/stdlib/msilib/text.pyi | 0 mypy/{ => typeshed}/stdlib/msvcrt.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/connection.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/context.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/dummy/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/dummy/connection.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/managers.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/pool.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/process.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/queues.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/shared_memory.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/spawn.pyi | 0 mypy/{ => typeshed}/stdlib/multiprocessing/synchronize.pyi | 0 mypy/{ => typeshed}/stdlib/netrc.pyi | 0 mypy/{ => typeshed}/stdlib/nis.pyi | 0 mypy/{ => typeshed}/stdlib/nntplib.pyi | 0 mypy/{ => typeshed}/stdlib/ntpath.pyi | 0 mypy/{ => typeshed}/stdlib/nturl2path.pyi | 0 mypy/{ => typeshed}/stdlib/numbers.pyi | 0 mypy/{ => typeshed}/stdlib/opcode.pyi | 0 mypy/{ => typeshed}/stdlib/operator.pyi | 0 mypy/{ => typeshed}/stdlib/optparse.pyi | 0 mypy/{ => typeshed}/stdlib/os/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/os/path.pyi | 0 mypy/{ => typeshed}/stdlib/parser.pyi | 0 mypy/{ => typeshed}/stdlib/pathlib.pyi | 0 mypy/{ => typeshed}/stdlib/pdb.pyi | 0 mypy/{ => typeshed}/stdlib/pickle.pyi | 0 mypy/{ => typeshed}/stdlib/pickletools.pyi | 0 mypy/{ => typeshed}/stdlib/pipes.pyi | 0 mypy/{ => typeshed}/stdlib/pkgutil.pyi | 0 mypy/{ => typeshed}/stdlib/platform.pyi | 0 mypy/{ => typeshed}/stdlib/plistlib.pyi | 0 mypy/{ => typeshed}/stdlib/poplib.pyi | 0 mypy/{ => typeshed}/stdlib/posix.pyi | 0 mypy/{ => typeshed}/stdlib/posixpath.pyi | 0 mypy/{ => typeshed}/stdlib/pprint.pyi | 0 mypy/{ => typeshed}/stdlib/profile.pyi | 0 mypy/{ => typeshed}/stdlib/pstats.pyi | 0 mypy/{ => typeshed}/stdlib/pty.pyi | 0 mypy/{ => typeshed}/stdlib/pwd.pyi | 0 mypy/{ => typeshed}/stdlib/py_compile.pyi | 0 mypy/{ => typeshed}/stdlib/pyclbr.pyi | 0 mypy/{ => typeshed}/stdlib/pydoc.pyi | 0 mypy/{ => typeshed}/stdlib/pyexpat/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/pyexpat/errors.pyi | 0 mypy/{ => typeshed}/stdlib/pyexpat/model.pyi | 0 mypy/{ => typeshed}/stdlib/python2/BaseHTTPServer.pyi | 0 mypy/{ => typeshed}/stdlib/python2/CGIHTTPServer.pyi | 0 mypy/{ => typeshed}/stdlib/python2/ConfigParser.pyi | 0 mypy/{ => typeshed}/stdlib/python2/Cookie.pyi | 0 mypy/{ => typeshed}/stdlib/python2/HTMLParser.pyi | 0 mypy/{ => typeshed}/stdlib/python2/Queue.pyi | 0 mypy/{ => typeshed}/stdlib/python2/SimpleHTTPServer.pyi | 0 mypy/{ => typeshed}/stdlib/python2/SocketServer.pyi | 0 mypy/{ => typeshed}/stdlib/python2/StringIO.pyi | 0 mypy/{ => typeshed}/stdlib/python2/UserDict.pyi | 0 mypy/{ => typeshed}/stdlib/python2/UserList.pyi | 0 mypy/{ => typeshed}/stdlib/python2/UserString.pyi | 0 mypy/{ => typeshed}/stdlib/python2/__builtin__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_ast.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_collections.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_functools.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_hotshot.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_io.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_json.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_md5.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_sha.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_sha256.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_sha512.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_socket.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_sre.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_struct.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_symtable.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_threading_local.pyi | 0 mypy/{ => typeshed}/stdlib/python2/_winreg.pyi | 0 mypy/{ => typeshed}/stdlib/python2/abc.pyi | 0 mypy/{ => typeshed}/stdlib/python2/ast.pyi | 0 mypy/{ => typeshed}/stdlib/python2/atexit.pyi | 0 mypy/{ => typeshed}/stdlib/python2/cPickle.pyi | 0 mypy/{ => typeshed}/stdlib/python2/cStringIO.pyi | 0 mypy/{ => typeshed}/stdlib/python2/collections.pyi | 0 mypy/{ => typeshed}/stdlib/python2/commands.pyi | 0 mypy/{ => typeshed}/stdlib/python2/compileall.pyi | 0 mypy/{ => typeshed}/stdlib/python2/cookielib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/copy_reg.pyi | 0 mypy/{ => typeshed}/stdlib/python2/dircache.pyi | 0 mypy/{ => typeshed}/stdlib/python2/distutils/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/distutils/emxccompiler.pyi | 0 mypy/{ => typeshed}/stdlib/python2/dummy_thread.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/MIMEText.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/_parseaddr.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/base64mime.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/charset.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/encoders.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/feedparser.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/generator.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/header.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/iterators.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/message.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/application.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/audio.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/base.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/image.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/message.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/multipart.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/nonmultipart.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/mime/text.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/parser.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/quoprimime.pyi | 0 mypy/{ => typeshed}/stdlib/python2/email/utils.pyi | 0 mypy/{ => typeshed}/stdlib/python2/encodings/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/encodings/utf_8.pyi | 0 mypy/{ => typeshed}/stdlib/python2/exceptions.pyi | 0 mypy/{ => typeshed}/stdlib/python2/fcntl.pyi | 0 mypy/{ => typeshed}/stdlib/python2/fnmatch.pyi | 0 mypy/{ => typeshed}/stdlib/python2/functools.pyi | 0 mypy/{ => typeshed}/stdlib/python2/future_builtins.pyi | 0 mypy/{ => typeshed}/stdlib/python2/gc.pyi | 0 mypy/{ => typeshed}/stdlib/python2/getopt.pyi | 0 mypy/{ => typeshed}/stdlib/python2/getpass.pyi | 0 mypy/{ => typeshed}/stdlib/python2/gettext.pyi | 0 mypy/{ => typeshed}/stdlib/python2/glob.pyi | 0 mypy/{ => typeshed}/stdlib/python2/gzip.pyi | 0 mypy/{ => typeshed}/stdlib/python2/hashlib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/heapq.pyi | 0 mypy/{ => typeshed}/stdlib/python2/htmlentitydefs.pyi | 0 mypy/{ => typeshed}/stdlib/python2/httplib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/imp.pyi | 0 mypy/{ => typeshed}/stdlib/python2/importlib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/inspect.pyi | 0 mypy/{ => typeshed}/stdlib/python2/io.pyi | 0 mypy/{ => typeshed}/stdlib/python2/itertools.pyi | 0 mypy/{ => typeshed}/stdlib/python2/json.pyi | 0 mypy/{ => typeshed}/stdlib/python2/markupbase.pyi | 0 mypy/{ => typeshed}/stdlib/python2/md5.pyi | 0 mypy/{ => typeshed}/stdlib/python2/mimetools.pyi | 0 mypy/{ => typeshed}/stdlib/python2/multiprocessing/__init__.pyi | 0 .../stdlib/python2/multiprocessing/dummy/__init__.pyi | 0 .../stdlib/python2/multiprocessing/dummy/connection.pyi | 0 mypy/{ => typeshed}/stdlib/python2/multiprocessing/pool.pyi | 0 mypy/{ => typeshed}/stdlib/python2/multiprocessing/process.pyi | 0 mypy/{ => typeshed}/stdlib/python2/multiprocessing/util.pyi | 0 mypy/{ => typeshed}/stdlib/python2/mutex.pyi | 0 mypy/{ => typeshed}/stdlib/python2/nturl2path.pyi | 0 mypy/{ => typeshed}/stdlib/python2/os/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/python2/os/path.pyi | 0 mypy/{ => typeshed}/stdlib/python2/os2emxpath.pyi | 0 mypy/{ => typeshed}/stdlib/python2/pipes.pyi | 0 mypy/{ => typeshed}/stdlib/python2/platform.pyi | 0 mypy/{ => typeshed}/stdlib/python2/popen2.pyi | 0 mypy/{ => typeshed}/stdlib/python2/posix.pyi | 0 mypy/{ => typeshed}/stdlib/python2/random.pyi | 0 mypy/{ => typeshed}/stdlib/python2/re.pyi | 0 mypy/{ => typeshed}/stdlib/python2/repr.pyi | 0 mypy/{ => typeshed}/stdlib/python2/resource.pyi | 0 mypy/{ => typeshed}/stdlib/python2/rfc822.pyi | 0 mypy/{ => typeshed}/stdlib/python2/robotparser.pyi | 0 mypy/{ => typeshed}/stdlib/python2/runpy.pyi | 0 mypy/{ => typeshed}/stdlib/python2/sets.pyi | 0 mypy/{ => typeshed}/stdlib/python2/sha.pyi | 0 mypy/{ => typeshed}/stdlib/python2/shelve.pyi | 0 mypy/{ => typeshed}/stdlib/python2/shlex.pyi | 0 mypy/{ => typeshed}/stdlib/python2/signal.pyi | 0 mypy/{ => typeshed}/stdlib/python2/smtplib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/spwd.pyi | 0 mypy/{ => typeshed}/stdlib/python2/sre_constants.pyi | 0 mypy/{ => typeshed}/stdlib/python2/sre_parse.pyi | 0 mypy/{ => typeshed}/stdlib/python2/stat.pyi | 0 mypy/{ => typeshed}/stdlib/python2/string.pyi | 0 mypy/{ => typeshed}/stdlib/python2/stringold.pyi | 0 mypy/{ => typeshed}/stdlib/python2/strop.pyi | 0 mypy/{ => typeshed}/stdlib/python2/subprocess.pyi | 0 mypy/{ => typeshed}/stdlib/python2/symbol.pyi | 0 mypy/{ => typeshed}/stdlib/python2/sys.pyi | 0 mypy/{ => typeshed}/stdlib/python2/tempfile.pyi | 0 mypy/{ => typeshed}/stdlib/python2/textwrap.pyi | 0 mypy/{ => typeshed}/stdlib/python2/thread.pyi | 0 mypy/{ => typeshed}/stdlib/python2/toaiff.pyi | 0 mypy/{ => typeshed}/stdlib/python2/tokenize.pyi | 0 mypy/{ => typeshed}/stdlib/python2/types.pyi | 0 mypy/{ => typeshed}/stdlib/python2/typing.pyi | 0 mypy/{ => typeshed}/stdlib/python2/unittest.pyi | 0 mypy/{ => typeshed}/stdlib/python2/urllib.pyi | 0 mypy/{ => typeshed}/stdlib/python2/urllib2.pyi | 0 mypy/{ => typeshed}/stdlib/python2/urlparse.pyi | 0 mypy/{ => typeshed}/stdlib/python2/user.pyi | 0 mypy/{ => typeshed}/stdlib/python2/whichdb.pyi | 0 mypy/{ => typeshed}/stdlib/python2/xmlrpclib.pyi | 0 mypy/{ => typeshed}/stdlib/queue.pyi | 0 mypy/{ => typeshed}/stdlib/quopri.pyi | 0 mypy/{ => typeshed}/stdlib/random.pyi | 0 mypy/{ => typeshed}/stdlib/re.pyi | 0 mypy/{ => typeshed}/stdlib/readline.pyi | 0 mypy/{ => typeshed}/stdlib/reprlib.pyi | 0 mypy/{ => typeshed}/stdlib/resource.pyi | 0 mypy/{ => typeshed}/stdlib/rlcompleter.pyi | 0 mypy/{ => typeshed}/stdlib/runpy.pyi | 0 mypy/{ => typeshed}/stdlib/sched.pyi | 0 mypy/{ => typeshed}/stdlib/secrets.pyi | 0 mypy/{ => typeshed}/stdlib/select.pyi | 0 mypy/{ => typeshed}/stdlib/selectors.pyi | 0 mypy/{ => typeshed}/stdlib/shelve.pyi | 0 mypy/{ => typeshed}/stdlib/shlex.pyi | 0 mypy/{ => typeshed}/stdlib/shutil.pyi | 0 mypy/{ => typeshed}/stdlib/signal.pyi | 0 mypy/{ => typeshed}/stdlib/site.pyi | 0 mypy/{ => typeshed}/stdlib/smtpd.pyi | 0 mypy/{ => typeshed}/stdlib/smtplib.pyi | 0 mypy/{ => typeshed}/stdlib/sndhdr.pyi | 0 mypy/{ => typeshed}/stdlib/socket.pyi | 0 mypy/{ => typeshed}/stdlib/socketserver.pyi | 0 mypy/{ => typeshed}/stdlib/spwd.pyi | 0 mypy/{ => typeshed}/stdlib/sqlite3/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/sqlite3/dbapi2.pyi | 0 mypy/{ => typeshed}/stdlib/sre_compile.pyi | 0 mypy/{ => typeshed}/stdlib/sre_constants.pyi | 0 mypy/{ => typeshed}/stdlib/sre_parse.pyi | 0 mypy/{ => typeshed}/stdlib/ssl.pyi | 0 mypy/{ => typeshed}/stdlib/stat.pyi | 0 mypy/{ => typeshed}/stdlib/statistics.pyi | 0 mypy/{ => typeshed}/stdlib/string.pyi | 0 mypy/{ => typeshed}/stdlib/stringprep.pyi | 0 mypy/{ => typeshed}/stdlib/struct.pyi | 0 mypy/{ => typeshed}/stdlib/subprocess.pyi | 0 mypy/{ => typeshed}/stdlib/sunau.pyi | 0 mypy/{ => typeshed}/stdlib/symbol.pyi | 0 mypy/{ => typeshed}/stdlib/symtable.pyi | 0 mypy/{ => typeshed}/stdlib/sys.pyi | 0 mypy/{ => typeshed}/stdlib/sysconfig.pyi | 0 mypy/{ => typeshed}/stdlib/syslog.pyi | 0 mypy/{ => typeshed}/stdlib/tabnanny.pyi | 0 mypy/{ => typeshed}/stdlib/tarfile.pyi | 0 mypy/{ => typeshed}/stdlib/telnetlib.pyi | 0 mypy/{ => typeshed}/stdlib/tempfile.pyi | 0 mypy/{ => typeshed}/stdlib/termios.pyi | 0 mypy/{ => typeshed}/stdlib/textwrap.pyi | 0 mypy/{ => typeshed}/stdlib/this.pyi | 0 mypy/{ => typeshed}/stdlib/threading.pyi | 0 mypy/{ => typeshed}/stdlib/time.pyi | 0 mypy/{ => typeshed}/stdlib/timeit.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/commondialog.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/constants.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/dialog.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/filedialog.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/messagebox.pyi | 0 mypy/{ => typeshed}/stdlib/tkinter/ttk.pyi | 0 mypy/{ => typeshed}/stdlib/token.pyi | 0 mypy/{ => typeshed}/stdlib/tokenize.pyi | 0 mypy/{ => typeshed}/stdlib/trace.pyi | 0 mypy/{ => typeshed}/stdlib/traceback.pyi | 0 mypy/{ => typeshed}/stdlib/tracemalloc.pyi | 0 mypy/{ => typeshed}/stdlib/tty.pyi | 0 mypy/{ => typeshed}/stdlib/turtle.pyi | 0 mypy/{ => typeshed}/stdlib/types.pyi | 0 mypy/{ => typeshed}/stdlib/typing.pyi | 0 mypy/{ => typeshed}/stdlib/unicodedata.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/async_case.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/case.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/loader.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/main.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/mock.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/result.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/runner.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/signals.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/suite.pyi | 0 mypy/{ => typeshed}/stdlib/unittest/util.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/error.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/parse.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/request.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/response.pyi | 0 mypy/{ => typeshed}/stdlib/urllib/robotparser.pyi | 0 mypy/{ => typeshed}/stdlib/uu.pyi | 0 mypy/{ => typeshed}/stdlib/uuid.pyi | 0 mypy/{ => typeshed}/stdlib/venv/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/warnings.pyi | 0 mypy/{ => typeshed}/stdlib/wave.pyi | 0 mypy/{ => typeshed}/stdlib/weakref.pyi | 0 mypy/{ => typeshed}/stdlib/webbrowser.pyi | 0 mypy/{ => typeshed}/stdlib/winreg.pyi | 0 mypy/{ => typeshed}/stdlib/winsound.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/handlers.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/headers.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/simple_server.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/types.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/util.pyi | 0 mypy/{ => typeshed}/stdlib/wsgiref/validate.pyi | 0 mypy/{ => typeshed}/stdlib/xdrlib.pyi | 0 mypy/{ => typeshed}/stdlib/xml/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/dom/NodeFilter.pyi | 0 mypy/{ => typeshed}/stdlib/xml/dom/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/dom/minidom.pyi | 0 mypy/{ => typeshed}/stdlib/xml/dom/pulldom.pyi | 0 mypy/{ => typeshed}/stdlib/xml/etree/ElementInclude.pyi | 0 mypy/{ => typeshed}/stdlib/xml/etree/ElementPath.pyi | 0 mypy/{ => typeshed}/stdlib/xml/etree/ElementTree.pyi | 0 mypy/{ => typeshed}/stdlib/xml/etree/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/etree/cElementTree.pyi | 0 mypy/{ => typeshed}/stdlib/xml/parsers/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/parsers/expat/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/parsers/expat/errors.pyi | 0 mypy/{ => typeshed}/stdlib/xml/parsers/expat/model.pyi | 0 mypy/{ => typeshed}/stdlib/xml/sax/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xml/sax/handler.pyi | 0 mypy/{ => typeshed}/stdlib/xml/sax/saxutils.pyi | 0 mypy/{ => typeshed}/stdlib/xml/sax/xmlreader.pyi | 0 mypy/{ => typeshed}/stdlib/xmlrpc/__init__.pyi | 0 mypy/{ => typeshed}/stdlib/xmlrpc/client.pyi | 0 mypy/{ => typeshed}/stdlib/xmlrpc/server.pyi | 0 mypy/{ => typeshed}/stdlib/zipapp.pyi | 0 mypy/{ => typeshed}/stdlib/zipfile.pyi | 0 mypy/{ => typeshed}/stdlib/zipimport.pyi | 0 mypy/{ => typeshed}/stdlib/zlib.pyi | 0 mypy/{ => typeshed}/stdlib/zoneinfo/__init__.pyi | 0 596 files changed, 0 insertions(+), 0 deletions(-) rename mypy/{ => typeshed}/stdlib/VERSIONS (100%) rename mypy/{ => typeshed}/stdlib/__future__.pyi (100%) rename mypy/{ => typeshed}/stdlib/_ast.pyi (100%) rename mypy/{ => typeshed}/stdlib/_bisect.pyi (100%) rename mypy/{ => typeshed}/stdlib/_bootlocale.pyi (100%) rename mypy/{ => typeshed}/stdlib/_codecs.pyi (100%) rename mypy/{ => typeshed}/stdlib/_compat_pickle.pyi (100%) rename mypy/{ => typeshed}/stdlib/_compression.pyi (100%) rename mypy/{ => typeshed}/stdlib/_csv.pyi (100%) rename mypy/{ => typeshed}/stdlib/_curses.pyi (100%) rename mypy/{ => typeshed}/stdlib/_decimal.pyi (100%) rename mypy/{ => typeshed}/stdlib/_dummy_thread.pyi (100%) rename mypy/{ => typeshed}/stdlib/_dummy_threading.pyi (100%) rename mypy/{ => typeshed}/stdlib/_heapq.pyi (100%) rename mypy/{ => typeshed}/stdlib/_imp.pyi (100%) rename mypy/{ => typeshed}/stdlib/_importlib_modulespec.pyi (100%) rename mypy/{ => typeshed}/stdlib/_json.pyi (100%) rename mypy/{ => typeshed}/stdlib/_markupbase.pyi (100%) rename mypy/{ => typeshed}/stdlib/_msi.pyi (100%) rename mypy/{ => typeshed}/stdlib/_operator.pyi (100%) rename mypy/{ => typeshed}/stdlib/_osx_support.pyi (100%) rename mypy/{ => typeshed}/stdlib/_posixsubprocess.pyi (100%) rename mypy/{ => typeshed}/stdlib/_py_abc.pyi (100%) rename mypy/{ => typeshed}/stdlib/_pydecimal.pyi (100%) rename mypy/{ => typeshed}/stdlib/_random.pyi (100%) rename mypy/{ => typeshed}/stdlib/_sitebuiltins.pyi (100%) rename mypy/{ => typeshed}/stdlib/_stat.pyi (100%) rename mypy/{ => typeshed}/stdlib/_thread.pyi (100%) rename mypy/{ => typeshed}/stdlib/_threading_local.pyi (100%) rename mypy/{ => typeshed}/stdlib/_tracemalloc.pyi (100%) rename mypy/{ => typeshed}/stdlib/_typeshed/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/_typeshed/wsgi.pyi (100%) rename mypy/{ => typeshed}/stdlib/_warnings.pyi (100%) rename mypy/{ => typeshed}/stdlib/_weakref.pyi (100%) rename mypy/{ => typeshed}/stdlib/_weakrefset.pyi (100%) rename mypy/{ => typeshed}/stdlib/_winapi.pyi (100%) rename mypy/{ => typeshed}/stdlib/abc.pyi (100%) rename mypy/{ => typeshed}/stdlib/aifc.pyi (100%) rename mypy/{ => typeshed}/stdlib/antigravity.pyi (100%) rename mypy/{ => typeshed}/stdlib/argparse.pyi (100%) rename mypy/{ => typeshed}/stdlib/array.pyi (100%) rename mypy/{ => typeshed}/stdlib/ast.pyi (100%) rename mypy/{ => typeshed}/stdlib/asynchat.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/base_events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/base_futures.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/base_subprocess.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/base_tasks.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/compat.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/constants.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/coroutines.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/exceptions.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/format_helpers.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/futures.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/locks.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/log.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/proactor_events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/protocols.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/queues.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/runners.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/selector_events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/sslproto.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/staggered.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/streams.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/subprocess.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/tasks.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/threads.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/transports.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/trsock.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/unix_events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/windows_events.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncio/windows_utils.pyi (100%) rename mypy/{ => typeshed}/stdlib/asyncore.pyi (100%) rename mypy/{ => typeshed}/stdlib/atexit.pyi (100%) rename mypy/{ => typeshed}/stdlib/audioop.pyi (100%) rename mypy/{ => typeshed}/stdlib/base64.pyi (100%) rename mypy/{ => typeshed}/stdlib/bdb.pyi (100%) rename mypy/{ => typeshed}/stdlib/binascii.pyi (100%) rename mypy/{ => typeshed}/stdlib/binhex.pyi (100%) rename mypy/{ => typeshed}/stdlib/bisect.pyi (100%) rename mypy/{ => typeshed}/stdlib/builtins.pyi (100%) rename mypy/{ => typeshed}/stdlib/bz2.pyi (100%) rename mypy/{ => typeshed}/stdlib/cProfile.pyi (100%) rename mypy/{ => typeshed}/stdlib/calendar.pyi (100%) rename mypy/{ => typeshed}/stdlib/cgi.pyi (100%) rename mypy/{ => typeshed}/stdlib/cgitb.pyi (100%) rename mypy/{ => typeshed}/stdlib/chunk.pyi (100%) rename mypy/{ => typeshed}/stdlib/cmath.pyi (100%) rename mypy/{ => typeshed}/stdlib/cmd.pyi (100%) rename mypy/{ => typeshed}/stdlib/code.pyi (100%) rename mypy/{ => typeshed}/stdlib/codecs.pyi (100%) rename mypy/{ => typeshed}/stdlib/codeop.pyi (100%) rename mypy/{ => typeshed}/stdlib/collections/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/collections/abc.pyi (100%) rename mypy/{ => typeshed}/stdlib/colorsys.pyi (100%) rename mypy/{ => typeshed}/stdlib/compileall.pyi (100%) rename mypy/{ => typeshed}/stdlib/concurrent/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/concurrent/futures/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/concurrent/futures/_base.pyi (100%) rename mypy/{ => typeshed}/stdlib/concurrent/futures/process.pyi (100%) rename mypy/{ => typeshed}/stdlib/concurrent/futures/thread.pyi (100%) rename mypy/{ => typeshed}/stdlib/configparser.pyi (100%) rename mypy/{ => typeshed}/stdlib/contextlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/contextvars.pyi (100%) rename mypy/{ => typeshed}/stdlib/copy.pyi (100%) rename mypy/{ => typeshed}/stdlib/copyreg.pyi (100%) rename mypy/{ => typeshed}/stdlib/crypt.pyi (100%) rename mypy/{ => typeshed}/stdlib/csv.pyi (100%) rename mypy/{ => typeshed}/stdlib/ctypes/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/ctypes/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/ctypes/wintypes.pyi (100%) rename mypy/{ => typeshed}/stdlib/curses/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/curses/ascii.pyi (100%) rename mypy/{ => typeshed}/stdlib/curses/panel.pyi (100%) rename mypy/{ => typeshed}/stdlib/curses/textpad.pyi (100%) rename mypy/{ => typeshed}/stdlib/dataclasses.pyi (100%) rename mypy/{ => typeshed}/stdlib/datetime.pyi (100%) rename mypy/{ => typeshed}/stdlib/dbm/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/dbm/dumb.pyi (100%) rename mypy/{ => typeshed}/stdlib/dbm/gnu.pyi (100%) rename mypy/{ => typeshed}/stdlib/dbm/ndbm.pyi (100%) rename mypy/{ => typeshed}/stdlib/decimal.pyi (100%) rename mypy/{ => typeshed}/stdlib/difflib.pyi (100%) rename mypy/{ => typeshed}/stdlib/dis.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/archive_util.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/bcppcompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/ccompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/cmd.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist_dumb.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist_msi.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist_packager.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist_rpm.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/bdist_wininst.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/build.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/build_clib.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/build_ext.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/build_py.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/build_scripts.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/check.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/clean.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/config.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/install.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/install_data.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/install_headers.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/install_lib.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/install_scripts.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/register.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/command/sdist.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/core.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/cygwinccompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/debug.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/dep_util.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/dir_util.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/dist.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/errors.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/extension.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/fancy_getopt.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/file_util.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/filelist.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/log.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/msvccompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/spawn.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/sysconfig.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/text_file.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/unixccompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/distutils/version.pyi (100%) rename mypy/{ => typeshed}/stdlib/doctest.pyi (100%) rename mypy/{ => typeshed}/stdlib/dummy_threading.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/charset.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/contentmanager.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/encoders.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/errors.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/feedparser.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/generator.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/header.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/headerregistry.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/iterators.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/message.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/application.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/audio.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/base.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/image.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/message.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/multipart.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/nonmultipart.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/mime/text.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/parser.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/policy.pyi (100%) rename mypy/{ => typeshed}/stdlib/email/utils.pyi (100%) rename mypy/{ => typeshed}/stdlib/encodings/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/encodings/utf_8.pyi (100%) rename mypy/{ => typeshed}/stdlib/ensurepip/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/enum.pyi (100%) rename mypy/{ => typeshed}/stdlib/errno.pyi (100%) rename mypy/{ => typeshed}/stdlib/faulthandler.pyi (100%) rename mypy/{ => typeshed}/stdlib/fcntl.pyi (100%) rename mypy/{ => typeshed}/stdlib/filecmp.pyi (100%) rename mypy/{ => typeshed}/stdlib/fileinput.pyi (100%) rename mypy/{ => typeshed}/stdlib/fnmatch.pyi (100%) rename mypy/{ => typeshed}/stdlib/formatter.pyi (100%) rename mypy/{ => typeshed}/stdlib/fractions.pyi (100%) rename mypy/{ => typeshed}/stdlib/ftplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/functools.pyi (100%) rename mypy/{ => typeshed}/stdlib/gc.pyi (100%) rename mypy/{ => typeshed}/stdlib/genericpath.pyi (100%) rename mypy/{ => typeshed}/stdlib/getopt.pyi (100%) rename mypy/{ => typeshed}/stdlib/getpass.pyi (100%) rename mypy/{ => typeshed}/stdlib/gettext.pyi (100%) rename mypy/{ => typeshed}/stdlib/glob.pyi (100%) rename mypy/{ => typeshed}/stdlib/grp.pyi (100%) rename mypy/{ => typeshed}/stdlib/gzip.pyi (100%) rename mypy/{ => typeshed}/stdlib/hashlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/heapq.pyi (100%) rename mypy/{ => typeshed}/stdlib/hmac.pyi (100%) rename mypy/{ => typeshed}/stdlib/html/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/html/entities.pyi (100%) rename mypy/{ => typeshed}/stdlib/html/parser.pyi (100%) rename mypy/{ => typeshed}/stdlib/http/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/http/client.pyi (100%) rename mypy/{ => typeshed}/stdlib/http/cookiejar.pyi (100%) rename mypy/{ => typeshed}/stdlib/http/cookies.pyi (100%) rename mypy/{ => typeshed}/stdlib/http/server.pyi (100%) rename mypy/{ => typeshed}/stdlib/imaplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/imghdr.pyi (100%) rename mypy/{ => typeshed}/stdlib/imp.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/abc.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/machinery.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/metadata.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/resources.pyi (100%) rename mypy/{ => typeshed}/stdlib/importlib/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/inspect.pyi (100%) rename mypy/{ => typeshed}/stdlib/io.pyi (100%) rename mypy/{ => typeshed}/stdlib/ipaddress.pyi (100%) rename mypy/{ => typeshed}/stdlib/itertools.pyi (100%) rename mypy/{ => typeshed}/stdlib/json/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/json/decoder.pyi (100%) rename mypy/{ => typeshed}/stdlib/json/encoder.pyi (100%) rename mypy/{ => typeshed}/stdlib/keyword.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/driver.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/grammar.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/literals.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/parse.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/pgen.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/token.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pgen2/tokenize.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pygram.pyi (100%) rename mypy/{ => typeshed}/stdlib/lib2to3/pytree.pyi (100%) rename mypy/{ => typeshed}/stdlib/linecache.pyi (100%) rename mypy/{ => typeshed}/stdlib/locale.pyi (100%) rename mypy/{ => typeshed}/stdlib/logging/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/logging/config.pyi (100%) rename mypy/{ => typeshed}/stdlib/logging/handlers.pyi (100%) rename mypy/{ => typeshed}/stdlib/lzma.pyi (100%) rename mypy/{ => typeshed}/stdlib/macpath.pyi (100%) rename mypy/{ => typeshed}/stdlib/macurl2path.pyi (100%) rename mypy/{ => typeshed}/stdlib/mailbox.pyi (100%) rename mypy/{ => typeshed}/stdlib/mailcap.pyi (100%) rename mypy/{ => typeshed}/stdlib/marshal.pyi (100%) rename mypy/{ => typeshed}/stdlib/math.pyi (100%) rename mypy/{ => typeshed}/stdlib/mimetypes.pyi (100%) rename mypy/{ => typeshed}/stdlib/mmap.pyi (100%) rename mypy/{ => typeshed}/stdlib/modulefinder.pyi (100%) rename mypy/{ => typeshed}/stdlib/msilib/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/msilib/schema.pyi (100%) rename mypy/{ => typeshed}/stdlib/msilib/sequence.pyi (100%) rename mypy/{ => typeshed}/stdlib/msilib/text.pyi (100%) rename mypy/{ => typeshed}/stdlib/msvcrt.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/connection.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/context.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/dummy/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/dummy/connection.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/managers.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/pool.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/process.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/queues.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/shared_memory.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/spawn.pyi (100%) rename mypy/{ => typeshed}/stdlib/multiprocessing/synchronize.pyi (100%) rename mypy/{ => typeshed}/stdlib/netrc.pyi (100%) rename mypy/{ => typeshed}/stdlib/nis.pyi (100%) rename mypy/{ => typeshed}/stdlib/nntplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/ntpath.pyi (100%) rename mypy/{ => typeshed}/stdlib/nturl2path.pyi (100%) rename mypy/{ => typeshed}/stdlib/numbers.pyi (100%) rename mypy/{ => typeshed}/stdlib/opcode.pyi (100%) rename mypy/{ => typeshed}/stdlib/operator.pyi (100%) rename mypy/{ => typeshed}/stdlib/optparse.pyi (100%) rename mypy/{ => typeshed}/stdlib/os/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/os/path.pyi (100%) rename mypy/{ => typeshed}/stdlib/parser.pyi (100%) rename mypy/{ => typeshed}/stdlib/pathlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/pdb.pyi (100%) rename mypy/{ => typeshed}/stdlib/pickle.pyi (100%) rename mypy/{ => typeshed}/stdlib/pickletools.pyi (100%) rename mypy/{ => typeshed}/stdlib/pipes.pyi (100%) rename mypy/{ => typeshed}/stdlib/pkgutil.pyi (100%) rename mypy/{ => typeshed}/stdlib/platform.pyi (100%) rename mypy/{ => typeshed}/stdlib/plistlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/poplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/posix.pyi (100%) rename mypy/{ => typeshed}/stdlib/posixpath.pyi (100%) rename mypy/{ => typeshed}/stdlib/pprint.pyi (100%) rename mypy/{ => typeshed}/stdlib/profile.pyi (100%) rename mypy/{ => typeshed}/stdlib/pstats.pyi (100%) rename mypy/{ => typeshed}/stdlib/pty.pyi (100%) rename mypy/{ => typeshed}/stdlib/pwd.pyi (100%) rename mypy/{ => typeshed}/stdlib/py_compile.pyi (100%) rename mypy/{ => typeshed}/stdlib/pyclbr.pyi (100%) rename mypy/{ => typeshed}/stdlib/pydoc.pyi (100%) rename mypy/{ => typeshed}/stdlib/pyexpat/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/pyexpat/errors.pyi (100%) rename mypy/{ => typeshed}/stdlib/pyexpat/model.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/BaseHTTPServer.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/CGIHTTPServer.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/ConfigParser.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/Cookie.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/HTMLParser.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/Queue.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/SimpleHTTPServer.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/SocketServer.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/StringIO.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/UserDict.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/UserList.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/UserString.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/__builtin__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_ast.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_collections.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_functools.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_hotshot.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_io.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_json.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_md5.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_sha.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_sha256.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_sha512.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_socket.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_sre.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_struct.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_symtable.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_threading_local.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/_winreg.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/abc.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/ast.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/atexit.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/cPickle.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/cStringIO.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/collections.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/commands.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/compileall.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/cookielib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/copy_reg.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/dircache.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/distutils/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/distutils/emxccompiler.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/dummy_thread.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/MIMEText.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/_parseaddr.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/base64mime.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/charset.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/encoders.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/feedparser.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/generator.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/header.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/iterators.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/message.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/application.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/audio.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/base.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/image.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/message.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/multipart.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/nonmultipart.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/mime/text.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/parser.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/quoprimime.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/email/utils.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/encodings/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/encodings/utf_8.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/exceptions.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/fcntl.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/fnmatch.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/functools.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/future_builtins.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/gc.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/getopt.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/getpass.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/gettext.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/glob.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/gzip.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/hashlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/heapq.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/htmlentitydefs.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/httplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/imp.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/importlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/inspect.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/io.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/itertools.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/json.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/markupbase.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/md5.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/mimetools.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/dummy/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/dummy/connection.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/pool.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/process.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/multiprocessing/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/mutex.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/nturl2path.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/os/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/os/path.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/os2emxpath.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/pipes.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/platform.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/popen2.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/posix.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/random.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/re.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/repr.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/resource.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/rfc822.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/robotparser.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/runpy.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/sets.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/sha.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/shelve.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/shlex.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/signal.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/smtplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/spwd.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/sre_constants.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/sre_parse.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/stat.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/string.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/stringold.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/strop.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/subprocess.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/symbol.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/sys.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/tempfile.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/textwrap.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/thread.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/toaiff.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/tokenize.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/types.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/typing.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/unittest.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/urllib.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/urllib2.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/urlparse.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/user.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/whichdb.pyi (100%) rename mypy/{ => typeshed}/stdlib/python2/xmlrpclib.pyi (100%) rename mypy/{ => typeshed}/stdlib/queue.pyi (100%) rename mypy/{ => typeshed}/stdlib/quopri.pyi (100%) rename mypy/{ => typeshed}/stdlib/random.pyi (100%) rename mypy/{ => typeshed}/stdlib/re.pyi (100%) rename mypy/{ => typeshed}/stdlib/readline.pyi (100%) rename mypy/{ => typeshed}/stdlib/reprlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/resource.pyi (100%) rename mypy/{ => typeshed}/stdlib/rlcompleter.pyi (100%) rename mypy/{ => typeshed}/stdlib/runpy.pyi (100%) rename mypy/{ => typeshed}/stdlib/sched.pyi (100%) rename mypy/{ => typeshed}/stdlib/secrets.pyi (100%) rename mypy/{ => typeshed}/stdlib/select.pyi (100%) rename mypy/{ => typeshed}/stdlib/selectors.pyi (100%) rename mypy/{ => typeshed}/stdlib/shelve.pyi (100%) rename mypy/{ => typeshed}/stdlib/shlex.pyi (100%) rename mypy/{ => typeshed}/stdlib/shutil.pyi (100%) rename mypy/{ => typeshed}/stdlib/signal.pyi (100%) rename mypy/{ => typeshed}/stdlib/site.pyi (100%) rename mypy/{ => typeshed}/stdlib/smtpd.pyi (100%) rename mypy/{ => typeshed}/stdlib/smtplib.pyi (100%) rename mypy/{ => typeshed}/stdlib/sndhdr.pyi (100%) rename mypy/{ => typeshed}/stdlib/socket.pyi (100%) rename mypy/{ => typeshed}/stdlib/socketserver.pyi (100%) rename mypy/{ => typeshed}/stdlib/spwd.pyi (100%) rename mypy/{ => typeshed}/stdlib/sqlite3/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/sqlite3/dbapi2.pyi (100%) rename mypy/{ => typeshed}/stdlib/sre_compile.pyi (100%) rename mypy/{ => typeshed}/stdlib/sre_constants.pyi (100%) rename mypy/{ => typeshed}/stdlib/sre_parse.pyi (100%) rename mypy/{ => typeshed}/stdlib/ssl.pyi (100%) rename mypy/{ => typeshed}/stdlib/stat.pyi (100%) rename mypy/{ => typeshed}/stdlib/statistics.pyi (100%) rename mypy/{ => typeshed}/stdlib/string.pyi (100%) rename mypy/{ => typeshed}/stdlib/stringprep.pyi (100%) rename mypy/{ => typeshed}/stdlib/struct.pyi (100%) rename mypy/{ => typeshed}/stdlib/subprocess.pyi (100%) rename mypy/{ => typeshed}/stdlib/sunau.pyi (100%) rename mypy/{ => typeshed}/stdlib/symbol.pyi (100%) rename mypy/{ => typeshed}/stdlib/symtable.pyi (100%) rename mypy/{ => typeshed}/stdlib/sys.pyi (100%) rename mypy/{ => typeshed}/stdlib/sysconfig.pyi (100%) rename mypy/{ => typeshed}/stdlib/syslog.pyi (100%) rename mypy/{ => typeshed}/stdlib/tabnanny.pyi (100%) rename mypy/{ => typeshed}/stdlib/tarfile.pyi (100%) rename mypy/{ => typeshed}/stdlib/telnetlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/tempfile.pyi (100%) rename mypy/{ => typeshed}/stdlib/termios.pyi (100%) rename mypy/{ => typeshed}/stdlib/textwrap.pyi (100%) rename mypy/{ => typeshed}/stdlib/this.pyi (100%) rename mypy/{ => typeshed}/stdlib/threading.pyi (100%) rename mypy/{ => typeshed}/stdlib/time.pyi (100%) rename mypy/{ => typeshed}/stdlib/timeit.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/commondialog.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/constants.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/dialog.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/filedialog.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/messagebox.pyi (100%) rename mypy/{ => typeshed}/stdlib/tkinter/ttk.pyi (100%) rename mypy/{ => typeshed}/stdlib/token.pyi (100%) rename mypy/{ => typeshed}/stdlib/tokenize.pyi (100%) rename mypy/{ => typeshed}/stdlib/trace.pyi (100%) rename mypy/{ => typeshed}/stdlib/traceback.pyi (100%) rename mypy/{ => typeshed}/stdlib/tracemalloc.pyi (100%) rename mypy/{ => typeshed}/stdlib/tty.pyi (100%) rename mypy/{ => typeshed}/stdlib/turtle.pyi (100%) rename mypy/{ => typeshed}/stdlib/types.pyi (100%) rename mypy/{ => typeshed}/stdlib/typing.pyi (100%) rename mypy/{ => typeshed}/stdlib/unicodedata.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/async_case.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/case.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/loader.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/main.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/mock.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/result.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/runner.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/signals.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/suite.pyi (100%) rename mypy/{ => typeshed}/stdlib/unittest/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/error.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/parse.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/request.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/response.pyi (100%) rename mypy/{ => typeshed}/stdlib/urllib/robotparser.pyi (100%) rename mypy/{ => typeshed}/stdlib/uu.pyi (100%) rename mypy/{ => typeshed}/stdlib/uuid.pyi (100%) rename mypy/{ => typeshed}/stdlib/venv/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/warnings.pyi (100%) rename mypy/{ => typeshed}/stdlib/wave.pyi (100%) rename mypy/{ => typeshed}/stdlib/weakref.pyi (100%) rename mypy/{ => typeshed}/stdlib/webbrowser.pyi (100%) rename mypy/{ => typeshed}/stdlib/winreg.pyi (100%) rename mypy/{ => typeshed}/stdlib/winsound.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/handlers.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/headers.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/simple_server.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/types.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/util.pyi (100%) rename mypy/{ => typeshed}/stdlib/wsgiref/validate.pyi (100%) rename mypy/{ => typeshed}/stdlib/xdrlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/dom/NodeFilter.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/dom/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/dom/minidom.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/dom/pulldom.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/etree/ElementInclude.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/etree/ElementPath.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/etree/ElementTree.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/etree/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/etree/cElementTree.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/parsers/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/parsers/expat/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/parsers/expat/errors.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/parsers/expat/model.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/sax/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/sax/handler.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/sax/saxutils.pyi (100%) rename mypy/{ => typeshed}/stdlib/xml/sax/xmlreader.pyi (100%) rename mypy/{ => typeshed}/stdlib/xmlrpc/__init__.pyi (100%) rename mypy/{ => typeshed}/stdlib/xmlrpc/client.pyi (100%) rename mypy/{ => typeshed}/stdlib/xmlrpc/server.pyi (100%) rename mypy/{ => typeshed}/stdlib/zipapp.pyi (100%) rename mypy/{ => typeshed}/stdlib/zipfile.pyi (100%) rename mypy/{ => typeshed}/stdlib/zipimport.pyi (100%) rename mypy/{ => typeshed}/stdlib/zlib.pyi (100%) rename mypy/{ => typeshed}/stdlib/zoneinfo/__init__.pyi (100%) diff --git a/mypy/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS similarity index 100% rename from mypy/stdlib/VERSIONS rename to mypy/typeshed/stdlib/VERSIONS diff --git a/mypy/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi similarity index 100% rename from mypy/stdlib/__future__.pyi rename to mypy/typeshed/stdlib/__future__.pyi diff --git a/mypy/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi similarity index 100% rename from mypy/stdlib/_ast.pyi rename to mypy/typeshed/stdlib/_ast.pyi diff --git a/mypy/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi similarity index 100% rename from mypy/stdlib/_bisect.pyi rename to mypy/typeshed/stdlib/_bisect.pyi diff --git a/mypy/stdlib/_bootlocale.pyi b/mypy/typeshed/stdlib/_bootlocale.pyi similarity index 100% rename from mypy/stdlib/_bootlocale.pyi rename to mypy/typeshed/stdlib/_bootlocale.pyi diff --git a/mypy/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi similarity index 100% rename from mypy/stdlib/_codecs.pyi rename to mypy/typeshed/stdlib/_codecs.pyi diff --git a/mypy/stdlib/_compat_pickle.pyi b/mypy/typeshed/stdlib/_compat_pickle.pyi similarity index 100% rename from mypy/stdlib/_compat_pickle.pyi rename to mypy/typeshed/stdlib/_compat_pickle.pyi diff --git a/mypy/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi similarity index 100% rename from mypy/stdlib/_compression.pyi rename to mypy/typeshed/stdlib/_compression.pyi diff --git a/mypy/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi similarity index 100% rename from mypy/stdlib/_csv.pyi rename to mypy/typeshed/stdlib/_csv.pyi diff --git a/mypy/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi similarity index 100% rename from mypy/stdlib/_curses.pyi rename to mypy/typeshed/stdlib/_curses.pyi diff --git a/mypy/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi similarity index 100% rename from mypy/stdlib/_decimal.pyi rename to mypy/typeshed/stdlib/_decimal.pyi diff --git a/mypy/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi similarity index 100% rename from mypy/stdlib/_dummy_thread.pyi rename to mypy/typeshed/stdlib/_dummy_thread.pyi diff --git a/mypy/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi similarity index 100% rename from mypy/stdlib/_dummy_threading.pyi rename to mypy/typeshed/stdlib/_dummy_threading.pyi diff --git a/mypy/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi similarity index 100% rename from mypy/stdlib/_heapq.pyi rename to mypy/typeshed/stdlib/_heapq.pyi diff --git a/mypy/stdlib/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi similarity index 100% rename from mypy/stdlib/_imp.pyi rename to mypy/typeshed/stdlib/_imp.pyi diff --git a/mypy/stdlib/_importlib_modulespec.pyi b/mypy/typeshed/stdlib/_importlib_modulespec.pyi similarity index 100% rename from mypy/stdlib/_importlib_modulespec.pyi rename to mypy/typeshed/stdlib/_importlib_modulespec.pyi diff --git a/mypy/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi similarity index 100% rename from mypy/stdlib/_json.pyi rename to mypy/typeshed/stdlib/_json.pyi diff --git a/mypy/stdlib/_markupbase.pyi b/mypy/typeshed/stdlib/_markupbase.pyi similarity index 100% rename from mypy/stdlib/_markupbase.pyi rename to mypy/typeshed/stdlib/_markupbase.pyi diff --git a/mypy/stdlib/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi similarity index 100% rename from mypy/stdlib/_msi.pyi rename to mypy/typeshed/stdlib/_msi.pyi diff --git a/mypy/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi similarity index 100% rename from mypy/stdlib/_operator.pyi rename to mypy/typeshed/stdlib/_operator.pyi diff --git a/mypy/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi similarity index 100% rename from mypy/stdlib/_osx_support.pyi rename to mypy/typeshed/stdlib/_osx_support.pyi diff --git a/mypy/stdlib/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi similarity index 100% rename from mypy/stdlib/_posixsubprocess.pyi rename to mypy/typeshed/stdlib/_posixsubprocess.pyi diff --git a/mypy/stdlib/_py_abc.pyi b/mypy/typeshed/stdlib/_py_abc.pyi similarity index 100% rename from mypy/stdlib/_py_abc.pyi rename to mypy/typeshed/stdlib/_py_abc.pyi diff --git a/mypy/stdlib/_pydecimal.pyi b/mypy/typeshed/stdlib/_pydecimal.pyi similarity index 100% rename from mypy/stdlib/_pydecimal.pyi rename to mypy/typeshed/stdlib/_pydecimal.pyi diff --git a/mypy/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi similarity index 100% rename from mypy/stdlib/_random.pyi rename to mypy/typeshed/stdlib/_random.pyi diff --git a/mypy/stdlib/_sitebuiltins.pyi b/mypy/typeshed/stdlib/_sitebuiltins.pyi similarity index 100% rename from mypy/stdlib/_sitebuiltins.pyi rename to mypy/typeshed/stdlib/_sitebuiltins.pyi diff --git a/mypy/stdlib/_stat.pyi b/mypy/typeshed/stdlib/_stat.pyi similarity index 100% rename from mypy/stdlib/_stat.pyi rename to mypy/typeshed/stdlib/_stat.pyi diff --git a/mypy/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi similarity index 100% rename from mypy/stdlib/_thread.pyi rename to mypy/typeshed/stdlib/_thread.pyi diff --git a/mypy/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi similarity index 100% rename from mypy/stdlib/_threading_local.pyi rename to mypy/typeshed/stdlib/_threading_local.pyi diff --git a/mypy/stdlib/_tracemalloc.pyi b/mypy/typeshed/stdlib/_tracemalloc.pyi similarity index 100% rename from mypy/stdlib/_tracemalloc.pyi rename to mypy/typeshed/stdlib/_tracemalloc.pyi diff --git a/mypy/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi similarity index 100% rename from mypy/stdlib/_typeshed/__init__.pyi rename to mypy/typeshed/stdlib/_typeshed/__init__.pyi diff --git a/mypy/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi similarity index 100% rename from mypy/stdlib/_typeshed/wsgi.pyi rename to mypy/typeshed/stdlib/_typeshed/wsgi.pyi diff --git a/mypy/stdlib/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi similarity index 100% rename from mypy/stdlib/_warnings.pyi rename to mypy/typeshed/stdlib/_warnings.pyi diff --git a/mypy/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi similarity index 100% rename from mypy/stdlib/_weakref.pyi rename to mypy/typeshed/stdlib/_weakref.pyi diff --git a/mypy/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi similarity index 100% rename from mypy/stdlib/_weakrefset.pyi rename to mypy/typeshed/stdlib/_weakrefset.pyi diff --git a/mypy/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi similarity index 100% rename from mypy/stdlib/_winapi.pyi rename to mypy/typeshed/stdlib/_winapi.pyi diff --git a/mypy/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi similarity index 100% rename from mypy/stdlib/abc.pyi rename to mypy/typeshed/stdlib/abc.pyi diff --git a/mypy/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi similarity index 100% rename from mypy/stdlib/aifc.pyi rename to mypy/typeshed/stdlib/aifc.pyi diff --git a/mypy/stdlib/antigravity.pyi b/mypy/typeshed/stdlib/antigravity.pyi similarity index 100% rename from mypy/stdlib/antigravity.pyi rename to mypy/typeshed/stdlib/antigravity.pyi diff --git a/mypy/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi similarity index 100% rename from mypy/stdlib/argparse.pyi rename to mypy/typeshed/stdlib/argparse.pyi diff --git a/mypy/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi similarity index 100% rename from mypy/stdlib/array.pyi rename to mypy/typeshed/stdlib/array.pyi diff --git a/mypy/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi similarity index 100% rename from mypy/stdlib/ast.pyi rename to mypy/typeshed/stdlib/ast.pyi diff --git a/mypy/stdlib/asynchat.pyi b/mypy/typeshed/stdlib/asynchat.pyi similarity index 100% rename from mypy/stdlib/asynchat.pyi rename to mypy/typeshed/stdlib/asynchat.pyi diff --git a/mypy/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi similarity index 100% rename from mypy/stdlib/asyncio/__init__.pyi rename to mypy/typeshed/stdlib/asyncio/__init__.pyi diff --git a/mypy/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi similarity index 100% rename from mypy/stdlib/asyncio/base_events.pyi rename to mypy/typeshed/stdlib/asyncio/base_events.pyi diff --git a/mypy/stdlib/asyncio/base_futures.pyi b/mypy/typeshed/stdlib/asyncio/base_futures.pyi similarity index 100% rename from mypy/stdlib/asyncio/base_futures.pyi rename to mypy/typeshed/stdlib/asyncio/base_futures.pyi diff --git a/mypy/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi similarity index 100% rename from mypy/stdlib/asyncio/base_subprocess.pyi rename to mypy/typeshed/stdlib/asyncio/base_subprocess.pyi diff --git a/mypy/stdlib/asyncio/base_tasks.pyi b/mypy/typeshed/stdlib/asyncio/base_tasks.pyi similarity index 100% rename from mypy/stdlib/asyncio/base_tasks.pyi rename to mypy/typeshed/stdlib/asyncio/base_tasks.pyi diff --git a/mypy/stdlib/asyncio/compat.pyi b/mypy/typeshed/stdlib/asyncio/compat.pyi similarity index 100% rename from mypy/stdlib/asyncio/compat.pyi rename to mypy/typeshed/stdlib/asyncio/compat.pyi diff --git a/mypy/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi similarity index 100% rename from mypy/stdlib/asyncio/constants.pyi rename to mypy/typeshed/stdlib/asyncio/constants.pyi diff --git a/mypy/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi similarity index 100% rename from mypy/stdlib/asyncio/coroutines.pyi rename to mypy/typeshed/stdlib/asyncio/coroutines.pyi diff --git a/mypy/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi similarity index 100% rename from mypy/stdlib/asyncio/events.pyi rename to mypy/typeshed/stdlib/asyncio/events.pyi diff --git a/mypy/stdlib/asyncio/exceptions.pyi b/mypy/typeshed/stdlib/asyncio/exceptions.pyi similarity index 100% rename from mypy/stdlib/asyncio/exceptions.pyi rename to mypy/typeshed/stdlib/asyncio/exceptions.pyi diff --git a/mypy/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi similarity index 100% rename from mypy/stdlib/asyncio/format_helpers.pyi rename to mypy/typeshed/stdlib/asyncio/format_helpers.pyi diff --git a/mypy/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi similarity index 100% rename from mypy/stdlib/asyncio/futures.pyi rename to mypy/typeshed/stdlib/asyncio/futures.pyi diff --git a/mypy/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi similarity index 100% rename from mypy/stdlib/asyncio/locks.pyi rename to mypy/typeshed/stdlib/asyncio/locks.pyi diff --git a/mypy/stdlib/asyncio/log.pyi b/mypy/typeshed/stdlib/asyncio/log.pyi similarity index 100% rename from mypy/stdlib/asyncio/log.pyi rename to mypy/typeshed/stdlib/asyncio/log.pyi diff --git a/mypy/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi similarity index 100% rename from mypy/stdlib/asyncio/proactor_events.pyi rename to mypy/typeshed/stdlib/asyncio/proactor_events.pyi diff --git a/mypy/stdlib/asyncio/protocols.pyi b/mypy/typeshed/stdlib/asyncio/protocols.pyi similarity index 100% rename from mypy/stdlib/asyncio/protocols.pyi rename to mypy/typeshed/stdlib/asyncio/protocols.pyi diff --git a/mypy/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi similarity index 100% rename from mypy/stdlib/asyncio/queues.pyi rename to mypy/typeshed/stdlib/asyncio/queues.pyi diff --git a/mypy/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi similarity index 100% rename from mypy/stdlib/asyncio/runners.pyi rename to mypy/typeshed/stdlib/asyncio/runners.pyi diff --git a/mypy/stdlib/asyncio/selector_events.pyi b/mypy/typeshed/stdlib/asyncio/selector_events.pyi similarity index 100% rename from mypy/stdlib/asyncio/selector_events.pyi rename to mypy/typeshed/stdlib/asyncio/selector_events.pyi diff --git a/mypy/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi similarity index 100% rename from mypy/stdlib/asyncio/sslproto.pyi rename to mypy/typeshed/stdlib/asyncio/sslproto.pyi diff --git a/mypy/stdlib/asyncio/staggered.pyi b/mypy/typeshed/stdlib/asyncio/staggered.pyi similarity index 100% rename from mypy/stdlib/asyncio/staggered.pyi rename to mypy/typeshed/stdlib/asyncio/staggered.pyi diff --git a/mypy/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi similarity index 100% rename from mypy/stdlib/asyncio/streams.pyi rename to mypy/typeshed/stdlib/asyncio/streams.pyi diff --git a/mypy/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi similarity index 100% rename from mypy/stdlib/asyncio/subprocess.pyi rename to mypy/typeshed/stdlib/asyncio/subprocess.pyi diff --git a/mypy/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi similarity index 100% rename from mypy/stdlib/asyncio/tasks.pyi rename to mypy/typeshed/stdlib/asyncio/tasks.pyi diff --git a/mypy/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi similarity index 100% rename from mypy/stdlib/asyncio/threads.pyi rename to mypy/typeshed/stdlib/asyncio/threads.pyi diff --git a/mypy/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi similarity index 100% rename from mypy/stdlib/asyncio/transports.pyi rename to mypy/typeshed/stdlib/asyncio/transports.pyi diff --git a/mypy/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi similarity index 100% rename from mypy/stdlib/asyncio/trsock.pyi rename to mypy/typeshed/stdlib/asyncio/trsock.pyi diff --git a/mypy/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi similarity index 100% rename from mypy/stdlib/asyncio/unix_events.pyi rename to mypy/typeshed/stdlib/asyncio/unix_events.pyi diff --git a/mypy/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi similarity index 100% rename from mypy/stdlib/asyncio/windows_events.pyi rename to mypy/typeshed/stdlib/asyncio/windows_events.pyi diff --git a/mypy/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi similarity index 100% rename from mypy/stdlib/asyncio/windows_utils.pyi rename to mypy/typeshed/stdlib/asyncio/windows_utils.pyi diff --git a/mypy/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi similarity index 100% rename from mypy/stdlib/asyncore.pyi rename to mypy/typeshed/stdlib/asyncore.pyi diff --git a/mypy/stdlib/atexit.pyi b/mypy/typeshed/stdlib/atexit.pyi similarity index 100% rename from mypy/stdlib/atexit.pyi rename to mypy/typeshed/stdlib/atexit.pyi diff --git a/mypy/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi similarity index 100% rename from mypy/stdlib/audioop.pyi rename to mypy/typeshed/stdlib/audioop.pyi diff --git a/mypy/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi similarity index 100% rename from mypy/stdlib/base64.pyi rename to mypy/typeshed/stdlib/base64.pyi diff --git a/mypy/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi similarity index 100% rename from mypy/stdlib/bdb.pyi rename to mypy/typeshed/stdlib/bdb.pyi diff --git a/mypy/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi similarity index 100% rename from mypy/stdlib/binascii.pyi rename to mypy/typeshed/stdlib/binascii.pyi diff --git a/mypy/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi similarity index 100% rename from mypy/stdlib/binhex.pyi rename to mypy/typeshed/stdlib/binhex.pyi diff --git a/mypy/stdlib/bisect.pyi b/mypy/typeshed/stdlib/bisect.pyi similarity index 100% rename from mypy/stdlib/bisect.pyi rename to mypy/typeshed/stdlib/bisect.pyi diff --git a/mypy/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi similarity index 100% rename from mypy/stdlib/builtins.pyi rename to mypy/typeshed/stdlib/builtins.pyi diff --git a/mypy/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi similarity index 100% rename from mypy/stdlib/bz2.pyi rename to mypy/typeshed/stdlib/bz2.pyi diff --git a/mypy/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi similarity index 100% rename from mypy/stdlib/cProfile.pyi rename to mypy/typeshed/stdlib/cProfile.pyi diff --git a/mypy/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi similarity index 100% rename from mypy/stdlib/calendar.pyi rename to mypy/typeshed/stdlib/calendar.pyi diff --git a/mypy/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi similarity index 100% rename from mypy/stdlib/cgi.pyi rename to mypy/typeshed/stdlib/cgi.pyi diff --git a/mypy/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi similarity index 100% rename from mypy/stdlib/cgitb.pyi rename to mypy/typeshed/stdlib/cgitb.pyi diff --git a/mypy/stdlib/chunk.pyi b/mypy/typeshed/stdlib/chunk.pyi similarity index 100% rename from mypy/stdlib/chunk.pyi rename to mypy/typeshed/stdlib/chunk.pyi diff --git a/mypy/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi similarity index 100% rename from mypy/stdlib/cmath.pyi rename to mypy/typeshed/stdlib/cmath.pyi diff --git a/mypy/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi similarity index 100% rename from mypy/stdlib/cmd.pyi rename to mypy/typeshed/stdlib/cmd.pyi diff --git a/mypy/stdlib/code.pyi b/mypy/typeshed/stdlib/code.pyi similarity index 100% rename from mypy/stdlib/code.pyi rename to mypy/typeshed/stdlib/code.pyi diff --git a/mypy/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi similarity index 100% rename from mypy/stdlib/codecs.pyi rename to mypy/typeshed/stdlib/codecs.pyi diff --git a/mypy/stdlib/codeop.pyi b/mypy/typeshed/stdlib/codeop.pyi similarity index 100% rename from mypy/stdlib/codeop.pyi rename to mypy/typeshed/stdlib/codeop.pyi diff --git a/mypy/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi similarity index 100% rename from mypy/stdlib/collections/__init__.pyi rename to mypy/typeshed/stdlib/collections/__init__.pyi diff --git a/mypy/stdlib/collections/abc.pyi b/mypy/typeshed/stdlib/collections/abc.pyi similarity index 100% rename from mypy/stdlib/collections/abc.pyi rename to mypy/typeshed/stdlib/collections/abc.pyi diff --git a/mypy/stdlib/colorsys.pyi b/mypy/typeshed/stdlib/colorsys.pyi similarity index 100% rename from mypy/stdlib/colorsys.pyi rename to mypy/typeshed/stdlib/colorsys.pyi diff --git a/mypy/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi similarity index 100% rename from mypy/stdlib/compileall.pyi rename to mypy/typeshed/stdlib/compileall.pyi diff --git a/mypy/stdlib/concurrent/__init__.pyi b/mypy/typeshed/stdlib/concurrent/__init__.pyi similarity index 100% rename from mypy/stdlib/concurrent/__init__.pyi rename to mypy/typeshed/stdlib/concurrent/__init__.pyi diff --git a/mypy/stdlib/concurrent/futures/__init__.pyi b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi similarity index 100% rename from mypy/stdlib/concurrent/futures/__init__.pyi rename to mypy/typeshed/stdlib/concurrent/futures/__init__.pyi diff --git a/mypy/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi similarity index 100% rename from mypy/stdlib/concurrent/futures/_base.pyi rename to mypy/typeshed/stdlib/concurrent/futures/_base.pyi diff --git a/mypy/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi similarity index 100% rename from mypy/stdlib/concurrent/futures/process.pyi rename to mypy/typeshed/stdlib/concurrent/futures/process.pyi diff --git a/mypy/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi similarity index 100% rename from mypy/stdlib/concurrent/futures/thread.pyi rename to mypy/typeshed/stdlib/concurrent/futures/thread.pyi diff --git a/mypy/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi similarity index 100% rename from mypy/stdlib/configparser.pyi rename to mypy/typeshed/stdlib/configparser.pyi diff --git a/mypy/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi similarity index 100% rename from mypy/stdlib/contextlib.pyi rename to mypy/typeshed/stdlib/contextlib.pyi diff --git a/mypy/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi similarity index 100% rename from mypy/stdlib/contextvars.pyi rename to mypy/typeshed/stdlib/contextvars.pyi diff --git a/mypy/stdlib/copy.pyi b/mypy/typeshed/stdlib/copy.pyi similarity index 100% rename from mypy/stdlib/copy.pyi rename to mypy/typeshed/stdlib/copy.pyi diff --git a/mypy/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi similarity index 100% rename from mypy/stdlib/copyreg.pyi rename to mypy/typeshed/stdlib/copyreg.pyi diff --git a/mypy/stdlib/crypt.pyi b/mypy/typeshed/stdlib/crypt.pyi similarity index 100% rename from mypy/stdlib/crypt.pyi rename to mypy/typeshed/stdlib/crypt.pyi diff --git a/mypy/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi similarity index 100% rename from mypy/stdlib/csv.pyi rename to mypy/typeshed/stdlib/csv.pyi diff --git a/mypy/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi similarity index 100% rename from mypy/stdlib/ctypes/__init__.pyi rename to mypy/typeshed/stdlib/ctypes/__init__.pyi diff --git a/mypy/stdlib/ctypes/util.pyi b/mypy/typeshed/stdlib/ctypes/util.pyi similarity index 100% rename from mypy/stdlib/ctypes/util.pyi rename to mypy/typeshed/stdlib/ctypes/util.pyi diff --git a/mypy/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi similarity index 100% rename from mypy/stdlib/ctypes/wintypes.pyi rename to mypy/typeshed/stdlib/ctypes/wintypes.pyi diff --git a/mypy/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi similarity index 100% rename from mypy/stdlib/curses/__init__.pyi rename to mypy/typeshed/stdlib/curses/__init__.pyi diff --git a/mypy/stdlib/curses/ascii.pyi b/mypy/typeshed/stdlib/curses/ascii.pyi similarity index 100% rename from mypy/stdlib/curses/ascii.pyi rename to mypy/typeshed/stdlib/curses/ascii.pyi diff --git a/mypy/stdlib/curses/panel.pyi b/mypy/typeshed/stdlib/curses/panel.pyi similarity index 100% rename from mypy/stdlib/curses/panel.pyi rename to mypy/typeshed/stdlib/curses/panel.pyi diff --git a/mypy/stdlib/curses/textpad.pyi b/mypy/typeshed/stdlib/curses/textpad.pyi similarity index 100% rename from mypy/stdlib/curses/textpad.pyi rename to mypy/typeshed/stdlib/curses/textpad.pyi diff --git a/mypy/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi similarity index 100% rename from mypy/stdlib/dataclasses.pyi rename to mypy/typeshed/stdlib/dataclasses.pyi diff --git a/mypy/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi similarity index 100% rename from mypy/stdlib/datetime.pyi rename to mypy/typeshed/stdlib/datetime.pyi diff --git a/mypy/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi similarity index 100% rename from mypy/stdlib/dbm/__init__.pyi rename to mypy/typeshed/stdlib/dbm/__init__.pyi diff --git a/mypy/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi similarity index 100% rename from mypy/stdlib/dbm/dumb.pyi rename to mypy/typeshed/stdlib/dbm/dumb.pyi diff --git a/mypy/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi similarity index 100% rename from mypy/stdlib/dbm/gnu.pyi rename to mypy/typeshed/stdlib/dbm/gnu.pyi diff --git a/mypy/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi similarity index 100% rename from mypy/stdlib/dbm/ndbm.pyi rename to mypy/typeshed/stdlib/dbm/ndbm.pyi diff --git a/mypy/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi similarity index 100% rename from mypy/stdlib/decimal.pyi rename to mypy/typeshed/stdlib/decimal.pyi diff --git a/mypy/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi similarity index 100% rename from mypy/stdlib/difflib.pyi rename to mypy/typeshed/stdlib/difflib.pyi diff --git a/mypy/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi similarity index 100% rename from mypy/stdlib/dis.pyi rename to mypy/typeshed/stdlib/dis.pyi diff --git a/mypy/stdlib/distutils/__init__.pyi b/mypy/typeshed/stdlib/distutils/__init__.pyi similarity index 100% rename from mypy/stdlib/distutils/__init__.pyi rename to mypy/typeshed/stdlib/distutils/__init__.pyi diff --git a/mypy/stdlib/distutils/archive_util.pyi b/mypy/typeshed/stdlib/distutils/archive_util.pyi similarity index 100% rename from mypy/stdlib/distutils/archive_util.pyi rename to mypy/typeshed/stdlib/distutils/archive_util.pyi diff --git a/mypy/stdlib/distutils/bcppcompiler.pyi b/mypy/typeshed/stdlib/distutils/bcppcompiler.pyi similarity index 100% rename from mypy/stdlib/distutils/bcppcompiler.pyi rename to mypy/typeshed/stdlib/distutils/bcppcompiler.pyi diff --git a/mypy/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi similarity index 100% rename from mypy/stdlib/distutils/ccompiler.pyi rename to mypy/typeshed/stdlib/distutils/ccompiler.pyi diff --git a/mypy/stdlib/distutils/cmd.pyi b/mypy/typeshed/stdlib/distutils/cmd.pyi similarity index 100% rename from mypy/stdlib/distutils/cmd.pyi rename to mypy/typeshed/stdlib/distutils/cmd.pyi diff --git a/mypy/stdlib/distutils/command/__init__.pyi b/mypy/typeshed/stdlib/distutils/command/__init__.pyi similarity index 100% rename from mypy/stdlib/distutils/command/__init__.pyi rename to mypy/typeshed/stdlib/distutils/command/__init__.pyi diff --git a/mypy/stdlib/distutils/command/bdist.pyi b/mypy/typeshed/stdlib/distutils/command/bdist.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist.pyi diff --git a/mypy/stdlib/distutils/command/bdist_dumb.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist_dumb.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi diff --git a/mypy/stdlib/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist_msi.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi diff --git a/mypy/stdlib/distutils/command/bdist_packager.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist_packager.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi diff --git a/mypy/stdlib/distutils/command/bdist_rpm.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist_rpm.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi diff --git a/mypy/stdlib/distutils/command/bdist_wininst.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi similarity index 100% rename from mypy/stdlib/distutils/command/bdist_wininst.pyi rename to mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi diff --git a/mypy/stdlib/distutils/command/build.pyi b/mypy/typeshed/stdlib/distutils/command/build.pyi similarity index 100% rename from mypy/stdlib/distutils/command/build.pyi rename to mypy/typeshed/stdlib/distutils/command/build.pyi diff --git a/mypy/stdlib/distutils/command/build_clib.pyi b/mypy/typeshed/stdlib/distutils/command/build_clib.pyi similarity index 100% rename from mypy/stdlib/distutils/command/build_clib.pyi rename to mypy/typeshed/stdlib/distutils/command/build_clib.pyi diff --git a/mypy/stdlib/distutils/command/build_ext.pyi b/mypy/typeshed/stdlib/distutils/command/build_ext.pyi similarity index 100% rename from mypy/stdlib/distutils/command/build_ext.pyi rename to mypy/typeshed/stdlib/distutils/command/build_ext.pyi diff --git a/mypy/stdlib/distutils/command/build_py.pyi b/mypy/typeshed/stdlib/distutils/command/build_py.pyi similarity index 100% rename from mypy/stdlib/distutils/command/build_py.pyi rename to mypy/typeshed/stdlib/distutils/command/build_py.pyi diff --git a/mypy/stdlib/distutils/command/build_scripts.pyi b/mypy/typeshed/stdlib/distutils/command/build_scripts.pyi similarity index 100% rename from mypy/stdlib/distutils/command/build_scripts.pyi rename to mypy/typeshed/stdlib/distutils/command/build_scripts.pyi diff --git a/mypy/stdlib/distutils/command/check.pyi b/mypy/typeshed/stdlib/distutils/command/check.pyi similarity index 100% rename from mypy/stdlib/distutils/command/check.pyi rename to mypy/typeshed/stdlib/distutils/command/check.pyi diff --git a/mypy/stdlib/distutils/command/clean.pyi b/mypy/typeshed/stdlib/distutils/command/clean.pyi similarity index 100% rename from mypy/stdlib/distutils/command/clean.pyi rename to mypy/typeshed/stdlib/distutils/command/clean.pyi diff --git a/mypy/stdlib/distutils/command/config.pyi b/mypy/typeshed/stdlib/distutils/command/config.pyi similarity index 100% rename from mypy/stdlib/distutils/command/config.pyi rename to mypy/typeshed/stdlib/distutils/command/config.pyi diff --git a/mypy/stdlib/distutils/command/install.pyi b/mypy/typeshed/stdlib/distutils/command/install.pyi similarity index 100% rename from mypy/stdlib/distutils/command/install.pyi rename to mypy/typeshed/stdlib/distutils/command/install.pyi diff --git a/mypy/stdlib/distutils/command/install_data.pyi b/mypy/typeshed/stdlib/distutils/command/install_data.pyi similarity index 100% rename from mypy/stdlib/distutils/command/install_data.pyi rename to mypy/typeshed/stdlib/distutils/command/install_data.pyi diff --git a/mypy/stdlib/distutils/command/install_headers.pyi b/mypy/typeshed/stdlib/distutils/command/install_headers.pyi similarity index 100% rename from mypy/stdlib/distutils/command/install_headers.pyi rename to mypy/typeshed/stdlib/distutils/command/install_headers.pyi diff --git a/mypy/stdlib/distutils/command/install_lib.pyi b/mypy/typeshed/stdlib/distutils/command/install_lib.pyi similarity index 100% rename from mypy/stdlib/distutils/command/install_lib.pyi rename to mypy/typeshed/stdlib/distutils/command/install_lib.pyi diff --git a/mypy/stdlib/distutils/command/install_scripts.pyi b/mypy/typeshed/stdlib/distutils/command/install_scripts.pyi similarity index 100% rename from mypy/stdlib/distutils/command/install_scripts.pyi rename to mypy/typeshed/stdlib/distutils/command/install_scripts.pyi diff --git a/mypy/stdlib/distutils/command/register.pyi b/mypy/typeshed/stdlib/distutils/command/register.pyi similarity index 100% rename from mypy/stdlib/distutils/command/register.pyi rename to mypy/typeshed/stdlib/distutils/command/register.pyi diff --git a/mypy/stdlib/distutils/command/sdist.pyi b/mypy/typeshed/stdlib/distutils/command/sdist.pyi similarity index 100% rename from mypy/stdlib/distutils/command/sdist.pyi rename to mypy/typeshed/stdlib/distutils/command/sdist.pyi diff --git a/mypy/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi similarity index 100% rename from mypy/stdlib/distutils/core.pyi rename to mypy/typeshed/stdlib/distutils/core.pyi diff --git a/mypy/stdlib/distutils/cygwinccompiler.pyi b/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi similarity index 100% rename from mypy/stdlib/distutils/cygwinccompiler.pyi rename to mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi diff --git a/mypy/stdlib/distutils/debug.pyi b/mypy/typeshed/stdlib/distutils/debug.pyi similarity index 100% rename from mypy/stdlib/distutils/debug.pyi rename to mypy/typeshed/stdlib/distutils/debug.pyi diff --git a/mypy/stdlib/distutils/dep_util.pyi b/mypy/typeshed/stdlib/distutils/dep_util.pyi similarity index 100% rename from mypy/stdlib/distutils/dep_util.pyi rename to mypy/typeshed/stdlib/distutils/dep_util.pyi diff --git a/mypy/stdlib/distutils/dir_util.pyi b/mypy/typeshed/stdlib/distutils/dir_util.pyi similarity index 100% rename from mypy/stdlib/distutils/dir_util.pyi rename to mypy/typeshed/stdlib/distutils/dir_util.pyi diff --git a/mypy/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi similarity index 100% rename from mypy/stdlib/distutils/dist.pyi rename to mypy/typeshed/stdlib/distutils/dist.pyi diff --git a/mypy/stdlib/distutils/errors.pyi b/mypy/typeshed/stdlib/distutils/errors.pyi similarity index 100% rename from mypy/stdlib/distutils/errors.pyi rename to mypy/typeshed/stdlib/distutils/errors.pyi diff --git a/mypy/stdlib/distutils/extension.pyi b/mypy/typeshed/stdlib/distutils/extension.pyi similarity index 100% rename from mypy/stdlib/distutils/extension.pyi rename to mypy/typeshed/stdlib/distutils/extension.pyi diff --git a/mypy/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi similarity index 100% rename from mypy/stdlib/distutils/fancy_getopt.pyi rename to mypy/typeshed/stdlib/distutils/fancy_getopt.pyi diff --git a/mypy/stdlib/distutils/file_util.pyi b/mypy/typeshed/stdlib/distutils/file_util.pyi similarity index 100% rename from mypy/stdlib/distutils/file_util.pyi rename to mypy/typeshed/stdlib/distutils/file_util.pyi diff --git a/mypy/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi similarity index 100% rename from mypy/stdlib/distutils/filelist.pyi rename to mypy/typeshed/stdlib/distutils/filelist.pyi diff --git a/mypy/stdlib/distutils/log.pyi b/mypy/typeshed/stdlib/distutils/log.pyi similarity index 100% rename from mypy/stdlib/distutils/log.pyi rename to mypy/typeshed/stdlib/distutils/log.pyi diff --git a/mypy/stdlib/distutils/msvccompiler.pyi b/mypy/typeshed/stdlib/distutils/msvccompiler.pyi similarity index 100% rename from mypy/stdlib/distutils/msvccompiler.pyi rename to mypy/typeshed/stdlib/distutils/msvccompiler.pyi diff --git a/mypy/stdlib/distutils/spawn.pyi b/mypy/typeshed/stdlib/distutils/spawn.pyi similarity index 100% rename from mypy/stdlib/distutils/spawn.pyi rename to mypy/typeshed/stdlib/distutils/spawn.pyi diff --git a/mypy/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi similarity index 100% rename from mypy/stdlib/distutils/sysconfig.pyi rename to mypy/typeshed/stdlib/distutils/sysconfig.pyi diff --git a/mypy/stdlib/distutils/text_file.pyi b/mypy/typeshed/stdlib/distutils/text_file.pyi similarity index 100% rename from mypy/stdlib/distutils/text_file.pyi rename to mypy/typeshed/stdlib/distutils/text_file.pyi diff --git a/mypy/stdlib/distutils/unixccompiler.pyi b/mypy/typeshed/stdlib/distutils/unixccompiler.pyi similarity index 100% rename from mypy/stdlib/distutils/unixccompiler.pyi rename to mypy/typeshed/stdlib/distutils/unixccompiler.pyi diff --git a/mypy/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi similarity index 100% rename from mypy/stdlib/distutils/util.pyi rename to mypy/typeshed/stdlib/distutils/util.pyi diff --git a/mypy/stdlib/distutils/version.pyi b/mypy/typeshed/stdlib/distutils/version.pyi similarity index 100% rename from mypy/stdlib/distutils/version.pyi rename to mypy/typeshed/stdlib/distutils/version.pyi diff --git a/mypy/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi similarity index 100% rename from mypy/stdlib/doctest.pyi rename to mypy/typeshed/stdlib/doctest.pyi diff --git a/mypy/stdlib/dummy_threading.pyi b/mypy/typeshed/stdlib/dummy_threading.pyi similarity index 100% rename from mypy/stdlib/dummy_threading.pyi rename to mypy/typeshed/stdlib/dummy_threading.pyi diff --git a/mypy/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi similarity index 100% rename from mypy/stdlib/email/__init__.pyi rename to mypy/typeshed/stdlib/email/__init__.pyi diff --git a/mypy/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi similarity index 100% rename from mypy/stdlib/email/charset.pyi rename to mypy/typeshed/stdlib/email/charset.pyi diff --git a/mypy/stdlib/email/contentmanager.pyi b/mypy/typeshed/stdlib/email/contentmanager.pyi similarity index 100% rename from mypy/stdlib/email/contentmanager.pyi rename to mypy/typeshed/stdlib/email/contentmanager.pyi diff --git a/mypy/stdlib/email/encoders.pyi b/mypy/typeshed/stdlib/email/encoders.pyi similarity index 100% rename from mypy/stdlib/email/encoders.pyi rename to mypy/typeshed/stdlib/email/encoders.pyi diff --git a/mypy/stdlib/email/errors.pyi b/mypy/typeshed/stdlib/email/errors.pyi similarity index 100% rename from mypy/stdlib/email/errors.pyi rename to mypy/typeshed/stdlib/email/errors.pyi diff --git a/mypy/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi similarity index 100% rename from mypy/stdlib/email/feedparser.pyi rename to mypy/typeshed/stdlib/email/feedparser.pyi diff --git a/mypy/stdlib/email/generator.pyi b/mypy/typeshed/stdlib/email/generator.pyi similarity index 100% rename from mypy/stdlib/email/generator.pyi rename to mypy/typeshed/stdlib/email/generator.pyi diff --git a/mypy/stdlib/email/header.pyi b/mypy/typeshed/stdlib/email/header.pyi similarity index 100% rename from mypy/stdlib/email/header.pyi rename to mypy/typeshed/stdlib/email/header.pyi diff --git a/mypy/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi similarity index 100% rename from mypy/stdlib/email/headerregistry.pyi rename to mypy/typeshed/stdlib/email/headerregistry.pyi diff --git a/mypy/stdlib/email/iterators.pyi b/mypy/typeshed/stdlib/email/iterators.pyi similarity index 100% rename from mypy/stdlib/email/iterators.pyi rename to mypy/typeshed/stdlib/email/iterators.pyi diff --git a/mypy/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi similarity index 100% rename from mypy/stdlib/email/message.pyi rename to mypy/typeshed/stdlib/email/message.pyi diff --git a/mypy/stdlib/email/mime/__init__.pyi b/mypy/typeshed/stdlib/email/mime/__init__.pyi similarity index 100% rename from mypy/stdlib/email/mime/__init__.pyi rename to mypy/typeshed/stdlib/email/mime/__init__.pyi diff --git a/mypy/stdlib/email/mime/application.pyi b/mypy/typeshed/stdlib/email/mime/application.pyi similarity index 100% rename from mypy/stdlib/email/mime/application.pyi rename to mypy/typeshed/stdlib/email/mime/application.pyi diff --git a/mypy/stdlib/email/mime/audio.pyi b/mypy/typeshed/stdlib/email/mime/audio.pyi similarity index 100% rename from mypy/stdlib/email/mime/audio.pyi rename to mypy/typeshed/stdlib/email/mime/audio.pyi diff --git a/mypy/stdlib/email/mime/base.pyi b/mypy/typeshed/stdlib/email/mime/base.pyi similarity index 100% rename from mypy/stdlib/email/mime/base.pyi rename to mypy/typeshed/stdlib/email/mime/base.pyi diff --git a/mypy/stdlib/email/mime/image.pyi b/mypy/typeshed/stdlib/email/mime/image.pyi similarity index 100% rename from mypy/stdlib/email/mime/image.pyi rename to mypy/typeshed/stdlib/email/mime/image.pyi diff --git a/mypy/stdlib/email/mime/message.pyi b/mypy/typeshed/stdlib/email/mime/message.pyi similarity index 100% rename from mypy/stdlib/email/mime/message.pyi rename to mypy/typeshed/stdlib/email/mime/message.pyi diff --git a/mypy/stdlib/email/mime/multipart.pyi b/mypy/typeshed/stdlib/email/mime/multipart.pyi similarity index 100% rename from mypy/stdlib/email/mime/multipart.pyi rename to mypy/typeshed/stdlib/email/mime/multipart.pyi diff --git a/mypy/stdlib/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi similarity index 100% rename from mypy/stdlib/email/mime/nonmultipart.pyi rename to mypy/typeshed/stdlib/email/mime/nonmultipart.pyi diff --git a/mypy/stdlib/email/mime/text.pyi b/mypy/typeshed/stdlib/email/mime/text.pyi similarity index 100% rename from mypy/stdlib/email/mime/text.pyi rename to mypy/typeshed/stdlib/email/mime/text.pyi diff --git a/mypy/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi similarity index 100% rename from mypy/stdlib/email/parser.pyi rename to mypy/typeshed/stdlib/email/parser.pyi diff --git a/mypy/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi similarity index 100% rename from mypy/stdlib/email/policy.pyi rename to mypy/typeshed/stdlib/email/policy.pyi diff --git a/mypy/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi similarity index 100% rename from mypy/stdlib/email/utils.pyi rename to mypy/typeshed/stdlib/email/utils.pyi diff --git a/mypy/stdlib/encodings/__init__.pyi b/mypy/typeshed/stdlib/encodings/__init__.pyi similarity index 100% rename from mypy/stdlib/encodings/__init__.pyi rename to mypy/typeshed/stdlib/encodings/__init__.pyi diff --git a/mypy/stdlib/encodings/utf_8.pyi b/mypy/typeshed/stdlib/encodings/utf_8.pyi similarity index 100% rename from mypy/stdlib/encodings/utf_8.pyi rename to mypy/typeshed/stdlib/encodings/utf_8.pyi diff --git a/mypy/stdlib/ensurepip/__init__.pyi b/mypy/typeshed/stdlib/ensurepip/__init__.pyi similarity index 100% rename from mypy/stdlib/ensurepip/__init__.pyi rename to mypy/typeshed/stdlib/ensurepip/__init__.pyi diff --git a/mypy/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi similarity index 100% rename from mypy/stdlib/enum.pyi rename to mypy/typeshed/stdlib/enum.pyi diff --git a/mypy/stdlib/errno.pyi b/mypy/typeshed/stdlib/errno.pyi similarity index 100% rename from mypy/stdlib/errno.pyi rename to mypy/typeshed/stdlib/errno.pyi diff --git a/mypy/stdlib/faulthandler.pyi b/mypy/typeshed/stdlib/faulthandler.pyi similarity index 100% rename from mypy/stdlib/faulthandler.pyi rename to mypy/typeshed/stdlib/faulthandler.pyi diff --git a/mypy/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi similarity index 100% rename from mypy/stdlib/fcntl.pyi rename to mypy/typeshed/stdlib/fcntl.pyi diff --git a/mypy/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi similarity index 100% rename from mypy/stdlib/filecmp.pyi rename to mypy/typeshed/stdlib/filecmp.pyi diff --git a/mypy/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi similarity index 100% rename from mypy/stdlib/fileinput.pyi rename to mypy/typeshed/stdlib/fileinput.pyi diff --git a/mypy/stdlib/fnmatch.pyi b/mypy/typeshed/stdlib/fnmatch.pyi similarity index 100% rename from mypy/stdlib/fnmatch.pyi rename to mypy/typeshed/stdlib/fnmatch.pyi diff --git a/mypy/stdlib/formatter.pyi b/mypy/typeshed/stdlib/formatter.pyi similarity index 100% rename from mypy/stdlib/formatter.pyi rename to mypy/typeshed/stdlib/formatter.pyi diff --git a/mypy/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi similarity index 100% rename from mypy/stdlib/fractions.pyi rename to mypy/typeshed/stdlib/fractions.pyi diff --git a/mypy/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi similarity index 100% rename from mypy/stdlib/ftplib.pyi rename to mypy/typeshed/stdlib/ftplib.pyi diff --git a/mypy/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi similarity index 100% rename from mypy/stdlib/functools.pyi rename to mypy/typeshed/stdlib/functools.pyi diff --git a/mypy/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi similarity index 100% rename from mypy/stdlib/gc.pyi rename to mypy/typeshed/stdlib/gc.pyi diff --git a/mypy/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi similarity index 100% rename from mypy/stdlib/genericpath.pyi rename to mypy/typeshed/stdlib/genericpath.pyi diff --git a/mypy/stdlib/getopt.pyi b/mypy/typeshed/stdlib/getopt.pyi similarity index 100% rename from mypy/stdlib/getopt.pyi rename to mypy/typeshed/stdlib/getopt.pyi diff --git a/mypy/stdlib/getpass.pyi b/mypy/typeshed/stdlib/getpass.pyi similarity index 100% rename from mypy/stdlib/getpass.pyi rename to mypy/typeshed/stdlib/getpass.pyi diff --git a/mypy/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi similarity index 100% rename from mypy/stdlib/gettext.pyi rename to mypy/typeshed/stdlib/gettext.pyi diff --git a/mypy/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi similarity index 100% rename from mypy/stdlib/glob.pyi rename to mypy/typeshed/stdlib/glob.pyi diff --git a/mypy/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi similarity index 100% rename from mypy/stdlib/grp.pyi rename to mypy/typeshed/stdlib/grp.pyi diff --git a/mypy/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi similarity index 100% rename from mypy/stdlib/gzip.pyi rename to mypy/typeshed/stdlib/gzip.pyi diff --git a/mypy/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi similarity index 100% rename from mypy/stdlib/hashlib.pyi rename to mypy/typeshed/stdlib/hashlib.pyi diff --git a/mypy/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi similarity index 100% rename from mypy/stdlib/heapq.pyi rename to mypy/typeshed/stdlib/heapq.pyi diff --git a/mypy/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi similarity index 100% rename from mypy/stdlib/hmac.pyi rename to mypy/typeshed/stdlib/hmac.pyi diff --git a/mypy/stdlib/html/__init__.pyi b/mypy/typeshed/stdlib/html/__init__.pyi similarity index 100% rename from mypy/stdlib/html/__init__.pyi rename to mypy/typeshed/stdlib/html/__init__.pyi diff --git a/mypy/stdlib/html/entities.pyi b/mypy/typeshed/stdlib/html/entities.pyi similarity index 100% rename from mypy/stdlib/html/entities.pyi rename to mypy/typeshed/stdlib/html/entities.pyi diff --git a/mypy/stdlib/html/parser.pyi b/mypy/typeshed/stdlib/html/parser.pyi similarity index 100% rename from mypy/stdlib/html/parser.pyi rename to mypy/typeshed/stdlib/html/parser.pyi diff --git a/mypy/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi similarity index 100% rename from mypy/stdlib/http/__init__.pyi rename to mypy/typeshed/stdlib/http/__init__.pyi diff --git a/mypy/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi similarity index 100% rename from mypy/stdlib/http/client.pyi rename to mypy/typeshed/stdlib/http/client.pyi diff --git a/mypy/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi similarity index 100% rename from mypy/stdlib/http/cookiejar.pyi rename to mypy/typeshed/stdlib/http/cookiejar.pyi diff --git a/mypy/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi similarity index 100% rename from mypy/stdlib/http/cookies.pyi rename to mypy/typeshed/stdlib/http/cookies.pyi diff --git a/mypy/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi similarity index 100% rename from mypy/stdlib/http/server.pyi rename to mypy/typeshed/stdlib/http/server.pyi diff --git a/mypy/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi similarity index 100% rename from mypy/stdlib/imaplib.pyi rename to mypy/typeshed/stdlib/imaplib.pyi diff --git a/mypy/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi similarity index 100% rename from mypy/stdlib/imghdr.pyi rename to mypy/typeshed/stdlib/imghdr.pyi diff --git a/mypy/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi similarity index 100% rename from mypy/stdlib/imp.pyi rename to mypy/typeshed/stdlib/imp.pyi diff --git a/mypy/stdlib/importlib/__init__.pyi b/mypy/typeshed/stdlib/importlib/__init__.pyi similarity index 100% rename from mypy/stdlib/importlib/__init__.pyi rename to mypy/typeshed/stdlib/importlib/__init__.pyi diff --git a/mypy/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi similarity index 100% rename from mypy/stdlib/importlib/abc.pyi rename to mypy/typeshed/stdlib/importlib/abc.pyi diff --git a/mypy/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi similarity index 100% rename from mypy/stdlib/importlib/machinery.pyi rename to mypy/typeshed/stdlib/importlib/machinery.pyi diff --git a/mypy/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata.pyi similarity index 100% rename from mypy/stdlib/importlib/metadata.pyi rename to mypy/typeshed/stdlib/importlib/metadata.pyi diff --git a/mypy/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi similarity index 100% rename from mypy/stdlib/importlib/resources.pyi rename to mypy/typeshed/stdlib/importlib/resources.pyi diff --git a/mypy/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi similarity index 100% rename from mypy/stdlib/importlib/util.pyi rename to mypy/typeshed/stdlib/importlib/util.pyi diff --git a/mypy/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi similarity index 100% rename from mypy/stdlib/inspect.pyi rename to mypy/typeshed/stdlib/inspect.pyi diff --git a/mypy/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi similarity index 100% rename from mypy/stdlib/io.pyi rename to mypy/typeshed/stdlib/io.pyi diff --git a/mypy/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi similarity index 100% rename from mypy/stdlib/ipaddress.pyi rename to mypy/typeshed/stdlib/ipaddress.pyi diff --git a/mypy/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi similarity index 100% rename from mypy/stdlib/itertools.pyi rename to mypy/typeshed/stdlib/itertools.pyi diff --git a/mypy/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi similarity index 100% rename from mypy/stdlib/json/__init__.pyi rename to mypy/typeshed/stdlib/json/__init__.pyi diff --git a/mypy/stdlib/json/decoder.pyi b/mypy/typeshed/stdlib/json/decoder.pyi similarity index 100% rename from mypy/stdlib/json/decoder.pyi rename to mypy/typeshed/stdlib/json/decoder.pyi diff --git a/mypy/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi similarity index 100% rename from mypy/stdlib/json/encoder.pyi rename to mypy/typeshed/stdlib/json/encoder.pyi diff --git a/mypy/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi similarity index 100% rename from mypy/stdlib/keyword.pyi rename to mypy/typeshed/stdlib/keyword.pyi diff --git a/mypy/stdlib/lib2to3/__init__.pyi b/mypy/typeshed/stdlib/lib2to3/__init__.pyi similarity index 100% rename from mypy/stdlib/lib2to3/__init__.pyi rename to mypy/typeshed/stdlib/lib2to3/__init__.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/__init__.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/__init__.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/driver.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/grammar.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/literals.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/parse.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/pgen.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/token.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi diff --git a/mypy/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pgen2/tokenize.pyi rename to mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi diff --git a/mypy/stdlib/lib2to3/pygram.pyi b/mypy/typeshed/stdlib/lib2to3/pygram.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pygram.pyi rename to mypy/typeshed/stdlib/lib2to3/pygram.pyi diff --git a/mypy/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi similarity index 100% rename from mypy/stdlib/lib2to3/pytree.pyi rename to mypy/typeshed/stdlib/lib2to3/pytree.pyi diff --git a/mypy/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi similarity index 100% rename from mypy/stdlib/linecache.pyi rename to mypy/typeshed/stdlib/linecache.pyi diff --git a/mypy/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi similarity index 100% rename from mypy/stdlib/locale.pyi rename to mypy/typeshed/stdlib/locale.pyi diff --git a/mypy/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi similarity index 100% rename from mypy/stdlib/logging/__init__.pyi rename to mypy/typeshed/stdlib/logging/__init__.pyi diff --git a/mypy/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi similarity index 100% rename from mypy/stdlib/logging/config.pyi rename to mypy/typeshed/stdlib/logging/config.pyi diff --git a/mypy/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi similarity index 100% rename from mypy/stdlib/logging/handlers.pyi rename to mypy/typeshed/stdlib/logging/handlers.pyi diff --git a/mypy/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi similarity index 100% rename from mypy/stdlib/lzma.pyi rename to mypy/typeshed/stdlib/lzma.pyi diff --git a/mypy/stdlib/macpath.pyi b/mypy/typeshed/stdlib/macpath.pyi similarity index 100% rename from mypy/stdlib/macpath.pyi rename to mypy/typeshed/stdlib/macpath.pyi diff --git a/mypy/stdlib/macurl2path.pyi b/mypy/typeshed/stdlib/macurl2path.pyi similarity index 100% rename from mypy/stdlib/macurl2path.pyi rename to mypy/typeshed/stdlib/macurl2path.pyi diff --git a/mypy/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi similarity index 100% rename from mypy/stdlib/mailbox.pyi rename to mypy/typeshed/stdlib/mailbox.pyi diff --git a/mypy/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi similarity index 100% rename from mypy/stdlib/mailcap.pyi rename to mypy/typeshed/stdlib/mailcap.pyi diff --git a/mypy/stdlib/marshal.pyi b/mypy/typeshed/stdlib/marshal.pyi similarity index 100% rename from mypy/stdlib/marshal.pyi rename to mypy/typeshed/stdlib/marshal.pyi diff --git a/mypy/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi similarity index 100% rename from mypy/stdlib/math.pyi rename to mypy/typeshed/stdlib/math.pyi diff --git a/mypy/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi similarity index 100% rename from mypy/stdlib/mimetypes.pyi rename to mypy/typeshed/stdlib/mimetypes.pyi diff --git a/mypy/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi similarity index 100% rename from mypy/stdlib/mmap.pyi rename to mypy/typeshed/stdlib/mmap.pyi diff --git a/mypy/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi similarity index 100% rename from mypy/stdlib/modulefinder.pyi rename to mypy/typeshed/stdlib/modulefinder.pyi diff --git a/mypy/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi similarity index 100% rename from mypy/stdlib/msilib/__init__.pyi rename to mypy/typeshed/stdlib/msilib/__init__.pyi diff --git a/mypy/stdlib/msilib/schema.pyi b/mypy/typeshed/stdlib/msilib/schema.pyi similarity index 100% rename from mypy/stdlib/msilib/schema.pyi rename to mypy/typeshed/stdlib/msilib/schema.pyi diff --git a/mypy/stdlib/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi similarity index 100% rename from mypy/stdlib/msilib/sequence.pyi rename to mypy/typeshed/stdlib/msilib/sequence.pyi diff --git a/mypy/stdlib/msilib/text.pyi b/mypy/typeshed/stdlib/msilib/text.pyi similarity index 100% rename from mypy/stdlib/msilib/text.pyi rename to mypy/typeshed/stdlib/msilib/text.pyi diff --git a/mypy/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi similarity index 100% rename from mypy/stdlib/msvcrt.pyi rename to mypy/typeshed/stdlib/msvcrt.pyi diff --git a/mypy/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/__init__.pyi rename to mypy/typeshed/stdlib/multiprocessing/__init__.pyi diff --git a/mypy/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/connection.pyi rename to mypy/typeshed/stdlib/multiprocessing/connection.pyi diff --git a/mypy/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/context.pyi rename to mypy/typeshed/stdlib/multiprocessing/context.pyi diff --git a/mypy/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/dummy/__init__.pyi rename to mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi diff --git a/mypy/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/dummy/connection.pyi rename to mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi diff --git a/mypy/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/managers.pyi rename to mypy/typeshed/stdlib/multiprocessing/managers.pyi diff --git a/mypy/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/pool.pyi rename to mypy/typeshed/stdlib/multiprocessing/pool.pyi diff --git a/mypy/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/process.pyi rename to mypy/typeshed/stdlib/multiprocessing/process.pyi diff --git a/mypy/stdlib/multiprocessing/queues.pyi b/mypy/typeshed/stdlib/multiprocessing/queues.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/queues.pyi rename to mypy/typeshed/stdlib/multiprocessing/queues.pyi diff --git a/mypy/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/shared_memory.pyi rename to mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi diff --git a/mypy/stdlib/multiprocessing/spawn.pyi b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/spawn.pyi rename to mypy/typeshed/stdlib/multiprocessing/spawn.pyi diff --git a/mypy/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi similarity index 100% rename from mypy/stdlib/multiprocessing/synchronize.pyi rename to mypy/typeshed/stdlib/multiprocessing/synchronize.pyi diff --git a/mypy/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi similarity index 100% rename from mypy/stdlib/netrc.pyi rename to mypy/typeshed/stdlib/netrc.pyi diff --git a/mypy/stdlib/nis.pyi b/mypy/typeshed/stdlib/nis.pyi similarity index 100% rename from mypy/stdlib/nis.pyi rename to mypy/typeshed/stdlib/nis.pyi diff --git a/mypy/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi similarity index 100% rename from mypy/stdlib/nntplib.pyi rename to mypy/typeshed/stdlib/nntplib.pyi diff --git a/mypy/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi similarity index 100% rename from mypy/stdlib/ntpath.pyi rename to mypy/typeshed/stdlib/ntpath.pyi diff --git a/mypy/stdlib/nturl2path.pyi b/mypy/typeshed/stdlib/nturl2path.pyi similarity index 100% rename from mypy/stdlib/nturl2path.pyi rename to mypy/typeshed/stdlib/nturl2path.pyi diff --git a/mypy/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi similarity index 100% rename from mypy/stdlib/numbers.pyi rename to mypy/typeshed/stdlib/numbers.pyi diff --git a/mypy/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi similarity index 100% rename from mypy/stdlib/opcode.pyi rename to mypy/typeshed/stdlib/opcode.pyi diff --git a/mypy/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi similarity index 100% rename from mypy/stdlib/operator.pyi rename to mypy/typeshed/stdlib/operator.pyi diff --git a/mypy/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi similarity index 100% rename from mypy/stdlib/optparse.pyi rename to mypy/typeshed/stdlib/optparse.pyi diff --git a/mypy/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi similarity index 100% rename from mypy/stdlib/os/__init__.pyi rename to mypy/typeshed/stdlib/os/__init__.pyi diff --git a/mypy/stdlib/os/path.pyi b/mypy/typeshed/stdlib/os/path.pyi similarity index 100% rename from mypy/stdlib/os/path.pyi rename to mypy/typeshed/stdlib/os/path.pyi diff --git a/mypy/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi similarity index 100% rename from mypy/stdlib/parser.pyi rename to mypy/typeshed/stdlib/parser.pyi diff --git a/mypy/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi similarity index 100% rename from mypy/stdlib/pathlib.pyi rename to mypy/typeshed/stdlib/pathlib.pyi diff --git a/mypy/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi similarity index 100% rename from mypy/stdlib/pdb.pyi rename to mypy/typeshed/stdlib/pdb.pyi diff --git a/mypy/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi similarity index 100% rename from mypy/stdlib/pickle.pyi rename to mypy/typeshed/stdlib/pickle.pyi diff --git a/mypy/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi similarity index 100% rename from mypy/stdlib/pickletools.pyi rename to mypy/typeshed/stdlib/pickletools.pyi diff --git a/mypy/stdlib/pipes.pyi b/mypy/typeshed/stdlib/pipes.pyi similarity index 100% rename from mypy/stdlib/pipes.pyi rename to mypy/typeshed/stdlib/pipes.pyi diff --git a/mypy/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi similarity index 100% rename from mypy/stdlib/pkgutil.pyi rename to mypy/typeshed/stdlib/pkgutil.pyi diff --git a/mypy/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi similarity index 100% rename from mypy/stdlib/platform.pyi rename to mypy/typeshed/stdlib/platform.pyi diff --git a/mypy/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi similarity index 100% rename from mypy/stdlib/plistlib.pyi rename to mypy/typeshed/stdlib/plistlib.pyi diff --git a/mypy/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi similarity index 100% rename from mypy/stdlib/poplib.pyi rename to mypy/typeshed/stdlib/poplib.pyi diff --git a/mypy/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi similarity index 100% rename from mypy/stdlib/posix.pyi rename to mypy/typeshed/stdlib/posix.pyi diff --git a/mypy/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi similarity index 100% rename from mypy/stdlib/posixpath.pyi rename to mypy/typeshed/stdlib/posixpath.pyi diff --git a/mypy/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi similarity index 100% rename from mypy/stdlib/pprint.pyi rename to mypy/typeshed/stdlib/pprint.pyi diff --git a/mypy/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi similarity index 100% rename from mypy/stdlib/profile.pyi rename to mypy/typeshed/stdlib/profile.pyi diff --git a/mypy/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi similarity index 100% rename from mypy/stdlib/pstats.pyi rename to mypy/typeshed/stdlib/pstats.pyi diff --git a/mypy/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi similarity index 100% rename from mypy/stdlib/pty.pyi rename to mypy/typeshed/stdlib/pty.pyi diff --git a/mypy/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi similarity index 100% rename from mypy/stdlib/pwd.pyi rename to mypy/typeshed/stdlib/pwd.pyi diff --git a/mypy/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi similarity index 100% rename from mypy/stdlib/py_compile.pyi rename to mypy/typeshed/stdlib/py_compile.pyi diff --git a/mypy/stdlib/pyclbr.pyi b/mypy/typeshed/stdlib/pyclbr.pyi similarity index 100% rename from mypy/stdlib/pyclbr.pyi rename to mypy/typeshed/stdlib/pyclbr.pyi diff --git a/mypy/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi similarity index 100% rename from mypy/stdlib/pydoc.pyi rename to mypy/typeshed/stdlib/pydoc.pyi diff --git a/mypy/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi similarity index 100% rename from mypy/stdlib/pyexpat/__init__.pyi rename to mypy/typeshed/stdlib/pyexpat/__init__.pyi diff --git a/mypy/stdlib/pyexpat/errors.pyi b/mypy/typeshed/stdlib/pyexpat/errors.pyi similarity index 100% rename from mypy/stdlib/pyexpat/errors.pyi rename to mypy/typeshed/stdlib/pyexpat/errors.pyi diff --git a/mypy/stdlib/pyexpat/model.pyi b/mypy/typeshed/stdlib/pyexpat/model.pyi similarity index 100% rename from mypy/stdlib/pyexpat/model.pyi rename to mypy/typeshed/stdlib/pyexpat/model.pyi diff --git a/mypy/stdlib/python2/BaseHTTPServer.pyi b/mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi similarity index 100% rename from mypy/stdlib/python2/BaseHTTPServer.pyi rename to mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi diff --git a/mypy/stdlib/python2/CGIHTTPServer.pyi b/mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi similarity index 100% rename from mypy/stdlib/python2/CGIHTTPServer.pyi rename to mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi diff --git a/mypy/stdlib/python2/ConfigParser.pyi b/mypy/typeshed/stdlib/python2/ConfigParser.pyi similarity index 100% rename from mypy/stdlib/python2/ConfigParser.pyi rename to mypy/typeshed/stdlib/python2/ConfigParser.pyi diff --git a/mypy/stdlib/python2/Cookie.pyi b/mypy/typeshed/stdlib/python2/Cookie.pyi similarity index 100% rename from mypy/stdlib/python2/Cookie.pyi rename to mypy/typeshed/stdlib/python2/Cookie.pyi diff --git a/mypy/stdlib/python2/HTMLParser.pyi b/mypy/typeshed/stdlib/python2/HTMLParser.pyi similarity index 100% rename from mypy/stdlib/python2/HTMLParser.pyi rename to mypy/typeshed/stdlib/python2/HTMLParser.pyi diff --git a/mypy/stdlib/python2/Queue.pyi b/mypy/typeshed/stdlib/python2/Queue.pyi similarity index 100% rename from mypy/stdlib/python2/Queue.pyi rename to mypy/typeshed/stdlib/python2/Queue.pyi diff --git a/mypy/stdlib/python2/SimpleHTTPServer.pyi b/mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi similarity index 100% rename from mypy/stdlib/python2/SimpleHTTPServer.pyi rename to mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi diff --git a/mypy/stdlib/python2/SocketServer.pyi b/mypy/typeshed/stdlib/python2/SocketServer.pyi similarity index 100% rename from mypy/stdlib/python2/SocketServer.pyi rename to mypy/typeshed/stdlib/python2/SocketServer.pyi diff --git a/mypy/stdlib/python2/StringIO.pyi b/mypy/typeshed/stdlib/python2/StringIO.pyi similarity index 100% rename from mypy/stdlib/python2/StringIO.pyi rename to mypy/typeshed/stdlib/python2/StringIO.pyi diff --git a/mypy/stdlib/python2/UserDict.pyi b/mypy/typeshed/stdlib/python2/UserDict.pyi similarity index 100% rename from mypy/stdlib/python2/UserDict.pyi rename to mypy/typeshed/stdlib/python2/UserDict.pyi diff --git a/mypy/stdlib/python2/UserList.pyi b/mypy/typeshed/stdlib/python2/UserList.pyi similarity index 100% rename from mypy/stdlib/python2/UserList.pyi rename to mypy/typeshed/stdlib/python2/UserList.pyi diff --git a/mypy/stdlib/python2/UserString.pyi b/mypy/typeshed/stdlib/python2/UserString.pyi similarity index 100% rename from mypy/stdlib/python2/UserString.pyi rename to mypy/typeshed/stdlib/python2/UserString.pyi diff --git a/mypy/stdlib/python2/__builtin__.pyi b/mypy/typeshed/stdlib/python2/__builtin__.pyi similarity index 100% rename from mypy/stdlib/python2/__builtin__.pyi rename to mypy/typeshed/stdlib/python2/__builtin__.pyi diff --git a/mypy/stdlib/python2/_ast.pyi b/mypy/typeshed/stdlib/python2/_ast.pyi similarity index 100% rename from mypy/stdlib/python2/_ast.pyi rename to mypy/typeshed/stdlib/python2/_ast.pyi diff --git a/mypy/stdlib/python2/_collections.pyi b/mypy/typeshed/stdlib/python2/_collections.pyi similarity index 100% rename from mypy/stdlib/python2/_collections.pyi rename to mypy/typeshed/stdlib/python2/_collections.pyi diff --git a/mypy/stdlib/python2/_functools.pyi b/mypy/typeshed/stdlib/python2/_functools.pyi similarity index 100% rename from mypy/stdlib/python2/_functools.pyi rename to mypy/typeshed/stdlib/python2/_functools.pyi diff --git a/mypy/stdlib/python2/_hotshot.pyi b/mypy/typeshed/stdlib/python2/_hotshot.pyi similarity index 100% rename from mypy/stdlib/python2/_hotshot.pyi rename to mypy/typeshed/stdlib/python2/_hotshot.pyi diff --git a/mypy/stdlib/python2/_io.pyi b/mypy/typeshed/stdlib/python2/_io.pyi similarity index 100% rename from mypy/stdlib/python2/_io.pyi rename to mypy/typeshed/stdlib/python2/_io.pyi diff --git a/mypy/stdlib/python2/_json.pyi b/mypy/typeshed/stdlib/python2/_json.pyi similarity index 100% rename from mypy/stdlib/python2/_json.pyi rename to mypy/typeshed/stdlib/python2/_json.pyi diff --git a/mypy/stdlib/python2/_md5.pyi b/mypy/typeshed/stdlib/python2/_md5.pyi similarity index 100% rename from mypy/stdlib/python2/_md5.pyi rename to mypy/typeshed/stdlib/python2/_md5.pyi diff --git a/mypy/stdlib/python2/_sha.pyi b/mypy/typeshed/stdlib/python2/_sha.pyi similarity index 100% rename from mypy/stdlib/python2/_sha.pyi rename to mypy/typeshed/stdlib/python2/_sha.pyi diff --git a/mypy/stdlib/python2/_sha256.pyi b/mypy/typeshed/stdlib/python2/_sha256.pyi similarity index 100% rename from mypy/stdlib/python2/_sha256.pyi rename to mypy/typeshed/stdlib/python2/_sha256.pyi diff --git a/mypy/stdlib/python2/_sha512.pyi b/mypy/typeshed/stdlib/python2/_sha512.pyi similarity index 100% rename from mypy/stdlib/python2/_sha512.pyi rename to mypy/typeshed/stdlib/python2/_sha512.pyi diff --git a/mypy/stdlib/python2/_socket.pyi b/mypy/typeshed/stdlib/python2/_socket.pyi similarity index 100% rename from mypy/stdlib/python2/_socket.pyi rename to mypy/typeshed/stdlib/python2/_socket.pyi diff --git a/mypy/stdlib/python2/_sre.pyi b/mypy/typeshed/stdlib/python2/_sre.pyi similarity index 100% rename from mypy/stdlib/python2/_sre.pyi rename to mypy/typeshed/stdlib/python2/_sre.pyi diff --git a/mypy/stdlib/python2/_struct.pyi b/mypy/typeshed/stdlib/python2/_struct.pyi similarity index 100% rename from mypy/stdlib/python2/_struct.pyi rename to mypy/typeshed/stdlib/python2/_struct.pyi diff --git a/mypy/stdlib/python2/_symtable.pyi b/mypy/typeshed/stdlib/python2/_symtable.pyi similarity index 100% rename from mypy/stdlib/python2/_symtable.pyi rename to mypy/typeshed/stdlib/python2/_symtable.pyi diff --git a/mypy/stdlib/python2/_threading_local.pyi b/mypy/typeshed/stdlib/python2/_threading_local.pyi similarity index 100% rename from mypy/stdlib/python2/_threading_local.pyi rename to mypy/typeshed/stdlib/python2/_threading_local.pyi diff --git a/mypy/stdlib/python2/_winreg.pyi b/mypy/typeshed/stdlib/python2/_winreg.pyi similarity index 100% rename from mypy/stdlib/python2/_winreg.pyi rename to mypy/typeshed/stdlib/python2/_winreg.pyi diff --git a/mypy/stdlib/python2/abc.pyi b/mypy/typeshed/stdlib/python2/abc.pyi similarity index 100% rename from mypy/stdlib/python2/abc.pyi rename to mypy/typeshed/stdlib/python2/abc.pyi diff --git a/mypy/stdlib/python2/ast.pyi b/mypy/typeshed/stdlib/python2/ast.pyi similarity index 100% rename from mypy/stdlib/python2/ast.pyi rename to mypy/typeshed/stdlib/python2/ast.pyi diff --git a/mypy/stdlib/python2/atexit.pyi b/mypy/typeshed/stdlib/python2/atexit.pyi similarity index 100% rename from mypy/stdlib/python2/atexit.pyi rename to mypy/typeshed/stdlib/python2/atexit.pyi diff --git a/mypy/stdlib/python2/cPickle.pyi b/mypy/typeshed/stdlib/python2/cPickle.pyi similarity index 100% rename from mypy/stdlib/python2/cPickle.pyi rename to mypy/typeshed/stdlib/python2/cPickle.pyi diff --git a/mypy/stdlib/python2/cStringIO.pyi b/mypy/typeshed/stdlib/python2/cStringIO.pyi similarity index 100% rename from mypy/stdlib/python2/cStringIO.pyi rename to mypy/typeshed/stdlib/python2/cStringIO.pyi diff --git a/mypy/stdlib/python2/collections.pyi b/mypy/typeshed/stdlib/python2/collections.pyi similarity index 100% rename from mypy/stdlib/python2/collections.pyi rename to mypy/typeshed/stdlib/python2/collections.pyi diff --git a/mypy/stdlib/python2/commands.pyi b/mypy/typeshed/stdlib/python2/commands.pyi similarity index 100% rename from mypy/stdlib/python2/commands.pyi rename to mypy/typeshed/stdlib/python2/commands.pyi diff --git a/mypy/stdlib/python2/compileall.pyi b/mypy/typeshed/stdlib/python2/compileall.pyi similarity index 100% rename from mypy/stdlib/python2/compileall.pyi rename to mypy/typeshed/stdlib/python2/compileall.pyi diff --git a/mypy/stdlib/python2/cookielib.pyi b/mypy/typeshed/stdlib/python2/cookielib.pyi similarity index 100% rename from mypy/stdlib/python2/cookielib.pyi rename to mypy/typeshed/stdlib/python2/cookielib.pyi diff --git a/mypy/stdlib/python2/copy_reg.pyi b/mypy/typeshed/stdlib/python2/copy_reg.pyi similarity index 100% rename from mypy/stdlib/python2/copy_reg.pyi rename to mypy/typeshed/stdlib/python2/copy_reg.pyi diff --git a/mypy/stdlib/python2/dircache.pyi b/mypy/typeshed/stdlib/python2/dircache.pyi similarity index 100% rename from mypy/stdlib/python2/dircache.pyi rename to mypy/typeshed/stdlib/python2/dircache.pyi diff --git a/mypy/stdlib/python2/distutils/__init__.pyi b/mypy/typeshed/stdlib/python2/distutils/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/distutils/__init__.pyi rename to mypy/typeshed/stdlib/python2/distutils/__init__.pyi diff --git a/mypy/stdlib/python2/distutils/emxccompiler.pyi b/mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi similarity index 100% rename from mypy/stdlib/python2/distutils/emxccompiler.pyi rename to mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi diff --git a/mypy/stdlib/python2/dummy_thread.pyi b/mypy/typeshed/stdlib/python2/dummy_thread.pyi similarity index 100% rename from mypy/stdlib/python2/dummy_thread.pyi rename to mypy/typeshed/stdlib/python2/dummy_thread.pyi diff --git a/mypy/stdlib/python2/email/MIMEText.pyi b/mypy/typeshed/stdlib/python2/email/MIMEText.pyi similarity index 100% rename from mypy/stdlib/python2/email/MIMEText.pyi rename to mypy/typeshed/stdlib/python2/email/MIMEText.pyi diff --git a/mypy/stdlib/python2/email/__init__.pyi b/mypy/typeshed/stdlib/python2/email/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/email/__init__.pyi rename to mypy/typeshed/stdlib/python2/email/__init__.pyi diff --git a/mypy/stdlib/python2/email/_parseaddr.pyi b/mypy/typeshed/stdlib/python2/email/_parseaddr.pyi similarity index 100% rename from mypy/stdlib/python2/email/_parseaddr.pyi rename to mypy/typeshed/stdlib/python2/email/_parseaddr.pyi diff --git a/mypy/stdlib/python2/email/base64mime.pyi b/mypy/typeshed/stdlib/python2/email/base64mime.pyi similarity index 100% rename from mypy/stdlib/python2/email/base64mime.pyi rename to mypy/typeshed/stdlib/python2/email/base64mime.pyi diff --git a/mypy/stdlib/python2/email/charset.pyi b/mypy/typeshed/stdlib/python2/email/charset.pyi similarity index 100% rename from mypy/stdlib/python2/email/charset.pyi rename to mypy/typeshed/stdlib/python2/email/charset.pyi diff --git a/mypy/stdlib/python2/email/encoders.pyi b/mypy/typeshed/stdlib/python2/email/encoders.pyi similarity index 100% rename from mypy/stdlib/python2/email/encoders.pyi rename to mypy/typeshed/stdlib/python2/email/encoders.pyi diff --git a/mypy/stdlib/python2/email/feedparser.pyi b/mypy/typeshed/stdlib/python2/email/feedparser.pyi similarity index 100% rename from mypy/stdlib/python2/email/feedparser.pyi rename to mypy/typeshed/stdlib/python2/email/feedparser.pyi diff --git a/mypy/stdlib/python2/email/generator.pyi b/mypy/typeshed/stdlib/python2/email/generator.pyi similarity index 100% rename from mypy/stdlib/python2/email/generator.pyi rename to mypy/typeshed/stdlib/python2/email/generator.pyi diff --git a/mypy/stdlib/python2/email/header.pyi b/mypy/typeshed/stdlib/python2/email/header.pyi similarity index 100% rename from mypy/stdlib/python2/email/header.pyi rename to mypy/typeshed/stdlib/python2/email/header.pyi diff --git a/mypy/stdlib/python2/email/iterators.pyi b/mypy/typeshed/stdlib/python2/email/iterators.pyi similarity index 100% rename from mypy/stdlib/python2/email/iterators.pyi rename to mypy/typeshed/stdlib/python2/email/iterators.pyi diff --git a/mypy/stdlib/python2/email/message.pyi b/mypy/typeshed/stdlib/python2/email/message.pyi similarity index 100% rename from mypy/stdlib/python2/email/message.pyi rename to mypy/typeshed/stdlib/python2/email/message.pyi diff --git a/mypy/stdlib/python2/email/mime/__init__.pyi b/mypy/typeshed/stdlib/python2/email/mime/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/__init__.pyi rename to mypy/typeshed/stdlib/python2/email/mime/__init__.pyi diff --git a/mypy/stdlib/python2/email/mime/application.pyi b/mypy/typeshed/stdlib/python2/email/mime/application.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/application.pyi rename to mypy/typeshed/stdlib/python2/email/mime/application.pyi diff --git a/mypy/stdlib/python2/email/mime/audio.pyi b/mypy/typeshed/stdlib/python2/email/mime/audio.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/audio.pyi rename to mypy/typeshed/stdlib/python2/email/mime/audio.pyi diff --git a/mypy/stdlib/python2/email/mime/base.pyi b/mypy/typeshed/stdlib/python2/email/mime/base.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/base.pyi rename to mypy/typeshed/stdlib/python2/email/mime/base.pyi diff --git a/mypy/stdlib/python2/email/mime/image.pyi b/mypy/typeshed/stdlib/python2/email/mime/image.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/image.pyi rename to mypy/typeshed/stdlib/python2/email/mime/image.pyi diff --git a/mypy/stdlib/python2/email/mime/message.pyi b/mypy/typeshed/stdlib/python2/email/mime/message.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/message.pyi rename to mypy/typeshed/stdlib/python2/email/mime/message.pyi diff --git a/mypy/stdlib/python2/email/mime/multipart.pyi b/mypy/typeshed/stdlib/python2/email/mime/multipart.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/multipart.pyi rename to mypy/typeshed/stdlib/python2/email/mime/multipart.pyi diff --git a/mypy/stdlib/python2/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/nonmultipart.pyi rename to mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi diff --git a/mypy/stdlib/python2/email/mime/text.pyi b/mypy/typeshed/stdlib/python2/email/mime/text.pyi similarity index 100% rename from mypy/stdlib/python2/email/mime/text.pyi rename to mypy/typeshed/stdlib/python2/email/mime/text.pyi diff --git a/mypy/stdlib/python2/email/parser.pyi b/mypy/typeshed/stdlib/python2/email/parser.pyi similarity index 100% rename from mypy/stdlib/python2/email/parser.pyi rename to mypy/typeshed/stdlib/python2/email/parser.pyi diff --git a/mypy/stdlib/python2/email/quoprimime.pyi b/mypy/typeshed/stdlib/python2/email/quoprimime.pyi similarity index 100% rename from mypy/stdlib/python2/email/quoprimime.pyi rename to mypy/typeshed/stdlib/python2/email/quoprimime.pyi diff --git a/mypy/stdlib/python2/email/utils.pyi b/mypy/typeshed/stdlib/python2/email/utils.pyi similarity index 100% rename from mypy/stdlib/python2/email/utils.pyi rename to mypy/typeshed/stdlib/python2/email/utils.pyi diff --git a/mypy/stdlib/python2/encodings/__init__.pyi b/mypy/typeshed/stdlib/python2/encodings/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/encodings/__init__.pyi rename to mypy/typeshed/stdlib/python2/encodings/__init__.pyi diff --git a/mypy/stdlib/python2/encodings/utf_8.pyi b/mypy/typeshed/stdlib/python2/encodings/utf_8.pyi similarity index 100% rename from mypy/stdlib/python2/encodings/utf_8.pyi rename to mypy/typeshed/stdlib/python2/encodings/utf_8.pyi diff --git a/mypy/stdlib/python2/exceptions.pyi b/mypy/typeshed/stdlib/python2/exceptions.pyi similarity index 100% rename from mypy/stdlib/python2/exceptions.pyi rename to mypy/typeshed/stdlib/python2/exceptions.pyi diff --git a/mypy/stdlib/python2/fcntl.pyi b/mypy/typeshed/stdlib/python2/fcntl.pyi similarity index 100% rename from mypy/stdlib/python2/fcntl.pyi rename to mypy/typeshed/stdlib/python2/fcntl.pyi diff --git a/mypy/stdlib/python2/fnmatch.pyi b/mypy/typeshed/stdlib/python2/fnmatch.pyi similarity index 100% rename from mypy/stdlib/python2/fnmatch.pyi rename to mypy/typeshed/stdlib/python2/fnmatch.pyi diff --git a/mypy/stdlib/python2/functools.pyi b/mypy/typeshed/stdlib/python2/functools.pyi similarity index 100% rename from mypy/stdlib/python2/functools.pyi rename to mypy/typeshed/stdlib/python2/functools.pyi diff --git a/mypy/stdlib/python2/future_builtins.pyi b/mypy/typeshed/stdlib/python2/future_builtins.pyi similarity index 100% rename from mypy/stdlib/python2/future_builtins.pyi rename to mypy/typeshed/stdlib/python2/future_builtins.pyi diff --git a/mypy/stdlib/python2/gc.pyi b/mypy/typeshed/stdlib/python2/gc.pyi similarity index 100% rename from mypy/stdlib/python2/gc.pyi rename to mypy/typeshed/stdlib/python2/gc.pyi diff --git a/mypy/stdlib/python2/getopt.pyi b/mypy/typeshed/stdlib/python2/getopt.pyi similarity index 100% rename from mypy/stdlib/python2/getopt.pyi rename to mypy/typeshed/stdlib/python2/getopt.pyi diff --git a/mypy/stdlib/python2/getpass.pyi b/mypy/typeshed/stdlib/python2/getpass.pyi similarity index 100% rename from mypy/stdlib/python2/getpass.pyi rename to mypy/typeshed/stdlib/python2/getpass.pyi diff --git a/mypy/stdlib/python2/gettext.pyi b/mypy/typeshed/stdlib/python2/gettext.pyi similarity index 100% rename from mypy/stdlib/python2/gettext.pyi rename to mypy/typeshed/stdlib/python2/gettext.pyi diff --git a/mypy/stdlib/python2/glob.pyi b/mypy/typeshed/stdlib/python2/glob.pyi similarity index 100% rename from mypy/stdlib/python2/glob.pyi rename to mypy/typeshed/stdlib/python2/glob.pyi diff --git a/mypy/stdlib/python2/gzip.pyi b/mypy/typeshed/stdlib/python2/gzip.pyi similarity index 100% rename from mypy/stdlib/python2/gzip.pyi rename to mypy/typeshed/stdlib/python2/gzip.pyi diff --git a/mypy/stdlib/python2/hashlib.pyi b/mypy/typeshed/stdlib/python2/hashlib.pyi similarity index 100% rename from mypy/stdlib/python2/hashlib.pyi rename to mypy/typeshed/stdlib/python2/hashlib.pyi diff --git a/mypy/stdlib/python2/heapq.pyi b/mypy/typeshed/stdlib/python2/heapq.pyi similarity index 100% rename from mypy/stdlib/python2/heapq.pyi rename to mypy/typeshed/stdlib/python2/heapq.pyi diff --git a/mypy/stdlib/python2/htmlentitydefs.pyi b/mypy/typeshed/stdlib/python2/htmlentitydefs.pyi similarity index 100% rename from mypy/stdlib/python2/htmlentitydefs.pyi rename to mypy/typeshed/stdlib/python2/htmlentitydefs.pyi diff --git a/mypy/stdlib/python2/httplib.pyi b/mypy/typeshed/stdlib/python2/httplib.pyi similarity index 100% rename from mypy/stdlib/python2/httplib.pyi rename to mypy/typeshed/stdlib/python2/httplib.pyi diff --git a/mypy/stdlib/python2/imp.pyi b/mypy/typeshed/stdlib/python2/imp.pyi similarity index 100% rename from mypy/stdlib/python2/imp.pyi rename to mypy/typeshed/stdlib/python2/imp.pyi diff --git a/mypy/stdlib/python2/importlib.pyi b/mypy/typeshed/stdlib/python2/importlib.pyi similarity index 100% rename from mypy/stdlib/python2/importlib.pyi rename to mypy/typeshed/stdlib/python2/importlib.pyi diff --git a/mypy/stdlib/python2/inspect.pyi b/mypy/typeshed/stdlib/python2/inspect.pyi similarity index 100% rename from mypy/stdlib/python2/inspect.pyi rename to mypy/typeshed/stdlib/python2/inspect.pyi diff --git a/mypy/stdlib/python2/io.pyi b/mypy/typeshed/stdlib/python2/io.pyi similarity index 100% rename from mypy/stdlib/python2/io.pyi rename to mypy/typeshed/stdlib/python2/io.pyi diff --git a/mypy/stdlib/python2/itertools.pyi b/mypy/typeshed/stdlib/python2/itertools.pyi similarity index 100% rename from mypy/stdlib/python2/itertools.pyi rename to mypy/typeshed/stdlib/python2/itertools.pyi diff --git a/mypy/stdlib/python2/json.pyi b/mypy/typeshed/stdlib/python2/json.pyi similarity index 100% rename from mypy/stdlib/python2/json.pyi rename to mypy/typeshed/stdlib/python2/json.pyi diff --git a/mypy/stdlib/python2/markupbase.pyi b/mypy/typeshed/stdlib/python2/markupbase.pyi similarity index 100% rename from mypy/stdlib/python2/markupbase.pyi rename to mypy/typeshed/stdlib/python2/markupbase.pyi diff --git a/mypy/stdlib/python2/md5.pyi b/mypy/typeshed/stdlib/python2/md5.pyi similarity index 100% rename from mypy/stdlib/python2/md5.pyi rename to mypy/typeshed/stdlib/python2/md5.pyi diff --git a/mypy/stdlib/python2/mimetools.pyi b/mypy/typeshed/stdlib/python2/mimetools.pyi similarity index 100% rename from mypy/stdlib/python2/mimetools.pyi rename to mypy/typeshed/stdlib/python2/mimetools.pyi diff --git a/mypy/stdlib/python2/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/__init__.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi diff --git a/mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/dummy/__init__.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi diff --git a/mypy/stdlib/python2/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/dummy/connection.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi diff --git a/mypy/stdlib/python2/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/pool.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi diff --git a/mypy/stdlib/python2/multiprocessing/process.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/process.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/process.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/process.pyi diff --git a/mypy/stdlib/python2/multiprocessing/util.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/util.pyi similarity index 100% rename from mypy/stdlib/python2/multiprocessing/util.pyi rename to mypy/typeshed/stdlib/python2/multiprocessing/util.pyi diff --git a/mypy/stdlib/python2/mutex.pyi b/mypy/typeshed/stdlib/python2/mutex.pyi similarity index 100% rename from mypy/stdlib/python2/mutex.pyi rename to mypy/typeshed/stdlib/python2/mutex.pyi diff --git a/mypy/stdlib/python2/nturl2path.pyi b/mypy/typeshed/stdlib/python2/nturl2path.pyi similarity index 100% rename from mypy/stdlib/python2/nturl2path.pyi rename to mypy/typeshed/stdlib/python2/nturl2path.pyi diff --git a/mypy/stdlib/python2/os/__init__.pyi b/mypy/typeshed/stdlib/python2/os/__init__.pyi similarity index 100% rename from mypy/stdlib/python2/os/__init__.pyi rename to mypy/typeshed/stdlib/python2/os/__init__.pyi diff --git a/mypy/stdlib/python2/os/path.pyi b/mypy/typeshed/stdlib/python2/os/path.pyi similarity index 100% rename from mypy/stdlib/python2/os/path.pyi rename to mypy/typeshed/stdlib/python2/os/path.pyi diff --git a/mypy/stdlib/python2/os2emxpath.pyi b/mypy/typeshed/stdlib/python2/os2emxpath.pyi similarity index 100% rename from mypy/stdlib/python2/os2emxpath.pyi rename to mypy/typeshed/stdlib/python2/os2emxpath.pyi diff --git a/mypy/stdlib/python2/pipes.pyi b/mypy/typeshed/stdlib/python2/pipes.pyi similarity index 100% rename from mypy/stdlib/python2/pipes.pyi rename to mypy/typeshed/stdlib/python2/pipes.pyi diff --git a/mypy/stdlib/python2/platform.pyi b/mypy/typeshed/stdlib/python2/platform.pyi similarity index 100% rename from mypy/stdlib/python2/platform.pyi rename to mypy/typeshed/stdlib/python2/platform.pyi diff --git a/mypy/stdlib/python2/popen2.pyi b/mypy/typeshed/stdlib/python2/popen2.pyi similarity index 100% rename from mypy/stdlib/python2/popen2.pyi rename to mypy/typeshed/stdlib/python2/popen2.pyi diff --git a/mypy/stdlib/python2/posix.pyi b/mypy/typeshed/stdlib/python2/posix.pyi similarity index 100% rename from mypy/stdlib/python2/posix.pyi rename to mypy/typeshed/stdlib/python2/posix.pyi diff --git a/mypy/stdlib/python2/random.pyi b/mypy/typeshed/stdlib/python2/random.pyi similarity index 100% rename from mypy/stdlib/python2/random.pyi rename to mypy/typeshed/stdlib/python2/random.pyi diff --git a/mypy/stdlib/python2/re.pyi b/mypy/typeshed/stdlib/python2/re.pyi similarity index 100% rename from mypy/stdlib/python2/re.pyi rename to mypy/typeshed/stdlib/python2/re.pyi diff --git a/mypy/stdlib/python2/repr.pyi b/mypy/typeshed/stdlib/python2/repr.pyi similarity index 100% rename from mypy/stdlib/python2/repr.pyi rename to mypy/typeshed/stdlib/python2/repr.pyi diff --git a/mypy/stdlib/python2/resource.pyi b/mypy/typeshed/stdlib/python2/resource.pyi similarity index 100% rename from mypy/stdlib/python2/resource.pyi rename to mypy/typeshed/stdlib/python2/resource.pyi diff --git a/mypy/stdlib/python2/rfc822.pyi b/mypy/typeshed/stdlib/python2/rfc822.pyi similarity index 100% rename from mypy/stdlib/python2/rfc822.pyi rename to mypy/typeshed/stdlib/python2/rfc822.pyi diff --git a/mypy/stdlib/python2/robotparser.pyi b/mypy/typeshed/stdlib/python2/robotparser.pyi similarity index 100% rename from mypy/stdlib/python2/robotparser.pyi rename to mypy/typeshed/stdlib/python2/robotparser.pyi diff --git a/mypy/stdlib/python2/runpy.pyi b/mypy/typeshed/stdlib/python2/runpy.pyi similarity index 100% rename from mypy/stdlib/python2/runpy.pyi rename to mypy/typeshed/stdlib/python2/runpy.pyi diff --git a/mypy/stdlib/python2/sets.pyi b/mypy/typeshed/stdlib/python2/sets.pyi similarity index 100% rename from mypy/stdlib/python2/sets.pyi rename to mypy/typeshed/stdlib/python2/sets.pyi diff --git a/mypy/stdlib/python2/sha.pyi b/mypy/typeshed/stdlib/python2/sha.pyi similarity index 100% rename from mypy/stdlib/python2/sha.pyi rename to mypy/typeshed/stdlib/python2/sha.pyi diff --git a/mypy/stdlib/python2/shelve.pyi b/mypy/typeshed/stdlib/python2/shelve.pyi similarity index 100% rename from mypy/stdlib/python2/shelve.pyi rename to mypy/typeshed/stdlib/python2/shelve.pyi diff --git a/mypy/stdlib/python2/shlex.pyi b/mypy/typeshed/stdlib/python2/shlex.pyi similarity index 100% rename from mypy/stdlib/python2/shlex.pyi rename to mypy/typeshed/stdlib/python2/shlex.pyi diff --git a/mypy/stdlib/python2/signal.pyi b/mypy/typeshed/stdlib/python2/signal.pyi similarity index 100% rename from mypy/stdlib/python2/signal.pyi rename to mypy/typeshed/stdlib/python2/signal.pyi diff --git a/mypy/stdlib/python2/smtplib.pyi b/mypy/typeshed/stdlib/python2/smtplib.pyi similarity index 100% rename from mypy/stdlib/python2/smtplib.pyi rename to mypy/typeshed/stdlib/python2/smtplib.pyi diff --git a/mypy/stdlib/python2/spwd.pyi b/mypy/typeshed/stdlib/python2/spwd.pyi similarity index 100% rename from mypy/stdlib/python2/spwd.pyi rename to mypy/typeshed/stdlib/python2/spwd.pyi diff --git a/mypy/stdlib/python2/sre_constants.pyi b/mypy/typeshed/stdlib/python2/sre_constants.pyi similarity index 100% rename from mypy/stdlib/python2/sre_constants.pyi rename to mypy/typeshed/stdlib/python2/sre_constants.pyi diff --git a/mypy/stdlib/python2/sre_parse.pyi b/mypy/typeshed/stdlib/python2/sre_parse.pyi similarity index 100% rename from mypy/stdlib/python2/sre_parse.pyi rename to mypy/typeshed/stdlib/python2/sre_parse.pyi diff --git a/mypy/stdlib/python2/stat.pyi b/mypy/typeshed/stdlib/python2/stat.pyi similarity index 100% rename from mypy/stdlib/python2/stat.pyi rename to mypy/typeshed/stdlib/python2/stat.pyi diff --git a/mypy/stdlib/python2/string.pyi b/mypy/typeshed/stdlib/python2/string.pyi similarity index 100% rename from mypy/stdlib/python2/string.pyi rename to mypy/typeshed/stdlib/python2/string.pyi diff --git a/mypy/stdlib/python2/stringold.pyi b/mypy/typeshed/stdlib/python2/stringold.pyi similarity index 100% rename from mypy/stdlib/python2/stringold.pyi rename to mypy/typeshed/stdlib/python2/stringold.pyi diff --git a/mypy/stdlib/python2/strop.pyi b/mypy/typeshed/stdlib/python2/strop.pyi similarity index 100% rename from mypy/stdlib/python2/strop.pyi rename to mypy/typeshed/stdlib/python2/strop.pyi diff --git a/mypy/stdlib/python2/subprocess.pyi b/mypy/typeshed/stdlib/python2/subprocess.pyi similarity index 100% rename from mypy/stdlib/python2/subprocess.pyi rename to mypy/typeshed/stdlib/python2/subprocess.pyi diff --git a/mypy/stdlib/python2/symbol.pyi b/mypy/typeshed/stdlib/python2/symbol.pyi similarity index 100% rename from mypy/stdlib/python2/symbol.pyi rename to mypy/typeshed/stdlib/python2/symbol.pyi diff --git a/mypy/stdlib/python2/sys.pyi b/mypy/typeshed/stdlib/python2/sys.pyi similarity index 100% rename from mypy/stdlib/python2/sys.pyi rename to mypy/typeshed/stdlib/python2/sys.pyi diff --git a/mypy/stdlib/python2/tempfile.pyi b/mypy/typeshed/stdlib/python2/tempfile.pyi similarity index 100% rename from mypy/stdlib/python2/tempfile.pyi rename to mypy/typeshed/stdlib/python2/tempfile.pyi diff --git a/mypy/stdlib/python2/textwrap.pyi b/mypy/typeshed/stdlib/python2/textwrap.pyi similarity index 100% rename from mypy/stdlib/python2/textwrap.pyi rename to mypy/typeshed/stdlib/python2/textwrap.pyi diff --git a/mypy/stdlib/python2/thread.pyi b/mypy/typeshed/stdlib/python2/thread.pyi similarity index 100% rename from mypy/stdlib/python2/thread.pyi rename to mypy/typeshed/stdlib/python2/thread.pyi diff --git a/mypy/stdlib/python2/toaiff.pyi b/mypy/typeshed/stdlib/python2/toaiff.pyi similarity index 100% rename from mypy/stdlib/python2/toaiff.pyi rename to mypy/typeshed/stdlib/python2/toaiff.pyi diff --git a/mypy/stdlib/python2/tokenize.pyi b/mypy/typeshed/stdlib/python2/tokenize.pyi similarity index 100% rename from mypy/stdlib/python2/tokenize.pyi rename to mypy/typeshed/stdlib/python2/tokenize.pyi diff --git a/mypy/stdlib/python2/types.pyi b/mypy/typeshed/stdlib/python2/types.pyi similarity index 100% rename from mypy/stdlib/python2/types.pyi rename to mypy/typeshed/stdlib/python2/types.pyi diff --git a/mypy/stdlib/python2/typing.pyi b/mypy/typeshed/stdlib/python2/typing.pyi similarity index 100% rename from mypy/stdlib/python2/typing.pyi rename to mypy/typeshed/stdlib/python2/typing.pyi diff --git a/mypy/stdlib/python2/unittest.pyi b/mypy/typeshed/stdlib/python2/unittest.pyi similarity index 100% rename from mypy/stdlib/python2/unittest.pyi rename to mypy/typeshed/stdlib/python2/unittest.pyi diff --git a/mypy/stdlib/python2/urllib.pyi b/mypy/typeshed/stdlib/python2/urllib.pyi similarity index 100% rename from mypy/stdlib/python2/urllib.pyi rename to mypy/typeshed/stdlib/python2/urllib.pyi diff --git a/mypy/stdlib/python2/urllib2.pyi b/mypy/typeshed/stdlib/python2/urllib2.pyi similarity index 100% rename from mypy/stdlib/python2/urllib2.pyi rename to mypy/typeshed/stdlib/python2/urllib2.pyi diff --git a/mypy/stdlib/python2/urlparse.pyi b/mypy/typeshed/stdlib/python2/urlparse.pyi similarity index 100% rename from mypy/stdlib/python2/urlparse.pyi rename to mypy/typeshed/stdlib/python2/urlparse.pyi diff --git a/mypy/stdlib/python2/user.pyi b/mypy/typeshed/stdlib/python2/user.pyi similarity index 100% rename from mypy/stdlib/python2/user.pyi rename to mypy/typeshed/stdlib/python2/user.pyi diff --git a/mypy/stdlib/python2/whichdb.pyi b/mypy/typeshed/stdlib/python2/whichdb.pyi similarity index 100% rename from mypy/stdlib/python2/whichdb.pyi rename to mypy/typeshed/stdlib/python2/whichdb.pyi diff --git a/mypy/stdlib/python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/python2/xmlrpclib.pyi similarity index 100% rename from mypy/stdlib/python2/xmlrpclib.pyi rename to mypy/typeshed/stdlib/python2/xmlrpclib.pyi diff --git a/mypy/stdlib/queue.pyi b/mypy/typeshed/stdlib/queue.pyi similarity index 100% rename from mypy/stdlib/queue.pyi rename to mypy/typeshed/stdlib/queue.pyi diff --git a/mypy/stdlib/quopri.pyi b/mypy/typeshed/stdlib/quopri.pyi similarity index 100% rename from mypy/stdlib/quopri.pyi rename to mypy/typeshed/stdlib/quopri.pyi diff --git a/mypy/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi similarity index 100% rename from mypy/stdlib/random.pyi rename to mypy/typeshed/stdlib/random.pyi diff --git a/mypy/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi similarity index 100% rename from mypy/stdlib/re.pyi rename to mypy/typeshed/stdlib/re.pyi diff --git a/mypy/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi similarity index 100% rename from mypy/stdlib/readline.pyi rename to mypy/typeshed/stdlib/readline.pyi diff --git a/mypy/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi similarity index 100% rename from mypy/stdlib/reprlib.pyi rename to mypy/typeshed/stdlib/reprlib.pyi diff --git a/mypy/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi similarity index 100% rename from mypy/stdlib/resource.pyi rename to mypy/typeshed/stdlib/resource.pyi diff --git a/mypy/stdlib/rlcompleter.pyi b/mypy/typeshed/stdlib/rlcompleter.pyi similarity index 100% rename from mypy/stdlib/rlcompleter.pyi rename to mypy/typeshed/stdlib/rlcompleter.pyi diff --git a/mypy/stdlib/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi similarity index 100% rename from mypy/stdlib/runpy.pyi rename to mypy/typeshed/stdlib/runpy.pyi diff --git a/mypy/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi similarity index 100% rename from mypy/stdlib/sched.pyi rename to mypy/typeshed/stdlib/sched.pyi diff --git a/mypy/stdlib/secrets.pyi b/mypy/typeshed/stdlib/secrets.pyi similarity index 100% rename from mypy/stdlib/secrets.pyi rename to mypy/typeshed/stdlib/secrets.pyi diff --git a/mypy/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi similarity index 100% rename from mypy/stdlib/select.pyi rename to mypy/typeshed/stdlib/select.pyi diff --git a/mypy/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi similarity index 100% rename from mypy/stdlib/selectors.pyi rename to mypy/typeshed/stdlib/selectors.pyi diff --git a/mypy/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi similarity index 100% rename from mypy/stdlib/shelve.pyi rename to mypy/typeshed/stdlib/shelve.pyi diff --git a/mypy/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi similarity index 100% rename from mypy/stdlib/shlex.pyi rename to mypy/typeshed/stdlib/shlex.pyi diff --git a/mypy/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi similarity index 100% rename from mypy/stdlib/shutil.pyi rename to mypy/typeshed/stdlib/shutil.pyi diff --git a/mypy/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi similarity index 100% rename from mypy/stdlib/signal.pyi rename to mypy/typeshed/stdlib/signal.pyi diff --git a/mypy/stdlib/site.pyi b/mypy/typeshed/stdlib/site.pyi similarity index 100% rename from mypy/stdlib/site.pyi rename to mypy/typeshed/stdlib/site.pyi diff --git a/mypy/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi similarity index 100% rename from mypy/stdlib/smtpd.pyi rename to mypy/typeshed/stdlib/smtpd.pyi diff --git a/mypy/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi similarity index 100% rename from mypy/stdlib/smtplib.pyi rename to mypy/typeshed/stdlib/smtplib.pyi diff --git a/mypy/stdlib/sndhdr.pyi b/mypy/typeshed/stdlib/sndhdr.pyi similarity index 100% rename from mypy/stdlib/sndhdr.pyi rename to mypy/typeshed/stdlib/sndhdr.pyi diff --git a/mypy/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi similarity index 100% rename from mypy/stdlib/socket.pyi rename to mypy/typeshed/stdlib/socket.pyi diff --git a/mypy/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi similarity index 100% rename from mypy/stdlib/socketserver.pyi rename to mypy/typeshed/stdlib/socketserver.pyi diff --git a/mypy/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi similarity index 100% rename from mypy/stdlib/spwd.pyi rename to mypy/typeshed/stdlib/spwd.pyi diff --git a/mypy/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi similarity index 100% rename from mypy/stdlib/sqlite3/__init__.pyi rename to mypy/typeshed/stdlib/sqlite3/__init__.pyi diff --git a/mypy/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi similarity index 100% rename from mypy/stdlib/sqlite3/dbapi2.pyi rename to mypy/typeshed/stdlib/sqlite3/dbapi2.pyi diff --git a/mypy/stdlib/sre_compile.pyi b/mypy/typeshed/stdlib/sre_compile.pyi similarity index 100% rename from mypy/stdlib/sre_compile.pyi rename to mypy/typeshed/stdlib/sre_compile.pyi diff --git a/mypy/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi similarity index 100% rename from mypy/stdlib/sre_constants.pyi rename to mypy/typeshed/stdlib/sre_constants.pyi diff --git a/mypy/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi similarity index 100% rename from mypy/stdlib/sre_parse.pyi rename to mypy/typeshed/stdlib/sre_parse.pyi diff --git a/mypy/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi similarity index 100% rename from mypy/stdlib/ssl.pyi rename to mypy/typeshed/stdlib/ssl.pyi diff --git a/mypy/stdlib/stat.pyi b/mypy/typeshed/stdlib/stat.pyi similarity index 100% rename from mypy/stdlib/stat.pyi rename to mypy/typeshed/stdlib/stat.pyi diff --git a/mypy/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi similarity index 100% rename from mypy/stdlib/statistics.pyi rename to mypy/typeshed/stdlib/statistics.pyi diff --git a/mypy/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi similarity index 100% rename from mypy/stdlib/string.pyi rename to mypy/typeshed/stdlib/string.pyi diff --git a/mypy/stdlib/stringprep.pyi b/mypy/typeshed/stdlib/stringprep.pyi similarity index 100% rename from mypy/stdlib/stringprep.pyi rename to mypy/typeshed/stdlib/stringprep.pyi diff --git a/mypy/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi similarity index 100% rename from mypy/stdlib/struct.pyi rename to mypy/typeshed/stdlib/struct.pyi diff --git a/mypy/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi similarity index 100% rename from mypy/stdlib/subprocess.pyi rename to mypy/typeshed/stdlib/subprocess.pyi diff --git a/mypy/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi similarity index 100% rename from mypy/stdlib/sunau.pyi rename to mypy/typeshed/stdlib/sunau.pyi diff --git a/mypy/stdlib/symbol.pyi b/mypy/typeshed/stdlib/symbol.pyi similarity index 100% rename from mypy/stdlib/symbol.pyi rename to mypy/typeshed/stdlib/symbol.pyi diff --git a/mypy/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi similarity index 100% rename from mypy/stdlib/symtable.pyi rename to mypy/typeshed/stdlib/symtable.pyi diff --git a/mypy/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi similarity index 100% rename from mypy/stdlib/sys.pyi rename to mypy/typeshed/stdlib/sys.pyi diff --git a/mypy/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi similarity index 100% rename from mypy/stdlib/sysconfig.pyi rename to mypy/typeshed/stdlib/sysconfig.pyi diff --git a/mypy/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi similarity index 100% rename from mypy/stdlib/syslog.pyi rename to mypy/typeshed/stdlib/syslog.pyi diff --git a/mypy/stdlib/tabnanny.pyi b/mypy/typeshed/stdlib/tabnanny.pyi similarity index 100% rename from mypy/stdlib/tabnanny.pyi rename to mypy/typeshed/stdlib/tabnanny.pyi diff --git a/mypy/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi similarity index 100% rename from mypy/stdlib/tarfile.pyi rename to mypy/typeshed/stdlib/tarfile.pyi diff --git a/mypy/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi similarity index 100% rename from mypy/stdlib/telnetlib.pyi rename to mypy/typeshed/stdlib/telnetlib.pyi diff --git a/mypy/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi similarity index 100% rename from mypy/stdlib/tempfile.pyi rename to mypy/typeshed/stdlib/tempfile.pyi diff --git a/mypy/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi similarity index 100% rename from mypy/stdlib/termios.pyi rename to mypy/typeshed/stdlib/termios.pyi diff --git a/mypy/stdlib/textwrap.pyi b/mypy/typeshed/stdlib/textwrap.pyi similarity index 100% rename from mypy/stdlib/textwrap.pyi rename to mypy/typeshed/stdlib/textwrap.pyi diff --git a/mypy/stdlib/this.pyi b/mypy/typeshed/stdlib/this.pyi similarity index 100% rename from mypy/stdlib/this.pyi rename to mypy/typeshed/stdlib/this.pyi diff --git a/mypy/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi similarity index 100% rename from mypy/stdlib/threading.pyi rename to mypy/typeshed/stdlib/threading.pyi diff --git a/mypy/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi similarity index 100% rename from mypy/stdlib/time.pyi rename to mypy/typeshed/stdlib/time.pyi diff --git a/mypy/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi similarity index 100% rename from mypy/stdlib/timeit.pyi rename to mypy/typeshed/stdlib/timeit.pyi diff --git a/mypy/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi similarity index 100% rename from mypy/stdlib/tkinter/__init__.pyi rename to mypy/typeshed/stdlib/tkinter/__init__.pyi diff --git a/mypy/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi similarity index 100% rename from mypy/stdlib/tkinter/commondialog.pyi rename to mypy/typeshed/stdlib/tkinter/commondialog.pyi diff --git a/mypy/stdlib/tkinter/constants.pyi b/mypy/typeshed/stdlib/tkinter/constants.pyi similarity index 100% rename from mypy/stdlib/tkinter/constants.pyi rename to mypy/typeshed/stdlib/tkinter/constants.pyi diff --git a/mypy/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi similarity index 100% rename from mypy/stdlib/tkinter/dialog.pyi rename to mypy/typeshed/stdlib/tkinter/dialog.pyi diff --git a/mypy/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi similarity index 100% rename from mypy/stdlib/tkinter/filedialog.pyi rename to mypy/typeshed/stdlib/tkinter/filedialog.pyi diff --git a/mypy/stdlib/tkinter/messagebox.pyi b/mypy/typeshed/stdlib/tkinter/messagebox.pyi similarity index 100% rename from mypy/stdlib/tkinter/messagebox.pyi rename to mypy/typeshed/stdlib/tkinter/messagebox.pyi diff --git a/mypy/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi similarity index 100% rename from mypy/stdlib/tkinter/ttk.pyi rename to mypy/typeshed/stdlib/tkinter/ttk.pyi diff --git a/mypy/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi similarity index 100% rename from mypy/stdlib/token.pyi rename to mypy/typeshed/stdlib/token.pyi diff --git a/mypy/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi similarity index 100% rename from mypy/stdlib/tokenize.pyi rename to mypy/typeshed/stdlib/tokenize.pyi diff --git a/mypy/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi similarity index 100% rename from mypy/stdlib/trace.pyi rename to mypy/typeshed/stdlib/trace.pyi diff --git a/mypy/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi similarity index 100% rename from mypy/stdlib/traceback.pyi rename to mypy/typeshed/stdlib/traceback.pyi diff --git a/mypy/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi similarity index 100% rename from mypy/stdlib/tracemalloc.pyi rename to mypy/typeshed/stdlib/tracemalloc.pyi diff --git a/mypy/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi similarity index 100% rename from mypy/stdlib/tty.pyi rename to mypy/typeshed/stdlib/tty.pyi diff --git a/mypy/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi similarity index 100% rename from mypy/stdlib/turtle.pyi rename to mypy/typeshed/stdlib/turtle.pyi diff --git a/mypy/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi similarity index 100% rename from mypy/stdlib/types.pyi rename to mypy/typeshed/stdlib/types.pyi diff --git a/mypy/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi similarity index 100% rename from mypy/stdlib/typing.pyi rename to mypy/typeshed/stdlib/typing.pyi diff --git a/mypy/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi similarity index 100% rename from mypy/stdlib/unicodedata.pyi rename to mypy/typeshed/stdlib/unicodedata.pyi diff --git a/mypy/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi similarity index 100% rename from mypy/stdlib/unittest/__init__.pyi rename to mypy/typeshed/stdlib/unittest/__init__.pyi diff --git a/mypy/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi similarity index 100% rename from mypy/stdlib/unittest/async_case.pyi rename to mypy/typeshed/stdlib/unittest/async_case.pyi diff --git a/mypy/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi similarity index 100% rename from mypy/stdlib/unittest/case.pyi rename to mypy/typeshed/stdlib/unittest/case.pyi diff --git a/mypy/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi similarity index 100% rename from mypy/stdlib/unittest/loader.pyi rename to mypy/typeshed/stdlib/unittest/loader.pyi diff --git a/mypy/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi similarity index 100% rename from mypy/stdlib/unittest/main.pyi rename to mypy/typeshed/stdlib/unittest/main.pyi diff --git a/mypy/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi similarity index 100% rename from mypy/stdlib/unittest/mock.pyi rename to mypy/typeshed/stdlib/unittest/mock.pyi diff --git a/mypy/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi similarity index 100% rename from mypy/stdlib/unittest/result.pyi rename to mypy/typeshed/stdlib/unittest/result.pyi diff --git a/mypy/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi similarity index 100% rename from mypy/stdlib/unittest/runner.pyi rename to mypy/typeshed/stdlib/unittest/runner.pyi diff --git a/mypy/stdlib/unittest/signals.pyi b/mypy/typeshed/stdlib/unittest/signals.pyi similarity index 100% rename from mypy/stdlib/unittest/signals.pyi rename to mypy/typeshed/stdlib/unittest/signals.pyi diff --git a/mypy/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi similarity index 100% rename from mypy/stdlib/unittest/suite.pyi rename to mypy/typeshed/stdlib/unittest/suite.pyi diff --git a/mypy/stdlib/unittest/util.pyi b/mypy/typeshed/stdlib/unittest/util.pyi similarity index 100% rename from mypy/stdlib/unittest/util.pyi rename to mypy/typeshed/stdlib/unittest/util.pyi diff --git a/mypy/stdlib/urllib/__init__.pyi b/mypy/typeshed/stdlib/urllib/__init__.pyi similarity index 100% rename from mypy/stdlib/urllib/__init__.pyi rename to mypy/typeshed/stdlib/urllib/__init__.pyi diff --git a/mypy/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi similarity index 100% rename from mypy/stdlib/urllib/error.pyi rename to mypy/typeshed/stdlib/urllib/error.pyi diff --git a/mypy/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi similarity index 100% rename from mypy/stdlib/urllib/parse.pyi rename to mypy/typeshed/stdlib/urllib/parse.pyi diff --git a/mypy/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi similarity index 100% rename from mypy/stdlib/urllib/request.pyi rename to mypy/typeshed/stdlib/urllib/request.pyi diff --git a/mypy/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi similarity index 100% rename from mypy/stdlib/urllib/response.pyi rename to mypy/typeshed/stdlib/urllib/response.pyi diff --git a/mypy/stdlib/urllib/robotparser.pyi b/mypy/typeshed/stdlib/urllib/robotparser.pyi similarity index 100% rename from mypy/stdlib/urllib/robotparser.pyi rename to mypy/typeshed/stdlib/urllib/robotparser.pyi diff --git a/mypy/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi similarity index 100% rename from mypy/stdlib/uu.pyi rename to mypy/typeshed/stdlib/uu.pyi diff --git a/mypy/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi similarity index 100% rename from mypy/stdlib/uuid.pyi rename to mypy/typeshed/stdlib/uuid.pyi diff --git a/mypy/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi similarity index 100% rename from mypy/stdlib/venv/__init__.pyi rename to mypy/typeshed/stdlib/venv/__init__.pyi diff --git a/mypy/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi similarity index 100% rename from mypy/stdlib/warnings.pyi rename to mypy/typeshed/stdlib/warnings.pyi diff --git a/mypy/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi similarity index 100% rename from mypy/stdlib/wave.pyi rename to mypy/typeshed/stdlib/wave.pyi diff --git a/mypy/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi similarity index 100% rename from mypy/stdlib/weakref.pyi rename to mypy/typeshed/stdlib/weakref.pyi diff --git a/mypy/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi similarity index 100% rename from mypy/stdlib/webbrowser.pyi rename to mypy/typeshed/stdlib/webbrowser.pyi diff --git a/mypy/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi similarity index 100% rename from mypy/stdlib/winreg.pyi rename to mypy/typeshed/stdlib/winreg.pyi diff --git a/mypy/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi similarity index 100% rename from mypy/stdlib/winsound.pyi rename to mypy/typeshed/stdlib/winsound.pyi diff --git a/mypy/stdlib/wsgiref/__init__.pyi b/mypy/typeshed/stdlib/wsgiref/__init__.pyi similarity index 100% rename from mypy/stdlib/wsgiref/__init__.pyi rename to mypy/typeshed/stdlib/wsgiref/__init__.pyi diff --git a/mypy/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi similarity index 100% rename from mypy/stdlib/wsgiref/handlers.pyi rename to mypy/typeshed/stdlib/wsgiref/handlers.pyi diff --git a/mypy/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi similarity index 100% rename from mypy/stdlib/wsgiref/headers.pyi rename to mypy/typeshed/stdlib/wsgiref/headers.pyi diff --git a/mypy/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi similarity index 100% rename from mypy/stdlib/wsgiref/simple_server.pyi rename to mypy/typeshed/stdlib/wsgiref/simple_server.pyi diff --git a/mypy/stdlib/wsgiref/types.pyi b/mypy/typeshed/stdlib/wsgiref/types.pyi similarity index 100% rename from mypy/stdlib/wsgiref/types.pyi rename to mypy/typeshed/stdlib/wsgiref/types.pyi diff --git a/mypy/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi similarity index 100% rename from mypy/stdlib/wsgiref/util.pyi rename to mypy/typeshed/stdlib/wsgiref/util.pyi diff --git a/mypy/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi similarity index 100% rename from mypy/stdlib/wsgiref/validate.pyi rename to mypy/typeshed/stdlib/wsgiref/validate.pyi diff --git a/mypy/stdlib/xdrlib.pyi b/mypy/typeshed/stdlib/xdrlib.pyi similarity index 100% rename from mypy/stdlib/xdrlib.pyi rename to mypy/typeshed/stdlib/xdrlib.pyi diff --git a/mypy/stdlib/xml/__init__.pyi b/mypy/typeshed/stdlib/xml/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/__init__.pyi rename to mypy/typeshed/stdlib/xml/__init__.pyi diff --git a/mypy/stdlib/xml/dom/NodeFilter.pyi b/mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi similarity index 100% rename from mypy/stdlib/xml/dom/NodeFilter.pyi rename to mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi diff --git a/mypy/stdlib/xml/dom/__init__.pyi b/mypy/typeshed/stdlib/xml/dom/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/dom/__init__.pyi rename to mypy/typeshed/stdlib/xml/dom/__init__.pyi diff --git a/mypy/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi similarity index 100% rename from mypy/stdlib/xml/dom/minidom.pyi rename to mypy/typeshed/stdlib/xml/dom/minidom.pyi diff --git a/mypy/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi similarity index 100% rename from mypy/stdlib/xml/dom/pulldom.pyi rename to mypy/typeshed/stdlib/xml/dom/pulldom.pyi diff --git a/mypy/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi similarity index 100% rename from mypy/stdlib/xml/etree/ElementInclude.pyi rename to mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi diff --git a/mypy/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi similarity index 100% rename from mypy/stdlib/xml/etree/ElementPath.pyi rename to mypy/typeshed/stdlib/xml/etree/ElementPath.pyi diff --git a/mypy/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi similarity index 100% rename from mypy/stdlib/xml/etree/ElementTree.pyi rename to mypy/typeshed/stdlib/xml/etree/ElementTree.pyi diff --git a/mypy/stdlib/xml/etree/__init__.pyi b/mypy/typeshed/stdlib/xml/etree/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/etree/__init__.pyi rename to mypy/typeshed/stdlib/xml/etree/__init__.pyi diff --git a/mypy/stdlib/xml/etree/cElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi similarity index 100% rename from mypy/stdlib/xml/etree/cElementTree.pyi rename to mypy/typeshed/stdlib/xml/etree/cElementTree.pyi diff --git a/mypy/stdlib/xml/parsers/__init__.pyi b/mypy/typeshed/stdlib/xml/parsers/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/parsers/__init__.pyi rename to mypy/typeshed/stdlib/xml/parsers/__init__.pyi diff --git a/mypy/stdlib/xml/parsers/expat/__init__.pyi b/mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/parsers/expat/__init__.pyi rename to mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi diff --git a/mypy/stdlib/xml/parsers/expat/errors.pyi b/mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi similarity index 100% rename from mypy/stdlib/xml/parsers/expat/errors.pyi rename to mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi diff --git a/mypy/stdlib/xml/parsers/expat/model.pyi b/mypy/typeshed/stdlib/xml/parsers/expat/model.pyi similarity index 100% rename from mypy/stdlib/xml/parsers/expat/model.pyi rename to mypy/typeshed/stdlib/xml/parsers/expat/model.pyi diff --git a/mypy/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi similarity index 100% rename from mypy/stdlib/xml/sax/__init__.pyi rename to mypy/typeshed/stdlib/xml/sax/__init__.pyi diff --git a/mypy/stdlib/xml/sax/handler.pyi b/mypy/typeshed/stdlib/xml/sax/handler.pyi similarity index 100% rename from mypy/stdlib/xml/sax/handler.pyi rename to mypy/typeshed/stdlib/xml/sax/handler.pyi diff --git a/mypy/stdlib/xml/sax/saxutils.pyi b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi similarity index 100% rename from mypy/stdlib/xml/sax/saxutils.pyi rename to mypy/typeshed/stdlib/xml/sax/saxutils.pyi diff --git a/mypy/stdlib/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi similarity index 100% rename from mypy/stdlib/xml/sax/xmlreader.pyi rename to mypy/typeshed/stdlib/xml/sax/xmlreader.pyi diff --git a/mypy/stdlib/xmlrpc/__init__.pyi b/mypy/typeshed/stdlib/xmlrpc/__init__.pyi similarity index 100% rename from mypy/stdlib/xmlrpc/__init__.pyi rename to mypy/typeshed/stdlib/xmlrpc/__init__.pyi diff --git a/mypy/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi similarity index 100% rename from mypy/stdlib/xmlrpc/client.pyi rename to mypy/typeshed/stdlib/xmlrpc/client.pyi diff --git a/mypy/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi similarity index 100% rename from mypy/stdlib/xmlrpc/server.pyi rename to mypy/typeshed/stdlib/xmlrpc/server.pyi diff --git a/mypy/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi similarity index 100% rename from mypy/stdlib/zipapp.pyi rename to mypy/typeshed/stdlib/zipapp.pyi diff --git a/mypy/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi similarity index 100% rename from mypy/stdlib/zipfile.pyi rename to mypy/typeshed/stdlib/zipfile.pyi diff --git a/mypy/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi similarity index 100% rename from mypy/stdlib/zipimport.pyi rename to mypy/typeshed/stdlib/zipimport.pyi diff --git a/mypy/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi similarity index 100% rename from mypy/stdlib/zlib.pyi rename to mypy/typeshed/stdlib/zlib.pyi diff --git a/mypy/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi similarity index 100% rename from mypy/stdlib/zoneinfo/__init__.pyi rename to mypy/typeshed/stdlib/zoneinfo/__init__.pyi From 39de1f4018a1385984c94195a87c644505481509 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 25 Jun 2020 16:02:14 +0100 Subject: [PATCH 03/50] Support VERSIONS for stdlib minimum Python versions --- mypy/modulefinder.py | 84 +++++++++++++++++++++++++++++--------------- 1 file changed, 55 insertions(+), 29 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index bdc71d7a7e58..99d5d605fb30 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -1,6 +1,6 @@ """Low-level infrastructure to find modules. -This build on fscache.py; find_sources.py builds on top of this. +This builds on fscache.py; find_sources.py builds on top of this. """ import ast @@ -14,7 +14,6 @@ from typing import Dict, Iterator, List, NamedTuple, Optional, Set, Tuple, Union from typing_extensions import Final -from mypy.defaults import PYTHON3_VERSION_MIN from mypy.fscache import FileSystemCache from mypy.options import Options from mypy import sitepkgs @@ -116,6 +115,7 @@ def __init__(self, self.results = {} # type: Dict[str, ModuleSearchResult] self.ns_ancestors = {} # type: Dict[str, str] self.options = options + self.stdlib_py_versions = load_stdlib_py_versions() def clear(self) -> None: self.results.clear() @@ -125,7 +125,8 @@ def clear(self) -> None: def find_lib_path_dirs(self, id: str, lib_path: Tuple[str, ...]) -> PackageDirs: """Find which elements of a lib_path have the directory a module needs to exist. - This is run for the python_path, mypy_path, and typeshed_path search paths.""" + This is run for the python_path, mypy_path, and typeshed_path search paths. + """ components = id.split('.') dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' @@ -171,6 +172,11 @@ def get_toplevel_possibilities(self, lib_path: Tuple[str, ...], id: str) -> List def find_module(self, id: str) -> ModuleSearchResult: """Return the path of the module source file or why it wasn't found.""" if id not in self.results: + top_level = id.partition('.')[0] + use_typeshed = True + if top_level in self.stdlib_py_versions: + min_version = self.stdlib_py_versions[top_level] + use_typeshed = self.options is None or self.options.python_version >= min_version self.results[id] = self._find_module(id) if (self.results[id] is ModuleNotFoundReason.NOT_FOUND and self._can_find_module_in_parent_dir(id)): @@ -215,7 +221,7 @@ def _can_find_module_in_parent_dir(self, id: str) -> bool: return True return False - def _find_module(self, id: str) -> ModuleSearchResult: + def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: fscache = self.fscache # If we're looking for a module like 'foo.bar.baz', it's likely that most of the @@ -224,7 +230,6 @@ def _find_module(self, id: str) -> ModuleSearchResult: # that will require the same subdirectory. components = id.split('.') dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' - # TODO (ethanhs): refactor each path search to its own method with lru_cache # We have two sets of folders so that we collect *all* stubs folders and # put them in the front of the search path @@ -270,9 +275,11 @@ def _find_module(self, id: str) -> ModuleSearchResult: third_party_stubs_dirs.clear() found_possible_third_party_missing_type_hints = False python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path - candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path) + \ - third_party_stubs_dirs + third_party_inline_dirs + \ - self.find_lib_path_dirs(id, self.search_paths.typeshed_path) + candidate_base_dirs = (self.find_lib_path_dirs(id, python_mypy_path) + + third_party_stubs_dirs + + third_party_inline_dirs) + if use_typeshed: + candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path) # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now # contains just the subdirectories 'foo/bar' that actually exist under the @@ -442,7 +449,6 @@ def default_lib_path(data_dir: str, pyversion: Tuple[int, int], custom_typeshed_dir: Optional[str]) -> List[str]: """Return default standard library search paths.""" - # IDEA: Make this more portable. path = [] # type: List[str] if custom_typeshed_dir: @@ -451,21 +457,12 @@ def default_lib_path(data_dir: str, auto = os.path.join(data_dir, 'stubs-auto') if os.path.isdir(auto): data_dir = auto - typeshed_dir = os.path.join(data_dir, "typeshed") - if pyversion[0] == 3: - # We allow a module for e.g. version 3.5 to be in 3.4/. The assumption - # is that a module added with 3.4 will still be present in Python 3.5. - versions = ["%d.%d" % (pyversion[0], minor) - for minor in reversed(range(PYTHON3_VERSION_MIN[1], pyversion[1] + 1))] - else: - # For Python 2, we only have stubs for 2.7 - versions = ["2.7"] - # E.g. for Python 3.6, try 3.6/, 3.5/, 3.4/, 3/, 2and3/. - for v in versions + [str(pyversion[0]), '2and3']: - for lib_type in ['stdlib', 'third_party']: - stubdir = os.path.join(typeshed_dir, lib_type, v) - if os.path.isdir(stubdir): - path.append(stubdir) + typeshed_dir = os.path.join(data_dir, "typeshed", "stdlib") + if pyversion[0] == 2: + # Python 2 variants of certain stdlib modules are under python2/. + python2_dir = os.path.join(typeshed_dir, "python2") + path.append(python2_dir) + path.append(typeshed_dir) # Add fallback path that can be used if we have a broken installation. if sys.platform != 'win32': @@ -485,7 +482,8 @@ def get_site_packages_dirs(python_executable: Optional[str]) -> Tuple[List[str], This runs a subprocess call, which generates a list of the egg directories, and the site package directories. To avoid repeatedly calling a subprocess (which can be slow!) we - lru_cache the results.""" + lru_cache the results. + """ if python_executable is None: return [], [] @@ -623,7 +621,35 @@ def compute_search_paths(sources: List[BuildSource], file=sys.stderr) sys.exit(1) - return SearchPaths(tuple(reversed(python_path)), - tuple(mypypath), - tuple(egg_dirs + site_packages), - tuple(lib_path)) + return SearchPaths(python_path=tuple(reversed(python_path)), + mypy_path=tuple(mypypath), + package_path=tuple(egg_dirs + site_packages), + typeshed_path=tuple(lib_path)) + + +def load_stdlib_py_versions() -> Dict[str, Tuple[int, int]]: + """Return dict with minimum Python versions of stdlib modules. + + The contents look like {..., 'secrets': 3.6, 're': 2.7, ...}. + """ + typeshed_dir = os.path.join(os.path.dirname(__file__), "typeshed", "stdlib") + result = {} + + versions_path = os.path.join(typeshed_dir, "VERSIONS") + with open(versions_path) as f: + for line in f: + line = line.strip() + if line.startswith("#") or line == "": + continue + module, version = line.split(":") + major, minor = version.strip().split(".") + result[module] = int(major), int(minor) + + # Modules that are Python 2 only or have separate Python 2 stubs + # have stubs in python2/ and may need an override. + python2_dir = os.path.join(typeshed_dir, "python2") + for fnam in os.listdir(python2_dir): + fnam = fnam.replace(".pyi", "") + result[fnam] = (2, 7) + + return result From 3dddc4eb1d7934c9383e9546f205be9ce441bf53 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 25 Jun 2020 17:48:59 +0100 Subject: [PATCH 04/50] Add custom error message for packages with legacy bundled stubs --- mypy/build.py | 3 +++ mypy/modulefinder.py | 22 ++++++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index eaa10063df2d..51b5ebe155cb 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -59,6 +59,7 @@ from mypy.renaming import VariableRenameVisitor from mypy.config_parser import parse_mypy_comments from mypy.freetree import free_tree +from mypy.stubinfo import legacy_bundled_packages from mypy import errorcodes as codes @@ -2499,6 +2500,8 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, errors.raise_error() else: msg, note = reason.error_message_templates() + if '{}' in note: + note = note.format(legacy_bundled_packages[target]) errors.report(line, 0, msg.format(target), code=codes.IMPORT) errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) errors.set_import_context(save_import_context) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 99d5d605fb30..defe721d7b59 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -16,6 +16,7 @@ from mypy.fscache import FileSystemCache from mypy.options import Options +from mypy.stubinfo import legacy_bundled_packages from mypy import sitepkgs # Paths to be searched in find_module(). @@ -52,17 +53,23 @@ class ModuleNotFoundReason(Enum): # was able to be found in the parent directory. WRONG_WORKING_DIRECTORY = 2 + # Stub PyPI package (typically types-pkgname) known to exist but not installed. + STUBS_NOT_INSTALLED = 3 + def error_message_templates(self) -> Tuple[str, str]: if self is ModuleNotFoundReason.NOT_FOUND: - msg = "Cannot find implementation or library stub for module named '{}'" + msg = 'Cannot find implementation or library stub for module named "{}"' note = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: msg = "Cannot find implementation or library stub for module named '{}'" note = ("You may be running mypy in a subpackage, " "mypy should be run on the package root") elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: - msg = "Skipping analyzing '{}': found module but no type hints or library stubs" + msg = 'Skipping analyzing "{}": found module but no type hints or library stubs' note = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" + elif self is ModuleNotFoundReason.STUBS_NOT_INSTALLED: + msg = 'Library stubs not installed for "{}"' + note = 'Hint: "python3 -m pip install {}"' else: assert False return msg, note @@ -194,7 +201,9 @@ def _find_module_non_stub_helper(self, components: List[str], elif not plausible_match and (self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + ".py")): plausible_match = True - if plausible_match: + if components[0] in legacy_bundled_packages: + return ModuleNotFoundReason.STUBS_NOT_INSTALLED + elif plausible_match: return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS else: return ModuleNotFoundReason.NOT_FOUND @@ -236,6 +245,7 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: third_party_inline_dirs = [] # type: PackageDirs third_party_stubs_dirs = [] # type: PackageDirs found_possible_third_party_missing_type_hints = False + need_installed_stubs = False # Third-party stub/typed packages for pkg_dir in self.search_paths.package_path: stub_name = components[0] + '-stubs' @@ -266,6 +276,8 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: if isinstance(non_stub_match, ModuleNotFoundReason): if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: found_possible_third_party_missing_type_hints = True + elif non_stub_match is ModuleNotFoundReason.STUBS_NOT_INSTALLED: + need_installed_stubs = True else: third_party_inline_dirs.append(non_stub_match) self._update_ns_ancestors(components, non_stub_match) @@ -359,7 +371,9 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: if ancestor is not None: return ancestor - if found_possible_third_party_missing_type_hints: + if need_installed_stubs: + return ModuleNotFoundReason.STUBS_NOT_INSTALLED + elif found_possible_third_party_missing_type_hints: return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS else: return ModuleNotFoundReason.NOT_FOUND From bbdb4b8bdd87bd594589732d12599a51d5c069dd Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 25 Jun 2020 17:49:17 +0100 Subject: [PATCH 05/50] Also display legacy package error if global ignore_missing_imports is enabled --- mypy/build.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/mypy/build.py b/mypy/build.py index 51b5ebe155cb..ff2171ccccbc 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2404,10 +2404,21 @@ def find_module_and_diagnose(manager: BuildManager, # Could not find a module. Typically the reason is a # misspelled module name, missing stub, module not in # search path or the module has not been installed. + + ignore_missing_imports = options.ignore_missing_imports + top_level = file_id.partition('.')[0] + # Don't honor a global (not per-module) ignore_missing_imports + # setting for modules that used to have bundled stubs, as + # otherwise updating mypy can silently result in new false + # negatives. + global_ignore_missing_imports = manager.options.ignore_missing_imports + if top_level in legacy_bundled_packages and global_ignore_missing_imports: + ignore_missing_imports = False + if skip_diagnose: raise ModuleNotFound if caller_state: - if not (options.ignore_missing_imports or in_partial_package(id, manager)): + if not (ignore_missing_imports or in_partial_package(id, manager)): module_not_found(manager, caller_line, caller_state, id, result) raise ModuleNotFound elif root_source: From fd1d5788ed111c542ccd0474e198f9f2e3285260 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 26 Jun 2020 12:25:49 +0100 Subject: [PATCH 06/50] Use bold in notes as well --- mypy/util.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mypy/util.py b/mypy/util.py index 214b5f428f9a..6832f14141da 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -628,7 +628,8 @@ def colorize(self, error: str) -> str: self.highlight_quote_groups(msg) + self.style(code, 'yellow')) elif ': note:' in error: loc, msg = error.split('note:', maxsplit=1) - return loc + self.style('note:', 'blue') + self.underline_link(msg) + formatted = self.highlight_quote_groups(self.underline_link(msg)) + return loc + self.style('note:', 'blue') + formatted elif error.startswith(' ' * DEFAULT_SOURCE_OFFSET): # TODO: detecting source code highlights through an indent can be surprising. if '^' not in error: From 84ff38c21e62b720c9878205b101e1e3a7d3596f Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 26 Jun 2020 12:26:04 +0100 Subject: [PATCH 07/50] Improve notes --- mypy/build.py | 9 +++++---- mypy/modulefinder.py | 15 ++++++++------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index ff2171ccccbc..74ddfce90040 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2510,11 +2510,12 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, blocker=True) errors.raise_error() else: - msg, note = reason.error_message_templates() - if '{}' in note: - note = note.format(legacy_bundled_packages[target]) + msg, notes = reason.error_message_templates() errors.report(line, 0, msg.format(target), code=codes.IMPORT) - errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) + for note in notes: + if '{}' in note: + note = note.format(legacy_bundled_packages[target]) + errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) errors.set_import_context(save_import_context) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index defe721d7b59..e90f405fe357 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -56,23 +56,24 @@ class ModuleNotFoundReason(Enum): # Stub PyPI package (typically types-pkgname) known to exist but not installed. STUBS_NOT_INSTALLED = 3 - def error_message_templates(self) -> Tuple[str, str]: + def error_message_templates(self) -> Tuple[str, List[str]]: + doc_link = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" if self is ModuleNotFoundReason.NOT_FOUND: msg = 'Cannot find implementation or library stub for module named "{}"' - note = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" + notes = [doc_link] elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: msg = "Cannot find implementation or library stub for module named '{}'" - note = ("You may be running mypy in a subpackage, " - "mypy should be run on the package root") + notes = ["You may be running mypy in a subpackage, " + "mypy should be run on the package root"] elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: msg = 'Skipping analyzing "{}": found module but no type hints or library stubs' - note = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" + notes = [doc_link] elif self is ModuleNotFoundReason.STUBS_NOT_INSTALLED: msg = 'Library stubs not installed for "{}"' - note = 'Hint: "python3 -m pip install {}"' + notes = ['Hint: "python3 -m pip install {}"', doc_link] else: assert False - return msg, note + return msg, notes # If we found the module, returns the path to the module as a str. From 7719b30bdb66d260bd36de7ae923156f9e3166c9 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 26 Jun 2020 17:21:54 +0100 Subject: [PATCH 08/50] Add --install-types option for installing missing stub packages It can used in a normal mypy run (missing stub packages will be installed at the end). We also record the missing stub packages in a file so that another "mypy --install-types" run (with no other arguments) can be used to just install stub packages, without type checking anything. --- mypy/build.py | 26 ++++++++++++++++++++++++ mypy/main.py | 47 +++++++++++++++++++++++++++++++++++++++++++- mypy/modulefinder.py | 4 +++- mypy/options.py | 2 ++ 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 74ddfce90040..4d86c4309897 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -270,6 +270,8 @@ def _build(sources: List[BuildSource], if not cache_dir_existed and os.path.isdir(options.cache_dir): add_catch_all_gitignore(options.cache_dir) exclude_from_backups(options.cache_dir) + if os.path.isdir(options.cache_dir): + record_missing_stub_packages(options.cache_dir, manager.missing_stub_packages) def default_data_dir() -> str: @@ -642,6 +644,8 @@ def __init__(self, data_dir: str, # the semantic analyzer, used only for testing. Currently used only by the new # semantic analyzer. self.processed_targets = [] # type: List[str] + # Missing stub packages encountered. + self.missing_stub_packages = set() # type: Set[str] def dump_stats(self) -> None: if self.options.dump_build_stats: @@ -2516,6 +2520,8 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, if '{}' in note: note = note.format(legacy_bundled_packages[target]) errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) + if reason is ModuleNotFoundReason.STUBS_NOT_INSTALLED: + manager.missing_stub_packages.add(legacy_bundled_packages[target]) errors.set_import_context(save_import_context) @@ -3232,3 +3238,23 @@ def topsort(data: Dict[AbstractSet[str], for item, dep in data.items() if item not in ready} assert not data, "A cyclic dependency exists amongst %r" % data + + +def missing_stubs_file(cache_dir: str) -> str: + return os.path.join(cache_dir, 'missing_stubs') + + +def record_missing_stub_packages(cache_dir: str, missing_stub_packages: Set[str]) -> None: + """Write a file containing missing stub packages. + + This allows a subsequent "mypy --install-types" run (without other arguments) + to install missing stub packages. + """ + fnam = missing_stubs_file(cache_dir) + if missing_stub_packages: + with open(fnam, 'w') as f: + for pkg in sorted(missing_stub_packages): + f.write('%s\n' % pkg) + else: + if os.path.isfile(fnam): + os.remove(fnam) diff --git a/mypy/main.py b/mypy/main.py index 06a9f43e20ee..be2fab1bb0f9 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -70,6 +70,14 @@ def main(script_path: Optional[str], messages = [] formatter = util.FancyFormatter(stdout, stderr, options.show_error_codes) + if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr): + # Since --install-types performs user input, we want regular stdout and stderr. + fail("--install-types not supported in this mode of running mypy", stderr, options) + + if options.install_types and not sources: + install_types(options.cache_dir, formatter) + return + def flush_errors(new_messages: List[str], serious: bool) -> None: if options.pretty: new_messages = formatter.fit_in_terminal(new_messages) @@ -119,6 +127,11 @@ def flush_errors(new_messages: List[str], serious: bool) -> None: else: stdout.write(formatter.format_success(len(sources), options.color_output) + '\n') stdout.flush() + + if options.install_types: + install_types(options.cache_dir, formatter, after_run=True) + return + if options.fast_exit: # Exit without freeing objects -- it's faster. # @@ -731,6 +744,10 @@ def add_invertible_flag(flag: str, '--scripts-are-modules', action='store_true', help="Script x becomes module x instead of __main__") + add_invertible_flag('--install-types', default=False, strict_flag=False, + help="Install detected missing library stub packages using pip", + group=other_group) + if server_options: # TODO: This flag is superfluous; remove after a short transition (2018-03-16) other_group.add_argument( @@ -863,7 +880,7 @@ def set_strict_flags() -> None: code_methods = sum(bool(c) for c in [special_opts.modules + special_opts.packages, special_opts.command, special_opts.files]) - if code_methods == 0: + if code_methods == 0 and not options.install_types: parser.error("Missing target module, package, files, or command.") elif code_methods > 1: parser.error("May only specify one of: module/package, files, or command.") @@ -1036,3 +1053,31 @@ def fail(msg: str, stderr: TextIO, options: Options) -> None: stderr.write('%s\n' % msg) maybe_write_junit_xml(0.0, serious=True, messages=[msg], options=options) sys.exit(2) + + +def install_types(cache_dir: str, + formatter: util.FancyFormatter, + after_run: bool = False) -> None: + """Install stub packages using pip if some missing stubs were detected.""" + if not os.path.isdir(cache_dir): + sys.stderr.write( + "Error: no mypy cache directory (you must enable incremental mode)\n") + sys.exit(2) + fnam = build.missing_stubs_file(cache_dir) + if not os.path.isfile(fnam): + # If there are no missing stubs, generate no output. + return + with open(fnam) as f: + packages = [line.strip() for line in f.readlines()] + if after_run: + print() + print('Installing missing stub packages:') + cmd = ['python3', '-m', 'pip', 'install'] + packages + print(formatter.style(' '.join(cmd), 'none', bold=True)) + print() + x = input('Install? [yN] ') + if not x.strip() or not x.lower().startswith('y'): + print(formatter.style('mypy: Skipping installation', 'red', bold=True)) + sys.exit(2) + print() + subprocess.run(cmd) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index e90f405fe357..8a43ab13914c 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -70,7 +70,9 @@ def error_message_templates(self) -> Tuple[str, List[str]]: notes = [doc_link] elif self is ModuleNotFoundReason.STUBS_NOT_INSTALLED: msg = 'Library stubs not installed for "{}"' - notes = ['Hint: "python3 -m pip install {}"', doc_link] + notes = ['Hint: "python3 -m pip install {}"', + '(or run "mypy --install-types" to install all missing stub packages)', + doc_link] else: assert False return msg, notes diff --git a/mypy/options.py b/mypy/options.py index e95ed3e0bb46..2a0b3e111442 100644 --- a/mypy/options.py +++ b/mypy/options.py @@ -291,6 +291,8 @@ def __init__(self) -> None: self.transform_source = None # type: Optional[Callable[[Any], Any]] # Print full path to each file in the report. self.show_absolute_path = False # type: bool + # Install missing stub packages if True + self.install_types = False # To avoid breaking plugin compatibility, keep providing new_semantic_analyzer @property From 6134bc0f6e540b80231b8594d96dd3bd7102ffea Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 11:47:37 +0100 Subject: [PATCH 09/50] Update tests to use double quotes around module name --- test-data/unit/check-custom-plugin.test | 2 +- test-data/unit/check-errorcodes.test | 10 +- test-data/unit/check-flags.test | 4 +- test-data/unit/check-incremental.test | 10 +- test-data/unit/check-literal.test | 2 +- test-data/unit/check-modules.test | 54 +++---- test-data/unit/check-semanal-error.test | 6 +- test-data/unit/check-unreachable-code.test | 10 +- test-data/unit/cmdline.test | 12 +- test-data/unit/fine-grained-blockers.test | 14 +- .../unit/fine-grained-follow-imports.test | 38 ++--- test-data/unit/fine-grained-modules.test | 132 +++++++++--------- test-data/unit/fine-grained.test | 20 +-- test-data/unit/pep561.test | 14 +- test-data/unit/pythoneval.test | 2 +- test-data/unit/semanal-errors.test | 22 +-- 16 files changed, 176 insertions(+), 176 deletions(-) diff --git a/test-data/unit/check-custom-plugin.test b/test-data/unit/check-custom-plugin.test index 9ab79bafd244..ed0e85cea689 100644 --- a/test-data/unit/check-custom-plugin.test +++ b/test-data/unit/check-custom-plugin.test @@ -70,7 +70,7 @@ tmp/mypy.ini:2: error: Can't find plugin 'tmp/missing.py' \[mypy] plugins=missing [out] -tmp/mypy.ini:2: error: Error importing plugin 'missing': No module named 'missing' +tmp/mypy.ini:2: error: Error importing plugin 'missing': No module named "missing" [case testMultipleSectionsDefinePlugin] # flags: --config-file tmp/mypy.ini diff --git a/test-data/unit/check-errorcodes.test b/test-data/unit/check-errorcodes.test index 53d518f4c468..8e959a4044e3 100644 --- a/test-data/unit/check-errorcodes.test +++ b/test-data/unit/check-errorcodes.test @@ -499,13 +499,13 @@ if int() is str(): # E: Non-overlapping identity check (left operand type: "int [builtins fixtures/primitives.pyi] [case testErrorCodeMissingModule] -from defusedxml import xyz # E: Cannot find implementation or library stub for module named 'defusedxml' [import] \ +from defusedxml import xyz # E: Cannot find implementation or library stub for module named "defusedxml" [import] \ # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -from nonexistent import foobar # E: Cannot find implementation or library stub for module named 'nonexistent' [import] -import nonexistent2 # E: Cannot find implementation or library stub for module named 'nonexistent2' [import] -from nonexistent3 import * # E: Cannot find implementation or library stub for module named 'nonexistent3' [import] +from nonexistent import foobar # E: Cannot find implementation or library stub for module named "nonexistent" [import] +import nonexistent2 # E: Cannot find implementation or library stub for module named "nonexistent2" [import] +from nonexistent3 import * # E: Cannot find implementation or library stub for module named "nonexistent3" [import] from pkg import bad # E: Module 'pkg' has no attribute 'bad' [attr-defined] -from pkg.bad2 import bad3 # E: Cannot find implementation or library stub for module named 'pkg.bad2' [import] +from pkg.bad2 import bad3 # E: Cannot find implementation or library stub for module named "pkg.bad2" [import] [file pkg/__init__.py] [case testErrorCodeAlreadyDefined] diff --git a/test-data/unit/check-flags.test b/test-data/unit/check-flags.test index 0834019077b2..23f6280c61f0 100644 --- a/test-data/unit/check-flags.test +++ b/test-data/unit/check-flags.test @@ -453,7 +453,7 @@ main:2: note: (Using --follow-imports=error, module not passed on command line) [case testIgnoreMissingImportsFalse] from mod import x [out] -main:1: error: Cannot find implementation or library stub for module named 'mod' +main:1: error: Cannot find implementation or library stub for module named "mod" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testIgnoreMissingImportsTrue] @@ -610,7 +610,7 @@ from missing import MyType def f(x: MyType) -> None: pass [out] -main:2: error: Cannot find implementation or library stub for module named 'missing' +main:2: error: Cannot find implementation or library stub for module named "missing" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:4: error: Argument 1 to "f" becomes "Any" due to an unfollowed import diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test index 5d2407b45848..dc19aa2a266e 100644 --- a/test-data/unit/check-incremental.test +++ b/test-data/unit/check-incremental.test @@ -2135,7 +2135,7 @@ x = 1 [rechecked n] [stale] [out2] -tmp/n.py:1: error: Cannot find implementation or library stub for module named 'm' +tmp/n.py:1: error: Cannot find implementation or library stub for module named "m" tmp/n.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testDeleteFileWithinCycle] @@ -3433,7 +3433,7 @@ import a [out1] [out2] -main:2: error: Cannot find implementation or library stub for module named 'a' +main:2: error: Cannot find implementation or library stub for module named "a" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testIncrementalInheritanceAddAnnotation] @@ -3576,7 +3576,7 @@ def f() -> None: pass def f(x: int) -> None: pass [out] [out2] -main:1: error: Cannot find implementation or library stub for module named 'p.q' +main:1: error: Cannot find implementation or library stub for module named "p.q" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [out3] main:2: error: Missing positional argument "x" in call to "f" @@ -4201,10 +4201,10 @@ def __getattr__(attr: str) -> Any: ... # empty [builtins fixtures/module.pyi] [out] -tmp/c.py:1: error: Cannot find implementation or library stub for module named 'a.b.c' +tmp/c.py:1: error: Cannot find implementation or library stub for module named "a.b.c" tmp/c.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [out2] -tmp/c.py:1: error: Cannot find implementation or library stub for module named 'a.b.c' +tmp/c.py:1: error: Cannot find implementation or library stub for module named "a.b.c" tmp/c.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testAddedMissingStubs] diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index 87d9323e8f89..739637beeaf2 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -867,7 +867,7 @@ func(f) # E: Argument 1 to "func" has incompatible type "Union[Literal['foo'], [case testLiteralDisallowAny] from typing import Any from typing_extensions import Literal -from missing_module import BadAlias # E: Cannot find implementation or library stub for module named 'missing_module' \ +from missing_module import BadAlias # E: Cannot find implementation or library stub for module named "missing_module" \ # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports a: Literal[Any] # E: Parameter 1 of Literal[...] cannot be of type "Any" diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test index b41d864435c7..f3a4af9649ba 100644 --- a/test-data/unit/check-modules.test +++ b/test-data/unit/check-modules.test @@ -208,7 +208,7 @@ else: import nonexistent None + '' [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") @@ -220,7 +220,7 @@ m.x = '' [file m.py] x = 1 [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") main:4: error: Incompatible types in assignment (expression has type "str", variable has type "int") @@ -233,7 +233,7 @@ m.x = '' [file m.py] x = 1 [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") main:4: error: Incompatible types in assignment (expression has type "str", variable has type "int") @@ -242,16 +242,16 @@ main:4: error: Incompatible types in assignment (expression has type "str", vari import nonexistent, another None + '' [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'another' +main:1: error: Cannot find implementation or library stub for module named "another" main:2: error: Unsupported left operand type for + ("None") [case testTypeCheckWithUnknownModule5] import nonexistent as x None + '' [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") @@ -259,7 +259,7 @@ main:2: error: Unsupported left operand type for + ("None") from nonexistent import x None + '' [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") @@ -267,7 +267,7 @@ main:2: error: Unsupported left operand type for + ("None") from nonexistent import * None + '' [out] -main:1: error: Cannot find implementation or library stub for module named 'nonexistent' +main:1: error: Cannot find implementation or library stub for module named "nonexistent" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Unsupported left operand type for + ("None") @@ -276,7 +276,7 @@ import xyz xyz.foo() xyz() [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testAccessingUnknownModule2] @@ -284,16 +284,16 @@ import xyz, bar xyz.foo() bar() [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'bar' +main:1: error: Cannot find implementation or library stub for module named "bar" [case testAccessingUnknownModule3] import xyz as z xyz.foo() z() [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Name 'xyz' is not defined @@ -302,14 +302,14 @@ from xyz import y, z y.foo() z() [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testAccessingNameImportedFromUnknownModule2] from xyz import * y [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Name 'y' is not defined @@ -318,14 +318,14 @@ from xyz import y as z y z [out] -main:1: error: Cannot find implementation or library stub for module named 'xyz' +main:1: error: Cannot find implementation or library stub for module named "xyz" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Name 'y' is not defined [case testUnknownModuleRedefinition] # Error messages differ with the new analyzer -import xab # E: Cannot find implementation or library stub for module named 'xab' # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports +import xab # E: Cannot find implementation or library stub for module named "xab" # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports def xab(): pass # E: Name 'xab' already defined (possibly by an import) [case testAccessingUnknownModuleFromOtherModule] @@ -336,7 +336,7 @@ x.z import nonexistent [builtins fixtures/module.pyi] [out] -tmp/x.py:1: error: Cannot find implementation or library stub for module named 'nonexistent' +tmp/x.py:1: error: Cannot find implementation or library stub for module named "nonexistent" tmp/x.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:3: error: Module has no attribute "z" @@ -346,7 +346,7 @@ def f(): def foobar(): pass foobar('') [out] -main:2: error: Cannot find implementation or library stub for module named 'foobar' +main:2: error: Cannot find implementation or library stub for module named "foobar" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:4: error: Too many arguments for "foobar" @@ -356,7 +356,7 @@ def f(): def x(): pass x('') [out] -main:2: error: Cannot find implementation or library stub for module named 'foobar' +main:2: error: Cannot find implementation or library stub for module named "foobar" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:4: error: Too many arguments for "x" @@ -2180,8 +2180,8 @@ import c [out] -- TODO: it would be better for this to be in the other order -tmp/b.py:1: error: Cannot find implementation or library stub for module named 'c' -main:1: error: Cannot find implementation or library stub for module named 'c' +tmp/b.py:1: error: Cannot find implementation or library stub for module named "c" +main:1: error: Cannot find implementation or library stub for module named "c" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testIndirectFromImportWithinCycle1] @@ -2313,7 +2313,7 @@ from typing import Any def __getattr__(attr: str) -> Any: ... [builtins fixtures/module.pyi] [out] -main:1: error: Cannot find implementation or library stub for module named 'a.b' +main:1: error: Cannot find implementation or library stub for module named "a.b" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testModuleGetattrInit4] @@ -2358,12 +2358,12 @@ def __getattr__(attr: str) -> Any: ... # empty (i.e. complete subpackage) [builtins fixtures/module.pyi] [out] -main:1: error: Cannot find implementation or library stub for module named 'a.b.c.d' +main:1: error: Cannot find implementation or library stub for module named "a.b.c.d" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'a.b.c' +main:1: error: Cannot find implementation or library stub for module named "a.b.c" [case testModuleGetattrInit8a] -import a.b.c # E: Cannot find implementation or library stub for module named 'a.b.c' # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports +import a.b.c # E: Cannot find implementation or library stub for module named "a.b.c" # N: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports import a.d # OK [file a/__init__.pyi] from typing import Any @@ -2389,7 +2389,7 @@ def __getattr__(attr: str) -> Any: ... ignore_missing_imports = True [builtins fixtures/module.pyi] [out] -main:3: error: Cannot find implementation or library stub for module named 'a.b.d' +main:3: error: Cannot find implementation or library stub for module named "a.b.d" main:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testIndirectFromImportWithinCycleUsedAsBaseClass] @@ -2621,7 +2621,7 @@ from foo.bar import x [file foo/bar.py] x = 0 [out] -main:1: error: Cannot find implementation or library stub for module named 'foo.bar' +main:1: error: Cannot find implementation or library stub for module named "foo.bar" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testNamespacePackage] diff --git a/test-data/unit/check-semanal-error.test b/test-data/unit/check-semanal-error.test index ac8f72b4cd36..73d3ac7fa5cd 100644 --- a/test-data/unit/check-semanal-error.test +++ b/test-data/unit/check-semanal-error.test @@ -18,7 +18,7 @@ m.foo() m.x = m.y 1() # E [out] -main:1: error: Cannot find implementation or library stub for module named 'm' +main:1: error: Cannot find implementation or library stub for module named "m" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:4: error: "int" not callable @@ -28,7 +28,7 @@ x.foo() x.a = x.b 1() # E [out] -main:1: error: Cannot find implementation or library stub for module named 'm' +main:1: error: Cannot find implementation or library stub for module named "m" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:4: error: "int" not callable @@ -37,7 +37,7 @@ from m import * # E x # E 1() # E [out] -main:1: error: Cannot find implementation or library stub for module named 'm' +main:1: error: Cannot find implementation or library stub for module named "m" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: error: Name 'x' is not defined main:3: error: "int" not callable diff --git a/test-data/unit/check-unreachable-code.test b/test-data/unit/check-unreachable-code.test index e95faf503d99..2632a2f349d5 100644 --- a/test-data/unit/check-unreachable-code.test +++ b/test-data/unit/check-unreachable-code.test @@ -78,7 +78,7 @@ else: import pow123 # E [builtins fixtures/bool.pyi] [out] -main:6: error: Cannot find implementation or library stub for module named 'pow123' +main:6: error: Cannot find implementation or library stub for module named "pow123" main:6: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testMypyConditional] @@ -98,7 +98,7 @@ else: import xyz753 [typing fixtures/typing-medium.pyi] [out] -main:3: error: Cannot find implementation or library stub for module named 'pow123' +main:3: error: Cannot find implementation or library stub for module named "pow123" main:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testTypeCheckingConditionalFromImport] @@ -109,7 +109,7 @@ else: import xyz753 [typing fixtures/typing-medium.pyi] [out] -main:3: error: Cannot find implementation or library stub for module named 'pow123' +main:3: error: Cannot find implementation or library stub for module named "pow123" main:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testNegatedTypeCheckingConditional] @@ -121,7 +121,7 @@ else: [builtins fixtures/bool.pyi] [typing fixtures/typing-medium.pyi] [out] -main:5: error: Cannot find implementation or library stub for module named 'xyz753' +main:5: error: Cannot find implementation or library stub for module named "xyz753" main:5: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testUndefinedTypeCheckingConditional] @@ -132,7 +132,7 @@ else: [builtins fixtures/bool.pyi] [out] main:1: error: Name 'TYPE_CHECKING' is not defined -main:4: error: Cannot find implementation or library stub for module named 'xyz753' +main:4: error: Cannot find implementation or library stub for module named "xyz753" main:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testConditionalClassDefPY3] diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index 8fe9f478a077..4740ecbe95e9 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -124,7 +124,7 @@ mypy: can't decode file 'a.py': unknown encoding: uft-8 [file two/mod/__init__.py] # type: ignore [out] -two/mod/__init__.py: error: Duplicate module named 'mod' (also at 'one/mod/__init__.py') +two/mod/__init__.py: error: Duplicate module named "mod" (also at 'one/mod/__init__.py') == Return code: 2 [case promptsForgotInit] @@ -136,7 +136,7 @@ two/mod/__init__.py: error: Duplicate module named 'mod' (also at 'one/mod/__ini [file one/mod/a.py] #type: ignore [out] -one/mod/a.py: error: Duplicate module named 'a' (also at 'a.py') +one/mod/a.py: error: Duplicate module named "a" (also at 'a.py') one/mod/a.py: error: Are you missing an __init__.py? == Return code: 2 @@ -334,7 +334,7 @@ from baz import baz baz(bar(foo(42))) baz(bar(foo('oof'))) [out] -file.py:1: error: Cannot find implementation or library stub for module named 'no_stubs' +file.py:1: error: Cannot find implementation or library stub for module named "no_stubs" file.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports file.py:6: error: Argument 1 to "foo" has incompatible type "str"; expected "int" @@ -489,7 +489,7 @@ reveal_type(missing.x) # Expect Any \[mypy] ignore_missing_imports = False [out] -main.py:1: error: Cannot find implementation or library stub for module named 'missing' +main.py:1: error: Cannot find implementation or library stub for module named "missing" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main.py:2: note: Revealed type is 'Any' @@ -567,9 +567,9 @@ import a.b [file a.b.py] whatever [out] -main.py:1: error: Cannot find implementation or library stub for module named 'a.b' +main.py:1: error: Cannot find implementation or library stub for module named "a.b" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" [case testPythonVersionTooOld10] # cmd: mypy -c pass diff --git a/test-data/unit/fine-grained-blockers.test b/test-data/unit/fine-grained-blockers.test index 5196387fb52d..6745fe2ddedb 100644 --- a/test-data/unit/fine-grained-blockers.test +++ b/test-data/unit/fine-grained-blockers.test @@ -134,7 +134,7 @@ x x [file a.py.3] def f() -> None: pass [out] -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == a.py:1: error: invalid syntax @@ -277,9 +277,9 @@ x x == a.py:1: error: invalid syntax == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" [case testDeleteFileWithBlockingError-only_when_cache] -- Different cache/no-cache tests because: @@ -298,9 +298,9 @@ x x == a.py:1: error: invalid syntax == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" [case testModifyFileWhileBlockingErrorElsewhere] import a @@ -371,7 +371,7 @@ class A: pass [builtins fixtures/module.pyi] [out] == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:4: error: "A" has no attribute "f" @@ -389,7 +389,7 @@ class A: [builtins fixtures/module.pyi] [out] == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:1: error: Module 'a' has no attribute 'A' diff --git a/test-data/unit/fine-grained-follow-imports.test b/test-data/unit/fine-grained-follow-imports.test index ea064e0b4e66..d87a0db8962a 100644 --- a/test-data/unit/fine-grained-follow-imports.test +++ b/test-data/unit/fine-grained-follow-imports.test @@ -39,7 +39,7 @@ def f(x: str) -> None: pass def f() -> None: pass [out] -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main.py:2: error: Missing positional argument "x" in call to "f" @@ -82,7 +82,7 @@ def f(x: str) -> None: pass def f() -> None: pass [out] -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main.py:2: error: Missing positional argument "x" in call to "f" @@ -216,7 +216,7 @@ def f(x: str) -> None: pass [out] == -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main.py:2: error: Missing positional argument "x" in call to "f" @@ -239,7 +239,7 @@ def f(x: str) -> None: pass [out] == -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main.py:2: error: Missing positional argument "x" in call to "f" @@ -333,7 +333,7 @@ import b [out] b.py:1: error: "int" not callable == -main.py:1: error: Cannot find implementation or library stub for module named 'a' +main.py:1: error: Cannot find implementation or library stub for module named "a" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == b.py:1: error: "int" not callable @@ -473,12 +473,12 @@ from p2 import m [file p2/m.py.3] [out] -main.py:1: error: Cannot find implementation or library stub for module named 'p1.m' +main.py:1: error: Cannot find implementation or library stub for module named "p1.m" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main.py:1: error: Cannot find implementation or library stub for module named 'p1' -main.py:2: error: Cannot find implementation or library stub for module named 'p2' +main.py:1: error: Cannot find implementation or library stub for module named "p1" +main.py:2: error: Cannot find implementation or library stub for module named "p2" == -main.py:2: error: Cannot find implementation or library stub for module named 'p2' +main.py:2: error: Cannot find implementation or library stub for module named "p2" main.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports p1/__init__.py:1: error: "int" not callable == @@ -498,7 +498,7 @@ from p import m ''() [out] -main.py:1: error: Cannot find implementation or library stub for module named 'p' +main.py:1: error: Cannot find implementation or library stub for module named "p" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main.py:1: error: Module 'p' has no attribute 'm' @@ -530,13 +530,13 @@ def f(x: str) -> None: pass def f() -> None: pass [out] -main.py:1: error: Cannot find implementation or library stub for module named 'p1.s1.m' +main.py:1: error: Cannot find implementation or library stub for module named "p1.s1.m" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main.py:1: error: Cannot find implementation or library stub for module named 'p1' -main.py:1: error: Cannot find implementation or library stub for module named 'p1.s1' -main.py:2: error: Cannot find implementation or library stub for module named 'p2.s2' +main.py:1: error: Cannot find implementation or library stub for module named "p1" +main.py:1: error: Cannot find implementation or library stub for module named "p1.s1" +main.py:2: error: Cannot find implementation or library stub for module named "p2.s2" == -main.py:2: error: Cannot find implementation or library stub for module named 'p2.s2' +main.py:2: error: Cannot find implementation or library stub for module named "p2.s2" main.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main.py:3: error: Missing positional argument "x" in call to "f" == @@ -586,7 +586,7 @@ def f() -> None: ''() [out] -main.py:2: error: Cannot find implementation or library stub for module named 'p' +main.py:2: error: Cannot find implementation or library stub for module named "p" main.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == p/m.py:1: error: "str" not callable @@ -609,7 +609,7 @@ from p import m x x x [out] -main.py:1: error: Cannot find implementation or library stub for module named 'p' +main.py:1: error: Cannot find implementation or library stub for module named "p" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == p/m.pyi:1: error: "str" not callable @@ -636,13 +636,13 @@ import p2.m2 [out] p1/m1.py:1: error: "int" not callable -main.py:2: error: Cannot find implementation or library stub for module named 'p2.m2' +main.py:2: error: Cannot find implementation or library stub for module named "p2.m2" main.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == p2/m2.py:1: error: "str" not callable p1/m1.py:1: error: "int" not callable == -main.py:2: error: Cannot find implementation or library stub for module named 'p2.m2' +main.py:2: error: Cannot find implementation or library stub for module named "p2.m2" main.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports p1/m1.py:1: error: "int" not callable diff --git a/test-data/unit/fine-grained-modules.test b/test-data/unit/fine-grained-modules.test index e49f69a885f1..33363f33367d 100644 --- a/test-data/unit/fine-grained-modules.test +++ b/test-data/unit/fine-grained-modules.test @@ -52,7 +52,7 @@ f() def f() -> None: pass [out] == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == @@ -68,10 +68,10 @@ f(1) def f() -> None: pass [out] == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == b.py:2: error: Too many arguments for "f" @@ -88,10 +88,10 @@ x = 'whatever' def f() -> None: pass [out] == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == b.py:2: error: Too many arguments for "f" @@ -118,10 +118,10 @@ f(1) # unrelated change [out] == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == -b.py:1: error: Cannot find implementation or library stub for module named 'a' +b.py:1: error: Cannot find implementation or library stub for module named "a" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testAddFilePreservesError2] @@ -161,7 +161,7 @@ x = 1 import a [out] == -b.py:2: error: Cannot find implementation or library stub for module named 'a' +b.py:2: error: Cannot find implementation or library stub for module named "a" b.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testImportLineNumber2] @@ -174,13 +174,13 @@ from c import f [file x.py.3] [out] == -b.py:2: error: Cannot find implementation or library stub for module named 'a' +b.py:2: error: Cannot find implementation or library stub for module named "a" b.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -b.py:3: error: Cannot find implementation or library stub for module named 'c' +b.py:3: error: Cannot find implementation or library stub for module named "c" == -b.py:2: error: Cannot find implementation or library stub for module named 'a' +b.py:2: error: Cannot find implementation or library stub for module named "a" b.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -b.py:3: error: Cannot find implementation or library stub for module named 'c' +b.py:3: error: Cannot find implementation or library stub for module named "c" [case testAddPackage1] import p.a @@ -189,9 +189,9 @@ p.a.f(1) [file p/a.py.2] def f(x: str) -> None: pass [out] -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" == main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -203,7 +203,7 @@ from p.a import f [file p/a.py.2] def f(x: str) -> None: pass [out] -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -215,11 +215,11 @@ p.a.f(1) [file p/a.py.3] def f(x: str) -> None: pass [out] -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" == -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -232,13 +232,13 @@ p.a.f(1) def f(x: str) -> None: pass [file p/__init__.py.3] [out] -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" == -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" == main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -266,13 +266,13 @@ p.a.f(1) def f(x: str) -> None: pass [file p/__init__.py.3] [out] -main:4: error: Cannot find implementation or library stub for module named 'p.a' +main:4: error: Cannot find implementation or library stub for module named "p.a" main:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:4: error: Cannot find implementation or library stub for module named 'p' +main:4: error: Cannot find implementation or library stub for module named "p" == -main:4: error: Cannot find implementation or library stub for module named 'p.a' +main:4: error: Cannot find implementation or library stub for module named "p.a" main:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:4: error: Cannot find implementation or library stub for module named 'p' +main:4: error: Cannot find implementation or library stub for module named "p" == main:5: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -301,7 +301,7 @@ f(1) def f(x: str) -> None: pass [file p/__init__.py.2] [out] -x.py:1: error: Cannot find implementation or library stub for module named 'p.a' +x.py:1: error: Cannot find implementation or library stub for module named "p.a" x.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == x.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -374,7 +374,7 @@ def f() -> None: pass def f(x: int) -> None: pass [out] == -a.py:1: error: Cannot find implementation or library stub for module named 'b' +a.py:1: error: Cannot find implementation or library stub for module named "b" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == a.py:4: error: Missing positional argument "x" in call to "f" @@ -388,7 +388,7 @@ def f() -> None: pass def f() -> None: pass [out] == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == @@ -404,7 +404,7 @@ from p import q == main:1: error: Module 'p' has no attribute 'q' -- TODO: The following messages are different compared to non-incremental mode -main:1: error: Cannot find implementation or library stub for module named 'p.q' +main:1: error: Cannot find implementation or library stub for module named "p.q" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == @@ -420,7 +420,7 @@ from p import q [file p/q.py.3] [out] == -main:1: error: Cannot find implementation or library stub for module named 'p.q' +main:1: error: Cannot find implementation or library stub for module named "p.q" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == @@ -435,7 +435,7 @@ def f() -> None: pass def f(x: int) -> None: pass [out] == -main:1: error: Cannot find implementation or library stub for module named 'p.q' +main:1: error: Cannot find implementation or library stub for module named "p.q" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:2: error: Missing positional argument "x" in call to "f" @@ -450,7 +450,7 @@ def f() -> None: pass def f(x: int) -> None: pass [out] == -main:1: error: Cannot find implementation or library stub for module named 'p.q' +main:1: error: Cannot find implementation or library stub for module named "p.q" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == @@ -481,7 +481,7 @@ def f() -> str: == a.py:2: error: Incompatible return value type (got "int", expected "str") == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testDeleteModuleWithErrorInsidePackage] @@ -496,7 +496,7 @@ def f() -> str: [out] a/b.py:2: error: Incompatible return value type (got "str", expected "int") == -main:1: error: Cannot find implementation or library stub for module named 'a.b' +main:1: error: Cannot find implementation or library stub for module named "a.b" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testModifyTwoFilesNoError1] @@ -635,9 +635,9 @@ import b def g() -> None: pass b.f() [out] -a.py:1: error: Cannot find implementation or library stub for module named 'b' +a.py:1: error: Cannot find implementation or library stub for module named "b" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -a.py:2: error: Cannot find implementation or library stub for module named 'c' +a.py:2: error: Cannot find implementation or library stub for module named "c" == [case testAddTwoFilesErrorsInBoth] @@ -656,9 +656,9 @@ import b def g() -> None: pass b.f(1) [out] -a.py:1: error: Cannot find implementation or library stub for module named 'b' +a.py:1: error: Cannot find implementation or library stub for module named "b" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -a.py:2: error: Cannot find implementation or library stub for module named 'c' +a.py:2: error: Cannot find implementation or library stub for module named "c" == c.py:3: error: Too many arguments for "f" b.py:3: error: Too many arguments for "g" @@ -673,9 +673,9 @@ def f() -> None: pass [file b.py.2] def g() -> None: pass [out] -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'b' +main:2: error: Cannot find implementation or library stub for module named "b" == main:3: error: Too many arguments for "f" main:4: error: Too many arguments for "g" @@ -693,9 +693,9 @@ def g() -> None: pass [delete b.py.2] [out] == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'b' +main:2: error: Cannot find implementation or library stub for module named "b" [case testDeleteTwoFilesNoErrors] import a @@ -734,9 +734,9 @@ a.f(1) b.py:3: error: Too many arguments for "f" a.py:3: error: Too many arguments for "g" == -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'b' +main:2: error: Cannot find implementation or library stub for module named "b" [case testAddFileWhichImportsLibModule] import a @@ -746,7 +746,7 @@ import sys x = sys.platform [builtins fixtures/tuple.pyi] [out] -main:1: error: Cannot find implementation or library stub for module named 'a' +main:1: error: Cannot find implementation or library stub for module named "a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == main:2: error: Incompatible types in assignment (expression has type "int", variable has type "str") @@ -760,7 +760,7 @@ import broken x = broken.x z [out] -main:2: error: Cannot find implementation or library stub for module named 'a' +main:2: error: Cannot find implementation or library stub for module named "a" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == a.py:3: error: Name 'z' is not defined @@ -827,7 +827,7 @@ def g() -> None: pass [out] a.py:2: error: Too many arguments for "g" == -a.py:1: error: Cannot find implementation or library stub for module named 'm.x' +a.py:1: error: Cannot find implementation or library stub for module named "m.x" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports a.py:2: error: Module has no attribute "x" @@ -843,9 +843,9 @@ def f(x: str) -> None: pass [out] main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" [case testDeletePackage2] import p @@ -859,7 +859,7 @@ def f(x: str) -> None: pass [out] main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testDeletePackage3] @@ -875,13 +875,13 @@ def f(x: str) -> None: pass [out] main:3: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -main:2: error: Cannot find implementation or library stub for module named 'p.a' +main:2: error: Cannot find implementation or library stub for module named "p.a" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:3: error: Module has no attribute "a" == -main:2: error: Cannot find implementation or library stub for module named 'p.a' +main:2: error: Cannot find implementation or library stub for module named "p.a" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'p' +main:2: error: Cannot find implementation or library stub for module named "p" [case testDeletePackage4] import p.a @@ -894,13 +894,13 @@ def f(x: str) -> None: pass [out] main:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" == -main:1: error: Cannot find implementation or library stub for module named 'p.a' +main:1: error: Cannot find implementation or library stub for module named "p.a" main:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:1: error: Cannot find implementation or library stub for module named 'p' +main:1: error: Cannot find implementation or library stub for module named "p" [case testDeletePackage5] # cmd1: mypy main p/a.py p/__init__.py @@ -917,13 +917,13 @@ def f(x: str) -> None: pass [out] main:6: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -main:5: error: Cannot find implementation or library stub for module named 'p.a' +main:5: error: Cannot find implementation or library stub for module named "p.a" main:5: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:5: error: Cannot find implementation or library stub for module named 'p' +main:5: error: Cannot find implementation or library stub for module named "p" == -main:5: error: Cannot find implementation or library stub for module named 'p.a' +main:5: error: Cannot find implementation or library stub for module named "p.a" main:5: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:5: error: Cannot find implementation or library stub for module named 'p' +main:5: error: Cannot find implementation or library stub for module named "p" [case testDeletePackage6] @@ -943,7 +943,7 @@ f(12) [out] p/b.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" == -p/b.py:1: error: Cannot find implementation or library stub for module named 'p.a' +p/b.py:1: error: Cannot find implementation or library stub for module named "p.a" p/b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == p/b.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" @@ -1417,7 +1417,7 @@ def f() -> None: pass [out] == -a.py:1: error: Cannot find implementation or library stub for module named 'b' +a.py:1: error: Cannot find implementation or library stub for module named "b" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports @@ -1813,7 +1813,7 @@ x = 2 [out] == == -a.py:2: error: Cannot find implementation or library stub for module named 'b' +a.py:2: error: Cannot find implementation or library stub for module named "b" a.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testErrorButDontIgnore1] @@ -1888,7 +1888,7 @@ x = 1 == p/b.py: error: Ancestor package 'p' ignored p/b.py: note: (Using --follow-imports=error, submodule passed on command line) -p/b.py:1: error: Cannot find implementation or library stub for module named 'z' +p/b.py:1: error: Cannot find implementation or library stub for module named "z" p/b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testTurnPackageToModule] diff --git a/test-data/unit/fine-grained.test b/test-data/unit/fine-grained.test index 60df7cddbb42..e7f7c4dff094 100644 --- a/test-data/unit/fine-grained.test +++ b/test-data/unit/fine-grained.test @@ -473,7 +473,7 @@ x = 3 == == == -a.py:1: error: Cannot find implementation or library stub for module named 'b' +a.py:1: error: Cannot find implementation or library stub for module named "b" a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testIgnoreWorksWithMissingImports] @@ -507,7 +507,7 @@ from xyz import x # type: ignore [file xyz.py.3] x = str() [out] -b.py:1: error: Cannot find implementation or library stub for module named 'xyz' +b.py:1: error: Cannot find implementation or library stub for module named "xyz" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == == @@ -526,7 +526,7 @@ from xyz import x x = str() [out] == -b.py:1: error: Cannot find implementation or library stub for module named 'xyz' +b.py:1: error: Cannot find implementation or library stub for module named "xyz" b.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == a.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int") @@ -1809,7 +1809,7 @@ def f() -> Iterator[None]: [out] main:2: note: Revealed type is 'contextlib.GeneratorContextManager[None]' == -a.py:3: error: Cannot find implementation or library stub for module named 'b' +a.py:3: error: Cannot find implementation or library stub for module named "b" a.py:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:2: note: Revealed type is 'contextlib.GeneratorContextManager[None]' == @@ -1856,7 +1856,7 @@ def g() -> None: [out] a.py:11: error: Too many arguments for "h" == -a.py:10: error: Cannot find implementation or library stub for module named 'b' +a.py:10: error: Cannot find implementation or library stub for module named "b" a.py:10: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == a.py:11: error: Too many arguments for "h" @@ -1890,7 +1890,7 @@ def f(x: List[int]) -> Iterator[None]: [builtins fixtures/list.pyi] [out] == -a.py:3: error: Cannot find implementation or library stub for module named 'b' +a.py:3: error: Cannot find implementation or library stub for module named "b" a.py:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports == == @@ -2509,10 +2509,10 @@ def g() -> None: pass [delete n.py.2] [out] == -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:7: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader -main:9: error: Cannot find implementation or library stub for module named 'n' +main:9: error: Cannot find implementation or library stub for module named "n" [case testOverloadSpecialCase] from typing import overload @@ -2538,10 +2538,10 @@ def g() -> None: pass [builtins fixtures/ops.pyi] [out] == -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports main:12: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader -main:14: error: Cannot find implementation or library stub for module named 'n' +main:14: error: Cannot find implementation or library stub for module named "n" [case testOverloadClassmethodDisappears] from typing import overload diff --git a/test-data/unit/pep561.test b/test-data/unit/pep561.test index bdd22e3d0c5d..9fcc33645afb 100644 --- a/test-data/unit/pep561.test +++ b/test-data/unit/pep561.test @@ -35,9 +35,9 @@ reveal_type(a) \[mypy] no_site_packages=True [out] -testTypedPkg_config_nositepackages.py:2: error: Cannot find implementation or library stub for module named 'typedpkg.sample' +testTypedPkg_config_nositepackages.py:2: error: Cannot find implementation or library stub for module named "typedpkg.sample" testTypedPkg_config_nositepackages.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -testTypedPkg_config_nositepackages.py:3: error: Cannot find implementation or library stub for module named 'typedpkg' +testTypedPkg_config_nositepackages.py:3: error: Cannot find implementation or library stub for module named "typedpkg" testTypedPkg_config_nositepackages.py:5: note: Revealed type is 'Any' [case testTypedPkg_args_nositepackages] @@ -48,9 +48,9 @@ from typedpkg import dne a = ex(['']) reveal_type(a) [out] -testTypedPkg_args_nositepackages.py:3: error: Cannot find implementation or library stub for module named 'typedpkg.sample' +testTypedPkg_args_nositepackages.py:3: error: Cannot find implementation or library stub for module named "typedpkg.sample" testTypedPkg_args_nositepackages.py:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -testTypedPkg_args_nositepackages.py:4: error: Cannot find implementation or library stub for module named 'typedpkg' +testTypedPkg_args_nositepackages.py:4: error: Cannot find implementation or library stub for module named "typedpkg" testTypedPkg_args_nositepackages.py:6: note: Revealed type is 'Any' [case testTypedPkgStubs] @@ -132,7 +132,7 @@ af(False) bf(2) dne("abc") [out] -testTypedPkgNamespaceImportFrom.py:4: error: Cannot find implementation or library stub for module named 'typedpkg_ns.ns.dne' +testTypedPkgNamespaceImportFrom.py:4: error: Cannot find implementation or library stub for module named "typedpkg_ns.ns.dne" testTypedPkgNamespaceImportFrom.py:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports testTypedPkgNamespaceImportFrom.py:10: error: Argument 1 to "af" has incompatible type "bool"; expected "str" testTypedPkgNamespaceImportFrom.py:11: error: Argument 1 to "bf" has incompatible type "int"; expected "bool" @@ -151,7 +151,7 @@ af(False) bf(2) dne("abc") [out] -testTypedPkgNamespaceImportAs.py:4: error: Cannot find implementation or library stub for module named 'typedpkg_ns.ns.dne' +testTypedPkgNamespaceImportAs.py:4: error: Cannot find implementation or library stub for module named "typedpkg_ns.ns.dne" testTypedPkgNamespaceImportAs.py:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports testTypedPkgNamespaceImportAs.py:10: error: Argument 1 has incompatible type "bool"; expected "str" testTypedPkgNamespaceImportAs.py:11: error: Argument 1 has incompatible type "int"; expected "bool" @@ -171,7 +171,7 @@ bf(2) dne("abc") [out] -testTypedPkgNamespaceRegImport.py:4: error: Cannot find implementation or library stub for module named 'typedpkg_ns.ns.dne' +testTypedPkgNamespaceRegImport.py:4: error: Cannot find implementation or library stub for module named "typedpkg_ns.ns.dne" testTypedPkgNamespaceRegImport.py:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports testTypedPkgNamespaceRegImport.py:10: error: Argument 1 has incompatible type "bool"; expected "str" testTypedPkgNamespaceRegImport.py:11: error: Argument 1 has incompatible type "int"; expected "bool" diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index 4d2c7c19c086..6876744cbbb5 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -1259,7 +1259,7 @@ bar: Type[C] bar * 4 + bar + 3 # should not produce more errors [out] -_testMetaclassOpAccessAny.py:2: error: Cannot find implementation or library stub for module named 'nonexistent' +_testMetaclassOpAccessAny.py:2: error: Cannot find implementation or library stub for module named "nonexistent" _testMetaclassOpAccessAny.py:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testEnumIterationAndPreciseElementType] diff --git a/test-data/unit/semanal-errors.test b/test-data/unit/semanal-errors.test index f6446b87c24a..8fe6c70cb393 100644 --- a/test-data/unit/semanal-errors.test +++ b/test-data/unit/semanal-errors.test @@ -201,21 +201,21 @@ main:2: error: Module 'm' has no attribute 'y' import typing import m [out] -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testMissingModule2] import typing from m import x [out] -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testMissingModule3] import typing from m import * [out] -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testMissingModuleRelativeImport] @@ -224,7 +224,7 @@ import m [file m/__init__.py] from .x import y [out] -tmp/m/__init__.py:1: error: Cannot find implementation or library stub for module named 'm.x' +tmp/m/__init__.py:1: error: Cannot find implementation or library stub for module named "m.x" tmp/m/__init__.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testMissingModuleRelativeImport2] @@ -234,7 +234,7 @@ import m.a [file m/a.py] from .x import y [out] -tmp/m/a.py:1: error: Cannot find implementation or library stub for module named 'm.x' +tmp/m/a.py:1: error: Cannot find implementation or library stub for module named "m.x" tmp/m/a.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testModuleNotImported] @@ -283,18 +283,18 @@ main:4: error: Name 'n' is not defined import typing import m.n [out] -main:2: error: Cannot find implementation or library stub for module named 'm.n' +main:2: error: Cannot find implementation or library stub for module named "m.n" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" [case testMissingPackage2] import typing from m.n import x from a.b import * [out] -main:2: error: Cannot find implementation or library stub for module named 'm.n' +main:2: error: Cannot find implementation or library stub for module named "m.n" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:3: error: Cannot find implementation or library stub for module named 'a.b' +main:3: error: Cannot find implementation or library stub for module named "a.b" [case testErrorInImportedModule] import m @@ -322,9 +322,9 @@ m.n.x [file m/n.py] x = 1 [out] -main:2: error: Cannot find implementation or library stub for module named 'm.n' +main:2: error: Cannot find implementation or library stub for module named "m.n" main:2: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports -main:2: error: Cannot find implementation or library stub for module named 'm' +main:2: error: Cannot find implementation or library stub for module named "m" [case testBreakOutsideLoop] break From 2e4256507d09a27893cab85a8ce565d648ed1aa4 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 12:19:07 +0100 Subject: [PATCH 10/50] Fix some test cases --- test-data/unit/check-dataclasses.test | 86 ++++++++++++++++----------- test-data/unit/check-incremental.test | 16 +++-- test-data/unit/check-narrowing.test | 3 + 3 files changed, 67 insertions(+), 38 deletions(-) diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index 75f5d82ddc76..94fa17f0fcfc 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -1,5 +1,5 @@ [case testDataclassesBasic] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -18,7 +18,7 @@ Person('Jonh', 21, None) # E: Too many arguments for "Person" [typing fixtures/typing-medium.pyi] [case testDataclassesCustomInit] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -33,7 +33,7 @@ A('1') [builtins fixtures/list.pyi] [case testDataclassesBasicInheritance] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -56,7 +56,7 @@ Person(21, 'Jonh', None) # E: Too many arguments for "Person" [typing fixtures/typing-medium.pyi] [case testDataclassesDeepInheritance] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -83,6 +83,7 @@ reveal_type(D) # N: Revealed type is 'def (a: builtins.int, b: builtins.int, c: [builtins fixtures/list.pyi] [case testDataclassesMultipleInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass, field, InitVar @dataclass class A: @@ -105,6 +106,7 @@ reveal_type(C) # N: Revealed type is 'def (b: builtins.bool, a: builtins.bool) [builtins fixtures/bool.pyi] [case testDataclassesDeepInitVarInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass, field, InitVar @dataclass class A: @@ -133,7 +135,7 @@ reveal_type(D) # N: Revealed type is 'def (b: builtins.bool) -> __main__.D' [builtins fixtures/bool.pyi] [case testDataclassesOverriding] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -167,7 +169,7 @@ ExtraSpecialPerson(21, 'John', 0.5) [case testDataclassesOverridingWithDefaults] # Issue #5681 https://github.com/python/mypy/issues/5681 -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Any @@ -186,7 +188,7 @@ reveal_type(C) # N: Revealed type is 'def (some_int: builtins.int, some_str: bu [builtins fixtures/list.pyi] [case testDataclassesFreezing] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass(frozen=True) @@ -199,7 +201,7 @@ john.name = 'Ben' # E: Property "name" defined in "Person" is read-only [builtins fixtures/list.pyi] [case testDataclassesFields] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field @dataclass @@ -215,7 +217,7 @@ john.age = 24 [builtins fixtures/list.pyi] [case testDataclassesBadInit] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field @dataclass @@ -229,7 +231,7 @@ class Person: [builtins fixtures/list.pyi] [case testDataclassesMultiInit] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field from typing import List @@ -245,7 +247,7 @@ reveal_type(Person) # N: Revealed type is 'def (name: builtins.str, friend_name [builtins fixtures/list.pyi] [case testDataclassesMultiInitDefaults] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field from typing import List, Optional @@ -262,7 +264,7 @@ reveal_type(Person) # N: Revealed type is 'def (name: builtins.str, friend_name [builtins fixtures/list.pyi] [case testDataclassesDefaults] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -276,7 +278,7 @@ app = Application() [builtins fixtures/list.pyi] [case testDataclassesDefaultFactories] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field @dataclass @@ -288,7 +290,7 @@ class Application: [builtins fixtures/list.pyi] [case testDataclassesDefaultFactoryTypeChecking] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass, field @dataclass @@ -299,7 +301,7 @@ class Application: [builtins fixtures/list.pyi] [case testDataclassesDefaultOrdering] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -310,7 +312,7 @@ class Application: [builtins fixtures/list.pyi] [case testDataclassesClassmethods] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -327,7 +329,7 @@ app = Application.parse('') [builtins fixtures/classmethod.pyi] [case testDataclassesOverloadsAndClassmethods] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import overload, Union @@ -360,7 +362,7 @@ reveal_type(A.foo("foo")) # N: Revealed type is 'builtins.str' [builtins fixtures/classmethod.pyi] [case testDataclassesClassVars] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import ClassVar @@ -378,7 +380,7 @@ Application.COUNTER = 1 [builtins fixtures/list.pyi] [case testDataclassOrdering] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass(order=True) @@ -409,7 +411,7 @@ app1 >= app3 [builtins fixtures/list.pyi] [case testDataclassOrderingWithoutEquality] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass(eq=False, order=True) @@ -419,7 +421,7 @@ class Application: # E: eq must be True if order is True [builtins fixtures/list.pyi] [case testDataclassOrderingWithCustomMethods] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass(order=True) @@ -430,7 +432,7 @@ class Application: [builtins fixtures/list.pyi] [case testDataclassDefaultsInheritance] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Optional @@ -448,7 +450,7 @@ reveal_type(SpecializedApplication) # N: Revealed type is 'def (id: Union[built [builtins fixtures/list.pyi] [case testDataclassGenerics] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, List, Optional, TypeVar @@ -577,7 +579,7 @@ reveal_type(sub.middle_attr) # N: Revealed type is 'builtins.str*' [case testDataclassGenericsClassmethod] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, TypeVar @@ -599,6 +601,7 @@ reveal_type(A(0).other) # N: Revealed type is 'def (x: builtins.int*) -> __main [builtins fixtures/classmethod.pyi] [case testDataclassesForwardRefs] +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -617,6 +620,7 @@ A(b=42) # E: Argument "b" to "A" has incompatible type "int"; expected "B" [case testDataclassesInitVars] +# flags: --python-version 3.7 from dataclasses import InitVar, dataclass @dataclass @@ -645,7 +649,7 @@ app.database_name # E: "SpecializedApplication" has no attribute "database_name [builtins fixtures/list.pyi] [case testDataclassesInitVarsAndDefer] - +# flags: --python-version 3.7 from dataclasses import InitVar, dataclass defer: Yes @@ -665,6 +669,7 @@ class Yes: ... [builtins fixtures/list.pyi] [case testDataclassesNoInitInitVarInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass, field, InitVar @dataclass @@ -681,6 +686,7 @@ sub.bar [builtins fixtures/bool.pyi] [case testDataclassFactory] +# flags: --python-version 3.7 from typing import Type, TypeVar from dataclasses import dataclass @@ -696,6 +702,7 @@ class A: [builtins fixtures/classmethod.pyi] [case testDataclassesInitVarOverride] +# flags: --python-version 3.7 import dataclasses @dataclasses.dataclass @@ -718,6 +725,7 @@ class B(A): [builtins fixtures/bool.pyi] [case testDataclassesInitVarNoOverride] +# flags: --python-version 3.7 import dataclasses @dataclasses.dataclass @@ -743,6 +751,7 @@ B(1, 'a') # E: Argument 2 to "B" has incompatible type "str"; expected "int" [builtins fixtures/bool.pyi] [case testDataclassesInitVarPostInitOverride] +# flags: --python-version 3.7 import dataclasses @dataclasses.dataclass @@ -778,6 +787,7 @@ C(1, 'a') # E: Argument 2 to "C" has incompatible type "str"; expected "int" [builtins fixtures/primitives.pyi] [case testDataclassesInitVarIncremental] +# flags: --python-version 3.7 import a [file a.py] @@ -823,7 +833,7 @@ tmp/a.py:12: note: Revealed type is 'def (a: builtins.int) -> a.B' [case testNoComplainFieldNone] -# flags: --python-version 3.6 +# flags: --python-version 3.7 # flags: --no-strict-optional from dataclasses import dataclass, field from typing import Optional @@ -835,7 +845,7 @@ class Foo: [out] [case testNoComplainFieldNoneStrict] -# flags: --python-version 3.6 +# flags: --python-version 3.7 # flags: --strict-optional from dataclasses import dataclass, field from typing import Optional @@ -847,7 +857,7 @@ class Foo: [out] [case testDisallowUntypedWorksForward] -# flags: --disallow-untyped-defs +# flags: --disallow-untyped-defs --python-version 3.7 from dataclasses import dataclass from typing import List @@ -862,7 +872,7 @@ reveal_type(B) # N: Revealed type is 'def (x: __main__.C) -> __main__.B' [builtins fixtures/list.pyi] [case testDisallowUntypedWorksForwardBad] -# flags: --disallow-untyped-defs +# flags: --disallow-untyped-defs --python-version 3.7 from dataclasses import dataclass @dataclass @@ -874,6 +884,7 @@ reveal_type(B) # N: Revealed type is 'def (x: Any) -> __main__.B' [builtins fixtures/list.pyi] [case testMemberExprWorksAsField] +# flags: --python-version 3.7 import dataclasses @dataclasses.dataclass @@ -893,7 +904,7 @@ class C: [builtins fixtures/dict.pyi] [case testDataclassOrderingDeferred] -# flags: --python-version 3.6 +# flags: --python-version 3.7 from dataclasses import dataclass defer: Yes @@ -911,6 +922,7 @@ class Yes: ... [builtins fixtures/list.pyi] [case testDataclassFieldDeferred] +# flags: --python-version 3.7 from dataclasses import field, dataclass @dataclass @@ -922,6 +934,7 @@ C('no') # E: Argument 1 to "C" has incompatible type "str"; expected "int" [builtins fixtures/bool.pyi] [case testDataclassFieldDeferredFrozen] +# flags: --python-version 3.7 from dataclasses import field, dataclass @dataclass(frozen=True) @@ -934,6 +947,7 @@ c.x = 1 # E: Property "x" defined in "C" is read-only [builtins fixtures/bool.pyi] [case testTypeInDataclassDeferredStar] +# flags: --python-version 3.7 import lib [file lib.py] from dataclasses import dataclass @@ -952,6 +966,7 @@ import lib [builtins fixtures/bool.pyi] [case testDeferredDataclassInitSignature] +# flags: --python-version 3.7 --no-strict-optional from dataclasses import dataclass from typing import Optional, Type @@ -968,7 +983,7 @@ class Deferred: pass [builtins fixtures/classmethod.pyi] [case testDeferredDataclassInitSignatureSubclass] -# flags: --strict-optional +# flags: --strict-optional --python-version 3.7 from dataclasses import dataclass from typing import Optional @@ -984,7 +999,7 @@ a = C(None, 'abc') [builtins fixtures/bool.pyi] [case testDataclassesDefaultsIncremental] -# flags: --python-version 3.6 +# flags: --python-version 3.7 import a [file a.py] @@ -1016,7 +1031,7 @@ class Person: [builtins fixtures/list.pyi] [case testDataclassesDefaultsMroOtherFile] -# flags: --python-version 3.6 +# flags: --python-version 3.7 import a [file a.py] @@ -1045,19 +1060,21 @@ class A2: [builtins fixtures/list.pyi] [case testDataclassesInheritingDuplicateField] +# flags: --python-version 3.7 # see mypy issue #7792 from dataclasses import dataclass @dataclass class A: # E: Name 'x' already defined (possibly by an import) x: int = 0 - x: int = 0 # E: Name 'x' already defined on line 6 + x: int = 0 # E: Name 'x' already defined on line 7 @dataclass class B(A): pass [case testDataclassInheritanceNoAnnotation] +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass @@ -1072,6 +1089,7 @@ class B(A): reveal_type(B) # N: Revealed type is 'def (foo: builtins.int) -> __main__.B' [case testDataclassInheritanceNoAnnotation2] +# flags: --python-version 3.7 from dataclasses import dataclass @dataclass(frozen=True) diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test index dc19aa2a266e..053e0334bde3 100644 --- a/test-data/unit/check-incremental.test +++ b/test-data/unit/check-incremental.test @@ -3776,6 +3776,7 @@ import b [rechecked b] [case testIncrementalDataclassesSubclassingCached] +# flags: --python-version 3.7 from a import A from dataclasses import dataclass @@ -3808,6 +3809,7 @@ class A: [out2] [case testIncrementalDataclassesSubclassingCachedType] +# flags: --python-version 3.7 import b [file b.py] @@ -3841,6 +3843,7 @@ class A: tmp/b.py:8: note: Revealed type is 'def (x: builtins.int) -> b.B' [case testIncrementalDataclassesArguments] +# flags: --python-version 3.7 import b [file b.py] @@ -3889,6 +3892,7 @@ tmp/b.py:15: error: Unsupported left operand type for > ("NoCmp") tmp/b.py:16: error: Unsupported left operand type for >= ("NoCmp") [case testIncrementalDataclassesDunder] +# flags: --python-version 3.7 import b [file b.py] @@ -3953,6 +3957,7 @@ tmp/b.py:27: error: Unsupported operand types for < ("A" and "int") tmp/b.py:28: error: Unsupported operand types for <= ("A" and "int") [case testIncrementalDataclassesSubclassModified] +# flags: --python-version 3.7 from b import B B(5, 'foo') @@ -3982,10 +3987,11 @@ class B(A): [builtins fixtures/list.pyi] [out1] [out2] -main:2: error: Argument 2 to "B" has incompatible type "str"; expected "int" +main:3: error: Argument 2 to "B" has incompatible type "str"; expected "int" [rechecked b] [case testIncrementalDataclassesSubclassModifiedErrorFirst] +# flags: --python-version 3.7 from b import B B(5, 'foo') @@ -4014,12 +4020,13 @@ class B(A): [builtins fixtures/list.pyi] [out1] -main:2: error: Argument 2 to "B" has incompatible type "str"; expected "int" +main:3: error: Argument 2 to "B" has incompatible type "str"; expected "int" [out2] [rechecked b] [case testIncrementalDataclassesThreeFiles] +# flags: --python-version 3.7 from c import C C('foo', 5, True) @@ -4058,9 +4065,10 @@ class C(A, B): [out1] [out2] tmp/c.py:7: error: Incompatible types in assignment (expression has type "bool", base class "B" defined the type as "str") -main:2: error: Argument 2 to "C" has incompatible type "int"; expected "bool" +main:3: error: Argument 2 to "C" has incompatible type "int"; expected "bool" [case testIncrementalDataclassesThreeRuns] +# flags: --python-version 3.7 from a import A A(5) @@ -4088,7 +4096,7 @@ class A: [builtins fixtures/list.pyi] [out1] [out2] -main:2: error: Argument 1 to "A" has incompatible type "int"; expected "str" +main:3: error: Argument 1 to "A" has incompatible type "int"; expected "str" [out3] [case testParentPatchingMess] diff --git a/test-data/unit/check-narrowing.test b/test-data/unit/check-narrowing.test index a1d9685cc43d..8eb6f6439f60 100644 --- a/test-data/unit/check-narrowing.test +++ b/test-data/unit/check-narrowing.test @@ -1,4 +1,5 @@ [case testNarrowingParentWithStrsBasic] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import NamedTuple, Tuple, Union from typing_extensions import Literal, TypedDict @@ -82,6 +83,7 @@ else: [builtins fixtures/primitives.pyi] [case testNarrowingParentWithEnumsBasic] +# flags: --python-version 3.7 from enum import Enum from dataclasses import dataclass from typing import NamedTuple, Tuple, Union @@ -171,6 +173,7 @@ else: [builtins fixtures/tuple.pyi] [case testNarrowingParentWithIsInstanceBasic] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import NamedTuple, Tuple, Union from typing_extensions import TypedDict From b954fef0f0b7b818909e98b2d7dc0712267dbd25 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 12:47:19 +0100 Subject: [PATCH 11/50] Fix specifying Python version in fine-grained deps tests --- mypy/test/testdeps.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/mypy/test/testdeps.py b/mypy/test/testdeps.py index 3b1cddf00756..ea58d49533fc 100644 --- a/mypy/test/testdeps.py +++ b/mypy/test/testdeps.py @@ -35,15 +35,12 @@ class GetDependenciesSuite(DataSuite): def run_case(self, testcase: DataDrivenTestCase) -> None: src = '\n'.join(testcase.input) dump_all = '# __dump_all__' in src - if testcase.name.endswith('python2'): - python_version = defaults.PYTHON2_VERSION - else: - python_version = defaults.PYTHON3_VERSION options = parse_options(src, testcase, incremental_step=1) + if testcase.name.endswith('python2'): + options.python_version = defaults.PYTHON2_VERSION options.use_builtins_fixtures = True options.show_traceback = True options.cache_dir = os.devnull - options.python_version = python_version options.export_types = True options.preserve_asts = True messages, files, type_map = self.build(src, options) @@ -59,7 +56,8 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: 'mypy_extensions', 'typing_extensions', 'enum'): - new_deps = get_dependencies(files[module], type_map, python_version, options) + new_deps = get_dependencies(files[module], type_map, options.python_version, + options) for source in new_deps: deps[source].update(new_deps[source]) From 33f65add7c4b1e8d02e7bd0258bc28a9d28af15b Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 12:47:40 +0100 Subject: [PATCH 12/50] Fix error messages for submodules of third-party packages --- mypy/build.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 4d86c4309897..f61fb100f392 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2516,12 +2516,13 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, else: msg, notes = reason.error_message_templates() errors.report(line, 0, msg.format(target), code=codes.IMPORT) + top_level = target.partition('.')[0] for note in notes: if '{}' in note: - note = note.format(legacy_bundled_packages[target]) + note = note.format(legacy_bundled_packages[top_level]) errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) if reason is ModuleNotFoundReason.STUBS_NOT_INSTALLED: - manager.missing_stub_packages.add(legacy_bundled_packages[target]) + manager.missing_stub_packages.add(legacy_bundled_packages[top_level]) errors.set_import_context(save_import_context) From c83d584822fe60eea90fa8921b7ea19514ba03f9 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 12:52:16 +0100 Subject: [PATCH 13/50] Fix quoting issue in test --- test-data/unit/check-custom-plugin.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-data/unit/check-custom-plugin.test b/test-data/unit/check-custom-plugin.test index ed0e85cea689..9ab79bafd244 100644 --- a/test-data/unit/check-custom-plugin.test +++ b/test-data/unit/check-custom-plugin.test @@ -70,7 +70,7 @@ tmp/mypy.ini:2: error: Can't find plugin 'tmp/missing.py' \[mypy] plugins=missing [out] -tmp/mypy.ini:2: error: Error importing plugin 'missing': No module named "missing" +tmp/mypy.ini:2: error: Error importing plugin 'missing': No module named 'missing' [case testMultipleSectionsDefinePlugin] # flags: --config-file tmp/mypy.ini From 7bb7ef0edd977fb45dd65667b1a2ca4f00aeed83 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 14:23:56 +0100 Subject: [PATCH 14/50] Fix some error messages --- test-data/unit/cmdline.test | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index 4740ecbe95e9..cd67c0b646fb 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -124,7 +124,7 @@ mypy: can't decode file 'a.py': unknown encoding: uft-8 [file two/mod/__init__.py] # type: ignore [out] -two/mod/__init__.py: error: Duplicate module named "mod" (also at 'one/mod/__init__.py') +two/mod/__init__.py: error: Duplicate module named 'mod' (also at 'one/mod/__init__.py') == Return code: 2 [case promptsForgotInit] @@ -136,7 +136,7 @@ two/mod/__init__.py: error: Duplicate module named "mod" (also at 'one/mod/__ini [file one/mod/a.py] #type: ignore [out] -one/mod/a.py: error: Duplicate module named "a" (also at 'a.py') +one/mod/a.py: error: Duplicate module named 'a' (also at 'a.py') one/mod/a.py: error: Are you missing an __init__.py? == Return code: 2 From f0306f94b8a55fd89aa0ced7614ed1f1e8b68f25 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 14:25:19 +0100 Subject: [PATCH 15/50] Add mypy_extensiosn and typing_extensions to stdlib They are actually 3rd party modules, but they are special like some stdlib modules so we bundle them with mypy. --- mypy/typeshed/stdlib/mypy_extensions.pyi | 51 +++++++++++++++ mypy/typeshed/stdlib/typing_extensions.pyi | 76 ++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 mypy/typeshed/stdlib/mypy_extensions.pyi create mode 100644 mypy/typeshed/stdlib/typing_extensions.pyi diff --git a/mypy/typeshed/stdlib/mypy_extensions.pyi b/mypy/typeshed/stdlib/mypy_extensions.pyi new file mode 100644 index 000000000000..9e756dd5f0ee --- /dev/null +++ b/mypy/typeshed/stdlib/mypy_extensions.pyi @@ -0,0 +1,51 @@ +import abc +import sys +from typing import ( + Dict, Type, TypeVar, Optional, Union, Any, Generic, Mapping, ItemsView, KeysView, ValuesView, + Callable, +) + +_T = TypeVar('_T') +_U = TypeVar('_U') + +# 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: ... + def update(self: _T, __m: _T) -> None: ... + if sys.version_info < (3, 0): + def has_key(self, k: str) -> bool: ... + def viewitems(self) -> ItemsView[str, object]: ... + def viewkeys(self) -> KeysView[str]: ... + def viewvalues(self) -> ValuesView[object]: ... + else: + def items(self) -> ItemsView[str, object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... + def __delitem__(self, k: NoReturn) -> None: ... + +def TypedDict(typename: str, fields: Dict[str, Type[_T]], total: bool = ...) -> Type[Dict[str, Any]]: ... + +def Arg(type: _T = ..., name: Optional[str] = ...) -> _T: ... +def DefaultArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... +def NamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... +def DefaultNamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... +def VarArg(type: _T = ...) -> _T: ... +def KwArg(type: _T = ...) -> _T: ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] # Deprecated: Use typing.NoReturn instead. + +# This is intended as a class decorator, but mypy rejects abstract classes +# when a Type[_T] is expected, so we can't give it the type we want +def trait(cls: Any) -> Any: ... + +def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... + +class FlexibleAlias(Generic[_T, _U]): ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi new file mode 100644 index 000000000000..4a40137b99c6 --- /dev/null +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -0,0 +1,76 @@ +import abc +import sys +from typing import Callable +from typing import ClassVar as ClassVar +from typing import ContextManager as ContextManager +from typing import Counter as Counter +from typing import DefaultDict as DefaultDict +from typing import Deque as Deque +from typing import NewType as NewType +from typing import NoReturn as NoReturn +from typing import overload as overload +from typing import Text as Text +from typing import Type as Type +from typing import TYPE_CHECKING as TYPE_CHECKING +from typing import TypeVar, Any, Mapping, ItemsView, KeysView, Optional, ValuesView, Dict + +_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: ... + def update(self: _T, __m: _T) -> None: ... + if sys.version_info < (3, 0): + def has_key(self, k: str) -> bool: ... + def viewitems(self) -> ItemsView[str, object]: ... + def viewkeys(self) -> KeysView[str]: ... + def viewvalues(self) -> ValuesView[object]: ... + else: + 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. +TypedDict: object = ... + +if sys.version_info >= (3, 3): + from typing import ChainMap as ChainMap + +if sys.version_info >= (3, 5): + from typing import AsyncIterable as AsyncIterable + from typing import AsyncIterator as AsyncIterator + from typing import AsyncContextManager as AsyncContextManager + from typing import Awaitable as Awaitable + from typing import 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]] = ..., localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ... +) -> Dict[str, Any]: ... + +Annotated: _SpecialForm = ... +_AnnotatedAlias: Any = ... # undocumented + +# TypeAlias is a (non-subscriptable) special form. +TypeAlias: object From 94d68ea7cec8143014c3616955569daeab357789 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 15:40:09 +0100 Subject: [PATCH 16/50] Prefer typeshed over stub packages This avoids picking up the backport of dataclasses when type checking in Python 3.7 mode. It will still be picked up in Python 3.6 mode. --- mypy/modulefinder.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 8a43ab13914c..c2147bba1944 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -290,11 +290,13 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: third_party_stubs_dirs.clear() found_possible_third_party_missing_type_hints = False python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path - candidate_base_dirs = (self.find_lib_path_dirs(id, python_mypy_path) + - third_party_stubs_dirs + - third_party_inline_dirs) + candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path) if use_typeshed: + # Search for stdlib stubs in typeshed before installed + # stubs to avoid picking up backports (dataclasses, for + # example) when the library is included in stdlib. candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path) + candidate_base_dirs += third_party_stubs_dirs + third_party_inline_dirs # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now # contains just the subdirectories 'foo/bar' that actually exist under the From 58c770d9bebc4cbd8639df397643ffe57238d7ec Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 15:55:43 +0100 Subject: [PATCH 17/50] Determine supported Python major versions by reading METADATA.toml --- mypy/build.py | 6 +++--- mypy/modulefinder.py | 28 +++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index f61fb100f392..ac02372ee043 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2515,11 +2515,11 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, errors.raise_error() else: msg, notes = reason.error_message_templates() - errors.report(line, 0, msg.format(target), code=codes.IMPORT) + pyver = '%d.%d' % manager.options.python_version + errors.report(line, 0, msg.format(module=target, pyver=pyver), code=codes.IMPORT) top_level = target.partition('.')[0] for note in notes: - if '{}' in note: - note = note.format(legacy_bundled_packages[top_level]) + note = note.format(stub_dist=legacy_bundled_packages[top_level]) errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) if reason is ModuleNotFoundReason.STUBS_NOT_INSTALLED: manager.missing_stub_packages.add(legacy_bundled_packages[top_level]) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index c2147bba1944..7d5a319ebfef 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -59,18 +59,18 @@ class ModuleNotFoundReason(Enum): def error_message_templates(self) -> Tuple[str, List[str]]: doc_link = "See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports" if self is ModuleNotFoundReason.NOT_FOUND: - msg = 'Cannot find implementation or library stub for module named "{}"' + msg = 'Cannot find implementation or library stub for module named "{module}"' notes = [doc_link] elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: msg = "Cannot find implementation or library stub for module named '{}'" notes = ["You may be running mypy in a subpackage, " "mypy should be run on the package root"] elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: - msg = 'Skipping analyzing "{}": found module but no type hints or library stubs' + msg = 'Skipping analyzing "{module}": found module but no type hints or library stubs' notes = [doc_link] elif self is ModuleNotFoundReason.STUBS_NOT_INSTALLED: - msg = 'Library stubs not installed for "{}"' - notes = ['Hint: "python3 -m pip install {}"', + msg = 'Library stubs not installed for "{module}" (or incompatible with Python {pyver})' + notes = ['Hint: "python3 -m pip install {stub_dist}"', '(or run "mypy --install-types" to install all missing stub packages)', doc_link] else: @@ -253,7 +253,7 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: for pkg_dir in self.search_paths.package_path: stub_name = components[0] + '-stubs' stub_dir = os.path.join(pkg_dir, stub_name) - if fscache.isdir(stub_dir): + if fscache.isdir(stub_dir) and self._is_compatible_stub_package(stub_dir): stub_typed_file = os.path.join(stub_dir, 'py.typed') stub_components = [stub_name] + components[1:] path = os.path.join(pkg_dir, *stub_components[:-1]) @@ -383,6 +383,24 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: else: return ModuleNotFoundReason.NOT_FOUND + def _is_compatible_stub_package(self, stub_dir: str) -> bool: + """Does a stub package support the target Python version? + + Stub packages may contain a metadata file which specifies + whether the stubs are compatible with Python 2 and 3. + """ + metadata_fnam = os.path.join(stub_dir, 'METADATA.toml') + if os.path.isfile(metadata_fnam) and self.options: + # Delay import for a possible minor performance win. + import toml + with open(metadata_fnam, 'r') as f: + metadata = toml.load(f) + if self.options.python_version[0] == 2: + return bool(metadata.get('python2', False)) + else: + return bool(metadata.get('python3', True)) + return True + def find_modules_recursive(self, module: str) -> List[BuildSource]: module_path = self.find_module(module) if isinstance(module_path, ModuleNotFoundReason): From f651a5e423b2853baf5fcfb04eb50d03d6609b7b Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 16:47:50 +0100 Subject: [PATCH 18/50] Fix crash on missing package --- mypy/build.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mypy/build.py b/mypy/build.py index ac02372ee043..c8447718327e 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2519,7 +2519,8 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, errors.report(line, 0, msg.format(module=target, pyver=pyver), code=codes.IMPORT) top_level = target.partition('.')[0] for note in notes: - note = note.format(stub_dist=legacy_bundled_packages[top_level]) + if '{stub_dist}' in note: + note = note.format(stub_dist=legacy_bundled_packages[top_level]) errors.report(line, 0, note, severity='note', only_once=True, code=codes.IMPORT) if reason is ModuleNotFoundReason.STUBS_NOT_INSTALLED: manager.missing_stub_packages.add(legacy_bundled_packages[top_level]) From d2b52a12a11d7a03203ddc2db0166e8390af7ce1 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 16:48:34 +0100 Subject: [PATCH 19/50] Find Python 2 variants of stub packages This is currently needed for six. --- mypy/modulefinder.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 7d5a319ebfef..efbe0e6534d2 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -126,6 +126,7 @@ def __init__(self, self.ns_ancestors = {} # type: Dict[str, str] self.options = options self.stdlib_py_versions = load_stdlib_py_versions() + self.python2 = options and options.python_version[0] == 2 def clear(self) -> None: self.results.clear() @@ -253,6 +254,12 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: for pkg_dir in self.search_paths.package_path: stub_name = components[0] + '-stubs' stub_dir = os.path.join(pkg_dir, stub_name) + if self.python2: + alt_stub_name = components[0] + '-python2-stubs' + alt_stub_dir = os.path.join(pkg_dir, alt_stub_name) + if fscache.isdir(alt_stub_dir): + stub_name = alt_stub_name + stub_dir = alt_stub_dir if fscache.isdir(stub_dir) and self._is_compatible_stub_package(stub_dir): stub_typed_file = os.path.join(stub_dir, 'py.typed') stub_components = [stub_name] + components[1:] @@ -314,7 +321,11 @@ def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult: # Prefer package over module, i.e. baz/__init__.py* over baz.py*. for extension in PYTHON_EXTENSIONS: path = base_path + sepinit + extension - path_stubs = base_path + '-stubs' + sepinit + extension + suffix = '-stubs' + if self.python2: + if os.path.isdir(base_path + '-python2-stubs'): + suffix = '-python2-stubs' + path_stubs = base_path + suffix + sepinit + extension if fscache.isfile_case(path, dir_prefix): has_init = True if verify and not verify_module(fscache, id, path, dir_prefix): @@ -390,12 +401,12 @@ def _is_compatible_stub_package(self, stub_dir: str) -> bool: whether the stubs are compatible with Python 2 and 3. """ metadata_fnam = os.path.join(stub_dir, 'METADATA.toml') - if os.path.isfile(metadata_fnam) and self.options: + if os.path.isfile(metadata_fnam): # Delay import for a possible minor performance win. import toml with open(metadata_fnam, 'r') as f: metadata = toml.load(f) - if self.options.python_version[0] == 2: + if self.python2: return bool(metadata.get('python2', False)) else: return bool(metadata.get('python3', True)) From 49ca5440a709bba920d5cee449381e4d4bb182c0 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 18:15:37 +0100 Subject: [PATCH 20/50] Skip Python 2 enum test --- test-data/unit/check-enum.test | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test-data/unit/check-enum.test b/test-data/unit/check-enum.test index 37b12a0c32eb..0da3217b72e8 100644 --- a/test-data/unit/check-enum.test +++ b/test-data/unit/check-enum.test @@ -505,7 +505,8 @@ def fn(x: F) -> None: fn(b) [out] -[case testFunctionalEnum_python2] +[case testFunctionalEnum_python2-skip] +# TODO: Needs to have enum34 stubs somehow from enum import Enum Eu = Enum(u'Eu', u'a b') Eb = Enum(b'Eb', b'a b') From e9dfad81de663772af06687551fd13e0044285b7 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 29 Jun 2020 18:20:51 +0100 Subject: [PATCH 21/50] Fix attrs test case by completing test stub --- .../unit/lib-stub/{attr.pyi => attr/__init__.pyi} | 0 test-data/unit/lib-stub/attr/converters.pyi | 12 ++++++++++++ 2 files changed, 12 insertions(+) rename test-data/unit/lib-stub/{attr.pyi => attr/__init__.pyi} (100%) create mode 100644 test-data/unit/lib-stub/attr/converters.pyi diff --git a/test-data/unit/lib-stub/attr.pyi b/test-data/unit/lib-stub/attr/__init__.pyi similarity index 100% rename from test-data/unit/lib-stub/attr.pyi rename to test-data/unit/lib-stub/attr/__init__.pyi diff --git a/test-data/unit/lib-stub/attr/converters.pyi b/test-data/unit/lib-stub/attr/converters.pyi new file mode 100644 index 000000000000..63b2a3866e31 --- /dev/null +++ b/test-data/unit/lib-stub/attr/converters.pyi @@ -0,0 +1,12 @@ +from typing import TypeVar, Optional, Callable, overload +from . import _ConverterType + +_T = TypeVar("_T") + +def optional( + converter: _ConverterType[_T] +) -> _ConverterType[Optional[_T]]: ... +@overload +def default_if_none(default: _T) -> _ConverterType[_T]: ... +@overload +def default_if_none(*, factory: Callable[[], _T]) -> _ConverterType[_T]: ... From 191a1be9a906b94579f9507da28cb39f5230c63a Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 30 Jun 2020 15:46:03 +0100 Subject: [PATCH 22/50] Update documentation for modular typeshed --- docs/source/command_line.rst | 20 ++++ docs/source/getting_started.rst | 48 ++++++++-- docs/source/installed_packages.rst | 147 +++++++++++++++++++---------- docs/source/running_mypy.rst | 44 ++++++++- 4 files changed, 193 insertions(+), 66 deletions(-) diff --git a/docs/source/command_line.rst b/docs/source/command_line.rst index 40df775742a6..51edffcd1c62 100644 --- a/docs/source/command_line.rst +++ b/docs/source/command_line.rst @@ -841,6 +841,26 @@ format into the specified directory. Miscellaneous ************* +.. option:: --install-types + + This flag causes mypy to install known missing stub packages for + third-party libraries using pip. It will display the pip command + line to run, and expects a confirmation before installing + anything. + + If you use this option without providing any files or modules to + type check, mypy will install stub packages suggested during the + previous mypy run. If there are files or modules to type check, + mypy first type checks those, and proposes to install missing + stubs at the end of the run, but only if any missing modules were + detected. + + .. note:: + + This is new in mypy 0.800. Previous mypy versions included a + selection of third-party packages, instead of having them + installed separately. + .. option:: --junit-xml JUNIT_XML Causes mypy to generate a JUnit XML test result document with diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index 398a6f566cfc..07b1193e6b4f 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -329,10 +329,11 @@ Library stubs and typeshed Mypy uses library *stubs* to type check code interacting with library modules, including the Python standard library. A library stub defines a skeleton of the public interface of the library, including classes, -variables and functions, and their types. Mypy ships with stubs from -the `typeshed `_ project, which -contains library stubs for the Python builtins, the standard library, -and selected third-party packages. +variables and functions, and their types. Mypy ships with stubs for +the standard library from the `typeshed +`_ project, which contains library +stubs for the Python builtins, the standard library, and selected +third-party packages. For example, consider this code: @@ -344,11 +345,40 @@ Without a library stub, mypy would have no way of inferring the type of ``x`` and checking that the argument to :py:func:`chr` has a valid type. Mypy complains if it can't find a stub (or a real module) for a -library module that you import. Some modules ship with stubs that mypy -can automatically find, or you can install a 3rd party module with -additional stubs (see :ref:`installed-packages` for details). You can -also :ref:`create stubs ` easily. We discuss ways of -silencing complaints about missing stubs in :ref:`ignore-missing-imports`. +library module that you import. Some modules ship with stubs or inline +annotations that mypy can automatically find, or you can install +additional stubs using pip (see :ref:`fix-missing-imports` and +:ref:`installed-packages` for the details). For example, you can install +the stubs for the ``requests`` package like this: + +.. code-block:: + + python3 -m pip install types-requests + +The stubs are usually packaged in a distribution named +``types-``. Note that the distribution name may be +different from the name of the package that you import. For example, +``types-PyYAML`` contains stubs for the ``yaml`` package. Mypy can +often suggest the name of the stub distribution: + +.. code-block:: text + + prog.py:1: error: Library stubs not installed for "yaml" (or incompatible with Python 3.8) + prog.py:1: note: Hint: "python3 -m pip install types-PyYAML" + ... + +.. note:: + + Starting in mypy 0.800, most third-party package stubs must be + installed explicitly. This decouples mypy and stub versioning, + allowing stubs to updated without updating mypy. This also allows + stubs not originally included with mypy to be installed. Earlier + mypy versions included a fixed set of stubs for third-party + packages. + +You can also :ref:`create +stubs ` easily. We discuss ways of silencing complaints +about missing stubs in :ref:`ignore-missing-imports`. Configuring mypy **************** diff --git a/docs/source/installed_packages.rst b/docs/source/installed_packages.rst index 0a509c51fa0d..d640f5d13afb 100644 --- a/docs/source/installed_packages.rst +++ b/docs/source/installed_packages.rst @@ -3,54 +3,92 @@ Using installed packages ======================== -:pep:`561` specifies how to mark a package as supporting type checking. -Below is a summary of how to create PEP 561 compatible packages and have -mypy use them in type checking. - -Using PEP 561 compatible packages with mypy -******************************************* - -Generally, you do not need to do anything to use installed packages that -support typing for the Python executable used to run mypy. Note that most -packages do not support typing. Packages that do support typing should be -automatically picked up by mypy and used for type checking. - -By default, mypy searches for packages installed for the Python executable -running mypy. It is highly unlikely you want this situation if you have -installed typed packages in another Python's package directory. - -Generally, you can use the :option:`--python-version ` flag and mypy will try to find -the correct package directory. If that fails, you can use the -:option:`--python-executable ` flag to point to the exact executable, and mypy will -find packages installed for that Python executable. - -Note that mypy does not support some more advanced import features, such as zip -imports and custom import hooks. - -If you do not want to use typed packages, use the :option:`--no-site-packages ` flag -to disable searching. - -Note that stub-only packages (defined in :pep:`PEP 561: Stub-only Packages -<561#stub-only-packages>`) cannot be used with ``MYPYPATH``. If you want mypy -to find the package, it must be installed. For a package ``foo``, the name of -the stub-only package (``foo-stubs``) is not a legal package name, so mypy -will not find it, unless it is installed. - -Making PEP 561 compatible packages -********************************** - -:pep:`561` notes three main ways to distribute type information. The first is a -package that has only inline type annotations in the code itself. The second is -a package that ships :ref:`stub files ` with type information -alongside the runtime code. The third method, also known as a "stub only -package" is a package that ships type information for a package separately as -stub files. - -If you would like to publish a library package to a package repository (e.g. -PyPI) for either internal or external use in type checking, packages that -supply type information via type comments or annotations in the code should put -a ``py.typed`` file in their package directory. For example, with a directory -structure as follows +Packages installed with pip can declare that they support type +checking. For example, the `aiohttp +`_ package has built-in support +for type checking. + +Packages can also provide stubs for a library. For example, +``types-requests`` is a stub-only package that provides stubs for the +`requests `_ package. +Stub packages are usually published from `typeshed +`_, a shared repository for Python +library stubs, and have a name of form ``types-``. Note that +many stub packages are not maintained by the original maintainers of +the package. + +The sections below explain how mypy can use these packages, and how +you can create such packages. + +.. note:: + + :pep:`561` specifies how a package can declare that it supports + type checking. + +Using installed packages with mypy (PEP 561) +******************************************** + +Typically mypy will automatically find and use installed packages that +support type checking or provide stubs. This requires that you install +the packages in the Python environment that you use to run mypy. As +many packages don't support type checking yet, you may also have to +install a separate stub package, usually named +``types-``. (See :ref:`fix-missing-imports` for how to deal +with libraries that don't support type checking and are also missing +stubs.) + +If you have installed typed packages in another Python installation or +environment, mypy won't automatically find them. One option is to +install another copy of those packages in the environment in which you +use to run mypy. Alternatively, you can use the +:option:`--python-executable ` flag to point +to the target Python executable, and mypy will find packages installed +for that Python executable. + +Note that mypy does not support some more advanced import features, +such as zip imports and custom import hooks. + +If you don't want to use installed packages that provide type +information at all, use the :option:`--no-site-packages ` flag to disable searching for installed packages. + +Note that stub-only packages cannot be used with ``MYPYPATH``. If you +want mypy to find the package, it must be installed. For a package +``foo``, the name of the stub-only package (``foo-stubs``) is not a +legal package name, so mypy will not find it, unless it is installed +(see :pep:`PEP 561: Stub-only Packages <561#stub-only-packages>` for +more information). + +Creating PEP 561 compatible packages +************************************ + +.. note:: + + You can generally ignore this section unless you maintain a package on + PyPI, or want to publish type information for an existing PyPI + package. + +:pep:`561` describes three main ways to distribute type +information: + +1. A package has inline type annotations in the Python implementation. + +2. A package ships :ref:`stub files ` with type + information alongside the Python implementation. + +3. A package ships type information for another package separately as + stub files (also known as a "stub-only package"). + +If you want to create a stub-only package for an existing library, the +simplest way is to contribute stubs to the `typeshed +`_ repository, and a stub package +will automatically be uploaded to PyPI. + +If you would like to publish a library package to a package repository +yourself (e.g. on PyPI) for either internal or external use in type +checking, packages that supply type information via type comments or +annotations in the code should put a ``py.typed`` file in their +package directory. For example, here is a typical directory structure: .. code-block:: text @@ -60,7 +98,7 @@ structure as follows lib.py py.typed -the ``setup.py`` might look like +The ``setup.py`` file could look like this: .. code-block:: python @@ -80,7 +118,7 @@ the ``setup.py`` might look like ``setup()``, or mypy will not be able to find the installed package. Some packages have a mix of stub files and runtime files. These packages also -require a ``py.typed`` file. An example can be seen below +require a ``py.typed`` file. An example can be seen below: .. code-block:: text @@ -91,7 +129,7 @@ require a ``py.typed`` file. An example can be seen below lib.pyi py.typed -the ``setup.py`` might look like: +The ``setup.py`` file might look like this: .. code-block:: python @@ -121,7 +159,7 @@ had stubs for ``package_c``, we might do the following: __init__.pyi lib.pyi -the ``setup.py`` might look like: +The ``setup.py`` might look like this: .. code-block:: python @@ -134,3 +172,8 @@ the ``setup.py`` might look like: package_data={"package_c-stubs": ["__init__.pyi", "lib.pyi"]}, packages=["package_c-stubs"] ) + +If you have separate stubs for Python 2 and Python 3, you can place +the Python 2 stubs in a directory with the suffix ``-python2-stubs``. +We recommend that Python 2 and Python 3 stubs are bundled together for +simplicity, instead of distributing them separately. diff --git a/docs/source/running_mypy.rst b/docs/source/running_mypy.rst index 12001a04f2f0..3498aaf07275 100644 --- a/docs/source/running_mypy.rst +++ b/docs/source/running_mypy.rst @@ -127,17 +127,21 @@ The third outcome is what mypy will do in the ideal case. The following sections will discuss what to do in the other two cases. .. _ignore-missing-imports: +.. _fix-missing-imports: Missing imports *************** -When you import a module, mypy may report that it is unable to -follow the import. +When you import a module, mypy may report that it is unable to follow +the import. -This can cause errors that look like the following:: +This can cause errors that look like the following: - main.py:1: error: Skipping analyzing 'django': found module but no type hints or library stubs - main.py:2: error: Cannot find implementation or library stub for module named 'this_module_does_not_exist' +.. code-block:: text + + main.py:1: error: Library stubs not installed for "requests" (or incompatible with Python 3.8) + main.py:2: error: Skipping analyzing 'django': found module but no type hints or library stubs + main.py:3: error: Cannot find implementation or library stub for module named "this_module_does_not_exist" If you get any of these errors on an import, mypy will assume the type of that module is ``Any``, the dynamic type. This means attempting to access any @@ -153,6 +157,36 @@ attribute of the module will automatically succeed: The next sections describe what each error means and recommended next steps. +Library stubs not installed +--------------------------- + +If mypy can't find stubs for a third-party library, and it knows that stubs exist for +the library, you will get a message like this: + +.. code-block:: text + + main.py:1: error: Library stubs not installed for "yaml" (or incompatible with Python 3.8) + main.py:1: note: Hint: "python3 -m pip install types-PyYAML" + main.py:1: note: (or run "mypy --install-types" to install all missing stub packages) + +You can resolve the issue by running the suggested pip command or +commands. Alternatively, you can use :option:`--install-types ` to install all known missing stubs: + +.. code-block:: text + + mypy --install-types + +This installs any stub packages that were suggested in the previous +mypy run. You can also use your normal mypy command line with the +extra :option:`--install-types ` option to +install missing stubs at the end of the run (if any were found). + +You can also get this message if the stubs only support Python 3 and +your target Python version is Python 2, or vice versa. In this case +follow instructions in +:ref:`missing-type-hints-for-third-party-library`. + .. _missing-type-hints-for-third-party-library: Missing type hints for third party library From c91ef99442615a04ece063deb80a39537a610553 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 11:23:10 +0000 Subject: [PATCH 23/50] Add mypy.stubinfo --- mypy/stubinfo.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 mypy/stubinfo.py diff --git a/mypy/stubinfo.py b/mypy/stubinfo.py new file mode 100644 index 000000000000..275cd44092f2 --- /dev/null +++ b/mypy/stubinfo.py @@ -0,0 +1,73 @@ +# Stubs for these third-party packages used to be shipped with mypy. +# +# Map package name to PyPI stub distribution name. +legacy_bundled_packages = { + 'atomicwrites': 'types-atomicwrites', + 'attr': 'types-attrs', + 'backports': 'types-backports', + 'backports_abc': 'types-backports_abc', + 'bleach': 'types-bleach', + 'boto': 'types-boto', + 'certifi': 'types-certifi', + 'characteristic': 'types-characteristic', + 'chardet': 'types-chardet', + 'click': 'types-click', + 'concurrent': 'types-futures', + 'contextvars': 'types-contextvars', + 'croniter': 'types-croniter', + 'Crypto': 'types-pycrypto', + 'cryptography': 'types-cryptography', + 'dataclasses': 'types-dataclasses', + 'dateparser': 'types-dateparser', + 'datetimerange': 'types-DateTimeRange', + 'dateutil': 'types-python-dateutil', + 'decorator': 'types-decorator', + 'docutils': 'types-docutils', + 'emoji': 'types-emoji', + 'enum': 'types-enum34', + 'fb303': 'types-fb303', + 'first': 'types-first', + 'flask': 'types-Flask', + 'geoip2': 'types-geoip2', + 'gflags': 'types-python-gflags', + 'google': 'types-protobuf', + 'ipaddress': 'types-ipaddress', + 'itsdangerous': 'types-itsdangerous', + 'jinja2': 'types-Jinja2', + 'jwt': 'types-jwt', + 'kazoo': 'types-kazoo', + 'markupsafe': 'types-MarkupSafe', + 'maxminddb': 'types-maxminddb', + 'mock': 'types-mock', + 'mypy_extensions': 'types-mypy-extensions', + 'OpenSSL': 'types-openssl-python', + 'orjson': 'types-orjson', + 'pathlib2': 'types-pathlib2', + 'pkg_resources': 'types-pkg_resources', + 'pycurl': 'types-pycurl', + 'pymssql': 'types-pymssql', + 'pymysql': 'types-PyMySQL', + 'pynamodb': 'types-pynamodb', + 'pyre_extensions': 'types-pyre-extensions', + 'python2': 'types-six', + 'pytz': 'types-pytz', + 'pyVmomi': 'types-pyvmomi', + 'redis': 'types-redis', + 'requests': 'types-requests', + 'routes': 'types-Routes', + 'scribe': 'types-scribe', + 'simplejson': 'types-simplejson', + 'singledispatch': 'types-singledispatch', + 'six': 'types-six', + 'tabulate': 'types-tabulate', + 'termcolor': 'types-termcolor', + 'toml': 'types-toml', + 'tornado': 'types-tornado', + 'typed_ast': 'types-typed-ast', + 'typing_extensions': 'types-typing-extensions', + 'tzlocal': 'types-tzlocal', + 'ujson': 'types-ujson', + 'waitress': 'types-waitress', + 'werkzeug': 'types-Werkzeug', + 'yaml': 'types-PyYAML', +} From 508f00994ef10edbcdcbd150cfc1a6591110751b Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 11:24:40 +0000 Subject: [PATCH 24/50] Fix issues from rebase --- mypy/modulefinder.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index efbe0e6534d2..3b7e503c7fd3 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -188,7 +188,7 @@ def find_module(self, id: str) -> ModuleSearchResult: if top_level in self.stdlib_py_versions: min_version = self.stdlib_py_versions[top_level] use_typeshed = self.options is None or self.options.python_version >= min_version - self.results[id] = self._find_module(id) + self.results[id] = self._find_module(id, use_typeshed) if (self.results[id] is ModuleNotFoundReason.NOT_FOUND and self._can_find_module_in_parent_dir(id)): self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY @@ -230,7 +230,7 @@ def _can_find_module_in_parent_dir(self, id: str) -> bool: for file in os.listdir(working_dir)): working_dir = os.path.dirname(working_dir) parent_search.search_paths = SearchPaths((working_dir,), (), (), ()) - if not isinstance(parent_search._find_module(id), ModuleNotFoundReason): + if not isinstance(parent_search._find_module(id, False), ModuleNotFoundReason): return True return False From 62eeb0e0be71465c627cdf72993c11c688c45130 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 11:33:47 +0000 Subject: [PATCH 25/50] Fix tests --- test-data/unit/check-dataclasses.test | 4 ++++ test-data/unit/check-modules.test | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index 94fa17f0fcfc..8448de0a31b4 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -484,6 +484,7 @@ s: str = a.bar() # E: Incompatible types in assignment (expression has type "in [case testDataclassUntypedGenericInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, TypeVar @@ -503,6 +504,7 @@ reveal_type(sub.attr) # N: Revealed type is 'Any' [case testDataclassGenericSubtype] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, TypeVar @@ -528,6 +530,7 @@ reveal_type(sub_str.attr) # N: Revealed type is 'builtins.str*' [case testDataclassGenericInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, TypeVar @@ -553,6 +556,7 @@ reveal_type(sub.three) # N: Revealed type is 'builtins.float*' [case testDataclassMultiGenericInheritance] +# flags: --python-version 3.7 from dataclasses import dataclass from typing import Generic, TypeVar diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test index f3a4af9649ba..630f05b0a9fe 100644 --- a/test-data/unit/check-modules.test +++ b/test-data/unit/check-modules.test @@ -2823,5 +2823,5 @@ from stub import d # E: Module 'stub' has no attribute 'd' from mystery import a, b as b, c as d [out] -tmp/stub.pyi:1: error: Cannot find implementation or library stub for module named 'mystery' +tmp/stub.pyi:1: error: Cannot find implementation or library stub for module named "mystery" tmp/stub.pyi:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports From 11e6f03d2d4c3d9d8f24a6056b5f4e5e2f84124b Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 11:40:11 +0000 Subject: [PATCH 26/50] Fix lint --- mypy/build.py | 2 +- mypy/modulefinder.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index c8447718327e..f83fb4d56bfe 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -2515,7 +2515,7 @@ def module_not_found(manager: BuildManager, line: int, caller_state: State, errors.raise_error() else: msg, notes = reason.error_message_templates() - pyver = '%d.%d' % manager.options.python_version + pyver = '%d.%d' % manager.options.python_version errors.report(line, 0, msg.format(module=target, pyver=pyver), code=codes.IMPORT) top_level = target.partition('.')[0] for note in notes: diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 3b7e503c7fd3..d1ff86c46356 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -69,7 +69,9 @@ def error_message_templates(self) -> Tuple[str, List[str]]: msg = 'Skipping analyzing "{module}": found module but no type hints or library stubs' notes = [doc_link] elif self is ModuleNotFoundReason.STUBS_NOT_INSTALLED: - msg = 'Library stubs not installed for "{module}" (or incompatible with Python {pyver})' + msg = ( + 'Library stubs not installed for "{module}" (or incompatible with Python {pyver})' + ) notes = ['Hint: "python3 -m pip install {stub_dist}"', '(or run "mypy --install-types" to install all missing stub packages)', doc_link] From b17ebdb5a5f409543c5edb12cc5030dccb462232 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 16:18:13 +0000 Subject: [PATCH 27/50] Sync typeshed Source commit: https://github.com/python/typeshed/commit/eb9d9953625846179f6f492f867e449deec1ecb3 --- mypy/typeshed/stdlib/VERSIONS | 209 +- mypy/typeshed/stdlib/_ast.pyi | 98 +- mypy/typeshed/stdlib/_bisect.pyi | 5 +- mypy/typeshed/stdlib/_bootlocale.pyi | 1 - mypy/typeshed/stdlib/_codecs.pyi | 23 +- mypy/typeshed/stdlib/_compat_pickle.pyi | 6 +- mypy/typeshed/stdlib/_compression.pyi | 29 +- mypy/typeshed/stdlib/_csv.pyi | 3 +- mypy/typeshed/stdlib/_curses.pyi | 39 +- mypy/typeshed/stdlib/_decimal.pyi | 1 - mypy/typeshed/stdlib/_dummy_threading.pyi | 103 +- mypy/typeshed/stdlib/_heapq.pyi | 5 +- mypy/typeshed/stdlib/_imp.pyi | 5 +- .../typeshed/stdlib/_importlib_modulespec.pyi | 12 +- mypy/typeshed/stdlib/_json.pyi | 19 +- mypy/typeshed/stdlib/_markupbase.pyi | 1 - mypy/typeshed/stdlib/_msi.pyi | 15 +- mypy/typeshed/stdlib/_operator.pyi | 93 +- mypy/typeshed/stdlib/_osx_support.pyi | 14 +- mypy/typeshed/stdlib/_posixsubprocess.pyi | 30 +- mypy/typeshed/stdlib/_py_abc.pyi | 7 +- mypy/typeshed/stdlib/_pydecimal.pyi | 1 - mypy/typeshed/stdlib/_random.pyi | 2 - mypy/typeshed/stdlib/_sitebuiltins.pyi | 4 +- mypy/typeshed/stdlib/_stat.pyi | 4 - mypy/typeshed/stdlib/_thread.pyi | 27 +- mypy/typeshed/stdlib/_threading_local.pyi | 1 - mypy/typeshed/stdlib/_tkinter.pyi | 93 + mypy/typeshed/stdlib/_tracemalloc.pyi | 9 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 147 +- mypy/typeshed/stdlib/_typeshed/wsgi.pyi | 7 +- mypy/typeshed/stdlib/_typeshed/xml.pyi | 10 + mypy/typeshed/stdlib/_warnings.pyi | 5 +- mypy/typeshed/stdlib/_weakref.pyi | 12 +- mypy/typeshed/stdlib/_weakrefset.pyi | 16 +- mypy/typeshed/stdlib/_winapi.pyi | 57 +- mypy/typeshed/stdlib/abc.pyi | 9 +- mypy/typeshed/stdlib/aifc.pyi | 16 +- mypy/typeshed/stdlib/antigravity.pyi | 1 - mypy/typeshed/stdlib/argparse.pyi | 402 ++- mypy/typeshed/stdlib/array.pyi | 31 +- mypy/typeshed/stdlib/ast.pyi | 38 +- mypy/typeshed/stdlib/asynchat.pyi | 4 +- mypy/typeshed/stdlib/asyncio/__init__.pyi | 150 +- mypy/typeshed/stdlib/asyncio/base_events.pyi | 298 +- mypy/typeshed/stdlib/asyncio/base_futures.pyi | 17 +- .../stdlib/asyncio/base_subprocess.pyi | 45 +- mypy/typeshed/stdlib/asyncio/base_tasks.pyi | 9 +- mypy/typeshed/stdlib/asyncio/compat.pyi | 2 - mypy/typeshed/stdlib/asyncio/constants.pyi | 4 +- mypy/typeshed/stdlib/asyncio/coroutines.pyi | 2 +- mypy/typeshed/stdlib/asyncio/events.pyi | 345 +- .../stdlib/asyncio/format_helpers.pyi | 11 +- mypy/typeshed/stdlib/asyncio/futures.pyi | 22 +- mypy/typeshed/stdlib/asyncio/locks.pyi | 21 +- mypy/typeshed/stdlib/asyncio/log.pyi | 1 - .../stdlib/asyncio/proactor_events.pyi | 55 +- mypy/typeshed/stdlib/asyncio/protocols.pyi | 2 +- mypy/typeshed/stdlib/asyncio/queues.pyi | 15 +- mypy/typeshed/stdlib/asyncio/runners.pyi | 11 +- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 50 +- mypy/typeshed/stdlib/asyncio/staggered.pyi | 11 +- mypy/typeshed/stdlib/asyncio/streams.pyi | 54 +- mypy/typeshed/stdlib/asyncio/subprocess.pyi | 25 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 206 +- mypy/typeshed/stdlib/asyncio/threads.pyi | 2 +- mypy/typeshed/stdlib/asyncio/transports.pyi | 15 +- mypy/typeshed/stdlib/asyncio/trsock.pyi | 32 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 10 +- .../typeshed/stdlib/asyncio/windows_utils.pyi | 8 +- mypy/typeshed/stdlib/asyncore.pyi | 30 +- mypy/typeshed/stdlib/atexit.pyi | 2 - mypy/typeshed/stdlib/audioop.pyi | 2 +- mypy/typeshed/stdlib/base64.pyi | 19 +- mypy/typeshed/stdlib/bdb.pyi | 20 +- mypy/typeshed/stdlib/binascii.pyi | 15 +- mypy/typeshed/stdlib/binhex.pyi | 8 +- mypy/typeshed/stdlib/bisect.pyi | 2 +- mypy/typeshed/stdlib/builtins.pyi | 1804 ++++------ mypy/typeshed/stdlib/bz2.pyi | 16 +- mypy/typeshed/stdlib/cProfile.pyi | 12 +- mypy/typeshed/stdlib/calendar.pyi | 3 +- mypy/typeshed/stdlib/cgi.pyi | 88 +- mypy/typeshed/stdlib/cgitb.pyi | 22 +- mypy/typeshed/stdlib/chunk.pyi | 3 - mypy/typeshed/stdlib/cmath.pyi | 4 +- mypy/typeshed/stdlib/cmd.pyi | 4 +- mypy/typeshed/stdlib/code.pyi | 34 +- mypy/typeshed/stdlib/codecs.pyi | 64 +- mypy/typeshed/stdlib/codeop.pyi | 3 - mypy/typeshed/stdlib/collections/__init__.pyi | 118 +- mypy/typeshed/stdlib/collections/abc.pyi | 29 +- mypy/typeshed/stdlib/colorsys.pyi | 2 - mypy/typeshed/stdlib/compileall.pyi | 25 +- .../stdlib/concurrent/futures/__init__.pyi | 14 +- .../stdlib/concurrent/futures/_base.pyi | 83 +- .../stdlib/concurrent/futures/process.pyi | 19 +- .../stdlib/concurrent/futures/thread.pyi | 34 +- mypy/typeshed/stdlib/configparser.pyi | 193 +- mypy/typeshed/stdlib/contextlib.pyi | 89 +- mypy/typeshed/stdlib/contextvars.pyi | 18 +- mypy/typeshed/stdlib/copy.pyi | 10 +- mypy/typeshed/stdlib/copyreg.pyi | 16 +- mypy/typeshed/stdlib/crypt.pyi | 2 +- mypy/typeshed/stdlib/csv.pyi | 2 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 147 +- mypy/typeshed/stdlib/ctypes/util.pyi | 7 +- mypy/typeshed/stdlib/ctypes/wintypes.pyi | 29 +- mypy/typeshed/stdlib/curses/__init__.pyi | 4 +- mypy/typeshed/stdlib/curses/ascii.pyi | 10 +- mypy/typeshed/stdlib/dataclasses.pyi | 125 +- mypy/typeshed/stdlib/datetime.pyi | 106 +- mypy/typeshed/stdlib/dbm/__init__.pyi | 11 +- mypy/typeshed/stdlib/dbm/dumb.pyi | 14 +- mypy/typeshed/stdlib/dbm/gnu.pyi | 11 +- mypy/typeshed/stdlib/dbm/ndbm.pyi | 12 +- mypy/typeshed/stdlib/decimal.pyi | 67 +- mypy/typeshed/stdlib/difflib.pyi | 135 +- mypy/typeshed/stdlib/dis.pyi | 37 +- .../stdlib/distutils/archive_util.pyi | 20 +- .../stdlib/distutils/bcppcompiler.pyi | 3 - mypy/typeshed/stdlib/distutils/ccompiler.pyi | 199 +- mypy/typeshed/stdlib/distutils/cmd.pyi | 65 +- .../stdlib/distutils/command/build_py.pyi | 12 +- .../stdlib/distutils/command/config.pyi | 2 +- .../stdlib/distutils/command/install.pyi | 12 +- .../distutils/command/install_egg_info.pyi | 10 + .../stdlib/distutils/command/upload.pyi | 8 + mypy/typeshed/stdlib/distutils/config.pyi | 17 + mypy/typeshed/stdlib/distutils/core.pyi | 4 +- .../stdlib/distutils/cygwinccompiler.pyi | 3 - mypy/typeshed/stdlib/distutils/debug.pyi | 2 - mypy/typeshed/stdlib/distutils/dep_util.pyi | 5 +- mypy/typeshed/stdlib/distutils/dir_util.pyi | 26 +- mypy/typeshed/stdlib/distutils/dist.pyi | 56 +- mypy/typeshed/stdlib/distutils/extension.pyi | 57 +- .../stdlib/distutils/fancy_getopt.pyi | 14 +- mypy/typeshed/stdlib/distutils/file_util.pyi | 20 +- mypy/typeshed/stdlib/distutils/filelist.pyi | 2 - mypy/typeshed/stdlib/distutils/log.pyi | 29 +- .../stdlib/distutils/msvccompiler.pyi | 3 - mypy/typeshed/stdlib/distutils/spawn.pyi | 8 +- mypy/typeshed/stdlib/distutils/sysconfig.pyi | 11 +- mypy/typeshed/stdlib/distutils/text_file.pyi | 23 +- .../stdlib/distutils/unixccompiler.pyi | 3 - mypy/typeshed/stdlib/distutils/util.pyi | 23 +- mypy/typeshed/stdlib/distutils/version.pyi | 56 +- mypy/typeshed/stdlib/doctest.pyi | 128 +- mypy/typeshed/stdlib/dummy_threading.pyi | 1 - mypy/typeshed/stdlib/email/__init__.pyi | 4 +- mypy/typeshed/stdlib/email/charset.pyi | 13 +- mypy/typeshed/stdlib/email/contentmanager.pyi | 10 +- mypy/typeshed/stdlib/email/encoders.pyi | 2 - mypy/typeshed/stdlib/email/errors.pyi | 3 - mypy/typeshed/stdlib/email/feedparser.pyi | 26 +- mypy/typeshed/stdlib/email/generator.pyi | 21 +- mypy/typeshed/stdlib/email/header.pyi | 35 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 21 +- mypy/typeshed/stdlib/email/iterators.pyi | 7 +- mypy/typeshed/stdlib/email/message.pyi | 68 +- .../stdlib/email/mime/application.pyi | 30 +- mypy/typeshed/stdlib/email/mime/audio.pyi | 30 +- mypy/typeshed/stdlib/email/mime/base.pyi | 8 +- mypy/typeshed/stdlib/email/mime/image.pyi | 30 +- mypy/typeshed/stdlib/email/mime/message.pyi | 8 +- mypy/typeshed/stdlib/email/mime/multipart.pyi | 30 +- .../stdlib/email/mime/nonmultipart.pyi | 2 - mypy/typeshed/stdlib/email/mime/text.pyi | 12 +- mypy/typeshed/stdlib/email/parser.pyi | 14 +- mypy/typeshed/stdlib/email/policy.pyi | 32 +- mypy/typeshed/stdlib/email/utils.pyi | 43 +- mypy/typeshed/stdlib/encodings/__init__.pyi | 4 - mypy/typeshed/stdlib/ensurepip/__init__.pyi | 25 +- mypy/typeshed/stdlib/enum.pyi | 61 +- mypy/typeshed/stdlib/errno.pyi | 3 - mypy/typeshed/stdlib/faulthandler.pyi | 1 + mypy/typeshed/stdlib/fcntl.pyi | 43 +- mypy/typeshed/stdlib/filecmp.pyi | 46 +- mypy/typeshed/stdlib/fileinput.pyi | 12 +- mypy/typeshed/stdlib/fnmatch.pyi | 7 +- mypy/typeshed/stdlib/formatter.pyi | 4 +- mypy/typeshed/stdlib/fractions.pyi | 148 +- mypy/typeshed/stdlib/ftplib.pyi | 35 +- mypy/typeshed/stdlib/functools.pyi | 77 +- mypy/typeshed/stdlib/gc.pyi | 18 +- mypy/typeshed/stdlib/genericpath.pyi | 7 +- mypy/typeshed/stdlib/getopt.pyi | 4 - mypy/typeshed/stdlib/getpass.pyi | 6 - mypy/typeshed/stdlib/gettext.pyi | 45 +- mypy/typeshed/stdlib/glob.pyi | 15 +- mypy/typeshed/stdlib/graphlib.pyi | 16 + mypy/typeshed/stdlib/gzip.pyi | 12 +- mypy/typeshed/stdlib/hashlib.pyi | 117 +- mypy/typeshed/stdlib/heapq.pyi | 16 +- mypy/typeshed/stdlib/hmac.pyi | 27 +- mypy/typeshed/stdlib/html/parser.pyi | 9 +- mypy/typeshed/stdlib/http/client.pyi | 109 +- mypy/typeshed/stdlib/http/cookiejar.pyi | 96 +- mypy/typeshed/stdlib/http/cookies.pyi | 20 +- mypy/typeshed/stdlib/http/server.pyi | 38 +- mypy/typeshed/stdlib/imaplib.pyi | 53 +- mypy/typeshed/stdlib/imghdr.pyi | 3 +- mypy/typeshed/stdlib/imp.pyi | 50 +- mypy/typeshed/stdlib/importlib/__init__.pyi | 17 +- mypy/typeshed/stdlib/importlib/abc.pyi | 63 +- mypy/typeshed/stdlib/importlib/machinery.pyi | 73 +- mypy/typeshed/stdlib/importlib/metadata.pyi | 2 +- mypy/typeshed/stdlib/importlib/resources.pyi | 19 +- mypy/typeshed/stdlib/importlib/util.pyi | 45 +- mypy/typeshed/stdlib/inspect.pyi | 193 +- mypy/typeshed/stdlib/io.pyi | 50 +- mypy/typeshed/stdlib/ipaddress.pyi | 24 +- mypy/typeshed/stdlib/itertools.pyi | 160 +- mypy/typeshed/stdlib/json/__init__.pyi | 107 +- mypy/typeshed/stdlib/json/decoder.pyi | 35 +- mypy/typeshed/stdlib/json/encoder.pyi | 39 +- mypy/typeshed/stdlib/json/tool.pyi | 1 + mypy/typeshed/stdlib/keyword.pyi | 10 +- mypy/typeshed/stdlib/lib2to3/__init__.pyi | 1 - mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi | 12 +- .../typeshed/stdlib/lib2to3/pgen2/grammar.pyi | 2 +- .../stdlib/lib2to3/pgen2/literals.pyi | 2 - mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi | 7 +- mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi | 5 +- mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi | 2 - .../stdlib/lib2to3/pgen2/tokenize.pyi | 11 +- mypy/typeshed/stdlib/lib2to3/pygram.pyi | 3 - mypy/typeshed/stdlib/lib2to3/pytree.pyi | 25 +- mypy/typeshed/stdlib/linecache.pyi | 1 + mypy/typeshed/stdlib/locale.pyi | 24 +- mypy/typeshed/stdlib/logging/__init__.pyi | 918 +++-- mypy/typeshed/stdlib/logging/config.pyi | 26 +- mypy/typeshed/stdlib/logging/handlers.pyi | 225 +- mypy/typeshed/stdlib/lzma.pyi | 2 +- mypy/typeshed/stdlib/macpath.pyi | 18 +- mypy/typeshed/stdlib/macurl2path.pyi | 2 - mypy/typeshed/stdlib/mailbox.pyi | 115 +- mypy/typeshed/stdlib/mailcap.pyi | 7 +- mypy/typeshed/stdlib/marshal.pyi | 2 +- mypy/typeshed/stdlib/math.pyi | 50 +- mypy/typeshed/stdlib/mimetypes.pyi | 26 +- mypy/typeshed/stdlib/mmap.pyi | 21 +- mypy/typeshed/stdlib/modulefinder.pyi | 30 +- mypy/typeshed/stdlib/msilib/__init__.pyi | 139 +- mypy/typeshed/stdlib/msilib/schema.pyi | 9 +- mypy/typeshed/stdlib/msilib/sequence.pyi | 5 +- mypy/typeshed/stdlib/msilib/text.pyi | 5 +- mypy/typeshed/stdlib/msvcrt.pyi | 36 +- .../stdlib/multiprocessing/__init__.pyi | 64 +- .../stdlib/multiprocessing/connection.pyi | 24 +- .../stdlib/multiprocessing/context.pyi | 61 +- .../stdlib/multiprocessing/dummy/__init__.pyi | 22 +- .../multiprocessing/dummy/connection.pyi | 28 +- .../stdlib/multiprocessing/managers.pyi | 94 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 115 +- .../stdlib/multiprocessing/process.pyi | 1 + .../stdlib/multiprocessing/queues.pyi | 9 +- .../stdlib/multiprocessing/shared_memory.pyi | 8 +- .../stdlib/multiprocessing/sharedctypes.pyi | 43 + .../typeshed/stdlib/multiprocessing/spawn.pyi | 5 +- .../stdlib/multiprocessing/synchronize.pyi | 38 +- mypy/typeshed/stdlib/mypy_extensions.pyi | 11 +- mypy/typeshed/stdlib/netrc.pyi | 6 +- mypy/typeshed/stdlib/nis.pyi | 3 +- mypy/typeshed/stdlib/nntplib.pyi | 53 +- mypy/typeshed/stdlib/ntpath.pyi | 177 +- mypy/typeshed/stdlib/numbers.pyi | 94 +- mypy/typeshed/stdlib/opcode.pyi | 4 +- mypy/typeshed/stdlib/operator.pyi | 83 +- mypy/typeshed/stdlib/optparse.pyi | 73 +- mypy/typeshed/stdlib/os/__init__.pyi | 478 ++- mypy/typeshed/stdlib/os/path.pyi | 177 +- mypy/typeshed/stdlib/ossaudiodev.pyi | 131 + mypy/typeshed/stdlib/parser.pyi | 4 +- mypy/typeshed/stdlib/pathlib.pyi | 172 +- mypy/typeshed/stdlib/pdb.pyi | 16 +- mypy/typeshed/stdlib/pickle.pyi | 95 +- mypy/typeshed/stdlib/pickletools.pyi | 48 +- mypy/typeshed/stdlib/pipes.pyi | 4 - mypy/typeshed/stdlib/pkgutil.pyi | 32 +- mypy/typeshed/stdlib/platform.pyi | 41 +- mypy/typeshed/stdlib/plistlib.pyi | 70 +- mypy/typeshed/stdlib/poplib.pyi | 30 +- mypy/typeshed/stdlib/posix.pyi | 109 +- mypy/typeshed/stdlib/posixpath.pyi | 177 +- mypy/typeshed/stdlib/pprint.pyi | 61 +- mypy/typeshed/stdlib/profile.pyi | 9 +- mypy/typeshed/stdlib/pstats.pyi | 31 +- mypy/typeshed/stdlib/pty.pyi | 3 +- mypy/typeshed/stdlib/py_compile.pyi | 34 +- mypy/typeshed/stdlib/pyclbr.pyi | 25 +- mypy/typeshed/stdlib/pydoc.pyi | 134 +- .../distutils => pydoc_data}/__init__.pyi | 0 mypy/typeshed/stdlib/pydoc_data/topics.pyi | 3 + mypy/typeshed/stdlib/pyexpat/__init__.pyi | 21 +- .../stdlib/python2/BaseHTTPServer.pyi | 47 - .../typeshed/stdlib/python2/CGIHTTPServer.pyi | 8 - mypy/typeshed/stdlib/python2/ConfigParser.pyi | 97 - mypy/typeshed/stdlib/python2/Cookie.pyi | 40 - mypy/typeshed/stdlib/python2/HTMLParser.pyi | 31 - mypy/typeshed/stdlib/python2/Queue.pyi | 31 - .../stdlib/python2/SimpleHTTPServer.pyi | 16 - mypy/typeshed/stdlib/python2/SocketServer.pyi | 135 - mypy/typeshed/stdlib/python2/StringIO.pyi | 30 - mypy/typeshed/stdlib/python2/UserDict.pyi | 44 - mypy/typeshed/stdlib/python2/UserList.pyi | 19 - mypy/typeshed/stdlib/python2/UserString.pyi | 75 - mypy/typeshed/stdlib/python2/__builtin__.pyi | 1842 ---------- mypy/typeshed/stdlib/python2/_ast.pyi | 330 -- mypy/typeshed/stdlib/python2/_collections.pyi | 38 - mypy/typeshed/stdlib/python2/_functools.pyi | 20 - mypy/typeshed/stdlib/python2/_hotshot.pyi | 24 - mypy/typeshed/stdlib/python2/_io.pyi | 186 - mypy/typeshed/stdlib/python2/_json.pyi | 7 - mypy/typeshed/stdlib/python2/_md5.pyi | 13 - mypy/typeshed/stdlib/python2/_sha.pyi | 15 - mypy/typeshed/stdlib/python2/_sha256.pyi | 23 - mypy/typeshed/stdlib/python2/_sha512.pyi | 23 - mypy/typeshed/stdlib/python2/_socket.pyi | 283 -- mypy/typeshed/stdlib/python2/_sre.pyi | 55 - mypy/typeshed/stdlib/python2/_struct.pyi | 22 - mypy/typeshed/stdlib/python2/_symtable.pyi | 39 - .../stdlib/python2/_threading_local.pyi | 12 - mypy/typeshed/stdlib/python2/_winreg.pyi | 99 - mypy/typeshed/stdlib/python2/abc.pyi | 31 - mypy/typeshed/stdlib/python2/ast.pyi | 28 - mypy/typeshed/stdlib/python2/atexit.pyi | 5 - mypy/typeshed/stdlib/python2/cPickle.pyi | 32 - mypy/typeshed/stdlib/python2/cStringIO.pyi | 54 - mypy/typeshed/stdlib/python2/collections.pyi | 120 - mypy/typeshed/stdlib/python2/commands.pyi | 12 - mypy/typeshed/stdlib/python2/compileall.pyi | 16 - mypy/typeshed/stdlib/python2/cookielib.pyi | 112 - mypy/typeshed/stdlib/python2/copy_reg.pyi | 14 - mypy/typeshed/stdlib/python2/dircache.pyi | 10 - .../stdlib/python2/distutils/emxccompiler.pyi | 5 - mypy/typeshed/stdlib/python2/dummy_thread.pyi | 21 - .../stdlib/python2/email/MIMEText.pyi | 4 - .../stdlib/python2/email/__init__.pyi | 6 - .../stdlib/python2/email/_parseaddr.pyi | 40 - .../stdlib/python2/email/base64mime.pyi | 8 - .../typeshed/stdlib/python2/email/charset.pyi | 26 - .../stdlib/python2/email/encoders.pyi | 4 - .../stdlib/python2/email/feedparser.pyi | 18 - .../stdlib/python2/email/generator.pyi | 9 - mypy/typeshed/stdlib/python2/email/header.pyi | 11 - .../stdlib/python2/email/iterators.pyi | 5 - .../typeshed/stdlib/python2/email/message.pyi | 45 - .../stdlib/python2/email/mime/__init__.pyi | 0 .../stdlib/python2/email/mime/application.pyi | 11 - .../stdlib/python2/email/mime/audio.pyi | 5 - .../stdlib/python2/email/mime/base.pyi | 4 - .../stdlib/python2/email/mime/image.pyi | 5 - .../stdlib/python2/email/mime/message.pyi | 5 - .../stdlib/python2/email/mime/multipart.pyi | 4 - .../python2/email/mime/nonmultipart.pyi | 4 - .../stdlib/python2/email/mime/text.pyi | 4 - mypy/typeshed/stdlib/python2/email/parser.pyi | 10 - .../stdlib/python2/email/quoprimime.pyi | 18 - mypy/typeshed/stdlib/python2/email/utils.pyi | 19 - .../stdlib/python2/encodings/__init__.pyi | 8 - .../stdlib/python2/encodings/utf_8.pyi | 15 - mypy/typeshed/stdlib/python2/exceptions.pyi | 48 - mypy/typeshed/stdlib/python2/fcntl.pyi | 85 - mypy/typeshed/stdlib/python2/fnmatch.pyi | 8 - mypy/typeshed/stdlib/python2/functools.pyi | 33 - .../stdlib/python2/future_builtins.pyi | 14 - mypy/typeshed/stdlib/python2/gc.pyi | 29 - mypy/typeshed/stdlib/python2/getopt.pyi | 12 - mypy/typeshed/stdlib/python2/getpass.pyi | 8 - mypy/typeshed/stdlib/python2/gettext.pyi | 41 - mypy/typeshed/stdlib/python2/glob.pyi | 7 - mypy/typeshed/stdlib/python2/gzip.pyi | 37 - mypy/typeshed/stdlib/python2/hashlib.pyi | 31 - mypy/typeshed/stdlib/python2/heapq.pyi | 18 - .../stdlib/python2/htmlentitydefs.pyi | 5 - mypy/typeshed/stdlib/python2/httplib.pyi | 205 -- mypy/typeshed/stdlib/python2/imp.pyi | 35 - mypy/typeshed/stdlib/python2/importlib.pyi | 4 - mypy/typeshed/stdlib/python2/inspect.pyi | 129 - mypy/typeshed/stdlib/python2/io.pyi | 42 - mypy/typeshed/stdlib/python2/itertools.pyi | 167 - mypy/typeshed/stdlib/python2/json.pyi | 94 - mypy/typeshed/stdlib/python2/markupbase.pyi | 9 - mypy/typeshed/stdlib/python2/md5.pyi | 6 - mypy/typeshed/stdlib/python2/mimetools.pyi | 27 - .../python2/multiprocessing/__init__.pyi | 50 - .../multiprocessing/dummy/__init__.pyi | 51 - .../multiprocessing/dummy/connection.pyi | 26 - .../stdlib/python2/multiprocessing/pool.pyi | 54 - .../python2/multiprocessing/process.pyi | 36 - .../stdlib/python2/multiprocessing/util.pyi | 29 - mypy/typeshed/stdlib/python2/mutex.pyi | 14 - mypy/typeshed/stdlib/python2/nturl2path.pyi | 4 - mypy/typeshed/stdlib/python2/os/__init__.pyi | 357 -- mypy/typeshed/stdlib/python2/os/path.pyi | 164 - mypy/typeshed/stdlib/python2/os2emxpath.pyi | 164 - mypy/typeshed/stdlib/python2/pipes.pyi | 13 - mypy/typeshed/stdlib/python2/platform.pyi | 45 - mypy/typeshed/stdlib/python2/popen2.pyi | 28 - mypy/typeshed/stdlib/python2/posix.pyi | 198 -- mypy/typeshed/stdlib/python2/random.pyi | 77 - mypy/typeshed/stdlib/python2/re.pyi | 100 - mypy/typeshed/stdlib/python2/repr.pyi | 33 - mypy/typeshed/stdlib/python2/resource.pyi | 45 - mypy/typeshed/stdlib/python2/rfc822.pyi | 79 - mypy/typeshed/stdlib/python2/robotparser.pyi | 7 - mypy/typeshed/stdlib/python2/runpy.pyi | 17 - mypy/typeshed/stdlib/python2/sets.pyi | 61 - mypy/typeshed/stdlib/python2/sha.pyi | 11 - mypy/typeshed/stdlib/python2/shelve.pyi | 33 - mypy/typeshed/stdlib/python2/shlex.pyi | 31 - mypy/typeshed/stdlib/python2/signal.pyi | 68 - mypy/typeshed/stdlib/python2/smtplib.pyi | 86 - mypy/typeshed/stdlib/python2/spwd.pyi | 15 - .../typeshed/stdlib/python2/sre_constants.pyi | 94 - mypy/typeshed/stdlib/python2/sre_parse.pyi | 63 - mypy/typeshed/stdlib/python2/stat.pyi | 59 - mypy/typeshed/stdlib/python2/string.pyi | 75 - mypy/typeshed/stdlib/python2/stringold.pyi | 46 - mypy/typeshed/stdlib/python2/strop.pyi | 29 - mypy/typeshed/stdlib/python2/subprocess.pyi | 120 - mypy/typeshed/stdlib/python2/symbol.pyi | 91 - mypy/typeshed/stdlib/python2/sys.pyi | 136 - mypy/typeshed/stdlib/python2/tempfile.pyi | 111 - mypy/typeshed/stdlib/python2/textwrap.pyi | 61 - mypy/typeshed/stdlib/python2/thread.pyi | 28 - mypy/typeshed/stdlib/python2/toaiff.pyi | 14 - mypy/typeshed/stdlib/python2/tokenize.pyi | 136 - mypy/typeshed/stdlib/python2/types.pyi | 187 - mypy/typeshed/stdlib/python2/typing.pyi | 510 --- mypy/typeshed/stdlib/python2/unittest.pyi | 290 -- mypy/typeshed/stdlib/python2/urllib.pyi | 134 - mypy/typeshed/stdlib/python2/urllib2.pyi | 182 - mypy/typeshed/stdlib/python2/urlparse.pyi | 66 - mypy/typeshed/stdlib/python2/user.pyi | 9 - mypy/typeshed/stdlib/python2/whichdb.pyi | 5 - mypy/typeshed/stdlib/python2/xmlrpclib.pyi | 231 -- mypy/typeshed/stdlib/queue.pyi | 18 +- mypy/typeshed/stdlib/quopri.pyi | 2 - mypy/typeshed/stdlib/random.pyi | 52 +- mypy/typeshed/stdlib/re.pyi | 141 +- mypy/typeshed/stdlib/readline.pyi | 14 +- mypy/typeshed/stdlib/reprlib.pyi | 3 +- mypy/typeshed/stdlib/resource.pyi | 10 +- mypy/typeshed/stdlib/rlcompleter.pyi | 5 +- mypy/typeshed/stdlib/runpy.pyi | 27 +- mypy/typeshed/stdlib/sched.pyi | 19 +- mypy/typeshed/stdlib/secrets.pyi | 6 +- mypy/typeshed/stdlib/select.pyi | 34 +- mypy/typeshed/stdlib/selectors.pyi | 12 +- mypy/typeshed/stdlib/shelve.pyi | 11 +- mypy/typeshed/stdlib/shlex.pyi | 26 +- mypy/typeshed/stdlib/shutil.pyi | 127 +- mypy/typeshed/stdlib/signal.pyi | 23 +- mypy/typeshed/stdlib/site.pyi | 8 +- mypy/typeshed/stdlib/smtpd.pyi | 38 +- mypy/typeshed/stdlib/smtplib.pyi | 77 +- mypy/typeshed/stdlib/socket.pyi | 199 +- mypy/typeshed/stdlib/socketserver.pyi | 106 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 127 +- mypy/typeshed/stdlib/sre_compile.pyi | 21 +- mypy/typeshed/stdlib/sre_constants.pyi | 3 - mypy/typeshed/stdlib/sre_parse.pyi | 33 +- mypy/typeshed/stdlib/ssl.pyi | 162 +- mypy/typeshed/stdlib/stat.pyi | 10 +- mypy/typeshed/stdlib/statistics.pyi | 42 +- mypy/typeshed/stdlib/string.pyi | 19 +- mypy/typeshed/stdlib/stringprep.pyi | 2 - mypy/typeshed/stdlib/struct.pyi | 10 +- mypy/typeshed/stdlib/subprocess.pyi | 1318 ++++--- mypy/typeshed/stdlib/sunau.pyi | 5 +- mypy/typeshed/stdlib/symbol.pyi | 6 +- mypy/typeshed/stdlib/symtable.pyi | 2 +- mypy/typeshed/stdlib/sys.pyi | 102 +- mypy/typeshed/stdlib/sysconfig.pyi | 2 +- mypy/typeshed/stdlib/syslog.pyi | 1 - mypy/typeshed/stdlib/tarfile.pyi | 173 +- mypy/typeshed/stdlib/telnetlib.pyi | 10 +- mypy/typeshed/stdlib/tempfile.pyi | 32 +- mypy/typeshed/stdlib/termios.pyi | 6 +- mypy/typeshed/stdlib/textwrap.pyi | 139 +- mypy/typeshed/stdlib/this.pyi | 1 - mypy/typeshed/stdlib/threading.pyi | 103 +- mypy/typeshed/stdlib/time.pyi | 33 +- mypy/typeshed/stdlib/timeit.pyi | 34 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 3019 ++++++++++++++--- mypy/typeshed/stdlib/tkinter/constants.pyi | 157 +- mypy/typeshed/stdlib/tkinter/dialog.pyi | 2 +- mypy/typeshed/stdlib/tkinter/filedialog.pyi | 6 +- mypy/typeshed/stdlib/tkinter/font.pyi | 98 + mypy/typeshed/stdlib/tkinter/ttk.pyi | 895 ++++- mypy/typeshed/stdlib/token.pyi | 1 + mypy/typeshed/stdlib/tokenize.pyi | 36 +- mypy/typeshed/stdlib/trace.pyi | 30 +- mypy/typeshed/stdlib/traceback.pyi | 137 +- mypy/typeshed/stdlib/tracemalloc.pyi | 33 +- mypy/typeshed/stdlib/tty.pyi | 2 - mypy/typeshed/stdlib/turtle.pyi | 87 +- mypy/typeshed/stdlib/types.pyi | 130 +- mypy/typeshed/stdlib/typing.pyi | 333 +- mypy/typeshed/stdlib/typing_extensions.pyi | 91 +- mypy/typeshed/stdlib/unicodedata.pyi | 20 +- mypy/typeshed/stdlib/unittest/__init__.pyi | 6 +- mypy/typeshed/stdlib/unittest/async_case.pyi | 1 + mypy/typeshed/stdlib/unittest/case.pyi | 325 +- mypy/typeshed/stdlib/unittest/loader.pyi | 51 +- mypy/typeshed/stdlib/unittest/main.pyi | 42 +- mypy/typeshed/stdlib/unittest/mock.pyi | 350 +- mypy/typeshed/stdlib/unittest/result.pyi | 25 +- mypy/typeshed/stdlib/unittest/runner.pyi | 8 +- mypy/typeshed/stdlib/unittest/signals.pyi | 6 +- mypy/typeshed/stdlib/unittest/suite.pyi | 8 +- mypy/typeshed/stdlib/unittest/util.pyi | 3 +- mypy/typeshed/stdlib/urllib/error.pyi | 6 +- mypy/typeshed/stdlib/urllib/parse.pyi | 39 +- mypy/typeshed/stdlib/urllib/request.pyi | 295 +- mypy/typeshed/stdlib/urllib/response.pyi | 8 +- mypy/typeshed/stdlib/urllib/robotparser.pyi | 9 +- mypy/typeshed/stdlib/uu.pyi | 9 +- mypy/typeshed/stdlib/uuid.pyi | 41 +- mypy/typeshed/stdlib/venv/__init__.pyi | 50 +- mypy/typeshed/stdlib/warnings.pyi | 14 +- mypy/typeshed/stdlib/wave.pyi | 7 +- mypy/typeshed/stdlib/weakref.pyi | 51 +- mypy/typeshed/stdlib/webbrowser.pyi | 17 +- mypy/typeshed/stdlib/winreg.pyi | 21 +- mypy/typeshed/stdlib/winsound.pyi | 1 - mypy/typeshed/stdlib/wsgiref/handlers.pyi | 28 +- mypy/typeshed/stdlib/wsgiref/headers.pyi | 2 +- .../typeshed/stdlib/wsgiref/simple_server.pyi | 11 +- mypy/typeshed/stdlib/wsgiref/validate.pyi | 5 +- mypy/typeshed/stdlib/xdrlib.pyi | 3 +- mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi | 1 - mypy/typeshed/stdlib/xml/dom/__init__.pyi | 9 +- mypy/typeshed/stdlib/xml/dom/domreg.pyi | 10 + mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi | 3 + mypy/typeshed/stdlib/xml/dom/minicompat.pyi | 3 + mypy/typeshed/stdlib/xml/dom/minidom.pyi | 5 +- mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi | 3 + .../stdlib/xml/etree/ElementInclude.pyi | 10 +- .../typeshed/stdlib/xml/etree/ElementPath.pyi | 10 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 136 +- .../stdlib/xml/etree/cElementTree.pyi | 2 - mypy/typeshed/stdlib/xml/sax/__init__.pyi | 21 +- mypy/typeshed/stdlib/xml/sax/saxutils.pyi | 23 +- mypy/typeshed/stdlib/xml/sax/xmlreader.pyi | 3 +- mypy/typeshed/stdlib/xmlrpc/client.pyi | 103 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 87 +- mypy/typeshed/stdlib/xxlimited.pyi | 13 + mypy/typeshed/stdlib/zipapp.pyi | 20 +- mypy/typeshed/stdlib/zipfile.pyi | 57 +- mypy/typeshed/stdlib/zipimport.pyi | 9 +- mypy/typeshed/stdlib/zlib.pyi | 22 +- mypy/typeshed/stdlib/zoneinfo/__init__.pyi | 21 +- 555 files changed, 15079 insertions(+), 19833 deletions(-) create mode 100644 mypy/typeshed/stdlib/_tkinter.pyi create mode 100644 mypy/typeshed/stdlib/_typeshed/xml.pyi create mode 100644 mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi create mode 100644 mypy/typeshed/stdlib/distutils/command/upload.pyi create mode 100644 mypy/typeshed/stdlib/distutils/config.pyi create mode 100644 mypy/typeshed/stdlib/graphlib.pyi create mode 100644 mypy/typeshed/stdlib/json/tool.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi create mode 100644 mypy/typeshed/stdlib/ossaudiodev.pyi rename mypy/typeshed/stdlib/{python2/distutils => pydoc_data}/__init__.pyi (100%) create mode 100644 mypy/typeshed/stdlib/pydoc_data/topics.pyi delete mode 100644 mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi delete mode 100644 mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi delete mode 100644 mypy/typeshed/stdlib/python2/ConfigParser.pyi delete mode 100644 mypy/typeshed/stdlib/python2/Cookie.pyi delete mode 100644 mypy/typeshed/stdlib/python2/HTMLParser.pyi delete mode 100644 mypy/typeshed/stdlib/python2/Queue.pyi delete mode 100644 mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi delete mode 100644 mypy/typeshed/stdlib/python2/SocketServer.pyi delete mode 100644 mypy/typeshed/stdlib/python2/StringIO.pyi delete mode 100644 mypy/typeshed/stdlib/python2/UserDict.pyi delete mode 100644 mypy/typeshed/stdlib/python2/UserList.pyi delete mode 100644 mypy/typeshed/stdlib/python2/UserString.pyi delete mode 100644 mypy/typeshed/stdlib/python2/__builtin__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_ast.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_collections.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_functools.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_hotshot.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_io.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_json.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_md5.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_sha.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_sha256.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_sha512.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_socket.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_sre.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_struct.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_symtable.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_threading_local.pyi delete mode 100644 mypy/typeshed/stdlib/python2/_winreg.pyi delete mode 100644 mypy/typeshed/stdlib/python2/abc.pyi delete mode 100644 mypy/typeshed/stdlib/python2/ast.pyi delete mode 100644 mypy/typeshed/stdlib/python2/atexit.pyi delete mode 100644 mypy/typeshed/stdlib/python2/cPickle.pyi delete mode 100644 mypy/typeshed/stdlib/python2/cStringIO.pyi delete mode 100644 mypy/typeshed/stdlib/python2/collections.pyi delete mode 100644 mypy/typeshed/stdlib/python2/commands.pyi delete mode 100644 mypy/typeshed/stdlib/python2/compileall.pyi delete mode 100644 mypy/typeshed/stdlib/python2/cookielib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/copy_reg.pyi delete mode 100644 mypy/typeshed/stdlib/python2/dircache.pyi delete mode 100644 mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi delete mode 100644 mypy/typeshed/stdlib/python2/dummy_thread.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/MIMEText.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/_parseaddr.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/base64mime.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/charset.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/encoders.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/feedparser.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/generator.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/header.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/iterators.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/message.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/application.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/audio.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/base.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/image.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/message.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/multipart.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/mime/text.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/parser.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/quoprimime.pyi delete mode 100644 mypy/typeshed/stdlib/python2/email/utils.pyi delete mode 100644 mypy/typeshed/stdlib/python2/encodings/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/encodings/utf_8.pyi delete mode 100644 mypy/typeshed/stdlib/python2/exceptions.pyi delete mode 100644 mypy/typeshed/stdlib/python2/fcntl.pyi delete mode 100644 mypy/typeshed/stdlib/python2/fnmatch.pyi delete mode 100644 mypy/typeshed/stdlib/python2/functools.pyi delete mode 100644 mypy/typeshed/stdlib/python2/future_builtins.pyi delete mode 100644 mypy/typeshed/stdlib/python2/gc.pyi delete mode 100644 mypy/typeshed/stdlib/python2/getopt.pyi delete mode 100644 mypy/typeshed/stdlib/python2/getpass.pyi delete mode 100644 mypy/typeshed/stdlib/python2/gettext.pyi delete mode 100644 mypy/typeshed/stdlib/python2/glob.pyi delete mode 100644 mypy/typeshed/stdlib/python2/gzip.pyi delete mode 100644 mypy/typeshed/stdlib/python2/hashlib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/heapq.pyi delete mode 100644 mypy/typeshed/stdlib/python2/htmlentitydefs.pyi delete mode 100644 mypy/typeshed/stdlib/python2/httplib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/imp.pyi delete mode 100644 mypy/typeshed/stdlib/python2/importlib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/inspect.pyi delete mode 100644 mypy/typeshed/stdlib/python2/io.pyi delete mode 100644 mypy/typeshed/stdlib/python2/itertools.pyi delete mode 100644 mypy/typeshed/stdlib/python2/json.pyi delete mode 100644 mypy/typeshed/stdlib/python2/markupbase.pyi delete mode 100644 mypy/typeshed/stdlib/python2/md5.pyi delete mode 100644 mypy/typeshed/stdlib/python2/mimetools.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/process.pyi delete mode 100644 mypy/typeshed/stdlib/python2/multiprocessing/util.pyi delete mode 100644 mypy/typeshed/stdlib/python2/mutex.pyi delete mode 100644 mypy/typeshed/stdlib/python2/nturl2path.pyi delete mode 100644 mypy/typeshed/stdlib/python2/os/__init__.pyi delete mode 100644 mypy/typeshed/stdlib/python2/os/path.pyi delete mode 100644 mypy/typeshed/stdlib/python2/os2emxpath.pyi delete mode 100644 mypy/typeshed/stdlib/python2/pipes.pyi delete mode 100644 mypy/typeshed/stdlib/python2/platform.pyi delete mode 100644 mypy/typeshed/stdlib/python2/popen2.pyi delete mode 100644 mypy/typeshed/stdlib/python2/posix.pyi delete mode 100644 mypy/typeshed/stdlib/python2/random.pyi delete mode 100644 mypy/typeshed/stdlib/python2/re.pyi delete mode 100644 mypy/typeshed/stdlib/python2/repr.pyi delete mode 100644 mypy/typeshed/stdlib/python2/resource.pyi delete mode 100644 mypy/typeshed/stdlib/python2/rfc822.pyi delete mode 100644 mypy/typeshed/stdlib/python2/robotparser.pyi delete mode 100644 mypy/typeshed/stdlib/python2/runpy.pyi delete mode 100644 mypy/typeshed/stdlib/python2/sets.pyi delete mode 100644 mypy/typeshed/stdlib/python2/sha.pyi delete mode 100644 mypy/typeshed/stdlib/python2/shelve.pyi delete mode 100644 mypy/typeshed/stdlib/python2/shlex.pyi delete mode 100644 mypy/typeshed/stdlib/python2/signal.pyi delete mode 100644 mypy/typeshed/stdlib/python2/smtplib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/spwd.pyi delete mode 100644 mypy/typeshed/stdlib/python2/sre_constants.pyi delete mode 100644 mypy/typeshed/stdlib/python2/sre_parse.pyi delete mode 100644 mypy/typeshed/stdlib/python2/stat.pyi delete mode 100644 mypy/typeshed/stdlib/python2/string.pyi delete mode 100644 mypy/typeshed/stdlib/python2/stringold.pyi delete mode 100644 mypy/typeshed/stdlib/python2/strop.pyi delete mode 100644 mypy/typeshed/stdlib/python2/subprocess.pyi delete mode 100644 mypy/typeshed/stdlib/python2/symbol.pyi delete mode 100644 mypy/typeshed/stdlib/python2/sys.pyi delete mode 100644 mypy/typeshed/stdlib/python2/tempfile.pyi delete mode 100644 mypy/typeshed/stdlib/python2/textwrap.pyi delete mode 100644 mypy/typeshed/stdlib/python2/thread.pyi delete mode 100644 mypy/typeshed/stdlib/python2/toaiff.pyi delete mode 100644 mypy/typeshed/stdlib/python2/tokenize.pyi delete mode 100644 mypy/typeshed/stdlib/python2/types.pyi delete mode 100644 mypy/typeshed/stdlib/python2/typing.pyi delete mode 100644 mypy/typeshed/stdlib/python2/unittest.pyi delete mode 100644 mypy/typeshed/stdlib/python2/urllib.pyi delete mode 100644 mypy/typeshed/stdlib/python2/urllib2.pyi delete mode 100644 mypy/typeshed/stdlib/python2/urlparse.pyi delete mode 100644 mypy/typeshed/stdlib/python2/user.pyi delete mode 100644 mypy/typeshed/stdlib/python2/whichdb.pyi delete mode 100644 mypy/typeshed/stdlib/python2/xmlrpclib.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/font.pyi create mode 100644 mypy/typeshed/stdlib/xml/dom/domreg.pyi create mode 100644 mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi create mode 100644 mypy/typeshed/stdlib/xml/dom/minicompat.pyi create mode 100644 mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi create mode 100644 mypy/typeshed/stdlib/xxlimited.pyi diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index dc749563a526..c3a08455b5f6 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -1,54 +1,55 @@ __future__: 2.7 -_ast: 3.5 +_ast: 3.6 _bisect: 2.7 -_bootlocale: 3.5 +_bootlocale: 3.6 _codecs: 2.7 -_compat_pickle: 3.5 -_compression: 3.5 +_compat_pickle: 3.6 +_compression: 3.6 _csv: 2.7 _curses: 2.7 -_decimal: 3.5 -_dummy_thread: 3.5 +_decimal: 3.6 +_dummy_thread: 3.6 _dummy_threading: 2.7 _heapq: 2.7 -_imp: 3.5 -_importlib_modulespec: 3.5 -_json: 3.5 -_markupbase: 3.5 +_imp: 3.6 +_importlib_modulespec: 3.6 +_json: 3.6 +_markupbase: 3.6 _msi: 2.7 -_operator: 3.5 -_osx_support: 3.5 -_posixsubprocess: 3.5 +_operator: 3.6 +_osx_support: 3.6 +_posixsubprocess: 3.6 _py_abc: 3.7 -_pydecimal: 3.5 +_pydecimal: 3.6 _random: 2.7 -_sitebuiltins: 3.5 -_stat: 3.5 -_thread: 3.5 -_threading_local: 3.5 -_tracemalloc: 3.5 +_sitebuiltins: 3.6 +_stat: 3.6 +_thread: 3.6 +_threading_local: 3.6 +_tkinter: 3.6 +_tracemalloc: 3.6 _typeshed: 2.7 _warnings: 2.7 _weakref: 2.7 _weakrefset: 2.7 -_winapi: 3.5 -abc: 3.5 +_winapi: 3.6 +abc: 3.6 aifc: 2.7 antigravity: 2.7 argparse: 2.7 array: 2.7 -ast: 3.5 +ast: 3.6 asynchat: 2.7 -asyncio: 3.5 +asyncio: 3.6 asyncore: 2.7 -atexit: 3.5 +atexit: 3.6 audioop: 2.7 base64: 2.7 bdb: 2.7 binascii: 2.7 binhex: 2.7 bisect: 2.7 -builtins: 2.7 +builtins: 3.6 bz2: 2.7 cProfile: 2.7 calendar: 2.7 @@ -60,72 +61,73 @@ cmd: 2.7 code: 2.7 codecs: 2.7 codeop: 2.7 -collections: 3.5 +collections: 3.6 colorsys: 2.7 -compileall: 3.5 -concurrent: 3.5 -configparser: 3.5 +compileall: 3.6 +concurrent: 3.6 +configparser: 3.6 contextlib: 2.7 contextvars: 3.7 copy: 2.7 -copyreg: 3.5 +copyreg: 3.6 crypt: 2.7 csv: 2.7 ctypes: 2.7 curses: 2.7 dataclasses: 3.7 datetime: 2.7 -dbm: 3.5 +dbm: 3.6 decimal: 2.7 difflib: 2.7 dis: 2.7 -distutils: 2.7 +distutils: 3.6 doctest: 2.7 dummy_threading: 2.7 -email: 3.5 -encodings: 3.5 +email: 3.6 +encodings: 3.6 ensurepip: 2.7 -enum: 3.5 +enum: 3.6 errno: 2.7 -faulthandler: 3.5 -fcntl: 3.5 +faulthandler: 3.6 +fcntl: 3.6 filecmp: 2.7 fileinput: 2.7 -fnmatch: 3.5 +fnmatch: 3.6 formatter: 2.7 fractions: 2.7 ftplib: 2.7 -functools: 3.5 -gc: 3.5 +functools: 3.6 +gc: 3.6 genericpath: 2.7 -getopt: 3.5 -getpass: 3.5 -gettext: 3.5 -glob: 3.5 +getopt: 3.6 +getpass: 3.6 +gettext: 3.6 +glob: 3.6 +graphlib: 3.9 grp: 2.7 -gzip: 3.5 -hashlib: 3.5 -heapq: 3.5 +gzip: 3.6 +hashlib: 3.6 +heapq: 3.6 hmac: 2.7 -html: 3.5 -http: 3.5 +html: 3.6 +http: 3.6 imaplib: 2.7 imghdr: 2.7 -imp: 3.5 -importlib: 3.5 -inspect: 3.5 -io: 3.5 -ipaddress: 3.5 -itertools: 3.5 -json: 3.5 +imp: 3.6 +importlib: 3.6 +inspect: 3.6 +io: 3.6 +ipaddress: 3.6 +itertools: 3.6 +json: 3.6 keyword: 2.7 lib2to3: 2.7 linecache: 2.7 locale: 2.7 logging: 2.7 -lzma: 3.5 +lzma: 3.6 macpath: 2.7 -macurl2path: 3.5 +macurl2path: 3.6 mailbox: 2.7 mailcap: 2.7 marshal: 2.7 @@ -135,29 +137,30 @@ mmap: 2.7 modulefinder: 2.7 msilib: 2.7 msvcrt: 2.7 -multiprocessing: 3.5 +multiprocessing: 3.6 netrc: 2.7 nis: 2.7 -nntplib: 3.5 -ntpath: 2.7 -nturl2path: 3.5 +nntplib: 3.6 +ntpath: 3.6 +nturl2path: 3.6 numbers: 2.7 opcode: 2.7 operator: 2.7 optparse: 2.7 -os: 3.5 +os: 3.6 +ossaudiodev: 3.6 parser: 2.7 -pathlib: 3.5 +pathlib: 3.6 pdb: 2.7 pickle: 2.7 pickletools: 2.7 -pipes: 3.5 +pipes: 3.6 pkgutil: 2.7 -platform: 3.5 +platform: 3.6 plistlib: 2.7 poplib: 2.7 -posix: 3.5 -posixpath: 2.7 +posix: 3.6 +posixpath: 3.6 pprint: 2.7 profile: 2.7 pstats: 2.7 @@ -166,85 +169,87 @@ pwd: 2.7 py_compile: 2.7 pyclbr: 2.7 pydoc: 2.7 +pydoc_data: 2.7 pyexpat: 2.7 -queue: 3.5 +queue: 3.6 quopri: 2.7 -random: 3.5 -re: 3.5 +random: 3.6 +re: 3.6 readline: 2.7 -reprlib: 3.5 -resource: 3.5 +reprlib: 3.6 +resource: 3.6 rlcompleter: 2.7 -runpy: 3.5 +runpy: 3.6 sched: 2.7 secrets: 3.6 select: 2.7 -selectors: 3.5 -shelve: 3.5 -shlex: 3.5 +selectors: 3.6 +shelve: 3.6 +shlex: 3.6 shutil: 2.7 -signal: 3.5 +signal: 3.6 site: 2.7 smtpd: 2.7 -smtplib: 3.5 +smtplib: 3.6 sndhdr: 2.7 socket: 2.7 -socketserver: 3.5 -spwd: 3.5 +socketserver: 3.6 +spwd: 3.6 sqlite3: 2.7 sre_compile: 2.7 -sre_constants: 3.5 -sre_parse: 3.5 +sre_constants: 3.6 +sre_parse: 3.6 ssl: 2.7 -stat: 3.5 -statistics: 3.5 -string: 3.5 +stat: 3.6 +statistics: 3.6 +string: 3.6 stringprep: 2.7 struct: 2.7 -subprocess: 3.5 +subprocess: 3.6 sunau: 2.7 -symbol: 3.5 +symbol: 3.6 symtable: 2.7 -sys: 3.5 +sys: 3.6 sysconfig: 2.7 syslog: 2.7 tabnanny: 2.7 tarfile: 2.7 telnetlib: 2.7 -tempfile: 3.5 +tempfile: 3.6 termios: 2.7 -textwrap: 3.5 +textwrap: 3.6 this: 2.7 threading: 2.7 time: 2.7 timeit: 2.7 -tkinter: 3.5 +tkinter: 3.6 token: 2.7 -tokenize: 3.5 +tokenize: 3.6 trace: 2.7 traceback: 2.7 -tracemalloc: 3.5 +tracemalloc: 3.6 tty: 2.7 turtle: 2.7 -types: 3.5 -typing: 3.5 +types: 3.6 +typing: 3.6 unicodedata: 2.7 -unittest: 3.5 -urllib: 3.5 +unittest: 3.6 +urllib: 3.6 uu: 2.7 uuid: 2.7 -venv: 3.5 +venv: 3.6 warnings: 2.7 wave: 2.7 weakref: 2.7 webbrowser: 2.7 -winreg: 3.5 +winreg: 3.6 winsound: 2.7 wsgiref: 2.7 xdrlib: 2.7 xml: 2.7 -xmlrpc: 3.5 -zipapp: 3.5 +xmlrpc: 3.6 +xxlimited: 3.6 +zipapp: 3.6 zipfile: 2.7 zipimport: 2.7 zlib: 2.7 diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 888b3876c8b4..1555652902ed 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,6 +1,6 @@ import sys import typing -from typing import Any, Optional, ClassVar +from typing import Any, ClassVar, Optional PyCF_ONLY_AST: int if sys.version_info >= (3, 8): @@ -21,22 +21,17 @@ class AST: end_col_offset: Optional[int] type_comment: Optional[str] -class mod(AST): - ... +class mod(AST): ... if sys.version_info >= (3, 8): class type_ignore(AST): ... - class TypeIgnore(type_ignore): ... - class FunctionType(mod): argtypes: typing.List[expr] returns: expr class Module(mod): body: typing.List[stmt] - if sys.version_info >= (3, 7): - docstring: Optional[str] if sys.version_info >= (3, 8): type_ignores: typing.List[TypeIgnore] @@ -46,7 +41,6 @@ class Interactive(mod): class Expression(mod): body: expr - class stmt(AST): ... class FunctionDef(stmt): @@ -55,8 +49,6 @@ class FunctionDef(stmt): body: typing.List[stmt] decorator_list: typing.List[expr] returns: Optional[expr] - if sys.version_info >= (3, 7): - docstring: Optional[str] class AsyncFunctionDef(stmt): name: _identifier @@ -64,8 +56,6 @@ class AsyncFunctionDef(stmt): body: typing.List[stmt] decorator_list: typing.List[expr] returns: Optional[expr] - if sys.version_info >= (3, 7): - docstring: Optional[str] class ClassDef(stmt): name: _identifier @@ -73,8 +63,6 @@ class ClassDef(stmt): keywords: typing.List[keyword] body: typing.List[stmt] decorator_list: typing.List[expr] - if sys.version_info >= (3, 7): - docstring: Optional[str] class Return(stmt): value: Optional[expr] @@ -91,12 +79,11 @@ class AugAssign(stmt): op: operator value: expr -if sys.version_info >= (3, 6): - class AnnAssign(stmt): - target: expr - annotation: expr - value: Optional[expr] - simple: int +class AnnAssign(stmt): + target: expr + annotation: expr + value: Optional[expr] + simple: int class For(stmt): target: expr @@ -162,7 +149,6 @@ class Expr(stmt): class Pass(stmt): ... class Break(stmt): ... class Continue(stmt): ... - class expr(AST): ... class BoolOp(expr): @@ -230,37 +216,31 @@ class Call(expr): args: typing.List[expr] keywords: typing.List[keyword] -if sys.version_info >= (3, 6): - class FormattedValue(expr): - value: expr - conversion: Optional[int] - format_spec: Optional[expr] +class FormattedValue(expr): + value: expr + conversion: Optional[int] + format_spec: Optional[expr] - class JoinedStr(expr): - values: typing.List[expr] +class JoinedStr(expr): + values: typing.List[expr] if sys.version_info < (3, 8): class Num(expr): # Deprecated in 3.8; use Constant n: complex - class Str(expr): # Deprecated in 3.8; use Constant s: str - class Bytes(expr): # Deprecated in 3.8; use Constant s: bytes - class NameConstant(expr): # Deprecated in 3.8; use Constant value: Any - class Ellipsis(expr): ... # Deprecated in 3.8; use Constant -if sys.version_info >= (3, 6): - class Constant(expr): - value: Any # None, str, bytes, bool, int, float, complex, Ellipsis - kind: Optional[str] - # Aliases for value, for backwards compatibility - s: Any - n: complex +class Constant(expr): + value: Any # None, str, bytes, bool, int, float, complex, Ellipsis + kind: Optional[str] + # Aliases for value, for backwards compatibility + s: Any + n: complex if sys.version_info >= (3, 8): class NamedExpr(expr): @@ -275,8 +255,7 @@ class Attribute(expr): if sys.version_info >= (3, 9): _SliceT = expr else: - class slice(AST): - ... + class slice(AST): ... _SliceT = slice class Slice(_SliceT): @@ -287,7 +266,6 @@ class Slice(_SliceT): if sys.version_info < (3, 9): class ExtSlice(slice): dims: typing.List[slice] - class Index(slice): value: expr @@ -312,9 +290,7 @@ class Tuple(expr): elts: typing.List[expr] ctx: expr_context - -class expr_context(AST): - ... +class expr_context(AST): ... if sys.version_info < (3, 9): class AugLoad(expr_context): ... @@ -326,17 +302,10 @@ if sys.version_info < (3, 9): class Del(expr_context): ... class Load(expr_context): ... class Store(expr_context): ... - - -class boolop(AST): - ... - +class boolop(AST): ... class And(boolop): ... class Or(boolop): ... - -class operator(AST): - ... - +class operator(AST): ... class Add(operator): ... class BitAnd(operator): ... class BitOr(operator): ... @@ -350,18 +319,12 @@ class MatMult(operator): ... class Pow(operator): ... class RShift(operator): ... class Sub(operator): ... - -class unaryop(AST): - ... - +class unaryop(AST): ... class Invert(unaryop): ... class Not(unaryop): ... class UAdd(unaryop): ... class USub(unaryop): ... - -class cmpop(AST): - ... - +class cmpop(AST): ... class Eq(cmpop): ... class Gt(cmpop): ... class GtE(cmpop): ... @@ -373,31 +336,26 @@ class LtE(cmpop): ... class NotEq(cmpop): ... class NotIn(cmpop): ... - class comprehension(AST): target: expr iter: expr ifs: typing.List[expr] - if sys.version_info >= (3, 6): - is_async: int - + is_async: int -class excepthandler(AST): - ... +class excepthandler(AST): ... class ExceptHandler(excepthandler): type: Optional[expr] name: Optional[_identifier] body: typing.List[stmt] - class arguments(AST): if sys.version_info >= (3, 8): posonlyargs: typing.List[arg] args: typing.List[arg] vararg: Optional[arg] kwonlyargs: typing.List[arg] - kw_defaults: typing.List[expr] + kw_defaults: typing.List[Optional[expr]] kwarg: Optional[arg] defaults: typing.List[expr] diff --git a/mypy/typeshed/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi index 43ee44bba586..1e909c2a77d3 100644 --- a/mypy/typeshed/stdlib/_bisect.pyi +++ b/mypy/typeshed/stdlib/_bisect.pyi @@ -1,8 +1,7 @@ -"""Stub file for the '_bisect' module.""" +from typing import MutableSequence, Optional, Sequence, TypeVar -from typing import Optional, Sequence, MutableSequence, TypeVar +_T = TypeVar("_T") -_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: ... diff --git a/mypy/typeshed/stdlib/_bootlocale.pyi b/mypy/typeshed/stdlib/_bootlocale.pyi index a29c066eba2c..ee2d89347a9f 100644 --- a/mypy/typeshed/stdlib/_bootlocale.pyi +++ b/mypy/typeshed/stdlib/_bootlocale.pyi @@ -1,2 +1 @@ - def getpreferredencoding(do_setlocale: bool = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index d933d0917439..2316cdbbc756 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,9 +1,6 @@ -"""Stub file for the '_codecs' module.""" - -import sys -from typing import Any, Callable, Tuple, Optional, Dict, Text, Union - import codecs +import sys +from typing import Any, Callable, Dict, Optional, Text, Tuple, Union # For convenience: _Handler = Callable[[Exception], Tuple[Text, int]] @@ -19,6 +16,7 @@ else: # 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: ... @@ -28,11 +26,12 @@ 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]: ... @@ -44,21 +43,27 @@ def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tup 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]: ... + 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 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_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_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]: ... @@ -66,7 +71,7 @@ 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': +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): diff --git a/mypy/typeshed/stdlib/_compat_pickle.pyi b/mypy/typeshed/stdlib/_compat_pickle.pyi index 688e0ad04ade..5be4c9b9d829 100644 --- a/mypy/typeshed/stdlib/_compat_pickle.pyi +++ b/mypy/typeshed/stdlib/_compat_pickle.pyi @@ -1,6 +1,4 @@ - from typing import Dict, Tuple -import sys IMPORT_MAPPING: Dict[str, str] NAME_MAPPING: Dict[Tuple[str, str], Tuple[str, str]] @@ -9,6 +7,4 @@ MULTIPROCESSING_EXCEPTIONS: Tuple[str, ...] REVERSE_IMPORT_MAPPING: Dict[str, str] REVERSE_NAME_MAPPING: Dict[Tuple[str, str], Tuple[str, str]] PYTHON3_OSERROR_EXCEPTIONS: Tuple[str, ...] - -if sys.version_info >= (3, 6): - PYTHON3_IMPORTERROR_EXCEPTIONS: Tuple[str, ...] +PYTHON3_IMPORTERROR_EXCEPTIONS: Tuple[str, ...] diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index 99d08212b8be..ac44d6d6505d 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -1,16 +1,23 @@ -from typing import Any -import io +from _typeshed import WriteableBuffer +from io import BufferedIOBase, RawIOBase +from typing import Any, Callable, Tuple, Type, Union BUFFER_SIZE: Any -class BaseStream(io.BufferedIOBase): ... +class BaseStream(BufferedIOBase): ... -class DecompressReader(io.RawIOBase): - def readable(self): ... - def __init__(self, fp, decomp_factory, trailing_error=..., **decomp_args): ... - def close(self): ... - def seekable(self): ... - def readinto(self, b): ... +class DecompressReader(RawIOBase): + def __init__( + self, + fp: RawIOBase, + decomp_factory: Callable[..., object], + trailing_error: Union[Type[Exception], Tuple[Type[Exception], ...]] = ..., + **decomp_args: Any, + ) -> None: ... + def readable(self) -> bool: ... + def close(self) -> None: ... + def seekable(self) -> bool: ... + def readinto(self, b: WriteableBuffer) -> int: ... def read(self, size: int = ...) -> bytes: ... - def seek(self, offset, whence=...): ... - def tell(self): ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 4f722891b69f..2b4b1a743865 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 QUOTE_ALL: int @@ -40,9 +39,9 @@ class _writer: 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: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 8c6d986cc459..5e447a249bf8 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, BinaryIO, IO, NamedTuple, Optional, Tuple, Union, overload +from typing import IO, Any, BinaryIO, NamedTuple, Optional, Tuple, Union, overload _chtype = Union[str, bytes, int] @@ -283,15 +283,30 @@ 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 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: ... + if sys.version_info >= (3, 3): 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 use_default_colors() -> None: ... def use_env(__flag: bool) -> None: ... @@ -317,7 +332,17 @@ class _CursesWindow: 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: ... + 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 @@ -415,11 +440,15 @@ class _CursesWindow: @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: ... + 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 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: ... diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index e38f3cf07653..e58805855b13 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -1,2 +1 @@ - from decimal import * diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index ae8997251322..625ec7b5c4f6 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,20 +1,17 @@ - -from typing import ( - Any, Callable, Iterable, List, Mapping, Optional, Text, Tuple, Type, Union, - TypeVar, -) -from types import FrameType, TracebackType import sys +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') +_T = TypeVar("_T") __all__: List[str] def active_count() -> int: ... + if sys.version_info < (3,): def activeCount() -> int: ... @@ -41,30 +38,35 @@ if sys.version_info >= (3,): 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 if sys.version_info >= (3,): - def __init__(self, group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[str] = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] = ..., - *, daemon: Optional[bool] = ...) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + *, + daemon: Optional[bool] = ..., + ) -> None: ... else: - def __init__(self, group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[Text] = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] = ...) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[Text, Any] = ..., + ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: Optional[float] = ...) -> None: ... @@ -79,16 +81,14 @@ class Thread: 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 __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: @@ -96,29 +96,26 @@ class Lock: 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 __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 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 __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: @@ -126,19 +123,17 @@ class Condition: 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: ... - class Semaphore: def __init__(self, value: int = ...) -> None: ... def __enter__(self) -> bool: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + 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: @@ -150,7 +145,6 @@ class Semaphore: class BoundedSemaphore(Semaphore): ... - class Event: def __init__(self) -> None: ... def is_set(self) -> bool: ... @@ -161,30 +155,33 @@ class Event: def wait(self, timeout: Optional[float] = ...) -> bool: ... if sys.version_info >= (3, 8): - from _thread import _ExceptHookArgs as ExceptHookArgs, ExceptHookArgs as _ExceptHookArgs # don't ask - excepthook: Callable[[_ExceptHookArgs], Any] + from _thread import _excepthook, _ExceptHookArgs + + excepthook = _excepthook + 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: ... + 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: Iterable[Any] = ..., kwargs: 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 __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 24e7003978ec..673c03e80047 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -1,7 +1,5 @@ -"""Stub file for the '_heapq' module.""" - -from typing import TypeVar, List, Iterable, Any, Callable, Optional import sys +from typing import Any, Callable, Iterable, List, Optional, TypeVar _T = TypeVar("_T") @@ -10,6 +8,7 @@ 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/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi index 9e4bc0bfa03f..bfc4d42cd065 100644 --- a/mypy/typeshed/stdlib/_imp.pyi +++ b/mypy/typeshed/stdlib/_imp.pyi @@ -1,12 +1,9 @@ -# Stubs for _imp (Python 3.6) - import types +from importlib.machinery import ModuleSpec from typing import Any, List -from importlib.machinery import ModuleSpec def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> None: ... - def acquire_lock() -> None: ... def exec_builtin(__mod: types.ModuleType) -> int: ... def exec_dynamic(__mod: types.ModuleType) -> int: ... diff --git a/mypy/typeshed/stdlib/_importlib_modulespec.pyi b/mypy/typeshed/stdlib/_importlib_modulespec.pyi index 026dab8d01a3..114b78e1061d 100644 --- a/mypy/typeshed/stdlib/_importlib_modulespec.pyi +++ b/mypy/typeshed/stdlib/_importlib_modulespec.pyi @@ -14,9 +14,15 @@ class _Loader(Protocol): def load_module(self, fullname: str) -> ModuleType: ... class ModuleSpec: - def __init__(self, name: str, loader: Optional[Loader], *, - origin: Optional[str] = ..., loader_state: Any = ..., - is_package: Optional[bool] = ...) -> None: ... + def __init__( + self, + name: str, + loader: Optional[Loader], + *, + origin: Optional[str] = ..., + loader_state: Any = ..., + is_package: Optional[bool] = ..., + ) -> None: ... name: str loader: Optional[_Loader] origin: Optional[str] diff --git a/mypy/typeshed/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi index 9f7c80176595..af2b024af5af 100644 --- a/mypy/typeshed/stdlib/_json.pyi +++ b/mypy/typeshed/stdlib/_json.pyi @@ -1,6 +1,4 @@ -"""Stub file for the '_json' module.""" - -from typing import Any, Tuple, Optional, Dict, Callable +from typing import Any, Callable, Dict, Optional, Tuple class make_encoder: sort_keys: Any @@ -11,9 +9,18 @@ class make_encoder: default: Any encoder: Any item_separator: Any - def __init__(self, markers: Optional[Dict[int, Any]], default: Callable[[Any], Any], encoder: Callable[[str], str], - indent: Optional[int], key_separator: str, item_separator: str, sort_keys: bool, skipkeys: bool, - allow_nan: bool) -> None: ... + def __init__( + self, + markers: Optional[Dict[int, Any]], + default: Callable[[Any], Any], + encoder: Callable[[str], str], + indent: Optional[int], + key_separator: str, + item_separator: str, + sort_keys: bool, + skipkeys: bool, + allow_nan: bool, + ) -> None: ... def __call__(self, obj: object, _current_indent_level: int) -> Any: ... class make_scanner: diff --git a/mypy/typeshed/stdlib/_markupbase.pyi b/mypy/typeshed/stdlib/_markupbase.pyi index 09f69c7420b4..d8bc79f34e8c 100644 --- a/mypy/typeshed/stdlib/_markupbase.pyi +++ b/mypy/typeshed/stdlib/_markupbase.pyi @@ -5,5 +5,4 @@ class ParserBase: 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/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi index 092edf9932bc..a8f9c60bbadd 100644 --- a/mypy/typeshed/stdlib/_msi.pyi +++ b/mypy/typeshed/stdlib/_msi.pyi @@ -1,49 +1,38 @@ - import sys from typing import List, Optional, Union -if sys.platform == 'win32': +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: ... @@ -51,11 +40,9 @@ if sys.platform == 'win32': 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: ... diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index b37475472f50..bea438861886 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,63 +1,60 @@ -# Stubs for _operator (Python 3.5) - -from typing import AnyStr - # In reality the import is the other way around, but this way we can keep the operator stub in 2and3 from operator import ( - truth as truth, + abs as abs, + add as add, + and_ as and_, + attrgetter as attrgetter, + concat as concat, contains as contains, - indexOf as indexOf, countOf as countOf, - is_ as is_, - is_not as is_not, - index as index, - add as add, - sub as sub, - mul as mul, + delitem as delitem, + eq as eq, floordiv as floordiv, - truediv as truediv, - mod as mod, - neg as neg, - pos as pos, - abs as abs, - inv as inv, - invert as invert, - length_hint as length_hint, - lshift as lshift, - rshift as rshift, - not_ as not_, - and_ as and_, - xor as xor, - or_ as or_, + ge as ge, + getitem as getitem, + gt as gt, iadd as iadd, - isub as isub, - imul as imul, + iand as iand, + iconcat as iconcat, ifloordiv as ifloordiv, - itruediv as itruediv, - imod as imod, ilshift as ilshift, - irshift as irshift, - iand as iand, - ixor as ixor, + imatmul as imatmul, + imod as imod, + imul as imul, + index as index, + indexOf as indexOf, + inv as inv, + invert as invert, ior as ior, - concat as concat, - iconcat as iconcat, - getitem as getitem, - setitem as setitem, - delitem as delitem, - pow as pow, ipow as ipow, - eq as eq, - ne as ne, - lt as lt, - le as le, - gt as gt, - ge as ge, + irshift as irshift, + is_ as is_, + is_not as is_not, + isub as isub, itemgetter as itemgetter, - attrgetter as attrgetter, - methodcaller as methodcaller, + itruediv as itruediv, + ixor as ixor, + le as le, + length_hint as length_hint, + lshift as lshift, + lt as lt, matmul as matmul, - imatmul as imatmul, + methodcaller as methodcaller, + mod as mod, + mul as mul, + ne as ne, + neg as neg, + not_ as not_, + or_ as or_, + pos as pos, + pow as pow, + rshift as rshift, + setitem as setitem, + sub as sub, + truediv as truediv, + truth as truth, + xor as xor, ) +from typing import AnyStr def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/mypy/typeshed/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi index 6dc0e93e75ea..5d67d996b30a 100644 --- a/mypy/typeshed/stdlib/_osx_support.pyi +++ b/mypy/typeshed/stdlib/_osx_support.pyi @@ -1,9 +1,8 @@ +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union -from typing import Tuple, List, Optional, Dict, Sequence, Iterable, TypeVar, Union - -_T = TypeVar('_T') -_K = TypeVar('_K') -_V = TypeVar('_V') +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") __all__: List[str] @@ -26,8 +25,9 @@ def _remove_universal_flags(_config_vars: Dict[str, str]) -> Dict[str, str]: ... 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]]: ... +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/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi index 67b7d7cc5634..05209ba05b9b 100644 --- a/mypy/typeshed/stdlib/_posixsubprocess.pyi +++ b/mypy/typeshed/stdlib/_posixsubprocess.pyi @@ -1,14 +1,24 @@ -# Stubs for _posixsubprocess - # NOTE: These are incomplete! -from typing import Tuple, Sequence, Callable +from typing import Callable, Sequence, Tuple def cloexec_pipe() -> Tuple[int, int]: ... -def fork_exec(args: Sequence[str], - executable_list: Sequence[bytes], close_fds: bool, fds_to_keep: Sequence[int], - cwd: str, env_list: Sequence[bytes], - p2cread: int, p2cwrite: int, c2pred: int, c2pwrite: int, - errread: int, errwrite: int, errpipe_read: int, - errpipe_write: int, restore_signals: int, start_new_session: int, - preexec_fn: Callable[[], None]) -> int: ... +def fork_exec( + args: Sequence[str], + executable_list: Sequence[bytes], + close_fds: bool, + fds_to_keep: Sequence[int], + cwd: str, + env_list: Sequence[bytes], + p2cread: int, + p2cwrite: int, + c2pred: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: int, + start_new_session: int, + preexec_fn: Callable[[], None], +) -> int: ... diff --git a/mypy/typeshed/stdlib/_py_abc.pyi b/mypy/typeshed/stdlib/_py_abc.pyi index 5d71b730b149..9b0812d67c0f 100644 --- a/mypy/typeshed/stdlib/_py_abc.pyi +++ b/mypy/typeshed/stdlib/_py_abc.pyi @@ -1,11 +1,10 @@ +from typing import Any, Dict, Tuple, Type, TypeVar -from typing import Type, TypeVar, Tuple, Any, Dict, NewType - -_T = TypeVar('_T') +_T = TypeVar("_T") # TODO: Change the return into a NewType bound to int after pytype/#597 def get_cache_token() -> object: ... class ABCMeta(type): - def __new__(mcls, __name: str, __bases: Tuple[Type[Any], ...], __namespace: Dict[str, Any]) -> ABCMeta: ... + def __new__(__mcls, __name: str, __bases: Tuple[Type[Any], ...], __namespace: Dict[str, Any]) -> ABCMeta: ... def register(cls, subclass: Type[_T]) -> Type[_T]: ... diff --git a/mypy/typeshed/stdlib/_pydecimal.pyi b/mypy/typeshed/stdlib/_pydecimal.pyi index 4f742239336c..56fbddfffa5c 100644 --- a/mypy/typeshed/stdlib/_pydecimal.pyi +++ b/mypy/typeshed/stdlib/_pydecimal.pyi @@ -1,4 +1,3 @@ - # This is a slight lie, the implementations aren't exactly identical # However, in all likelihood, the differences are inconsequential from decimal import * diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index ec21c420e30b..aa09693420ca 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -1,5 +1,3 @@ -# Stubs for _random - import sys from typing import Tuple diff --git a/mypy/typeshed/stdlib/_sitebuiltins.pyi b/mypy/typeshed/stdlib/_sitebuiltins.pyi index bf2713f8b737..e0e9316aa290 100644 --- a/mypy/typeshed/stdlib/_sitebuiltins.pyi +++ b/mypy/typeshed/stdlib/_sitebuiltins.pyi @@ -1,16 +1,14 @@ -from typing import Optional, NoReturn, ClassVar, Iterable +from typing import ClassVar, Iterable, NoReturn, Optional from typing_extensions import Literal class Quitter: name: str eof: str - def __init__(self, name: str, eof: str) -> None: ... def __call__(self, code: Optional[int] = ...) -> NoReturn: ... class _Printer: MAXLINES: ClassVar[Literal[23]] - def __init__(self, name: str, data: str, files: Iterable[str] = ..., dirs: Iterable[str] = ...) -> None: ... def __call__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/_stat.pyi b/mypy/typeshed/stdlib/_stat.pyi index ffd28cb8ad9c..634f7da02563 100644 --- a/mypy/typeshed/stdlib/_stat.pyi +++ b/mypy/typeshed/stdlib/_stat.pyi @@ -1,5 +1,3 @@ -"""Stub file for the '_stat' module.""" - SF_APPEND: int SF_ARCHIVED: int SF_IMMUTABLE: int @@ -54,7 +52,6 @@ UF_OPAQUE: int def S_IMODE(mode: int) -> int: ... def S_IFMT(mode: int) -> int: ... - def S_ISBLK(mode: int) -> bool: ... def S_ISCHR(mode: int) -> bool: ... def S_ISDIR(mode: int) -> bool: ... @@ -65,5 +62,4 @@ def S_ISPORT(mode: int) -> bool: ... def S_ISREG(mode: int) -> bool: ... def S_ISSOCK(mode: int) -> bool: ... def S_ISWHT(mode: int) -> bool: ... - def filemode(mode: int) -> str: ... diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 56f343b5a838..513678499223 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -1,9 +1,7 @@ -# Stubs for _thread - import sys from threading import Thread from types import TracebackType -from typing import Any, Callable, Dict, NamedTuple, NoReturn, Optional, Tuple, Type +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple, Type error = RuntimeError @@ -17,10 +15,7 @@ class LockType: def locked(self) -> bool: ... def __enter__(self) -> bool: ... def __exit__( - self, - type: Optional[Type[BaseException]], - value: Optional[BaseException], - traceback: Optional[TracebackType], + 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: ... @@ -34,11 +29,13 @@ TIMEOUT_MAX: float if sys.version_info >= (3, 8): def get_native_id() -> int: ... # only available on some platforms - - class ExceptHookArgs(NamedTuple): - exc_type: Type[BaseException] - exc_value: Optional[BaseException] - exc_traceback: Optional[TracebackType] - thread: Optional[Thread] - def _ExceptHookArgs(args) -> ExceptHookArgs: ... - _excepthook: Callable[[ExceptHookArgs], Any] + class _ExceptHookArgs(Tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]]): + @property + def exc_type(self) -> Type[BaseException]: ... + @property + def exc_value(self) -> Optional[BaseException]: ... + @property + def exc_traceback(self) -> Optional[TracebackType]: ... + @property + def thread(self) -> Optional[Thread]: ... + _excepthook: Callable[[_ExceptHookArgs], Any] diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index 426496b11405..ed6eb8d9513e 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -1,4 +1,3 @@ -# Source: https://github.com/python/cpython/blob/master/Lib/_threading_local.py from typing import Any, Dict, Tuple from weakref import ReferenceType diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi new file mode 100644 index 000000000000..bc42dbf86937 --- /dev/null +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -0,0 +1,93 @@ +from typing import Any, Tuple, Union + +# _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: Union[str, Tuple[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 + +ALL_EVENTS: int +FILE_EVENTS: int +IDLE_EVENTS: int +TIMER_EVENTS: int +WINDOW_EVENTS: int + +DONT_WAIT: int +EXCEPTION: int +READABLE: int +WRITABLE: int + +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/_tracemalloc.pyi b/mypy/typeshed/stdlib/_tracemalloc.pyi index 3651c93198f7..4319ed46da64 100644 --- a/mypy/typeshed/stdlib/_tracemalloc.pyi +++ b/mypy/typeshed/stdlib/_tracemalloc.pyi @@ -1,12 +1,17 @@ +import sys +from tracemalloc import _FrameTupleT, _TraceTupleT from typing import Optional, Sequence, Tuple -from tracemalloc import _TraceTupleT, _FrameTupleT -def _get_object_traceback(__obj) -> Optional[Sequence[_FrameTupleT]]: ... +def _get_object_traceback(__obj: object) -> Optional[Sequence[_FrameTupleT]]: ... def _get_traces() -> Sequence[_TraceTupleT]: ... def clear_traces() -> None: ... def get_traceback_limit() -> int: ... def get_traced_memory() -> Tuple[int, int]: ... def get_tracemalloc_memory() -> int: ... def is_tracing() -> bool: ... + +if sys.version_info >= (3, 9): + def reset_peak() -> None: ... + def start(__nframe: int = ...) -> None: ... def stop() -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 5b535d322b2c..8160286c7ab2 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -15,16 +15,47 @@ import array import mmap import sys -from typing import Protocol, Text, TypeVar, Union -from typing_extensions import Literal +from typing import AbstractSet, 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_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) +class SupportsLessThan(Protocol): + def __lt__(self, __other: Any) -> bool: ... + +SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 + +# Mapping-like protocols + +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]]: ... + +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: ... + # 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]] @@ -34,27 +65,88 @@ else: AnyPath = Union[Text, bytes] OpenTextMode = Literal[ - 'r', 'r+', '+r', 'rt', 'tr', 'rt+', 'r+t', '+rt', 'tr+', 't+r', '+tr', - 'w', 'w+', '+w', 'wt', 'tw', 'wt+', 'w+t', '+wt', 'tw+', 't+w', '+tw', - 'a', 'a+', '+a', 'at', 'ta', 'at+', 'a+t', '+at', 'ta+', 't+a', '+ta', - 'x', 'x+', '+x', 'xt', 'tx', 'xt+', 'x+t', '+xt', 'tx+', 't+x', '+tx', - 'U', 'rU', 'Ur', 'rtU', 'rUt', 'Urt', 'trU', 'tUr', 'Utr', + "r", + "r+", + "+r", + "rt", + "tr", + "rt+", + "r+t", + "+rt", + "tr+", + "t+r", + "+tr", + "w", + "w+", + "+w", + "wt", + "tw", + "wt+", + "w+t", + "+wt", + "tw+", + "t+w", + "+tw", + "a", + "a+", + "+a", + "at", + "ta", + "at+", + "a+t", + "+at", + "ta+", + "t+a", + "+ta", + "x", + "x+", + "+x", + "xt", + "tx", + "xt+", + "x+t", + "+xt", + "tx+", + "t+x", + "+tx", + "U", + "rU", + "Ur", + "rtU", + "rUt", + "Urt", + "trU", + "tUr", + "Utr", ] 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', + "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): @@ -65,10 +157,15 @@ 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) -> int: ... + def write(self, __s: _T_contra) -> Any: ... if sys.version_info >= (3,): ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap] @@ -76,3 +173,11 @@ if sys.version_info >= (3,): else: ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap, buffer] WriteableBuffer = Union[bytearray, memoryview, array.array, mmap.mmap, buffer] + +if sys.version_info >= (3, 10): + from types import NoneType as NoneType +else: + # 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/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index f79d54d3bb33..bafaf7bc5f66 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -4,10 +4,12 @@ # file. They are provided for type checking purposes. from sys import _OptExcInfo -from typing import Callable, Dict, Iterable, List, Any, Text, Protocol, Tuple, Optional +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]: ... + 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]] @@ -27,6 +29,7 @@ class ErrorStream(Protocol): 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/_typeshed/xml.pyi b/mypy/typeshed/stdlib/_typeshed/xml.pyi new file mode 100644 index 000000000000..7ad28aef1b75 --- /dev/null +++ b/mypy/typeshed/stdlib/_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/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi index 6c8906e091cf..b4ec4e6ee794 100644 --- a/mypy/typeshed/stdlib/_warnings.pyi +++ b/mypy/typeshed/stdlib/_warnings.pyi @@ -12,7 +12,9 @@ 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: ... + 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 @@ -37,6 +39,7 @@ if sys.version_info >= (3, 6): module_globals: Optional[Dict[str, Any]] = ..., source: Optional[Any] = ..., ) -> None: ... + else: @overload def warn(message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 6a527c1894a6..5b4870229e66 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -1,8 +1,11 @@ import sys from typing import Any, Callable, Generic, Optional, TypeVar, overload -_C = TypeVar('_C', bound=Callable[..., Any]) -_T = TypeVar('_T') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_C = TypeVar("_C", bound=Callable[..., Any]) +_T = TypeVar("_T") class CallableProxyType(object): # "weakcallableproxy" def __getattr__(self, attr: str) -> Any: ... @@ -16,13 +19,16 @@ 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: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... ref = ReferenceType -def getweakrefcount(object: Any) -> int: ... +def getweakrefcount(__object: Any) -> int: ... def getweakrefs(object: Any) -> int: ... @overload def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType: ... + # 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/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index f7dc56ec3295..6f84124643af 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,12 +1,15 @@ -from typing import Iterator, Any, Iterable, MutableSet, Optional, TypeVar, Generic, Union +import sys +from typing import Any, Generic, Iterable, Iterator, MutableSet, Optional, TypeVar, Union -_S = TypeVar('_S') -_T = TypeVar('_T') -_SelfT = TypeVar('_SelfT', bound=WeakSet[Any]) +if sys.version_info >= (3, 9): + from types import GenericAlias + +_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: ... @@ -17,7 +20,6 @@ class WeakSet(MutableSet[_T], Generic[_T]): 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: ... @@ -41,3 +43,5 @@ class WeakSet(MutableSet[_T], Generic[_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: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 6a8990c4f9b8..09245b5218c1 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Union, Tuple, Optional, overload, Dict, NoReturn, Sequence +from typing import Any, Dict, NoReturn, Optional, Sequence, Tuple, Union, overload from typing_extensions import Literal CREATE_NEW_CONSOLE: int @@ -47,24 +47,58 @@ WAIT_OBJECT_0: int WAIT_TIMEOUT: int def CloseHandle(__handle: int) -> None: ... - @overload def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... @overload def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... @overload def ConnectNamedPipe(handle: int, overlapped: bool) -> Optional[Overlapped]: ... - -def CreateFile(__file_name: str, __desired_access: int, __share_mode: int, __security_attributes: int, __creation_disposition: int, __flags_and_attributes: int, __template_file: int) -> int: ... +def CreateFile( + __file_name: str, + __desired_access: int, + __share_mode: int, + __security_attributes: int, + __creation_disposition: int, + __flags_and_attributes: int, + __template_file: int, +) -> int: ... def CreateJunction(__src_path: str, __dst_path: str) -> None: ... -def CreateNamedPipe(__name: str, __open_mode: int, __pipe_mode: int, __max_instances: int, __out_buffer_size: int, __in_buffer_size: int, __default_timeout: int, __security_attributes: int) -> int: ... +def CreateNamedPipe( + __name: str, + __open_mode: int, + __pipe_mode: int, + __max_instances: int, + __out_buffer_size: int, + __in_buffer_size: int, + __default_timeout: int, + __security_attributes: int, +) -> int: ... def CreatePipe(__pipe_attrs: Any, __size: int) -> Tuple[int, int]: ... -def CreateProcess(__application_name: Optional[str], __command_line: Optional[str], __proc_attrs: Any, __thread_attrs: Any, __inherit_handles: bool, __creation_flags: int, __env_mapping: Dict[str, str], __current_directory: Optional[str], __startup_info: Any) -> Tuple[int, int, int, int]: ... -def DuplicateHandle(__source_process_handle: int, __source_handle: int, __target_process_handle: int, __desired_access: int, __inherit_handle: bool, __options: int = ...) -> int: ... +def CreateProcess( + __application_name: Optional[str], + __command_line: Optional[str], + __proc_attrs: Any, + __thread_attrs: Any, + __inherit_handles: bool, + __creation_flags: int, + __env_mapping: Dict[str, str], + __current_directory: Optional[str], + __startup_info: Any, +) -> Tuple[int, int, int, int]: ... +def DuplicateHandle( + __source_process_handle: int, + __source_handle: int, + __target_process_handle: int, + __desired_access: int, + __inherit_handle: bool, + __options: int = ..., +) -> int: ... def ExitProcess(__ExitCode: int) -> NoReturn: ... + if sys.version_info >= (3, 7): def GetACP() -> int: ... def GetFileType(handle: int) -> int: ... + def GetCurrentProcess() -> int: ... def GetExitCodeProcess(__process: int) -> int: ... def GetLastError() -> int: ... @@ -73,21 +107,19 @@ def GetStdHandle(__std_handle: int) -> int: ... def GetVersion() -> int: ... def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... def PeekNamedPipe(__handle: int, __size: int = ...) -> Union[Tuple[int, int], Tuple[bytes, int, int]]: ... - @overload def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... @overload def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> Tuple[bytes, int]: ... @overload def ReadFile(handle: int, size: int, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... - -def SetNamedPipeHandleState(__named_pipe: int, __mode: Optional[int], __max_collection_count: Optional[int], __collect_data_timeout: Optional[int]) -> None: ... +def SetNamedPipeHandleState( + __named_pipe: int, __mode: Optional[int], __max_collection_count: Optional[int], __collect_data_timeout: Optional[int] +) -> None: ... def TerminateProcess(__handle: int, __exit_code: int) -> None: ... def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... def WaitNamedPipe(__name: str, __timeout: int) -> None: ... - - @overload def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... @overload @@ -95,7 +127,6 @@ def WriteFile(handle: int, buffer: bytes, overlapped: Literal[False] = ...) -> T @overload def WriteFile(handle: int, buffer: bytes, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... - class Overlapped: event: int = ... def GetOverlappedResult(self, __wait: bool) -> Tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index e9c530d20f83..6be75c3bc7cc 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -1,15 +1,16 @@ from typing import Any, Callable, Type, TypeVar -# Stubs for abc. -_T = TypeVar('_T') -_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) +_T = TypeVar("_T") +_FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) -# Thesee definitions have special processing in mypy +# These definitions have special processing in mypy class ABCMeta(type): def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... def abstractmethod(callable: _FuncT) -> _FuncT: ... + class abstractproperty(property): ... + # These two are deprecated and not supported by mypy def abstractstaticmethod(callable: _FuncT) -> _FuncT: ... def abstractclassmethod(callable: _FuncT) -> _FuncT: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index 696ae4c5255f..f812ac593e97 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,7 +1,7 @@ -from typing import Union, IO, Optional, Type, NamedTuple, List, Tuple, Any, Text, overload -from typing_extensions import Literal -from types import TracebackType import sys +from types import TracebackType +from typing import IO, Any, List, NamedTuple, Optional, Text, Tuple, Type, Union, overload +from typing_extensions import Literal class Error(Exception): ... @@ -20,8 +20,9 @@ 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 __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: ... @@ -44,8 +45,9 @@ class Aifc_write: 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 __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 94e67addd477..52e2c5d96bef 100644 --- a/mypy/typeshed/stdlib/antigravity.pyi +++ b/mypy/typeshed/stdlib/antigravity.pyi @@ -1,4 +1,3 @@ - import sys if sys.version_info >= (3, 0): diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 20202f17b2ed..3dd6e56175dd 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -1,12 +1,28 @@ +import sys from typing import ( - Any, Callable, Dict, Generator, Iterable, List, IO, NoReturn, Optional, - Pattern, Protocol, Sequence, Text, Tuple, Type, Union, TypeVar, overload + IO, + Any, + Callable, + Dict, + Generator, + Iterable, + List, + NoReturn, + Optional, + Pattern, + Protocol, + Sequence, + Text, + Tuple, + Type, + TypeVar, + Union, + overload, ) -import sys -_T = TypeVar('_T') -_ActionT = TypeVar('_ActionT', bound=Action) -_N = TypeVar('_N') +_T = TypeVar("_T") +_ActionT = TypeVar("_ActionT", bound=Action) +_N = TypeVar("_N") if sys.version_info >= (3,): _Text = str @@ -22,6 +38,8 @@ 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 @@ -33,7 +51,7 @@ class _AttributeHolder: class _ActionsContainer: description: Optional[_Text] prefix_chars: _Text - argument_default: Optional[_Text] + argument_default: Any conflict_handler: _Text _registries: Dict[_Text, Dict[Any, Any]] @@ -44,27 +62,29 @@ class _ActionsContainer: _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: Optional[Text], conflict_handler: Text) -> None: ... + 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( + 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: ... @@ -98,48 +118,53 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): _subparsers: Optional[_ArgumentGroup] if sys.version_info >= (3, 9): - def __init__(self, - prog: Optional[str] = ..., - usage: Optional[str] = ..., - description: Optional[str] = ..., - epilog: Optional[str] = ..., - parents: Sequence[ArgumentParser] = ..., - formatter_class: _FormatterClass = ..., - prefix_chars: str = ..., - fromfile_prefix_chars: Optional[str] = ..., - argument_default: Optional[str] = ..., - conflict_handler: str = ..., - add_help: bool = ..., - allow_abbrev: bool = ..., - exit_on_error: bool = ...) -> None: ... + def __init__( + self, + prog: Optional[str] = ..., + usage: Optional[str] = ..., + description: Optional[str] = ..., + epilog: Optional[str] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: Optional[str] = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = ..., + allow_abbrev: bool = ..., + exit_on_error: bool = ..., + ) -> None: ... elif sys.version_info >= (3, 5): - def __init__(self, - prog: Optional[str] = ..., - usage: Optional[str] = ..., - description: Optional[str] = ..., - epilog: Optional[str] = ..., - parents: Sequence[ArgumentParser] = ..., - formatter_class: _FormatterClass = ..., - prefix_chars: str = ..., - fromfile_prefix_chars: Optional[str] = ..., - argument_default: Optional[str] = ..., - conflict_handler: str = ..., - add_help: bool = ..., - allow_abbrev: bool = ...) -> None: ... + def __init__( + self, + prog: Optional[str] = ..., + usage: Optional[str] = ..., + description: Optional[str] = ..., + epilog: Optional[str] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: Optional[str] = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + 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: Optional[Text] = ..., - conflict_handler: Text = ..., - add_help: bool = ...) -> None: ... - + 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 @@ -152,44 +177,52 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore @overload def parse_args(self, *, namespace: _N) -> _N: ... - if sys.version_info >= (3, 7): - def add_subparsers(self, *, title: str = ..., - description: Optional[str] = ..., - prog: str = ..., - parser_class: Type[ArgumentParser] = ..., - action: Type[Action] = ..., - option_string: str = ..., - dest: Optional[str] = ..., - required: bool = ..., - help: Optional[str] = ..., - metavar: Optional[str] = ...) -> _SubParsersAction: ... + def add_subparsers( + self, + *, + title: str = ..., + description: Optional[str] = ..., + prog: str = ..., + parser_class: Type[ArgumentParser] = ..., + action: Type[Action] = ..., + option_string: str = ..., + dest: Optional[str] = ..., + required: bool = ..., + help: Optional[str] = ..., + metavar: Optional[str] = ..., + ) -> _SubParsersAction: ... else: - 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 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 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: ... if sys.version_info >= (3, 7): - def parse_intermixed_args(self, args: Optional[Sequence[str]] = ..., - namespace: Optional[Namespace] = ...) -> Namespace: ... - def parse_known_intermixed_args(self, - args: Optional[Sequence[str]] = ..., - namespace: Optional[Namespace] = ...) -> Tuple[Namespace, List[str]]: ... + def parse_intermixed_args( + self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ... + ) -> Namespace: ... + def parse_known_intermixed_args( + self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ... + ) -> Tuple[Namespace, List[str]]: ... # undocumented def _get_optional_actions(self) -> List[Action]: ... def _get_positional_actions(self) -> List[Action]: ... @@ -220,21 +253,25 @@ class HelpFormatter: _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 __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: Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[Text] = ...) -> None: ... + def add_usage( + self, usage: 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_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: ... @@ -252,6 +289,7 @@ class HelpFormatter: class RawDescriptionHelpFormatter(HelpFormatter): ... class RawTextHelpFormatter(RawDescriptionHelpFormatter): ... class ArgumentDefaultsHelpFormatter(HelpFormatter): ... + if sys.version_info >= (3,): class MetavarTypeHelpFormatter(HelpFormatter): ... @@ -266,21 +304,26 @@ class Action(_AttributeHolder): 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: ... + 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: ... if sys.version_info >= (3, 9): def format_usage(self) -> str: ... @@ -290,7 +333,6 @@ if sys.version_info >= (3, 9): self, option_strings: Sequence[str], dest: str, - const: None = ..., # unused in implementation default: Union[_T, str, None] = ..., type: Optional[Union[Callable[[Text], _T], Callable[[str], _T], FileType]] = ..., choices: Optional[Iterable[_T]] = ..., @@ -312,21 +354,20 @@ class FileType: 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: ... + 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 __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: ... + def __init__( + self, container: _ActionsContainer, title: Optional[Text] = ..., description: Optional[Text] = ..., **kwargs: Any + ) -> None: ... # undocumented class _MutuallyExclusiveGroup(_ArgumentGroup): @@ -339,73 +380,68 @@ 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: ... + 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: ... + 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: ... + 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: ... + 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: ... + 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: ... + 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: ... + def __init__( + self, + option_strings: Sequence[Text], + version: Optional[Text] = ..., + dest: Text = ..., + default: Text = ..., + help: Text = ..., + ) -> None: ... # undocumented class _SubParsersAction(Action): @@ -416,22 +452,26 @@ class _SubParsersAction(Action): choices: Dict[_Text, ArgumentParser] _choices_actions: List[Action] if sys.version_info >= (3, 7): - def __init__(self, - option_strings: Sequence[Text], - prog: Text, - parser_class: Type[ArgumentParser], - dest: Text = ..., - required: bool = ..., - help: Optional[Text] = ..., - metavar: Optional[Union[Text, Tuple[Text, ...]]] = ...) -> None: ... + def __init__( + self, + option_strings: Sequence[Text], + prog: Text, + parser_class: Type[ArgumentParser], + dest: Text = ..., + required: bool = ..., + help: Optional[Text] = ..., + metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., + ) -> None: ... else: - 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: ... + 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]: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 1ca55c8526cd..c7e1ef0bb8fa 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,18 +1,13 @@ -# Stubs for array - -# Based on http://docs.python.org/3.6/library/array.html - import sys -from typing import (Any, BinaryIO, Generic, Iterable, Iterator, List, MutableSequence, - overload, Text, Tuple, TypeVar, Union) +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'] +_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) +_T = TypeVar("_T", int, float, Text) if sys.version_info >= (3,): typecodes: str @@ -21,17 +16,13 @@ class array(MutableSequence[_T], Generic[_T]): typecode: _TypeCode itemsize: int @overload - def __init__(self: array[int], typecode: _IntTypeCode, - __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + 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: ... + 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[Text], typecode: _UnicodeTypeCode, __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... @overload - def __init__(self, typecode: str, - __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + 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: ... @@ -59,19 +50,15 @@ class array(MutableSequence[_T], Generic[_T]): if sys.version_info < (3, 9): 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: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index d798376a6180..ff1cd00c7757 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -14,11 +14,19 @@ from typing_extensions import Literal from _ast import * # type: ignore if sys.version_info >= (3, 8): - class Num(Constant): ... - class Str(Constant): ... - class Bytes(Constant): ... + class Num(Constant): + value: complex + class Str(Constant): + value: str + # Aliases for value, for backwards compatibility + s: str + class Bytes(Constant): + value: bytes + # Aliases for value, for backwards compatibility + s: bytes class NameConstant(Constant): ... class Ellipsis(Constant): ... + if sys.version_info >= (3, 9): class slice(AST): ... class ExtSlice(slice): ... @@ -41,8 +49,7 @@ class NodeVisitor: def visit_Delete(self, node: Delete) -> Any: ... def visit_Assign(self, node: Assign) -> Any: ... def visit_AugAssign(self, node: AugAssign) -> Any: ... - if sys.version_info >= (3, 6): - def visit_AnnAssign(self, node: AnnAssign) -> Any: ... + def visit_AnnAssign(self, node: AnnAssign) -> Any: ... def visit_For(self, node: For) -> Any: ... def visit_AsyncFor(self, node: AsyncFor) -> Any: ... def visit_While(self, node: While) -> Any: ... @@ -77,11 +84,9 @@ class NodeVisitor: def visit_YieldFrom(self, node: YieldFrom) -> Any: ... def visit_Compare(self, node: Compare) -> Any: ... def visit_Call(self, node: Call) -> Any: ... - if sys.version_info >= (3, 6): - def visit_FormattedValue(self, node: FormattedValue) -> Any: ... - def visit_JoinedStr(self, node: JoinedStr) -> Any: ... - if sys.version_info >= (3, 6): - def visit_Constant(self, node: Constant) -> Any: ... + def visit_FormattedValue(self, node: FormattedValue) -> Any: ... + def visit_JoinedStr(self, node: JoinedStr) -> Any: ... + def visit_Constant(self, node: Constant) -> Any: ... if sys.version_info >= (3, 8): def visit_NamedExpr(self, node: NamedExpr) -> Any: ... def visit_Attribute(self, node: Attribute) -> Any: ... @@ -143,7 +148,7 @@ class NodeVisitor: def visit_Ellipsis(self, node: Ellipsis) -> Any: ... class NodeTransformer(NodeVisitor): - def generic_visit(self, node: AST) -> Optional[AST]: ... + def generic_visit(self, node: AST) -> AST: ... # TODO: Override the visit_* methods with better return types. # The usual return type is Optional[AST], but Iterable[AST] # is also allowed in some cases -- this needs to be mapped. @@ -180,16 +185,23 @@ if sys.version_info >= (3, 9): def unparse(ast_obj: AST) -> str: ... def copy_location(new_node: _T, old_node: AST) -> _T: ... + if sys.version_info >= (3, 9): - def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ..., *, indent: Union[int, str, None] = ...) -> str: ... + def dump( + node: AST, annotate_fields: bool = ..., include_attributes: bool = ..., *, indent: Union[int, str, None] = ... + ) -> str: ... + else: def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... + def fix_missing_locations(node: _T) -> _T: ... -def get_docstring(node: AST, clean: bool = ...) -> str: ... +def get_docstring(node: AST, clean: bool = ...) -> Optional[str]: ... def increment_lineno(node: _T, n: int = ...) -> _T: ... def iter_child_nodes(node: AST) -> Iterator[AST]: ... def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... def literal_eval(node_or_string: Union[str, AST]) -> Any: ... + if sys.version_info >= (3, 8): def get_source_segment(source: str, node: AST, *, padded: bool = ...) -> Optional[str]: ... + def walk(node: AST) -> Iterator[AST]: ... diff --git a/mypy/typeshed/stdlib/asynchat.pyi b/mypy/typeshed/stdlib/asynchat.pyi index a359ae7de147..34039b993400 100644 --- a/mypy/typeshed/stdlib/asynchat.pyi +++ b/mypy/typeshed/stdlib/asynchat.pyi @@ -1,10 +1,9 @@ -from abc import abstractmethod import asyncore import socket import sys +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: ... @@ -13,7 +12,6 @@ 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 diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index 147c8b46d4eb..42e7aa9ba6d8 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -1,97 +1,58 @@ import sys from typing import Type -from asyncio.base_events import BaseEventLoop as BaseEventLoop -from asyncio.coroutines import ( - coroutine as coroutine, - iscoroutinefunction as iscoroutinefunction, - iscoroutine as iscoroutine, -) -from asyncio.events import ( - AbstractEventLoopPolicy as AbstractEventLoopPolicy, +from .base_events import BaseEventLoop as BaseEventLoop +from .coroutines import coroutine as coroutine, iscoroutine as iscoroutine, iscoroutinefunction as iscoroutinefunction +from .events import ( AbstractEventLoop as AbstractEventLoop, + AbstractEventLoopPolicy as AbstractEventLoopPolicy, AbstractServer as AbstractServer, Handle as Handle, TimerHandle as TimerHandle, - get_event_loop_policy as get_event_loop_policy, - set_event_loop_policy as set_event_loop_policy, + _get_running_loop as _get_running_loop, + _set_running_loop as _set_running_loop, + get_child_watcher as get_child_watcher, get_event_loop as get_event_loop, - set_event_loop as set_event_loop, + get_event_loop_policy as get_event_loop_policy, new_event_loop as new_event_loop, - get_child_watcher as get_child_watcher, set_child_watcher as set_child_watcher, - _set_running_loop as _set_running_loop, - _get_running_loop as _get_running_loop, -) -if sys.version_info >= (3, 7): - from asyncio.events import get_running_loop as get_running_loop -if sys.version_info >= (3, 8): - from asyncio.exceptions import ( - CancelledError as CancelledError, - IncompleteReadError as IncompleteReadError, - InvalidStateError as InvalidStateError, - LimitOverrunError as LimitOverrunError, - SendfileNotAvailableError as SendfileNotAvailableError, - TimeoutError as TimeoutError, - ) -else: - if sys.version_info >= (3, 7): - from asyncio.events import ( - SendfileNotAvailableError as SendfileNotAvailableError - ) - from asyncio.futures import ( - CancelledError as CancelledError, - TimeoutError as TimeoutError, - InvalidStateError as InvalidStateError, - ) - from asyncio.streams import ( - IncompleteReadError as IncompleteReadError, - LimitOverrunError as LimitOverrunError, - ) -from asyncio.futures import ( - Future as Future, - isfuture as isfuture, - wrap_future as wrap_future, + set_event_loop as set_event_loop, + set_event_loop_policy as set_event_loop_policy, ) -from asyncio.locks import ( - Lock as Lock, - Event as Event, +from .futures import Future as Future, isfuture as isfuture, wrap_future as wrap_future +from .locks import ( + BoundedSemaphore as BoundedSemaphore, Condition as Condition, + Event as Event, + Lock as Lock, Semaphore as Semaphore, - BoundedSemaphore as BoundedSemaphore, ) -from asyncio.protocols import ( +from .protocols import ( BaseProtocol as BaseProtocol, - Protocol as Protocol, DatagramProtocol as DatagramProtocol, + Protocol as Protocol, SubprocessProtocol as SubprocessProtocol, ) -if sys.version_info >= (3, 7): - from asyncio.protocols import BufferedProtocol as BufferedProtocol -from asyncio.queues import ( - Queue as Queue, - PriorityQueue as PriorityQueue, +from .queues import ( LifoQueue as LifoQueue, - QueueFull as QueueFull, + PriorityQueue as PriorityQueue, + Queue as Queue, QueueEmpty as QueueEmpty, + QueueFull as QueueFull, ) -if sys.version_info >= (3, 7): - from asyncio.runners import run as run -from asyncio.streams import ( +from .streams import ( StreamReader as StreamReader, - StreamWriter as StreamWriter, StreamReaderProtocol as StreamReaderProtocol, + StreamWriter as StreamWriter, open_connection as open_connection, start_server as start_server, ) -from asyncio.subprocess import ( - create_subprocess_exec as create_subprocess_exec, - create_subprocess_shell as create_subprocess_shell, -) -from asyncio.tasks import ( +from .subprocess import create_subprocess_exec as create_subprocess_exec, create_subprocess_shell as create_subprocess_shell +from .tasks import ( + ALL_COMPLETED as ALL_COMPLETED, FIRST_COMPLETED as FIRST_COMPLETED, FIRST_EXCEPTION as FIRST_EXCEPTION, - ALL_COMPLETED as ALL_COMPLETED, + Task as Task, as_completed as as_completed, ensure_future as ensure_future, gather as gather, @@ -100,39 +61,56 @@ from asyncio.tasks import ( sleep as sleep, wait as wait, wait_for as wait_for, - Task as Task, ) -if sys.version_info >= (3, 7): - from asyncio.tasks import ( - all_tasks as all_tasks, - create_task as create_task, - current_task as current_task, - ) -if sys.version_info >= (3, 9): - from asyncio.threads import to_thread as to_thread -from asyncio.transports import ( +from .transports import ( BaseTransport as BaseTransport, - ReadTransport as ReadTransport, - WriteTransport as WriteTransport, - Transport as Transport, DatagramTransport as DatagramTransport, + ReadTransport as ReadTransport, SubprocessTransport as SubprocessTransport, + Transport as Transport, + WriteTransport as WriteTransport, ) +if sys.version_info >= (3, 7): + from .events import get_running_loop as get_running_loop +if sys.version_info >= (3, 8): + from .exceptions import ( + CancelledError as CancelledError, + IncompleteReadError as IncompleteReadError, + InvalidStateError as InvalidStateError, + LimitOverrunError as LimitOverrunError, + SendfileNotAvailableError as SendfileNotAvailableError, + TimeoutError as TimeoutError, + ) +else: + if sys.version_info >= (3, 7): + from .events import SendfileNotAvailableError as SendfileNotAvailableError + from .futures import CancelledError as CancelledError, InvalidStateError as InvalidStateError, TimeoutError as TimeoutError + from .streams import IncompleteReadError as IncompleteReadError, LimitOverrunError as LimitOverrunError + +if sys.version_info >= (3, 7): + from .protocols import BufferedProtocol as BufferedProtocol + +if sys.version_info >= (3, 7): + from .runners import run as run + +if sys.version_info >= (3, 7): + from .tasks import all_tasks as all_tasks, create_task as create_task, current_task as current_task +if sys.version_info >= (3, 9): + from .threads import to_thread as to_thread + DefaultEventLoopPolicy: Type[AbstractEventLoopPolicy] -if sys.platform == 'win32': - from asyncio.windows_events import * +if sys.platform == "win32": + from .windows_events import * -if sys.platform != 'win32': - from asyncio.streams import ( - open_unix_connection as open_unix_connection, - start_unix_server as start_unix_server, - ) +if sys.platform != "win32": + from .streams import open_unix_connection as open_unix_connection, start_unix_server as start_unix_server from .unix_events import ( AbstractChildWatcher as AbstractChildWatcher, FastChildWatcher as FastChildWatcher, SafeChildWatcher as SafeChildWatcher, SelectorEventLoop as SelectorEventLoop, ) + if sys.version_info >= (3, 8): from .unix_events import MultiLoopChildWatcher as MultiLoopChildWatcher, ThreadedChildWatcher as ThreadedChildWatcher diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 0be834bab326..33c0f87d8da2 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -1,20 +1,20 @@ -from socket import socket, _Address, _RetAddress import ssl import sys -from typing import Any, Awaitable, Callable, Dict, Generator, IO, List, Optional, Sequence, Tuple, TypeVar, Union, overload -from typing_extensions import Literal +from _typeshed import FileDescriptorLike from abc import ABCMeta -from asyncio.futures import Future from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle +from asyncio.futures import Future from asyncio.protocols import BaseProtocol from asyncio.tasks import Task from asyncio.transports import BaseTransport -from _typeshed import FileDescriptorLike +from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket +from typing import IO, Any, Awaitable, Callable, Dict, Generator, List, Optional, Sequence, Tuple, TypeVar, Union, overload +from typing_extensions import Literal if sys.version_info >= (3, 7): from contextvars import Context -_T = TypeVar('_T') +_T = TypeVar("_T") _Context = Dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] @@ -25,27 +25,24 @@ class Server(AbstractServer): ... class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): def run_forever(self) -> None: ... - # Can't use a union, see mypy issue # 1873. @overload def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... @overload def run_until_complete(self, future: Awaitable[_T]) -> _T: ... - def stop(self) -> None: ... def is_running(self) -> bool: ... def is_closed(self) -> bool: ... def close(self) -> None: ... - if sys.version_info >= (3, 6): - async def shutdown_asyncgens(self) -> None: ... + async def shutdown_asyncgens(self) -> None: ... # Methods scheduling callbacks. All these return Handles. if sys.version_info >= (3, 7): def call_soon(self, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ...) -> Handle: ... def call_later( - self, delay: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ..., + self, delay: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ... ) -> TimerHandle: ... def call_at( - self, when: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ..., + self, when: float, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ... ) -> TimerHandle: ... else: def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... @@ -56,30 +53,34 @@ 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: Optional[str] = ...) -> Task[_T]: ... else: def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... - def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ... + def set_task_factory( + self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]] + ) -> None: ... def get_task_factory(self) -> Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]: ... # Methods for interacting with threads if sys.version_info >= (3, 7): def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any, context: Optional[Context] = ...) -> Handle: ... else: def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... - # run_in_executor is defined as a coroutine in AbstractEventLoop but returns a Future in concrete implementation. - # Need to ignore mypy Return type error as a result. - def run_in_executor(self, executor: Any, # type: ignore - func: Callable[..., _T], *args: Any) -> Future[_T]: ... + def run_in_executor(self, executor: Any, func: Callable[..., _T], *args: Any) -> Future[_T]: ... def set_default_executor(self, executor: Any) -> None: ... # Network I/O methods returning Futures. - # TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers - # https://github.com/python/mypy/issues/2509 - async def getaddrinfo(self, host: Optional[str], port: Union[str, int, None], *, - family: int = ..., type: int = ..., proto: int = ..., - flags: int = ...) -> List[Tuple[int, int, int, str, Tuple[Any, ...]]]: ... - async def getnameinfo(self, sockaddr: Tuple[Any, ...], flags: int = ...) -> Tuple[str, int]: ... + async def getaddrinfo( + self, + host: Optional[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]]]]: ... + async def getnameinfo( + self, sockaddr: Union[Tuple[str, int], Tuple[str, int, int, int]], flags: int = ... + ) -> Tuple[str, str]: ... if sys.version_info >= (3, 8): @overload async def create_connection( @@ -119,74 +120,209 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ) -> _TransProtPair: ... elif sys.version_info >= (3, 7): @overload - async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., - sock: None = ..., local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... @overload - async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., - sock: socket, local_addr: None = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... else: @overload - async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: None = ..., - local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ) -> _TransProtPair: ... @overload - async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: socket, - local_addr: None = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ) -> _TransProtPair: ... if sys.version_info >= (3, 7): - async def sock_sendfile(self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, - fallback: bool = ...) -> int: ... + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: bool = ... + ) -> int: ... @overload - async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., - port: int = ..., *, family: int = ..., flags: int = ..., sock: None = ..., backlog: int = ..., - ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> Server: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ..., + ) -> Server: ... @overload - async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - family: int = ..., flags: int = ..., sock: socket = ..., backlog: int = ..., - ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> Server: ... - async def connect_accepted_socket(self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... - async def sendfile(self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, - fallback: bool = ...) -> int: ... - async def start_tls(self, transport: BaseTransport, protocol: BaseProtocol, sslcontext: ssl.SSLContext, *, - server_side: bool = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> BaseTransport: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ..., + ) -> Server: ... + async def connect_accepted_socket( + self, + protocol_factory: _ProtocolFactory, + sock: socket, + *, + ssl: _SSLContext = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... + async def sendfile( + self, + transport: BaseTransport, + file: IO[bytes], + offset: int = ..., + count: Optional[int] = ..., + *, + fallback: bool = ..., + ) -> int: ... + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> BaseTransport: ... else: @overload - async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., port: int = ..., *, - family: int = ..., flags: int = ..., - sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ...) -> Server: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ) -> Server: ... @overload - async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - family: int = ..., flags: int = ..., - sock: socket, backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ...) -> Server: ... - async def connect_accepted_socket(self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ...) -> _TransProtPair: ... - async def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory, - local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *, - family: int = ..., proto: int = ..., flags: int = ..., - reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - allow_broadcast: Optional[bool] = ..., - sock: Optional[socket] = ...) -> _TransProtPair: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket, + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ) -> Server: ... + async def connect_accepted_socket( + self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ... + ) -> _TransProtPair: ... + async def create_datagram_endpoint( + self, + protocol_factory: _ProtocolFactory, + local_addr: Optional[Tuple[str, int]] = ..., + remote_addr: Optional[Tuple[str, int]] = ..., + *, + family: int = ..., + proto: int = ..., + flags: int = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + allow_broadcast: Optional[bool] = ..., + sock: Optional[socket] = ..., + ) -> _TransProtPair: ... # Pipes and subprocesses. async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... - async def subprocess_shell(self, protocol_factory: _ProtocolFactory, cmd: Union[bytes, str], *, stdin: Any = ..., - stdout: Any = ..., stderr: Any = ..., universal_newlines: Literal[False] = ..., - shell: Literal[True] = ..., bufsize: Literal[0] = ..., encoding: None = ..., - errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any) -> _TransProtPair: ... - async def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ..., - stdout: Any = ..., stderr: Any = ..., - **kwargs: Any) -> _TransProtPair: ... + async def subprocess_shell( + self, + protocol_factory: _ProtocolFactory, + cmd: Union[bytes, str], + *, + stdin: Any = ..., + stdout: Any = ..., + stderr: Any = ..., + universal_newlines: Literal[False] = ..., + shell: Literal[True] = ..., + bufsize: Literal[0] = ..., + encoding: None = ..., + errors: None = ..., + text: Literal[False, None] = ..., + **kwargs: Any, + ) -> _TransProtPair: ... + async def subprocess_exec( + self, + protocol_factory: _ProtocolFactory, + *args: Any, + stdin: Any = ..., + stdout: Any = ..., + stderr: Any = ..., + **kwargs: Any, + ) -> _TransProtPair: ... def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... def remove_reader(self, fd: FileDescriptorLike) -> None: ... def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_futures.pyi b/mypy/typeshed/stdlib/asyncio/base_futures.pyi index 2298e500c0e3..270a69685c24 100644 --- a/mypy/typeshed/stdlib/asyncio/base_futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_futures.pyi @@ -1,7 +1,10 @@ -import contextvars -from typing import List, Tuple, Callable, Sequence +import sys +from typing import Any, Callable, List, Sequence, Tuple from typing_extensions import Literal +if sys.version_info >= (3, 7): + from contextvars import Context + from . import futures _PENDING: Literal["PENDING"] # undocumented @@ -9,5 +12,11 @@ _CANCELLED: Literal["CANCELLED"] # undocumented _FINISHED: Literal["FINISHED"] # undocumented def isfuture(obj: object) -> bool: ... -def _format_callbacks(cb: Sequence[Tuple[Callable[[futures.Future], None], contextvars.Context]]) -> str: ... # undocumented -def _future_repr_info(future: futures.Future) -> List[str]: ... # undocumented + +if sys.version_info >= (3, 7): + def _format_callbacks(cb: Sequence[Tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented + +else: + def _format_callbacks(cb: Sequence[Callable[[futures.Future[Any]], None]]) -> str: ... # undocumented + +def _future_repr_info(future: futures.Future[Any]) -> List[str]: ... # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index 31cf24860eff..acdf985205ab 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,11 +1,7 @@ - -from typing import Optional, Union, Sequence, IO, Any, List, Deque, Dict, Tuple, Callable import subprocess +from typing import IO, Any, Callable, Deque, Dict, List, Optional, Sequence, Tuple, Union -from . import events -from . import protocols -from . import futures -from . import transports +from . import events, futures, protocols, transports _File = Optional[Union[int, IO[Any]]] @@ -14,18 +10,37 @@ class BaseSubprocessTransport(transports.SubprocessTransport): _closed: bool # undocumented _protocol: protocols.SubprocessProtocol # undocumented _loop: events.AbstractEventLoop # undocumented - _proc: Optional[subprocess.Popen] # undocumented + _proc: Optional[subprocess.Popen[Any]] # undocumented _pid: Optional[int] # undocumented _returncode: Optional[int] # undocumented - _exit_waiters: List[futures.Future] # undocumented + _exit_waiters: List[futures.Future[Any]] # undocumented _pending_calls: Deque[Tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented _pipes: Dict[int, _File] # undocumented _finished: bool # undocumented - - def __init__(self, loop: events.AbstractEventLoop, protocol: protocols.SubprocessProtocol, args: Union[str, bytes, Sequence[Union[str, bytes]]], - shell: bool, stdin: _File, stdout: _File, stderr: _File, bufsize: int, waiter: Optional[futures.Future] = ..., extra: Optional[Any] = ..., **kwargs: Any) -> None: ... - - def _start(self, args: Union[str, bytes, Sequence[Union[str, bytes]]], shell: bool, stdin: _File, stdout: _File, stderr: _File, bufsize: int, **kwargs: Any): ... # undocumented + def __init__( + self, + loop: events.AbstractEventLoop, + protocol: protocols.SubprocessProtocol, + args: Union[str, bytes, Sequence[Union[str, bytes]]], + shell: bool, + stdin: _File, + stdout: _File, + stderr: _File, + bufsize: int, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Any] = ..., + **kwargs: Any, + ) -> None: ... + def _start( + self, + args: Union[str, bytes, Sequence[Union[str, bytes]]], + shell: bool, + stdin: _File, + stdout: _File, + stderr: _File, + bufsize: int, + **kwargs: Any, + ) -> None: ... # undocumented def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... def get_protocol(self) -> protocols.BaseProtocol: ... def is_closing(self) -> bool: ... @@ -37,7 +52,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport): def send_signal(self, signal: int) -> None: ... # type: ignore def terminate(self) -> None: ... def kill(self) -> None: ... - async def _connect_pipes(self, waiter: Optional[futures.Future]) -> None: ... # undocumented + async def _connect_pipes(self, waiter: Optional[futures.Future[Any]]) -> None: ... # undocumented def _call(self, cb: Callable[..., Any], *data: Any) -> None: ... # undocumented def _pipe_connection_lost(self, fd: int, exc: Optional[BaseException]) -> None: ... # undocumented def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented @@ -47,7 +62,6 @@ class BaseSubprocessTransport(transports.SubprocessTransport): def _call_connection_lost(self, exc: Optional[BaseException]) -> None: ... # undocumented class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented - def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ... def connection_made(self, transport: transports.BaseTransport) -> None: ... def connection_lost(self, exc: Optional[BaseException]) -> None: ... @@ -55,5 +69,4 @@ class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented def resume_writing(self) -> None: ... class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): # undocumented - def data_received(self, data: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_tasks.pyi b/mypy/typeshed/stdlib/asyncio/base_tasks.pyi index aa9f600e1a16..fbe0a03e8755 100644 --- a/mypy/typeshed/stdlib/asyncio/base_tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_tasks.pyi @@ -1,8 +1,9 @@ from _typeshed import AnyPath -from typing import List, Optional from types import FrameType +from typing import Any, List, Optional + from . import tasks -def _task_repr_info(task: tasks.Task) -> List[str]: ... # undocumented -def _task_get_stack(task: tasks.Task, limit: Optional[int]) -> List[FrameType]: ... # undocumented -def _task_print_stack(task: tasks.Task, limit: Optional[int], file: AnyPath): ... # undocumented +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 diff --git a/mypy/typeshed/stdlib/asyncio/compat.pyi b/mypy/typeshed/stdlib/asyncio/compat.pyi index 24d448f49dd5..2dbc03d543dc 100644 --- a/mypy/typeshed/stdlib/asyncio/compat.pyi +++ b/mypy/typeshed/stdlib/asyncio/compat.pyi @@ -1,4 +1,3 @@ - import sys from typing import List @@ -6,5 +5,4 @@ if sys.version_info < (3, 7): PY34: bool PY35: bool PY352: bool - def flatten_list_bytes(list_of_data: List[bytes]) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi index 0b28309e9ff7..14681f330f02 100644 --- a/mypy/typeshed/stdlib/asyncio/constants.pyi +++ b/mypy/typeshed/stdlib/asyncio/constants.pyi @@ -1,11 +1,9 @@ - import enum import sys LOG_THRESHOLD_FOR_CONNLOST_WRITES: int ACCEPT_RETRY_DELAY: int -if sys.version_info >= (3, 6): - DEBUG_STACK_DEPTH: int +DEBUG_STACK_DEPTH: int if sys.version_info >= (3, 7): SSL_HANDSHAKE_TIMEOUT: float SENDFILE_FALLBACK_READBUFFER_SIZE: int diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index f75dfe5f63e9..dea090682f2b 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -1,6 +1,6 @@ from typing import Any, Callable, TypeVar -_F = TypeVar('_F', bound=Callable[..., Any]) +_F = TypeVar("_F", bound=Callable[..., Any]) def coroutine(func: _F) -> _F: ... def iscoroutinefunction(func: Callable[..., Any]) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 9fc466ae5cd5..8cda63a5caec 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -1,19 +1,19 @@ -from socket import socket, _Address, _RetAddress import ssl import sys -from typing import Any, Awaitable, Callable, Dict, Generator, IO, List, Optional, Sequence, Tuple, TypeVar, Union, overload +from _typeshed import FileDescriptorLike from abc import ABCMeta, abstractmethod from asyncio.futures import Future from asyncio.protocols import BaseProtocol from asyncio.tasks import Task from asyncio.transports import BaseTransport from asyncio.unix_events import AbstractChildWatcher -from _typeshed import FileDescriptorLike +from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket +from typing import IO, Any, Awaitable, Callable, Dict, Generator, List, Optional, Sequence, Tuple, TypeVar, Union, overload if sys.version_info >= (3, 7): from contextvars import Context -_T = TypeVar('_T') +_T = TypeVar("_T") _Context = Dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] @@ -24,7 +24,9 @@ class Handle: _cancelled = False _args: Sequence[Any] if sys.version_info >= (3, 7): - def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context] = ...) -> None: ... + def __init__( + self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context] = ... + ) -> None: ... else: def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... def __repr__(self) -> str: ... @@ -35,11 +37,16 @@ class Handle: class TimerHandle(Handle): if sys.version_info >= (3, 7): - def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], - loop: AbstractEventLoop, context: Optional[Context] = ...) -> None: ... + def __init__( + self, + when: float, + callback: Callable[..., Any], + args: Sequence[Any], + loop: AbstractEventLoop, + context: Optional[Context] = ..., + ) -> None: ... else: - def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], - loop: AbstractEventLoop) -> None: ... + def __init__(self, when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... def __hash__(self) -> int: ... if sys.version_info >= (3, 7): def when(self) -> float: ... @@ -60,7 +67,6 @@ class AbstractEventLoop(metaclass=ABCMeta): slow_callback_duration: float = ... @abstractmethod def run_forever(self) -> None: ... - # Can't use a union, see mypy issue # 1873. @overload @abstractmethod @@ -68,7 +74,6 @@ class AbstractEventLoop(metaclass=ABCMeta): @overload @abstractmethod def run_until_complete(self, future: Awaitable[_T]) -> _T: ... - @abstractmethod def stop(self) -> None: ... @abstractmethod @@ -77,9 +82,8 @@ class AbstractEventLoop(metaclass=ABCMeta): def is_closed(self) -> bool: ... @abstractmethod def close(self) -> None: ... - if sys.version_info >= (3, 6): - @abstractmethod - async def shutdown_asyncgens(self) -> None: ... + @abstractmethod + async def shutdown_asyncgens(self) -> None: ... # Methods scheduling callbacks. All these return Handles. @abstractmethod def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... @@ -95,33 +99,39 @@ class AbstractEventLoop(metaclass=ABCMeta): # Tasks methods if sys.version_info >= (3, 8): @abstractmethod - 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: Optional[str] = ...) -> Task[_T]: ... else: @abstractmethod def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... @abstractmethod - def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ... + def set_task_factory( + self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]] + ) -> None: ... @abstractmethod def get_task_factory(self) -> Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]: ... # Methods for interacting with threads @abstractmethod def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... @abstractmethod - async def run_in_executor(self, executor: Any, - func: Callable[..., _T], *args: Any) -> _T: ... + def run_in_executor(self, executor: Any, func: Callable[..., _T], *args: Any) -> Awaitable[_T]: ... @abstractmethod def set_default_executor(self, executor: Any) -> None: ... # Network I/O methods returning Futures. @abstractmethod - # TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers - # https://github.com/python/mypy/issues/2509 - async def getaddrinfo(self, host: Optional[str], port: Union[str, int, None], *, - family: int = ..., type: int = ..., proto: int = ..., - flags: int = ...) -> List[Tuple[int, int, int, str, Tuple[Any, ...]]]: ... - @abstractmethod - async def getnameinfo(self, sockaddr: Tuple[Any, ...], flags: int = ...) -> Tuple[str, int]: ... + async def getaddrinfo( + self, + host: Optional[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]]]]: ... + @abstractmethod + async def getnameinfo( + self, sockaddr: Union[Tuple[str, int], Tuple[str, int, int, int]], flags: int = ... + ) -> Tuple[str, str]: ... if sys.version_info >= (3, 8): @overload @abstractmethod @@ -164,96 +174,246 @@ class AbstractEventLoop(metaclass=ABCMeta): elif sys.version_info >= (3, 7): @overload @abstractmethod - async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., - sock: None = ..., local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... @overload @abstractmethod - async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., - sock: socket, local_addr: None = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... else: @overload @abstractmethod - async def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: None = ..., - local_addr: Optional[Tuple[str, int]] = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: Optional[Tuple[str, int]] = ..., + server_hostname: Optional[str] = ..., + ) -> _TransProtPair: ... @overload @abstractmethod - async def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: socket, - local_addr: None = ..., server_hostname: Optional[str] = ...) -> _TransProtPair: ... + async def create_connection( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: Optional[str] = ..., + ) -> _TransProtPair: ... if sys.version_info >= (3, 7): @abstractmethod - async def sock_sendfile(self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, - fallback: bool = ...) -> int: ... + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: bool = ... + ) -> int: ... @overload @abstractmethod - async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., - port: int = ..., *, family: int = ..., flags: int = ..., sock: None = ..., backlog: int = ..., - ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> AbstractServer: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ..., + ) -> AbstractServer: ... @overload @abstractmethod - async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - family: int = ..., flags: int = ..., sock: socket = ..., backlog: int = ..., - ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ...) -> AbstractServer: ... - async def create_unix_connection(self, protocol_factory: _ProtocolFactory, path: Optional[str] = ..., *, ssl: _SSLContext = ..., - sock: Optional[socket] = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> _TransProtPair: ... - async def create_unix_server(self, protocol_factory: _ProtocolFactory, path: Optional[str] = ..., *, sock: Optional[socket] = ..., - backlog: int = ..., ssl: _SSLContext = ..., ssl_handshake_timeout: Optional[float] = ..., - start_serving: bool = ...) -> AbstractServer: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ..., + ) -> AbstractServer: ... + async def create_unix_connection( + self, + protocol_factory: _ProtocolFactory, + path: Optional[str] = ..., + *, + ssl: _SSLContext = ..., + sock: Optional[socket] = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> _TransProtPair: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: Optional[str] = ..., + *, + sock: Optional[socket] = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ssl_handshake_timeout: Optional[float] = ..., + start_serving: bool = ..., + ) -> AbstractServer: ... @abstractmethod - async def sendfile(self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, - fallback: bool = ...) -> int: ... + async def sendfile( + self, + transport: BaseTransport, + file: IO[bytes], + offset: int = ..., + count: Optional[int] = ..., + *, + fallback: bool = ..., + ) -> int: ... @abstractmethod - async def start_tls(self, transport: BaseTransport, protocol: BaseProtocol, sslcontext: ssl.SSLContext, *, - server_side: bool = ..., server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ...) -> BaseTransport: ... + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = ..., + server_hostname: Optional[str] = ..., + ssl_handshake_timeout: Optional[float] = ..., + ) -> BaseTransport: ... else: @overload @abstractmethod - async def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., port: int = ..., *, - family: int = ..., flags: int = ..., - sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ...) -> AbstractServer: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: Optional[Union[str, Sequence[str]]] = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ) -> AbstractServer: ... @overload @abstractmethod - async def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, - family: int = ..., flags: int = ..., - sock: socket, backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ...) -> AbstractServer: ... - async def create_unix_connection(self, protocol_factory: _ProtocolFactory, path: str, *, - ssl: _SSLContext = ..., sock: Optional[socket] = ..., - server_hostname: Optional[str] = ...) -> _TransProtPair: ... - async def create_unix_server(self, protocol_factory: _ProtocolFactory, path: str, *, - sock: Optional[socket] = ..., backlog: int = ..., ssl: _SSLContext = ...) -> AbstractServer: ... - @abstractmethod - async def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory, - local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *, - family: int = ..., proto: int = ..., flags: int = ..., - reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - allow_broadcast: Optional[bool] = ..., - sock: Optional[socket] = ...) -> _TransProtPair: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket, + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + ) -> AbstractServer: ... + async def create_unix_connection( + self, + protocol_factory: _ProtocolFactory, + path: str, + *, + ssl: _SSLContext = ..., + sock: Optional[socket] = ..., + server_hostname: Optional[str] = ..., + ) -> _TransProtPair: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: str, + *, + sock: Optional[socket] = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ) -> AbstractServer: ... + @abstractmethod + async def create_datagram_endpoint( + self, + protocol_factory: _ProtocolFactory, + local_addr: Optional[Tuple[str, int]] = ..., + remote_addr: Optional[Tuple[str, int]] = ..., + *, + family: int = ..., + proto: int = ..., + flags: int = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ..., + allow_broadcast: Optional[bool] = ..., + sock: Optional[socket] = ..., + ) -> _TransProtPair: ... # Pipes and subprocesses. @abstractmethod async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... @abstractmethod async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... @abstractmethod - async def subprocess_shell(self, protocol_factory: _ProtocolFactory, cmd: Union[bytes, str], *, stdin: Any = ..., - stdout: Any = ..., stderr: Any = ..., - **kwargs: Any) -> _TransProtPair: ... - @abstractmethod - async def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ..., - stdout: Any = ..., stderr: Any = ..., - **kwargs: Any) -> _TransProtPair: ... + async def subprocess_shell( + self, + protocol_factory: _ProtocolFactory, + cmd: Union[bytes, str], + *, + stdin: Any = ..., + stdout: Any = ..., + stderr: Any = ..., + **kwargs: Any, + ) -> _TransProtPair: ... + @abstractmethod + async def subprocess_exec( + self, + protocol_factory: _ProtocolFactory, + *args: Any, + stdin: Any = ..., + stdout: Any = ..., + stderr: Any = ..., + **kwargs: Any, + ) -> _TransProtPair: ... @abstractmethod def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... @abstractmethod @@ -327,14 +487,11 @@ class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): def get_event_loop_policy() -> AbstractEventLoopPolicy: ... def set_event_loop_policy(policy: Optional[AbstractEventLoopPolicy]) -> None: ... - def get_event_loop() -> AbstractEventLoop: ... def set_event_loop(loop: Optional[AbstractEventLoop]) -> None: ... def new_event_loop() -> AbstractEventLoop: ... - def get_child_watcher() -> AbstractChildWatcher: ... def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... - def _set_running_loop(__loop: Optional[AbstractEventLoop]) -> None: ... def _get_running_loop() -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index a1b2d09bfad7..5f2baf7b6c59 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -1,10 +1,8 @@ - -import sys import functools +import sys import traceback - -from typing import Optional, Tuple, Union, Iterable, Dict, Any, overload -from types import FunctionType, FrameType +from types import FrameType, FunctionType +from typing import Any, Dict, Iterable, Optional, Tuple, Union, overload class _HasWrapper: __wrapper__: Union[_HasWrapper, FunctionType] @@ -12,14 +10,11 @@ class _HasWrapper: _FuncType = Union[FunctionType, _HasWrapper, functools.partial, functools.partialmethod] if sys.version_info >= (3, 7): - @overload def _get_function_source(func: _FuncType) -> Tuple[str, int]: ... @overload def _get_function_source(func: object) -> Optional[Tuple[str, int]]: ... - def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... def _format_args_and_kwargs(args: Iterable[Any], kwargs: Dict[str, Any]) -> str: ... def _format_callback(func: object, args: Iterable[Any], kwargs: Dict[str, Any], suffix: str = ...) -> str: ... - def extract_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ...) -> traceback.StackSummary: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index a4f8d6710cf6..1252c02cb58d 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -1,21 +1,21 @@ import sys -from typing import Any, Union, Callable, TypeVar, Type, List, Iterable, Generator, Awaitable, Optional, Tuple +from concurrent.futures._base import Error, Future as _ConcurrentFuture +from typing import Any, Awaitable, Callable, Generator, Iterable, List, Optional, Tuple, TypeVar, Union + from .events import AbstractEventLoop -from concurrent.futures._base import ( - Future as _ConcurrentFuture, - Error, -) if sys.version_info < (3, 8): - from concurrent.futures import CancelledError as CancelledError - from concurrent.futures import TimeoutError as TimeoutError + from concurrent.futures import CancelledError as CancelledError, TimeoutError as TimeoutError class InvalidStateError(Error): ... if sys.version_info >= (3, 7): from contextvars import Context -_T = TypeVar('_T') -_S = TypeVar('_S') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_T = TypeVar("_T") +_S = TypeVar("_S") if sys.version_info < (3, 7): class _TracebackLogger: @@ -33,8 +33,6 @@ class Future(Awaitable[_T], Iterable[_T]): _exception: BaseException _blocking = False _log_traceback = False - if sys.version_info < (3, 6): - _tb_logger: Type[_TracebackLogger] def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... def __repr__(self) -> str: ... def __del__(self) -> None: ... @@ -61,5 +59,7 @@ class Future(Awaitable[_T], Iterable[_T]): def __await__(self) -> Generator[Any, None, _T]: ... @property def _loop(self) -> AbstractEventLoop: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... def wrap_future(future: Union[_ConcurrentFuture[_T], Future[_T]], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 55eabfffc3a9..7480c3394e70 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,24 +1,25 @@ import sys -from typing import Any, Callable, Iterable, Generator, Type, TypeVar, Union, Optional, Awaitable +from types import TracebackType +from typing import Any, Awaitable, Callable, Deque, Generator, Optional, Type, TypeVar, Union from .events import AbstractEventLoop from .futures import Future -from types import TracebackType - -_T = TypeVar('_T') +_T = TypeVar("_T") if sys.version_info >= (3, 9): class _ContextManagerMixin: def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... def __aenter__(self) -> Awaitable[None]: ... - def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ... + def __aexit__( + self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType] + ) -> Awaitable[None]: ... + else: class _ContextManager: def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... def __enter__(self) -> object: ... def __exit__(self, *args: Any) -> None: ... - class _ContextManagerMixin: def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... # Apparently this exists to *prohibit* use as a context manager. @@ -27,8 +28,9 @@ else: def __iter__(self) -> Generator[Any, None, _ContextManager]: ... def __await__(self) -> Generator[Any, None, _ContextManager]: ... def __aenter__(self) -> Awaitable[None]: ... - def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ... - + def __aexit__( + self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType] + ) -> Awaitable[None]: ... class Lock(_ContextManagerMixin): def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... @@ -54,10 +56,13 @@ class Condition(_ContextManagerMixin): def notify_all(self) -> None: ... class Semaphore(_ContextManagerMixin): + _value: int + _waiters: Deque[Future[Any]] def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... def locked(self) -> bool: ... async def acquire(self) -> bool: ... def release(self) -> None: ... + def _wake_up_next(self) -> None: ... class BoundedSemaphore(Semaphore): def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/log.pyi b/mypy/typeshed/stdlib/asyncio/log.pyi index 5534ebda5802..e1de0b3bb845 100644 --- a/mypy/typeshed/stdlib/asyncio/log.pyi +++ b/mypy/typeshed/stdlib/asyncio/log.pyi @@ -1,4 +1,3 @@ - import logging logger: logging.Logger diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index f5602f6fdab2..e3ebeb502f3c 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -5,31 +5,66 @@ from typing_extensions import Literal from . import base_events, constants, events, futures, streams, transports class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): - - def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Mapping[Any, Any]] = ..., + server: Optional[events.AbstractServer] = ..., + ) -> None: ... def __repr__(self) -> str: ... def __del__(self) -> None: ... def get_write_buffer_size(self) -> int: ... class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): - - def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Mapping[Any, Any]] = ..., + server: Optional[events.AbstractServer] = ..., + ) -> None: ... class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): - - def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Mapping[Any, Any]] = ..., + server: Optional[events.AbstractServer] = ..., + ) -> None: ... class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): - - def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Mapping[Any, Any]] = ..., + server: Optional[events.AbstractServer] = ..., + ) -> None: ... class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ... class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): _sendfile_compatible: constants._SendfileMode = ... - - def __init__(self, loop: events.AbstractEventLoop, sock: socket, protocol: streams.StreamReaderProtocol, waiter: Optional[futures.Future[Any]] = ..., extra: Optional[Mapping[Any, Any]] = ..., server: Optional[events.AbstractServer] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: Optional[futures.Future[Any]] = ..., + extra: Optional[Mapping[Any, Any]] = ..., + server: Optional[events.AbstractServer] = ..., + ) -> None: ... def _set_extra(self, sock: socket) -> None: ... def can_write_eof(self) -> Literal[True]: ... def write_eof(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/protocols.pyi b/mypy/typeshed/stdlib/asyncio/protocols.pyi index 710fad75e193..ec89a299956f 100644 --- a/mypy/typeshed/stdlib/asyncio/protocols.pyi +++ b/mypy/typeshed/stdlib/asyncio/protocols.pyi @@ -1,6 +1,6 @@ import sys from asyncio import transports -from typing import Optional, Tuple, Union +from typing import Optional, Tuple class BaseProtocol: def connection_made(self, transport: transports.BaseTransport) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index 75340e67e2e7..2d4bada035b3 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -1,10 +1,14 @@ +import sys from asyncio.events import AbstractEventLoop -from typing import Generic, TypeVar, Optional +from typing import Any, Generic, Optional, TypeVar + +if sys.version_info >= (3, 9): + from types import GenericAlias class QueueEmpty(Exception): ... class QueueFull(Exception): ... -_T = TypeVar('_T') +_T = TypeVar("_T") class Queue(Generic[_T]): def __init__(self, maxsize: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... @@ -23,11 +27,10 @@ class Queue(Generic[_T]): def put_nowait(self, item: _T) -> None: ... async def get(self) -> _T: ... def get_nowait(self) -> _T: ... - async def join(self) -> bool: ... + async def join(self) -> None: ... def task_done(self) -> None: ... - + if sys.version_info >= (3, 9): + def __class_getitem__(cls, type: Any) -> GenericAlias: ... class PriorityQueue(Queue[_T]): ... - - class LifoQueue(Queue[_T]): ... diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 7d8c28c0d7d4..1628cb3e89f1 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -1,9 +1,10 @@ import sys - if sys.version_info >= (3, 7): - from typing import Awaitable, TypeVar - - _T = TypeVar('_T') + from typing import Awaitable, Optional, TypeVar - def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... + _T = TypeVar("_T") + if sys.version_info >= (3, 8): + def run(main: Awaitable[_T], *, debug: Optional[bool] = ...) -> _T: ... + else: + def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 18bf1d874681..8d1c44aee7e8 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -1,15 +1,9 @@ - -import sys import ssl - -from typing import ClassVar, Optional, List, Tuple, Callable, Dict, Any, Deque +import sys +from typing import Any, Callable, ClassVar, Deque, Dict, List, Optional, Tuple from typing_extensions import Literal -from . import transports -from . import constants -from . import events -from . import protocols -from . import futures +from . import constants, events, futures, protocols, transports def _create_transport_context(server_side: bool, server_hostname: Optional[str]) -> ssl.SSLContext: ... @@ -32,9 +26,7 @@ class _SSLPipe: _need_ssldata: bool _handshake_cb: Optional[Callable[[Optional[BaseException]], None]] _shutdown_cb: Optional[Callable[[], None]] - def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: Optional[str] = ...) -> None: ... - @property def context(self) -> ssl.SSLContext: ... @property @@ -43,7 +35,6 @@ class _SSLPipe: def need_ssldata(self) -> bool: ... @property def wrapped(self) -> bool: ... - def do_handshake(self, callback: Optional[Callable[[Optional[BaseException]], None]] = ...) -> List[bytes]: ... def shutdown(self, callback: Optional[Callable[[], None]] = ...) -> List[bytes]: ... def feed_eof(self) -> None: ... @@ -57,12 +48,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): _loop: events.AbstractEventLoop _ssl_protocol: SSLProtocol _closed: bool - - if sys.version_info >= (3, 6): - def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... - else: - def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol, app_protocol: protocols.BaseProtocol) -> None: ... - + def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... def get_extra_info(self, name: str, default: Optional[Any] = ...) -> Dict[str, Any]: ... def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... def get_protocol(self) -> protocols.BaseProtocol: ... @@ -89,7 +75,7 @@ class SSLProtocol(protocols.Protocol): _extra: Dict[str, Any] _write_backlog: Deque[Tuple[bytes, int]] _write_buffer_size: int - _waiter: futures.Future + _waiter: futures.Future[Any] _loop: events.AbstractEventLoop _app_transport: _SSLProtocolTransport _sslpipe: Optional[_SSLPipe] @@ -103,12 +89,28 @@ class SSLProtocol(protocols.Protocol): _app_protocol_is_buffer: bool if sys.version_info >= (3, 7): - def __init__(self, loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future, - server_side: bool = ..., server_hostname: Optional[str] = ..., call_connection_made: bool = ..., ssl_handshake_timeout: Optional[int] = ...) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + app_protocol: protocols.BaseProtocol, + sslcontext: ssl.SSLContext, + waiter: futures.Future[Any], + server_side: bool = ..., + server_hostname: Optional[str] = ..., + call_connection_made: bool = ..., + ssl_handshake_timeout: Optional[int] = ..., + ) -> None: ... else: - def __init__(self, loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, waiter: futures.Future, - server_side: bool = ..., server_hostname: Optional[str] = ..., call_connection_made: bool = ...) -> None: ... - + def __init__( + self, + loop: events.AbstractEventLoop, + app_protocol: protocols.BaseProtocol, + sslcontext: ssl.SSLContext, + waiter: futures.Future, + server_side: bool = ..., + server_hostname: Optional[str] = ..., + call_connection_made: bool = ..., + ) -> None: ... if sys.version_info >= (3, 7): def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... def _wakeup_waiter(self, exc: Optional[BaseException] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/staggered.pyi b/mypy/typeshed/stdlib/asyncio/staggered.pyi index 3ba73b11b089..057883e0ab2c 100644 --- a/mypy/typeshed/stdlib/asyncio/staggered.pyi +++ b/mypy/typeshed/stdlib/asyncio/staggered.pyi @@ -1,7 +1,12 @@ - import sys -from typing import Iterable, Callable, Awaitable, Optional, Tuple, Any, List +from typing import Any, Awaitable, Callable, Iterable, List, Optional, Tuple + from . import events if sys.version_info >= (3, 8): - async def staggered_race(coro_fns: Iterable[Callable[[], Awaitable]], delay: Optional[float], *, loop: Optional[events.AbstractEventLoop] = ...) -> Tuple[Any, Optional[int], List[Optional[Exception]]]: ... + async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[Any]]], + delay: Optional[float], + *, + loop: Optional[events.AbstractEventLoop] = ..., + ) -> Tuple[Any, Optional[int], List[Optional[Exception]]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index b691798ab454..36aafedd7aa3 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,9 +1,7 @@ import sys -from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union +from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional, Tuple, Union -from . import events -from . import protocols -from . import transports +from . import events, protocols, transports _ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] @@ -12,7 +10,6 @@ if sys.version_info < (3, 8): expected: Optional[int] partial: bytes def __init__(self, partial: bytes, expected: Optional[int]) -> None: ... - class LimitOverrunError(Exception): consumed: int def __init__(self, message: str, consumed: int) -> None: ... @@ -24,9 +21,8 @@ async def open_connection( loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., ssl_handshake_timeout: Optional[float] = ..., - **kwds: Any + **kwds: Any, ) -> Tuple[StreamReader, StreamWriter]: ... - async def start_server( client_connected_cb: _ClientConnectedCallback, host: Optional[str] = ..., @@ -35,50 +31,50 @@ async def start_server( loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., ssl_handshake_timeout: Optional[float] = ..., - **kwds: Any + **kwds: Any, ) -> events.AbstractServer: ... -if sys.platform != 'win32': +if sys.platform != "win32": if sys.version_info >= (3, 7): from os import PathLike + _PathType = Union[str, PathLike[str]] else: _PathType = str - async def open_unix_connection( - path: Optional[_PathType] = ..., - *, - loop: Optional[events.AbstractEventLoop] = ..., - limit: int = ..., - **kwds: Any + path: Optional[_PathType] = ..., *, loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., **kwds: Any ) -> Tuple[StreamReader, StreamWriter]: ... - async def start_unix_server( client_connected_cb: _ClientConnectedCallback, path: Optional[_PathType] = ..., *, loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., - **kwds: Any) -> events.AbstractServer: ... + **kwds: Any, + ) -> events.AbstractServer: ... class FlowControlMixin(protocols.Protocol): ... class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): - def __init__(self, - stream_reader: StreamReader, - client_connected_cb: Optional[_ClientConnectedCallback] = ..., - loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def __init__( + self, + stream_reader: StreamReader, + client_connected_cb: Optional[_ClientConnectedCallback] = ..., + loop: Optional[events.AbstractEventLoop] = ..., + ) -> None: ... def connection_made(self, transport: transports.BaseTransport) -> None: ... def connection_lost(self, exc: Optional[Exception]) -> None: ... def data_received(self, data: bytes) -> None: ... def eof_received(self) -> bool: ... class StreamWriter: - def __init__(self, - transport: transports.BaseTransport, - protocol: protocols.BaseProtocol, - reader: Optional[StreamReader], - loop: events.AbstractEventLoop) -> None: ... + def __init__( + self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + reader: Optional[StreamReader], + loop: events.AbstractEventLoop, + ) -> None: ... @property def transport(self) -> transports.BaseTransport: ... def write(self, data: bytes) -> None: ... @@ -93,9 +89,7 @@ class StreamWriter: async def drain(self) -> None: ... class StreamReader: - def __init__(self, - limit: int = ..., - loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def __init__(self, limit: int = ..., loop: Optional[events.AbstractEventLoop] = ...) -> None: ... def exception(self) -> Exception: ... def set_exception(self, exc: Exception) -> None: ... def set_transport(self, transport: transports.BaseTransport) -> None: ... @@ -106,3 +100,5 @@ class StreamReader: async def readuntil(self, separator: bytes = ...) -> bytes: ... async def read(self, n: int = ...) -> bytes: ... async def readexactly(self, n: int) -> bytes: ... + def __aiter__(self) -> AsyncIterator[bytes]: ... + async def __anext__(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index ef4544247400..58e1bd40d0eb 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -1,12 +1,10 @@ import sys -from asyncio import events -from asyncio import protocols -from asyncio import streams -from asyncio import transports -from typing import Any, Optional, Tuple, Union, IO +from asyncio import events, protocols, streams, transports +from typing import IO, Any, Optional, Tuple, Union if sys.version_info >= (3, 8): from os import PathLike + _ExecArg = Union[str, bytes, PathLike[str], PathLike[bytes]] else: _ExecArg = Union[str, bytes] # Union used instead of AnyStr due to mypy issue #1236 @@ -15,8 +13,7 @@ PIPE: int STDOUT: int DEVNULL: int -class SubprocessStreamProtocol(streams.FlowControlMixin, - protocols.SubprocessProtocol): +class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol): stdin: Optional[streams.StreamWriter] stdout: Optional[streams.StreamReader] stderr: Optional[streams.StreamReader] @@ -26,16 +23,14 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, def pipe_connection_lost(self, fd: int, exc: Optional[Exception]) -> None: ... def process_exited(self) -> None: ... - class Process: stdin: Optional[streams.StreamWriter] stdout: Optional[streams.StreamReader] stderr: Optional[streams.StreamReader] pid: int - def __init__(self, - transport: transports.BaseTransport, - protocol: protocols.BaseProtocol, - loop: events.AbstractEventLoop) -> None: ... + def __init__( + self, transport: transports.BaseTransport, protocol: protocols.BaseProtocol, loop: events.AbstractEventLoop + ) -> None: ... @property def returncode(self) -> Optional[int]: ... async def wait(self) -> int: ... @@ -44,7 +39,6 @@ class Process: def kill(self) -> None: ... async def communicate(self, input: Optional[bytes] = ...) -> Tuple[bytes, bytes]: ... - async def create_subprocess_shell( cmd: Union[str, bytes], # Union used instead of AnyStr due to mypy issue #1236 stdin: Union[int, IO[Any], None] = ..., @@ -52,9 +46,8 @@ async def create_subprocess_shell( stderr: Union[int, IO[Any], None] = ..., loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., - **kwds: Any + **kwds: Any, ) -> Process: ... - async def create_subprocess_exec( program: _ExecArg, *args: _ExecArg, @@ -63,5 +56,5 @@ async def create_subprocess_exec( stderr: Union[int, IO[Any], None] = ..., loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., - **kwds: Any + **kwds: Any, ) -> Process: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 7f73bb2a4489..0c148fa1ad6d 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -1,29 +1,48 @@ import concurrent.futures import sys +from types import FrameType from typing import ( - Any, TypeVar, Set, List, TextIO, Union, Tuple, Generic, Generator, Iterable, Awaitable, overload, Iterator, Optional, + Any, + Awaitable, + Generator, + Generic, + Iterable, + Iterator, + List, + Optional, + Set, + TextIO, + Tuple, + TypeVar, + Union, + overload, ) from typing_extensions import Literal -from types import FrameType + from .events import AbstractEventLoop from .futures import Future -_T = TypeVar('_T') -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_T3 = TypeVar('_T3') -_T4 = TypeVar('_T4') -_T5 = TypeVar('_T5') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") _FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] +_TaskYieldType = Optional[Future[object]] FIRST_EXCEPTION: str FIRST_COMPLETED: str ALL_COMPLETED: str -def as_completed(fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., - timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... -def ensure_future(coro_or_future: _FutureT[_T], - *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def as_completed( + fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ... +) -> Iterator[Future[_T]]: ... +def ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... + # Prior to Python 3.7 'async' was an alias for 'ensure_future'. # It became a keyword in 3.7. @@ -32,76 +51,132 @@ def ensure_future(coro_or_future: _FutureT[_T], # zip() because typing does not support variadic type variables. See # typing PR #1550 for discussion. @overload -def gather(coro_or_future1: _FutureT[_T1], - *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1]]: ... +def gather( + coro_or_future1: _FutureT[_T1], *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ... +) -> Future[Tuple[_T1]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], - *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - *, loop: Optional[AbstractEventLoop] = ..., - return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, loop: Optional[AbstractEventLoop] = ..., - return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3, _T4]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3, _T4]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], coro_or_future5: _FutureT[_T5], - *, loop: Optional[AbstractEventLoop] = ..., - return_exceptions: Literal[False] = ...) -> Future[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + coro_or_future5: _FutureT[_T5], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: Literal[False] = ..., +) -> Future[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload -def gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], - coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], - *coros_or_futures: _FutureT[Any], - loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[List[Any]]: ... +def gather( + coro_or_future1: _FutureT[Any], + coro_or_future2: _FutureT[Any], + coro_or_future3: _FutureT[Any], + coro_or_future4: _FutureT[Any], + coro_or_future5: _FutureT[Any], + coro_or_future6: _FutureT[Any], + *coros_or_futures: _FutureT[Any], + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[List[Any]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], - *, loop: Optional[AbstractEventLoop] = ..., - return_exceptions: bool = ...) -> Future[Tuple[Union[_T1, BaseException]]]: ... +def gather( + coro_or_future1: _FutureT[_T1], *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ... +) -> Future[Tuple[Union[_T1, BaseException]]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], - *, loop: Optional[AbstractEventLoop] = ..., - return_exceptions: bool = ...) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException]]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException]]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ - Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException]]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException]]]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ - Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[ + Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] +]: ... @overload -def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], coro_or_future5: _FutureT[_T5], - *, loop: Optional[AbstractEventLoop] = ..., return_exceptions: bool = ...) -> Future[ - Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException], Union[_T5, BaseException]]]: ... -def run_coroutine_threadsafe(coro: _FutureT[_T], - loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def gather( + coro_or_future1: _FutureT[_T1], + coro_or_future2: _FutureT[_T2], + coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + coro_or_future5: _FutureT[_T5], + *, + loop: Optional[AbstractEventLoop] = ..., + return_exceptions: bool = ..., +) -> Future[ + Tuple[ + Union[_T1, BaseException], + Union[_T2, BaseException], + Union[_T3, BaseException], + Union[_T4, BaseException], + Union[_T5, BaseException], + ] +]: ... +def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... def shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... def sleep(delay: float, result: _T = ..., *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... -def wait(fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., - return_when: str = ...) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... -def wait_for(fut: _FutureT[_T], timeout: Optional[float], - *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +def wait( + fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., return_when: str = ... +) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... +def wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... class Task(Future[_T], Generic[_T]): - @classmethod - def current_task(cls, loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... - @classmethod - def all_tasks(cls, loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... if sys.version_info >= (3, 8): def __init__( self, - coro: Union[Generator[Any, None, _T], Awaitable[_T]], + coro: Union[Generator[_TaskYieldType, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ..., name: Optional[str] = ..., ) -> None: ... else: - def __init__(self, coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ...) -> None: ... + def __init__( + self, coro: Union[Generator[_TaskYieldType, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ... + ) -> None: ... def __repr__(self) -> str: ... if sys.version_info >= (3, 8): def get_coro(self) -> Any: ... @@ -113,15 +188,22 @@ class Task(Future[_T], Generic[_T]): def cancel(self, msg: Optional[str] = ...) -> bool: ... else: def cancel(self) -> bool: ... + if sys.version_info < (3, 9): + @classmethod + def current_task(cls, loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... + @classmethod + def all_tasks(cls, loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... if sys.version_info < (3, 7): def _wakeup(self, fut: Future[Any]) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 7): def all_tasks(loop: Optional[AbstractEventLoop] = ...) -> Set[Task[Any]]: ... if sys.version_info >= (3, 8): def create_task( - coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, name: Optional[str] = ..., + coro: Union[Generator[_TaskYieldType, None, _T], Awaitable[_T]], *, name: Optional[str] = ... ) -> Task[_T]: ... else: - def create_task(coro: Union[Generator[Any, None, _T], Awaitable[_T]]) -> Task[_T]: ... + def create_task(coro: Union[Generator[_TaskYieldType, None, _T], Awaitable[_T]]) -> Task[_T]: ... def current_task(loop: Optional[AbstractEventLoop] = ...) -> Optional[Task[Any]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index 52e9a63ac0cc..3f798d8ac862 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -1,7 +1,7 @@ import sys from typing import Any, Callable, TypeVar -_T = TypeVar('_T') +_T = TypeVar("_T") if sys.version_info >= (3, 9): async def to_thread(__func: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index 863da761f20b..636ac36301c1 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -1,17 +1,16 @@ import sys -from socket import _Address -from typing import Any, Mapping, List, Optional, Tuple -from asyncio.protocols import BaseProtocol from asyncio.events import AbstractEventLoop +from asyncio.protocols import BaseProtocol +from socket import _Address +from typing import Any, List, Mapping, Optional, Tuple class BaseTransport: def __init__(self, extra: Optional[Mapping[Any, Any]] = ...) -> None: ... def get_extra_info(self, name: Any, default: Any = ...) -> Any: ... def is_closing(self) -> bool: ... def close(self) -> None: ... - if sys.version_info >= (3, 5): - def set_protocol(self, protocol: BaseProtocol) -> None: ... - def get_protocol(self) -> BaseProtocol: ... + def set_protocol(self, protocol: BaseProtocol) -> None: ... + def get_protocol(self) -> BaseProtocol: ... class ReadTransport(BaseTransport): if sys.version_info >= (3, 7): @@ -20,9 +19,7 @@ class ReadTransport(BaseTransport): def resume_reading(self) -> None: ... class WriteTransport(BaseTransport): - def set_write_buffer_limits( - self, high: Optional[int] = ..., low: Optional[int] = ... - ) -> None: ... + def set_write_buffer_limits(self, high: Optional[int] = ..., low: Optional[int] = ...) -> None: ... def get_write_buffer_size(self) -> int: ... def write(self, data: Any) -> None: ... def writelines(self, list_of_data: List[Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 9dbefbe8c8c1..db9efb08b585 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -1,8 +1,7 @@ - -import sys import socket -from typing import Union, NoReturn, Tuple, Optional, Iterable, List, Any, BinaryIO, Type, overload +import sys from types import TracebackType +from typing import Any, BinaryIO, Iterable, List, NoReturn, Optional, Tuple, Type, Union, overload if sys.version_info >= (3, 8): # These are based in socket, maybe move them out into _typeshed.pyi or such @@ -10,7 +9,6 @@ if sys.version_info >= (3, 8): _RetAddress = Any _WriteBuffer = Union[bytearray, memoryview] _CMSG = Tuple[int, int, bytes] - class TransportSocket: def __init__(self, sock: socket.socket) -> None: ... def _na(self, what: str) -> None: ... @@ -40,20 +38,26 @@ if sys.version_info >= (3, 8): def connect(self, address: Union[_Address, bytes]) -> None: ... def connect_ex(self, address: Union[_Address, bytes]) -> int: ... def bind(self, address: Union[_Address, bytes]) -> None: ... - if sys.platform == 'win32': + if sys.platform == "win32": def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> None: ... else: def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> NoReturn: ... def listen(self, __backlog: int = ...) -> None: ... def makefile(self) -> BinaryIO: ... - def sendfile(self, file, offset: int = ..., count: Optional[int] = ...) -> int: ... + def sendfile(self, file: BinaryIO, offset: int = ..., count: Optional[int] = ...) -> int: ... def close(self) -> None: ... def detach(self) -> int: ... if sys.platform == "linux": - def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> int: ... + def sendmsg_afalg( + self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + ) -> int: ... else: - def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> NoReturn: ... - def sendmsg(self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ...) -> int: ... + def sendmsg_afalg( + self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + ) -> NoReturn: ... + def sendmsg( + self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... + ) -> int: ... @overload def sendto(self, data: bytes, address: _Address) -> int: ... @overload @@ -61,13 +65,15 @@ if sys.version_info >= (3, 8): def send(self, data: bytes, flags: int = ...) -> int: ... def sendall(self, data: bytes, flags: int = ...) -> None: ... def set_inheritable(self, inheritable: bool) -> None: ... - if sys.platform == 'win32': + if sys.platform == "win32": def share(self, process_id: int) -> bytes: ... else: def share(self, process_id: int) -> NoReturn: ... def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... - def recvmsg_into(self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ...) -> Tuple[int, List[_CMSG], int, Any]: ... + def recvmsg_into( + self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... + ) -> Tuple[int, List[_CMSG], int, Any]: ... def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> Tuple[bytes, List[_CMSG], int, Any]: ... def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... @@ -75,4 +81,6 @@ if sys.version_info >= (3, 8): def gettimeout(self) -> Optional[float]: ... def setblocking(self, flag: bool) -> None: ... def __enter__(self) -> socket.socket: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 3dddf555ea06..7d3c1b208a35 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -5,9 +5,9 @@ from typing import Any, Callable, Optional, Type, TypeVar from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy from .selector_events import BaseSelectorEventLoop -_T1 = TypeVar('_T1', bound=AbstractChildWatcher) -_T2 = TypeVar('_T2', bound=SafeChildWatcher) -_T3 = TypeVar('_T3', bound=FastChildWatcher) +_T1 = TypeVar("_T1", bound=AbstractChildWatcher) +_T2 = TypeVar("_T2", bound=SafeChildWatcher) +_T3 = TypeVar("_T3", bound=FastChildWatcher) class AbstractChildWatcher: def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... @@ -44,8 +44,8 @@ if sys.version_info >= (3, 8): from typing import Protocol - _T4 = TypeVar('_T4', bound=MultiLoopChildWatcher) - _T5 = TypeVar('_T5', bound=ThreadedChildWatcher) + _T4 = TypeVar("_T4", bound=MultiLoopChildWatcher) + _T5 = TypeVar("_T5", bound=ThreadedChildWatcher) class _Warn(Protocol): def __call__( self, message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ... diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index bf7c9380b266..e6009d58ebc7 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -1,12 +1,9 @@ - import sys -from typing import Tuple, Callable, Optional, Type, Protocol from types import TracebackType - +from typing import Callable, Optional, Protocol, Tuple, Type class _WarnFunction(Protocol): - def __call__(self, message: str, category: Type[Warning], source: PipeHandle): ... - + def __call__(self, message: str, category: Type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ...) -> None: ... BUFSIZE: int PIPE: int @@ -15,7 +12,6 @@ STDOUT: int def pipe(*, duplex: bool = ..., overlapped: Tuple[bool, bool] = ..., bufsize: int = ...) -> Tuple[int, int]: ... class PipeHandle: - def __init__(self, handle: int) -> None: ... def __repr__(self) -> str: ... if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 742ac77e2849..a05a205115f3 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -1,9 +1,7 @@ -from typing import Tuple, Union, Any, Dict, overload - import sys -from socket import SocketType -from typing import Optional 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] @@ -22,7 +20,6 @@ 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: @@ -34,7 +31,6 @@ class dispatcher: 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: ... @@ -50,7 +46,6 @@ class dispatcher: 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: ... @@ -64,34 +59,26 @@ 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: ... + 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: - ... - + 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: ... @@ -116,22 +103,17 @@ 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/atexit.pyi b/mypy/typeshed/stdlib/atexit.pyi index 24f93899d5d2..f068a3ded323 100644 --- a/mypy/typeshed/stdlib/atexit.pyi +++ b/mypy/typeshed/stdlib/atexit.pyi @@ -1,5 +1,3 @@ -"""Stub file for the 'atexit' module.""" - from typing import Any, Callable def _clear() -> None: ... diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index a6885d277cce..606f4b9f5f7e 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -1,4 +1,4 @@ -from typing import Any, Optional, Tuple +from typing import Optional, Tuple AdpcmState = Tuple[int, int] RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index d61cb3acd895..01be704aa71c 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -1,7 +1,5 @@ -# Stubs for base64 - -from typing import IO, Optional, Text, Union import sys +from typing import IO, Optional, Union if sys.version_info < (3,): _encodable = Union[bytes, unicode] @@ -11,30 +9,29 @@ else: _decodable = Union[bytes, str] def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... -def b64decode(s: _decodable, altchars: Optional[bytes] = ..., - validate: bool = ...) -> 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 b32decode(s: _decodable, casefold: bool = ..., map01: Optional[bytes] = ...) -> bytes: ... def b16encode(s: _encodable) -> bytes: ... def b16decode(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 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 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: ... + if sys.version_info < (3, 9): def encodestring(s: bytes) -> bytes: ... def decodestring(s: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 1f7f7f335b16..9d76b3afde22 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,7 +1,5 @@ - -from typing import Set, Dict, Iterable, Any, Callable, Mapping, Tuple, Type, SupportsInt, List, Union, TypeVar, Optional, IO -from types import FrameType, TracebackType, CodeType - +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 @@ -22,7 +20,6 @@ class Bdb: 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: ... @@ -47,7 +44,9 @@ class Bdb: 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 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: ... @@ -63,7 +62,9 @@ class Bdb: 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 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: @@ -82,8 +83,9 @@ class Breakpoint: ignore: int hits: int number: int - - def __init__(self, file: str, line: int, temporary: bool = ..., cond: Optional[str] = ..., funcname: Optional[str] = ...) -> None: ... + 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: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 7e023c239f46..d4141b9c4656 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,9 +1,5 @@ -# Stubs for binascii - -# Based on http://docs.python.org/3.2/library/binascii.html - import sys -from typing import Union, Text +from typing import Text, Union if sys.version_info < (3,): # Python 2 accepts unicode ascii pretty much everywhere. @@ -16,15 +12,21 @@ else: _Ascii = Union[bytes, str] def a2b_uu(__data: _Ascii) -> 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: ... + 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: ... @@ -34,10 +36,13 @@ 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 a2b_hex(__hexstr: _Ascii) -> bytes: ... def unhexlify(__hexstr: _Ascii) -> bytes: ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index c759ba0b6f19..02d094faf923 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,10 +1,4 @@ -from typing import ( - Any, - IO, - Tuple, - Union, -) - +from typing import IO, Any, Tuple, Union class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/bisect.pyi b/mypy/typeshed/stdlib/bisect.pyi index 67cf11dd2535..60dfc48d69bd 100644 --- a/mypy/typeshed/stdlib/bisect.pyi +++ b/mypy/typeshed/stdlib/bisect.pyi @@ -1,4 +1,4 @@ -# Stubs for bisect from _bisect import * + bisect = bisect_right insort = insort_right diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index c644038d1446..939effa782a4 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1,30 +1,62 @@ -# True and False are deliberately omitted because they are keywords in -# Python 3, and stub files conform to Python 3 syntax. - +import sys +from _typeshed import ( + AnyPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + SupportsKeysAndGetItem, + SupportsLessThan, + SupportsLessThanT, + SupportsWrite, +) +from ast import AST, mod +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from types import CodeType, TracebackType from typing import ( - TypeVar, Iterator, Iterable, NoReturn, overload, Container, - Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, - Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, - SupportsComplex, IO, BinaryIO, Union, - ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, + IO, + AbstractSet, + Any, + BinaryIO, + ByteString, + Callable, + Container, + Dict, + FrozenSet, + Generic, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + NoReturn, + Optional, Protocol, -) -from abc import ABCMeta -from ast import mod, AST -from io import ( - TextIOWrapper, FileIO, BufferedRandom, BufferedReader, BufferedWriter -) -from types import TracebackType, CodeType -from _typeshed import ( - AnyPath, OpenBinaryMode, OpenTextMode, - OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenBinaryModeReading, - SupportsWrite, ReadableBuffer, + Reversible, + Sequence, + Set, + Sized, + SupportsAbs, + SupportsBytes, + SupportsComplex, + SupportsFloat, + SupportsInt, + SupportsRound, + Tuple, + Type, + TypeVar, + Union, + ValuesView, + overload, + runtime_checkable, ) from typing_extensions import Literal -import sys - -if sys.version_info >= (3,): - from typing import SupportsBytes, SupportsRound if sys.version_info >= (3, 9): from types import GenericAlias @@ -32,30 +64,28 @@ if sys.version_info >= (3, 9): class _SupportsIndex(Protocol): def __index__(self) -> int: ... -class _SupportsLessThan(Protocol): - def __lt__(self, other: Any) -> bool: ... - -_T = TypeVar('_T') -_T_co = TypeVar('_T_co', covariant=True) -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') -_S = TypeVar('_S') -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_T3 = TypeVar('_T3') -_T4 = TypeVar('_T4') -_T5 = TypeVar('_T5') -_TT = TypeVar('_TT', bound='type') -_LT = TypeVar('_LT', bound=_SupportsLessThan) +class _SupportsTrunc(Protocol): + def __trunc__(self) -> int: ... + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_TT = TypeVar("_TT", bound="type") +_TBE = TypeVar("_TBE", bound="BaseException") class object: __doc__: Optional[str] __dict__: Dict[str, Any] - __slots__: Union[Text, Iterable[Text]] + __slots__: Union[str, Iterable[str]] __module__: str - if sys.version_info >= (3, 6): - __annotations__: Dict[str, Any] - + __annotations__: Dict[str, Any] @property def __class__(self: _T) -> Type[_T]: ... @__class__.setter @@ -74,25 +104,19 @@ class object: def __sizeof__(self) -> int: ... def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... - if sys.version_info >= (3,): - def __dir__(self) -> Iterable[str]: ... - if sys.version_info >= (3, 6): - def __init_subclass__(cls) -> None: ... + def __dir__(self) -> Iterable[str]: ... + def __init_subclass__(cls) -> None: ... class staticmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] - if sys.version_info >= (3,): - __isabstractmethod__: bool - + __isabstractmethod__: bool def __init__(self, f: Callable[..., Any]) -> None: ... def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... class classmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] - if sys.version_info >= (3,): - __isabstractmethod__: bool - + __isabstractmethod__: bool def __init__(self, f: Callable[..., Any]) -> None: ... def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... @@ -108,19 +132,17 @@ class type(object): __module__: str __mro__: Tuple[type, ...] __name__: str - if sys.version_info >= (3,): - __qualname__: str - __text_signature__: Optional[str] + __qualname__: str + __text_signature__: Optional[str] __weakrefoffset__: int - @overload def __init__(self, o: object) -> None: ... @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any], **kwds: Any) -> None: ... @overload def __new__(cls, o: object) -> type: ... @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any], **kwds: Any) -> type: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _TT) -> List[_TT]: ... # Note: the documentation doesnt specify what the return type is, the standard @@ -128,32 +150,22 @@ class type(object): def mro(self) -> List[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... def __subclasscheck__(self, subclass: type) -> bool: ... - if sys.version_info >= (3,): - @classmethod - def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... class super(object): - if sys.version_info >= (3,): - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... - @overload - def __init__(self) -> None: ... - else: - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... class int: @overload - def __init__(self, x: Union[Text, bytes, SupportsInt, _SupportsIndex] = ...) -> None: ... + def __new__(cls: Type[_T], x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc] = ...) -> _T: ... @overload - def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... - + def __new__(cls: Type[_T], x: Union[str, bytes, bytearray], base: int) -> _T: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... @property @@ -165,20 +177,16 @@ class int: @property def denominator(self) -> int: ... def conjugate(self) -> int: ... - def bit_length(self) -> int: ... - if sys.version_info >= (3,): - def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... - @classmethod - def from_bytes(cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, - signed: bool = ...) -> int: ... # TODO buffer object argument - + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes( + cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, signed: bool = ... + ) -> int: ... # TODO buffer object argument def __add__(self, x: int) -> int: ... def __sub__(self, x: int) -> int: ... def __mul__(self, x: int) -> int: ... def __floordiv__(self, x: int) -> int: ... - if sys.version_info < (3,): - def __div__(self, x: int) -> int: ... def __truediv__(self, x: int) -> float: ... def __mod__(self, x: int) -> int: ... def __divmod__(self, x: int) -> Tuple[int, int]: ... @@ -186,11 +194,12 @@ class int: def __rsub__(self, x: int) -> int: ... def __rmul__(self, x: int) -> int: ... def __rfloordiv__(self, x: int) -> int: ... - if sys.version_info < (3,): - def __rdiv__(self, x: int) -> int: ... def __rtruediv__(self, x: int) -> float: ... def __rmod__(self, x: int) -> int: ... def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + @overload + def __pow__(self, __x: Literal[2], __modulo: Optional[int] = ...) -> int: ... + @overload def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... def __and__(self, n: int) -> int: ... @@ -207,72 +216,63 @@ class int: def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... - if sys.version_info >= (3,): - def __ceil__(self) -> int: ... - def __floor__(self) -> int: ... - def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + def __round__(self, ndigits: Optional[int] = ...) -> int: ... def __getnewargs__(self) -> Tuple[int]: ... - def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: int) -> bool: ... def __le__(self, x: int) -> bool: ... def __gt__(self, x: int) -> bool: ... def __ge__(self, x: int) -> bool: ... - def __str__(self) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... def __index__(self) -> int: ... class float: - def __init__(self, x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> None: ... + def __new__(cls: Type[_T], x: Union[SupportsFloat, _SupportsIndex, str, bytes, bytearray] = ...) -> _T: ... def as_integer_ratio(self) -> Tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod def fromhex(cls, __s: str) -> float: ... - @property def real(self) -> float: ... @property def imag(self) -> float: ... def conjugate(self) -> float: ... - def __add__(self, x: float) -> float: ... def __sub__(self, x: float) -> float: ... def __mul__(self, x: float) -> float: ... def __floordiv__(self, x: float) -> float: ... - if sys.version_info < (3,): - def __div__(self, x: float) -> float: ... def __truediv__(self, x: float) -> float: ... def __mod__(self, x: float) -> float: ... def __divmod__(self, x: float) -> Tuple[float, float]: ... - def __pow__(self, x: float, mod: None = ...) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __pow__( + self, x: float, mod: None = ... + ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole def __radd__(self, x: float) -> float: ... def __rsub__(self, x: float) -> float: ... def __rmul__(self, x: float) -> float: ... def __rfloordiv__(self, x: float) -> float: ... - if sys.version_info < (3,): - def __rdiv__(self, x: float) -> float: ... def __rtruediv__(self, x: float) -> float: ... def __rmod__(self, x: float) -> float: ... def __rdivmod__(self, x: float) -> Tuple[float, float]: ... def __rpow__(self, x: float, mod: None = ...) -> float: ... def __getnewargs__(self) -> Tuple[float]: ... def __trunc__(self) -> int: ... - if sys.version_info >= (3,): - @overload - def __round__(self, ndigits: None = ...) -> int: ... - @overload - def __round__(self, ndigits: int) -> float: ... - + if sys.version_info >= (3, 9): + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + @overload + def __round__(self, ndigits: None = ...) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: float) -> bool: ... @@ -281,286 +281,116 @@ class float: def __ge__(self, x: float) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... - def __str__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... class complex: @overload - def __init__(self, real: float = ..., imag: float = ...) -> None: ... + def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... @overload - def __init__(self, real: Union[str, SupportsComplex, _SupportsIndex]) -> None: ... - + def __new__(cls: Type[_T], real: Union[str, SupportsComplex, _SupportsIndex]) -> _T: ... @property def real(self) -> float: ... @property def imag(self) -> float: ... - def conjugate(self) -> complex: ... - def __add__(self, x: complex) -> complex: ... def __sub__(self, x: complex) -> complex: ... def __mul__(self, x: complex) -> complex: ... def __pow__(self, x: complex, mod: None = ...) -> complex: ... - if sys.version_info < (3,): - def __div__(self, x: complex) -> complex: ... def __truediv__(self, x: complex) -> complex: ... def __radd__(self, x: complex) -> complex: ... def __rsub__(self, x: complex) -> complex: ... def __rmul__(self, x: complex) -> complex: ... def __rpow__(self, x: complex, mod: None = ...) -> complex: ... - if sys.version_info < (3,): - def __rdiv__(self, x: complex) -> complex: ... def __rtruediv__(self, x: complex) -> complex: ... - def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... - def __complex__(self) -> complex: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - -if sys.version_info >= (3,): - _str_base = object -else: - class basestring(metaclass=ABCMeta): ... - - class unicode(basestring, Sequence[unicode]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... - def capitalize(self) -> unicode: ... - def center(self, width: int, fillchar: unicode = ...) -> unicode: ... - def count(self, x: unicode) -> int: ... - def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... - def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., - end: int = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> unicode: ... - def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> unicode: ... - def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def isidentifier(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, iterable: Iterable[unicode]) -> unicode: ... - def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def lower(self) -> unicode: ... - def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... - def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... - def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., - end: int = ...) -> bool: ... - def strip(self, chars: unicode = ...) -> unicode: ... - def swapcase(self) -> unicode: ... - def title(self) -> unicode: ... - def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... - def upper(self) -> unicode: ... - def zfill(self, width: int) -> unicode: ... - - @overload - def __getitem__(self, i: int) -> unicode: ... - @overload - def __getitem__(self, s: slice) -> unicode: ... - def __getslice__(self, start: int, stop: int) -> unicode: ... - def __add__(self, s: unicode) -> unicode: ... - def __mul__(self, n: int) -> unicode: ... - def __rmul__(self, n: int) -> unicode: ... - def __mod__(self, x: Any) -> unicode: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: unicode) -> bool: ... - def __le__(self, x: unicode) -> bool: ... - def __gt__(self, x: unicode) -> bool: ... - def __ge__(self, x: unicode) -> bool: ... - - def __len__(self) -> int: ... - # The argument type is incompatible with Sequence - def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore - def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... - - _str_base = basestring + def __bool__(self) -> bool: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... -class str(Sequence[str], _str_base): - if sys.version_info >= (3,): - @overload - def __init__(self, o: object = ...) -> None: ... - @overload - def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... - else: - def __init__(self, o: object = ...) -> None: ... - +class str(Sequence[str]): + @overload + def __new__(cls: Type[_T], o: object = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... def capitalize(self) -> str: ... - if sys.version_info >= (3, 3): - def casefold(self) -> str: ... + def casefold(self) -> str: ... def center(self, __width: int, __fillchar: str = ...) -> str: ... - def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - if sys.version_info < (3,): - def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... - def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - if sys.version_info >= (3,): - def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., - end: Optional[int] = ...) -> bool: ... - else: - def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def count(self, x: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... + def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def find(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... - if sys.version_info >= (3,): - def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... if sys.version_info >= (3, 7): def isascii(self) -> bool: ... - if sys.version_info >= (3,): - def isdecimal(self) -> bool: ... + def isdecimal(self) -> bool: ... def isdigit(self) -> bool: ... - if sys.version_info >= (3,): - def isidentifier(self) -> bool: ... + def isidentifier(self) -> bool: ... def islower(self) -> bool: ... - if sys.version_info >= (3,): - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - if sys.version_info >= (3,): - def join(self, __iterable: Iterable[str]) -> str: ... - else: - def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... + def join(self, __iterable: Iterable[str]) -> str: ... def ljust(self, __width: int, __fillchar: str = ...) -> str: ... def lower(self) -> str: ... - if sys.version_info >= (3,): - def lstrip(self, __chars: Optional[str] = ...) -> str: ... - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... - else: - @overload - def lstrip(self, __chars: str = ...) -> str: ... - @overload - def lstrip(self, __chars: unicode) -> unicode: ... - @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... + def lstrip(self, __chars: Optional[str] = ...) -> str: ... + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... if sys.version_info >= (3, 9): def removeprefix(self, __prefix: str) -> str: ... def removesuffix(self, __suffix: str) -> str: ... - def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rfind(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... - if sys.version_info >= (3,): - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - def rstrip(self, __chars: Optional[str] = ...) -> str: ... - def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - else: - @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - @overload - def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - @overload - def rstrip(self, __chars: str = ...) -> str: ... - @overload - def rstrip(self, __chars: unicode) -> unicode: ... - @overload - def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, __chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... - if sys.version_info >= (3,): - def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., - end: Optional[int] = ...) -> bool: ... - def strip(self, __chars: Optional[str] = ...) -> str: ... - else: - def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... - @overload - def strip(self, __chars: str = ...) -> str: ... - @overload - def strip(self, chars: unicode) -> unicode: ... + def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... + def strip(self, __chars: Optional[str] = ...) -> str: ... def swapcase(self) -> str: ... def title(self) -> str: ... - if sys.version_info >= (3,): - def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... - else: - def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... def upper(self) -> str: ... def zfill(self, __width: int) -> str: ... - if sys.version_info >= (3,): - @staticmethod - @overload - def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... - @staticmethod - @overload - def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... - - if sys.version_info >= (3,): - def __add__(self, s: str) -> str: ... - else: - def __add__(self, s: AnyStr) -> AnyStr: ... + @staticmethod + @overload + def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... + def __add__(self, s: str) -> str: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore + def __contains__(self, o: str) -> bool: ... # type: ignore def __eq__(self, x: object) -> bool: ... - def __ge__(self, x: Text) -> bool: ... + def __ge__(self, x: str) -> bool: ... def __getitem__(self, i: Union[int, slice]) -> str: ... - def __gt__(self, x: Text) -> bool: ... + def __gt__(self, x: str) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[str]: ... - def __le__(self, x: Text) -> bool: ... + def __le__(self, x: str) -> bool: ... def __len__(self) -> int: ... - def __lt__(self, x: Text) -> bool: ... + def __lt__(self, x: str) -> bool: ... def __mod__(self, x: Any) -> str: ... def __mul__(self, n: int) -> str: ... def __ne__(self, x: object) -> bool: ... @@ -569,148 +399,115 @@ class str(Sequence[str], _str_base): def __str__(self) -> str: ... def __getnewargs__(self) -> Tuple[str]: ... - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - -if sys.version_info >= (3,): - class bytes(ByteString): - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str, encoding: str, - errors: str = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: SupportsBytes) -> None: ... - def capitalize(self) -> bytes: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def decode(self, encoding: str = ..., errors: str = ...) -> str: ... - def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytes: ... - def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... - elif sys.version_info >= (3, 5): - def hex(self) -> str: ... - def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def lower(self) -> bytes: ... - def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytes: ... - def removesuffix(self, __suffix: bytes) -> bytes: ... - def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... - def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... - def splitlines(self, keepends: bool = ...) -> List[bytes]: ... - def startswith( - self, - prefix: Union[bytes, Tuple[bytes, ...]], - start: Optional[int] = ..., - end: Optional[int] = ..., - ) -> bool: ... - def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def swapcase(self) -> bytes: ... - def title(self) -> bytes: ... - def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... - def upper(self) -> bytes: ... - def zfill(self, __width: int) -> bytes: ... - @classmethod - def fromhex(cls, __s: str) -> bytes: ... - @classmethod - def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... - - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> bytes: ... - def __add__(self, s: bytes) -> bytes: ... - def __mul__(self, n: int) -> bytes: ... - def __rmul__(self, n: int) -> bytes: ... - if sys.version_info >= (3, 5): - def __mod__(self, value: Any) -> bytes: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... - def __getnewargs__(self) -> Tuple[bytes]: ... -else: - bytes = str +class bytes(ByteString): + @overload + def __new__(cls: Type[_T], ints: Iterable[int]) -> _T: ... + @overload + def __new__(cls: Type[_T], string: str, encoding: str, errors: str = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], length: int) -> _T: ... + @overload + def __new__(cls: Type[_T]) -> _T: ... + @overload + def __new__(cls: Type[_T], o: SupportsBytes) -> _T: ... + def capitalize(self) -> bytes: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + else: + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... + if sys.version_info >= (3, 9): + def removeprefix(self, __prefix: bytes) -> bytes: ... + def removesuffix(self, __suffix: bytes) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, prefix: Union[bytes, Tuple[bytes, ...]], start: Optional[int] = ..., end: Optional[int] = ... + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, __width: int) -> bytes: ... + @classmethod + def fromhex(cls, __s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + def __mod__(self, value: Any) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... class bytearray(MutableSequence[int], ByteString): - if sys.version_info >= (3,): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - else: - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... def capitalize(self) -> bytearray: ... def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - if sys.version_info >= (3,): - def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def copy(self) -> bytearray: ... - else: - def count(self, __sub: str) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... - if sys.version_info < (3,): - def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... - if sys.version_info >= (3,): - def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - if sys.version_info >= (3, 5): - def hex(self) -> str: ... - def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... else: - def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def hex(self) -> str: ... + def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def insert(self, __index: int, __item: int) -> None: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... @@ -721,12 +518,8 @@ class bytearray(MutableSequence[int], ByteString): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - if sys.version_info >= (3,): - def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - else: - def join(self, __iterable: Iterable[str]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... + def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... @@ -734,12 +527,8 @@ class bytearray(MutableSequence[int], ByteString): def removeprefix(self, __prefix: bytes) -> bytearray: ... def removesuffix(self, __suffix: bytes) -> bytearray: ... def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... - if sys.version_info >= (3,): - def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - else: - def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... @@ -747,26 +536,18 @@ class bytearray(MutableSequence[int], ByteString): def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... def startswith( - self, - __prefix: Union[bytes, Tuple[bytes, ...]], - __start: Optional[int] = ..., - __end: Optional[int] = ..., + self, __prefix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... ) -> bool: ... def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... - if sys.version_info >= (3,): - def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... - else: - def translate(self, __table: str) -> bytearray: ... + def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... def upper(self) -> bytearray: ... def zfill(self, __width: int) -> bytearray: ... @classmethod def fromhex(cls, __string: str) -> bytearray: ... - if sys.version_info >= (3,): - @classmethod - def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... - + @classmethod + def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def __str__(self) -> str: ... @@ -783,19 +564,12 @@ class bytearray(MutableSequence[int], ByteString): @overload def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... def __delitem__(self, i: Union[int, slice]) -> None: ... - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> bytearray: ... - def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... def __add__(self, s: bytes) -> bytearray: ... - if sys.version_info >= (3,): - def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __iadd__(self, s: Iterable[int]) -> bytearray: ... def __mul__(self, n: int) -> bytearray: ... - if sys.version_info >= (3,): - def __rmul__(self, n: int) -> bytearray: ... - def __imul__(self, n: int) -> bytearray: ... - if sys.version_info >= (3, 5): - def __mod__(self, value: Any) -> bytes: ... + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + def __mod__(self, value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore def __eq__(self, x: object) -> bool: ... @@ -805,12 +579,7 @@ class bytearray(MutableSequence[int], ByteString): def __gt__(self, x: bytes) -> bool: ... def __ge__(self, x: bytes) -> bool: ... -if sys.version_info >= (3,): - _mv_container_type = int -else: - _mv_container_type = str - -class memoryview(Sized, Container[_mv_container_type]): +class memoryview(Sized, Container[int]): format: str itemsize: int shape: Optional[Tuple[int, ...]] @@ -819,35 +588,28 @@ class memoryview(Sized, Container[_mv_container_type]): readonly: bool ndim: int - if sys.version_info >= (3,): - obj: Union[bytes, bytearray] - c_contiguous: bool - f_contiguous: bool - contiguous: bool - nbytes: int - def __init__(self, obj: ReadableBuffer) -> None: ... - def __enter__(self) -> memoryview: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... - def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... - else: - def __init__(self, obj: ReadableBuffer) -> None: ... - + obj: Union[bytes, bytearray] + c_contiguous: bool + f_contiguous: bool + contiguous: bool + nbytes: int + def __init__(self, obj: ReadableBuffer) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... @overload - def __getitem__(self, i: int) -> _mv_container_type: ... + def __getitem__(self, i: int) -> int: ... @overload def __getitem__(self, s: slice) -> memoryview: ... - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[_mv_container_type]: ... + def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... - @overload - def __setitem__(self, s: slice, o: memoryview) -> None: ... + def __setitem__(self, s: slice, o: bytes) -> None: ... @overload - def __setitem__(self, i: int, o: bytes) -> None: ... - @overload - def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... - + def __setitem__(self, i: int, o: int) -> None: ... if sys.version_info >= (3, 8): def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... else: @@ -855,15 +617,14 @@ class memoryview(Sized, Container[_mv_container_type]): def tolist(self) -> List[int]: ... if sys.version_info >= (3, 8): def toreadonly(self) -> memoryview: ... - - if sys.version_info >= (3, 2): - def release(self) -> None: ... - - if sys.version_info >= (3, 5): + def release(self) -> None: ... + if sys.version_info >= (3, 8): + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + else: def hex(self) -> str: ... class bool(int): - def __init__(self, o: object = ...) -> None: ... + def __new__(cls: Type[_T], __o: object = ...) -> _T: ... @overload def __and__(self, x: bool) -> bool: ... @overload @@ -921,10 +682,7 @@ class tuple(Sequence[_T_co], Generic[_T_co]): def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... - if sys.version_info >= (3, 5): - def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... - else: - def index(self, __value: Any) -> int: ... + def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -933,18 +691,16 @@ class function: __name__: str __module__: str __code__: CodeType - if sys.version_info >= (3,): - __qualname__: str - __annotations__: Dict[str, Any] + __qualname__: str + __annotations__: Dict[str, Any] class list(MutableSequence[_T], Generic[_T]): @overload def __init__(self) -> None: ... @overload def __init__(self, iterable: Iterable[_T]) -> None: ... - if sys.version_info >= (3,): - def clear(self) -> None: ... - def copy(self) -> List[_T]: ... + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... def append(self, __object: _T) -> None: ... def extend(self, __iterable: Iterable[_T]) -> None: ... def pop(self, __index: int = ...) -> _T: ... @@ -953,14 +709,10 @@ class list(MutableSequence[_T], Generic[_T]): def insert(self, __index: int, __object: _T) -> None: ... def remove(self, __value: _T) -> None: ... def reverse(self) -> None: ... - if sys.version_info >= (3,): - @overload - def sort(self: List[_LT], *, key: None = ..., reverse: bool = ...) -> None: ... - @overload - def sort(self, *, key: Callable[[_T], _SupportsLessThan], reverse: bool = ...) -> None: ... - else: - def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... - + @overload + def sort(self: List[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __str__(self) -> str: ... @@ -974,16 +726,11 @@ class list(MutableSequence[_T], Generic[_T]): @overload def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... def __delitem__(self, i: Union[int, slice]) -> None: ... - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> List[_T]: ... - def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... def __add__(self, x: List[_T]) -> List[_T]: ... def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... def __mul__(self, n: int) -> List[_T]: ... def __rmul__(self, n: int) -> List[_T]: ... - if sys.version_info >= (3,): - def __imul__(self: _S, n: int) -> _S: ... + def __imul__(self: _S, n: int) -> _S: ... def __contains__(self, o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... def __gt__(self, x: List[_T]) -> bool: ... @@ -999,14 +746,10 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self, **kwargs: _VT) -> None: ... @overload - def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... - - if sys.version_info < (3,): - def has_key(self, k: _KT) -> bool: ... def clear(self) -> None: ... def copy(self) -> Dict[_KT, _VT]: ... def popitem(self) -> Tuple[_KT, _VT]: ... @@ -1017,17 +760,9 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... - if sys.version_info >= (3,): - def keys(self) -> KeysView[_KT]: ... - def values(self) -> ValuesView[_VT]: ... - def items(self) -> ItemsView[_KT, _VT]: ... - else: - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def viewkeys(self) -> KeysView[_KT]: ... - def viewvalues(self) -> ValuesView[_VT]: ... - def viewitems(self) -> ItemsView[_KT, _VT]: ... + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... @classmethod @overload def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... @@ -1045,6 +780,8 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): __hash__: None # type: ignore if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __or__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... + def __ior__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... @@ -1073,8 +810,8 @@ class set(MutableSet[_T], Generic[_T]): def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... - def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __sub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... def __le__(self, s: AbstractSet[object]) -> bool: ... @@ -1113,47 +850,38 @@ class frozenset(AbstractSet[_T_co], Generic[_T_co]): class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... def __iter__(self) -> Iterator[Tuple[int, _T]]: ... - if sys.version_info >= (3,): - def __next__(self) -> Tuple[int, _T]: ... - else: - def next(self) -> Tuple[int, _T]: ... - -if sys.version_info >= (3,): - class range(Sequence[int]): - start: int - stop: int - step: int - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def count(self, value: int) -> int: ... - def index(self, value: int) -> int: ... # type: ignore - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[int]: ... - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> range: ... - def __repr__(self) -> str: ... - def __reversed__(self) -> Iterator[int]: ... -else: - class xrange(Sized, Iterable[int], Reversible[int]): - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __getitem__(self, i: int) -> int: ... - def __reversed__(self) -> Iterator[int]: ... + def __next__(self) -> Tuple[int, _T]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: _SupportsIndex) -> None: ... + @overload + def __init__(self, start: _SupportsIndex, stop: _SupportsIndex, step: _SupportsIndex = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int) -> int: ... # type: ignore + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: _SupportsIndex) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... class property(object): - def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., - fset: Optional[Callable[[Any, Any], None]] = ..., - fdel: Optional[Callable[[Any], None]] = ..., - doc: Optional[str] = ...) -> None: ... + def __init__( + self, + fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ..., + ) -> None: ... def getter(self, fget: Callable[[Any], Any]) -> property: ... def setter(self, fset: Callable[[Any, Any], None]) -> property: ... def deleter(self, fdel: Callable[[Any], None]) -> property: ... @@ -1164,9 +892,6 @@ class property(object): def fset(self, value: Any) -> None: ... def fdel(self) -> None: ... -if sys.version_info < (3,): - long = int - class _NotImplementedType(Any): # type: ignore # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better @@ -1177,75 +902,75 @@ NotImplemented: _NotImplementedType def abs(__x: SupportsAbs[_T]) -> _T: ... def all(__iterable: Iterable[object]) -> bool: ... def any(__iterable: Iterable[object]) -> bool: ... -if sys.version_info < (3,): - def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... -if sys.version_info >= (3,): - def ascii(__obj: object) -> str: ... - +def ascii(__obj: object) -> str: ... def bin(__number: Union[int, _SupportsIndex]) -> str: ... if sys.version_info >= (3, 7): def breakpoint(*args: Any, **kws: Any) -> None: ... + def callable(__obj: object) -> bool: ... def chr(__i: int) -> str: ... -if sys.version_info < (3,): - def cmp(__x: Any, __y: Any) -> int: ... - _N1 = TypeVar('_N1', bool, int, float, complex) - def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... -if sys.version_info >= (3, 6): - # This class is to be exported as PathLike from os, - # but we define it here as _PathLike to avoid import cycle issues. - # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 - class _PathLike(Generic[AnyStr]): - def __fspath__(self) -> AnyStr: ... - def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes, _PathLike[Any]], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... -elif sys.version_info >= (3,): - def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... + +# This class is to be exported as PathLike from os, +# but we define it here as _PathLike to avoid import cycle issues. +# See https://github.com/python/typeshed/pull/991#issuecomment-288160993 +_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +@runtime_checkable +class _PathLike(Protocol[_AnyStr_co]): + def __fspath__(self) -> _AnyStr_co: ... + +if sys.version_info >= (3, 8): + def compile( + source: Union[str, bytes, mod, AST], + filename: Union[str, bytes, _PathLike[Any]], + mode: str, + flags: int = ..., + dont_inherit: int = ..., + optimize: int = ..., + *, + _feature_version: int = ..., + ) -> Any: ... + else: - def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... -if sys.version_info >= (3,): - def copyright() -> None: ... - def credits() -> None: ... -def delattr(__obj: Any, __name: Text) -> None: ... + def compile( + source: Union[str, bytes, mod, AST], + filename: Union[str, bytes, _PathLike[Any]], + mode: str, + flags: int = ..., + dont_inherit: int = ..., + optimize: int = ..., + ) -> Any: ... + +def copyright() -> None: ... +def credits() -> None: ... +def delattr(__obj: Any, __name: str) -> None: ... def dir(__o: object = ...) -> List[str]: ... -_N2 = TypeVar('_N2', int, float) + +_N2 = TypeVar("_N2", int, float) + def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... -def eval(__source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... -if sys.version_info >= (3,): - def exec(__source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... -else: - def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... +def eval( + __source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ... +) -> Any: ... +def exec( + __source: Union[str, bytes, CodeType], + __globals: Optional[Dict[str, Any]] = ..., + __locals: Optional[Mapping[str, Any]] = ..., +) -> Any: ... def exit(code: object = ...) -> NoReturn: ... -if sys.version_info >= (3,): - @overload - def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... - @overload - def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... -else: - @overload - def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore - @overload - def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore - @overload - def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore - @overload - def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: ... - @overload - def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... +@overload +def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... +@overload +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode -def getattr(__o: Any, name: Text, __default: Any = ...) -> Any: ... +def getattr(__o: Any, name: str, __default: Any = ...) -> Any: ... def globals() -> Dict[str, Any]: ... -def hasattr(__obj: Any, __name: Text) -> bool: ... +def hasattr(__obj: Any, __name: str) -> bool: ... def hash(__obj: object) -> int: ... -if sys.version_info >= (3,): - def help(*args: Any, **kwds: Any) -> None: ... +def help(*args: Any, **kwds: Any) -> None: ... def hex(__number: Union[int, _SupportsIndex]) -> str: ... def id(__obj: object) -> int: ... -if sys.version_info >= (3,): - def input(__prompt: Any = ...) -> str: ... -else: - def input(__prompt: Any = ...) -> Any: ... - def intern(__string: str) -> str: ... +def input(__prompt: Any = ...) -> str: ... @overload def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... @overload @@ -1255,261 +980,185 @@ 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: ... def len(__obj: Sized) -> int: ... -if sys.version_info >= (3,): - def license() -> None: ... +def license() -> None: ... def locals() -> Dict[str, Any]: ... -if sys.version_info >= (3,): - @overload - def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[_S]: ... -else: - @overload - def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def map(__func: None, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... - @overload - def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> List[_S]: ... - @overload - def map(__func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[_S]: ... -if sys.version_info >= (3,): - @overload - def max(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... - @overload - def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... - @overload - def max(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... - @overload - def max(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... - @overload - def max(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... - @overload - def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... -else: - @overload - def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... - @overload - def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -if sys.version_info >= (3,): - @overload - def min(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... - @overload - def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... - @overload - def min(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... - @overload - def min(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... - @overload - def min(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... - @overload - def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... -else: - @overload - def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... - @overload - def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... +@overload +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> Iterator[_S]: ... +@overload +def map( + __func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[_S]: ... +@overload +def max( + __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... +) -> SupportsLessThanT: ... +@overload +def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ...) -> SupportsLessThanT: ... +@overload +def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., default: _T) -> Union[SupportsLessThanT, _T]: ... +@overload +def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsLessThanT], default: _T2) -> Union[_T1, _T2]: ... +@overload +def min( + __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... +) -> SupportsLessThanT: ... +@overload +def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def min(__iterable: Iterable[SupportsLessThanT], *, key: None = ...) -> SupportsLessThanT: ... +@overload +def min(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThanT]) -> _T: ... +@overload +def min(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., default: _T) -> Union[SupportsLessThanT, _T]: ... +@overload +def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsLessThanT], default: _T2) -> Union[_T1, _T2]: ... @overload def next(__i: Iterator[_T]) -> _T: ... @overload def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... def oct(__number: Union[int, _SupportsIndex]) -> str: ... -if sys.version_info >= (3,): - _OpenFile = Union[AnyPath, int] - _Opener = Callable[[str, int], int] - - # Text mode: always returns a TextIOWrapper - @overload - def open( - file: _OpenFile, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> TextIOWrapper: ... - - # Unbuffered binary mode: returns a FileIO - @overload - def open( - file: _OpenFile, - mode: OpenBinaryMode, - buffering: Literal[0], - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> FileIO: ... - - # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedRandom: ... - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedWriter: ... - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedReader: ... - - # Buffering cannot be determined: fall back to BinaryIO - @overload - def open( - file: _OpenFile, - mode: OpenBinaryMode, - buffering: int, - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BinaryIO: ... - - # Fallback if mode is not specified - @overload - def open( - file: _OpenFile, - mode: str, - buffering: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> IO[Any]: ... - -else: - def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... - -def ord(__c: Union[Text, bytes]) -> int: ... -if sys.version_info >= (3,): - def print( - *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[str]] = ..., flush: bool = ... - ) -> None: ... +_OpenFile = Union[AnyPath, int] +_Opener = Callable[[str, int], int] -else: - # This is only available after from __future__ import print_function. - def print(*values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ...) -> None: ... +# Text mode: always returns a TextIOWrapper +@overload +def open( + file: _OpenFile, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> TextIOWrapper: ... + +# Unbuffered binary mode: returns a FileIO +@overload +def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> FileIO: ... + +# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedRandom: ... +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedWriter: ... +@overload +def open( + file: _OpenFile, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedReader: ... + +# Buffering cannot be determined: fall back to BinaryIO +@overload +def open( + file: _OpenFile, + mode: OpenBinaryMode, + buffering: int, + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BinaryIO: ... + +# Fallback if mode is not specified +@overload +def open( + file: _OpenFile, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> IO[Any]: ... +def ord(__c: Union[str, bytes]) -> int: ... +def print( + *values: object, + sep: Optional[str] = ..., + end: Optional[str] = ..., + file: Optional[SupportsWrite[str]] = ..., + flush: bool = ..., +) -> None: ... _E = TypeVar("_E", contravariant=True) _M = TypeVar("_M", contravariant=True) + class _SupportsPow2(Protocol[_E, _T_co]): def __pow__(self, __other: _E) -> _T_co: ... + class _SupportsPow3(Protocol[_E, _M, _T_co]): def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... + if sys.version_info >= (3, 8): @overload def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative @@ -1521,9 +1170,12 @@ if sys.version_info >= (3, 8): def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... @overload def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... + else: @overload - def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + def pow( + __base: int, __exp: int, __mod: None = ... + ) -> Any: ... # returns int or float depending on whether exp is non-negative @overload def pow(__base: int, __exp: int, __mod: int) -> int: ... @overload @@ -1532,273 +1184,197 @@ else: def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... @overload def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... + def quit(code: object = ...) -> NoReturn: ... -if sys.version_info < (3,): - def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 - def raw_input(__prompt: Any = ...) -> str: ... - @overload - def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... - @overload - def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... - def reload(__module: Any) -> Any: ... @overload -def reversed(__object: Sequence[_T]) -> Iterator[_T]: ... +def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... @overload -def reversed(__object: Reversible[_T]) -> Iterator[_T]: ... +def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... def repr(__obj: object) -> str: ... -if sys.version_info >= (3,): - @overload - def round(number: float) -> int: ... - @overload - def round(number: float, ndigits: None) -> int: ... - @overload - def round(number: float, ndigits: int) -> float: ... - @overload - def round(number: SupportsRound[_T]) -> int: ... - @overload - def round(number: SupportsRound[_T], ndigits: None) -> int: ... - @overload - def round(number: SupportsRound[_T], ndigits: int) -> _T: ... -else: - @overload - def round(number: float) -> float: ... - @overload - def round(number: float, ndigits: int) -> float: ... - @overload - def round(number: SupportsFloat) -> float: ... - @overload - def round(number: SupportsFloat, ndigits: int) -> float: ... -def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... -if sys.version_info >= (3,): - @overload - def sorted(__iterable: Iterable[_LT], *, - key: None = ..., - reverse: bool = ...) -> List[_LT]: ... - @overload - def sorted(__iterable: Iterable[_T], *, - key: Callable[[_T], _SupportsLessThan], - reverse: bool = ...) -> List[_T]: ... -else: - def sorted(__iterable: Iterable[_T], *, - cmp: Callable[[_T, _T], int] = ..., - key: Optional[Callable[[_T], Any]] = ..., - reverse: bool = ...) -> List[_T]: ... +@overload +def round(number: float) -> int: ... +@overload +def round(number: float, ndigits: None) -> int: ... +@overload +def round(number: float, ndigits: int) -> float: ... +@overload +def round(number: SupportsRound[_T]) -> int: ... +@overload +def round(number: SupportsRound[_T], ndigits: None) -> int: ... +@overload +def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +def setattr(__obj: Any, __name: str, __value: Any) -> None: ... +@overload +def sorted(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> List[SupportsLessThanT]: ... +@overload +def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> List[_T]: ... + if sys.version_info >= (3, 8): @overload def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... @overload def sum(__iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... + else: @overload def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... -if sys.version_info < (3,): - def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... -if sys.version_info >= (3,): - # Some overloads to better support zipping heterogeneous tuples - @overload - def zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3, _T4]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3, _T4, _T5]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...], Tuple[_T5, ...]]: ... # type: ignore - @overload - def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], - __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... -else: - @overload - def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... - @overload - def zip(__iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], - __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... -def __import__(name: Text, globals: Optional[Mapping[str, Any]] = ..., - locals: Optional[Mapping[str, Any]] = ..., - fromlist: Sequence[str] = ..., - level: int = ...) -> Any: ... +def vars(__object: Any = ...) -> Dict[str, Any]: ... +@overload +def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def zip( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[Tuple[Any, ...]]: ... +def __import__( + name: str, + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ..., +) -> Any: ... # Actually the type of Ellipsis is , but since it's # not exposed anywhere under that name, we make it private here. class ellipsis: ... -Ellipsis: ellipsis - -if sys.version_info < (3,): - # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. - _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) - class buffer(Sized): - def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... - def __add__(self, other: _AnyBuffer) -> str: ... - def __cmp__(self, other: _AnyBuffer) -> bool: ... - def __getitem__(self, key: Union[int, slice]) -> str: ... - def __getslice__(self, i: int, j: int) -> str: ... - def __len__(self) -> int: ... - def __mul__(self, x: int) -> str: ... +Ellipsis: ellipsis class BaseException(object): args: Tuple[Any, ...] - if sys.version_info < (3,): - message: Any - if sys.version_info >= (3,): - __cause__: Optional[BaseException] - __context__: Optional[BaseException] - __suppress_context__: bool - __traceback__: Optional[TracebackType] + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __suppress_context__: bool + __traceback__: Optional[TracebackType] def __init__(self, *args: object) -> None: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... - if sys.version_info < (3,): - def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... - if sys.version_info >= (3,): - def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... + class SystemExit(BaseException): code: int + class Exception(BaseException): ... + class StopIteration(Exception): - if sys.version_info >= (3,): - value: Any -if sys.version_info >= (3,): - _StandardError = Exception - class OSError(Exception): - errno: int - strerror: str - # filename, filename2 are actually Union[str, bytes, None] - filename: Any - filename2: Any - EnvironmentError = OSError - IOError = OSError -else: - class StandardError(Exception): ... - _StandardError = StandardError - class EnvironmentError(StandardError): - errno: int - strerror: str - # TODO can this be unicode? - filename: str - class OSError(EnvironmentError): ... - class IOError(EnvironmentError): ... + value: Any + +_StandardError = Exception + +class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + +EnvironmentError = OSError +IOError = OSError class ArithmeticError(_StandardError): ... class AssertionError(_StandardError): ... class AttributeError(_StandardError): ... class BufferError(_StandardError): ... class EOFError(_StandardError): ... + class ImportError(_StandardError): - if sys.version_info >= (3, 3): - def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... - name: Optional[str] - path: Optional[str] + def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... + name: Optional[str] + path: Optional[str] + class LookupError(_StandardError): ... class MemoryError(_StandardError): ... class NameError(_StandardError): ... class ReferenceError(_StandardError): ... class RuntimeError(_StandardError): ... -if sys.version_info >= (3, 5): - class StopAsyncIteration(Exception): - value: Any + +class StopAsyncIteration(Exception): + value: Any + class SyntaxError(_StandardError): msg: str lineno: Optional[int] offset: Optional[int] text: Optional[str] filename: Optional[str] + class SystemError(_StandardError): ... class TypeError(_StandardError): ... class ValueError(_StandardError): ... - class FloatingPointError(ArithmeticError): ... class OverflowError(ArithmeticError): ... class ZeroDivisionError(ArithmeticError): ... - -if sys.version_info >= (3, 6): - class ModuleNotFoundError(ImportError): ... - +class ModuleNotFoundError(ImportError): ... class IndexError(LookupError): ... class KeyError(LookupError): ... - class UnboundLocalError(NameError): ... class WindowsError(OSError): winerror: int -if sys.version_info >= (3,): - class BlockingIOError(OSError): - characters_written: int - class ChildProcessError(OSError): ... - class ConnectionError(OSError): ... - class BrokenPipeError(ConnectionError): ... - class ConnectionAbortedError(ConnectionError): ... - class ConnectionRefusedError(ConnectionError): ... - class ConnectionResetError(ConnectionError): ... - class FileExistsError(OSError): ... - class FileNotFoundError(OSError): ... - class InterruptedError(OSError): ... - class IsADirectoryError(OSError): ... - class NotADirectoryError(OSError): ... - class PermissionError(OSError): ... - class ProcessLookupError(OSError): ... - class TimeoutError(OSError): ... +class BlockingIOError(OSError): + characters_written: int + +class ChildProcessError(OSError): ... +class ConnectionError(OSError): ... +class BrokenPipeError(ConnectionError): ... +class ConnectionAbortedError(ConnectionError): ... +class ConnectionRefusedError(ConnectionError): ... +class ConnectionResetError(ConnectionError): ... +class FileExistsError(OSError): ... +class FileNotFoundError(OSError): ... +class InterruptedError(OSError): ... +class IsADirectoryError(OSError): ... +class NotADirectoryError(OSError): ... +class PermissionError(OSError): ... +class ProcessLookupError(OSError): ... +class TimeoutError(OSError): ... class NotImplementedError(RuntimeError): ... -if sys.version_info >= (3, 5): - class RecursionError(RuntimeError): ... - +class RecursionError(RuntimeError): ... class IndentationError(SyntaxError): ... class TabError(IndentationError): ... - class UnicodeError(ValueError): ... + class UnicodeDecodeError(UnicodeError): encoding: str object: bytes start: int end: int reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, - __reason: str) -> None: ... + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + class UnicodeEncodeError(UnicodeError): encoding: str - object: Text + object: str start: int end: int reason: str - def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, - __reason: str) -> None: ... -class UnicodeTranslateError(UnicodeError): ... + def __init__(self, __encoding: str, __object: str, __start: int, __end: int, __reason: str) -> None: ... +class UnicodeTranslateError(UnicodeError): ... class Warning(Exception): ... class UserWarning(Warning): ... class DeprecationWarning(Warning): ... @@ -1809,34 +1385,4 @@ class PendingDeprecationWarning(Warning): ... class ImportWarning(Warning): ... class UnicodeWarning(Warning): ... class BytesWarning(Warning): ... -if sys.version_info >= (3, 2): - class ResourceWarning(Warning): ... - -if sys.version_info < (3,): - class file(BinaryIO): - @overload - def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def __enter__(self) -> BinaryIO: ... - def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> Optional[bool]: ... - def flush(self) -> None: ... - def fileno(self) -> int: ... - def isatty(self) -> bool: ... - def close(self) -> None: ... - - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def write(self, data: str) -> int: ... - def writelines(self, data: Iterable[str]) -> None: ... - def truncate(self, pos: Optional[int] = ...) -> int: ... +class ResourceWarning(Warning): ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index ce55ca7fee57..b67d00cc7be1 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -1,7 +1,7 @@ import io import sys -from typing import IO, Any, Optional, TextIO, Union, overload, TypeVar from _typeshed import AnyPath +from typing import IO, Any, Optional, TextIO, TypeVar, Union, overload from typing_extensions import Literal _PathOrFile = Union[AnyPath, IO[bytes]] @@ -44,17 +44,11 @@ if sys.version_info >= (3, 3): class BZ2File(io.BufferedIOBase, IO[bytes]): def __enter__(self: _T) -> _T: ... if sys.version_info >= (3, 9): - def __init__(self, - filename: _PathOrFile, - mode: str = ..., - *, - compresslevel: int = ...) -> None: ... + def __init__(self, filename: _PathOrFile, mode: str = ..., *, compresslevel: int = ...) -> None: ... else: - def __init__(self, - filename: _PathOrFile, - mode: str = ..., - buffering: Optional[Any] = ..., - compresslevel: int = ...) -> None: ... + def __init__( + self, filename: _PathOrFile, mode: str = ..., buffering: Optional[Any] = ..., compresslevel: int = ... + ) -> None: ... class BZ2Compressor(object): def __init__(self, compresslevel: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 43b21229babb..e5399beac9c4 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -3,13 +3,17 @@ from _typeshed import AnyPath from typing import Any, Callable, Dict, Optional, 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: ... +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') +_SelfT = TypeVar("_SelfT", bound=Profile) +_T = TypeVar("_T") class Profile: - def __init__(self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ...) -> None: ... + 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: ... diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index 4b452cc334b9..af2aa83edbdb 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -3,7 +3,6 @@ import sys from time import struct_time from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union - _LocaleType = Tuple[Optional[str], Optional[str]] class IllegalMonthError(ValueError): @@ -82,6 +81,7 @@ if sys.version_info < (3, 0): def __init__(self, locale: _LocaleType) -> None: ... def __enter__(self) -> _LocaleType: ... def __exit__(self, *args: Any) -> None: ... + else: class different_locale: def __init__(self, locale: _LocaleType) -> None: ... @@ -99,6 +99,7 @@ class LocaleHTMLCalendar(HTMLCalendar): 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: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 1f69efe3f163..c868d6521f3d 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,25 +1,43 @@ import sys -from typing import Any, AnyStr, Dict, IO, Iterator, List, Mapping, Optional, Tuple, TypeVar, Union +from _typeshed import SupportsGetItem, SupportsItemAccess +from builtins import type as _type +from typing import IO, Any, AnyStr, Dict, Iterable, Iterator, List, Mapping, Optional, Protocol, Tuple, TypeVar, Union -_T = TypeVar('_T', bound=FieldStorage) +_T = TypeVar("_T", bound=FieldStorage) + +def parse( + fp: Optional[IO[Any]] = ..., + environ: SupportsItemAccess[str, str] = ..., + keep_blank_values: bool = ..., + strict_parsing: bool = ..., +) -> Dict[str, List[str]]: ... -def parse(fp: Optional[IO[Any]] = ..., environ: Mapping[str, str] = ..., - keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... if sys.version_info < (3, 8): def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... - def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... + def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> List[Tuple[str, str]]: ... + if sys.version_info >= (3, 7): - def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes], encoding: str = ..., errors: str = ...) -> Dict[str, List[Any]]: ... + def parse_multipart( + fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = ..., errors: str = ... + ) -> Dict[str, List[Any]]: ... + else: - def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes]) -> Dict[str, List[bytes]]: ... + def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> Dict[str, List[bytes]]: ... + +class _Environ(Protocol): + def __getitem__(self, __k: str) -> str: ... + def keys(self) -> Iterable[str]: ... + def parse_header(line: str) -> Tuple[str, Dict[str, str]]: ... -def test(environ: Mapping[str, str] = ...) -> None: ... -def print_environ(environ: Mapping[str, str] = ...) -> None: ... +def test(environ: _Environ = ...) -> None: ... +def print_environ(environ: _Environ = ...) -> None: ... def print_form(form: Dict[str, Any]) -> None: ... def print_directory() -> None: ... def print_environ_usage() -> None: ... + if sys.version_info < (3,): def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... + elif sys.version_info < (3, 8): def escape(s: str, quote: Optional[bool] = ...) -> str: ... @@ -35,13 +53,11 @@ class MiniFieldStorage: headers: Dict[Any, Any] name: Any value: Any - def __init__(self, name: Any, value: Any) -> None: ... def __repr__(self) -> str: ... - class FieldStorage(object): - FieldStorageClass: Optional[type] + FieldStorageClass: Optional[_type] keep_blank_values: int strict_parsing: int qs_on_post: Optional[str] @@ -65,17 +81,42 @@ class FieldStorage(object): value: Union[None, bytes, List[Any]] if sys.version_info >= (3, 6): - def __init__(self, fp: Optional[IO[Any]] = ..., headers: Optional[Mapping[str, str]] = ..., outerboundary: bytes = ..., - environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ..., - limit: Optional[int] = ..., encoding: str = ..., errors: str = ..., max_num_fields: Optional[int] = ...) -> None: ... + def __init__( + self, + fp: Optional[IO[Any]] = ..., + headers: Optional[Mapping[str, str]] = ..., + outerboundary: bytes = ..., + environ: SupportsGetItem[str, str] = ..., + keep_blank_values: int = ..., + strict_parsing: int = ..., + limit: Optional[int] = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + ) -> None: ... elif sys.version_info >= (3, 0): - def __init__(self, fp: Optional[IO[Any]] = ..., headers: Optional[Mapping[str, str]] = ..., outerboundary: bytes = ..., - environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ..., - limit: Optional[int] = ..., encoding: str = ..., errors: str = ...) -> None: ... + def __init__( + self, + fp: Optional[IO[Any]] = ..., + headers: Optional[Mapping[str, str]] = ..., + outerboundary: bytes = ..., + environ: SupportsGetItem[str, str] = ..., + keep_blank_values: int = ..., + strict_parsing: int = ..., + limit: Optional[int] = ..., + encoding: str = ..., + errors: str = ..., + ) -> None: ... else: - def __init__(self, fp: IO[Any] = ..., headers: Mapping[str, str] = ..., outerboundary: bytes = ..., - environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... - + def __init__( + self, + fp: IO[Any] = ..., + headers: Mapping[str, str] = ..., + outerboundary: bytes = ..., + environ: SupportsGetItem[str, str] = ..., + keep_blank_values: int = ..., + strict_parsing: int = ..., + ) -> None: ... if sys.version_info >= (3, 0): def __enter__(self: _T) -> _T: ... def __exit__(self, *args: Any) -> None: ... @@ -101,19 +142,14 @@ class FieldStorage(object): # In Python 2 it always returns bytes and ignores the "binary" flag def make_file(self, binary: Any = ...) -> IO[bytes]: ... - if sys.version_info < (3, 0): from UserDict import UserDict - class FormContentDict(UserDict[str, List[str]]): query_string: str def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... - class SvFormContentDict(FormContentDict): def getlist(self, key: Any) -> Any: ... - class InterpFormContentDict(SvFormContentDict): ... - class FormContent(FormContentDict): # TODO this should have # def values(self, key: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index a20c58a210c2..7603ecd9afbe 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,6 +1,6 @@ -from typing import Dict, Any, List, Tuple, Optional, Callable, Type, IO -from types import FrameType, TracebackType from _typeshed import AnyPath +from types import FrameType, TracebackType +from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type _ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] @@ -9,15 +9,25 @@ 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 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[AnyPath] = ..., context: int = ..., file: Optional[IO[str]] = ..., format: str = ...) -> None: ... - def __call__(self, etype: Optional[Type[BaseException]], evalue: Optional[BaseException], etb: Optional[TracebackType]) -> None: ... + def __init__( + self, + display: int = ..., + logdir: Optional[AnyPath] = ..., + 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[AnyPath] = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/chunk.pyi b/mypy/typeshed/stdlib/chunk.pyi index 2337f00cafe1..50ff267c5436 100644 --- a/mypy/typeshed/stdlib/chunk.pyi +++ b/mypy/typeshed/stdlib/chunk.pyi @@ -1,6 +1,3 @@ -# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/chunk.py -# Source(py3): https://github.com/python/cpython/blob/master/Lib/chunk.py - from typing import IO class Chunk: diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 97651b324e8e..bb9e302ed414 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,5 +1,3 @@ -"""Stub file for the 'cmath' module.""" - import sys from typing import SupportsComplex, SupportsFloat, Tuple, Union @@ -23,8 +21,10 @@ 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 isinf(__z: _C) -> bool: ... def isnan(__z: _C) -> bool: ... def log(__x: _C, __y_obj: _C = ...) -> complex: ... diff --git a/mypy/typeshed/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi index b8a61e4af951..0b7a7f704a9b 100644 --- a/mypy/typeshed/stdlib/cmd.pyi +++ b/mypy/typeshed/stdlib/cmd.pyi @@ -1,6 +1,4 @@ -# Stubs for cmd (Python 2/3) - -from typing import Any, Optional, Text, IO, List, Callable, Tuple +from typing import IO, Any, Callable, List, Optional, Tuple class Cmd: prompt: str diff --git a/mypy/typeshed/stdlib/code.pyi b/mypy/typeshed/stdlib/code.pyi index 293ab9b98b61..16c2b129dd1e 100644 --- a/mypy/typeshed/stdlib/code.pyi +++ b/mypy/typeshed/stdlib/code.pyi @@ -1,24 +1,19 @@ -# Stubs for code - import sys -from typing import Any, Callable, Mapping, Optional 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 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 __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: ... + def interact(self, banner: Optional[str] = ..., exitmsg: Optional[str] = ...) -> None: ... else: def interact(self, banner: Optional[str] = ...) -> None: ... def push(self, line: str) -> bool: ... @@ -26,13 +21,16 @@ class InteractiveConsole(InteractiveInterpreter): 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: ... + 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 compile_command(source: str, filename: str = ..., - symbol: str = ...) -> Optional[CodeType]: ... + 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/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index e98dee161ec6..1a596b95a4bb 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -1,8 +1,25 @@ import sys -from typing import Any, BinaryIO, Callable, Generator, IO, Iterable, Iterator, List, Optional, Protocol, Text, TextIO, Tuple, Type, TypeVar, Union, overload - -from abc import abstractmethod 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 @@ -16,16 +33,19 @@ _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: ... @@ -55,15 +75,13 @@ def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> b 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 lookup(__encoding: str) -> CodecInfo: ... def utf_16_be_decode(__obj: _Encoded, __errors: str = ..., __final: bool = ...) -> Tuple[_Decoded, int]: ... # undocumented def utf_16_be_encode(__obj: _Decoded, __errors: str = ...) -> Tuple[_Encoded, int]: ... # undocumented @@ -81,16 +99,18 @@ class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property def incrementaldecoder(self) -> _IncrementalDecoder: ... name: str - def __init__( - self, + def __new__( + cls, encode: _Encoder, decode: _Decoder, - streamreader: _StreamReader = ..., - streamwriter: _StreamWriter = ..., - incrementalencoder: _IncrementalEncoder = ..., - incrementaldecoder: _IncrementalDecoder = ..., - name: str = ..., - ) -> None: ... + 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: ... @@ -98,9 +118,13 @@ 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: str = ..., errors: str = ..., buffering: int = ...) -> StreamReaderWriter: ... -def EncodedFile(file: IO[_Encoded], data_encoding: str, file_encoding: str = ..., errors: str = ...) -> StreamRecoder: ... +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]: ... @@ -118,8 +142,8 @@ 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(name: str, error_handler: Callable[[UnicodeError], Tuple[Union[str, bytes], int]]) -> None: ... -def lookup_error(name: str) -> Callable[[UnicodeError], Tuple[Union[str, bytes], int]]: ... +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]: ... @@ -146,7 +170,7 @@ class IncrementalDecoder: errors: str def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def decode(self, object: _Encoded, final: bool = ...) -> _Decoded: ... + 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: ... diff --git a/mypy/typeshed/stdlib/codeop.pyi b/mypy/typeshed/stdlib/codeop.pyi index 0e1129e678d4..f3d6c2819ec6 100644 --- a/mypy/typeshed/stdlib/codeop.pyi +++ b/mypy/typeshed/stdlib/codeop.pyi @@ -1,6 +1,3 @@ -# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/codeop.py -# Source(py3): https://github.com/python/cpython/blob/master/Lib/codeop.py - from types import CodeType from typing import Optional diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 17309d3ca3fd..65f1e0e95b73 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,49 +1,49 @@ -# These are not exported. import sys import typing from typing import ( - TypeVar, Generic, Dict, overload, List, Tuple, - Any, Type, Optional, Union -) -# These are exported. -from . import abc - -from typing import ( + AbstractSet, + Any, + AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, AsyncIterator as AsyncIterator, Awaitable as Awaitable, + ByteString as ByteString, Callable as Callable, + Collection as Collection, Container as Container, Coroutine as Coroutine, + Dict, + Generator as Generator, + Generic, Hashable as Hashable, + ItemsView as ItemsView, Iterable as Iterable, Iterator as Iterator, - Sized as Sized, - Generator as Generator, - ByteString as ByteString, - Reversible as Reversible, + KeysView as KeysView, + List, Mapping as Mapping, MappingView as MappingView, - ItemsView as ItemsView, - KeysView as KeysView, - ValuesView as ValuesView, MutableMapping as MutableMapping, - Sequence as Sequence, MutableSequence as MutableSequence, MutableSet as MutableSet, - AbstractSet as Set, + Optional, + Reversible as Reversible, + Sequence as Sequence, + Sized as Sized, + Tuple, + Type, + TypeVar, + Union, + ValuesView as ValuesView, + overload, ) -if sys.version_info >= (3, 6): - from typing import ( - Collection as Collection, - AsyncGenerator as AsyncGenerator, - ) -_S = TypeVar('_S') -_T = TypeVar('_T') -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') +Set = AbstractSet +_S = TypeVar("_S") +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") # namedtuple is special-cased in the type checker; the initializer is ignored. if sys.version_info >= (3, 7): @@ -55,7 +55,8 @@ if sys.version_info >= (3, 7): module: Optional[str] = ..., defaults: Optional[Iterable[Any]] = ..., ) -> Type[Tuple[Any, ...]]: ... -elif sys.version_info >= (3, 6): + +else: def namedtuple( typename: str, field_names: Union[str, Iterable[str]], @@ -64,14 +65,10 @@ elif sys.version_info >= (3, 6): rename: bool = ..., module: Optional[str] = ..., ) -> Type[Tuple[Any, ...]]: ... -else: - def namedtuple( - typename: str, field_names: Union[str, Iterable[str]], verbose: bool = ..., rename: bool = ..., - ) -> Type[Tuple[Any, ...]]: ... class UserDict(MutableMapping[_KT, _VT]): data: Dict[_KT, _VT] - def __init__(self, dict: Optional[Mapping[_KT, _VT]] = ..., **kwargs: _VT) -> None: ... + def __init__(self, __dict: Optional[Mapping[_KT, _VT]] = ..., **kwargs: _VT) -> None: ... def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, item: _VT) -> None: ... @@ -116,7 +113,7 @@ class UserList(MutableSequence[_T]): def sort(self, *args: Any, **kwds: Any) -> None: ... def extend(self, other: Iterable[_T]) -> None: ... -_UserStringT = TypeVar('_UserStringT', bound=UserString) +_UserStringT = TypeVar("_UserStringT", bound=UserString) class UserString(Sequence[str]): data: str @@ -140,7 +137,10 @@ class UserString(Sequence[str]): def casefold(self: _UserStringT) -> _UserStringT: ... def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... def count(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... - def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UserStringT: ... + if sys.version_info >= (3, 8): + def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> bytes: ... + else: + def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UserStringT: ... def endswith(self, suffix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... def find(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... @@ -172,7 +172,9 @@ class UserString(Sequence[str]): if sys.version_info >= (3, 9): def removeprefix(self: _UserStringT, __prefix: Union[str, UserString]) -> _UserStringT: ... def removesuffix(self: _UserStringT, __suffix: Union[str, UserString]) -> _UserStringT: ... - def replace(self: _UserStringT, old: Union[str, UserString], new: Union[str, UserString], maxsplit: int = ...) -> _UserStringT: ... + def replace( + self: _UserStringT, old: Union[str, UserString], new: Union[str, UserString], maxsplit: int = ... + ) -> _UserStringT: ... def rfind(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... @@ -189,15 +191,10 @@ class UserString(Sequence[str]): def upper(self: _UserStringT) -> _UserStringT: ... def zfill(self: _UserStringT, width: int) -> _UserStringT: ... - -# Technically, deque only derives from MutableSequence in 3.5 (before then, the insert and index -# methods did not exist). -# But in practice it's not worth losing sleep over. class deque(MutableSequence[_T], Generic[_T]): @property def maxlen(self) -> Optional[int]: ... - def __init__(self, iterable: Iterable[_T] = ..., - maxlen: Optional[int] = ...) -> None: ... + def __init__(self, iterable: Iterable[_T] = ..., maxlen: Optional[int] = ...) -> None: ... def append(self, x: _T) -> None: ... def appendleft(self, x: _T) -> None: ... def clear(self) -> None: ... @@ -207,17 +204,15 @@ class deque(MutableSequence[_T], Generic[_T]): def extendleft(self, iterable: Iterable[_T]) -> None: ... def insert(self, i: int, x: _T) -> None: ... def index(self, x: _T, start: int = ..., stop: int = ...) -> int: ... - def pop(self, i: int = ...) -> _T: ... + def pop(self) -> _T: ... # type: ignore def popleft(self) -> _T: ... def remove(self, value: _T) -> None: ... def reverse(self) -> None: ... - def rotate(self, n: int) -> None: ... - + def rotate(self, n: int = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __str__(self) -> str: ... def __hash__(self) -> int: ... - # These methods of deque don't really take slices, but we need to # define them as taking a slice to satisfy MutableSequence. @overload @@ -232,12 +227,9 @@ class deque(MutableSequence[_T], Generic[_T]): def __delitem__(self, i: int) -> None: ... @overload def __delitem__(self, s: slice) -> None: ... - def __contains__(self, o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... - def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... - def __add__(self, other: deque[_T]) -> deque[_T]: ... def __mul__(self, other: int) -> deque[_T]: ... def __imul__(self, other: int) -> None: ... @@ -251,16 +243,13 @@ class Counter(Dict[_T, int], Generic[_T]): def __init__(self, __iterable: Iterable[_T]) -> None: ... def copy(self: _S) -> _S: ... def elements(self) -> Iterator[_T]: ... - def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... - @overload def subtract(self, __iterable: None = ...) -> None: ... @overload def subtract(self, __mapping: Mapping[_T, int]) -> None: ... @overload def subtract(self, __iterable: Iterable[_T]) -> None: ... - # The Iterable[Tuple[...]] argument type is not actually desirable # (the tuples will be added as keys, breaking type safety) but # it's included so that the signature is compatible with @@ -272,22 +261,23 @@ class Counter(Dict[_T, int], Generic[_T]): def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... @overload def update(self, __m: None = ..., **kwargs: int) -> None: ... - def __add__(self, other: Counter[_T]) -> Counter[_T]: ... def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore def __pos__(self) -> Counter[_T]: ... def __neg__(self) -> Counter[_T]: ... def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... - def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore class _OrderedDictKeysView(KeysView[_KT], Reversible[_KT]): def __reversed__(self) -> Iterator[_KT]: ... + class _OrderedDictItemsView(ItemsView[_KT, _VT], Reversible[Tuple[_KT, _VT]]): def __reversed__(self) -> Iterator[Tuple[_KT, _VT]]: ... + class _OrderedDictValuesView(ValuesView[_VT], Reversible[_VT]): def __reversed__(self) -> Iterator[_VT]: ... @@ -302,7 +292,6 @@ class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Optional[Callable[[], _VT]] - @overload def __init__(self, **kwargs: _VT) -> None: ... @overload @@ -310,34 +299,29 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - map: Mapping[_KT, _VT]) -> None: ... + def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__( + self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT + ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... # TODO __reversed__ def copy(self: _S) -> _S: ... class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ... - @property def maps(self) -> List[Mapping[_KT, _VT]]: ... - def new_child(self, m: Mapping[_KT, _VT] = ...) -> typing.ChainMap[_KT, _VT]: ... - @property def parents(self) -> typing.ChainMap[_KT, _VT]: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... def __getitem__(self, k: _KT) -> _VT: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... + def __missing__(self, key: _KT) -> _VT: ... # undocumented diff --git a/mypy/typeshed/stdlib/collections/abc.pyi b/mypy/typeshed/stdlib/collections/abc.pyi index 11718438832b..c9d69978afd2 100644 --- a/mypy/typeshed/stdlib/collections/abc.pyi +++ b/mypy/typeshed/stdlib/collections/abc.pyi @@ -1,36 +1,27 @@ -# Stubs for collections.abc (introduced from Python 3.3) -# -# https://docs.python.org/3.3/whatsnew/3.3.html#collections -import sys - from . import ( + AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, AsyncIterator as AsyncIterator, Awaitable as Awaitable, ByteString as ByteString, + Callable as Callable, + Collection as Collection, Container as Container, Coroutine as Coroutine, Generator as Generator, Hashable as Hashable, + ItemsView as ItemsView, Iterable as Iterable, Iterator as Iterator, - Sized as Sized, - Callable as Callable, + KeysView as KeysView, Mapping as Mapping, + MappingView as MappingView, MutableMapping as MutableMapping, - Sequence as Sequence, MutableSequence as MutableSequence, - Set as Set, MutableSet as MutableSet, - MappingView as MappingView, - ItemsView as ItemsView, - KeysView as KeysView, + Reversible as Reversible, + Sequence as Sequence, + Set as Set, + Sized as Sized, ValuesView as ValuesView, ) - -if sys.version_info >= (3, 6): - from . import ( - Collection as Collection, - Reversible as Reversible, - AsyncGenerator as AsyncGenerator, - ) diff --git a/mypy/typeshed/stdlib/colorsys.pyi b/mypy/typeshed/stdlib/colorsys.pyi index c8b5591879f6..8db2e2c9ab3a 100644 --- a/mypy/typeshed/stdlib/colorsys.pyi +++ b/mypy/typeshed/stdlib/colorsys.pyi @@ -1,5 +1,3 @@ -# Stubs for colorsys - from typing import Tuple def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ... diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index 3be83d5ccd1a..bcc2a8e8275d 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -2,11 +2,6 @@ import sys from _typeshed import AnyPath from typing import Any, Optional, Pattern -if sys.version_info < (3, 6): - _SuccessType = bool -else: - _SuccessType = int - if sys.version_info >= (3, 7): from py_compile import PycInvalidationMode @@ -26,7 +21,8 @@ if sys.version_info >= (3, 9): stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved prependdir: Optional[AnyPath] = ..., limit_sl_dest: Optional[AnyPath] = ..., - ) -> _SuccessType: ... + hardlink_dupes: bool = ..., + ) -> int: ... def compile_file( fullname: AnyPath, ddir: Optional[AnyPath] = ..., @@ -40,7 +36,9 @@ if sys.version_info >= (3, 9): stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved prependdir: Optional[AnyPath] = ..., limit_sl_dest: Optional[AnyPath] = ..., - ) -> _SuccessType: ... + hardlink_dupes: bool = ..., + ) -> int: ... + elif sys.version_info >= (3, 7): def compile_dir( dir: AnyPath, @@ -53,7 +51,7 @@ elif sys.version_info >= (3, 7): optimize: int = ..., workers: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., - ) -> _SuccessType: ... + ) -> int: ... def compile_file( fullname: AnyPath, ddir: Optional[AnyPath] = ..., @@ -63,7 +61,7 @@ elif sys.version_info >= (3, 7): legacy: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., - ) -> _SuccessType: ... + ) -> int: ... else: # rx can be any object with a 'search' method; once we have Protocols we can change the type @@ -77,7 +75,7 @@ else: legacy: bool = ..., optimize: int = ..., workers: int = ..., - ) -> _SuccessType: ... + ) -> int: ... def compile_file( fullname: AnyPath, ddir: Optional[AnyPath] = ..., @@ -86,7 +84,7 @@ else: quiet: int = ..., legacy: bool = ..., optimize: int = ..., - ) -> _SuccessType: ... + ) -> int: ... if sys.version_info >= (3, 7): def compile_path( @@ -97,7 +95,8 @@ if sys.version_info >= (3, 7): legacy: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., - ) -> _SuccessType: ... + ) -> int: ... + else: def compile_path( skip_curdir: bool = ..., @@ -106,4 +105,4 @@ else: quiet: int = ..., legacy: bool = ..., optimize: int = ..., - ) -> _SuccessType: ... + ) -> int: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi index 9dfe12bac79e..f3b54e54228c 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi @@ -1,18 +1,20 @@ import sys + from ._base import ( + ALL_COMPLETED as ALL_COMPLETED, FIRST_COMPLETED as FIRST_COMPLETED, FIRST_EXCEPTION as FIRST_EXCEPTION, - ALL_COMPLETED as ALL_COMPLETED, CancelledError as CancelledError, - TimeoutError as TimeoutError, - Future as Future, Executor as Executor, - wait as wait, + Future as Future, + TimeoutError as TimeoutError, as_completed as as_completed, + wait as wait, ) +from .process import ProcessPoolExecutor as ProcessPoolExecutor +from .thread import ThreadPoolExecutor as ThreadPoolExecutor + if sys.version_info >= (3, 8): from ._base import InvalidStateError as InvalidStateError if sys.version_info >= (3, 7): from ._base import BrokenExecutor as BrokenExecutor -from .thread import ThreadPoolExecutor as ThreadPoolExecutor -from .process import ProcessPoolExecutor as ProcessPoolExecutor diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 27caf7c3ccff..ca4087948c3e 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -1,8 +1,25 @@ +import sys import threading +from abc import abstractmethod from logging import Logger -from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Tuple, Optional, Set, List -from types import TracebackType -import sys +from typing import ( + Any, + Callable, + Container, + Generic, + Iterable, + Iterator, + List, + Optional, + Protocol, + Sequence, + Set, + TypeVar, + overload, +) + +if sys.version_info >= (3, 9): + from types import GenericAlias FIRST_COMPLETED: str FIRST_EXCEPTION: str @@ -17,13 +34,23 @@ LOGGER: Logger class Error(Exception): ... class CancelledError(Error): ... class TimeoutError(Error): ... + if sys.version_info >= (3, 8): class InvalidStateError(Error): ... if sys.version_info >= (3, 7): class BrokenExecutor(RuntimeError): ... -_T = TypeVar('_T') +_T = TypeVar("_T") + +_T_co = TypeVar("_T_co", covariant=True) + +# Copied over Collection implementation as it does not exist in Python 2 and <3.6. +# Also to solve pytype issues with _Collection. +class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... class Future(Generic[_T]): def __init__(self) -> None: ... @@ -35,32 +62,40 @@ class Future(Generic[_T]): def result(self, timeout: Optional[float] = ...) -> _T: ... def set_running_or_notify_cancel(self) -> bool: ... def set_result(self, result: _T) -> None: ... - - if sys.version_info >= (3,): - def exception(self, timeout: Optional[float] = ...) -> Optional[BaseException]: ... - def set_exception(self, exception: Optional[BaseException]) -> None: ... - else: - def exception(self, timeout: Optional[float] = ...) -> Any: ... - def exception_info(self, timeout: Optional[float] = ...) -> Tuple[Any, Optional[TracebackType]]: ... - def set_exception(self, exception: Any) -> None: ... - def set_exception_info(self, exception: Any, traceback: Optional[TracebackType]) -> None: ... - + def exception(self, timeout: Optional[float] = ...) -> Optional[BaseException]: ... + def set_exception(self, exception: Optional[BaseException]) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Executor: - def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... - if sys.version_info >= (3, 5): - def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ..., - chunksize: int = ...) -> Iterator[_T]: ... + if sys.version_info >= (3, 9): + def submit(self, __fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + else: + def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def map( + self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ..., chunksize: int = ... + ) -> Iterator[_T]: ... + if sys.version_info >= (3, 9): + def shutdown(self, wait: bool = ..., *, cancel_futures: bool = ...) -> None: ... else: - def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ...,) -> Iterator[_T]: ... - def shutdown(self, wait: bool = ...) -> None: ... + def shutdown(self, wait: bool = ...) -> None: ... def __enter__(self: _T) -> _T: ... def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Optional[bool]: ... def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... -def wait(fs: Iterable[Future[_T]], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future[_T]], - Set[Future[_T]]]: ... +# Ideally this would be a namedtuple, but mypy doesn't support generic tuple types. See #1976 +class DoneAndNotDoneFutures(Sequence[Set[Future[_T]]]): + done: Set[Future[_T]] + not_done: Set[Future[_T]] + def __new__(_cls, done: Set[Future[_T]], not_done: Set[Future[_T]]) -> DoneAndNotDoneFutures[_T]: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> Set[Future[_T]]: ... + @overload + def __getitem__(self, s: slice) -> DoneAndNotDoneFutures[_T]: ... + +def wait(fs: Iterable[Future[_T]], timeout: Optional[float] = ..., return_when: str = ...) -> DoneAndNotDoneFutures[_T]: ... class _Waiter: event: threading.Event @@ -70,7 +105,6 @@ class _Waiter: def add_exception(self, future: Future[Any]) -> None: ... def add_cancelled(self, future: Future[Any]) -> None: ... - class _AsCompletedWaiter(_Waiter): lock: threading.Lock def __init__(self) -> None: ... @@ -78,13 +112,11 @@ class _AsCompletedWaiter(_Waiter): def add_exception(self, future: Future[Any]) -> None: ... def add_cancelled(self, future: Future[Any]) -> None: ... - class _FirstCompletedWaiter(_Waiter): def add_result(self, future: Future[Any]) -> None: ... def add_exception(self, future: Future[Any]) -> None: ... def add_cancelled(self, future: Future[Any]) -> None: ... - class _AllCompletedWaiter(_Waiter): num_pending_calls: int stop_on_exception: bool @@ -94,7 +126,6 @@ class _AllCompletedWaiter(_Waiter): def add_exception(self, future: Future[Any]) -> None: ... def add_cancelled(self, future: Future[Any]) -> None: ... - class _AcquireFutures: futures: Iterable[Future[Any]] def __init__(self, futures: Iterable[Future[Any]]) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 960a59f50f0d..a66557671ce5 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -1,23 +1,28 @@ +import sys from typing import Any, Callable, Optional, Tuple + from ._base import Executor -import sys EXTRA_QUEUED_CALLS: Any if sys.version_info >= (3, 7): from ._base import BrokenExecutor class BrokenProcessPool(BrokenExecutor): ... -elif sys.version_info >= (3,): + +else: class BrokenProcessPool(RuntimeError): ... if sys.version_info >= (3, 7): from multiprocessing.context import BaseContext - class ProcessPoolExecutor(Executor): - def __init__(self, max_workers: Optional[int] = ..., - mp_context: Optional[BaseContext] = ..., - initializer: Optional[Callable[..., None]] = ..., - initargs: Tuple[Any, ...] = ...) -> None: ... + def __init__( + self, + max_workers: Optional[int] = ..., + mp_context: Optional[BaseContext] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Tuple[Any, ...] = ..., + ) -> None: ... + else: class ProcessPoolExecutor(Executor): def __init__(self, max_workers: Optional[int] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index 82c8ddd03d94..aedfe5d05bad 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -1,26 +1,36 @@ -from typing import Any, Callable, Iterable, Mapping, Optional, Tuple, TypeVar, Generic -from ._base import Executor, Future +import queue import sys +from typing import Any, Callable, Generic, Iterable, Mapping, Optional, Tuple, TypeVar + +from ._base import Executor, Future if sys.version_info >= (3, 7): from ._base import BrokenExecutor class BrokenThreadPool(BrokenExecutor): ... -_S = TypeVar('_S') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_S = TypeVar("_S") class ThreadPoolExecutor(Executor): if sys.version_info >= (3, 7): - def __init__(self, max_workers: Optional[int] = ..., - thread_name_prefix: str = ..., - initializer: Optional[Callable[..., None]] = ..., - initargs: Tuple[Any, ...] = ...) -> None: ... - elif sys.version_info >= (3, 6) or sys.version_info < (3,): - def __init__(self, max_workers: Optional[int] = ..., - thread_name_prefix: str = ...) -> None: ... + _work_queue: queue.SimpleQueue[Any] + else: + _work_queue: queue.Queue[Any] + if sys.version_info >= (3, 7): + def __init__( + self, + max_workers: Optional[int] = ..., + thread_name_prefix: str = ..., + 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: ... - class _WorkItem(Generic[_S]): future: Future[_S] fn: Callable[..., _S] @@ -28,3 +38,5 @@ class _WorkItem(Generic[_S]): kwargs: Mapping[str, Any] def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... def run(self) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index 93a6393bdd02..e842e5e6e829 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -1,15 +1,33 @@ -from _typeshed import AnyPath, StrPath import sys -from typing import (AbstractSet, MutableMapping, Mapping, Dict, Sequence, List, - Union, Iterable, Iterator, Callable, Any, IO, overload, - Optional, Pattern, Type, TypeVar, ClassVar, Tuple) +from _typeshed import AnyPath, StrPath, SupportsWrite +from typing import ( + AbstractSet, + Any, + Callable, + ClassVar, + Dict, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + Optional, + Pattern, + Sequence, + Tuple, + Type, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal # Internal type aliases _section = Mapping[str, str] _parser = MutableMapping[str, _section] _converter = Callable[[str], Any] _converters = Dict[str, _converter] -_T = TypeVar('_T') +_T = TypeVar("_T") if sys.version_info >= (3, 7): _Path = AnyPath @@ -20,123 +38,123 @@ DEFAULTSECT: str MAX_INTERPOLATION_DEPTH: int class Interpolation: - def before_get(self, parser: _parser, - section: str, - option: str, - value: str, - defaults: _section) -> str: ... - - def before_set(self, parser: _parser, - section: str, - option: str, - value: str) -> str: ... - - def before_read(self, parser: _parser, - section: str, - option: str, - value: str) -> str: ... - - def before_write(self, parser: _parser, - section: str, - option: str, - value: str) -> str: ... - + def before_get(self, parser: _parser, section: str, option: str, value: str, defaults: _section) -> str: ... + def before_set(self, parser: _parser, section: str, option: str, value: str) -> str: ... + def before_read(self, parser: _parser, section: str, option: str, value: str) -> str: ... + def before_write(self, parser: _parser, section: str, option: str, value: str) -> str: ... class BasicInterpolation(Interpolation): ... class ExtendedInterpolation(Interpolation): ... class LegacyInterpolation(Interpolation): ... - class RawConfigParser(_parser): - BOOLEAN_STATES: ClassVar[Mapping[str, bool]] = ... # Undocumented - def __init__(self, - defaults: Optional[_section] = ..., - dict_type: Type[Mapping[str, str]] = ..., - allow_no_value: bool = ..., - *, - delimiters: Sequence[str] = ..., - comment_prefixes: Sequence[str] = ..., - inline_comment_prefixes: Optional[Sequence[str]] = ..., - strict: bool = ..., - empty_lines_in_values: bool = ..., - default_section: str = ..., - interpolation: Optional[Interpolation] = ..., - converters: _converters = ...) -> None: ... + _SECT_TMPL: ClassVar[str] = ... # Undocumented + _OPT_TMPL: ClassVar[str] = ... # Undocumented + _OPT_NV_TMPL: ClassVar[str] = ... # Undocumented - def __len__(self) -> int: ... + SECTCRE: Pattern[str] = ... + OPTCRE: ClassVar[Pattern[str]] = ... + OPTCRE_NV: ClassVar[Pattern[str]] = ... # Undocumented + NONSPACECRE: ClassVar[Pattern[str]] = ... # Undocumented + BOOLEAN_STATES: ClassVar[Mapping[str, bool]] = ... # Undocumented + default_section: str + @overload + def __init__( + self, + defaults: Optional[Mapping[str, Optional[str]]] = ..., + dict_type: Type[Mapping[str, str]] = ..., + allow_no_value: Literal[True] = ..., + *, + delimiters: Sequence[str] = ..., + comment_prefixes: Sequence[str] = ..., + inline_comment_prefixes: Optional[Sequence[str]] = ..., + strict: bool = ..., + empty_lines_in_values: bool = ..., + default_section: str = ..., + interpolation: Optional[Interpolation] = ..., + converters: _converters = ..., + ) -> None: ... + @overload + def __init__( + self, + defaults: Optional[_section] = ..., + dict_type: Type[Mapping[str, str]] = ..., + allow_no_value: bool = ..., + *, + delimiters: Sequence[str] = ..., + comment_prefixes: Sequence[str] = ..., + inline_comment_prefixes: Optional[Sequence[str]] = ..., + strict: bool = ..., + empty_lines_in_values: bool = ..., + default_section: str = ..., + interpolation: Optional[Interpolation] = ..., + converters: _converters = ..., + ) -> None: ... + def __len__(self) -> int: ... def __getitem__(self, section: str) -> SectionProxy: ... - def __setitem__(self, section: str, options: _section) -> None: ... - def __delitem__(self, section: str) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def defaults(self) -> _section: ... - def sections(self) -> List[str]: ... - def add_section(self, section: str) -> None: ... - def has_section(self, section: str) -> bool: ... - def options(self, section: str) -> List[str]: ... - def has_option(self, section: str, option: str) -> bool: ... - - def read(self, filenames: Union[_Path, Iterable[_Path]], - encoding: Optional[str] = ...) -> List[str]: ... + def read(self, filenames: Union[_Path, Iterable[_Path]], encoding: Optional[str] = ...) -> List[str]: ... def read_file(self, f: Iterable[str], source: Optional[str] = ...) -> None: ... def read_string(self, string: str, source: str = ...) -> None: ... - def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], - source: str = ...) -> None: ... + def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = ...) -> None: ... def readfp(self, fp: Iterable[str], filename: Optional[str] = ...) -> None: ... - # These get* methods are partially applied (with the same names) in # SectionProxy; the stubs should be kept updated together - @overload def getint(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> int: ... @overload - def getint(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[int, _T]: ... + def getint( + self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ... + ) -> Union[int, _T]: ... @overload def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> float: ... @overload - def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[float, _T]: ... + def getfloat( + self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ... + ) -> Union[float, _T]: ... @overload def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> bool: ... @overload - def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[bool, _T]: ... - - def _get_conv(self, section: str, option: str, conv: Callable[[str], _T], *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> _T: ... - + def getboolean( + self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ... + ) -> Union[bool, _T]: ... + def _get_conv( + self, + section: str, + option: str, + conv: Callable[[str], _T], + *, + raw: bool = ..., + vars: Optional[_section] = ..., + fallback: _T = ..., + ) -> _T: ... # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore def get(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> str: ... - @overload - def get(self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T) -> Union[str, _T]: ... - + def get( + self, section: str, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T + ) -> Union[str, _T]: ... @overload def items(self, *, raw: bool = ..., vars: Optional[_section] = ...) -> AbstractSet[Tuple[str, SectionProxy]]: ... - @overload def items(self, section: str, raw: bool = ..., vars: Optional[_section] = ...) -> List[Tuple[str, str]]: ... - def set(self, section: str, option: str, value: Optional[str] = ...) -> None: ... - - def write(self, fp: IO[str], space_around_delimiters: bool = ...) -> None: ... - + def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = ...) -> None: ... def remove_option(self, section: str, option: str) -> bool: ... - def remove_section(self, section: str) -> bool: ... - def optionxform(self, optionstr: str) -> str: ... - class ConfigParser(RawConfigParser): ... - class SafeConfigParser(ConfigParser): ... class SectionProxy(MutableMapping[str, str]): @@ -152,22 +170,24 @@ class SectionProxy(MutableMapping[str, str]): @property def name(self) -> str: ... def get(self, option: str, fallback: Optional[str] = ..., *, raw: bool = ..., vars: Optional[_section] = ..., _impl: Optional[Any] = ..., **kwargs: Any) -> str: ... # type: ignore - # These are partially-applied version of the methods with the same names in # RawConfigParser; the stubs should be kept updated together @overload def getint(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> int: ... @overload - def getint(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[int, _T]: ... + def getint(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: Optional[_section] = ...) -> Union[int, _T]: ... @overload def getfloat(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> float: ... @overload - def getfloat(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[float, _T]: ... + def getfloat( + self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: Optional[_section] = ... + ) -> Union[float, _T]: ... @overload def getboolean(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ...) -> bool: ... @overload - def getboolean(self, option: str, *, raw: bool = ..., vars: Optional[_section] = ..., fallback: _T = ...) -> Union[bool, _T]: ... - + def getboolean( + self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: Optional[_section] = ... + ) -> Union[bool, _T]: ... # SectionProxy can have arbitrary attributes when custon converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... @@ -180,24 +200,20 @@ class ConverterMapping(MutableMapping[str, Optional[_converter]]): def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... - class Error(Exception): message: str def __init__(self, msg: str = ...) -> None: ... - class NoSectionError(Error): section: str def __init__(self, section: str) -> None: ... - class DuplicateSectionError(Error): section: str source: Optional[str] lineno: Optional[int] def __init__(self, section: str, source: Optional[str] = ..., lineno: Optional[int] = ...) -> None: ... - class DuplicateOptionError(Error): section: str option: str @@ -205,38 +221,31 @@ class DuplicateOptionError(Error): lineno: Optional[int] def __init__(self, section: str, option: str, source: Optional[str] = ..., lineno: Optional[str] = ...) -> None: ... - class NoOptionError(Error): section: str option: str def __init__(self, option: str, section: str) -> None: ... - class InterpolationError(Error): section: str option: str def __init__(self, option: str, section: str, msg: str) -> None: ... - class InterpolationDepthError(InterpolationError): def __init__(self, option: str, section: str, rawval: object) -> None: ... - class InterpolationMissingOptionError(InterpolationError): reference: str def __init__(self, option: str, section: str, rawval: object, reference: str) -> None: ... - class InterpolationSyntaxError(InterpolationError): ... - class ParsingError(Error): source: str errors: List[Tuple[int, str]] def __init__(self, source: Optional[str] = ..., filename: Optional[str] = ...) -> None: ... def append(self, lineno: int, line: str) -> None: ... - class MissingSectionHeaderError(ParsingError): lineno: int line: str diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index f0dec323908a..509bcb6e4fc3 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,34 +1,30 @@ -# ContextManager aliased here for backwards compatibility; TODO eventually remove this -from typing import ( - Any, Callable, Generator, IO, Iterable, Iterator, Optional, Type, - Generic, TypeVar, overload -) -from types import TracebackType import sys -from typing import ContextManager as ContextManager +from types import TracebackType +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Type, TypeVar, overload if sys.version_info >= (3, 5): from typing import AsyncContextManager, AsyncIterator if sys.version_info >= (3, 6): - from typing import ContextManager as AbstractContextManager + AbstractContextManager = ContextManager if sys.version_info >= (3, 7): - from typing import AsyncContextManager as AbstractAsyncContextManager + AbstractAsyncContextManager = AsyncContextManager -_T = TypeVar('_T') -_F = TypeVar('_F', bound=Callable[..., Any]) +_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) +_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], Generic[_T]): + class _GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]: ... + else: - class GeneratorContextManager(ContextManager[_T], Generic[_T]): + class GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... @@ -38,69 +34,66 @@ if sys.version_info >= (3, 7): if sys.version_info < (3,): def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... -class closing(ContextManager[_T], Generic[_T]): +class closing(ContextManager[_T]): def __init__(self, thing: _T) -> 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[None]): - def __init__(self, new_target: Optional[IO[str]]) -> 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[None]): - def __init__(self, new_target: Optional[IO[str]]) -> None: ... + 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: Callable[..., None]) -> Callable[..., ContextManager[None]]: ... - - _U = TypeVar('_U', bound=ExitStack) - + 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 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: ... + 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 - _S = TypeVar('_S', bound=AsyncExitStack) + _S = TypeVar("_S", bound=AsyncExitStack) - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], - Optional[BaseException], - Optional[TracebackType]], Awaitable[bool]] + _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] - _ACM_EF = TypeVar('_ACM_EF', AsyncContextManager[Any], _ExitCoroFunc) - + _ACM_EF = TypeVar("_ACM_EF", AsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AsyncContextManager[AsyncExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: ContextManager[_T]) -> _T: ... def enter_async_context(self, cm: AsyncContextManager[_T]) -> Awaitable[_T]: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... - def callback(self, callback: Callable[..., Any], - *args: Any, **kwds: Any) -> Callable[..., Any]: ... - def push_async_callback(self, callback: _CallbackCoroFunc, - *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... + def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... + def push_async_callback(self, callback: _CallbackCoroFunc, *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... def pop_all(self: _S) -> _S: ... def aclose(self) -> Awaitable[None]: ... def __aenter__(self: _S) -> Awaitable[_S]: ... - def __aexit__(self, __exc_type: Optional[Type[BaseException]], - __exc_value: Optional[BaseException], - __traceback: Optional[TracebackType]) -> Awaitable[bool]: ... + def __aexit__( + self, + __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> Awaitable[bool]: ... if sys.version_info >= (3, 7): @overload diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index a90c2a8b5f65..810b699b668d 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -1,14 +1,24 @@ -from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar +import sys +from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, Union, overload -_T = TypeVar('_T') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_T = TypeVar("_T") +_D = TypeVar("_D") class ContextVar(Generic[_T]): def __init__(self, name: str, *, default: _T = ...) -> None: ... @property def name(self) -> str: ... - def get(self, default: _T = ...) -> _T: ... + @overload + def get(self) -> _T: ... + @overload + def get(self, default: Union[_D, _T]) -> Union[_D, _T]: ... def set(self, value: _T) -> Token[_T]: ... def reset(self, token: Token[_T]) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Token(Generic[_T]): @property @@ -16,6 +26,8 @@ class Token(Generic[_T]): @property def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express MISSING: ClassVar[object] + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... def copy_context() -> Context: ... diff --git a/mypy/typeshed/stdlib/copy.pyi b/mypy/typeshed/stdlib/copy.pyi index 523802a84ee7..b51c79c66c6a 100644 --- a/mypy/typeshed/stdlib/copy.pyi +++ b/mypy/typeshed/stdlib/copy.pyi @@ -1,14 +1,14 @@ -# Stubs for copy +from typing import Any, Dict, Optional, TypeVar -from typing import TypeVar, Optional, Dict, Any - -_T = TypeVar('_T') +_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, _T]] = ..., _nil: Any = ...) -> _T: ... +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/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index a64a82c700d0..ea07ba410b6d 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,14 +1,16 @@ +from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union -from typing import TypeVar, Callable, Union, Tuple, Any, Optional, SupportsInt, Hashable, List - - -_Type = TypeVar("_Type", bound=type) -_Reduce = Union[Tuple[Callable[..., _Type], Tuple[Any, ...]], Tuple[Callable[..., _Type], Tuple[Any, ...], Optional[Any]]] +_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: _Type, pickle_function: Callable[[_Type], Union[str, _Reduce[_Type]]], constructor_ob: Optional[Callable[[_Reduce[_Type]], _Type]] = ...) -> None: ... -def constructor(object: Callable[[_Reduce[_Type]], _Type]) -> None: ... +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/crypt.pyi b/mypy/typeshed/stdlib/crypt.pyi index 621ce0bd7150..18893721a11f 100644 --- a/mypy/typeshed/stdlib/crypt.pyi +++ b/mypy/typeshed/stdlib/crypt.pyi @@ -3,7 +3,6 @@ from typing import List, Optional, Union if sys.version_info >= (3, 3): class _Method: ... - METHOD_CRYPT: _Method METHOD_MD5: _Method METHOD_SHA256: _Method @@ -18,5 +17,6 @@ if sys.version_info >= (3, 3): else: def mksalt(method: Optional[_Method] = ...) -> str: ... def crypt(word: str, salt: Optional[Union[str, _Method]] = ...) -> str: ... + else: def crypt(word: str, salt: str) -> str: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 1181f231c18d..606694dca533 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -18,7 +18,7 @@ from _csv import ( writer as writer, ) from collections import OrderedDict -from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Text, Type, Union +from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Text, Type _DictRow = Mapping[str, Any] diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index d313e8463b0c..f06fa7396edf 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -1,23 +1,35 @@ -# Stubs for ctypes - +import sys from array import array from typing import ( - Any, Callable, ClassVar, Iterator, Iterable, List, Mapping, Optional, Sequence, Sized, Text, - Tuple, Type, Generic, TypeVar, overload, + Any, + Callable, + ClassVar, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Text, + Tuple, + Type, + TypeVar, + Union as _UnionT, + overload, ) -from typing import Union as _UnionT -import sys -_T = TypeVar('_T') -_DLLT = TypeVar('_DLLT', bound=CDLL) -_CT = TypeVar('_CT', bound=_CData) +if sys.version_info >= (3, 9): + from types import GenericAlias +_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] = ... @@ -33,11 +45,13 @@ class CDLL(object): use_last_error: bool = ..., winmode: Optional[int] = ..., ) -> None: ... - def __getattr__(self, name: str) -> _FuncPointer: ... - def __getitem__(self, name: str) -> _FuncPointer: ... -if sys.platform == 'win32': + 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]): @@ -45,9 +59,11 @@ class LibraryLoader(Generic[_DLLT]): def __getattr__(self, name: str) -> _DLLT: ... def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... cdll: LibraryLoader[CDLL] = ... -if sys.platform == 'win32': +if sys.platform == "win32": windll: LibraryLoader[WinDLL] = ... oledll: LibraryLoader[OleDLL] = ... pydll: LibraryLoader[PyDLL] = ... @@ -66,6 +82,7 @@ class _CDataMeta(type): # 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 = ... @@ -81,17 +98,12 @@ class _CData(metaclass=_CDataMeta): @classmethod def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... -class _PointerLike(_CData): ... - -_ECT = Callable[[Optional[Type[_CData]], - _FuncPointer, - Tuple[_CData, ...]], - _CData] -_PF = _UnionT[ - Tuple[int], - Tuple[int, str], - Tuple[int, str, Any] -] +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], None], None] = ... argtypes: Sequence[Type[_CData]] = ... @@ -101,28 +113,26 @@ class _FuncPointer(_PointerLike, _CData): @overload def __init__(self, callable: Callable[..., Any]) -> None: ... @overload - def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], - paramflags: Tuple[_PF, ...] = ...) -> None: ... + 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 __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]: ... -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]: ... +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: ... @@ -138,21 +148,27 @@ _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: ... -_PT = TypeVar('_PT', bound=_PointerLike) -def cast(obj: _UnionT[_CData, _CArgObject], type: Type[_PT]) -> _PT: ... -def create_string_buffer(init_or_size: _UnionT[int, bytes], - size: Optional[int] = ...) -> Array[c_char]: ... + +_CastT = TypeVar("_CastT", bound=_CanCastTo) + +def cast(obj: _UnionT[_CData, _CArgObject, int], type: 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_or_size: _UnionT[int, Text], - size: Optional[int] = ...) -> Array[c_wchar]: ... -if sys.platform == 'win32': + +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': + +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]]: ... @@ -174,16 +190,21 @@ 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': + +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: ... + +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): @@ -194,62 +215,56 @@ 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': +if sys.platform == "win32": class HRESULT(_SimpleCData[int]): ... # TODO undocumented -class py_object(_SimpleCData[_T]): ... +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: ... @@ -290,3 +305,5 @@ class Array(Generic[_CT], _CData): # Can't inherit from Sized because the metaclass conflict between # Sized and _CData prevents using _CDataMeta. def __len__(self) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/ctypes/util.pyi b/mypy/typeshed/stdlib/ctypes/util.pyi index 7077d9d2f1e9..20914c70a05c 100644 --- a/mypy/typeshed/stdlib/ctypes/util.pyi +++ b/mypy/typeshed/stdlib/ctypes/util.pyi @@ -1,8 +1,7 @@ -# Stubs for ctypes.util - -from typing import Optional import sys +from typing import Optional def find_library(name: str) -> Optional[str]: ... -if sys.platform == 'win32': + +if sys.platform == "win32": def find_msvcrt() -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index c5a6226b25c0..c178a9bdf936 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -1,6 +1,23 @@ from ctypes import ( - _SimpleCData, Array, Structure, 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, + 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, ) @@ -15,7 +32,9 @@ 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 @@ -86,6 +105,7 @@ class RECT(Structure): top: LONG right: LONG bottom: LONG + RECTL = RECT _RECTL = RECT tagRECT = RECT @@ -95,6 +115,7 @@ class _SMALL_RECT(Structure): Top: SHORT Right: SHORT Bottom: SHORT + SMALL_RECT = _SMALL_RECT class _COORD(Structure): @@ -104,6 +125,7 @@ class _COORD(Structure): class POINT(Structure): x: LONG y: LONG + POINTL = POINT _POINTL = POINT tagPOINT = POINT @@ -111,6 +133,7 @@ tagPOINT = POINT class SIZE(Structure): cx: LONG cy: LONG + SIZEL = SIZE tagSIZE = SIZE @@ -119,6 +142,7 @@ def RGB(red: int, green: int, blue: int) -> int: ... class FILETIME(Structure): dwLowDateTime: DWORD dwHighDateTime: DWORD + _FILETIME = FILETIME class MSG(Structure): @@ -128,6 +152,7 @@ class MSG(Structure): lParam: LPARAM time: DWORD pt: POINT + tagMSG = MSG MAX_PATH: int diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index be7362647b2b..73e84fba3763 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -1,8 +1,8 @@ from _curses import * # noqa: F403 from _curses import _CursesWindow as _CursesWindow -from typing import TypeVar, Callable, Any +from typing import Any, Callable, TypeVar -_T = TypeVar('_T') +_T = TypeVar("_T") # available after calling `curses.initscr()` LINES: int diff --git a/mypy/typeshed/stdlib/curses/ascii.pyi b/mypy/typeshed/stdlib/curses/ascii.pyi index 4033769252c8..10bab853adcf 100644 --- a/mypy/typeshed/stdlib/curses/ascii.pyi +++ b/mypy/typeshed/stdlib/curses/ascii.pyi @@ -1,6 +1,6 @@ -from typing import List, Union, overload, TypeVar +from typing import List, TypeVar, Union -_Ch = TypeVar('_Ch', str, int) +_CharT = TypeVar("_CharT", str, int) NUL: int SOH: int @@ -56,7 +56,7 @@ 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: _Ch) -> _Ch: ... -def ctrl(c: _Ch) -> _Ch: ... -def alt(c: _Ch) -> _Ch: ... +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/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index e0885932d09f..678e6bcb85a1 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -1,32 +1,43 @@ -from typing import overload, Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar, Union +import sys +from typing import Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload +if sys.version_info >= (3, 9): + from types import GenericAlias -_T = TypeVar('_T') +_T = TypeVar("_T") class _MISSING_TYPE: ... -MISSING: _MISSING_TYPE +MISSING: _MISSING_TYPE @overload def asdict(obj: Any) -> Dict[str, Any]: ... @overload def asdict(obj: Any, *, dict_factory: Callable[[List[Tuple[str, Any]]], _T]) -> _T: ... - @overload def astuple(obj: Any) -> Tuple[Any, ...]: ... @overload def astuple(obj: Any, *, tuple_factory: Callable[[List[Any]], _T]) -> _T: ... - -@overload -def dataclass(_cls: Type[_T]) -> Type[_T]: ... - -@overload -def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... - -@overload -def dataclass(*, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., - unsafe_hash: bool = ..., frozen: bool = ...) -> Callable[[Type[_T]], Type[_T]]: ... - +if sys.version_info >= (3, 8): + # cls argument is now positional-only + @overload + def dataclass(__cls: Type[_T]) -> Type[_T]: ... + @overload + def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + @overload + def dataclass( + *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... + ) -> Callable[[Type[_T]], Type[_T]]: ... + +else: + @overload + def dataclass(_cls: Type[_T]) -> Type[_T]: ... + @overload + def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + @overload + def dataclass( + *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... + ) -> Callable[[Type[_T]], Type[_T]]: ... class Field(Generic[_T]): name: str @@ -38,37 +49,75 @@ 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, 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: ... - +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: ... - +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 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: ... class FrozenInstanceError(AttributeError): ... -class InitVar(Generic[_T]): ... - -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: ... +class InitVar(Generic[_T]): + type: Type[_T] + def __init__(self, type: Type[_T]) -> None: ... + if sys.version_info >= (3, 9): + @overload + def __class_getitem__(cls, type: Type[_T]) -> InitVar[_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: ... +def replace(__obj: _T, **changes: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index e0ae3fa16aa2..5cfb42b32b31 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,6 +1,6 @@ import sys from time import struct_time -from typing import AnyStr, Optional, SupportsAbs, Tuple, Union, overload, ClassVar, Type, TypeVar +from typing import AnyStr, ClassVar, Optional, SupportsAbs, Tuple, Type, TypeVar, Union, overload _S = TypeVar("_S") @@ -23,7 +23,6 @@ if sys.version_info >= (3, 2): utc: ClassVar[timezone] min: ClassVar[timezone] max: ClassVar[timezone] - def __init__(self, offset: timedelta, name: str = ...) -> None: ... def __hash__(self) -> int: ... @@ -33,9 +32,7 @@ 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 @@ -48,14 +45,12 @@ class date: if sys.version_info >= (3, 8): @classmethod def fromisocalendar(cls: Type[_S], year: int, week: int, day: 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: ... if sys.version_info >= (3,): @@ -91,12 +86,20 @@ class 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: ... + 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 __init__( + self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ... + ) -> None: ... @property def hour(self) -> int: ... @property @@ -110,7 +113,6 @@ class time: if sys.version_info >= (3, 6): @property def fold(self) -> int: ... - def __le__(self, other: time) -> bool: ... def __lt__(self, other: time) -> bool: ... def __ge__(self, other: time) -> bool: ... @@ -132,12 +134,20 @@ class time: 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: ... + 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] = ... + ) -> time: ... _date = date _time = time @@ -148,21 +158,35 @@ class timedelta(SupportsAbs[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: ... + 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 __init__( + self, + days: float = ..., + seconds: float = ..., + microseconds: float = ..., + milliseconds: float = ..., + minutes: float = ..., + hours: float = ..., + weeks: float = ..., + ) -> None: ... @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: ... @@ -226,7 +250,6 @@ class datetime(date): microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... - @property def year(self) -> int: ... @property @@ -246,7 +269,6 @@ class datetime(date): if sys.version_info >= (3, 6): @property def fold(self) -> int: ... - @classmethod def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... @classmethod @@ -290,13 +312,31 @@ class datetime(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: ... + 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] = ..., + ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 338fe7744dd0..2b870b38e3c5 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,7 +1,5 @@ -import sys from types import TracebackType -from typing import Iterator, Optional, Type, Union, MutableMapping - +from typing import Iterator, MutableMapping, Optional, Type, Union from typing_extensions import Literal _KeyType = Union[str, bytes] @@ -16,10 +14,11 @@ class _Database(MutableMapping[_KeyType, 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 __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... class error(Exception): ... def whichdb(filename: str) -> str: ... - -def open(file: str, flag: Literal['r', 'w', 'c', 'n'] = ..., mode: int = ...) -> _Database: ... +def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index c89a96cf5e38..0b8ee50a79b7 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,12 +1,5 @@ - -import sys -from typing import Union, MutableMapping, Iterator, Optional, Type from types import TracebackType - -if sys.version_info >= (3, 8): - from typing import Final -else: - from typing_extensions import Final +from typing import Iterator, MutableMapping, Optional, Type, Union _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -14,7 +7,6 @@ _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 @@ -26,6 +18,8 @@ class _Database(MutableMapping[_KeyType, 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 __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/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 69c4ffa89b04..8f13a2988488 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -1,8 +1,7 @@ - -from typing import Union, Optional, Type, Iterator, overload, List, TypeVar, Generic from types import TracebackType +from typing import List, Optional, Type, TypeVar, Union, overload -_T = TypeVar('_T') +_T = TypeVar("_T") _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -20,15 +19,15 @@ class _gdbm: 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: ... - + 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 diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index db7c555be967..020131543e13 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -1,8 +1,7 @@ - -from typing import Generic, Union, Iterator, Optional, Type, TypeVar, overload, List from types import TracebackType +from typing import List, Optional, Type, TypeVar, Union, overload -_T = TypeVar('_T') +_T = TypeVar("_T") _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -12,7 +11,6 @@ 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: ... @@ -20,15 +18,15 @@ class _dbm: 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: ... - + 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 diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index 799894fc1c43..c3a671d4ba5f 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -1,9 +1,7 @@ import numbers import sys from types import TracebackType -from typing import ( - Any, Container, Dict, List, NamedTuple, Optional, overload, Sequence, Text, Tuple, Type, TypeVar, Union, -) +from typing import Any, Container, Dict, List, NamedTuple, Optional, Sequence, Text, Tuple, Type, TypeVar, Union, overload _Decimal = Union[Decimal, int] _DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] @@ -11,7 +9,7 @@ if sys.version_info >= (3,): _ComparableNum = Union[Decimal, float, numbers.Rational] else: _ComparableNum = Union[Decimal, float] -_DecimalT = TypeVar('_DecimalT', bound=Decimal) +_DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): sign: int @@ -39,27 +37,16 @@ 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): ... if sys.version_info >= (3,): @@ -80,15 +67,12 @@ class Decimal(object): 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: ... if sys.version_info >= (3, 6): 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: ... @@ -139,9 +123,7 @@ class Decimal(object): 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: ... @@ -161,16 +143,15 @@ class Decimal(object): else: 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: ... if sys.version_info >= (3,): - def quantize(self, exp: _Decimal, rounding: Optional[str] = ..., - context: Optional[Context] = ...) -> Decimal: ... + 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 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: ... @@ -251,19 +232,31 @@ class Context(object): 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: ... + 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: ... + 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. diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 110abf7a3bf2..572972ccda9e 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,18 +1,32 @@ -# Based on https://docs.python.org/2.7/library/difflib.html and https://docs.python.org/3.2/library/difflib.html - import sys from typing import ( - Any, TypeVar, Callable, Iterable, Iterator, List, NamedTuple, Sequence, Tuple, - Generic, Optional, Text, Union, AnyStr, overload + Any, + AnyStr, + Callable, + Generic, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Sequence, + Text, + Tuple, + TypeVar, + Union, + overload, ) -_T = TypeVar('_T') +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) + _StrType = TypeVar("_StrType", Text, bytes) _JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] @@ -22,31 +36,36 @@ class Match(NamedTuple): size: int class SequenceMatcher(Generic[_T]): - def __init__(self, isjunk: Optional[Callable[[_T], bool]] = ..., - a: Sequence[_T] = ..., b: Sequence[_T] = ..., - autojunk: bool = ...) -> None: ... + 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: ... if sys.version_info >= (3, 9): - def find_longest_match(self, alo: int = ..., ahi: Optional[int] = ..., blo: int = ..., bhi: Optional[int] = ...) -> Match: ... + def find_longest_match( + self, alo: int = ..., ahi: Optional[int] = ..., blo: int = ..., bhi: Optional[int] = ... + ) -> Match: ... else: 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 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: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # mypy thinks the signatures of the overloads overlap, but the types still work fine @overload -def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], # type: ignore - n: int = ..., cutoff: float = ...) -> List[AnyStr]: ... +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]]: ... +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: ... @@ -54,33 +73,69 @@ class Differ: 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]: ... +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 __init__( + self, + tabsize: int = ..., + wrapcolumn: Optional[int] = ..., + 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: ... + 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_table(self, fromlines: Sequence[_StrType], tolines: Sequence[_StrType], - fromdesc: _StrType = ..., todesc: _StrType = ..., context: bool = ..., - numlines: int = ...) -> _StrType: ... + 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]: ... @@ -94,5 +149,5 @@ if sys.version_info >= (3, 5): fromfiledate: bytes = ..., tofiledate: bytes = ..., n: int = ..., - lineterm: bytes = ... + lineterm: bytes = ..., ) -> Iterator[bytes]: ... diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 682c6851672c..b52d0ed624f6 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -1,12 +1,20 @@ -from typing import Callable, List, Union, Iterator, Tuple, Optional, Any, IO, NamedTuple, Dict - import sys import types - -from opcode import (hasconst as hasconst, hasname as hasname, hasjrel as hasjrel, - hasjabs as hasjabs, haslocal as haslocal, hascompare as hascompare, - hasfree as hasfree, cmp_op as cmp_op, opname as opname, opmap as opmap, - HAVE_ARGUMENT as HAVE_ARGUMENT, EXTENDED_ARG as EXTENDED_ARG) +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 IO, Any, Callable, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union if sys.version_info >= (3, 4): from opcode import stack_effect as stack_effect @@ -19,7 +27,6 @@ if sys.version_info >= (3, 6): _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 @@ -30,24 +37,21 @@ if sys.version_info >= (3, 4): 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 __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]]: ... @@ -57,8 +61,10 @@ if sys.version_info >= (3, 0): 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: ... @@ -67,12 +73,11 @@ if sys.version_info >= (3, 4): 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]: ... + 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: ... diff --git a/mypy/typeshed/stdlib/distutils/archive_util.pyi b/mypy/typeshed/stdlib/distutils/archive_util.pyi index 12172f3f2b01..0e94d3818ae4 100644 --- a/mypy/typeshed/stdlib/distutils/archive_util.pyi +++ b/mypy/typeshed/stdlib/distutils/archive_util.pyi @@ -1,12 +1,12 @@ -# Stubs for distutils.archive_util - from typing import Optional - -def make_archive(base_name: str, format: str, root_dir: Optional[str] = ..., - base_dir: Optional[str] = ..., verbose: int = ..., - dry_run: int = ...) -> str: ... -def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., - verbose: int = ..., dry_run: int = ...) -> str: ... -def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., - dry_run: int = ...) -> str: ... +def make_archive( + base_name: str, + format: str, + root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., + verbose: int = ..., + dry_run: int = ..., +) -> str: ... +def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., verbose: int = ..., dry_run: int = ...) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., dry_run: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/bcppcompiler.pyi b/mypy/typeshed/stdlib/distutils/bcppcompiler.pyi index 9f27a0ae0965..3e432f94b525 100644 --- a/mypy/typeshed/stdlib/distutils/bcppcompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/bcppcompiler.pyi @@ -1,6 +1,3 @@ -# Stubs for distutils.bcppcompiler - from distutils.ccompiler import CCompiler - class BCPPCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index b4243a176dfe..831311d2cb52 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -1,21 +1,15 @@ -# Stubs for distutils.ccompiler - from typing import Any, Callable, List, Optional, Tuple, Union - _Macro = Union[Tuple[str], Tuple[str, Optional[str]]] - -def gen_lib_options(compiler: CCompiler, library_dirs: List[str], - runtime_library_dirs: List[str], - libraries: List[str]) -> List[str]: ... -def gen_preprocess_options(macros: List[_Macro], - include_dirs: List[str]) -> List[str]: ... -def get_default_compiler(osname: Optional[str] = ..., - platform: Optional[str] = ...) -> str: ... -def new_compiler(plat: Optional[str] = ..., compiler: Optional[str] = ..., - verbose: int = ..., dry_run: int = ..., - force: int = ...) -> CCompiler: ... +def gen_lib_options( + compiler: CCompiler, library_dirs: List[str], runtime_library_dirs: List[str], libraries: List[str] +) -> List[str]: ... +def gen_preprocess_options(macros: List[_Macro], include_dirs: List[str]) -> List[str]: ... +def get_default_compiler(osname: Optional[str] = ..., platform: Optional[str] = ...) -> str: ... +def new_compiler( + plat: Optional[str] = ..., compiler: Optional[str] = ..., verbose: int = ..., dry_run: int = ..., force: int = ... +) -> CCompiler: ... def show_compilers() -> None: ... class CCompiler: @@ -29,8 +23,7 @@ class CCompiler: library_dirs: List[str] runtime_library_dirs: List[str] objects: List[str] - def __init__(self, verbose: int = ..., dry_run: int = ..., - force: int = ...) -> None: ... + def __init__(self, verbose: int = ..., dry_run: int = ..., force: int = ...) -> None: ... def add_include_dir(self, dir: str) -> None: ... def set_include_dirs(self, dirs: List[str]) -> None: ... def add_library(self, libname: str) -> None: ... @@ -44,83 +37,111 @@ class CCompiler: def add_link_object(self, object: str) -> None: ... def set_link_objects(self, objects: List[str]) -> None: ... def detect_language(self, sources: Union[str, List[str]]) -> Optional[str]: ... - def find_library_file(self, dirs: List[str], lib: str, - debug: bool = ...) -> Optional[str]: ... - def has_function(self, funcname: str, includes: Optional[List[str]] = ..., - include_dirs: Optional[List[str]] = ..., - libraries: Optional[List[str]] = ..., - library_dirs: Optional[List[str]] = ...) -> bool: ... + def find_library_file(self, dirs: List[str], lib: str, debug: bool = ...) -> Optional[str]: ... + def has_function( + self, + funcname: str, + includes: Optional[List[str]] = ..., + include_dirs: Optional[List[str]] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + ) -> bool: ... def library_dir_option(self, dir: str) -> str: ... def library_option(self, lib: str) -> str: ... def runtime_library_dir_option(self, dir: str) -> str: ... def set_executables(self, **args: str) -> None: ... - def compile(self, sources: List[str], output_dir: Optional[str] = ..., - macros: Optional[_Macro] = ..., - include_dirs: Optional[List[str]] = ..., debug: bool = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ..., - depends: Optional[List[str]] = ...) -> List[str]: ... - def create_static_lib(self, objects: List[str], output_libname: str, - output_dir: Optional[str] = ..., debug: bool = ..., - target_lang: Optional[str] = ...) -> None: ... - def link(self, target_desc: str, objects: List[str], output_filename: str, - output_dir: Optional[str] = ..., - libraries: Optional[List[str]] = ..., - library_dirs: Optional[List[str]] = ..., - runtime_library_dirs: Optional[List[str]] = ..., - export_symbols: Optional[List[str]] = ..., debug: bool = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ..., - build_temp: Optional[str] = ..., - target_lang: Optional[str] = ...) -> None: ... - def link_executable(self, objects: List[str], output_progname: str, - output_dir: Optional[str] = ..., - libraries: Optional[List[str]] = ..., - library_dirs: Optional[List[str]] = ..., - runtime_library_dirs: Optional[List[str]] = ..., - debug: bool = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ..., - target_lang: Optional[str] = ...) -> None: ... - def link_shared_lib(self, objects: List[str], output_libname: str, - output_dir: Optional[str] = ..., - libraries: Optional[List[str]] = ..., - library_dirs: Optional[List[str]] = ..., - runtime_library_dirs: Optional[List[str]] = ..., - export_symbols: Optional[List[str]] = ..., - debug: bool = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ..., - build_temp: Optional[str] = ..., - target_lang: Optional[str] = ...) -> None: ... - def link_shared_object(self, objects: List[str], output_filename: str, - output_dir: Optional[str] = ..., - libraries: Optional[List[str]] = ..., - library_dirs: Optional[List[str]] = ..., - runtime_library_dirs: Optional[List[str]] = ..., - export_symbols: Optional[List[str]] = ..., - debug: bool = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ..., - build_temp: Optional[str] = ..., - target_lang: Optional[str] = ...) -> None: ... - def preprocess(self, source: str, output_file: Optional[str] = ..., - macros: Optional[List[_Macro]] = ..., - include_dirs: Optional[List[str]] = ..., - extra_preargs: Optional[List[str]] = ..., - extra_postargs: Optional[List[str]] = ...) -> None: ... - def executable_filename(self, basename: str, strip_dir: int = ..., - output_dir: str = ...) -> str: ... - def library_filename(self, libname: str, lib_type: str = ..., - strip_dir: int = ..., - output_dir: str = ...) -> str: ... - def object_filenames(self, source_filenames: List[str], - strip_dir: int = ..., - output_dir: str = ...) -> List[str]: ... - def shared_object_filename(self, basename: str, strip_dir: int = ..., - output_dir: str = ...) -> str: ... - def execute(self, func: Callable[..., None], args: Tuple[Any, ...], - msg: Optional[str] = ..., level: int = ...) -> None: ... + def compile( + self, + sources: List[str], + output_dir: Optional[str] = ..., + macros: Optional[_Macro] = ..., + include_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + depends: Optional[List[str]] = ..., + ) -> List[str]: ... + def create_static_lib( + self, + objects: List[str], + output_libname: str, + output_dir: Optional[str] = ..., + debug: bool = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link( + self, + target_desc: str, + objects: List[str], + output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_executable( + self, + objects: List[str], + output_progname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_shared_lib( + self, + objects: List[str], + output_libname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_shared_object( + self, + objects: List[str], + output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def preprocess( + self, + source: str, + output_file: Optional[str] = ..., + macros: Optional[List[_Macro]] = ..., + include_dirs: Optional[List[str]] = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + ) -> None: ... + def executable_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... + def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... + def object_filenames(self, source_filenames: List[str], strip_dir: int = ..., output_dir: str = ...) -> List[str]: ... + def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... + def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: Optional[str] = ..., level: int = ...) -> None: ... def spawn(self, cmd: List[str]) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... def move_file(self, src: str, dst: str) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/cmd.pyi b/mypy/typeshed/stdlib/distutils/cmd.pyi index 3b0d02f49967..93bfc7c9dbb5 100644 --- a/mypy/typeshed/stdlib/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/distutils/cmd.pyi @@ -1,8 +1,6 @@ -# Stubs for distutils.cmd - -from typing import Callable, List, Tuple, Union, Optional, Iterable, Any, Text from abc import abstractmethod from distutils.dist import Distribution +from typing import Any, Callable, Iterable, List, Optional, Tuple, Union class Command: sub_commands: List[Tuple[str, Optional[Callable[[Command], bool]]]] @@ -13,28 +11,57 @@ class Command: def finalize_options(self) -> None: ... @abstractmethod def run(self) -> None: ... - - def announce(self, msg: Text, level: int = ...) -> None: ... - def debug_print(self, msg: Text) -> None: ... - + def announce(self, msg: str, level: int = ...) -> None: ... + def debug_print(self, msg: str) -> None: ... def ensure_string(self, option: str, default: Optional[str] = ...) -> None: ... def ensure_string_list(self, option: Union[str, List[str]]) -> None: ... def ensure_filename(self, option: str) -> None: ... def ensure_dirname(self, option: str) -> None: ... - def get_command_name(self) -> str: ... - def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... - def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... - def reinitialize_command(self, command: Union[Command, Text], reinit_subcommands: int = ...) -> Command: ... - def run_command(self, command: Text) -> None: ... + def set_undefined_options(self, src_cmd: str, *option_pairs: Tuple[str, str]) -> None: ... + def get_finalized_command(self, command: str, create: int = ...) -> Command: ... + def reinitialize_command(self, command: Union[Command, str], reinit_subcommands: int = ...) -> Command: ... + def run_command(self, command: str) -> None: ... def get_sub_commands(self) -> List[str]: ... - - def warn(self, msg: Text) -> None: ... - def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[Text] = ..., level: int = ...) -> None: ... + def warn(self, msg: str) -> None: ... + def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[str] = ..., level: int = ...) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... - def copy_file(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., link: Optional[str] = ..., level: Any = ...) -> Tuple[str, bool]: ... # level is not used - def copy_tree(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., preserve_symlinks: int = ..., level: Any = ...) -> List[str]: ... # level is not used + def copy_file( + self, + infile: str, + outfile: str, + preserve_mode: int = ..., + preserve_times: int = ..., + link: Optional[str] = ..., + level: Any = ..., + ) -> Tuple[str, bool]: ... # level is not used + def copy_tree( + self, + infile: str, + outfile: str, + preserve_mode: int = ..., + preserve_times: int = ..., + preserve_symlinks: int = ..., + level: Any = ..., + ) -> List[str]: ... # level is not used def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used - def make_archive(self, base_name: str, format: str, root_dir: Optional[str] = ..., base_dir: Optional[str] = ..., owner: Optional[str] = ..., group: Optional[str] = ...) -> str: ... - def make_file(self, infiles: Union[str, List[str], Tuple[str]], outfile: str, func: Callable[..., Any], args: List[Any], exec_msg: Optional[str] = ..., skip_msg: Optional[str] = ..., level: Any = ...) -> None: ... # level is not used + def make_archive( + self, + base_name: str, + format: str, + root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., + owner: Optional[str] = ..., + group: Optional[str] = ..., + ) -> str: ... + def make_file( + self, + infiles: Union[str, List[str], Tuple[str]], + outfile: str, + func: Callable[..., Any], + args: List[Any], + exec_msg: Optional[str] = ..., + skip_msg: Optional[str] = ..., + level: Any = ..., + ) -> None: ... # level is not used diff --git a/mypy/typeshed/stdlib/distutils/command/build_py.pyi b/mypy/typeshed/stdlib/distutils/command/build_py.pyi index 34753e4a75b6..4e8c9af4a546 100644 --- a/mypy/typeshed/stdlib/distutils/command/build_py.pyi +++ b/mypy/typeshed/stdlib/distutils/command/build_py.pyi @@ -1,10 +1,8 @@ from distutils.cmd import Command -import sys -if sys.version_info >= (3,): - class build_py(Command): - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... +class build_py(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... - class build_py_2to3(build_py): ... +class build_py_2to3(build_py): ... diff --git a/mypy/typeshed/stdlib/distutils/command/config.pyi b/mypy/typeshed/stdlib/distutils/command/config.pyi index 94e97355ea7c..6b57a64b48b1 100644 --- a/mypy/typeshed/stdlib/distutils/command/config.pyi +++ b/mypy/typeshed/stdlib/distutils/command/config.pyi @@ -3,7 +3,7 @@ from distutils.ccompiler import CCompiler from distutils.core import Command as Command from distutils.errors import DistutilsExecError as DistutilsExecError from distutils.sysconfig import customize_compiler as customize_compiler -from typing import Any, Dict, List, Match, Optional, Pattern, Sequence, Tuple, Union +from typing import Dict, List, Optional, Pattern, Sequence, Tuple, Union LANG_EXT: Dict[str, str] diff --git a/mypy/typeshed/stdlib/distutils/command/install.pyi b/mypy/typeshed/stdlib/distutils/command/install.pyi index 94a900824686..12e83d976a2d 100644 --- a/mypy/typeshed/stdlib/distutils/command/install.pyi +++ b/mypy/typeshed/stdlib/distutils/command/install.pyi @@ -1,14 +1,14 @@ from distutils.cmd import Command -from typing import Optional, Text +from typing import Optional, Tuple +SCHEME_KEYS: Tuple[str, ...] class install(Command): user: bool - prefix: Optional[Text] - home: Optional[Text] - root: Optional[Text] - install_lib: Optional[Text] - + prefix: Optional[str] + home: Optional[str] + root: Optional[str] + install_lib: Optional[str] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi b/mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi new file mode 100644 index 000000000000..80ffb19bda74 --- /dev/null +++ b/mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi @@ -0,0 +1,10 @@ +from distutils.cmd import Command +from typing import ClassVar, List, Optional, Tuple + +class install_egg_info(Command): + description: ClassVar[str] + user_options: ClassVar[List[Tuple[str, Optional[str], str]]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_outputs(self) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/distutils/command/upload.pyi b/mypy/typeshed/stdlib/distutils/command/upload.pyi new file mode 100644 index 000000000000..ef4bbc332230 --- /dev/null +++ b/mypy/typeshed/stdlib/distutils/command/upload.pyi @@ -0,0 +1,8 @@ +from distutils.config import PyPIRCCommand +from typing import ClassVar, List + +class upload(PyPIRCCommand): + description: ClassVar[str] + boolean_options: ClassVar[List[str]] + def run(self) -> None: ... + def upload_file(self, command: str, pyversion: str, filename: str) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/config.pyi b/mypy/typeshed/stdlib/distutils/config.pyi new file mode 100644 index 000000000000..e60507e0b65a --- /dev/null +++ b/mypy/typeshed/stdlib/distutils/config.pyi @@ -0,0 +1,17 @@ +from abc import abstractmethod +from distutils.cmd import Command +from typing import ClassVar, List, Optional, Tuple + +DEFAULT_PYPIRC: str + +class PyPIRCCommand(Command): + DEFAULT_REPOSITORY: ClassVar[str] + DEFAULT_REALM: ClassVar[str] + repository: None + realm: None + user_options: ClassVar[List[Tuple[str, Optional[str], str]]] + boolean_options: ClassVar[List[str]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi index 354eedde68e2..9a3fa70fd381 100644 --- a/mypy/typeshed/stdlib/distutils/core.pyi +++ b/mypy/typeshed/stdlib/distutils/core.pyi @@ -1,9 +1,7 @@ -# Stubs for distutils.core - -from typing import Any, List, Mapping, Optional, Tuple, Type, Union from distutils.cmd import Command as Command from distutils.dist import Distribution as Distribution from distutils.extension import Extension as Extension +from typing import Any, List, Mapping, Optional, Tuple, Type, Union def setup( *, diff --git a/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi b/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi index 1bfab90ead47..1f85b254860b 100644 --- a/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi @@ -1,7 +1,4 @@ -# Stubs for distutils.cygwinccompiler - from distutils.unixccompiler import UnixCCompiler - class CygwinCCompiler(UnixCCompiler): ... class Mingw32CCompiler(CygwinCCompiler): ... diff --git a/mypy/typeshed/stdlib/distutils/debug.pyi b/mypy/typeshed/stdlib/distutils/debug.pyi index 76de44772127..098dc3dee246 100644 --- a/mypy/typeshed/stdlib/distutils/debug.pyi +++ b/mypy/typeshed/stdlib/distutils/debug.pyi @@ -1,3 +1 @@ -# Stubs for distutils.debug - DEBUG: bool diff --git a/mypy/typeshed/stdlib/distutils/dep_util.pyi b/mypy/typeshed/stdlib/distutils/dep_util.pyi index 7df58478132d..6f779d540e5e 100644 --- a/mypy/typeshed/stdlib/distutils/dep_util.pyi +++ b/mypy/typeshed/stdlib/distutils/dep_util.pyi @@ -1,8 +1,5 @@ -# Stubs for distutils.dep_util - from typing import List, Tuple def newer(source: str, target: str) -> bool: ... -def newer_pairwise(sources: List[str], - targets: List[str]) -> List[Tuple[str, str]]: ... +def newer_pairwise(sources: List[str], targets: List[str]) -> List[Tuple[str, str]]: ... def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/distutils/dir_util.pyi b/mypy/typeshed/stdlib/distutils/dir_util.pyi index 667ac2fe710a..4c4a22102558 100644 --- a/mypy/typeshed/stdlib/distutils/dir_util.pyi +++ b/mypy/typeshed/stdlib/distutils/dir_util.pyi @@ -1,15 +1,15 @@ -# Stubs for distutils.dir_util - from typing import List - -def mkpath(name: str, mode: int = ..., verbose: int = ..., - dry_run: int = ...) -> List[str]: ... -def create_tree(base_dir: str, files: List[str], mode: int = ..., - verbose: int = ..., dry_run: int = ...) -> None: ... -def copy_tree(src: str, dst: str, preserve_mode: int = ..., - preserve_times: int = ..., preserve_symlinks: int = ..., - update: int = ..., verbose: int = ..., - dry_run: int = ...) -> List[str]: ... -def remove_tree(directory: str, verbose: int = ..., - dry_run: int = ...) -> None: ... +def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> List[str]: ... +def create_tree(base_dir: str, files: List[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... +def copy_tree( + src: str, + dst: str, + preserve_mode: int = ..., + preserve_times: int = ..., + preserve_symlinks: int = ..., + update: int = ..., + verbose: int = ..., + dry_run: int = ..., +) -> List[str]: ... +def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index 92ef8ae49054..d3acdafbd5b1 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -1,12 +1,58 @@ -# Stubs for distutils.dist +from _typeshed import AnyPath, SupportsWrite from distutils.cmd import Command +from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union -from typing import Any, Dict, Iterable, Mapping, Optional, Text, Tuple, Type - +class DistributionMetadata: + def __init__(self, path: Optional[Union[int, AnyPath]] = ...) -> None: ... + name: Optional[str] + version: Optional[str] + author: Optional[str] + author_email: Optional[str] + maintainer: Optional[str] + maintainer_email: Optional[str] + url: Optional[str] + license: Optional[str] + description: Optional[str] + long_description: Optional[str] + keywords: Optional[Union[str, List[str]]] + platforms: Optional[Union[str, List[str]]] + classifiers: Optional[Union[str, List[str]]] + download_url: Optional[str] + provides: Optional[List[str]] + requires: Optional[List[str]] + obsoletes: Optional[List[str]] + def read_pkg_file(self, file: IO[str]) -> None: ... + def write_pkg_info(self, base_dir: str) -> None: ... + def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> Union[str, List[str]]: ... + def get_platforms(self) -> Union[str, List[str]]: ... + def get_classifiers(self) -> Union[str, List[str]]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> List[str]: ... + def set_requires(self, value: Iterable[str]) -> None: ... + def get_provides(self) -> List[str]: ... + def set_provides(self, value: Iterable[str]) -> None: ... + def get_obsoletes(self) -> List[str]: ... + def set_obsoletes(self, value: Iterable[str]) -> None: ... class Distribution: cmdclass: Dict[str, Type[Command]] + metadata: DistributionMetadata def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ... - def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... - def parse_config_files(self, filenames: Optional[Iterable[Text]] = ...) -> None: ... + def get_option_dict(self, command: str) -> Dict[str, Tuple[str, str]]: ... + def parse_config_files(self, filenames: Optional[Iterable[str]] = ...) -> None: ... def get_command_obj(self, command: str, create: bool = ...) -> Optional[Command]: ... diff --git a/mypy/typeshed/stdlib/distutils/extension.pyi b/mypy/typeshed/stdlib/distutils/extension.pyi index 537e983967c2..c85128ab1a16 100644 --- a/mypy/typeshed/stdlib/distutils/extension.pyi +++ b/mypy/typeshed/stdlib/distutils/extension.pyi @@ -1,41 +1,22 @@ -# Stubs for distutils.extension - from typing import List, Optional, Tuple -import sys class Extension: - if sys.version_info >= (3,): - def __init__(self, - name: str, - sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, Optional[str]]] = ..., - undef_macros: List[str] = ..., - library_dirs: List[str] = ..., - libraries: List[str] = ..., - runtime_library_dirs: List[str] = ..., - extra_objects: List[str] = ..., - extra_compile_args: List[str] = ..., - extra_link_args: List[str] = ..., - export_symbols: List[str] = ..., - swig_opts: Optional[str] = ..., # undocumented - depends: List[str] = ..., - language: str = ..., - optional: bool = ...) -> None: ... - else: - def __init__(self, - name: str, - sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, Optional[str]]] = ..., - undef_macros: List[str] = ..., - library_dirs: List[str] = ..., - libraries: List[str] = ..., - runtime_library_dirs: List[str] = ..., - extra_objects: List[str] = ..., - extra_compile_args: List[str] = ..., - extra_link_args: List[str] = ..., - export_symbols: List[str] = ..., - swig_opts: Optional[str] = ..., # undocumented - depends: List[str] = ..., - language: str = ...) -> None: ... + def __init__( + self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + swig_opts: Optional[str] = ..., # undocumented + depends: List[str] = ..., + language: str = ..., + optional: bool = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index 4d38a75551ea..8eb4c416fa28 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,17 +1,11 @@ -# Stubs for distutils.fancy_getopt - -from typing import ( - Any, List, Mapping, Optional, Tuple, Union, - TypeVar, overload, -) +from typing import Any, List, Mapping, Optional, Tuple, Union, overload _Option = Tuple[str, Optional[str], str] _GR = Tuple[List[str], OptionDummy] -def fancy_getopt(options: List[_Option], - negative_opt: Mapping[_Option, _Option], - object: Any, - args: Optional[List[str]]) -> Union[List[str], _GR]: ... +def fancy_getopt( + options: List[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: Optional[List[str]] +) -> Union[List[str], _GR]: ... def wrap_text(text: str, width: int) -> List[str]: ... class FancyGetopt: diff --git a/mypy/typeshed/stdlib/distutils/file_util.pyi b/mypy/typeshed/stdlib/distutils/file_util.pyi index 6324d63d4b5d..018339733df0 100644 --- a/mypy/typeshed/stdlib/distutils/file_util.pyi +++ b/mypy/typeshed/stdlib/distutils/file_util.pyi @@ -1,12 +1,14 @@ -# Stubs for distutils.file_util - from typing import Optional, Sequence, Tuple - -def copy_file(src: str, dst: str, preserve_mode: bool = ..., - preserve_times: bool = ..., update: bool = ..., - link: Optional[str] = ..., verbose: bool = ..., - dry_run: bool = ...) -> Tuple[str, str]: ... -def move_file(src: str, dst: str, verbose: bool = ..., - dry_run: bool = ...) -> str: ... +def copy_file( + src: str, + dst: str, + preserve_mode: bool = ..., + preserve_times: bool = ..., + update: bool = ..., + link: Optional[str] = ..., + verbose: bool = ..., + dry_run: bool = ..., +) -> Tuple[str, str]: ... +def move_file(src: str, dst: str, verbose: bool = ..., dry_run: bool = ...) -> str: ... def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index 4ecaebaf714f..8fa55d09d265 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -1,3 +1 @@ -# Stubs for distutils.filelist - class FileList: ... diff --git a/mypy/typeshed/stdlib/distutils/log.pyi b/mypy/typeshed/stdlib/distutils/log.pyi index 6c37cc503b30..549b569e7356 100644 --- a/mypy/typeshed/stdlib/distutils/log.pyi +++ b/mypy/typeshed/stdlib/distutils/log.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Iterable, Text +from typing import Any DEBUG: int INFO: int @@ -8,21 +8,18 @@ FATAL: int class Log: def __init__(self, threshold: int = ...) -> None: ... - def log(self, level: int, msg: Text, *args: Any) -> None: ... - def debug(self, msg: Text, *args: Any) -> None: ... - def info(self, msg: Text, *args: Any) -> None: ... - def warn(self, msg: Text, *args: Any) -> None: ... - def error(self, msg: Text, *args: Any) -> None: ... - def fatal(self, msg: Text, *args: Any) -> None: ... - -_LogFunc = Callable[[Text, Iterable[Any]], None] - -log: Callable[[int, Text, Iterable[Any]], None] -debug: _LogFunc -info: _LogFunc -warn: _LogFunc -error: _LogFunc -fatal: _LogFunc + def log(self, level: int, msg: str, *args: Any) -> None: ... + def debug(self, msg: str, *args: Any) -> None: ... + def info(self, msg: str, *args: Any) -> None: ... + def warn(self, msg: str, *args: Any) -> None: ... + def error(self, msg: str, *args: Any) -> None: ... + def fatal(self, msg: str, *args: Any) -> None: ... +def log(level: int, msg: str, *args: Any) -> None: ... +def debug(msg: str, *args: Any) -> None: ... +def info(msg: str, *args: Any) -> None: ... +def warn(msg: str, *args: Any) -> None: ... +def error(msg: str, *args: Any) -> None: ... +def fatal(msg: str, *args: Any) -> None: ... def set_threshold(level: int) -> int: ... def set_verbosity(v: int) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/msvccompiler.pyi b/mypy/typeshed/stdlib/distutils/msvccompiler.pyi index ffc9e4490ce3..80872a6b739f 100644 --- a/mypy/typeshed/stdlib/distutils/msvccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/msvccompiler.pyi @@ -1,6 +1,3 @@ -# Stubs for distutils.msvccompiler - from distutils.ccompiler import CCompiler - class MSVCCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/distutils/spawn.pyi b/mypy/typeshed/stdlib/distutils/spawn.pyi index 8df9ebab7f23..e12eae99bf29 100644 --- a/mypy/typeshed/stdlib/distutils/spawn.pyi +++ b/mypy/typeshed/stdlib/distutils/spawn.pyi @@ -1,8 +1,4 @@ -# Stubs for distutils.spawn - from typing import List, Optional -def spawn(cmd: List[str], search_path: bool = ..., - verbose: bool = ..., dry_run: bool = ...) -> None: ... -def find_executable(executable: str, - path: Optional[str] = ...) -> Optional[str]: ... +def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... +def find_executable(executable: str, path: Optional[str] = ...) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi index 62fa9af81757..9061db75ccf1 100644 --- a/mypy/typeshed/stdlib/distutils/sysconfig.pyi +++ b/mypy/typeshed/stdlib/distutils/sysconfig.pyi @@ -1,7 +1,5 @@ -# Stubs for distutils.sysconfig - -from typing import Mapping, Optional, Union from distutils.ccompiler import CCompiler +from typing import Mapping, Optional, Union PREFIX: str EXEC_PREFIX: str @@ -10,10 +8,7 @@ def get_config_var(name: str) -> Union[int, str, None]: ... def get_config_vars(*args: str) -> Mapping[str, Union[int, str]]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... -def get_python_inc(plat_specific: bool = ..., - prefix: Optional[str] = ...) -> str: ... -def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., - prefix: Optional[str] = ...) -> str: ... - +def get_python_inc(plat_specific: bool = ..., prefix: Optional[str] = ...) -> str: ... +def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., prefix: Optional[str] = ...) -> str: ... def customize_compiler(compiler: CCompiler) -> None: ... def set_python_build() -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/text_file.pyi b/mypy/typeshed/stdlib/distutils/text_file.pyi index 8f90d41d10f6..9872a1f25751 100644 --- a/mypy/typeshed/stdlib/distutils/text_file.pyi +++ b/mypy/typeshed/stdlib/distutils/text_file.pyi @@ -1,18 +1,21 @@ -# Stubs for distutils.text_file - from typing import IO, List, Optional, Tuple, Union class TextFile: - def __init__(self, filename: Optional[str] = ..., - file: Optional[IO[str]] = ..., - *, strip_comments: bool = ..., - lstrip_ws: bool = ..., rstrip_ws: bool = ..., - skip_blanks: bool = ..., join_lines: bool = ..., - collapse_join: bool = ...) -> None: ... + def __init__( + self, + filename: Optional[str] = ..., + file: Optional[IO[str]] = ..., + *, + strip_comments: bool = ..., + lstrip_ws: bool = ..., + rstrip_ws: bool = ..., + skip_blanks: bool = ..., + join_lines: bool = ..., + collapse_join: bool = ..., + ) -> None: ... def open(self, filename: str) -> None: ... def close(self) -> None: ... - def warn(self, msg: str, - line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... + def warn(self, msg: str, line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... def readline(self) -> Optional[str]: ... def readlines(self) -> List[str]: ... def unreadline(self, line: str) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/unixccompiler.pyi b/mypy/typeshed/stdlib/distutils/unixccompiler.pyi index 7ab7298bf4c6..e1d443471af3 100644 --- a/mypy/typeshed/stdlib/distutils/unixccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/unixccompiler.pyi @@ -1,6 +1,3 @@ -# Stubs for distutils.unixccompiler - from distutils.ccompiler import CCompiler - class UnixCCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi index 942886d77f55..0086d726af65 100644 --- a/mypy/typeshed/stdlib/distutils/util.pyi +++ b/mypy/typeshed/stdlib/distutils/util.pyi @@ -1,20 +1,23 @@ -# Stubs for distutils.util - from typing import Any, Callable, List, Mapping, Optional, Tuple - def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... def change_root(new_root: str, pathname: str) -> str: ... def check_environ() -> None: ... def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... def split_quoted(s: str) -> List[str]: ... -def execute(func: Callable[..., None], args: Tuple[Any, ...], - msg: Optional[str] = ..., verbose: bool = ..., - dry_run: bool = ...) -> None: ... +def execute( + func: Callable[..., None], args: Tuple[Any, ...], msg: Optional[str] = ..., verbose: bool = ..., dry_run: bool = ... +) -> None: ... def strtobool(val: str) -> bool: ... -def byte_compile(py_files: List[str], optimize: int = ..., force: bool = ..., - prefix: Optional[str] = ..., base_dir: Optional[str] = ..., - verbose: bool = ..., dry_run: bool = ..., - direct: Optional[bool] = ...) -> None: ... +def byte_compile( + py_files: List[str], + optimize: int = ..., + force: bool = ..., + prefix: Optional[str] = ..., + base_dir: Optional[str] = ..., + verbose: bool = ..., + dry_run: bool = ..., + direct: Optional[bool] = ..., +) -> None: ... def rfc822_escape(header: str) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/version.pyi b/mypy/typeshed/stdlib/distutils/version.pyi index 36ee4b84b96a..311b0bead960 100644 --- a/mypy/typeshed/stdlib/distutils/version.pyi +++ b/mypy/typeshed/stdlib/distutils/version.pyi @@ -1,54 +1,38 @@ -import sys from abc import abstractmethod -from typing import Any, Optional, TypeVar, Union, Pattern, Text, Tuple +from typing import Optional, Pattern, Tuple, TypeVar, Union -_T = TypeVar('_T', bound=Version) +_T = TypeVar("_T", bound=Version) class Version: def __repr__(self) -> str: ... - - if sys.version_info >= (3,): - def __eq__(self, other: object) -> bool: ... - def __lt__(self: _T, other: Union[_T, str]) -> bool: ... - def __le__(self: _T, other: Union[_T, str]) -> bool: ... - def __gt__(self: _T, other: Union[_T, str]) -> bool: ... - def __ge__(self: _T, other: Union[_T, str]) -> bool: ... - + def __eq__(self, other: object) -> bool: ... + def __lt__(self: _T, other: Union[_T, str]) -> bool: ... + def __le__(self: _T, other: Union[_T, str]) -> bool: ... + def __gt__(self: _T, other: Union[_T, str]) -> bool: ... + def __ge__(self: _T, other: Union[_T, str]) -> bool: ... @abstractmethod - def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def __init__(self, vstring: Optional[str] = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: Text) -> _T: ... + def parse(self: _T, vstring: str) -> _T: ... @abstractmethod def __str__(self) -> str: ... - if sys.version_info >= (3,): - @abstractmethod - def _cmp(self: _T, other: Union[_T, str]) -> bool: ... - else: - @abstractmethod - def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + @abstractmethod + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... class StrictVersion(Version): version_re: Pattern[str] version: Tuple[int, int, int] - prerelease: Optional[Tuple[Text, int]] - - def __init__(self, vstring: Optional[Text] = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... + prerelease: Optional[Tuple[str, int]] + def __init__(self, vstring: Optional[str] = ...) -> None: ... + def parse(self: _T, vstring: str) -> _T: ... def __str__(self) -> str: ... - if sys.version_info >= (3,): - def _cmp(self: _T, other: Union[_T, str]) -> bool: ... - else: - def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] - vstring: Text - version: Tuple[Union[Text, int], ...] - - def __init__(self, vstring: Optional[Text] = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... + vstring: str + version: Tuple[Union[str, int], ...] + def __init__(self, vstring: Optional[str] = ...) -> None: ... + def parse(self: _T, vstring: str) -> _T: ... def __str__(self) -> str: ... - if sys.version_info >= (3,): - def _cmp(self: _T, other: Union[_T, str]) -> bool: ... - else: - def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 7349cdc74e55..ae84c2c25efc 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -1,15 +1,16 @@ -from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union - import sys 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 @@ -38,8 +39,15 @@ class Example: 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 __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: @@ -49,20 +57,37 @@ class DocTest: 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 __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_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]: ... + 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] @@ -74,13 +99,14 @@ class DocTestRunner: 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 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: ... @@ -92,35 +118,62 @@ 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 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 __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: ... @@ -138,20 +191,31 @@ class SkipDocTestCase(DocTestCase): if sys.version_info >= (3, 4): class _DocTestSuite(unittest.TestSuite): ... + else: _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: ... +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 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: ... diff --git a/mypy/typeshed/stdlib/dummy_threading.pyi b/mypy/typeshed/stdlib/dummy_threading.pyi index d7d12bb70667..757cb8d4bd4c 100644 --- a/mypy/typeshed/stdlib/dummy_threading.pyi +++ b/mypy/typeshed/stdlib/dummy_threading.pyi @@ -1,3 +1,2 @@ - from _dummy_threading import * from _dummy_threading import __all__ as __all__ diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index a69f188d4f7b..e2c22554a092 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -1,8 +1,6 @@ -# Stubs for email (Python 3.4) - -from typing import Callable, IO from email.message import Message from email.policy import Policy +from typing import IO, Callable def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index 3a6c19d1b91b..7c8e8ae711b9 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -1,6 +1,4 @@ -# Stubs for email.charset (Python 3.4) - -from typing import List, Optional, Iterator, Any +from typing import Any, Iterator, List, Optional QP: int # undocumented BASE64: int # undocumented @@ -17,15 +15,14 @@ class Charset: def get_body_encoding(self) -> str: ... def get_output_charset(self) -> Optional[str]: ... def header_encode(self, string: str) -> str: ... - def header_encode_lines(self, string: str, - maxlengths: Iterator[int]) -> List[str]: ... + def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> List[str]: ... def body_encode(self, string: str) -> str: ... def __str__(self) -> str: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... -def add_charset(charset: str, header_enc: Optional[int] = ..., - body_enc: Optional[int] = ..., - output_charset: Optional[str] = ...) -> None: ... +def add_charset( + charset: str, header_enc: Optional[int] = ..., body_enc: Optional[int] = ..., output_charset: Optional[str] = ... +) -> None: ... def add_alias(alias: str, canonical: str) -> None: ... def add_codec(charset: str, codecname: str) -> None: ... diff --git a/mypy/typeshed/stdlib/email/contentmanager.pyi b/mypy/typeshed/stdlib/email/contentmanager.pyi index ed55ef67dccd..68fe99c8c09f 100644 --- a/mypy/typeshed/stdlib/email/contentmanager.pyi +++ b/mypy/typeshed/stdlib/email/contentmanager.pyi @@ -1,15 +1,11 @@ -# Stubs for email.contentmanager (Python 3.4) - -from typing import Any, Callable from email.message import Message +from typing import Any, Callable class ContentManager: def __init__(self) -> None: ... def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ... - def set_content(self, msg: Message, obj: Any, *args: Any, - **kw: Any) -> Any: ... + def set_content(self, msg: Message, obj: Any, *args: Any, **kw: Any) -> Any: ... def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ... - def add_set_handler(self, typekey: type, - handler: Callable[..., Any]) -> None: ... + def add_set_handler(self, typekey: type, handler: Callable[..., Any]) -> None: ... raw_data_manager: ContentManager diff --git a/mypy/typeshed/stdlib/email/encoders.pyi b/mypy/typeshed/stdlib/email/encoders.pyi index bb5c84cb136a..e05225e895c4 100644 --- a/mypy/typeshed/stdlib/email/encoders.pyi +++ b/mypy/typeshed/stdlib/email/encoders.pyi @@ -1,5 +1,3 @@ -# Stubs for email.encoders (Python 3.4) - from email.message import Message def encode_base64(msg: Message) -> None: ... diff --git a/mypy/typeshed/stdlib/email/errors.pyi b/mypy/typeshed/stdlib/email/errors.pyi index 73e0b800f343..dd2b70b10fca 100644 --- a/mypy/typeshed/stdlib/email/errors.pyi +++ b/mypy/typeshed/stdlib/email/errors.pyi @@ -1,11 +1,8 @@ -# Stubs for email.errors (Python 3.4) - class MessageError(Exception): ... class MessageParseError(MessageError): ... class HeaderParseError(MessageParseError): ... class BoundaryError(MessageParseError): ... class MultipartConversionError(MessageError, TypeError): ... - class MessageDefect(ValueError): ... class NoBoundaryInMultipartDefect(MessageDefect): ... class StartBoundaryNotFoundDefect(MessageDefect): ... diff --git a/mypy/typeshed/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi index 8350d135dc86..ffcf4f0a7c6e 100644 --- a/mypy/typeshed/stdlib/email/feedparser.pyi +++ b/mypy/typeshed/stdlib/email/feedparser.pyi @@ -1,17 +1,21 @@ -# Stubs for email.feedparser (Python 3.4) - -from typing import Callable from email.message import Message from email.policy import Policy +from typing import Callable, Generic, TypeVar, overload + +_M = TypeVar("_M", bound=Message) -class FeedParser: - def __init__(self, _factory: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... +class FeedParser(Generic[_M]): + @overload + def __init__(self: FeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... + @overload + def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... def feed(self, data: str) -> None: ... - def close(self) -> Message: ... + def close(self) -> _M: ... -class BytesFeedParser: - def __init__(self, _factory: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... +class BytesFeedParser(Generic[_M]): + @overload + def __init__(self: BytesFeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... + @overload + def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... def feed(self, data: bytes) -> None: ... - def close(self) -> Message: ... + def close(self) -> _M: ... diff --git a/mypy/typeshed/stdlib/email/generator.pyi b/mypy/typeshed/stdlib/email/generator.pyi index 2cf3942d390b..ff0c2d902147 100644 --- a/mypy/typeshed/stdlib/email/generator.pyi +++ b/mypy/typeshed/stdlib/email/generator.pyi @@ -1,27 +1,18 @@ -# Stubs for email.generator (Python 3.4) - -from typing import BinaryIO, TextIO, Optional from email.message import Message from email.policy import Policy +from typing import BinaryIO, Optional, TextIO class Generator: def clone(self, fp: TextIO) -> Generator: ... def write(self, s: str) -> None: ... - def __init__(self, outfp: TextIO, mangle_from_: bool = ..., - maxheaderlen: int = ..., *, - policy: Policy = ...) -> None: ... - def flatten(self, msg: Message, unixfrom: bool = ..., - linesep: Optional[str] = ...) -> None: ... + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., linesep: Optional[str] = ...) -> None: ... class BytesGenerator: def clone(self, fp: BinaryIO) -> BytesGenerator: ... def write(self, s: str) -> None: ... - def __init__(self, outfp: BinaryIO, mangle_from_: bool = ..., - maxheaderlen: int = ..., *, - policy: Policy = ...) -> None: ... - def flatten(self, msg: Message, unixfrom: bool = ..., - linesep: Optional[str] = ...) -> None: ... + def __init__(self, outfp: BinaryIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., linesep: Optional[str] = ...) -> None: ... class DecodedGenerator(Generator): - def __init__(self, outfp: TextIO, mangle_from_: bool = ..., - maxheaderlen: int = ..., *, fmt: Optional[str] = ...) -> None: ... + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, fmt: Optional[str] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/header.pyi b/mypy/typeshed/stdlib/email/header.pyi index 21b999530154..1a5e1a2e4853 100644 --- a/mypy/typeshed/stdlib/email/header.pyi +++ b/mypy/typeshed/stdlib/email/header.pyi @@ -1,25 +1,26 @@ -# Stubs for email.header (Python 3.4) - -from typing import Union, Optional, Any, List, Tuple from email.charset import Charset +from typing import Any, List, Optional, Tuple, Union class Header: - def __init__(self, s: Union[bytes, str, None] = ..., - charset: Union[Charset, str, None] = ..., - maxlinelen: Optional[int] = ..., - header_name: Optional[str] = ..., continuation_ws: str = ..., - errors: str = ...) -> None: ... - def append(self, s: Union[bytes, str], - charset: Union[Charset, str, None] = ..., - errors: str = ...) -> None: ... - def encode(self, splitchars: str = ..., maxlinelen: Optional[int] = ..., - linesep: str = ...) -> str: ... + def __init__( + self, + s: Union[bytes, str, None] = ..., + charset: Union[Charset, str, None] = ..., + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., + continuation_ws: str = ..., + errors: str = ..., + ) -> None: ... + def append(self, s: Union[bytes, str], charset: Union[Charset, str, None] = ..., errors: str = ...) -> None: ... + def encode(self, splitchars: str = ..., maxlinelen: Optional[int] = ..., linesep: str = ...) -> str: ... def __str__(self) -> str: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... def decode_header(header: Union[Header, str]) -> List[Tuple[bytes, Optional[str]]]: ... -def make_header(decoded_seq: List[Tuple[bytes, Optional[str]]], - maxlinelen: Optional[int] = ..., - header_name: Optional[str] = ..., - continuation_ws: str = ...) -> Header: ... +def make_header( + decoded_seq: List[Tuple[bytes, Optional[str]]], + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., + continuation_ws: str = ..., +) -> Header: ... diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 6af1abfb517f..4ccb4d312203 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -1,9 +1,7 @@ -# Stubs for email.headerregistry (Python 3.4) - from datetime import datetime as _datetime -from typing import Dict, Tuple, Optional, Any, Union, Mapping from email.errors import MessageDefect from email.policy import Policy +from typing import Any, Dict, Mapping, Optional, Tuple, Union class BaseHeader(str): @property @@ -25,8 +23,7 @@ class UniqueUnstructuredHeader(UnstructuredHeader): ... class DateHeader: datetime: _datetime @classmethod - def parse(cls, string: Union[str, _datetime], - kwds: Dict[str, Any]) -> None: ... + def parse(cls, string: Union[str, _datetime], kwds: Dict[str, Any]) -> None: ... class UniqueDateHeader(DateHeader): ... @@ -70,9 +67,7 @@ class ContentTransferEncodingHeader: def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... class HeaderRegistry: - def __init__(self, base_class: BaseHeader = ..., - default_class: BaseHeader = ..., - use_default_map: bool = ...) -> None: ... + def __init__(self, base_class: BaseHeader = ..., default_class: BaseHeader = ..., use_default_map: bool = ...) -> None: ... def map_to_type(self, name: str, cls: BaseHeader) -> None: ... def __getitem__(self, name: str) -> BaseHeader: ... def __call__(self, name: str, value: Any) -> BaseHeader: ... @@ -83,15 +78,13 @@ class Address: domain: str @property def addr_spec(self) -> str: ... - def __init__(self, display_name: str = ..., - username: Optional[str] = ..., - domain: Optional[str] = ..., - addr_spec: Optional[str] = ...) -> None: ... + def __init__( + self, display_name: str = ..., username: Optional[str] = ..., domain: Optional[str] = ..., addr_spec: Optional[str] = ... + ) -> None: ... def __str__(self) -> str: ... class Group: display_name: Optional[str] addresses: Tuple[Address, ...] - def __init__(self, display_name: Optional[str] = ..., - addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... + def __init__(self, display_name: Optional[str] = ..., addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... def __str__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/email/iterators.pyi b/mypy/typeshed/stdlib/email/iterators.pyi index 6a69f39c9518..2b3d14c2ebeb 100644 --- a/mypy/typeshed/stdlib/email/iterators.pyi +++ b/mypy/typeshed/stdlib/email/iterators.pyi @@ -1,8 +1,5 @@ -# Stubs for email.iterators (Python 3.4) - -from typing import Iterator, Optional from email.message import Message +from typing import Iterator, Optional def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ... -def typed_subpart_iterator(msg: Message, maintype: str = ..., - subtype: Optional[str] = ...) -> Iterator[str]: ... +def typed_subpart_iterator(msg: Message, maintype: str = ..., subtype: Optional[str] = ...) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 85bba630beea..720d5e5d7b63 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -1,15 +1,10 @@ -# Stubs for email.message (Python 3.4) - -from typing import ( - List, Optional, Union, Tuple, TypeVar, Generator, Sequence, Iterator, Any -) from email.charset import Charset +from email.contentmanager import ContentManager from email.errors import MessageDefect -from email.header import Header from email.policy import Policy -from email.contentmanager import ContentManager +from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union -_T = TypeVar('_T') +_T = TypeVar("_T") _PayloadType = Union[List[Message], str, bytes] _CharsetType = Union[Charset, str, None] @@ -27,8 +22,7 @@ class Message: def get_unixfrom(self) -> Optional[str]: ... def attach(self, payload: Message) -> None: ... def get_payload(self, i: int = ..., decode: bool = ...) -> Any: ... # returns Optional[_PayloadType] - def set_payload(self, payload: _PayloadType, - charset: _CharsetType = ...) -> None: ... + def set_payload(self, payload: _PayloadType, charset: _CharsetType = ...) -> None: ... def set_charset(self, charset: _CharsetType) -> None: ... def get_charset(self) -> _CharsetType: ... def __len__(self) -> int: ... @@ -48,14 +42,10 @@ class Message: def get_content_subtype(self) -> str: ... def get_default_type(self) -> str: ... def set_default_type(self, ctype: str) -> None: ... - def get_params(self, failobj: _T = ..., header: str = ..., - unquote: bool = ...) -> Union[List[Tuple[str, str]], _T]: ... - def get_param(self, param: str, failobj: _T = ..., header: str = ..., - unquote: bool = ...) -> Union[_T, _ParamType]: ... - def del_param(self, param: str, header: str = ..., - requote: bool = ...) -> None: ... - def set_type(self, type: str, header: str = ..., - requote: bool = ...) -> None: ... + def get_params(self, failobj: _T = ..., header: str = ..., unquote: bool = ...) -> Union[List[Tuple[str, str]], _T]: ... + def get_param(self, param: str, failobj: _T = ..., header: str = ..., unquote: bool = ...) -> Union[_T, _ParamType]: ... + def del_param(self, param: str, header: str = ..., requote: bool = ...) -> None: ... + def set_type(self, type: str, header: str = ..., requote: bool = ...) -> None: ... def get_filename(self, failobj: _T = ...) -> Union[_T, str]: ... def get_boundary(self, failobj: _T = ...) -> Union[_T, str]: ... def set_boundary(self, boundary: str) -> None: ... @@ -63,39 +53,33 @@ class Message: def get_charsets(self, failobj: _T = ...) -> Union[_T, List[str]]: ... def walk(self) -> Generator[Message, None, None]: ... def get_content_disposition(self) -> Optional[str]: ... - def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ..., - policy: Optional[Policy] = ...) -> str: ... - def as_bytes(self, unixfrom: bool = ..., - policy: Optional[Policy] = ...) -> bytes: ... + def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ..., policy: Optional[Policy] = ...) -> str: ... + def as_bytes(self, unixfrom: bool = ..., policy: Optional[Policy] = ...) -> bytes: ... def __bytes__(self) -> bytes: ... - def set_param(self, param: str, value: str, header: str = ..., - requote: bool = ..., charset: str = ..., - language: str = ..., replace: bool = ...) -> None: ... + def set_param( + self, + param: str, + value: str, + header: str = ..., + requote: bool = ..., + charset: str = ..., + language: str = ..., + replace: bool = ..., + ) -> None: ... def __init__(self, policy: Policy = ...) -> None: ... class MIMEPart(Message): - def get_body(self, - preferencelist: Sequence[str] = ...) -> Optional[Message]: ... + def get_body(self, preferencelist: Sequence[str] = ...) -> Optional[Message]: ... def iter_attachments(self) -> Iterator[Message]: ... def iter_parts(self) -> Iterator[Message]: ... - def get_content(self, *args: Any, - content_manager: Optional[ContentManager] = ..., - **kw: Any) -> Any: ... - def set_content(self, *args: Any, - content_manager: Optional[ContentManager] = ..., - **kw: Any) -> None: ... + def get_content(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> Any: ... + def set_content(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> None: ... def make_related(self, boundary: Optional[str] = ...) -> None: ... def make_alternative(self, boundary: Optional[str] = ...) -> None: ... def make_mixed(self, boundary: Optional[str] = ...) -> None: ... - def add_related(self, *args: Any, - content_manager: Optional[ContentManager] = ..., - **kw: Any) -> None: ... - def add_alternative(self, *args: Any, - content_manager: Optional[ContentManager] = ..., - **kw: Any) -> None: ... - def add_attachment(self, *args: Any, - content_manager: Optional[ContentManager] = ..., - **kw: Any) -> None: ... + def add_related(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> None: ... + def add_alternative(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> None: ... + def add_attachment(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> None: ... def clear(self) -> None: ... def clear_content(self) -> None: ... def is_attachment(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/mime/application.pyi b/mypy/typeshed/stdlib/email/mime/application.pyi index c27d808a43c6..d1b2f1dad6b4 100644 --- a/mypy/typeshed/stdlib/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/email/mime/application.pyi @@ -1,6 +1,3 @@ -# Stubs for email.mime.application (Python 3.4) - -import sys from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Tuple, Union @@ -8,21 +5,12 @@ from typing import Callable, Optional, Tuple, Union _ParamsType = Union[str, None, Tuple[str, Optional[str], str]] class MIMEApplication(MIMENonMultipart): - if sys.version_info >= (3, 6): - def __init__( - self, - _data: Union[str, bytes], - _subtype: str = ..., - _encoder: Callable[[MIMEApplication], None] = ..., - *, - policy: Optional[Policy] = ..., - **_params: _ParamsType, - ) -> None: ... - else: - def __init__( - self, - _data: Union[str, bytes], - _subtype: str = ..., - _encoder: Callable[[MIMEApplication], None] = ..., - **_params: _ParamsType, - ) -> None: ... + def __init__( + self, + _data: Union[str, bytes], + _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/audio.pyi b/mypy/typeshed/stdlib/email/mime/audio.pyi index 71d060bcba5d..9bd5b5ca57b0 100644 --- a/mypy/typeshed/stdlib/email/mime/audio.pyi +++ b/mypy/typeshed/stdlib/email/mime/audio.pyi @@ -1,6 +1,3 @@ -# Stubs for email.mime.audio (Python 3.4) - -import sys from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Tuple, Union @@ -8,21 +5,12 @@ from typing import Callable, Optional, Tuple, Union _ParamsType = Union[str, None, Tuple[str, Optional[str], str]] class MIMEAudio(MIMENonMultipart): - if sys.version_info >= (3, 6): - def __init__( - self, - _audiodata: Union[str, bytes], - _subtype: Optional[str] = ..., - _encoder: Callable[[MIMEAudio], None] = ..., - *, - policy: Optional[Policy] = ..., - **_params: _ParamsType, - ) -> None: ... - else: - def __init__( - self, - _audiodata: Union[str, bytes], - _subtype: Optional[str] = ..., - _encoder: Callable[[MIMEAudio], None] = ..., - **_params: _ParamsType, - ) -> None: ... + def __init__( + self, + _audiodata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEAudio], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/base.pyi b/mypy/typeshed/stdlib/email/mime/base.pyi index 38c6130de023..1e3223315e88 100644 --- a/mypy/typeshed/stdlib/email/mime/base.pyi +++ b/mypy/typeshed/stdlib/email/mime/base.pyi @@ -1,14 +1,8 @@ -# Stubs for email.mime.base (Python 3.4) - import email.message -import sys from email.policy import Policy from typing import Optional, Tuple, Union _ParamsType = Union[str, None, Tuple[str, Optional[str], str]] class MIMEBase(email.message.Message): - if sys.version_info >= (3, 6): - def __init__(self, _maintype: str, _subtype: str, *, policy: Optional[Policy] = ..., **_params: _ParamsType) -> None: ... - else: - def __init__(self, _maintype: str, _subtype: str, **_params: _ParamsType) -> None: ... + def __init__(self, _maintype: str, _subtype: str, *, policy: Optional[Policy] = ..., **_params: _ParamsType) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/image.pyi b/mypy/typeshed/stdlib/email/mime/image.pyi index d6d019ce53cd..f192494ec74c 100644 --- a/mypy/typeshed/stdlib/email/mime/image.pyi +++ b/mypy/typeshed/stdlib/email/mime/image.pyi @@ -1,6 +1,3 @@ -# Stubs for email.mime.image (Python 3.4) - -import sys from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Tuple, Union @@ -8,21 +5,12 @@ from typing import Callable, Optional, Tuple, Union _ParamsType = Union[str, None, Tuple[str, Optional[str], str]] class MIMEImage(MIMENonMultipart): - if sys.version_info >= (3, 6): - def __init__( - self, - _imagedata: Union[str, bytes], - _subtype: Optional[str] = ..., - _encoder: Callable[[MIMEImage], None] = ..., - *, - policy: Optional[Policy] = ..., - **_params: _ParamsType, - ) -> None: ... - else: - def __init__( - self, - _imagedata: Union[str, bytes], - _subtype: Optional[str] = ..., - _encoder: Callable[[MIMEImage], None] = ..., - **_params: _ParamsType, - ) -> None: ... + def __init__( + self, + _imagedata: Union[str, bytes], + _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEImage], None] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/message.pyi b/mypy/typeshed/stdlib/email/mime/message.pyi index 1c56208f1183..d2ce81818a24 100644 --- a/mypy/typeshed/stdlib/email/mime/message.pyi +++ b/mypy/typeshed/stdlib/email/mime/message.pyi @@ -1,13 +1,7 @@ -# Stubs for email.mime.message (Python 3.4) - -import sys from email.message import Message from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Optional class MIMEMessage(MIMENonMultipart): - if sys.version_info >= (3, 6): - def __init__(self, _msg: Message, _subtype: str = ..., *, policy: Optional[Policy] = ...) -> None: ... - else: - def __init__(self, _msg: Message, _subtype: str = ...) -> None: ... + def __init__(self, _msg: Message, _subtype: str = ..., *, policy: Optional[Policy] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/multipart.pyi b/mypy/typeshed/stdlib/email/mime/multipart.pyi index 4c78fd4d5745..eb5f662de058 100644 --- a/mypy/typeshed/stdlib/email/mime/multipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/multipart.pyi @@ -1,6 +1,3 @@ -# Stubs for email.mime.multipart (Python 3.4) - -import sys from email.message import Message from email.mime.base import MIMEBase from email.policy import Policy @@ -9,21 +6,12 @@ from typing import Optional, Sequence, Tuple, Union _ParamsType = Union[str, None, Tuple[str, Optional[str], str]] class MIMEMultipart(MIMEBase): - if sys.version_info >= (3, 6): - def __init__( - self, - _subtype: str = ..., - boundary: Optional[str] = ..., - _subparts: Optional[Sequence[Message]] = ..., - *, - policy: Optional[Policy] = ..., - **_params: _ParamsType, - ) -> None: ... - else: - def __init__( - self, - _subtype: str = ..., - boundary: Optional[str] = ..., - _subparts: Optional[Sequence[Message]] = ..., - **_params: _ParamsType, - ) -> None: ... + def __init__( + self, + _subtype: str = ..., + boundary: Optional[str] = ..., + _subparts: Optional[Sequence[Message]] = ..., + *, + policy: Optional[Policy] = ..., + **_params: _ParamsType, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi index 1fd3ea98bc62..4addff18861a 100644 --- a/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi @@ -1,5 +1,3 @@ -# Stubs for email.mime.nonmultipart (Python 3.4) - from email.mime.base import MIMEBase class MIMENonMultipart(MIMEBase): ... diff --git a/mypy/typeshed/stdlib/email/mime/text.pyi b/mypy/typeshed/stdlib/email/mime/text.pyi index f219e843b865..aa5590ebb60f 100644 --- a/mypy/typeshed/stdlib/email/mime/text.pyi +++ b/mypy/typeshed/stdlib/email/mime/text.pyi @@ -1,14 +1,8 @@ -# Stubs for email.mime.text (Python 3.4) - -import sys from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Optional class MIMEText(MIMENonMultipart): - if sys.version_info >= (3, 6): - def __init__( - self, _text: str, _subtype: str = ..., _charset: Optional[str] = ..., *, policy: Optional[Policy] = ... - ) -> None: ... - else: - def __init__(self, _text: str, _subtype: str = ..., _charset: Optional[str] = ...) -> None: ... + def __init__( + self, _text: str, _subtype: str = ..., _charset: Optional[str] = ..., *, policy: Optional[Policy] = ... + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index 89ca2774b34a..f1e402408d47 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,5 +1,3 @@ -# Stubs for email.parser (Python 3.4) - import email.feedparser from email.message import Message from email.policy import Policy @@ -9,25 +7,21 @@ FeedParser = email.feedparser.FeedParser BytesFeedParser = email.feedparser.BytesFeedParser class Parser: - def __init__(self, _class: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... + def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... class HeaderParser(Parser): - def __init__(self, _class: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... + def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... class BytesHeaderParser(BytesParser): - def __init__(self, _class: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... + def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... class BytesParser: - def __init__(self, _class: Callable[[], Message] = ..., *, - policy: Policy = ...) -> None: ... + def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 5f3b8977af9d..d0906ebf1cf5 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -1,11 +1,9 @@ -# Stubs for email.policy (Python 3.4) - from abc import abstractmethod -from typing import Any, List, Optional, Tuple, Union, Callable -from email.message import Message +from email.contentmanager import ContentManager from email.errors import MessageDefect from email.header import Header -from email.contentmanager import ContentManager +from email.message import Message +from typing import Any, Callable, List, Optional, Tuple, Union class Policy: max_line_length: Optional[int] @@ -15,28 +13,23 @@ class Policy: mange_from: bool def __init__(self, **kw: Any) -> None: ... def clone(self, **kw: Any) -> Policy: ... - def handle_defect(self, obj: Message, - defect: MessageDefect) -> None: ... - def register_defect(self, obj: Message, - defect: MessageDefect) -> None: ... + def handle_defect(self, obj: Message, defect: MessageDefect) -> None: ... + def register_defect(self, obj: Message, defect: MessageDefect) -> None: ... def header_max_count(self, name: str) -> Optional[int]: ... @abstractmethod - def header_source_parse(self, sourcelines: List[str]) -> str: ... + def header_source_parse(self, sourcelines: List[str]) -> Tuple[str, str]: ... @abstractmethod - def header_store_parse(self, name: str, - value: str) -> Tuple[str, str]: ... + def header_store_parse(self, name: str, value: str) -> Tuple[str, str]: ... @abstractmethod - def header_fetch_parse(self, name: str, - value: str) -> str: ... + def header_fetch_parse(self, name: str, value: str) -> str: ... @abstractmethod def fold(self, name: str, value: str) -> str: ... @abstractmethod def fold_binary(self, name: str, value: str) -> bytes: ... class Compat32(Policy): - def header_source_parse(self, sourcelines: List[str]) -> str: ... - def header_store_parse(self, name: str, - value: str) -> Tuple[str, str]: ... + def header_source_parse(self, sourcelines: List[str]) -> Tuple[str, str]: ... + def header_store_parse(self, name: str, value: str) -> Tuple[str, str]: ... def header_fetch_parse(self, name: str, value: str) -> Union[str, Header]: ... # type: ignore def fold(self, name: str, value: str) -> str: ... def fold_binary(self, name: str, value: str) -> bytes: ... @@ -48,9 +41,8 @@ class EmailPolicy(Policy): refold_source: str header_factory: Callable[[str, str], str] content_manager: ContentManager - def header_source_parse(self, sourcelines: List[str]) -> str: ... - def header_store_parse(self, name: str, - value: str) -> Tuple[str, str]: ... + def header_source_parse(self, sourcelines: List[str]) -> Tuple[str, str]: ... + def header_store_parse(self, name: str, value: str) -> Tuple[str, str]: ... def header_fetch_parse(self, name: str, value: str) -> str: ... def fold(self, name: str, value: str) -> str: ... def fold_binary(self, name: str, value: str) -> bytes: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 6c0a18319759..7c4c409be80d 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -1,8 +1,7 @@ -# Stubs for email.utils (Python 3.4) - -from typing import List, Optional, Tuple, Union -from email.charset import Charset import datetime +import sys +from email.charset import Charset +from typing import List, Optional, Tuple, Union, overload _ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] _PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] @@ -10,24 +9,32 @@ _PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... def parseaddr(address: Optional[str]) -> Tuple[str, str]: ... -def formataddr(pair: Tuple[Optional[str], str], - charset: Union[str, Charset] = ...) -> str: ... +def formataddr(pair: Tuple[Optional[str], str], charset: Union[str, Charset] = ...) -> str: ... def getaddresses(fieldvalues: List[str]) -> List[Tuple[str, str]]: ... +@overload +def parsedate(date: None) -> None: ... +@overload def parsedate(date: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ... +@overload +def parsedate_tz(date: None) -> None: ... +@overload def parsedate_tz(date: str) -> Optional[_PDTZ]: ... -def parsedate_to_datetime(date: str) -> datetime.datetime: ... + +if sys.version_info >= (3, 10): + @overload + def parsedate_to_datetime(date: None) -> None: ... + @overload + def parsedate_to_datetime(date: str) -> datetime.datetime: ... + +else: + def parsedate_to_datetime(date: str) -> datetime.datetime: ... + def mktime_tz(tuple: _PDTZ) -> int: ... -def formatdate(timeval: Optional[float] = ..., localtime: bool = ..., - usegmt: bool = ...) -> str: ... +def formatdate(timeval: Optional[float] = ..., localtime: bool = ..., usegmt: bool = ...) -> str: ... def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ... def localtime(dt: Optional[datetime.datetime] = ...) -> datetime.datetime: ... -def make_msgid(idstring: Optional[str] = ..., - domain: Optional[str] = ...) -> str: ... +def make_msgid(idstring: Optional[str] = ..., domain: Optional[str] = ...) -> str: ... def decode_rfc2231(s: str) -> Tuple[Optional[str], Optional[str], str]: ... -def encode_rfc2231(s: str, charset: Optional[str] = ..., - language: Optional[str] = ...) -> str: ... -def collapse_rfc2231_value(value: _ParamType, errors: str = ..., - fallback_charset: str = ...) -> str: ... -def decode_params( - params: List[Tuple[str, str]] -) -> List[Tuple[str, _ParamType]]: ... +def encode_rfc2231(s: str, charset: Optional[str] = ..., language: Optional[str] = ...) -> str: ... +def collapse_rfc2231_value(value: _ParamType, errors: str = ..., fallback_charset: str = ...) -> str: ... +def decode_params(params: List[Tuple[str, str]]) -> List[Tuple[str, _ParamType]]: ... diff --git a/mypy/typeshed/stdlib/encodings/__init__.pyi b/mypy/typeshed/stdlib/encodings/__init__.pyi index c75fd07c6f33..d6f4389bc820 100644 --- a/mypy/typeshed/stdlib/encodings/__init__.pyi +++ b/mypy/typeshed/stdlib/encodings/__init__.pyi @@ -1,8 +1,4 @@ -# This comment serves as a workaround for timothycrosley/isort#1027 and can -# be removed when a release with a fix was released. - import codecs - from typing import Any def search_function(encoding: str) -> codecs.CodecInfo: ... diff --git a/mypy/typeshed/stdlib/ensurepip/__init__.pyi b/mypy/typeshed/stdlib/ensurepip/__init__.pyi index 10634f2baa6d..a411dbb456d2 100644 --- a/mypy/typeshed/stdlib/ensurepip/__init__.pyi +++ b/mypy/typeshed/stdlib/ensurepip/__init__.pyi @@ -1,10 +1,25 @@ - -from typing import Optional 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: ... + 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/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 8ffaa2b5eb1d..1a1dcf005b2d 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -1,10 +1,9 @@ -# NB: third_party/2/enum.pyi and stdlib/3.4/enum.pyi must remain consistent! import sys -from typing import Any, Dict, Iterator, List, Mapping, Type, TypeVar, Union from abc import ABCMeta +from typing import Any, Dict, Iterator, List, Mapping, Type, TypeVar, Union -_T = TypeVar('_T') -_S = TypeVar('_S', bound=Type[Enum]) +_T = TypeVar("_T") +_S = TypeVar("_S", bound=Type[Enum]) # Note: EnumMeta actually subclasses type directly, not ABCMeta. # This is a temporary workaround to allow multiple creation of enums with builtins @@ -30,13 +29,12 @@ class Enum(metaclass=EnumMeta): _value2member_map_: Dict[int, Enum] # undocumented if sys.version_info >= (3, 7): _ignore_: Union[str, List[str]] - if sys.version_info >= (3, 6): - _order_: str - __order__: str - @classmethod - def _missing_(cls, value: object) -> Any: ... - @staticmethod - def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> Any: ... + _order_: str + __order__: str + @classmethod + def _missing_(cls, value: object) -> Any: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> Any: ... def __new__(cls: Type[_T], value: object) -> _T: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... @@ -50,27 +48,26 @@ class IntEnum(int, Enum): def unique(enumeration: _S) -> _S: ... -if sys.version_info >= (3, 6): - _auto_null: Any +_auto_null: Any - # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() - class auto(IntFlag): - value: Any +# subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() +class auto(IntFlag): + value: Any - class Flag(Enum): - def __contains__(self: _T, other: _T) -> bool: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - def __bool__(self) -> bool: ... - def __or__(self: _T, other: _T) -> _T: ... - def __and__(self: _T, other: _T) -> _T: ... - def __xor__(self: _T, other: _T) -> _T: ... - def __invert__(self: _T) -> _T: ... +class Flag(Enum): + def __contains__(self: _T, other: _T) -> bool: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __bool__(self) -> bool: ... + def __or__(self: _T, other: _T) -> _T: ... + def __and__(self: _T, other: _T) -> _T: ... + def __xor__(self: _T, other: _T) -> _T: ... + def __invert__(self: _T) -> _T: ... - class IntFlag(int, Flag): - def __or__(self: _T, other: Union[int, _T]) -> _T: ... - def __and__(self: _T, other: Union[int, _T]) -> _T: ... - def __xor__(self: _T, other: Union[int, _T]) -> _T: ... - __ror__ = __or__ - __rand__ = __and__ - __rxor__ = __xor__ +class IntFlag(int, Flag): + def __or__(self: _T, other: Union[int, _T]) -> _T: ... + def __and__(self: _T, other: Union[int, _T]) -> _T: ... + def __xor__(self: _T, other: Union[int, _T]) -> _T: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ diff --git a/mypy/typeshed/stdlib/errno.pyi b/mypy/typeshed/stdlib/errno.pyi index 731681f1c6fd..b053604fc33a 100644 --- a/mypy/typeshed/stdlib/errno.pyi +++ b/mypy/typeshed/stdlib/errno.pyi @@ -1,7 +1,4 @@ -# Stubs for errno - from typing import Mapping -import sys errorcode: Mapping[int, str] diff --git a/mypy/typeshed/stdlib/faulthandler.pyi b/mypy/typeshed/stdlib/faulthandler.pyi index ffecf3d5daa6..7b42b8ec8444 100644 --- a/mypy/typeshed/stdlib/faulthandler.pyi +++ b/mypy/typeshed/stdlib/faulthandler.pyi @@ -7,6 +7,7 @@ def dump_traceback(file: FileDescriptorLike = ..., all_threads: bool = ...) -> N def dump_traceback_later(timeout: float, repeat: bool = ..., file: FileDescriptorLike = ..., exit: bool = ...) -> None: ... def enable(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ... def is_enabled() -> bool: ... + if sys.platform != "win32": def register(signum: int, file: FileDescriptorLike = ..., all_threads: bool = ..., chain: bool = ...) -> None: ... def unregister(signum: int) -> None: ... diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index cfb13ed9c4ee..7b94c6e941ce 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -1,7 +1,8 @@ +import sys +from _typeshed import FileDescriptorLike from array import array from typing import Any, Union, overload from typing_extensions import Literal -from _typeshed import FileDescriptorLike FASYNC: int FD_CLOEXEC: int @@ -33,6 +34,10 @@ F_SETLK: int F_SETLK64: int F_SETLKW: int F_SETLKW64: int +if sys.version_info >= (3, 9) and sys.platform == "linux": + F_OFD_GETLK: int + F_OFD_SETLK: int + F_OFD_SETLKW: int F_SETOWN: int F_SETSIG: int F_SHLCK: int @@ -75,40 +80,20 @@ LOCK_RW: int LOCK_SH: int LOCK_UN: int LOCK_WRITE: int - @overload -def fcntl(__fd: FileDescriptorLike, - __cmd: int, - __arg: int = ...) -> int: ... +def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... @overload -def fcntl(__fd: FileDescriptorLike, - __cmd: int, - __arg: bytes) -> bytes: ... +def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: bytes) -> bytes: ... + _ReadOnlyBuffer = bytes _WritableBuffer = Union[bytearray, memoryview, array] @overload -def ioctl(__fd: FileDescriptorLike, - __request: int, - __arg: int = ..., - __mutate_flag: bool = ...) -> int: ... +def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = ..., __mutate_flag: bool = ...) -> int: ... @overload -def ioctl(__fd: FileDescriptorLike, - __request: int, - __arg: _WritableBuffer, - __mutate_flag: Literal[True] = ...) -> int: ... +def ioctl(__fd: FileDescriptorLike, __request: int, __arg: _WritableBuffer, __mutate_flag: Literal[True] = ...) -> int: ... @overload -def ioctl(__fd: FileDescriptorLike, - __request: int, - __arg: _WritableBuffer, - __mutate_flag: Literal[False]) -> bytes: ... +def ioctl(__fd: FileDescriptorLike, __request: int, __arg: _WritableBuffer, __mutate_flag: Literal[False]) -> bytes: ... @overload -def ioctl(__fd: FileDescriptorLike, - __request: int, - __arg: _ReadOnlyBuffer, - __mutate_flag: bool = ...) -> bytes: ... +def ioctl(__fd: FileDescriptorLike, __request: int, __arg: _ReadOnlyBuffer, __mutate_flag: bool = ...) -> bytes: ... def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... -def lockf(__fd: FileDescriptorLike, - __cmd: int, - __len: int = ..., - __start: int = ..., - __whence: int = ...) -> Any: ... +def lockf(__fd: FileDescriptorLike, __cmd: int, __len: int = ..., __start: int = ..., __whence: int = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 3e28f32a9ebd..b05eebac07c9 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,36 +1,48 @@ -# Stubs for filecmp (Python 2/3) import sys -from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Tuple, Union, Text +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 +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]]: ... + 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 cmpfiles( + a: AnyStr, b: 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: ... + 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: 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] @@ -44,11 +56,9 @@ class dircmp(Generic[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: ... @@ -56,6 +66,8 @@ class dircmp(Generic[AnyStr]): def phase3(self) -> None: ... def phase4(self) -> None: ... def phase4_closure(self) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3,): def clear_cache() -> None: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 6a015b25220c..fbb602b3bf45 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,6 +1,6 @@ -from typing import Iterable, Callable, IO, AnyStr, Generic, Any, Union, Iterator, Optional -from _typeshed import AnyPath import sys +from _typeshed import AnyPath +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Optional, Union if sys.version_info >= (3, 8): def input( @@ -11,6 +11,7 @@ if sys.version_info >= (3, 8): mode: str = ..., openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., ) -> FileInput[AnyStr]: ... + else: def input( files: Union[AnyPath, Iterable[AnyPath], None] = ..., @@ -39,7 +40,7 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): backup: str = ..., *, mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ... + openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., ) -> None: ... else: def __init__( @@ -49,9 +50,8 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): backup: str = ..., bufsize: int = ..., mode: str = ..., - openhook: Callable[[AnyPath, str], IO[AnyStr]] = ... + openhook: Callable[[AnyPath, str], IO[AnyStr]] = ..., ) -> None: ... - def __del__(self) -> None: ... def close(self) -> None: ... if sys.version_info >= (3, 2): @@ -70,7 +70,9 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): 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]]: ... diff --git a/mypy/typeshed/stdlib/fnmatch.pyi b/mypy/typeshed/stdlib/fnmatch.pyi index 4f99b4aafd6d..5311f13e8874 100644 --- a/mypy/typeshed/stdlib/fnmatch.pyi +++ b/mypy/typeshed/stdlib/fnmatch.pyi @@ -1,9 +1,4 @@ -# Stubs for fnmatch - -# Based on http://docs.python.org/3.2/library/fnmatch.html and -# python-lib/fnmatch.py - -from typing import Iterable, List, AnyStr +from typing import AnyStr, Iterable, List def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ... def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... diff --git a/mypy/typeshed/stdlib/formatter.pyi b/mypy/typeshed/stdlib/formatter.pyi index 2ddef2be7580..31c45592a215 100644 --- a/mypy/typeshed/stdlib/formatter.pyi +++ b/mypy/typeshed/stdlib/formatter.pyi @@ -1,6 +1,4 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/formatter.py -# and https://github.com/python/cpython/blob/master/Lib/formatter.py -from typing import Any, IO, List, Optional, Tuple, Iterable +from typing import IO, Any, Iterable, List, Optional, Tuple AS_IS: None _FontType = Tuple[str, bool, bool, bool] diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 81d056a0756e..dd9c77ed3979 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -1,17 +1,11 @@ -# Stubs for fractions -# See https://docs.python.org/3/library/fractions.html -# -# Note: these stubs are incomplete. The more complex type -# signatures are currently omitted. Also see numbers.pyi. - -from typing import Optional, TypeVar, Union, overload, Any, Tuple -from numbers import Real, Integral, Rational -from decimal import Decimal import sys +from decimal import Decimal +from numbers import Integral, Rational, Real +from typing import Optional, Tuple, Union, overload +from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] - if sys.version_info < (3, 9): @overload def gcd(a: int, b: int) -> int: ... @@ -22,50 +16,119 @@ if sys.version_info < (3, 9): @overload def gcd(a: Integral, b: Integral) -> Integral: ... - class Fraction(Rational): @overload - def __new__(cls, - numerator: Union[int, Rational] = ..., - denominator: Optional[Union[int, Rational]] = ..., - *, - _normalize: bool = ...) -> Fraction: ... + def __new__( + cls, numerator: Union[int, Rational] = ..., denominator: Optional[Union[int, Rational]] = ..., *, _normalize: bool = ... + ) -> Fraction: ... @overload def __new__(cls, __value: Union[float, Decimal, str], *, _normalize: bool = ...) -> Fraction: ... - @classmethod def from_float(cls, f: float) -> Fraction: ... @classmethod def from_decimal(cls, dec: Decimal) -> Fraction: ... def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... - if sys.version_info >= (3, 8): def as_integer_ratio(self) -> Tuple[int, int]: ... @property def numerator(self) -> int: ... @property def denominator(self) -> int: ... - - def __add__(self, other): ... - def __radd__(self, other): ... - def __sub__(self, other): ... - def __rsub__(self, other): ... - def __mul__(self, other): ... - def __rmul__(self, other): ... - def __truediv__(self, other): ... - def __rtruediv__(self, other): ... + @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: ... if sys.version_info < (3, 0): - def __div__(self, other): ... - def __rdiv__(self, other): ... - def __floordiv__(self, other) -> int: ... - def __rfloordiv__(self, other) -> int: ... - def __mod__(self, other): ... - def __rmod__(self, other): ... - def __divmod__(self, other): ... - def __rdivmod__(self, other): ... - def __pow__(self, other): ... - def __rpow__(self, other): ... - + @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: ... @@ -73,8 +136,10 @@ class Fraction(Rational): if sys.version_info >= (3, 0): def __floor__(self) -> int: ... def __ceil__(self) -> int: ... - def __round__(self, ndigits: Optional[Any] = ...): ... - + @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: ... @@ -85,11 +150,10 @@ class Fraction(Rational): def __bool__(self) -> bool: ... else: def __nonzero__(self) -> bool: ... - # Not actually defined within fractions.py, but provides more useful # overrides @property def real(self) -> Fraction: ... @property - def imag(self) -> Fraction: ... + def imag(self) -> Literal[0]: ... def conjugate(self) -> Fraction: ... diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 0c708b3695d2..0661301c0827 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -1,25 +1,10 @@ import sys -from typing import ( - Any, - BinaryIO, - Callable, - Dict, - Generic, - Iterable, - Iterator, - List, - Optional, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, -) -from types import TracebackType +from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext -from _typeshed import SupportsRead, SupportsReadline +from types import TracebackType +from typing import Any, BinaryIO, Callable, Dict, Iterable, Iterator, List, Optional, Text, TextIO, Tuple, Type, TypeVar, Union +from typing_extensions import Literal _T = TypeVar("_T") _IntOrStr = Union[int, Text] @@ -166,3 +151,15 @@ if sys.version_info < (3,): 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/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index beccc37a1f50..10c46f42ea79 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,17 +1,34 @@ import sys -from typing import Any, Callable, Generic, Dict, Hashable, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, NamedTuple, Union, overload +from _typeshed import SupportsLessThan +from typing import ( + Any, + Callable, + Dict, + Generic, + Hashable, + Iterable, + Mapping, + NamedTuple, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + Union, + overload, +) + +if sys.version_info >= (3, 9): + from types import GenericAlias _AnyCallable = Callable[..., Any] _T = TypeVar("_T") _S = TypeVar("_S") - @overload -def reduce(function: Callable[[_T, _S], _T], - sequence: Iterable[_S], initial: _T) -> _T: ... +def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... @overload -def reduce(function: Callable[[_T, _T], _T], - sequence: Iterable[_T]) -> _T: ... +def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... class _CacheInfo(NamedTuple): hits: int @@ -30,17 +47,17 @@ if sys.version_info >= (3, 8): def lru_cache(maxsize: Optional[int] = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... @overload def lru_cache(maxsize: Callable[..., _T], typed: bool = ...) -> _lru_cache_wrapper[_T]: ... + else: def lru_cache(maxsize: Optional[int] = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... WRAPPER_ASSIGNMENTS: Sequence[str] WRAPPER_UPDATES: Sequence[str] -def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., - updated: Sequence[str] = ...) -> _AnyCallable: ... -def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... +def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... def total_ordering(cls: Type[_T]) -> Type[_T]: ... -def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsLessThan]: ... class partial(Generic[_T]): func: Callable[..., _T] @@ -48,6 +65,8 @@ class partial(Generic[_T]): keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # With protocols, this could change into a generic protocol that defines __get__ and returns _T _Descriptor = Any @@ -56,22 +75,30 @@ class partialmethod(Generic[_T]): func: Union[Callable[..., _T], _Descriptor] args: Tuple[Any, ...] keywords: Dict[str, Any] - @overload - def __init__(self, func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... + def __init__(self, __func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... @overload - def __init__(self, func: _Descriptor, *args: Any, **keywords: Any) -> None: ... + def __init__(self, __func: _Descriptor, *args: Any, **keywords: Any) -> None: ... def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class _SingleDispatchCallable(Generic[_T]): registry: Mapping[Any, Callable[..., _T]] def dispatch(self, cls: Any) -> Callable[..., _T]: ... + # @fun.register(complex) + # def _(arg, verbose=False): ... @overload - def register(self, cls: Any) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: type, func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + # @fun.register + # def _(arg: int, verbose=False): @overload - def register(self, cls: Any, func: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: Callable[..., _T], func: None = ...) -> Callable[..., _T]: ... + # fun.register(int, lambda x: x) + @overload + def register(self, cls: Type, func: Callable[..., _T]) -> Callable[..., _T]: ... def _clear_cache(self) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... @@ -83,11 +110,12 @@ if sys.version_info >= (3, 8): func: Callable[..., _T] def __init__(self, func: Callable[..., _T]) -> None: ... @overload - def register(self, cls: Any, method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: Type, method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... @overload - def register(self, cls: Any, method: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: Type, method: Callable[..., _T]) -> Callable[..., _T]: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... - class cached_property(Generic[_T]): func: Callable[[Any], _T] attrname: Optional[str] @@ -97,17 +125,8 @@ if sys.version_info >= (3, 8): @overload def __get__(self, instance: _S, owner: Optional[Type[Any]] = ...) -> _T: ... def __set_name__(self, owner: Type[Any], name: str) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 9): - class TopologicalSorter(Generic[_T]): - def __init__(self, graph: Optional[Dict[_T, Iterable[_T]]] = ...) -> None: ... - def add(self, node: _T, *predecessors: _T) -> None: ... - def prepare(self) -> None: ... - def is_active(self) -> bool: ... - def done(self, *nodes: _T) -> None: ... - def get_ready(self) -> Tuple[_T, ...]: ... - def static_order(self) -> Iterable[_T]: ... - - class CycleError(ValueError): ... - def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 80398ee2a753..841ffd8b34d2 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,9 +1,6 @@ -# Stubs for gc - import sys from typing import Any, Dict, List, Optional, Tuple - DEBUG_COLLECTABLE: int DEBUG_LEAK: int DEBUG_SAVEALL: int @@ -17,16 +14,27 @@ def disable() -> None: ... def enable() -> None: ... def get_count() -> Tuple[int, int, int]: ... def get_debug() -> int: ... + if sys.version_info >= (3, 8): def get_objects(generation: Optional[int] = ...) -> List[Any]: ... + else: def get_objects() -> List[Any]: ... + +if sys.version_info >= (3, 7): + def freeze() -> None: ... + def unfreeze() -> None: ... + def get_freeze_count() -> int: ... + def get_referents(*objs: Any) -> List[Any]: ... def get_referrers(*objs: Any) -> List[Any]: ... def get_stats() -> List[Dict[str, Any]]: ... def get_threshold() -> Tuple[int, int, int]: ... def is_tracked(__obj: Any) -> bool: ... + +if sys.version_info >= (3, 9): + def is_finalized(__obj: Any) -> bool: ... + def isenabled() -> bool: ... def set_debug(__flags: int) -> None: ... -def set_threshold(threshold0: int, threshold1: int = ..., - threshold2: int = ...) -> None: ... +def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 267900c90e5d..8171354d1f39 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -1,15 +1,19 @@ -from typing import Sequence, AnyStr, Text, Union import sys +from typing import AnyStr, Sequence, Text, Union if sys.version_info >= (3, 0): def commonprefix(m: Sequence[str]) -> str: ... + else: def commonprefix(m: Sequence[AnyStr]) -> AnyStr: ... + if sys.version_info >= (3, 6): from builtins import _PathLike def exists(path: Union[AnyStr, _PathLike[AnyStr]]) -> bool: ... + else: def exists(path: Text) -> bool: ... + def isfile(path: Text) -> bool: ... def isdir(s: Text) -> bool: ... def getsize(filename: Text) -> int: ... @@ -17,7 +21,6 @@ def getmtime(filename: Text) -> float: ... def getatime(filename: Text) -> float: ... def getctime(filename: Text) -> float: ... - if sys.version_info >= (3, 4): def samestat(s1: str, s2: str) -> int: ... def samefile(f1: str, f2: str) -> int: ... diff --git a/mypy/typeshed/stdlib/getopt.pyi b/mypy/typeshed/stdlib/getopt.pyi index 0417a827ab61..c92be2a6a8e4 100644 --- a/mypy/typeshed/stdlib/getopt.pyi +++ b/mypy/typeshed/stdlib/getopt.pyi @@ -1,7 +1,3 @@ -# Stubs for getopt - -# Based on http://docs.python.org/3.2/library/getopt.html - from typing import List, Tuple def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/mypy/typeshed/stdlib/getpass.pyi b/mypy/typeshed/stdlib/getpass.pyi index 55a8433fca43..aac162a5166b 100644 --- a/mypy/typeshed/stdlib/getpass.pyi +++ b/mypy/typeshed/stdlib/getpass.pyi @@ -1,12 +1,6 @@ -# Stubs for getpass - from typing import Optional, TextIO - def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... - - def getuser() -> str: ... - class GetPassWarning(UserWarning): ... diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index b28f25b2a8d5..5624817b1435 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -1,6 +1,6 @@ import sys -from typing import overload, Any, Container, IO, Iterable, Optional, Sequence, Type, TypeVar, Union from _typeshed import StrPath +from typing import IO, Any, Container, Iterable, Optional, Sequence, Type, TypeVar, overload from typing_extensions import Literal class NullTranslations: @@ -26,23 +26,39 @@ class GNUTranslations(NullTranslations): CONTEXT: str VERSIONS: Sequence[int] -def find(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., - all: bool = ...) -> Any: ... +def find(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., all: bool = ...) -> Any: ... -_T = TypeVar('_T') +_T = TypeVar("_T") @overload -def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., - class_: None = ..., fallback: bool = ..., codeset: Optional[str] = ...) -> NullTranslations: ... +def translation( + domain: str, + localedir: Optional[StrPath] = ..., + languages: Optional[Iterable[str]] = ..., + class_: None = ..., + fallback: bool = ..., + codeset: Optional[str] = ..., +) -> NullTranslations: ... @overload -def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., - class_: Type[_T] = ..., fallback: Literal[False] = ..., codeset: Optional[str] = ...) -> _T: ... +def translation( + domain: str, + localedir: Optional[StrPath] = ..., + languages: Optional[Iterable[str]] = ..., + class_: Type[_T] = ..., + fallback: Literal[False] = ..., + codeset: Optional[str] = ..., +) -> _T: ... @overload -def translation(domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., - class_: Type[_T] = ..., fallback: Literal[True] = ..., codeset: Optional[str] = ...) -> Any: ... - -def install(domain: str, localedir: Optional[StrPath] = ..., codeset: Optional[str] = ..., - names: Optional[Container[str]] = ...) -> None: ... - +def translation( + domain: str, + localedir: Optional[StrPath] = ..., + languages: Optional[Iterable[str]] = ..., + class_: Type[_T] = ..., + fallback: Literal[True] = ..., + codeset: Optional[str] = ..., +) -> Any: ... +def install( + domain: str, localedir: Optional[StrPath] = ..., codeset: Optional[str] = ..., names: Optional[Container[str]] = ... +) -> None: ... def textdomain(domain: Optional[str] = ...) -> str: ... def bindtextdomain(domain: str, localedir: Optional[StrPath] = ...) -> str: ... def bind_textdomain_codeset(domain: str, codeset: Optional[str] = ...) -> str: ... @@ -54,6 +70,7 @@ def gettext(message: str) -> str: ... def lgettext(message: str) -> str: ... def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... + if sys.version_info >= (3, 8): def pgettext(context: str, message: str) -> str: ... def dpgettext(domain: str, context: str, message: str) -> str: ... diff --git a/mypy/typeshed/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi index 5e73a79712a1..3029b258100a 100644 --- a/mypy/typeshed/stdlib/glob.pyi +++ b/mypy/typeshed/stdlib/glob.pyi @@ -1,19 +1,8 @@ -# Stubs for glob -# Based on http://docs.python.org/3/library/glob.html - -from typing import List, Iterator, AnyStr, Union -import sys - -if sys.version_info >= (3, 6): - def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... -else: - def glob0(dirname: AnyStr, basename: AnyStr) -> List[AnyStr]: ... +from typing import AnyStr, Iterator, List, Union +def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... def glob1(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... - def glob(pathname: AnyStr, *, recursive: bool = ...) -> List[AnyStr]: ... def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ... - def escape(pathname: AnyStr) -> AnyStr: ... - def has_magic(s: Union[str, bytes]) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi new file mode 100644 index 000000000000..ca21b42329d2 --- /dev/null +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -0,0 +1,16 @@ +from _typeshed import SupportsItems +from typing import Generic, Iterable, Optional, Tuple, TypeVar + +_T = TypeVar("_T") + +class TopologicalSorter(Generic[_T]): + def __init__(self, graph: Optional[SupportsItems[_T, Iterable[_T]]] = ...) -> None: ... + def add(self, node: _T, *predecessors: _T) -> None: ... + def prepare(self) -> None: ... + def is_active(self) -> bool: ... + def __bool__(self) -> bool: ... + def done(self, *nodes: _T) -> None: ... + def get_ready(self) -> Tuple[_T, ...]: ... + def static_order(self) -> Iterable[_T]: ... + +class CycleError(ValueError): ... diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index f2976dcb2ee4..4ce54b3b8a5d 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -1,13 +1,12 @@ +import _compression import sys import zlib -from typing import IO, Optional, TextIO, Union, overload -import _compression from _typeshed import AnyPath, ReadableBuffer +from typing import IO, Optional, TextIO, Union, overload from typing_extensions import Literal _OpenBinaryMode = Literal["r", "rb", "a", "ab", "w", "wb", "x", "xb"] _OpenTextMode = Literal["rt", "at", "wt", "xt"] - @overload def open( filename: Union[AnyPath, IO[bytes]], @@ -44,6 +43,9 @@ class _PaddedFile: def seek(self, off: int) -> int: ... def seekable(self) -> bool: ... +if sys.version_info >= (3, 8): + class BadGzipFile(OSError): ... + class GzipFile(_compression.BaseStream): myfileobj: Optional[IO[bytes]] mode: str @@ -84,9 +86,9 @@ class _GzipReader(_compression.DecompressReader): def read(self, size: int = ...) -> bytes: ... if sys.version_info >= (3, 8): - def compress(data, compresslevel: int = ..., *, mtime: Optional[float] = ...) -> bytes: ... + def compress(data: bytes, compresslevel: int = ..., *, mtime: Optional[float] = ...) -> bytes: ... else: - def compress(data, compresslevel: int = ...) -> bytes: ... + def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 0a15ab0d8651..70b120d08a46 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -1,8 +1,6 @@ -# Stubs for hashlib - import sys -from typing import AbstractSet, Optional, Union from _typeshed import ReadableBuffer +from typing import AbstractSet, Optional class _Hash(object): digest_size: int @@ -12,9 +10,7 @@ class _Hash(object): # been present in CPython since its inception, but until Python 3.4 was not # formally specified, so may not exist on some platforms name: str - def __init__(self, data: ReadableBuffer = ...) -> None: ... - def copy(self) -> _Hash: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... @@ -27,6 +23,7 @@ if sys.version_info >= (3, 9): def sha256(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... def sha384(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... def sha512(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... + elif sys.version_info >= (3, 8): def md5(string: ReadableBuffer = ...) -> _Hash: ... def sha1(string: ReadableBuffer = ...) -> _Hash: ... @@ -34,6 +31,7 @@ elif sys.version_info >= (3, 8): def sha256(string: ReadableBuffer = ...) -> _Hash: ... def sha384(string: ReadableBuffer = ...) -> _Hash: ... def sha512(string: ReadableBuffer = ...) -> _Hash: ... + else: def md5(__string: ReadableBuffer = ...) -> _Hash: ... def sha1(__string: ReadableBuffer = ...) -> _Hash: ... @@ -47,40 +45,79 @@ def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] -def pbkdf2_hmac(hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: Optional[int] = ...) -> bytes: ... - -if sys.version_info >= (3, 6): - class _VarLenHash(object): - digest_size: int - block_size: int - name: str - - def __init__(self, data: ReadableBuffer = ...) -> None: ... - - def copy(self) -> _VarLenHash: ... - def digest(self, __length: int) -> bytes: ... - def hexdigest(self, __length: int) -> str: ... - def update(self, __data: ReadableBuffer) -> None: ... +def pbkdf2_hmac( + hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: Optional[int] = ... +) -> bytes: ... - sha3_224 = _Hash - sha3_256 = _Hash - sha3_384 = _Hash - sha3_512 = _Hash - shake_128 = _VarLenHash - shake_256 = _VarLenHash - - def scrypt(password: ReadableBuffer, *, salt: Optional[ReadableBuffer] = ..., n: Optional[int] = ..., r: Optional[int] = ..., p: Optional[int] = ..., maxmem: int = ..., dklen: int = ...) -> bytes: ... - - class _BlakeHash(_Hash): - MAX_DIGEST_SIZE: int - MAX_KEY_SIZE: int - PERSON_SIZE: int - SALT_SIZE: int - - if sys.version_info >= (3, 9): - def __init__(self, __data: ReadableBuffer = ..., *, digest_size: int = ..., key: ReadableBuffer = ..., salt: ReadableBuffer = ..., person: ReadableBuffer = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ..., usedforsecurity: bool = ...) -> None: ... - else: - def __init__(self, __data: ReadableBuffer = ..., *, digest_size: int = ..., key: ReadableBuffer = ..., salt: ReadableBuffer = ..., person: ReadableBuffer = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ...) -> None: ... +class _VarLenHash(object): + digest_size: int + block_size: int + name: str + def __init__(self, data: ReadableBuffer = ...) -> None: ... + def copy(self) -> _VarLenHash: ... + def digest(self, __length: int) -> bytes: ... + def hexdigest(self, __length: int) -> str: ... + def update(self, __data: ReadableBuffer) -> None: ... - blake2b = _BlakeHash - blake2s = _BlakeHash +sha3_224 = _Hash +sha3_256 = _Hash +sha3_384 = _Hash +sha3_512 = _Hash +shake_128 = _VarLenHash +shake_256 = _VarLenHash + +def scrypt( + password: ReadableBuffer, + *, + salt: Optional[ReadableBuffer] = ..., + n: Optional[int] = ..., + r: Optional[int] = ..., + p: Optional[int] = ..., + maxmem: int = ..., + dklen: int = ..., +) -> bytes: ... + +class _BlakeHash(_Hash): + MAX_DIGEST_SIZE: int + MAX_KEY_SIZE: int + PERSON_SIZE: int + SALT_SIZE: int + + if sys.version_info >= (3, 9): + def __init__( + self, + __data: ReadableBuffer = ..., + *, + digest_size: int = ..., + key: ReadableBuffer = ..., + salt: ReadableBuffer = ..., + person: ReadableBuffer = ..., + fanout: int = ..., + depth: int = ..., + leaf_size: int = ..., + node_offset: int = ..., + node_depth: int = ..., + inner_size: int = ..., + last_node: bool = ..., + usedforsecurity: bool = ..., + ) -> None: ... + else: + def __init__( + self, + __data: ReadableBuffer = ..., + *, + digest_size: int = ..., + key: ReadableBuffer = ..., + salt: ReadableBuffer = ..., + person: ReadableBuffer = ..., + fanout: int = ..., + depth: int = ..., + leaf_size: int = ..., + node_offset: int = ..., + node_depth: int = ..., + inner_size: int = ..., + last_node: bool = ..., + ) -> None: ... + +blake2b = _BlakeHash +blake2s = _BlakeHash diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 1b060188093e..5592e615fcd2 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,10 +1,7 @@ -# Stubs for heapq +from _typeshed import SupportsLessThan +from typing import Any, Callable, Iterable, List, Optional, TypeVar -# Based on http://docs.python.org/3.2/library/heapq.html - -from typing import TypeVar, List, Iterable, Any, Callable, Optional - -_T = TypeVar('_T') +_T = TypeVar("_T") def heappush(__heap: List[_T], __item: _T) -> None: ... def heappop(__heap: List[_T]) -> _T: ... @@ -12,7 +9,6 @@ def heappushpop(__heap: List[_T], __item: _T) -> _T: ... def heapify(__heap: List[_T]) -> None: ... def heapreplace(__heap: List[_T], __item: _T) -> _T: ... def merge(*iterables: Iterable[_T], key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> Iterable[_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]: ... +def nlargest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... +def _heapify_max(__x: List[_T]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index d140f1594333..ca4013da7879 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -1,11 +1,7 @@ -# Stubs for hmac - -from typing import Any, AnyStr, Callable, Optional, Union, overload -from types import ModuleType import sys from _typeshed import ReadableBuffer - -_B = Union[bytes, bytearray] +from types import ModuleType +from typing import Any, AnyStr, Callable, Optional, Union, overload # TODO more precise type for object of hashlib _Hash = Any @@ -17,15 +13,15 @@ if sys.version_info >= (3, 8): # In reality digestmod has a default value, but the function always throws an error # if the argument is not given, so we pretend it is a required argument. @overload - def new(key: _B, msg: Optional[ReadableBuffer], digestmod: _DigestMod) -> HMAC: ... + def new(key: bytes, msg: Optional[ReadableBuffer], digestmod: _DigestMod) -> HMAC: ... @overload - def new(key: _B, *, digestmod: _DigestMod) -> HMAC: ... + def new(key: bytes, *, digestmod: _DigestMod) -> HMAC: ... + elif sys.version_info >= (3, 4): - def new(key: _B, msg: Optional[ReadableBuffer] = ..., - digestmod: Optional[_DigestMod] = ...) -> HMAC: ... + def new(key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: Optional[_DigestMod] = ...) -> HMAC: ... + else: - def new(key: _B, msg: Optional[ReadableBuffer] = ..., - digestmod: Optional[_DigestMod] = ...) -> HMAC: ... + def new(key: bytes, msg: Optional[ReadableBuffer] = ..., digestmod: Optional[_DigestMod] = ...) -> HMAC: ... class HMAC: if sys.version_info >= (3,): @@ -33,15 +29,16 @@ class HMAC: if sys.version_info >= (3, 4): 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: ... def hexdigest(self) -> str: ... def copy(self) -> HMAC: ... @overload -def compare_digest(a: ReadableBuffer, b: ReadableBuffer) -> bool: ... +def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... @overload -def compare_digest(a: AnyStr, b: AnyStr) -> bool: ... +def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... if sys.version_info >= (3, 7): - def digest(key: _B, msg: ReadableBuffer, digest: str) -> bytes: ... + def digest(key: bytes, msg: ReadableBuffer, digest: str) -> bytes: ... diff --git a/mypy/typeshed/stdlib/html/parser.pyi b/mypy/typeshed/stdlib/html/parser.pyi index 4c037845a3b0..31240f78c58e 100644 --- a/mypy/typeshed/stdlib/html/parser.pyi +++ b/mypy/typeshed/stdlib/html/parser.pyi @@ -1,5 +1,5 @@ -from typing import List, Optional, Tuple from _markupbase import ParserBase +from typing import List, Optional, Tuple class HTMLParser(ParserBase): def __init__(self, *, convert_charrefs: bool = ...) -> None: ... @@ -8,12 +8,9 @@ class HTMLParser(ParserBase): def reset(self) -> None: ... def getpos(self) -> Tuple[int, int]: ... def get_starttag_text(self) -> Optional[str]: ... - - def handle_starttag(self, tag: str, - attrs: List[Tuple[str, Optional[str]]]) -> None: ... + def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: ... def handle_endtag(self, tag: str) -> None: ... - def handle_startendtag(self, tag: str, - attrs: List[Tuple[str, Optional[str]]]) -> None: ... + def handle_startendtag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: ... def handle_data(self, data: str) -> None: ... def handle_entityref(self, name: str) -> None: ... def handle_charref(self, name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 8b1007e40df3..34402e40b468 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -1,19 +1,30 @@ -from typing import ( - Any, Dict, IO, Iterable, List, Iterator, Mapping, Optional, - Protocol, Tuple, Type, TypeVar, - Union, - overload, - BinaryIO, -) import email.message import io -from socket import socket -import sys import ssl +import sys import types +from socket import socket +from typing import ( + IO, + Any, + BinaryIO, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Protocol, + Tuple, + Type, + TypeVar, + Union, + overload, +) _DataType = Union[bytes, IO[Any], Iterable[bytes], str] -_T = TypeVar('_T') +_T = TypeVar("_T") HTTP_PORT: int HTTPS_PORT: int @@ -80,6 +91,8 @@ responses: Dict[int, str] class HTTPMessage(email.message.Message): ... +def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... + class HTTPResponse(io.BufferedIOBase, BinaryIO): msg: HTTPMessage headers: HTTPMessage @@ -88,8 +101,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): closed: bool status: int reason: str - def __init__(self, sock: socket, debuglevel: int = ..., - method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... + def __init__(self, sock: socket, debuglevel: int = ..., method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... def read(self, amt: Optional[int] = ...) -> bytes: ... @overload def getheader(self, name: str) -> Optional[str]: ... @@ -100,9 +112,9 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def isclosed(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... def __enter__(self) -> HTTPResponse: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[types.TracebackType]) -> Optional[bool]: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[types.TracebackType] + ) -> Optional[bool]: ... def info(self) -> email.message.Message: ... def geturl(self) -> str: ... def getcode(self) -> int: ... @@ -122,7 +134,7 @@ class _HTTPConnectionProtocol(Protocol): ) -> HTTPConnection: ... else: def __call__( - self, host: str, port: Optional[int] = ..., timeout: float = ..., source_address: Optional[Tuple[str, int]] = ..., + self, host: str, port: Optional[int] = ..., timeout: float = ..., source_address: Optional[Tuple[str, int]] = ... ) -> HTTPConnection: ... class HTTPConnection: @@ -133,53 +145,55 @@ class HTTPConnection: if sys.version_info >= (3, 7): def __init__( self, - host: str, port: Optional[int] = ..., + host: str, + port: Optional[int] = ..., timeout: Optional[float] = ..., - source_address: Optional[Tuple[str, int]] = ..., blocksize: int = ... + source_address: Optional[Tuple[str, int]] = ..., + blocksize: int = ..., ) -> None: ... else: def __init__( self, - host: str, port: Optional[int] = ..., + host: str, + port: Optional[int] = ..., timeout: Optional[float] = ..., - source_address: Optional[Tuple[str, int]] = ... + source_address: Optional[Tuple[str, int]] = ..., ) -> None: ... - if sys.version_info >= (3, 6): - def request(self, method: str, url: str, - body: Optional[_DataType] = ..., - headers: Mapping[str, str] = ..., - *, encode_chunked: bool = ...) -> None: ... - else: - def request(self, method: str, url: str, - body: Optional[_DataType] = ..., - headers: Mapping[str, str] = ...) -> None: ... + def request( + self, + method: str, + url: str, + body: Optional[_DataType] = ..., + headers: Mapping[str, str] = ..., + *, + encode_chunked: bool = ..., + ) -> None: ... def getresponse(self) -> HTTPResponse: ... def set_debuglevel(self, level: int) -> None: ... - def set_tunnel(self, host: str, port: Optional[int] = ..., - headers: Optional[Mapping[str, str]] = ...) -> None: ... + def set_tunnel(self, host: str, port: Optional[int] = ..., headers: Optional[Mapping[str, str]] = ...) -> None: ... def connect(self) -> None: ... def close(self) -> None: ... - def putrequest(self, method: str, url: str, skip_host: bool = ..., - skip_accept_encoding: bool = ...) -> None: ... + def putrequest(self, method: str, url: str, skip_host: bool = ..., skip_accept_encoding: bool = ...) -> None: ... def putheader(self, header: str, *argument: str) -> None: ... - if sys.version_info >= (3, 6): - def endheaders(self, message_body: Optional[_DataType] = ..., - *, encode_chunked: bool = ...) -> None: ... - else: - def endheaders(self, message_body: Optional[_DataType] = ...) -> None: ... + def endheaders(self, message_body: Optional[_DataType] = ..., *, encode_chunked: bool = ...) -> None: ... def send(self, data: _DataType) -> None: ... class HTTPSConnection(HTTPConnection): - def __init__(self, - host: str, port: Optional[int] = ..., - key_file: Optional[str] = ..., - cert_file: Optional[str] = ..., - timeout: Optional[float] = ..., - source_address: Optional[Tuple[str, int]] = ..., - *, context: Optional[ssl.SSLContext] = ..., - check_hostname: Optional[bool] = ...) -> None: ... + def __init__( + self, + host: str, + port: Optional[int] = ..., + key_file: Optional[str] = ..., + cert_file: Optional[str] = ..., + timeout: Optional[float] = ..., + source_address: Optional[Tuple[str, int]] = ..., + *, + context: Optional[ssl.SSLContext] = ..., + check_hostname: Optional[bool] = ..., + ) -> None: ... class HTTPException(Exception): ... + error = HTTPException class NotConnected(HTTPException): ... @@ -188,13 +202,10 @@ class UnknownProtocol(HTTPException): ... class UnknownTransferEncoding(HTTPException): ... class UnimplementedFileMode(HTTPException): ... class IncompleteRead(HTTPException): ... - class ImproperConnectionState(HTTPException): ... class CannotSendRequest(ImproperConnectionState): ... class CannotSendHeader(ImproperConnectionState): ... class ResponseNotReady(ImproperConnectionState): ... - class BadStatusLine(HTTPException): ... class LineTooLong(HTTPException): ... - class RemoteDisconnected(ConnectionResetError, BadStatusLine): ... diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 44d7b51345ab..310ccee71bf8 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,28 +1,22 @@ import sys -from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload 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 -if sys.version_info >= (3, 6): - from os import PathLike -_T = TypeVar('_T') +_T = TypeVar("_T") class LoadError(OSError): ... - class CookieJar(Iterable[Cookie]): def __init__(self, policy: Optional[CookiePolicy] = ...) -> None: ... def add_cookie_header(self, request: Request) -> None: ... - def extract_cookies(self, response: HTTPResponse, - request: Request) -> None: ... + def extract_cookies(self, response: HTTPResponse, request: Request) -> None: ... def set_policy(self, policy: CookiePolicy) -> None: ... - def make_cookies(self, response: HTTPResponse, - request: Request) -> Sequence[Cookie]: ... + def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: ... def set_cookie(self, cookie: Cookie) -> None: ... - def set_cookie_if_ok(self, cookie: Cookie, - request: Request) -> None: ... - def clear(self, domain: str = ..., path: str = ..., - name: str = ...) -> None: ... + def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ... + def clear(self, domain: str = ..., path: str = ..., name: str = ...) -> None: ... def clear_session_cookies(self) -> None: ... def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... @@ -31,17 +25,14 @@ class FileCookieJar(CookieJar): filename: str delayload: bool if sys.version_info >= (3, 8): - def __init__(self, filename: Union[str, PathLike[str]] = ..., delayload: bool = ..., - policy: Optional[CookiePolicy] = ...) -> None: ... + def __init__( + self, filename: Union[str, PathLike[str]] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... + ) -> None: ... else: - def __init__(self, filename: str = ..., delayload: bool = ..., - policy: Optional[CookiePolicy] = ...) -> None: ... - def save(self, filename: Optional[str] = ..., ignore_discard: bool = ..., - ignore_expires: bool = ...) -> None: ... - def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., - ignore_expires: bool = ...) -> None: ... - def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., - ignore_expires: bool = ...) -> None: ... + def __init__(self, filename: str = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ...) -> None: ... + def save(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... + def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... + def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... class MozillaCookieJar(FileCookieJar): ... @@ -57,7 +48,6 @@ class CookiePolicy: def domain_return_ok(self, domain: str, request: Request) -> bool: ... def path_return_ok(self, path: str, request: Request) -> bool: ... - class DefaultCookiePolicy(CookiePolicy): rfc2109_as_netscape: bool strict_domain: bool @@ -71,17 +61,21 @@ class DefaultCookiePolicy(CookiePolicy): DomainRFC2965Match: int DomainLiberal: int DomainStrict: int - def __init__(self, blocked_domains: Optional[Sequence[str]] = ..., - allowed_domains: Optional[Sequence[str]] = ..., - netscape: bool = ..., - rfc2965: bool = ..., - rfc2109_as_netscape: Optional[bool] = ..., - hide_cookie2: bool = ..., strict_domain: bool = ..., - strict_rfc2965_unverifiable: bool = ..., - strict_ns_unverifiable: bool = ..., - strict_ns_domain: int = ..., - strict_ns_set_initial_dollar: bool = ..., - strict_ns_set_path: bool = ...) -> None: ... + def __init__( + self, + blocked_domains: Optional[Sequence[str]] = ..., + allowed_domains: Optional[Sequence[str]] = ..., + netscape: bool = ..., + rfc2965: bool = ..., + rfc2109_as_netscape: Optional[bool] = ..., + hide_cookie2: bool = ..., + strict_domain: bool = ..., + strict_rfc2965_unverifiable: bool = ..., + strict_ns_unverifiable: bool = ..., + strict_ns_domain: int = ..., + strict_ns_set_initial_dollar: bool = ..., + strict_ns_set_path: bool = ..., + ) -> None: ... def blocked_domains(self) -> Tuple[str, ...]: ... def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... def is_blocked(self, domain: str) -> bool: ... @@ -89,13 +83,13 @@ class DefaultCookiePolicy(CookiePolicy): def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) -> None: ... def is_not_allowed(self, domain: str) -> bool: ... - class Cookie: version: Optional[int] name: str value: Optional[str] port: Optional[str] path: str + path_specified: bool secure: bool expires: Optional[int] discard: bool @@ -106,18 +100,30 @@ class Cookie: domain: str # undocumented domain_specified: bool domain_initial_dot: bool - def __init__(self, version: Optional[int], name: str, value: Optional[str], # undocumented - port: Optional[str], port_specified: bool, - domain: str, domain_specified: bool, domain_initial_dot: bool, - path: str, path_specified: bool, - secure: bool, expires: Optional[int], discard: bool, - comment: Optional[str], comment_url: Optional[str], - rest: Dict[str, str], - rfc2109: bool = ...) -> None: ... + def __init__( + self, + version: Optional[int], + name: str, + value: Optional[str], # undocumented + port: Optional[str], + port_specified: bool, + domain: str, + domain_specified: bool, + domain_initial_dot: bool, + path: str, + path_specified: bool, + secure: bool, + expires: Optional[int], + discard: bool, + comment: Optional[str], + comment_url: Optional[str], + rest: Dict[str, str], + rfc2109: bool = ..., + ) -> None: ... def has_nonstandard_attr(self, name: str) -> bool: ... @overload def get_nonstandard_attr(self, name: str) -> Optional[str]: ... @overload - def get_nonstandard_attr(self, name: str, default: _T = ...) -> Union[str, _T]: ... + def get_nonstandard_attr(self, name: str, default: _T) -> Union[str, _T]: ... def set_nonstandard_attr(self, name: str, value: str) -> None: ... def is_expired(self, now: int = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index b2fb13907caf..14b0f817e8b7 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,10 +1,16 @@ -# Stubs for http.cookies (Python 3.5) - import sys -from typing import Generic, Dict, List, Mapping, Optional, TypeVar, Union, Any +from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union, overload _DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] -_T = TypeVar('_T') +_T = TypeVar("_T") +@overload +def _quote(str: None) -> None: ... +@overload +def _quote(str: str) -> str: ... +@overload +def _unquote(str: None) -> None: ... +@overload +def _unquote(str: str) -> str: ... class CookieError(Exception): ... @@ -17,8 +23,7 @@ class Morsel(Dict[str, Any], Generic[_T]): else: def set(self, key: str, val: str, coded_val: _T, LegalChars: str = ...) -> None: ... def isReservedKey(self, K: str) -> bool: ... - def output(self, attrs: Optional[List[str]] = ..., - header: str = ...) -> str: ... + def output(self, attrs: Optional[List[str]] = ..., header: str = ...) -> str: ... def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... def OutputString(self, attrs: Optional[List[str]] = ...) -> str: ... @@ -26,8 +31,7 @@ class BaseCookie(Dict[str, Morsel[_T]], Generic[_T]): def __init__(self, input: Optional[_DataType] = ...) -> None: ... def value_decode(self, val: str) -> _T: ... def value_encode(self, val: _T) -> str: ... - def output(self, attrs: Optional[List[str]] = ..., header: str = ..., - sep: str = ...) -> str: ... + def output(self, attrs: Optional[List[str]] = ..., header: str = ..., sep: str = ...) -> str: ... def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... def load(self, rawdata: _DataType) -> None: ... def __setitem__(self, key: str, value: Union[str, Morsel[_T]]) -> None: ... diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index fe9fc238409b..995a089add96 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -1,9 +1,7 @@ -# Stubs for http.server (Python 3.4) - -import sys -from typing import Any, BinaryIO, Callable, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union -import socketserver import email.message +import socketserver +import sys +from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union if sys.version_info >= (3, 7): from builtins import _PathLike @@ -11,8 +9,7 @@ if sys.version_info >= (3, 7): class HTTPServer(socketserver.TCPServer): server_name: str server_port: int - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): @@ -36,22 +33,17 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): responses: Mapping[int, Tuple[str, str]] weekdayname: ClassVar[Sequence[str]] = ... # Undocumented monthname: ClassVar[Sequence[Optional[str]]] = ... # Undocumented - def __init__(self, request: bytes, client_address: Tuple[str, int], - server: socketserver.BaseServer) -> None: ... + def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... def handle(self) -> None: ... def handle_one_request(self) -> None: ... def handle_expect_100(self) -> bool: ... - def send_error(self, code: int, message: Optional[str] = ..., - explain: Optional[str] = ...) -> None: ... - def send_response(self, code: int, - message: Optional[str] = ...) -> None: ... + def send_error(self, code: int, message: Optional[str] = ..., explain: Optional[str] = ...) -> None: ... + def send_response(self, code: int, message: Optional[str] = ...) -> None: ... def send_header(self, keyword: str, value: str) -> None: ... - def send_response_only(self, code: int, - message: Optional[str] = ...) -> None: ... + def send_response_only(self, code: int, message: Optional[str] = ...) -> None: ... def end_headers(self) -> None: ... def flush_headers(self) -> None: ... - def log_request(self, code: Union[int, str] = ..., - size: Union[int, str] = ...) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... def log_error(self, format: str, *args: Any) -> None: ... def log_message(self, format: str, *args: Any) -> None: ... def version_string(self) -> str: ... @@ -63,11 +55,15 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): extensions_map: Dict[str, str] if sys.version_info >= (3, 7): - def __init__(self, request: bytes, client_address: Tuple[str, int], - server: socketserver.BaseServer, directory: Optional[Union[str, _PathLike[str]]]) -> None: ... + def __init__( + self, + request: bytes, + client_address: Tuple[str, int], + server: socketserver.BaseServer, + directory: Optional[Union[str, _PathLike[str]]] = ..., + ) -> None: ... else: - def __init__(self, request: bytes, client_address: Tuple[str, int], - server: socketserver.BaseServer) -> None: ... + def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... def do_GET(self) -> None: ... def do_HEAD(self) -> None: ... diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index a5962a8365a6..bb9e9c6db132 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -2,8 +2,9 @@ import subprocess import sys import time from socket import socket as _socket -from ssl import SSLSocket, SSLContext -from typing import Any, Callable, Dict, IO, List, Optional, Pattern, Text, Tuple, Type, Union +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_extensions import Literal # TODO: Commands should use their actual return types, not this type alias. @@ -30,13 +31,17 @@ class IMAP4: welcome: bytes = ... capabilities: Tuple[str] = ... PROTOCOL_VERSION: str = ... - def __init__(self, host: str = ..., port: int = ...) -> None: ... + if sys.version_info >= (3, 9): + def __init__(self, host: str = ..., port: int = ..., timeout: Optional[float] = ...) -> None: ... + def open(self, host: str = ..., port: int = ..., timeout: Optional[float] = ...) -> None: ... + else: + 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 open(self, host: str = ..., port: int = ...) -> None: ... def read(self, size: int) -> bytes: ... def readline(self) -> bytes: ... def send(self, data: bytes) -> None: ... @@ -56,7 +61,7 @@ class IMAP4: if sys.version_info >= (3, 5): def enable(self, capability: str) -> _CommandResults: ... def __enter__(self) -> IMAP4: ... - def __exit__(self, *args) -> None: ... + 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: ... @@ -88,22 +93,46 @@ class IMAP4: 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: ... + if sys.version_info >= (3, 9): + def unselect(self) -> _CommandResults: ... def xatom(self, name: str, *args: str) -> _CommandResults: ... def print_log(self) -> None: ... class IMAP4_SSL(IMAP4): keyfile: str = ... certfile: str = ... - if sys.version_info >= (3, 3): - def __init__(self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ..., ssl_context: Optional[SSLContext] = ...) -> None: ... + if sys.version_info >= (3, 9): + def __init__( + self, + host: str = ..., + port: int = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + ssl_context: Optional[SSLContext] = ..., + timeout: Optional[float] = ..., + ) -> None: ... + elif sys.version_info >= (3, 3): + def __init__( + self, + host: str = ..., + port: int = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + ssl_context: Optional[SSLContext] = ..., + ) -> None: ... else: - def __init__(self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ...) -> None: ... + 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: ... + if sys.version_info >= (3, 9): + def open(self, host: str = ..., port: Optional[int] = ..., timeout: Optional[float] = ...) -> None: ... + else: + 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: ... @@ -111,7 +140,6 @@ class IMAP4_SSL(IMAP4): def socket(self) -> _socket: ... def ssl(self) -> SSLSocket: ... - class IMAP4_stream(IMAP4): command: str = ... def __init__(self, command: str) -> None: ... @@ -122,7 +150,10 @@ class IMAP4_stream(IMAP4): process: subprocess.Popen[bytes] = ... writefile: IO[Any] = ... readfile: IO[Any] = ... - def open(self, host: str = ..., port: Optional[int] = ...) -> None: ... + if sys.version_info >= (3, 9): + def open(self, host: Optional[str] = ..., port: Optional[int] = ..., timeout: Optional[float] = ...) -> None: ... + else: + 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: ... diff --git a/mypy/typeshed/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi index 2906298297e3..ffdbbf20e97b 100644 --- a/mypy/typeshed/stdlib/imghdr.pyi +++ b/mypy/typeshed/stdlib/imghdr.pyi @@ -7,15 +7,14 @@ class _ReadableBinary(Protocol): 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]: ... @overload def what(file: Any, h: bytes) -> Optional[str]: ... + tests: List[Callable[[bytes, Optional[BinaryIO]], Optional[str]]] diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index ded2a160b725..adcf6e097b84 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -1,16 +1,21 @@ import os -import sys -from _typeshed import StrPath import types -from typing import Any, IO, List, Optional, Tuple, TypeVar, Union - -from _imp import (lock_held as lock_held, acquire_lock as acquire_lock, release_lock as release_lock, - get_frozen_object as get_frozen_object, is_frozen_package as is_frozen_package, - init_frozen as init_frozen, is_builtin as is_builtin, is_frozen as is_frozen) +from _typeshed import StrPath +from typing import IO, Any, List, Optional, Protocol, Tuple, TypeVar, Union -from _imp import create_dynamic as create_dynamic +from _imp import ( + acquire_lock as acquire_lock, + create_dynamic as create_dynamic, + get_frozen_object as get_frozen_object, + init_frozen as init_frozen, + is_builtin as is_builtin, + is_frozen as is_frozen, + is_frozen_package as is_frozen_package, + lock_held as lock_held, + release_lock as release_lock, +) -_T = TypeVar('_T') +_T = TypeVar("_T") SEARCH_ERROR: int PY_SOURCE: int @@ -34,15 +39,26 @@ class NullImporter: def __init__(self, path: StrPath) -> None: ... def find_module(self, fullname: Any) -> None: ... +# Technically, a text file has to support a slightly different set of operations than a binary file, +# but we ignore that here. +class _FileLike(Protocol): + closed: bool + mode: str + def read(self) -> Union[str, bytes]: ... + def close(self) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: Any) -> Any: ... + # PathLike doesn't work for the pathname argument here -def load_source(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... -def load_compiled(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_source(name: str, pathname: str, file: Optional[_FileLike] = ...) -> types.ModuleType: ... +def load_compiled(name: str, pathname: str, file: Optional[_FileLike] = ...) -> types.ModuleType: ... def load_package(name: str, path: StrPath) -> types.ModuleType: ... -def load_module(name: str, file: IO[Any], filename: str, details: Tuple[str, str, int]) -> types.ModuleType: ... -if sys.version_info >= (3, 6): - def find_module(name: str, path: Union[None, List[str], List[os.PathLike[str]], List[StrPath]] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... -else: - def find_module(name: str, path: Optional[List[str]] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... +def load_module(name: str, file: Optional[_FileLike], filename: str, details: Tuple[str, str, int]) -> types.ModuleType: ... + +# 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]] = ... +) -> Tuple[IO[Any], str, Tuple[str, str, int]]: ... def reload(module: types.ModuleType) -> types.ModuleType: ... def init_builtin(name: str) -> Optional[types.ModuleType]: ... -def load_dynamic(name: str, path: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_dynamic(name: str, path: str, file: Any = ...) -> types.ModuleType: ... # file argument is ignored diff --git a/mypy/typeshed/stdlib/importlib/__init__.pyi b/mypy/typeshed/stdlib/importlib/__init__.pyi index e44f424164af..d55393df315e 100644 --- a/mypy/typeshed/stdlib/importlib/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/__init__.pyi @@ -1,16 +1,15 @@ -from importlib.abc import Loader import types +from importlib.abc import Loader from typing import Any, Mapping, Optional, Sequence -def __import__(name: str, globals: Optional[Mapping[str, Any]] = ..., - locals: Optional[Mapping[str, Any]] = ..., - fromlist: Sequence[str] = ..., - level: int = ...) -> types.ModuleType: ... - +def __import__( + name: str, + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ..., +) -> types.ModuleType: ... def import_module(name: str, package: Optional[str] = ...) -> types.ModuleType: ... - def find_loader(name: str, path: Optional[str] = ...) -> Optional[Loader]: ... - def invalidate_caches() -> None: ... - def reload(module: types.ModuleType) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 709ba44f723b..0949d317cd86 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -1,25 +1,17 @@ -from abc import ABCMeta, abstractmethod import os import sys import types -from typing import Any, IO, Iterator, Mapping, Optional, Sequence, Tuple, Union +from abc import ABCMeta, abstractmethod +from typing import IO, Any, Iterator, Mapping, Optional, Sequence, Tuple, Union +from typing_extensions import Literal # Loader is exported from this module, but for circular import reasons # exists in its own stub file (with ModuleSpec and ModuleType). -from _importlib_modulespec import Loader as Loader # Exported - -from _importlib_modulespec import ModuleSpec +from _importlib_modulespec import Loader as Loader, ModuleSpec # Exported _Path = Union[bytes, str] -class Finder(metaclass=ABCMeta): - ... - # Technically this class defines the following method, but its subclasses - # in this module violate its signature. Since this class is deprecated, it's - # easier to simply ignore that this method exists. - # @abstractmethod - # def find_module(self, fullname: str, - # path: Optional[Sequence[_Path]] = ...) -> Optional[Loader]: ... +class Finder(metaclass=ABCMeta): ... class ResourceLoader(Loader): @abstractmethod @@ -46,30 +38,20 @@ class SourceLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): def get_source(self, fullname: str) -> Optional[str]: ... def path_stats(self, path: _Path) -> Mapping[str, Any]: ... - class MetaPathFinder(Finder): - def find_module(self, fullname: str, - path: Optional[Sequence[_Path]]) -> Optional[Loader]: - ... + def find_module(self, fullname: str, path: Optional[Sequence[_Path]]) -> Optional[Loader]: ... def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. def find_spec( - self, fullname: str, path: Optional[Sequence[_Path]], - target: Optional[types.ModuleType] = ... - ) -> Optional[ModuleSpec]: - ... + self, fullname: str, path: Optional[Sequence[_Path]], target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... class PathEntryFinder(Finder): def find_module(self, fullname: str) -> Optional[Loader]: ... - def find_loader( - self, fullname: str - ) -> Tuple[Optional[Loader], Sequence[_Path]]: ... + def find_loader(self, fullname: str) -> Tuple[Optional[Loader], Sequence[_Path]]: ... def invalidate_caches(self) -> None: ... # Not defined on the actual class, but expected to exist. - def find_spec( - self, fullname: str, - target: Optional[types.ModuleType] = ... - ) -> Optional[ModuleSpec]: ... + def find_spec(self, fullname: str, target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: ... class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): name: str @@ -80,7 +62,6 @@ class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): if sys.version_info >= (3, 7): _PathLike = Union[bytes, str, os.PathLike[Any]] - class ResourceReader(metaclass=ABCMeta): @abstractmethod def open_resource(self, resource: _PathLike) -> IO[bytes]: ... @@ -90,3 +71,27 @@ if sys.version_info >= (3, 7): def is_resource(self, name: str) -> bool: ... @abstractmethod def contents(self) -> Iterator[str]: ... + +if sys.version_info >= (3, 9): + from typing import Protocol, runtime_checkable + @runtime_checkable + class Traversable(Protocol): + @abstractmethod + def iterdir(self) -> Iterator[Traversable]: ... + @abstractmethod + def read_bytes(self) -> bytes: ... + @abstractmethod + def read_text(self, encoding: Optional[str] = ...) -> str: ... + @abstractmethod + def is_dir(self) -> bool: ... + @abstractmethod + def is_file(self) -> bool: ... + @abstractmethod + def joinpath(self, child: Traversable) -> Traversable: ... + @abstractmethod + def __truediv__(self, child: Traversable) -> Traversable: ... + @abstractmethod + def open(self, mode: Literal["r", "rb"] = ..., *args: Any, **kwargs: Any) -> IO[Any]: ... + @property + @abstractmethod + def name(self) -> str: ... diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index 07521adb2bd3..9d0333a2b669 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -1,25 +1,19 @@ import importlib.abc import types -from typing import Any, Callable, List, Optional, Sequence, Tuple, Union +from typing import Callable, List, Optional, Sequence, Tuple, Union # ModuleSpec is exported from this module, but for circular import # reasons exists in its own stub file (with Loader and ModuleType). -from _importlib_modulespec import ModuleSpec as ModuleSpec, Loader # Exported +from _importlib_modulespec import Loader, ModuleSpec as ModuleSpec # Exported -class BuiltinImporter(importlib.abc.MetaPathFinder, - importlib.abc.InspectLoader): +class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @classmethod - def find_module( - cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]] - ) -> Optional[importlib.abc.Loader]: - ... + def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... @classmethod - def find_spec(cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]], - target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: - ... + def find_spec( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... # InspectLoader @classmethod def is_package(cls, fullname: str) -> bool: ... @@ -40,16 +34,11 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @classmethod - def find_module( - cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]] - ) -> Optional[importlib.abc.Loader]: - ... + def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... @classmethod - def find_spec(cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]], - target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: - ... + def find_spec( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... # InspectLoader @classmethod def is_package(cls, fullname: str) -> bool: ... @@ -63,35 +52,27 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): @staticmethod def module_repr(module: types.ModuleType) -> str: ... @classmethod - def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: - ... + def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: ... @staticmethod def exec_module(module: types.ModuleType) -> None: ... class WindowsRegistryFinder(importlib.abc.MetaPathFinder): @classmethod - def find_module( - cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]] - ) -> Optional[importlib.abc.Loader]: - ... + def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... @classmethod - def find_spec(cls, fullname: str, - path: Optional[Sequence[importlib.abc._Path]], - target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: - ... + def find_spec( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... class PathFinder: @classmethod def invalidate_caches(cls) -> None: ... @classmethod - def find_spec(cls, fullname: str, - path: Optional[Sequence[Union[bytes, str]]] = ..., - target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: ... + def find_spec( + cls, fullname: str, path: Optional[Sequence[Union[bytes, str]]] = ..., target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... @classmethod - def find_module(cls, fullname: str, - path: Optional[Sequence[Union[bytes, str]]] = ...) -> Optional[Loader]: ... - + def find_module(cls, fullname: str, path: Optional[Sequence[Union[bytes, str]]] = ...) -> Optional[Loader]: ... SOURCE_SUFFIXES: List[str] DEBUG_BYTECODE_SUFFIXES: List[str] @@ -103,22 +84,14 @@ def all_suffixes() -> List[str]: ... class FileFinder(importlib.abc.PathEntryFinder): path: str - def __init__( - self, path: str, - *loader_details: Tuple[importlib.abc.Loader, List[str]] - ) -> None: ... + def __init__(self, path: str, *loader_details: Tuple[importlib.abc.Loader, List[str]]) -> None: ... @classmethod def path_hook( cls, *loader_details: Tuple[importlib.abc.Loader, List[str]] ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... -class SourceFileLoader(importlib.abc.FileLoader, - importlib.abc.SourceLoader): - ... - -class SourcelessFileLoader(importlib.abc.FileLoader, - importlib.abc.SourceLoader): - ... +class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... +class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... class ExtensionFileLoader(importlib.abc.ExecutionLoader): def get_filename(self, fullname: str) -> importlib.abc._Path: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata.pyi index 995118597c04..bc50c38d30f2 100644 --- a/mypy/typeshed/stdlib/importlib/metadata.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata.pyi @@ -65,7 +65,7 @@ if sys.version_info >= (3, 8): @property def pattern(self) -> str: ... @abc.abstractmethod - def find_distributions(self, context: Context = ...) -> Iterable[Distribution]: ... + def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... class MetadataPathFinder(DistributionFinder): @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index 007477d51b26..65beccba8cfd 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -1,25 +1,22 @@ import sys + # This is a >=3.7 module, so we conditionally include its source. if sys.version_info >= (3, 7): import os - from pathlib import Path from types import ModuleType - from typing import ContextManager, Iterator, Union, BinaryIO, TextIO + from typing import BinaryIO, ContextManager, Iterator, TextIO, Union Package = Union[str, ModuleType] Resource = Union[str, os.PathLike] - def open_binary(package: Package, resource: Resource) -> BinaryIO: ... - def open_text(package: Package, - resource: Resource, - encoding: str = ..., - errors: str = ...) -> TextIO: ... + def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... def read_binary(package: Package, resource: Resource) -> bytes: ... - def read_text(package: Package, - resource: Resource, - encoding: str = ..., - errors: str = ...) -> str: ... + def read_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> str: ... def path(package: Package, resource: Resource) -> ContextManager[Path]: ... def is_resource(package: Package, name: str) -> bool: ... def contents(package: Package) -> Iterator[str]: ... + +if sys.version_info >= (3, 9): + from importlib.abc import Traversable + def files(package: Package) -> Traversable: ... diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index 878d0652ee81..e586f99b9875 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -1,48 +1,35 @@ import importlib.abc import importlib.machinery -import sys +import os import types from typing import Any, Callable, List, Optional, Union -def module_for_loader( - fxn: Callable[..., types.ModuleType] -) -> Callable[..., types.ModuleType]: ... -def set_loader( - fxn: Callable[..., types.ModuleType] -) -> Callable[..., types.ModuleType]: ... -def set_package( - fxn: Callable[..., types.ModuleType] -) -> Callable[..., types.ModuleType]: ... - +def module_for_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... +def set_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... +def set_package(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... def resolve_name(name: str, package: str) -> str: ... MAGIC_NUMBER: bytes -def cache_from_source(path: str, debug_override: Optional[bool] = ..., *, - optimization: Optional[Any] = ...) -> str: ... +def cache_from_source(path: str, debug_override: Optional[bool] = ..., *, optimization: Optional[Any] = ...) -> str: ... def source_from_cache(path: str) -> str: ... def decode_source(source_bytes: bytes) -> str: ... -def find_spec( - name: str, package: Optional[str] = ... -) -> Optional[importlib.machinery.ModuleSpec]: ... +def find_spec(name: str, package: Optional[str] = ...) -> Optional[importlib.machinery.ModuleSpec]: ... def spec_from_loader( - name: str, loader: Optional[importlib.abc.Loader], *, - origin: Optional[str] = ..., loader_state: Optional[Any] = ..., - is_package: Optional[bool] = ... + name: str, + loader: Optional[importlib.abc.Loader], + *, + origin: Optional[str] = ..., + loader_state: Optional[Any] = ..., + is_package: Optional[bool] = ..., ) -> importlib.machinery.ModuleSpec: ... - -if sys.version_info >= (3, 6): - import os - _Path = Union[str, bytes, os.PathLike] -else: - _Path = str - def spec_from_file_location( - name: str, location: _Path, *, + name: str, + location: Union[str, bytes, os.PathLike[str], os.PathLike[bytes]], + *, loader: Optional[importlib.abc.Loader] = ..., - submodule_search_locations: Optional[List[str]] = ... + submodule_search_locations: Optional[List[str]] = ..., ) -> importlib.machinery.ModuleSpec: ... - def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... class LazyLoader(importlib.abc.Loader): diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 9696067ccacb..d0627d54981b 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -1,12 +1,24 @@ -import sys import enum -from typing import (AbstractSet, Any, Callable, Dict, Generator, List, Mapping, - NamedTuple, Optional, Sequence, Tuple, Type, Union, - ) -from types import (CodeType, FrameType, FunctionType, MethodType, ModuleType, - TracebackType, - ) +import sys from collections import OrderedDict +from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType +from typing import ( + AbstractSet, + Any, + Callable, + ClassVar, + Dict, + Generator, + List, + Mapping, + NamedTuple, + Optional, + Sequence, + Tuple, + Type, + Union, +) +from typing_extensions import Literal # # Types and members @@ -21,8 +33,7 @@ class BlockFinder: indecorator: bool decoratorhasargs: bool last: int - def tokeneater(self, type: int, token: str, srowcol: Tuple[int, int], - erowcol: Tuple[int, int], line: str) -> None: ... + def tokeneater(self, type: int, token: str, srowcol: Tuple[int, int], erowcol: Tuple[int, int], line: str) -> None: ... CO_OPTIMIZED: int CO_NEWLOCALS: int @@ -33,36 +44,35 @@ CO_GENERATOR: int CO_NOFREE: int CO_COROUTINE: int CO_ITERABLE_COROUTINE: int -if sys.version_info >= (3, 6): - CO_ASYNC_GENERATOR: int +CO_ASYNC_GENERATOR: int TPFLAGS_IS_ABSTRACT: int -if sys.version_info < (3, 6): - class ModuleInfo(NamedTuple): - name: str - suffix: str - mode: str - module_type: int - def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ... - -def getmembers(object: object, - predicate: Optional[Callable[[Any], bool]] = ..., - ) -> List[Tuple[str, Any]]: ... +def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> List[Tuple[str, Any]]: ... def getmodulename(path: str) -> Optional[str]: ... - def ismodule(object: object) -> bool: ... def isclass(object: object) -> bool: ... def ismethod(object: object) -> bool: ... def isfunction(object: object) -> bool: ... -def isgeneratorfunction(object: object) -> bool: ... -def isgenerator(object: object) -> bool: ... -def iscoroutinefunction(object: object) -> bool: ... +if sys.version_info >= (3, 8): + def isgeneratorfunction(obj: object) -> bool: ... + def iscoroutinefunction(obj: object) -> bool: ... + +else: + def isgeneratorfunction(object: object) -> bool: ... + def iscoroutinefunction(object: object) -> bool: ... + +def isgenerator(object: object) -> bool: ... def iscoroutine(object: object) -> bool: ... def isawaitable(object: object) -> bool: ... -if sys.version_info >= (3, 6): + +if sys.version_info >= (3, 8): + def isasyncgenfunction(obj: object) -> bool: ... + +else: def isasyncgenfunction(object: object) -> bool: ... - def isasyncgen(object: object) -> bool: ... + +def isasyncgen(object: object) -> bool: ... def istraceback(object: object) -> bool: ... def isframe(object: object) -> bool: ... def iscode(object: object) -> bool: ... @@ -74,38 +84,31 @@ def isdatadescriptor(object: object) -> bool: ... def isgetsetdescriptor(object: object) -> bool: ... def ismemberdescriptor(object: object) -> bool: ... - # # Retrieving source code # _SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... -def getabsfile(object: _SourceObjectType) -> str: ... +def getabsfile(object: _SourceObjectType, _filename: Optional[str] = ...) -> str: ... def getblock(lines: Sequence[str]) -> Sequence[str]: ... def getdoc(object: object) -> Optional[str]: ... def getcomments(object: object) -> Optional[str]: ... def getfile(object: _SourceObjectType) -> str: ... -def getmodule(object: object) -> Optional[ModuleType]: ... +def getmodule(object: object, _filename: Optional[str] = ...) -> Optional[ModuleType]: ... def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: str) -> str: ... def indentsize(line: str) -> int: ... - # # Introspecting callables with the Signature object # -def signature(obj: Callable[..., Any], - *, - follow_wrapped: bool = ...) -> Signature: ... +def signature(obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... class Signature: - def __init__(self, - parameters: Optional[Sequence[Parameter]] = ..., - *, - return_annotation: Any = ...) -> None: ... + def __init__(self, parameters: Optional[Sequence[Parameter]] = ..., *, return_annotation: Any = ...) -> None: ... # TODO: can we be more specific here? empty: object = ... @@ -113,57 +116,48 @@ class Signature: # TODO: can we be more specific here? return_annotation: Any - def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... - def replace(self, - *, - parameters: Optional[Sequence[Parameter]] = ..., - return_annotation: Any = ...) -> Signature: ... - + def replace(self, *, parameters: Optional[Sequence[Parameter]] = ..., return_annotation: Any = ...) -> Signature: ... @classmethod def from_callable(cls, obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): + POSITIONAL_ONLY: int + POSITIONAL_OR_KEYWORD: int + VAR_POSITIONAL: int + KEYWORD_ONLY: int + VAR_KEYWORD: int + if sys.version_info >= (3, 8): description: str class Parameter: - def __init__(self, - name: str, - kind: _ParameterKind, - *, - default: Any = ..., - annotation: Any = ...) -> None: ... + def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ... empty: Any = ... name: str default: Any annotation: Any kind: _ParameterKind - POSITIONAL_ONLY: _ParameterKind = ... - POSITIONAL_OR_KEYWORD: _ParameterKind = ... - VAR_POSITIONAL: _ParameterKind = ... - KEYWORD_ONLY: _ParameterKind = ... - VAR_KEYWORD: _ParameterKind = ... - - def replace(self, - *, - name: Optional[str] = ..., - kind: Optional[_ParameterKind] = ..., - default: Any = ..., - annotation: Any = ...) -> Parameter: ... + POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]] + POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] + VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]] + KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] + VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] + def replace( + self, *, name: Optional[str] = ..., kind: Optional[_ParameterKind] = ..., default: Any = ..., annotation: Any = ... + ) -> Parameter: ... class BoundArguments: arguments: OrderedDict[str, Any] args: Tuple[Any, ...] kwargs: Dict[str, Any] signature: Signature - + def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... def apply_defaults(self) -> None: ... - # # Classes and functions # @@ -207,46 +201,42 @@ class ArgInfo(NamedTuple): def getargvalues(frame: FrameType) -> ArgInfo: ... def formatannotation(annotation: object, base_module: Optional[str] = ...) -> str: ... def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... -def formatargspec(args: List[str], - varargs: Optional[str] = ..., - varkw: Optional[str] = ..., - defaults: Optional[Tuple[Any, ...]] = ..., - kwonlyargs: Optional[Sequence[str]] = ..., - kwonlydefaults: Optional[Dict[str, Any]] = ..., - annotations: Dict[str, Any] = ..., - formatarg: Callable[[str], str] = ..., - formatvarargs: Callable[[str], str] = ..., - formatvarkw: Callable[[str], str] = ..., - formatvalue: Callable[[Any], str] = ..., - formatreturns: Callable[[Any], str] = ..., - formatannotation: Callable[[Any], str] = ..., - ) -> str: ... -def formatargvalues(args: List[str], - varargs: Optional[str], - varkw: Optional[str], - locals: Optional[Dict[str, Any]], - formatarg: Optional[Callable[[str], str]] = ..., - formatvarargs: Optional[Callable[[str], str]] = ..., - formatvarkw: Optional[Callable[[str], str]] = ..., - formatvalue: Optional[Callable[[Any], str]] = ..., - ) -> str: ... +def formatargspec( + args: List[str], + varargs: Optional[str] = ..., + varkw: Optional[str] = ..., + defaults: Optional[Tuple[Any, ...]] = ..., + kwonlyargs: Optional[Sequence[str]] = ..., + kwonlydefaults: Optional[Dict[str, Any]] = ..., + annotations: Dict[str, Any] = ..., + formatarg: Callable[[str], str] = ..., + formatvarargs: Callable[[str], str] = ..., + formatvarkw: Callable[[str], str] = ..., + formatvalue: Callable[[Any], str] = ..., + formatreturns: Callable[[Any], str] = ..., + formatannotation: Callable[[Any], str] = ..., +) -> str: ... +def formatargvalues( + args: List[str], + varargs: Optional[str], + varkw: Optional[str], + locals: Optional[Dict[str, Any]], + formatarg: Optional[Callable[[str], str]] = ..., + formatvarargs: Optional[Callable[[str], str]] = ..., + formatvarkw: Optional[Callable[[str], str]] = ..., + formatvalue: Optional[Callable[[Any], str]] = ..., +) -> str: ... def getmro(cls: type) -> Tuple[type, ...]: ... - -def getcallargs(__func: Callable[..., Any], - *args: Any, - **kwds: Any) -> Dict[str, Any]: ... +def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> Dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] globals: Mapping[str, Any] builtins: Mapping[str, Any] unbound: AbstractSet[str] -def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... - -def unwrap(func: Callable[..., Any], - *, - stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... +def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... +def unwrap(func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... # # The interpreter stack @@ -281,7 +271,6 @@ def trace(context: int = ...) -> List[FrameInfo]: ... def getattr_static(obj: object, attr: str, default: Optional[Any] = ...) -> Any: ... - # # Current State of Generators and Coroutines # @@ -293,6 +282,7 @@ GEN_CREATED: str GEN_RUNNING: str GEN_SUSPENDED: str GEN_CLOSED: str + def getgeneratorstate(generator: Generator[Any, Any, Any]) -> str: ... CORO_CREATED: str @@ -301,16 +291,19 @@ CORO_SUSPENDED: str CORO_CLOSED: str # TODO can we be more specific than "object"? def getcoroutinestate(coroutine: object) -> str: ... - def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> Dict[str, Any]: ... # TODO can we be more specific than "object"? def getcoroutinelocals(coroutine: object) -> Dict[str, Any]: ... +# Create private type alias to avoid conflict with symbol of same +# name created in Attribute class. +_Object = object + class Attribute(NamedTuple): name: str kind: str defining_class: type - object: object + object: _Object def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index e1e732c9e677..f03a9a8740fe 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -1,12 +1,9 @@ -from typing import ( - List, BinaryIO, TextIO, Iterator, Union, Optional, Callable, Tuple, Type, Any, IO, Iterable, TypeVar -) import builtins import codecs import sys -from mmap import mmap -from types import TracebackType from _typeshed import ReadableBuffer, WriteableBuffer +from types import TracebackType +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, TypeVar, Union DEFAULT_BUFFER_SIZE: int @@ -14,7 +11,7 @@ SEEK_SET: int SEEK_CUR: int SEEK_END: int -_T = TypeVar('_T', bound=IOBase) +_T = TypeVar("_T", bound=IOBase) open = builtins.open @@ -22,25 +19,29 @@ if sys.version_info >= (3, 8): def open_code(path: str) -> IO[bytes]: ... BlockingIOError = builtins.BlockingIOError + class UnsupportedOperation(OSError, ValueError): ... class IOBase: def __iter__(self) -> Iterator[bytes]: ... def __next__(self) -> bytes: ... def __enter__(self: _T) -> _T: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... def close(self) -> None: ... def fileno(self) -> int: ... def flush(self) -> None: ... def isatty(self) -> bool: ... def readable(self) -> bool: ... + read: Callable[..., Any] def readlines(self, __hint: int = ...) -> List[bytes]: ... 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: ... + write: Callable[..., Any] def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ... def readline(self, __size: Optional[int] = ...) -> bytes: ... def __del__(self) -> None: ... @@ -72,8 +73,10 @@ class FileIO(RawIOBase, BinaryIO): file: Union[str, bytes, int], mode: str = ..., closefd: bool = ..., - opener: Optional[Callable[[Union[int, str], str], int]] = ... + opener: Optional[Callable[[Union[int, str], str], int]] = ..., ) -> None: ... + @property + def closefd(self) -> bool: ... def write(self, __b: ReadableBuffer) -> int: ... def read(self, __size: int = ...) -> bytes: ... def __enter__(self: _T) -> _T: ... @@ -116,9 +119,8 @@ class BufferedRandom(BufferedReader, BufferedWriter): def read1(self, __size: int) -> bytes: ... # type: ignore class BufferedRWPair(BufferedIOBase): - def __init__(self, reader: RawIOBase, writer: RawIOBase, - buffer_size: int = ...) -> None: ... - + def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = ...) -> None: ... + def peek(self, __size: int = ...) -> bytes: ... class TextIOBase(IOBase): encoding: str @@ -128,14 +130,13 @@ class TextIOBase(IOBase): def __next__(self) -> str: ... # type: ignore def detach(self) -> BinaryIO: ... def write(self, __s: str) -> int: ... - def writelines(self, __lines: List[str]) -> None: ... # type: ignore + def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore def readline(self, __size: int = ...) -> str: ... # type: ignore def readlines(self, __hint: int = ...) -> List[str]: ... # type: ignore def read(self, __size: Optional[int] = ...) -> str: ... def tell(self) -> int: ... class TextIOWrapper(TextIOBase, TextIO): - line_buffering: bool def __init__( self, buffer: IO[bytes], @@ -143,11 +144,17 @@ class TextIOWrapper(TextIOBase, TextIO): errors: Optional[str] = ..., newline: Optional[str] = ..., line_buffering: bool = ..., - write_through: bool = ... + write_through: bool = ..., ) -> None: ... @property def buffer(self) -> BinaryIO: ... + @property + def closed(self) -> bool: ... + @property + def line_buffering(self) -> bool: ... if sys.version_info >= (3, 7): + @property + def write_through(self) -> bool: ... def reconfigure( self, *, @@ -155,21 +162,19 @@ class TextIOWrapper(TextIOBase, TextIO): errors: Optional[str] = ..., newline: Optional[str] = ..., line_buffering: Optional[bool] = ..., - write_through: Optional[bool] = ... + write_through: Optional[bool] = ..., ) -> None: ... - closed: bool # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy. def __enter__(self: _T) -> _T: ... def __iter__(self) -> Iterator[str]: ... # type: ignore def __next__(self) -> str: ... # type: ignore - def writelines(self, __lines: List[str]) -> None: ... # type: ignore + def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore def readline(self, __size: int = ...) -> str: ... # type: ignore def readlines(self, __hint: int = ...) -> List[str]: ... # type: ignore def seek(self, __cookie: int, __whence: int = ...) -> int: ... class StringIO(TextIOWrapper): - def __init__(self, initial_value: Optional[str] = ..., - newline: Optional[str] = ...) -> None: ... + def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...) -> None: ... # StringIO does not contain a "name" field. This workaround is necessary # to allow StringIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. @@ -177,6 +182,7 @@ class StringIO(TextIOWrapper): def getvalue(self) -> str: ... class IncrementalNewlineDecoder(codecs.IncrementalDecoder): - def __init__(self, decoder: Optional[codecs.IncrementalDecoder], - translate: bool, errors: str = ...) -> None: ... + def __init__(self, decoder: Optional[codecs.IncrementalDecoder], translate: bool, errors: str = ...) -> None: ... def decode(self, input: Union[bytes, str], final: bool = ...) -> str: ... + @property + def newlines(self) -> Optional[Union[str, Tuple[str, ...]]]: ... diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index 5c7d9a2db225..b4e2b2c4b3f9 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,7 +1,5 @@ -from typing import (Any, Container, Generic, Iterable, Iterator, Optional, - overload, SupportsInt, Text, Tuple, TypeVar) - import sys +from typing import Any, Container, Generic, Iterable, Iterator, Optional, SupportsInt, Tuple, TypeVar, overload # Undocumented length constants IPV4LENGTH: int @@ -23,11 +21,11 @@ class _IPAddressBase: def __lt__(self: _T, other: _T) -> bool: ... def __ne__(self, other: Any) -> bool: ... @property - def compressed(self) -> Text: ... + def compressed(self) -> str: ... @property - def exploded(self) -> Text: ... + def exploded(self) -> str: ... @property - def reverse_pointer(self) -> Text: ... + def reverse_pointer(self) -> str: ... @property def version(self) -> int: ... @@ -86,7 +84,7 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): def max_prefixlen(self) -> int: ... @property def num_addresses(self) -> int: ... - def overlaps(self, other: _BaseNetwork) -> bool: ... + def overlaps(self, other: _BaseNetwork[_A]) -> bool: ... @property def prefixlen(self) -> int: ... if sys.version_info >= (3, 7): @@ -95,11 +93,11 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> Iterator[_T]: ... def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> _T: ... @property - def with_hostmask(self) -> Text: ... + def with_hostmask(self) -> str: ... @property - def with_netmask(self) -> Text: ... + def with_netmask(self) -> str: ... @property - def with_prefixlen(self) -> Text: ... + def with_prefixlen(self) -> str: ... @property def hostmask(self) -> _A: ... @@ -110,11 +108,11 @@ class _BaseInterface(_BaseAddress, Generic[_A, _N]): @property def ip(self) -> _A: ... @property - def with_hostmask(self) -> Text: ... + def with_hostmask(self) -> str: ... @property - def with_netmask(self) -> Text: ... + def with_netmask(self) -> str: ... @property - def with_prefixlen(self) -> Text: ... + def with_prefixlen(self) -> str: ... class IPv4Address(_BaseAddress): ... class IPv4Network(_BaseNetwork[IPv4Address]): ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index b5f75fe1cc9d..aef3aac78635 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,21 +1,16 @@ -# Stubs for itertools - -# Based on http://docs.python.org/3.2/library/itertools.html - -from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, - Generic, Optional) import sys +from typing import Any, Callable, Generic, Iterable, Iterator, Optional, Tuple, TypeVar, overload +from typing_extensions import Literal -_T = TypeVar('_T') -_S = TypeVar('_S') -_N = TypeVar('_N', int, float) +_T = TypeVar("_T") +_S = TypeVar("_S") +_N = TypeVar("_N", int, float) Predicate = Callable[[_T], object] -def count(start: _N = ..., - step: _N = ...) -> Iterator[_N]: ... # more general types? +def count(start: _N = ..., step: _N = ...) -> Iterator[_N]: ... # more general types? class cycle(Iterator[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T]) -> None: ... + def __init__(self, __iterable: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... @@ -26,96 +21,91 @@ def repeat(object: _T, times: int) -> Iterator[_T]: ... if sys.version_info >= (3, 8): @overload - def accumulate(iterable: Iterable[_T], - func: Callable[[_T, _T], _T] = ...) -> Iterator[_T]: ... + def accumulate(iterable: Iterable[_T], func: None = ..., *, initial: Optional[_T] = ...) -> Iterator[_T]: ... @overload - def accumulate(iterable: Iterable[_T], - func: Callable[[_S, _T], _S], - initial: Optional[_S]) -> Iterator[_S]: ... + def accumulate(iterable: Iterable[_T], func: Callable[[_S, _T], _S], *, initial: Optional[_S] = ...) -> Iterator[_S]: ... + else: - def accumulate(iterable: Iterable[_T], - func: Callable[[_T, _T], _T] = ...) -> Iterator[_T]: ... + def accumulate(iterable: Iterable[_T], func: Optional[Callable[[_T, _T], _T]] = ...) -> Iterator[_T]: ... class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... @staticmethod - def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + def from_iterable(__iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... -def dropwhile(predicate: Predicate[_T], - iterable: Iterable[_T]) -> Iterator[_T]: ... -def filterfalse(predicate: Optional[Predicate[_T]], - iterable: Iterable[_T]) -> Iterator[_T]: ... - +def dropwhile(__predicate: Predicate[_T], __iterable: Iterable[_T]) -> Iterator[_T]: ... +def filterfalse(__predicate: Optional[Predicate[_T]], __iterable: Iterable[_T]) -> Iterator[_T]: ... @overload def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... @overload def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... - @overload -def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +def islice(__iterable: Iterable[_T], __stop: Optional[int]) -> Iterator[_T]: ... @overload -def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], - step: Optional[int] = ...) -> Iterator[_T]: ... - -def starmap(func: Callable[..., _S], iterable: Iterable[Iterable[Any]]) -> Iterator[_S]: ... -def takewhile(predicate: Predicate[_T], - iterable: Iterable[_T]) -> Iterator[_T]: ... -def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... -def zip_longest(*p: Iterable[Any], - fillvalue: Any = ...) -> Iterator[Any]: ... - -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_T3 = TypeVar('_T3') -_T4 = TypeVar('_T4') -_T5 = TypeVar('_T5') -_T6 = TypeVar('_T6') +def islice( + __iterable: Iterable[_T], __start: Optional[int], __stop: Optional[int], __step: Optional[int] = ... +) -> Iterator[_T]: ... +def starmap(__function: Callable[..., _S], __iterable: Iterable[Iterable[Any]]) -> Iterator[_S]: ... +def takewhile(__predicate: Predicate[_T], __iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(__iterable: Iterable[_T], __n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def zip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") +@overload +def product(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... @overload -def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... -@overload -def product(iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - iter7: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +def product( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + __iter6: Iterable[_T6], +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + __iter7: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[_T1], repeat: int) -> Iterator[Tuple[_T1, ...]]: ... @overload def product(*iterables: Iterable[Any], repeat: int = ...) -> Iterator[Tuple[Any, ...]]: ... - -def permutations(iterable: Iterable[_T], - r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ... -def combinations(iterable: Iterable[_T], - r: int) -> Iterator[Tuple[_T, ...]]: ... -def combinations_with_replacement(iterable: Iterable[_T], - r: int) -> Iterator[Tuple[_T, ...]]: ... +def permutations(iterable: Iterable[_T], r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ... +@overload +def combinations(iterable: Iterable[_T], r: Literal[2]) -> Iterator[Tuple[_T, _T]]: ... +@overload +def combinations(iterable: Iterable[_T], r: Literal[3]) -> Iterator[Tuple[_T, _T, _T]]: ... +@overload +def combinations(iterable: Iterable[_T], r: Literal[4]) -> Iterator[Tuple[_T, _T, _T, _T]]: ... +@overload +def combinations(iterable: Iterable[_T], r: Literal[5]) -> Iterator[Tuple[_T, _T, _T, _T, _T]]: ... +@overload +def combinations(iterable: Iterable[_T], r: int) -> Iterator[Tuple[_T, ...]]: ... +def combinations_with_replacement(iterable: Iterable[_T], r: int) -> Iterator[Tuple[_T, ...]]: ... diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 37147330bfaa..69c82a9c6cd1 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,58 +1,57 @@ -import sys -from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Type from _typeshed import SupportsRead +from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type, Union -from .decoder import JSONDecoder as JSONDecoder +from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder -from .decoder import JSONDecodeError as JSONDecodeError -def dumps(obj: Any, - *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Optional[Type[JSONEncoder]] = ..., - indent: Union[None, int, str] = ..., - separators: Optional[Tuple[str, str]] = ..., - default: Optional[Callable[[Any], Any]] = ..., - sort_keys: bool = ..., - **kwds: Any) -> str: ... - -def dump(obj: Any, - fp: IO[str], - *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Optional[Type[JSONEncoder]] = ..., - indent: Union[None, int, str] = ..., - separators: Optional[Tuple[str, str]] = ..., - default: Optional[Callable[[Any], Any]] = ..., - sort_keys: bool = ..., - **kwds: Any) -> None: ... - -if sys.version_info >= (3, 6): - _LoadsString = Union[str, bytes] -else: - _LoadsString = str -def loads(s: _LoadsString, - *, - cls: Optional[Type[JSONDecoder]] = ..., - object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., - **kwds: Any) -> Any: ... - -def load(fp: SupportsRead[_LoadsString], - *, - cls: Optional[Type[JSONDecoder]] = ..., - object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., - **kwds: Any) -> Any: ... +def dumps( + obj: Any, + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> str: ... +def dump( + obj: Any, + fp: IO[str], + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> None: ... +def loads( + s: Union[str, bytes], + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... +def load( + fp: SupportsRead[Union[str, bytes]], + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... diff --git a/mypy/typeshed/stdlib/json/decoder.pyi b/mypy/typeshed/stdlib/json/decoder.pyi index 3eb4cf5d9625..19d7b4eb2545 100644 --- a/mypy/typeshed/stdlib/json/decoder.pyi +++ b/mypy/typeshed/stdlib/json/decoder.pyi @@ -1,4 +1,3 @@ -import sys from typing import Any, Callable, Dict, List, Optional, Tuple class JSONDecodeError(ValueError): @@ -13,30 +12,18 @@ class JSONDecoder: object_hook: Callable[[Dict[str, Any]], Any] parse_float: Callable[[str], Any] parse_int: Callable[[str], Any] - parse_constant = ... # Callable[[str], Any] + parse_constant: Callable[[str], Any] = ... strict: bool object_pairs_hook: Callable[[List[Tuple[str, Any]]], Any] - - if sys.version_info >= (3, 6): - def __init__( - self, - *, - object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - strict: bool = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ... - ) -> None: ... - else: - def __init__( - self, - object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - strict: bool = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ..., - ) -> None: ... + def __init__( + self, + *, + object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + strict: bool = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ..., + ) -> None: ... def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ... # _w is undocumented def raw_decode(self, s: str, idx: int = ...) -> Tuple[Any, int]: ... diff --git a/mypy/typeshed/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi index 69e11e102904..7d520149ba4a 100644 --- a/mypy/typeshed/stdlib/json/encoder.pyi +++ b/mypy/typeshed/stdlib/json/encoder.pyi @@ -1,4 +1,3 @@ -import sys from typing import Any, Callable, Iterator, Optional, Tuple class JSONEncoder: @@ -11,32 +10,18 @@ class JSONEncoder: allow_nan: bool sort_keys: bool indent: int - - if sys.version_info >= (3, 6): - def __init__( - self, - *, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - sort_keys: bool = ..., - indent: Optional[int] = ..., - separators: Optional[Tuple[str, str]] = ..., - default: Optional[Callable[..., Any]] = ... - ) -> None: ... - else: - def __init__( - self, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - sort_keys: bool = ..., - indent: Optional[int] = ..., - separators: Optional[Tuple[str, str]] = ..., - default: Optional[Callable[..., Any]] = ..., - ) -> None: ... + def __init__( + self, + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[..., Any]] = ..., + ) -> None: ... def default(self, o: Any) -> Any: ... def encode(self, o: Any) -> str: ... def iterencode(self, o: Any, _one_shot: bool = ...) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/json/tool.pyi b/mypy/typeshed/stdlib/json/tool.pyi new file mode 100644 index 000000000000..7e7363e797f3 --- /dev/null +++ b/mypy/typeshed/stdlib/json/tool.pyi @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index f9e3376eeca0..3e095ed5f94c 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,6 +1,10 @@ -# Stubs for keyword +import sys +from typing import Sequence, Text -from typing import Sequence, Text, Union +def iskeyword(s: Text) -> bool: ... -def iskeyword(s: Union[Text, bytes]) -> bool: ... kwlist: Sequence[str] + +if sys.version_info >= (3, 9): + def issoftkeyword(s: str) -> bool: ... + softkwlist: Sequence[str] diff --git a/mypy/typeshed/stdlib/lib2to3/__init__.pyi b/mypy/typeshed/stdlib/lib2to3/__init__.pyi index 145e31b1dec8..e69de29bb2d1 100644 --- a/mypy/typeshed/stdlib/lib2to3/__init__.pyi +++ b/mypy/typeshed/stdlib/lib2to3/__init__.pyi @@ -1 +0,0 @@ -# Stubs for lib2to3 (Python 3.6) diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi index a97dd5169c03..841b0e4b1cb3 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -1,10 +1,8 @@ from _typeshed import StrPath -from typing import Any, IO, Iterable, Optional, Text - -from logging import Logger -from lib2to3.pytree import _Convert, _NL 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 @@ -17,4 +15,6 @@ class Driver: 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: ... +def load_grammar( + gt: Text = ..., gp: Optional[Text] = ..., 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 c5fd030e59da..6ec97ce849d2 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from typing import Dict, List, Optional, Text, Tuple, TypeVar -_P = TypeVar('_P') +_P = TypeVar("_P") _Label = Tuple[int, Optional[Text]] _DFA = List[List[Tuple[int, int]]] _DFAS = Tuple[_DFA, Dict[int, int]] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi index 3166ffbf304c..160d6fd76f76 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi @@ -1,5 +1,3 @@ -# Stubs for lib2to3.pgen2.literals (Python 3.6) - from typing import Dict, Match, Text simple_escapes: Dict[Text, Text] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index 101d4760a60c..b7018cba9c1d 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,9 +1,6 @@ -# Stubs for lib2to3.pgen2.parse (Python 3.6) - -from typing import Any, Dict, List, Optional, Sequence, Set, Text, Tuple - -from lib2to3.pgen2.grammar import Grammar, _DFAS +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] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 2b9f5eaaa759..7920262f4f04 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -1,10 +1,7 @@ from _typeshed import StrPath -from typing import ( - Any, Dict, IO, Iterable, Iterator, List, NoReturn, Optional, Text, Tuple -) - 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): ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi index c256af8f27fe..19660cb0ce26 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi @@ -1,5 +1,3 @@ -# Stubs for lib2to3.pgen2.token (Python 3.6) - import sys from typing import Dict, Text diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index c10305ffdda0..477341c1a54e 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,15 +1,10 @@ -# Stubs for lib2to3.pgen2.tokenize (Python 3.6) -# NOTE: Only elements from __all__ are present. - -from typing import Callable, Iterable, Iterator, List, Text, Tuple 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): ... @@ -25,6 +20,4 @@ class Untokenizer: 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]: ... +def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pygram.pyi b/mypy/typeshed/stdlib/lib2to3/pygram.pyi index aeb7b93bf870..bf96a55c41b3 100644 --- a/mypy/typeshed/stdlib/lib2to3/pygram.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pygram.pyi @@ -1,6 +1,3 @@ -# Stubs for lib2to3.pygram (Python 3.6) - -from typing import Any from lib2to3.pgen2.grammar import Grammar class Symbols: diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 06a7c1229c40..955763588cd1 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,11 +1,8 @@ -# Stubs for lib2to3.pytree (Python 3.6) - import sys -from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union - from lib2to3.pgen2.grammar import Grammar +from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union -_P = TypeVar('_P') +_P = TypeVar("_P") _NL = Union[Node, Leaf] _Context = Tuple[Text, int, int] _Results = Dict[Text, _NL] @@ -45,7 +42,14 @@ class Base: 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 __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: ... @@ -55,7 +59,14 @@ class Leaf(Base): 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 __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: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index 3f35f469eb3f..f52267bdba98 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -8,5 +8,6 @@ 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: ... diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index c4703f7f0e1c..c5e25c95aa09 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -1,8 +1,6 @@ -# Stubs for locale - +import sys from decimal import Decimal from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union -import sys # workaround for mypy#2010 if sys.version_info < (3,): @@ -81,8 +79,7 @@ CHAR_MAX: int class Error(Exception): ... -def setlocale(category: int, - locale: Union[_str, Iterable[_str], None] = ...) -> _str: ... +def setlocale(category: int, locale: Union[_str, Iterable[_str], None] = ...) -> _str: ... def localeconv() -> Mapping[_str, Union[int, _str, List[int]]]: ... def nl_langinfo(option: int) -> _str: ... def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[Optional[_str], Optional[_str]]: ... @@ -92,18 +89,19 @@ 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(percent: _str, value: Union[float, Decimal], grouping: bool = ..., monetary: bool = ..., *additional: Any) -> _str: ... + if sys.version_info >= (3, 7): - def format_string(f: _str, val: Any, - grouping: bool = ..., monetary: bool = ...) -> _str: ... + def format_string(f: _str, val: Any, grouping: bool = ..., monetary: bool = ...) -> _str: ... + 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: ... + 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 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/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 2a480b967e28..865c527ac844 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -1,16 +1,27 @@ +import sys +import threading from _typeshed import StrPath -from typing import ( - Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, IO, - Sequence, Tuple, Text, Union, overload, -) from string import Template from time import struct_time -from types import TracebackType, FrameType -import sys -import threading +from types import FrameType, TracebackType +from typing import ( + IO, + Any, + Callable, + Dict, + Iterable, + List, + Mapping, + MutableMapping, + Optional, + Sequence, + Text, + Tuple, + Union, + overload, +) -_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], - Tuple[None, None, None]] +_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] if sys.version_info >= (3, 5): _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] else: @@ -53,30 +64,87 @@ class Logger(Filterer): def getEffectiveLevel(self) -> int: ... def getChild(self, suffix: str) -> Logger: ... if sys.version_info >= (3, 8): - def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... def _log( self, level: int, @@ -88,31 +156,80 @@ class Logger(Filterer): stacklevel: int = ..., ) -> None: ... # undocumented elif sys.version_info >= (3,): - def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... fatal = critical - def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... def _log( self, level: int, @@ -123,29 +240,35 @@ class Logger(Filterer): stack_info: bool = ..., ) -> None: ... # undocumented else: - def debug(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def info(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def warning(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def debug( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def info( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def warning( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... warn = warning - def error(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def critical(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def error( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def critical( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... fatal = critical - def log(self, - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def exception(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... def _log( self, level: int, @@ -165,23 +288,35 @@ class Logger(Filterer): def findCaller(self) -> Tuple[str, int, str]: ... def handle(self, record: LogRecord) -> None: ... if sys.version_info >= (3,): - def makeRecord(self, name: str, level: int, fn: str, lno: int, msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - extra: Optional[Mapping[str, Any]] = ..., - sinfo: Optional[str] = ...) -> LogRecord: ... + def makeRecord( + self, + name: str, + level: int, + fn: str, + lno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + sinfo: Optional[str] = ..., + ) -> LogRecord: ... else: - def makeRecord(self, - name: str, level: int, fn: str, lno: int, msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - extra: Optional[Mapping[str, Any]] = ...) -> LogRecord: ... + def makeRecord( + self, + name: str, + level: int, + fn: str, + lno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + ) -> LogRecord: ... if sys.version_info >= (3,): def hasHandlers(self) -> bool: ... - CRITICAL: int FATAL: int ERROR: int @@ -191,7 +326,6 @@ INFO: int DEBUG: int NOTSET: int - class Handler(Filterer): level: int # undocumented formatter: Optional[Formatter] # undocumented @@ -211,7 +345,6 @@ class Handler(Filterer): def format(self, record: LogRecord) -> str: ... def emit(self, record: LogRecord) -> None: ... - class Formatter: converter: Callable[[Optional[float]], struct_time] _fmt: Optional[str] @@ -222,18 +355,13 @@ class Formatter: default_msec_format: str if sys.version_info >= (3, 8): - def __init__(self, fmt: Optional[str] = ..., - datefmt: Optional[str] = ..., - style: str = ..., validate: bool = ...) -> None: ... + def __init__( + self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ..., validate: bool = ... + ) -> None: ... elif sys.version_info >= (3,): - def __init__(self, fmt: Optional[str] = ..., - datefmt: Optional[str] = ..., - style: str = ...) -> None: ... + def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ...) -> None: ... else: - def __init__(self, - fmt: Optional[str] = ..., - datefmt: Optional[str] = ...) -> None: ... - + def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ...) -> None: ... def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: Optional[str] = ...) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... @@ -241,11 +369,9 @@ class Formatter: def formatMessage(self, record: LogRecord) -> str: ... # undocumented def formatStack(self, stack_info: str) -> str: ... - class Filter: def __init__(self, name: str = ...) -> None: ... - def filter(self, record: LogRecord) -> int: ... - + def filter(self, record: LogRecord) -> bool: ... class LogRecord: args: _ArgsType @@ -272,97 +398,221 @@ class LogRecord: thread: int threadName: str if sys.version_info >= (3,): - def __init__(self, name: str, level: int, pathname: str, lineno: int, - msg: Any, args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - sinfo: Optional[str] = ...) -> None: ... + def __init__( + self, + name: str, + level: int, + pathname: str, + lineno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + sinfo: Optional[str] = ..., + ) -> None: ... else: - def __init__(self, - name: str, level: int, pathname: str, lineno: int, - msg: Any, args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ...) -> None: ... + def __init__( + self, + name: str, + level: int, + pathname: str, + lineno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + ) -> None: ... def getMessage(self) -> str: ... - class LoggerAdapter: logger: Logger extra: Mapping[str, Any] def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... if sys.version_info >= (3, 8): - def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... elif sys.version_info >= (3,): - def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + self, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... else: - def debug(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def info(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def warning(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def error(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def exception(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def critical(self, - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def log(self, - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def debug( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def info( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def warning( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def error( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def exception( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def critical( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... def isEnabledFor(self, level: int) -> bool: ... if sys.version_info >= (3,): def getEffectiveLevel(self) -> int: ... @@ -381,123 +631,247 @@ class LoggerAdapter: if sys.version_info >= (3,): def getLogger(name: Optional[str] = ...) -> Logger: ... + else: @overload def getLogger() -> Logger: ... @overload def getLogger(name: Union[Text, str]) -> Logger: ... + def getLoggerClass() -> type: ... + if sys.version_info >= (3,): def getLogRecordFactory() -> Callable[..., LogRecord]: ... if sys.version_info >= (3, 8): - def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., stacklevel: int = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def log( + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + stacklevel: int = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + elif sys.version_info >= (3,): - def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def warn(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... - def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any) -> None: ... + def debug( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def info( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warning( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def warn( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def error( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def critical( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def log( + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + stack_info: bool = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + else: - def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def debug( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def info( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def warning( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... warn = warning - def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... - def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def error( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def critical( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def exception( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def log( + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + fatal = critical if sys.version_info >= (3, 7): def disable(level: int = ...) -> None: ... + else: def disable(level: int) -> None: ... + def addLevelName(level: int, levelName: str) -> None: ... def getLevelName(level: Union[int, str]) -> Any: ... - def makeLogRecord(dict: Mapping[str, Any]) -> LogRecord: ... if sys.version_info >= (3, 8): - def basicConfig(*, filename: Optional[StrPath] = ..., filemode: str = ..., - format: str = ..., datefmt: Optional[str] = ..., style: str = ..., - level: Optional[_Level] = ..., stream: Optional[IO[str]] = ..., - handlers: Optional[Iterable[Handler]] = ..., force: bool = ...) -> None: ... + def basicConfig( + *, + filename: Optional[StrPath] = ..., + filemode: str = ..., + format: str = ..., + datefmt: Optional[str] = ..., + style: str = ..., + level: Optional[_Level] = ..., + stream: Optional[IO[str]] = ..., + handlers: Optional[Iterable[Handler]] = ..., + force: bool = ..., + ) -> None: ... + elif sys.version_info >= (3,): - def basicConfig(*, filename: Optional[StrPath] = ..., filemode: str = ..., - format: str = ..., datefmt: Optional[str] = ..., style: str = ..., - level: Optional[_Level] = ..., stream: Optional[IO[str]] = ..., - handlers: Optional[Iterable[Handler]] = ...) -> None: ... + def basicConfig( + *, + filename: Optional[StrPath] = ..., + filemode: str = ..., + format: str = ..., + datefmt: Optional[str] = ..., + style: str = ..., + level: Optional[_Level] = ..., + stream: Optional[IO[str]] = ..., + handlers: Optional[Iterable[Handler]] = ..., + ) -> None: ... + else: @overload def basicConfig() -> None: ... @overload - def basicConfig(*, filename: Optional[str] = ..., filemode: str = ..., - format: str = ..., datefmt: Optional[str] = ..., - level: Optional[_Level] = ..., stream: IO[str] = ...) -> None: ... -def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented + def basicConfig( + *, + filename: Optional[str] = ..., + filemode: str = ..., + format: str = ..., + datefmt: Optional[str] = ..., + level: Optional[_Level] = ..., + stream: IO[str] = ..., + ) -> None: ... +def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented def setLoggerClass(klass: type) -> None: ... - def captureWarnings(capture: bool) -> None: ... if sys.version_info >= (3,): def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... - if sys.version_info >= (3,): lastResort: Optional[StreamHandler] - class StreamHandler(Handler): stream: IO[str] # undocumented if sys.version_info >= (3, 2): @@ -506,25 +880,20 @@ class StreamHandler(Handler): if sys.version_info >= (3, 7): def setStream(self, stream: IO[str]) -> Optional[IO[str]]: ... - class FileHandler(StreamHandler): baseFilename: str # undocumented mode: str # undocumented encoding: Optional[str] # undocumented delay: bool # undocumented - def __init__(self, filename: StrPath, mode: str = ..., - encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... def _open(self) -> IO[Any]: ... - class NullHandler(Handler): ... - class PlaceHolder: def __init__(self, alogger: Logger) -> None: ... def append(self, alogger: Logger) -> None: ... - # Below aren't in module docs but still visible class RootLogger(Logger): @@ -532,25 +901,18 @@ class RootLogger(Logger): root: RootLogger - if sys.version_info >= (3,): class PercentStyle(object): default_format: str asctime_format: str asctime_search: str _fmt: str - def __init__(self, fmt: str) -> None: ... def usesTime(self) -> bool: ... def format(self, record: Any) -> str: ... - - class StrFormatStyle(PercentStyle): - ... - + class StrFormatStyle(PercentStyle): ... class StringTemplateStyle(PercentStyle): _tpl: Template - _STYLES: Dict[str, Tuple[PercentStyle, str]] - BASIC_FORMAT: str diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index 76420aba7747..535d583d759a 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -1,7 +1,8 @@ +import sys from _typeshed import AnyPath, StrPath -from typing import Any, Callable, Dict, Optional, IO, Union from threading import Thread -import sys +from typing import IO, Any, Callable, Dict, Optional, Union + if sys.version_info >= (3,): from configparser import RawConfigParser else: @@ -12,17 +13,20 @@ if sys.version_info >= (3, 7): else: _Path = StrPath - def dictConfig(config: Dict[str, Any]) -> None: ... + if sys.version_info >= (3, 4): - def fileConfig(fname: Union[_Path, IO[str], RawConfigParser], - defaults: Optional[Dict[str, str]] = ..., - disable_existing_loggers: bool = ...) -> None: ... - def listen(port: int = ..., - verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> Thread: ... + def fileConfig( + fname: Union[_Path, IO[str], RawConfigParser], + defaults: Optional[Dict[str, str]] = ..., + disable_existing_loggers: bool = ..., + ) -> None: ... + def listen(port: int = ..., verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> Thread: ... + else: - def fileConfig(fname: Union[str, IO[str]], - defaults: Optional[Dict[str, str]] = ..., - disable_existing_loggers: bool = ...) -> None: ... + def fileConfig( + fname: Union[str, IO[str]], defaults: Optional[Dict[str, str]] = ..., disable_existing_loggers: bool = ... + ) -> None: ... def listen(port: int = ...) -> Thread: ... + def stopListening() -> None: ... diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index b93d201160e4..3c726fc2a3c0 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -1,20 +1,18 @@ -from _typeshed import StrPath import datetime -from logging import Handler, FileHandler, LogRecord -from socket import SocketType import ssl import sys -from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload +from _typeshed import StrPath +from logging import FileHandler, Handler, LogRecord +from socket import SocketKind, SocketType +from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union + if sys.version_info >= (3, 7): - from queue import SimpleQueue, Queue + from queue import Queue, SimpleQueue elif sys.version_info >= (3,): from queue import Queue else: from Queue import Queue -# TODO update socket stubs to add SocketKind -_SocketKind = int - DEFAULT_TCP_LOGGING_PORT: int DEFAULT_UDP_LOGGING_PORT: int DEFAULT_HTTP_LOGGING_PORT: int @@ -25,60 +23,85 @@ SYSLOG_TCP_PORT: int class WatchedFileHandler(FileHandler): dev: int ino: int - def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., - delay: bool = ...) -> None: ... + def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... def _statstream(self) -> None: ... - if sys.version_info >= (3,): class BaseRotatingHandler(FileHandler): terminator: str namer: Optional[Callable[[str], str]] rotator: Optional[Callable[[str, str], None]] - def __init__(self, filename: StrPath, mode: str, - encoding: Optional[str] = ..., - delay: bool = ...) -> None: ... + def __init__(self, filename: StrPath, mode: str, encoding: Optional[str] = ..., delay: bool = ...) -> None: ... def rotation_filename(self, default_name: str) -> None: ... def rotate(self, source: str, dest: str) -> None: ... - if sys.version_info >= (3,): class RotatingFileHandler(BaseRotatingHandler): - def __init__(self, filename: StrPath, mode: str = ..., maxBytes: int = ..., - backupCount: int = ..., encoding: Optional[str] = ..., - delay: bool = ...) -> None: ... + def __init__( + self, + filename: StrPath, + mode: str = ..., + maxBytes: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + ) -> None: ... def doRollover(self) -> None: ... + else: class RotatingFileHandler(Handler): - def __init__(self, filename: str, mode: str = ..., maxBytes: int = ..., - backupCount: int = ..., encoding: Optional[str] = ..., - delay: bool = ...) -> None: ... + def __init__( + self, + filename: str, + mode: str = ..., + maxBytes: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + ) -> None: ... def doRollover(self) -> None: ... - if sys.version_info >= (3,): class TimedRotatingFileHandler(BaseRotatingHandler): if sys.version_info >= (3, 4): - def __init__(self, filename: StrPath, when: str = ..., - interval: int = ..., - backupCount: int = ..., encoding: Optional[str] = ..., - delay: bool = ..., utc: bool = ..., - atTime: Optional[datetime.datetime] = ...) -> None: ... + def __init__( + self, + filename: StrPath, + when: str = ..., + interval: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + utc: bool = ..., + atTime: Optional[datetime.datetime] = ..., + ) -> None: ... else: - def __init__(self, - filename: str, when: str = ..., interval: int = ..., - backupCount: int = ..., encoding: Optional[str] = ..., - delay: bool = ..., utc: bool = ...) -> None: ... + def __init__( + self, + filename: str, + when: str = ..., + interval: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + utc: bool = ..., + ) -> None: ... def doRollover(self) -> None: ... + else: class TimedRotatingFileHandler(Handler): - def __init__(self, - filename: str, when: str = ..., interval: int = ..., - backupCount: int = ..., encoding: Optional[str] = ..., - delay: bool = ..., utc: bool = ...) -> None: ... + def __init__( + self, + filename: str, + when: str = ..., + interval: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + utc: bool = ..., + ) -> None: ... def doRollover(self) -> None: ... - class SocketHandler(Handler): retryStart: float retryFactor: float @@ -92,32 +115,38 @@ class SocketHandler(Handler): def send(self, s: bytes) -> None: ... def createSocket(self) -> None: ... - class DatagramHandler(SocketHandler): def makeSocket(self) -> SocketType: ... # type: ignore - class SysLogHandler(Handler): + LOG_EMERG: int LOG_ALERT: int LOG_CRIT: int - LOG_DEBUG: int - LOG_EMERG: int LOG_ERR: int - LOG_INFO: int - LOG_NOTICE: int LOG_WARNING: int - LOG_AUTH: int - LOG_AUTHPRIV: int - LOG_CRON: int - LOG_DAEMON: int - LOG_FTP: int + LOG_NOTICE: int + LOG_INFO: int + LOG_DEBUG: int + LOG_KERN: int - LOG_LPR: int + LOG_USER: int LOG_MAIL: int - LOG_NEWS: int + LOG_DAEMON: int + LOG_AUTH: int LOG_SYSLOG: int - LOG_USER: int + LOG_LPR: int + LOG_NEWS: int LOG_UUCP: int + LOG_CRON: int + LOG_AUTHPRIV: int + LOG_FTP: int + + if sys.version_info >= (3, 9): + LOG_NTP: int + LOG_SECURITY: int + LOG_CONSOLE: int + LOG_SOLCRON: int + LOG_LOCAL0: int LOG_LOCAL1: int LOG_LOCAL2: int @@ -126,39 +155,52 @@ class SysLogHandler(Handler): LOG_LOCAL5: int LOG_LOCAL6: int LOG_LOCAL7: int - def __init__(self, address: Union[Tuple[str, int], str] = ..., - facility: int = ..., socktype: Optional[_SocketKind] = ...) -> None: ... - def encodePriority(self, facility: Union[int, str], - priority: Union[int, str]) -> int: ... + unixsocket: bool # undocumented + socktype: SocketKind # undocumented + if sys.version_info >= (3,): + ident: str # undocumented + facility: int # undocumented + priority_names: ClassVar[Dict[str, int]] # undocumented + facility_names: ClassVar[Dict[str, int]] # undocumented + priority_map: ClassVar[Dict[str, str]] # undocumented + def __init__( + self, address: Union[Tuple[str, int], str] = ..., facility: int = ..., socktype: Optional[SocketKind] = ... + ) -> None: ... + def encodePriority(self, facility: Union[int, str], priority: Union[int, str]) -> int: ... def mapPriority(self, levelName: str) -> str: ... - class NTEventLogHandler(Handler): - def __init__(self, appname: str, dllname: Optional[str] = ..., - logtype: str = ...) -> None: ... + def __init__(self, appname: str, dllname: Optional[str] = ..., logtype: str = ...) -> None: ... def getEventCategory(self, record: LogRecord) -> int: ... # TODO correct return value? def getEventType(self, record: LogRecord) -> int: ... def getMessageID(self, record: LogRecord) -> int: ... - class SMTPHandler(Handler): # TODO `secure` can also be an empty tuple if sys.version_info >= (3,): - def __init__(self, mailhost: Union[str, Tuple[str, int]], fromaddr: str, - toaddrs: List[str], subject: str, - credentials: Optional[Tuple[str, str]] = ..., - secure: Union[Tuple[str], Tuple[str, str], None] = ..., - timeout: float = ...) -> None: ... + def __init__( + self, + mailhost: Union[str, Tuple[str, int]], + fromaddr: str, + toaddrs: List[str], + subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ..., + timeout: float = ..., + ) -> None: ... else: - def __init__(self, - mailhost: Union[str, Tuple[str, int]], fromaddr: str, - toaddrs: List[str], subject: str, - credentials: Optional[Tuple[str, str]] = ..., - secure: Union[Tuple[str], Tuple[str, str], None] = ...) -> None: ... + def __init__( + self, + mailhost: Union[str, Tuple[str, int]], + fromaddr: str, + toaddrs: List[str], + subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ..., + ) -> None: ... def getSubject(self, record: LogRecord) -> str: ... - class BufferingHandler(Handler): buffer: List[LogRecord] def __init__(self, capacity: int) -> None: ... @@ -166,30 +208,32 @@ class BufferingHandler(Handler): class MemoryHandler(BufferingHandler): if sys.version_info >= (3, 6): - def __init__(self, capacity: int, flushLevel: int = ..., - target: Optional[Handler] = ..., flushOnClose: bool = ...) -> None: ... + def __init__( + self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ..., flushOnClose: bool = ... + ) -> None: ... else: - def __init__(self, capacity: int, flushLevel: int = ..., - target: Optional[Handler] = ...) -> None: ... + def __init__(self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ...) -> None: ... def setTarget(self, target: Handler) -> None: ... - class HTTPHandler(Handler): if sys.version_info >= (3, 5): - def __init__(self, host: str, url: str, method: str = ..., - secure: bool = ..., - credentials: Optional[Tuple[str, str]] = ..., - context: Optional[ssl.SSLContext] = ...) -> None: ... + def __init__( + self, + host: str, + url: str, + method: str = ..., + secure: bool = ..., + credentials: Optional[Tuple[str, str]] = ..., + context: Optional[ssl.SSLContext] = ..., + ) -> None: ... elif sys.version_info >= (3,): - def __init__(self, - host: str, url: str, method: str = ..., secure: bool = ..., - credentials: Optional[Tuple[str, str]] = ...) -> None: ... + def __init__( + self, host: str, url: str, method: str = ..., secure: bool = ..., credentials: Optional[Tuple[str, str]] = ... + ) -> None: ... else: - def __init__(self, - host: str, url: str, method: str = ...) -> None: ... + def __init__(self, host: str, url: str, method: str = ...) -> None: ... def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... - if sys.version_info >= (3,): class QueueHandler(Handler): if sys.version_info >= (3, 7): @@ -198,18 +242,15 @@ if sys.version_info >= (3,): def __init__(self, queue: Queue[Any]) -> None: ... def prepare(self, record: LogRecord) -> Any: ... def enqueue(self, record: LogRecord) -> None: ... - class QueueListener: if sys.version_info >= (3, 7): - def __init__(self, queue: Union[SimpleQueue[Any], Queue[Any]], - *handlers: Handler, - respect_handler_level: bool = ...) -> None: ... + def __init__( + self, queue: Union[SimpleQueue[Any], Queue[Any]], *handlers: Handler, respect_handler_level: bool = ... + ) -> None: ... elif sys.version_info >= (3, 5): - def __init__(self, queue: Queue[Any], *handlers: Handler, - respect_handler_level: bool = ...) -> None: ... + def __init__(self, queue: Queue[Any], *handlers: Handler, respect_handler_level: bool = ...) -> None: ... else: - def __init__(self, - queue: Queue, *handlers: Handler) -> None: ... + def __init__(self, queue: Queue, *handlers: Handler) -> None: ... def dequeue(self, block: bool) -> LogRecord: ... def prepare(self, record: LogRecord) -> Any: ... def start(self) -> None: ... diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 30e71e0ec8da..b39b5ecc77d3 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,6 +1,6 @@ import io -from typing import IO, Any, Mapping, Optional, Sequence, TextIO, TypeVar, Union, overload from _typeshed import AnyPath, ReadableBuffer +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"] diff --git a/mypy/typeshed/stdlib/macpath.pyi b/mypy/typeshed/stdlib/macpath.pyi index 65b0aa572467..0b5ccbf05f65 100644 --- a/mypy/typeshed/stdlib/macpath.pyi +++ b/mypy/typeshed/stdlib/macpath.pyi @@ -1,13 +1,10 @@ -# Stubs for os.path -# Ron Murawski - import os import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Union, Text, Callable, Optional -from _typeshed import StrPath, BytesPath, AnyPath +from _typeshed import AnyPath, BytesPath, StrPath +from typing import Any, AnyStr, Callable, List, Optional, Sequence, Text, Tuple, TypeVar, Union, overload if sys.version_info < (3, 8): - _T = TypeVar('_T') + _T = TypeVar("_T") if sys.version_info >= (3, 6): from builtins import _PathLike @@ -59,7 +56,6 @@ if sys.version_info < (3, 8): def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... @overload def realpath(path: AnyStr) -> AnyStr: ... - else: def abspath(path: AnyStr) -> AnyStr: ... def basename(s: AnyStr) -> AnyStr: ... @@ -69,31 +65,26 @@ if sys.version_info < (3, 8): def normcase(path: AnyStr) -> AnyStr: ... def normpath(s: AnyStr) -> AnyStr: ... def realpath(path: AnyStr) -> AnyStr: ... - # 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: ... - if sys.version_info >= (3, 3): def exists(path: Union[AnyPath, int]) -> bool: ... else: def exists(path: AnyPath) -> bool: ... def lexists(path: AnyPath) -> 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(s: AnyPath) -> bool: ... def ismount(s: AnyPath) -> bool: ... - if sys.version_info < (3, 0): # Make sure signatures are disjunct, and allow combinations of bytes and unicode. # (Since Python 2 allows that, too) @@ -117,11 +108,9 @@ if sys.version_info < (3, 8): def join(s: BytesPath, *paths: BytesPath) -> bytes: ... else: def join(s: AnyStr, *paths: AnyStr) -> AnyStr: ... - 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: ... - if sys.version_info >= (3, 6): @overload def split(s: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... @@ -139,6 +128,5 @@ if sys.version_info < (3, 8): def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - if sys.version_info < (3,): def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/macurl2path.pyi b/mypy/typeshed/stdlib/macurl2path.pyi index 95ee888fb564..41befd1d95c7 100644 --- a/mypy/typeshed/stdlib/macurl2path.pyi +++ b/mypy/typeshed/stdlib/macurl2path.pyi @@ -1,6 +1,4 @@ - import sys - from typing import Union if sys.version_info < (3, 7): diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 78bc22482532..e22788d21517 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -1,11 +1,35 @@ -from typing import Optional, Union, Text, AnyStr, Callable, IO, Any, Iterator, List, Tuple, TypeVar, Protocol, Dict, Sequence, Iterable, Generic, Type, Mapping, overload -from types import TracebackType -import email +import email.message +import sys from _typeshed import AnyPath +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 +if sys.version_info >= (3, 9): + from types import GenericAlias + _T = TypeVar("_T") -_MessageType = TypeVar("_MessageType", bound=Message) +_MessageT = TypeVar("_MessageT", bound=Message) _MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] class _HasIteritems(Protocol): @@ -16,55 +40,56 @@ class _HasItems(Protocol): linesep: bytes -class Mailbox(Generic[_MessageType]): +class Mailbox(Generic[_MessageT]): _path: Union[bytes, str] # undocumented - _factory: Optional[Callable[[IO[Any]], _MessageType]] # undocumented - - def __init__(self, path: AnyPath, factory: Optional[Callable[[IO[Any]], _MessageType]] = ..., create: bool = ...) -> None: ... + _factory: Optional[Callable[[IO[Any]], _MessageT]] # undocumented + def __init__(self, path: AnyPath, 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[_MessageType]: ... + def get(self, key: str, default: None = ...) -> Optional[_MessageT]: ... @overload - def get(self, key: str, default: _T) -> Union[_MessageType, _T]: ... - def __getitem__(self, key: str) -> _MessageType: ... - def get_message(self, key: str) -> _MessageType: ... + 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[_MessageType]: ... - def __iter__(self) -> Iterator[_MessageType]: ... - def values(self) -> List[_MessageType]: ... - def iteritems(self) -> Iterator[Tuple[str, _MessageType]]: ... - def items(self) -> List[Tuple[str, _MessageType]]: ... + 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[_MessageType]: ... + def pop(self, key: str, default: None = ...) -> Optional[_MessageT]: ... @overload - def pop(self, key: str, default: _T = ...) -> Union[_MessageType, _T]: ... - def popitem(self) -> Tuple[str, _MessageType]: ... + 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: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Maildir(Mailbox[MaildirMessage]): colon: str - - def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], MaildirMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, dirname: AnyPath, 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: ... @@ -72,25 +97,24 @@ class Maildir(Mailbox[MaildirMessage]): def clean(self) -> None: ... def next(self) -> Optional[str]: ... -class _singlefileMailbox(Mailbox[_MessageType]): ... - -class _mboxMMDF(_singlefileMailbox[_MessageType]): +class _singlefileMailbox(Mailbox[_MessageT]): ... +class _mboxMMDF(_singlefileMailbox[_MessageT]): def get_file(self, key: str) -> _PartialFile[bytes]: ... class mbox(_mboxMMDF[mboxMessage]): - - def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], mboxMessage]] = ..., create: bool = ... + ) -> None: ... class MMDF(_mboxMMDF[MMDFMessage]): - - def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ...) -> None: ... + def __init__( + self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], MMDFMessage]] = ..., create: bool = ... + ) -> None: ... class MH(Mailbox[MHMessage]): - def __init__(self, dirname: AnyPath, 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: ... @@ -100,18 +124,16 @@ class MH(Mailbox[MHMessage]): def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): - - def __init__(self, dirname: AnyPath, factory: Optional[Callable[[IO[Any]], BabylMessage]] = ..., create: bool = ...) -> None: ... - + def __init__( + self, dirname: AnyPath, 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: ... @@ -124,9 +146,10 @@ class MaildirMessage(Message): 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 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: ... @@ -135,14 +158,12 @@ class _mboxMMDFMessage(Message): 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: ... @@ -154,7 +175,6 @@ class BabylMessage(Message): 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: ... @@ -165,24 +185,23 @@ class _ProxyFile(Generic[AnyStr]): 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 __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: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... 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/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index 8f9689d9faf2..a65cc3a329d3 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -1,7 +1,8 @@ - -from typing import Sequence, Dict, List, Union, Tuple, Optional, Mapping +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 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/marshal.pyi b/mypy/typeshed/stdlib/marshal.pyi index b6c19b805f84..b2fde674a647 100644 --- a/mypy/typeshed/stdlib/marshal.pyi +++ b/mypy/typeshed/stdlib/marshal.pyi @@ -1,4 +1,4 @@ -from typing import Any, IO +from typing import IO, Any version: int diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index 7e2686c02f8d..6f9a89996dc0 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -1,9 +1,5 @@ -# Stubs for math -# See: http://docs.python.org/2/library/math.html - -from typing import Tuple, Iterable, SupportsFloat, SupportsInt, overload - import sys +from typing import Iterable, Optional, SupportsFloat, SupportsInt, Tuple, overload e: float pi: float @@ -20,64 +16,106 @@ 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: ... + +if sys.version_info >= (3, 8): + def comb(__n: int, __k: int) -> int: ... + def copysign(__x: SupportsFloat, __y: SupportsFloat) -> float: ... def cos(__x: SupportsFloat) -> float: ... def cosh(__x: SupportsFloat) -> float: ... def degrees(__x: SupportsFloat) -> float: ... + if sys.version_info >= (3, 8): def dist(__p: Iterable[SupportsFloat], __q: Iterable[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: ... + if sys.version_info >= (3,): def floor(__x: SupportsFloat) -> int: ... + else: 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: ... -if sys.version_info >= (3, 5): + +if sys.version_info >= (3, 9): + def gcd(*integers: int) -> int: ... + +elif sys.version_info >= (3, 5): def gcd(__x: int, __y: int) -> int: ... + if sys.version_info >= (3, 8): def hypot(*coordinates: SupportsFloat) -> float: ... + 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 isinf(__x: SupportsFloat) -> bool: ... + if sys.version_info >= (3,): def isfinite(__x: SupportsFloat) -> bool: ... + def isnan(__x: SupportsFloat) -> bool: ... + if sys.version_info >= (3, 8): def isqrt(__n: int) -> int: ... + +if sys.version_info >= (3, 9): + def lcm(*integers: int) -> int: ... + 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: ... + if sys.version_info >= (3, 3): def log2(__x: SupportsFloat) -> float: ... + def modf(__x: SupportsFloat) -> Tuple[float, float]: ... + +if sys.version_info >= (3, 9): + def nextafter(__x: SupportsFloat, __y: SupportsFloat) -> float: ... + +if sys.version_info >= (3, 8): + def perm(__n: int, __k: Optional[int] = ...) -> int: ... + def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... + if sys.version_info >= (3, 8): @overload def prod(__iterable: Iterable[int], *, start: int = ...) -> int: ... # type: ignore @overload def prod(__iterable: Iterable[SupportsFloat], *, start: SupportsFloat = ...) -> float: ... + def radians(__x: SupportsFloat) -> float: ... + if sys.version_info >= (3, 7): def remainder(__x: SupportsFloat, __y: 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: ... + +if sys.version_info >= (3, 9): + def ulp(__x: SupportsFloat) -> float: ... diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index 0d5a528d0b87..43f27dda4d7b 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -1,19 +1,15 @@ -# Stubs for mimetypes - -from typing import Dict, IO, List, Optional, Sequence, Text, Tuple, AnyStr, Union import sys +from typing import IO, Dict, List, Optional, Sequence, Text, Tuple, Union 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: Union[Text, PathLike[str]], strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + else: - def guess_type(url: Text, - strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + 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(filename: str) -> Optional[Dict[str, str]]: ... def add_type(type: str, ext: str, strict: bool = ...) -> None: ... @@ -30,15 +26,11 @@ class MimeTypes: 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 __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': + if sys.platform == "win32": def read_windows_registry(self, strict: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index fd60907128cc..7039e3da9870 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,7 +1,6 @@ import sys -from typing import (Optional, Sequence, Union, Generic, overload, - Iterable, Iterator, Sized, ContextManager, AnyStr) from _typeshed import ReadableBuffer +from typing import AnyStr, ContextManager, Generic, Iterable, Iterator, Optional, Sequence, Sized, Union, overload ACCESS_DEFAULT: int ACCESS_READ: int @@ -10,7 +9,7 @@ ACCESS_COPY: int ALLOCATIONGRANULARITY: int -if sys.platform != 'win32': +if sys.platform != "win32": MAP_ANON: int MAP_ANONYMOUS: int MAP_DENYWRITE: int @@ -24,15 +23,14 @@ if sys.platform != 'win32': 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: ... + 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 __init__( + self, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ... + ) -> None: ... def close(self) -> None: ... if sys.version_info >= (3, 8): def flush(self, offset: int = ..., size: int = ...) -> None: ... @@ -72,6 +70,7 @@ if sys.version_info >= (3,): # 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: ... diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index a3df358b5a45..89119b6029df 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -1,6 +1,6 @@ import sys -from typing import Optional, Container, Dict, Sequence, Tuple, List, Any, Iterator, IO, Iterable from types import CodeType +from typing import IO, Any, Container, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple LOAD_CONST: int # undocumented IMPORT_NAME: int # undocumented @@ -10,12 +10,14 @@ 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: ... @@ -30,15 +32,29 @@ class ModuleFinder: replace_paths: Sequence[Tuple[str, str]] # undocumented if sys.version_info >= (3, 8): - def __init__(self, path: Optional[List[str]] = ..., debug: int = ..., excludes: Optional[Container[str]] = ..., replace_paths: Optional[Sequence[Tuple[str, str]]] = ...) -> None: ... + def __init__( + self, + path: Optional[List[str]] = ..., + debug: int = ..., + excludes: Optional[Container[str]] = ..., + replace_paths: Optional[Sequence[Tuple[str, str]]] = ..., + ) -> None: ... else: - def __init__(self, path: Optional[List[str]] = ..., debug: int = ..., excludes: Container[str] = ..., replace_paths: Sequence[Tuple[str, str]] = ...) -> None: ... + 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 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 @@ -51,7 +67,9 @@ class ModuleFinder: 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 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 diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index 0cfe0dc27c20..0442ffaaec83 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,9 +1,9 @@ import sys -from typing import List, Tuple, Union, Set, Optional, Dict, Container, Any, Type, Iterable, Sequence 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': +if sys.platform == "win32": from _msi import _Database AMD64: bool @@ -11,52 +11,51 @@ if sys.platform == 'win32': Itanium: bool Win64: bool - datasizemask: Literal[0x00ff] + datasizemask: Literal[0x00FF] type_valid: Literal[0x0100] type_localizable: Literal[0x0200] - typemask: Literal[0x0c00] + typemask: Literal[0x0C00] type_long: Literal[0x0000] type_short: Literal[0x0400] - type_string: Literal[0x0c00] + type_string: Literal[0x0C00] type_binary: Literal[0x0800] type_nullable: Literal[0x1000] type_key: Literal[0x2000] - knownbits: Literal[0x3fff] - + 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 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 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 @@ -70,46 +69,65 @@ if sys.platform == 'win32': 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 __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 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 __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 @@ -118,12 +136,61 @@ if sys.platform == 'win32': 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 __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: ... + 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/msilib/schema.pyi b/mypy/typeshed/stdlib/msilib/schema.pyi index 251e1ea394ec..10b65088cf80 100644 --- a/mypy/typeshed/stdlib/msilib/schema.pyi +++ b/mypy/typeshed/stdlib/msilib/schema.pyi @@ -1,8 +1,7 @@ - import sys -from typing import List, Tuple, Optional +from typing import List, Optional, Tuple -if sys.platform == 'win32': +if sys.platform == "win32": from . import Table _Validation: Table @@ -93,4 +92,6 @@ if sys.platform == 'win32': tables: List[Table] - _Validation_records: List[Tuple[str, str, str, Optional[int], Optional[int], Optional[str], Optional[int], Optional[str], Optional[str], str]] + _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/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi index 4f75d0dd34ef..e4f400d33233 100644 --- a/mypy/typeshed/stdlib/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/msilib/sequence.pyi @@ -1,8 +1,7 @@ - import sys -from typing import List, Tuple, Optional +from typing import List, Optional, Tuple -if sys.platform == 'win32': +if sys.platform == "win32": _SequenceType = List[Tuple[str, Optional[str], int]] diff --git a/mypy/typeshed/stdlib/msilib/text.pyi b/mypy/typeshed/stdlib/msilib/text.pyi index c27aebb524c0..e338b8b5ba3d 100644 --- a/mypy/typeshed/stdlib/msilib/text.pyi +++ b/mypy/typeshed/stdlib/msilib/text.pyi @@ -1,8 +1,7 @@ - import sys -from typing import List, Tuple, Optional +from typing import List, Optional, Tuple -if sys.platform == 'win32': +if sys.platform == "win32": ActionText: List[Tuple[str, str, Optional[str]]] UIText: List[Tuple[str, Optional[str]]] diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index bfbb67a2872c..ede80c9fbb66 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -1,14 +1,24 @@ -# Stubs for msvcrt +import sys +from typing import Text -# NOTE: These are incomplete! - -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 get_osfhandle(__fd: int) -> int: ... -def open_osfhandle(__handle: int, __flags: int) -> int: ... +# 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/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index fb8021ffe6d8..c7de0a2d0cad 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -1,9 +1,6 @@ import sys -from typing import Any, Callable, Iterable, Optional, List, Union, Sequence, Tuple, Type, overload -from typing_extensions import Literal -from ctypes import _CData from logging import Logger -from multiprocessing import connection, pool, spawn, synchronize +from multiprocessing import connection, pool, sharedctypes, synchronize from multiprocessing.context import ( AuthenticationError as AuthenticationError, BaseContext, @@ -16,9 +13,12 @@ from multiprocessing.context import ( ) from multiprocessing.managers import SyncManager from multiprocessing.process import active_children as active_children, current_process as current_process -from multiprocessing.queues import Queue as Queue, SimpleQueue as SimpleQueue, JoinableQueue as JoinableQueue + +# These are technically functions that return instances of these Queue classes. See #4313 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 multiprocessing.spawn import set_executable as set_executable +from typing import Any, Callable, Iterable, List, Optional, Sequence, Tuple, Union, overload +from typing_extensions import Literal if sys.version_info >= (3, 8): from multiprocessing.process import parent_process as parent_process @@ -26,54 +26,33 @@ if sys.version_info >= (3, 8): if sys.platform != "win32": from multiprocessing.context import ForkContext, ForkServerContext - # 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). # Sychronization primitives _LockLike = Union[synchronize.Lock, synchronize.RLock] -def Barrier(parties: int, - action: Optional[Callable[..., Any]] = ..., - timeout: Optional[float] = ...) -> synchronize.Barrier: ... + +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(lock: Optional[_LockLike] = ...) -> synchronize.Event: ... +def Event() -> synchronize.Event: ... def Lock() -> synchronize.Lock: ... def RLock() -> synchronize.RLock: ... def Semaphore(value: int = ...) -> synchronize.Semaphore: ... - def Pipe(duplex: bool = ...) -> Tuple[connection.Connection, connection.Connection]: ... +def Pool( + processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., +) -> pool.Pool: ... -def Pool(processes: Optional[int] = ..., - initializer: Optional[Callable[..., Any]] = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... - -class Array: - value: Any = ... - - def __init__(self, typecode_or_type: Union[str, Type[_CData]], size_or_initializer: Union[int, Sequence[Any]], *, lock: Union[bool, _LockLike] = ...) -> None: ... - def acquire(self) -> bool: ... - def release(self) -> bool: ... - def get_lock(self) -> _LockLike: ... - def get_obj(self) -> Any: ... - - @overload - def __getitem__(self, key: int) -> Any: ... - @overload - def __getitem__(self, key: slice) -> List[Any]: ... - def __getslice__(self, start: int, stop: int) -> Any: ... - def __setitem__(self, key: int, value: Any) -> None: ... - - -class Value(): - value: Any = ... - def __init__(self, typecode_or_type: Union[str, Type[_CData]], *args: Any, lock: Union[bool, _LockLike] = ...) -> None: ... - def get_lock(self) -> _LockLike: ... - def get_obj(self) -> Any: ... - def acquire(self) -> bool: ... - def release(self) -> bool: ... +# Functions Array and Value are copied from context.pyi. +# See https://github.com/python/typeshed/blob/ac234f25927634e06d9c96df98d72d54dd80dfc4/stdlib/2and3/turtle.pyi#L284-L291 +# for rationale +def Array(typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]], *, lock: bool = ...) -> sharedctypes._Array: ... +def Value(typecode_or_type: Any, *args: Any, lock: bool = ...) -> sharedctypes._Value: ... # ----- multiprocessing function stubs ----- def allow_connection_pickling() -> None: ... @@ -81,12 +60,12 @@ def cpu_count() -> int: ... def get_logger() -> Logger: ... def log_to_stderr(level: Optional[Union[str, int]] = ...) -> Logger: ... def Manager() -> SyncManager: ... +def set_executable(executable: str) -> None: ... def set_forkserver_preload(module_names: List[str]) -> None: ... def get_all_start_methods() -> List[str]: ... def get_start_method(allow_none: bool = ...) -> Optional[str]: ... def set_start_method(method: str, force: Optional[bool] = ...) -> None: ... - if sys.platform != "win32": @overload def get_context(method: None = ...) -> DefaultContext: ... @@ -98,6 +77,7 @@ if sys.platform != "win32": def get_context(method: Literal["forkserver"]) -> ForkServerContext: ... @overload def get_context(method: str) -> BaseContext: ... + else: @overload def get_context(method: None = ...) -> DefaultContext: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 0fb97b107a9f..15f58a3745f3 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -1,7 +1,7 @@ -from typing import Any, Iterable, List, Optional, Tuple, Type, Union import socket import sys import types +from typing import Any, Iterable, List, Optional, Tuple, Type, Union if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -14,7 +14,6 @@ class _ConnectionBase: def __init__(self, handle: SupportsIndex, readable: bool = ..., writable: bool = ...) -> None: ... else: def __init__(self, handle: int, readable: bool = ..., writable: bool = ...) -> None: ... - @property def closed(self) -> bool: ... # undocumented @property @@ -23,17 +22,16 @@ class _ConnectionBase: def writable(self) -> bool: ... # undocumented def fileno(self) -> int: ... def close(self) -> None: ... - def send_bytes(self, - buf: bytes, - offset: int = ..., - size: Optional[int] = ...) -> None: ... + def send_bytes(self, buf: bytes, offset: int = ..., size: Optional[int] = ...) -> None: ... def send(self, obj: Any) -> None: ... def recv_bytes(self, maxlength: Optional[int] = ...) -> bytes: ... def recv_bytes_into(self, buf: Any, offset: int = ...) -> int: ... def recv(self) -> Any: ... def poll(self, timeout: Optional[float] = ...) -> bool: ... def __enter__(self) -> _ConnectionBase: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType] + ) -> None: ... class Connection(_ConnectionBase): ... @@ -41,7 +39,9 @@ if sys.platform == "win32": class PipeConnection(_ConnectionBase): ... class Listener: - def __init__(self, address: Optional[_Address] = ..., family: Optional[str] = ..., backlog: int = ..., authkey: Optional[bytes] = ...) -> None: ... + def __init__( + self, address: Optional[_Address] = ..., family: Optional[str] = ..., backlog: int = ..., authkey: Optional[bytes] = ... + ) -> None: ... def accept(self) -> Connection: ... def close(self) -> None: ... @property @@ -49,10 +49,14 @@ class Listener: @property def last_accepted(self) -> Optional[_Address]: ... def __enter__(self) -> Listener: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType] + ) -> None: ... def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... def answer_challenge(connection: Connection, authkey: bytes) -> None: ... -def wait(object_list: Iterable[Union[Connection, socket.socket, int]], timeout: Optional[float] = ...) -> List[Union[Connection, socket.socket, int]]: ... +def wait( + object_list: Iterable[Union[Connection, socket.socket, int]], timeout: Optional[float] = ... +) -> List[Union[Connection, socket.socket, int]]: ... def Client(address: _Address, family: Optional[str] = ..., authkey: Optional[bytes] = ...) -> Connection: ... def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index ced1d26ebae2..5f39d45dc32a 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -1,20 +1,16 @@ -from logging import Logger import multiprocessing -from multiprocessing import synchronize -from multiprocessing import queues -from multiprocessing.process import BaseProcess import sys -from typing import Any, Callable, Iterable, Optional, List, Sequence, Type, Union, overload +from logging import Logger +from multiprocessing import queues, sharedctypes, synchronize +from multiprocessing.process import BaseProcess +from typing import Any, Callable, Iterable, List, Optional, Sequence, Type, Union, overload from typing_extensions import Literal _LockLike = Union[synchronize.Lock, synchronize.RLock] class ProcessError(Exception): ... - class BufferTooShort(ProcessError): ... - class TimeoutError(ProcessError): ... - class AuthenticationError(ProcessError): ... class BaseContext(object): @@ -26,7 +22,6 @@ class BaseContext(object): # N.B. The methods below are applied at runtime to generate # multiprocessing.*, so the signatures should be identical (modulo self). - @staticmethod def current_process() -> BaseProcess: ... if sys.version_info >= (3, 8): @@ -39,20 +34,15 @@ class BaseContext(object): def Manager(self) -> Any: ... # TODO: change return to Pipe once a stub exists in multiprocessing.connection def Pipe(self, duplex: bool = ...) -> Any: ... - - def Barrier(self, - parties: int, - action: Optional[Callable[..., Any]] = ..., - timeout: Optional[float] = ...) -> synchronize.Barrier: ... - def BoundedSemaphore(self, - value: int = ...) -> synchronize.BoundedSemaphore: ... - def Condition(self, - lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... - def Event(self, lock: Optional[_LockLike] = ...) -> synchronize.Event: ... + def Barrier( + self, parties: int, action: Optional[Callable[..., Any]] = ..., timeout: Optional[float] = ... + ) -> synchronize.Barrier: ... + def BoundedSemaphore(self, value: int = ...) -> synchronize.BoundedSemaphore: ... + def Condition(self, lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... + def Event(self) -> synchronize.Event: ... def Lock(self) -> synchronize.Lock: ... def RLock(self) -> synchronize.RLock: ... def Semaphore(self, value: int = ...) -> synchronize.Semaphore: ... - def Queue(self, maxsize: int = ...) -> queues.Queue[Any]: ... def JoinableQueue(self, maxsize: int = ...) -> queues.JoinableQueue[Any]: ... def SimpleQueue(self) -> queues.SimpleQueue[Any]: ... @@ -61,7 +51,7 @@ class BaseContext(object): processes: Optional[int] = ..., initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ..., - maxtasksperchild: Optional[int] = ... + maxtasksperchild: Optional[int] = ..., ) -> multiprocessing.pool.Pool: ... # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out # how to handle the ctype @@ -73,30 +63,18 @@ class BaseContext(object): def RawArray(self, typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]]) -> Any: ... # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out # how to handle the ctype - # TODO: change return to Value once a stub exists in multiprocessing.sharedctypes - def Value( - self, - typecode_or_type: Any, - *args: Any, - lock: bool = ... - ) -> Any: ... + def Value(self, typecode_or_type: Any, *args: Any, lock: bool = ...) -> sharedctypes._Value: ... # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out # how to handle the ctype - # TODO: change return to Array once a stub exists in multiprocessing.sharedctypes def Array( - self, - typecode_or_type: Any, - size_or_initializer: Union[int, Sequence[Any]], - *, - lock: bool = ... - ) -> Any: ... + self, typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]], *, lock: bool = ... + ) -> sharedctypes._Array: ... def freeze_support(self) -> None: ... def get_logger(self) -> Logger: ... def log_to_stderr(self, level: Optional[str] = ...) -> Logger: ... def allow_connection_pickling(self) -> None: ... def set_executable(self, executable: str) -> None: ... def set_forkserver_preload(self, module_names: List[str]) -> None: ... - if sys.platform != "win32": @overload def get_context(self, method: None = ...) -> DefaultContext: ... @@ -115,7 +93,6 @@ class BaseContext(object): def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... @overload def get_context(self, method: str) -> BaseContext: ... - def get_start_method(self, allow_none: bool = ...) -> str: ... def set_start_method(self, method: Optional[str], force: bool = ...) -> None: ... @property @@ -131,45 +108,39 @@ class Process(BaseProcess): class DefaultContext(BaseContext): Process: Type[multiprocessing.Process] - def __init__(self, context: BaseContext) -> None: ... def set_start_method(self, method: Optional[str], force: bool = ...) -> None: ... def get_start_method(self, allow_none: bool = ...) -> str: ... def get_all_start_methods(self) -> List[str]: ... -if sys.platform != 'win32': +if sys.platform != "win32": class ForkProcess(BaseProcess): _start_method: str @staticmethod def _Popen(process_obj: BaseProcess) -> Any: ... - class SpawnProcess(BaseProcess): _start_method: str @staticmethod def _Popen(process_obj: BaseProcess) -> SpawnProcess: ... - class ForkServerProcess(BaseProcess): _start_method: str @staticmethod def _Popen(process_obj: BaseProcess) -> Any: ... - class ForkContext(BaseContext): _name: str Process: Type[ForkProcess] - class SpawnContext(BaseContext): _name: str Process: Type[SpawnProcess] - class ForkServerContext(BaseContext): _name: str Process: Type[ForkServerProcess] + else: class SpawnProcess(BaseProcess): _start_method: str @staticmethod def _Popen(process_obj: BaseProcess) -> Any: ... - class SpawnContext(BaseContext): _name: str Process: Type[SpawnProcess] diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi index 5d07f6d9c93c..0089defc0099 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi @@ -1,10 +1,8 @@ -from typing import Any, Optional, List - import array import threading import weakref - from queue import Queue as Queue +from typing import Any, Callable, Iterable, List, Mapping, Optional, Sequence JoinableQueue = Queue Barrier = threading.Barrier @@ -21,7 +19,14 @@ class DummyProcess(threading.Thread): _pid: None _start_called: int exitcode: Optional[int] - def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + def __init__( + self, + group: Any = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + ) -> None: ... Process = DummyProcess @@ -34,12 +39,13 @@ class Value: _typecode: Any _value: Any value: Any - def __init__(self, typecode, value, lock=...) -> None: ... - + def __init__(self, typecode: Any, value: Any, lock: Any = ...) -> None: ... -def Array(typecode, sequence, lock=...) -> array.array[Any]: ... +def Array(typecode: Any, sequence: Sequence[Any], lock: Any = ...) -> array.array[Any]: ... def Manager() -> Any: ... -def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def Pool( + processes: Optional[int] = ..., initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ... +) -> Any: ... def active_children() -> List[Any]: ... def current_process() -> threading.Thread: ... def freeze_support() -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi index d465a5b4f434..01733e59c763 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi @@ -1,11 +1,12 @@ -from typing import Any, List, Optional, Tuple, TypeVar - from queue import Queue +from types import TracebackType +from typing import Any, List, Optional, Tuple, Type, TypeVar, Union families: List[None] -_TConnection = TypeVar('_TConnection', bound=Connection) -_TListener = TypeVar('_TListener', bound=Listener) +_ConnectionT = TypeVar("_ConnectionT", bound=Connection) +_ListenerT = TypeVar("_ListenerT", bound=Listener) +_Address = Union[str, Tuple[str, int]] class Connection(object): _in: Any @@ -14,9 +15,11 @@ class Connection(object): recv_bytes: Any send: Any send_bytes: Any - def __enter__(self: _TConnection) -> _TConnection: ... - def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... - def __init__(self, _in, _out) -> None: ... + def __enter__(self: _ConnectionT) -> _ConnectionT: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def __init__(self, _in: Any, _out: Any) -> None: ... def close(self) -> None: ... def poll(self, timeout: float = ...) -> bool: ... @@ -24,12 +27,13 @@ class Listener(object): _backlog_queue: Optional[Queue[Any]] @property def address(self) -> Optional[Queue[Any]]: ... - def __enter__(self: _TListener) -> _TListener: ... - def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... - def __init__(self, address=..., family=..., backlog=...) -> None: ... + def __enter__(self: _ListenerT) -> _ListenerT: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... + def __init__(self, address: Optional[_Address] = ..., family: Optional[int] = ..., backlog: int = ...) -> None: ... def accept(self) -> Connection: ... def close(self) -> None: ... - -def Client(address) -> Connection: ... +def Client(address: _Address) -> Connection: ... def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 528a18038041..9cc671363f0b 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -1,22 +1,40 @@ -# Stubs for multiprocessing.managers - # NOTE: These are incomplete! import queue import sys import threading from typing import ( - Any, Callable, ContextManager, Dict, Iterable, Generic, List, Mapping, Optional, - Sequence, Tuple, TypeVar, Union, AnyStr, + Any, + AnyStr, + Callable, + ContextManager, + Dict, + Generic, + Iterable, + List, + Mapping, + Optional, + Sequence, + Tuple, + TypeVar, + Union, ) + +from .connection import Connection from .context import BaseContext if sys.version_info >= (3, 8): - from .shared_memory import ShareableList, SharedMemory, _SLT + from .shared_memory import _SLT, ShareableList, SharedMemory + + _SharedMemory = SharedMemory + _ShareableList = ShareableList + +if sys.version_info >= (3, 9): + from types import GenericAlias -_T = TypeVar('_T') -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") class Namespace: def __init__(self, **kwds: Any) -> None: ... @@ -29,28 +47,32 @@ class Token(object): typeid: Optional[Union[str, bytes]] address: Tuple[Union[str, bytes], int] id: Optional[Union[str, bytes, int]] - def __init__(self, typeid: Optional[Union[bytes, str]], address: Tuple[Union[str, bytes], int], - id: Optional[Union[str, bytes, int]]) -> None: ... + def __init__( + self, typeid: Optional[Union[bytes, str]], address: Tuple[Union[str, bytes], int], id: Optional[Union[str, bytes, int]] + ) -> None: ... def __repr__(self) -> str: ... - def __getstate__(self) -> Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], - Optional[Union[str, bytes, int]]]: ... - def __setstate__(self, state: Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], - Optional[Union[str, bytes, int]]]) -> None: ... + def __getstate__( + self, + ) -> Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], Optional[Union[str, bytes, int]]]: ... + def __setstate__( + self, state: Tuple[Optional[Union[str, bytes]], Tuple[Union[str, bytes], int], Optional[Union[str, bytes, int]]] + ) -> None: ... class BaseProxy(object): _address_to_local: Dict[Any, Any] _mutex: Any - if sys.version_info >= (3, 6): - def __init__(self, token: Any, serializer: str, manager: Any = ..., - authkey: Optional[AnyStr] = ..., exposed: Any = ..., - incref: bool = ..., manager_owned: bool = ...) -> None: ... - else: - def __init__(self, token: Any, serializer: str, manager: Any = ..., - authkey: Optional[AnyStr] = ..., exposed: Any = ..., - incref: bool = ...) -> None: ... + def __init__( + self, + token: Any, + serializer: str, + manager: Any = ..., + authkey: Optional[AnyStr] = ..., + exposed: Any = ..., + incref: bool = ..., + manager_owned: bool = ..., + ) -> None: ... def __deepcopy__(self, memo: Optional[Any]) -> Any: ... - def _callmethod(self, methodname: str, args: Tuple[Any, ...] = ..., - kwds: Dict[Any, Any] = ...) -> None: ... + def _callmethod(self, methodname: str, args: Tuple[Any, ...] = ..., kwds: Dict[Any, Any] = ...) -> None: ... def _getvalue(self) -> Any: ... def __reduce__(self) -> Tuple[Any, Tuple[Any, Any, str, Dict[Any, Any]]]: ... @@ -58,11 +80,17 @@ class ValueProxy(BaseProxy, Generic[_T]): def get(self) -> _T: ... def set(self, value: _T) -> None: ... value: _T + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # Returned by BaseManager.get_server() class Server: address: Any + def __init__( + self, registry: Dict[str, Tuple[Callable[..., Any], Any, Any, Any]], address: Any, authkey: bytes, serializer: str + ) -> None: ... def serve_forever(self) -> None: ... + def accept_connection(self, c: Connection, name: str) -> None: ... class BaseManager(ContextManager[BaseManager]): def __init__( @@ -80,11 +108,15 @@ class BaseManager(ContextManager[BaseManager]): @property def address(self) -> Any: ... @classmethod - def register(cls, typeid: str, callable: Optional[Callable[..., Any]] = ..., - proxytype: Any = ..., - exposed: Optional[Sequence[str]] = ..., - method_to_typeid: Optional[Mapping[str, str]] = ..., - create_method: bool = ...) -> None: ... + def register( + cls, + typeid: str, + callable: Optional[Callable[..., Any]] = ..., + proxytype: Any = ..., + exposed: Optional[Sequence[str]] = ..., + method_to_typeid: Optional[Mapping[str, str]] = ..., + create_method: bool = ..., + ) -> None: ... class SyncManager(BaseManager, ContextManager[SyncManager]): def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... @@ -106,5 +138,5 @@ if sys.version_info >= (3, 8): class SharedMemoryServer(Server): ... class SharedMemoryManager(BaseManager): def get_server(self) -> SharedMemoryServer: ... - def SharedMemory(self, size: int) -> SharedMemory: ... # noqa: F811 - def ShareableList(self, sequence: Optional[Iterable[_SLT]]) -> ShareableList[_SLT]: ... # noqa: F811 + def SharedMemory(self, size: int) -> _SharedMemory: ... + def ShareableList(self, sequence: Optional[Iterable[_SLT]]) -> _ShareableList[_SLT]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 5d37644306e7..40e5ec46f49b 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,14 +1,20 @@ -from typing import Any, Callable, ContextManager, Iterable, Mapping, Optional, List, TypeVar, Generic, Iterator +import sys +from typing import Any, Callable, ContextManager, Generic, Iterable, Iterator, List, Mapping, Optional, TypeVar -_PT = TypeVar('_PT', bound=Pool) -_S = TypeVar('_S') -_T = TypeVar('_T') +if sys.version_info >= (3, 9): + from types import GenericAlias + +_PT = TypeVar("_PT", bound=Pool) +_S = TypeVar("_S") +_T = TypeVar("_T") class ApplyResult(Generic[_T]): def get(self, timeout: Optional[float] = ...) -> _T: ... def wait(self, timeout: Optional[float] = ...) -> None: ... def ready(self) -> bool: ... def successful(self) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # alias created during issue #17805 AsyncResult = ApplyResult @@ -23,61 +29,62 @@ class IMapIterator(Iterator[_T]): class IMapUnorderedIterator(IMapIterator[_T]): ... class Pool(ContextManager[Pool]): - def __init__(self, processes: Optional[int] = ..., - initializer: Optional[Callable[..., None]] = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: Optional[int] = ..., - context: Optional[Any] = ...) -> None: ... - def apply(self, - func: Callable[..., _T], - args: Iterable[Any] = ..., - kwds: Mapping[str, Any] = ...) -> _T: ... - def apply_async(self, - func: Callable[..., _T], - args: Iterable[Any] = ..., - kwds: Mapping[str, Any] = ..., - callback: Optional[Callable[[_T], None]] = ..., - error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[_T]: ... - def map(self, - func: Callable[[_S], _T], - iterable: Iterable[_S] = ..., - chunksize: Optional[int] = ...) -> List[_T]: ... - def map_async(self, func: Callable[[_S], _T], - iterable: Iterable[_S] = ..., - chunksize: Optional[int] = ..., - callback: Optional[Callable[[_T], None]] = ..., - error_callback: Optional[Callable[[BaseException], None]] = ...) -> MapResult[_T]: ... - def imap(self, - func: Callable[[_S], _T], - iterable: Iterable[_S] = ..., - chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... - def imap_unordered(self, - func: Callable[[_S], _T], - iterable: Iterable[_S] = ..., - chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... - def starmap(self, - func: Callable[..., _T], - iterable: Iterable[Iterable[Any]] = ..., - chunksize: Optional[int] = ...) -> List[_T]: ... - def starmap_async(self, - func: Callable[..., _T], - iterable: Iterable[Iterable[Any]] = ..., - chunksize: Optional[int] = ..., - callback: Optional[Callable[[_T], None]] = ..., - error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[List[_T]]: ... + def __init__( + self, + processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., + context: Optional[Any] = ..., + ) -> None: ... + def apply(self, func: Callable[..., _T], args: Iterable[Any] = ..., kwds: Mapping[str, Any] = ...) -> _T: ... + def apply_async( + self, + func: Callable[..., _T], + args: Iterable[Any] = ..., + kwds: Mapping[str, Any] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ..., + ) -> AsyncResult[_T]: ... + def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: Optional[int] = ...) -> List[_T]: ... + def map_async( + self, + func: Callable[[_S], _T], + iterable: Iterable[_S], + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ..., + ) -> MapResult[_T]: ... + def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... + def imap_unordered( + self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: Optional[int] = ... + ) -> IMapIterator[_T]: ... + def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: Optional[int] = ...) -> List[_T]: ... + def starmap_async( + self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]], + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ..., + ) -> AsyncResult[List[_T]]: ... def close(self) -> None: ... def terminate(self) -> None: ... def join(self) -> None: ... def __enter__(self: _PT) -> _PT: ... - class ThreadPool(Pool, ContextManager[ThreadPool]): - - def __init__(self, processes: Optional[int] = ..., - initializer: Optional[Callable[..., Any]] = ..., - initargs: Iterable[Any] = ...) -> None: ... + def __init__( + self, processes: Optional[int] = ..., initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ... + ) -> None: ... # undocumented -RUN: int -CLOSE: int -TERMINATE: int +if sys.version_info >= (3, 8): + INIT: str + RUN: str + CLOSE: str + TERMINATE: str +else: + RUN: int + CLOSE: int + TERMINATE: int diff --git a/mypy/typeshed/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi index a979ee7b283d..f2d0b5740baf 100644 --- a/mypy/typeshed/stdlib/multiprocessing/process.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/process.pyi @@ -34,5 +34,6 @@ class BaseProcess: def current_process() -> BaseProcess: ... def active_children() -> List[BaseProcess]: ... + if sys.version_info >= (3, 8): def parent_process() -> Optional[BaseProcess]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/queues.pyi b/mypy/typeshed/stdlib/multiprocessing/queues.pyi index c6dd0f20d631..3d61e44e67c5 100644 --- a/mypy/typeshed/stdlib/multiprocessing/queues.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/queues.pyi @@ -1,8 +1,11 @@ +import queue +import sys from typing import Any, Generic, Optional, TypeVar -import queue +if sys.version_info >= (3, 9): + from types import GenericAlias -_T = TypeVar('_T') +_T = TypeVar("_T") class Queue(queue.Queue[_T]): # FIXME: `ctx` is a circular dependency and it's not actually optional. @@ -28,3 +31,5 @@ class SimpleQueue(Generic[_T]): def empty(self) -> bool: ... def get(self) -> _T: ... def put(self, item: _T) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index 6a16a09a60ef..cf8b68bfc0da 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,5 +1,8 @@ import sys -from typing import Generic, Iterable, Optional, Tuple, TypeVar +from typing import Any, Generic, Iterable, Optional, Tuple, TypeVar + +if sys.version_info >= (3, 9): + from types import GenericAlias _S = TypeVar("_S") _SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) @@ -15,7 +18,6 @@ if sys.version_info >= (3, 8): def size(self) -> int: ... def close(self) -> None: ... def unlink(self) -> None: ... - class ShareableList(Generic[_SLT]): shm: SharedMemory def __init__(self, sequence: Optional[Iterable[_SLT]] = ..., *, name: Optional[str] = ...) -> None: ... @@ -27,3 +29,5 @@ if sys.version_info >= (3, 8): def format(self) -> str: ... def count(self, value: _SLT) -> int: ... def index(self, value: _SLT) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi new file mode 100644 index 000000000000..3979b0947287 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -0,0 +1,43 @@ +from ctypes import _CData +from multiprocessing.context import BaseContext +from multiprocessing.synchronize import _LockLike +from typing import Any, List, Optional, Sequence, Type, Union, overload + +class _Array: + value: Any = ... + def __init__( + self, + typecode_or_type: Union[str, Type[_CData]], + size_or_initializer: Union[int, Sequence[Any]], + *, + lock: Union[bool, _LockLike] = ..., + ) -> None: ... + def acquire(self) -> bool: ... + def release(self) -> bool: ... + def get_lock(self) -> _LockLike: ... + def get_obj(self) -> Any: ... + @overload + def __getitem__(self, key: int) -> Any: ... + @overload + def __getitem__(self, key: slice) -> List[Any]: ... + def __getslice__(self, start: int, stop: int) -> Any: ... + def __setitem__(self, key: int, value: Any) -> None: ... + +class _Value: + value: Any = ... + def __init__(self, typecode_or_type: Union[str, Type[_CData]], *args: Any, lock: Union[bool, _LockLike] = ...) -> None: ... + def get_lock(self) -> _LockLike: ... + def get_obj(self) -> Any: ... + def acquire(self) -> bool: ... + def release(self) -> bool: ... + +def Array( + typecode_or_type: Union[str, Type[_CData]], + size_or_initializer: Union[int, Sequence[Any]], + *, + lock: Union[bool, _LockLike] = ..., + ctx: Optional[BaseContext] = ..., +) -> _Array: ... +def Value( + typecode_or_type: Union[str, Type[_CData]], *args: Any, lock: Union[bool, _LockLike] = ..., ctx: Optional[BaseContext] = ... +) -> _Value: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi index 9d170f6f2cc4..0faee1754f93 100644 --- a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi @@ -1,5 +1,5 @@ -from typing import Any, Dict, List, Mapping, Optional, Sequence from types import ModuleType +from typing import Any, Dict, List, Mapping, Optional, Sequence WINEXE: bool WINSERVICE: bool @@ -10,9 +10,12 @@ def is_forking(argv: Sequence[str]) -> bool: ... def freeze_support() -> None: ... def get_command_line(**kwds: Any) -> List[str]: ... def spawn_main(pipe_handle: int, parent_pid: Optional[int] = ..., tracker_fd: Optional[int] = ...) -> None: ... + # undocumented def _main(fd: int) -> Any: ... def get_preparation_data(name: str) -> Dict[str, Any]: ... + old_main_modules: List[ModuleType] + def prepare(data: Mapping[str, Any]) -> None: ... def import_main_path(main_path: str) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index 224485b317ba..7eefc7676b66 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -1,46 +1,32 @@ -from typing import Any, Callable, ContextManager, Optional, Union - -from multiprocessing.context import BaseContext -import threading import sys +import threading +from multiprocessing.context import BaseContext +from typing import Any, Callable, ContextManager, Optional, Union _LockLike = Union[Lock, RLock] class Barrier(threading.Barrier): - def __init__(self, - parties: int, - action: Optional[Callable[..., Any]] = ..., - timeout: Optional[float] = ..., - * - ctx: BaseContext) -> None: ... + def __init__( + self, parties: int, action: Optional[Callable[..., Any]] = ..., timeout: Optional[float] = ..., *ctx: BaseContext + ) -> None: ... class BoundedSemaphore(Semaphore): def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... class Condition(ContextManager[bool]): - def __init__(self, - lock: Optional[_LockLike] = ..., - *, - ctx: BaseContext) -> None: ... + def __init__(self, lock: Optional[_LockLike] = ..., *, ctx: BaseContext) -> None: ... if sys.version_info >= (3, 7): def notify(self, n: int = ...) -> None: ... else: def notify(self) -> None: ... def notify_all(self) -> None: ... def wait(self, timeout: Optional[float] = ...) -> bool: ... - def wait_for(self, - predicate: Callable[[], bool], - timeout: Optional[float] = ...) -> bool: ... - def acquire(self, - block: bool = ..., - timeout: Optional[float] = ...) -> bool: ... + def wait_for(self, predicate: Callable[[], bool], timeout: Optional[float] = ...) -> bool: ... + def acquire(self, block: bool = ..., timeout: Optional[float] = ...) -> bool: ... def release(self) -> None: ... class Event(ContextManager[bool]): - def __init__(self, - lock: Optional[_LockLike] = ..., - *, - ctx: BaseContext) -> None: ... + def __init__(self, lock: Optional[_LockLike] = ..., *, ctx: BaseContext) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... @@ -57,7 +43,5 @@ class Semaphore(SemLock): # Not part of public API class SemLock(ContextManager[bool]): - def acquire(self, - block: bool = ..., - timeout: Optional[float] = ...) -> bool: ... + def acquire(self, block: bool = ..., timeout: Optional[float] = ...) -> bool: ... def release(self) -> None: ... diff --git a/mypy/typeshed/stdlib/mypy_extensions.pyi b/mypy/typeshed/stdlib/mypy_extensions.pyi index 9e756dd5f0ee..e5df53ff7dd2 100644 --- a/mypy/typeshed/stdlib/mypy_extensions.pyi +++ b/mypy/typeshed/stdlib/mypy_extensions.pyi @@ -1,12 +1,9 @@ import abc import sys -from typing import ( - Dict, Type, TypeVar, Optional, Union, Any, Generic, Mapping, ItemsView, KeysView, ValuesView, - Callable, -) +from typing import Any, Callable, Dict, Generic, ItemsView, KeysView, Mapping, Optional, Type, TypeVar, Union, ValuesView -_T = TypeVar('_T') -_U = TypeVar('_U') +_T = TypeVar("_T") +_U = TypeVar("_U") # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): @@ -29,7 +26,6 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def __delitem__(self, k: NoReturn) -> None: ... def TypedDict(typename: str, fields: Dict[str, Type[_T]], total: bool = ...) -> Type[Dict[str, Any]]: ... - def Arg(type: _T = ..., name: Optional[str] = ...) -> _T: ... def DefaultArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... def NamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... @@ -45,7 +41,6 @@ NoReturn = Union[None] # Deprecated: Use typing.NoReturn instead. # This is intended as a class decorator, but mypy rejects abstract classes # when a Type[_T] is expected, so we can't give it the type we want def trait(cls: Any) -> Any: ... - def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... class FlexibleAlias(Generic[_T, _U]): ... diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 3ceae889963b..50fe3c0e0e6c 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,19 +1,15 @@ -from typing import AnyStr, Dict, List, Optional, Tuple, overload - +from typing import Dict, List, Optional, Tuple class NetrcParseError(Exception): filename: Optional[str] lineno: Optional[int] msg: str - # (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: str = ...) -> None: ... def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/mypy/typeshed/stdlib/nis.pyi b/mypy/typeshed/stdlib/nis.pyi index 87223caf2e39..bc6c2bc07256 100644 --- a/mypy/typeshed/stdlib/nis.pyi +++ b/mypy/typeshed/stdlib/nis.pyi @@ -1,10 +1,9 @@ import sys from typing import Dict, List -if sys.platform != 'win32': +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/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 0a88ff150b5c..7e7b7b84c4f0 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -1,17 +1,15 @@ -# Stubs for nntplib (Python 3) - import datetime import socket import ssl import sys -from typing import Any, Dict, IO, Iterable, List, NamedTuple, Optional, Tuple, TypeVar, Union +from typing import IO, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, TypeVar, Union -_SelfT = TypeVar('_SelfT', bound=_NNTPBase) +_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): ... @@ -26,6 +24,7 @@ class GroupInfo(NamedTuple): last: str first: str flag: str + class ArticleInfo(NamedTuple): number: int message_id: str @@ -46,9 +45,7 @@ class _NNTPBase: authenticated: bool nntp_implementation: str nntp_version: int - - def __init__(self, file: IO[bytes], host: str, - readermode: Optional[bool] = ..., timeout: float = ...) -> None: ... + 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: ... @@ -57,7 +54,9 @@ class _NNTPBase: 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 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]]: ... @@ -72,7 +71,9 @@ class _NNTPBase: 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 over( + self, message_spec: Union[None, str, List[Any], Tuple[Any, ...]], *, file: _File = ... + ) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... if sys.version_info < (3, 9): def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... def xpath(self, id: Any) -> Tuple[str, str]: ... @@ -83,20 +84,30 @@ class _NNTPBase: def login(self, user: Optional[str] = ..., password: Optional[str] = ..., usenetrc: bool = ...) -> None: ... def starttls(self, ssl_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: ... - + 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: ... + 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/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index ef4b48331d89..9fe5a7df6c85 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -1,14 +1,11 @@ -# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! import os import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from _typeshed import AnyPath, BytesPath, StrPath +from builtins import _PathLike from genericpath import exists as exists -from _typeshed import StrPath, BytesPath, AnyPath +from typing import Any, AnyStr, Optional, Sequence, Tuple, TypeVar, overload -_T = TypeVar('_T') - -if sys.version_info >= (3, 6): - from builtins import _PathLike +_T = TypeVar("_T") # ----- os.path variables ----- supports_unicode_filenames: bool @@ -16,7 +13,7 @@ supports_unicode_filenames: bool curdir: str pardir: str sep: str -if sys.platform == 'win32': +if sys.platform == "win32": altsep: str else: altsep: Optional[str] @@ -26,72 +23,55 @@ defpath: str devnull: str # ----- os.path function stubs ----- -if sys.version_info >= (3, 6): - # Overloads are necessary to work around python/mypy#3644. - @overload - def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def abspath(path: AnyStr) -> AnyStr: ... - @overload - def basename(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(p: AnyStr) -> AnyStr: ... - @overload - def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(p: AnyStr) -> AnyStr: ... - @overload - def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expanduser(path: AnyStr) -> AnyStr: ... - @overload - def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expandvars(path: AnyStr) -> AnyStr: ... - @overload - def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(s: AnyStr) -> AnyStr: ... +# Overloads are necessary to work around python/mypy#3644. +@overload +def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def abspath(path: AnyStr) -> AnyStr: ... +@overload +def basename(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def basename(p: AnyStr) -> AnyStr: ... +@overload +def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def dirname(p: AnyStr) -> AnyStr: ... +@overload +def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expanduser(path: AnyStr) -> AnyStr: ... +@overload +def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expandvars(path: AnyStr) -> AnyStr: ... +@overload +def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normcase(s: AnyStr) -> AnyStr: ... +@overload +def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": @overload - def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... @overload - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - @overload - def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - else: - @overload - def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(filename: AnyStr) -> AnyStr: ... + def realpath(path: AnyStr) -> AnyStr: ... else: - def abspath(path: AnyStr) -> AnyStr: ... - def basename(p: AnyStr) -> AnyStr: ... - def dirname(p: AnyStr) -> AnyStr: ... - def expanduser(path: AnyStr) -> AnyStr: ... - def expandvars(path: AnyStr) -> AnyStr: ... - def normcase(s: AnyStr) -> AnyStr: ... - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - def realpath(path: AnyStr) -> AnyStr: ... - else: - def realpath(filename: AnyStr) -> AnyStr: ... + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... -if sys.version_info >= (3, 6): - # In reality it returns str for sequences of StrPath and bytes for sequences - # of BytesPath, but mypy does not accept such a signature. - def commonpath(paths: Sequence[AnyPath]) -> Any: ... -elif sys.version_info >= (3, 5): - def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... +# In reality it returns str for sequences of StrPath and bytes for sequences +# of BytesPath, but mypy does not accept such a signature. +def commonpath(paths: Sequence[AnyPath]) -> Any: ... # 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: ... # These return float if os.stat_float_times() == True, @@ -99,66 +79,35 @@ def lexists(path: AnyPath) -> bool: ... 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: ... - -if sys.version_info < (3, 0): - # 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: ... -elif sys.version_info >= (3, 6): - @overload - def join(a: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(a: BytesPath, *paths: BytesPath) -> bytes: ... -else: - def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... - +@overload +def join(a: StrPath, *paths: StrPath) -> str: ... +@overload +def join(a: BytesPath, *paths: BytesPath) -> bytes: ... @overload def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... - +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> str: ... 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: ... +@overload +def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -if sys.version_info >= (3, 6): - @overload - def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -else: - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.version_info < (3, 7) and sys.platform == 'win32': +if sys.version_info < (3, 7) and sys.platform == "win32": def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -if sys.version_info < (3,): - def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index befe7d53a781..4f8a5a5d67fc 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -1,13 +1,9 @@ -# Stubs for numbers (Python 3.5) -# See https://docs.python.org/2.7/library/numbers.html -# and https://docs.python.org/3/library/numbers.html -# # Note: these stubs are incomplete. The more complex type # signatures are currently omitted. -from typing import Any, Optional, SupportsFloat, overload -from abc import ABCMeta, abstractmethod import sys +from abc import ABCMeta, abstractmethod +from typing import Any, Optional, SupportsFloat, overload class Number(metaclass=ABCMeta): @abstractmethod @@ -22,42 +18,42 @@ class Complex(Number): def __nonzero__(self) -> bool: ... @property @abstractmethod - def real(self): ... + def real(self) -> Any: ... @property @abstractmethod - def imag(self): ... + def imag(self) -> Any: ... @abstractmethod - def __add__(self, other): ... + def __add__(self, other: Any) -> Any: ... @abstractmethod - def __radd__(self, other): ... + def __radd__(self, other: Any) -> Any: ... @abstractmethod - def __neg__(self): ... + def __neg__(self) -> Any: ... @abstractmethod - def __pos__(self): ... - def __sub__(self, other): ... - def __rsub__(self, other): ... + def __pos__(self) -> Any: ... + def __sub__(self, other: Any) -> Any: ... + def __rsub__(self, other: Any) -> Any: ... @abstractmethod - def __mul__(self, other): ... + def __mul__(self, other: Any) -> Any: ... @abstractmethod - def __rmul__(self, other): ... + 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): ... + def __truediv__(self, other: Any) -> Any: ... @abstractmethod - def __rtruediv__(self, other): ... + def __rtruediv__(self, other: Any) -> Any: ... @abstractmethod - def __pow__(self, exponent): ... + def __pow__(self, exponent: Any) -> Any: ... @abstractmethod - def __rpow__(self, base): ... - def __abs__(self): ... - def conjugate(self): ... - def __eq__(self, other: object) -> bool: ... + def __rpow__(self, base: Any) -> Any: ... + def __abs__(self) -> Real: ... + def conjugate(self) -> Any: ... + def __eq__(self, other: Any) -> bool: ... if sys.version_info < (3, 0): - def __ne__(self, other: object) -> bool: ... + def __ne__(self, other: Any) -> bool: ... class Real(Complex, SupportsFloat): @abstractmethod @@ -71,30 +67,30 @@ class Real(Complex, SupportsFloat): def __ceil__(self) -> int: ... @abstractmethod @overload - def __round__(self, ndigits: None = ...): ... + def __round__(self, ndigits: None = ...) -> int: ... @abstractmethod @overload - def __round__(self, ndigits: int): ... - def __divmod__(self, other): ... - def __rdivmod__(self, other): ... + def __round__(self, ndigits: int) -> Any: ... + def __divmod__(self, other: Any) -> Any: ... + def __rdivmod__(self, other: Any) -> Any: ... @abstractmethod - def __floordiv__(self, other): ... + def __floordiv__(self, other: Any) -> int: ... @abstractmethod - def __rfloordiv__(self, other): ... + def __rfloordiv__(self, other: Any) -> int: ... @abstractmethod - def __mod__(self, other): ... + def __mod__(self, other: Any) -> Any: ... @abstractmethod - def __rmod__(self, other): ... + def __rmod__(self, other: Any) -> Any: ... @abstractmethod - def __lt__(self, other) -> bool: ... + def __lt__(self, other: Any) -> bool: ... @abstractmethod - def __le__(self, other) -> bool: ... + def __le__(self, other: Any) -> bool: ... def __complex__(self) -> complex: ... @property - def real(self): ... + def real(self) -> Any: ... @property - def imag(self): ... - def conjugate(self): ... + def imag(self) -> Any: ... + def conjugate(self) -> Any: ... class Rational(Real): @property @@ -114,29 +110,29 @@ class Integral(Rational): def __long__(self) -> long: ... def __index__(self) -> int: ... @abstractmethod - def __pow__(self, exponent, modulus: Optional[Any] = ...): ... + def __pow__(self, exponent: Any, modulus: Optional[Any] = ...) -> Any: ... @abstractmethod - def __lshift__(self, other): ... + def __lshift__(self, other: Any) -> Any: ... @abstractmethod - def __rlshift__(self, other): ... + def __rlshift__(self, other: Any) -> Any: ... @abstractmethod - def __rshift__(self, other): ... + def __rshift__(self, other: Any) -> Any: ... @abstractmethod - def __rrshift__(self, other): ... + def __rrshift__(self, other: Any) -> Any: ... @abstractmethod - def __and__(self, other): ... + def __and__(self, other: Any) -> Any: ... @abstractmethod - def __rand__(self, other): ... + def __rand__(self, other: Any) -> Any: ... @abstractmethod - def __xor__(self, other): ... + def __xor__(self, other: Any) -> Any: ... @abstractmethod - def __rxor__(self, other): ... + def __rxor__(self, other: Any) -> Any: ... @abstractmethod - def __or__(self, other): ... + def __or__(self, other: Any) -> Any: ... @abstractmethod - def __ror__(self, other): ... + def __ror__(self, other: Any) -> Any: ... @abstractmethod - def __invert__(self): ... + def __invert__(self) -> Any: ... def __float__(self) -> float: ... @property def numerator(self) -> int: ... diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index b219670f5dec..6307c280aebe 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -1,6 +1,5 @@ -from typing import List, Dict, Optional, Sequence - import sys +from typing import Dict, List, Optional, Sequence cmp_op: Sequence[str] hasconst: List[int] @@ -18,6 +17,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): def stack_effect(__opcode: int, __oparg: Optional[int] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index e301b0df3480..f82d4c6671f5 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -1,16 +1,21 @@ -# Stubs for operator - +import sys from typing import ( - Any, Callable, Container, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, Tuple, - TypeVar, overload, + Any, + Callable, + Container, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + SupportsAbs, + Tuple, + TypeVar, + overload, ) -import sys - - -_T = TypeVar('_T') -_K = TypeVar('_K') -_V = TypeVar('_V') +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") def lt(__a: Any, __b: Any) -> Any: ... def le(__a: Any, __b: Any) -> Any: ... @@ -24,46 +29,34 @@ 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: ... -if sys.version_info < (3, ): +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: ... 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: ... @@ -73,36 +66,25 @@ if sys.version_info >= (3, 5): 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[_T], __b: int) -> None: ... @overload @@ -116,7 +98,7 @@ def __delitem__(a: MutableSequence[_T], b: slice) -> None: ... @overload def __delitem__(a: MutableMapping[_K, _V], b: _K) -> None: ... -if sys.version_info < (3, ): +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: ... @@ -133,17 +115,17 @@ def __getitem__(a: Sequence[_T], b: slice) -> Sequence[_T]: ... @overload def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... -if sys.version_info < (3, ): +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, ): +if sys.version_info < (3,): def repeat(a: Any, b: int) -> Any: ... def __repeat__(a: Any, b: int) -> Any: ... -if sys.version_info < (3, ): +if sys.version_info < (3,): def sequenceIncludes(a: Container[Any], b: Any) -> bool: ... @overload @@ -159,11 +141,10 @@ 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, ): +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: ... @@ -171,37 +152,28 @@ if sys.version_info >= (3, 4): def attrgetter(attr: str) -> Callable[[Any], Any]: ... @overload def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ... - @overload def itemgetter(item: Any) -> Callable[[Any], Any]: ... @overload def itemgetter(*items: Any) -> Callable[[Any], Tuple[Any, ...]]: ... - -def methodcaller(name: str, *args: Any, **kwargs: Any) -> Callable[..., Any]: ... - - +def methodcaller(__name: str, *args: Any, **kwargs: Any) -> Callable[..., 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: ... -if sys.version_info < (3, ): +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: ... 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: ... @@ -211,28 +183,23 @@ if sys.version_info >= (3, 5): 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, ): +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: ... 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: ... - -if sys.version_info < (3, ): +if sys.version_info < (3,): def isCallable(x: Any) -> bool: ... def isMappingType(x: Any) -> bool: ... def isNumberType(x: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 9c96030d31d4..3d06ac65ed23 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,6 +1,5 @@ -# Generated by pytype, with only minor tweaks. Might be incomplete. import sys -from typing import Any, AnyStr, Callable, Dict, IO, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, overload +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 if sys.version_info >= (3,): @@ -14,6 +13,7 @@ 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: ... @@ -35,10 +35,8 @@ class OptionError(OptParseError): def __init__(self, msg: _Text, option: Option) -> None: ... class OptionConflictError(OptionError): ... - class OptionValueError(OptParseError): ... - class HelpFormatter: NO_DEFAULT_VALUE: _Text _long_opt_fmt: _Text @@ -61,8 +59,8 @@ class HelpFormatter: 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: OptionParser) -> _Text: ... - def format_option_strings(self, option: OptionParser) -> Any: ... + 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: ... @@ -71,20 +69,16 @@ class HelpFormatter: 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 __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 __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: ... @@ -104,6 +98,11 @@ class Option: dest: Optional[_Text] 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: ... @@ -115,8 +114,8 @@ class Option: 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: Any, value: Any) -> Any: ... - def convert_value(self, opt: Any, value: Any) -> Any: ... + 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: ... @@ -130,8 +129,8 @@ class OptionContainer: conflict_handler: _Text defaults: Dict[_Text, Any] description: Any - option_class: Any - def __init__(self, option_class: Option, conflict_handler: Any, description: Any) -> None: ... + 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: ... @@ -175,7 +174,7 @@ class OptionParser(OptionContainer): epilog: Optional[_Text] formatter: HelpFormatter largs: Optional[List[_Text]] - option_groups: List[OptionParser] + option_groups: List[OptionGroup] option_list: List[Option] process_default_values: Any prog: Optional[_Text] @@ -184,17 +183,19 @@ class OptionParser(OptionContainer): usage: Optional[_Text] values: Optional[Values] version: _Text - def __init__(self, - usage: Optional[_Text] = ..., - option_list: Iterable[Option] = ..., - option_class: 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 __init__( + self, + usage: Optional[_Text] = ..., + option_list: 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: ... @@ -207,9 +208,9 @@ class OptionParser(OptionContainer): 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) -> OptionParser: ... + def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... @overload - def add_option_group(self, *args: Any, **kwargs: Any) -> OptionParser: ... + 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: ... @@ -224,7 +225,9 @@ class OptionParser(OptionContainer): 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 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: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 4219794a2d0e..7df6229842ef 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1,15 +1,46 @@ -from io import TextIOWrapper as _TextIOWrapper -from posix import listdir as listdir, times_result import sys +from _typeshed import ( + AnyPath, + FileDescriptorLike, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, +) +from builtins import OSError, _PathLike +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper +from posix import listdir as listdir, times_result from typing import ( - Mapping, MutableMapping, Dict, List, Any, Tuple, Iterable, Iterator, NoReturn, overload, Union, AnyStr, - Optional, Generic, Set, Callable, Sequence, NamedTuple, ContextManager, TypeVar + IO, + Any, + AnyStr, + BinaryIO, + Callable, + ContextManager, + Dict, + Generic, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + NoReturn, + Optional, + Sequence, + Set, + Tuple, + TypeVar, + Union, + overload, ) -from _typeshed import AnyPath +from typing_extensions import Literal -from builtins import OSError as error from . import path as path +if sys.version_info >= (3, 9): + from types import GenericAlias + # We need to use something from path, or flake8 and pytype get unhappy _supports_unicode_filenames = path.supports_unicode_filenames @@ -17,6 +48,8 @@ _T = TypeVar("_T") # ----- os variables ----- +error = OSError + supports_bytes_environ: bool supports_dir_fd: Set[Callable[..., Any]] @@ -24,7 +57,7 @@ supports_fd: Set[Callable[..., Any]] supports_effective_ids: Set[Callable[..., Any]] supports_follow_symlinks: Set[Callable[..., Any]] -if sys.platform != 'win32': +if sys.platform != "win32": # Unix only PRIO_PROCESS: int PRIO_PGRP: int @@ -85,7 +118,7 @@ if sys.platform != "win32": SEEK_SET: int SEEK_CUR: int SEEK_END: int -if sys.platform != 'win32': +if sys.platform != "win32": SEEK_DATA: int # some flavors of Unix SEEK_HOLE: int # some flavors of Unix @@ -99,27 +132,27 @@ O_TRUNC: int # We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, # including tests for mypy, use a more finer way than sys.platform before using these APIs # See https://github.com/python/typeshed/pull/2286 for discussions -O_DSYNC: int # Unix only -O_RSYNC: int # Unix only -O_SYNC: int # Unix only -O_NDELAY: int # Unix only +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only O_NONBLOCK: int # Unix only -O_NOCTTY: int # Unix only +O_NOCTTY: int # Unix only O_CLOEXEC: int # Unix only -O_SHLOCK: int # Unix only -O_EXLOCK: int # Unix only -O_BINARY: int # Windows only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only O_NOINHERIT: int # Windows only O_SHORT_LIVED: int # Windows only O_TEMPORARY: int # Windows only -O_RANDOM: int # Windows only +O_RANDOM: int # Windows only O_SEQUENTIAL: int # Windows only -O_TEXT: int # Windows only -O_ASYNC: int # Gnu extension if in C library -O_DIRECT: int # Gnu extension if in C library +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library O_DIRECTORY: int # Gnu extension if in C library -O_NOFOLLOW: int # Gnu extension if in C library -O_NOATIME: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library O_PATH: int # Gnu extension if in C library O_TMPFILE: int # Gnu extension if in C library O_LARGEFILE: int # Gnu extension if in C library @@ -127,7 +160,7 @@ O_LARGEFILE: int # Gnu extension if in C library curdir: str pardir: str sep: str -if sys.platform == 'win32': +if sys.platform == "win32": altsep: str else: altsep: Optional[str] @@ -155,7 +188,7 @@ environ: _Environ[str] if sys.platform != "win32": environb: _Environ[bytes] -if sys.platform != 'win32': +if sys.platform != "win32": confstr_names: Dict[str, int] pathconf_names: Dict[str, int] sysconf_names: Dict[str, int] @@ -181,12 +214,12 @@ if sys.platform != 'win32': P_NOWAIT: int P_NOWAITO: int P_WAIT: int -if sys.platform == 'win32': +if sys.platform == "win32": P_DETACH: int P_OVERLAY: int # wait()/waitpid() options -if sys.platform != 'win32': +if sys.platform != "win32": WNOHANG: int # Unix only WCONTINUED: int # some Unix systems WUNTRACED: int # Unix only @@ -216,14 +249,11 @@ class stat_result: st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds if sys.version_info >= (3, 8) and sys.platform == "win32": st_reparse_tag: int - if sys.version_info >= (3, 5) and sys.platform == "win32": + if sys.platform == "win32": st_file_attributes: int - def __getitem__(self, i: int) -> int: ... - # not documented def __init__(self, tuple: Tuple[int, ...]) -> None: ... - # On some Unix systems (such as Linux), the following attributes may also # be available: st_blocks: int # number of blocks allocated for file @@ -241,43 +271,36 @@ class stat_result: st_creator: int st_type: int -if sys.version_info >= (3, 6): - from builtins import _PathLike as PathLike # See comment in builtins +PathLike = _PathLike # See comment in builtins _FdOrAnyPath = Union[int, AnyPath] -if sys.version_info >= (3, 6): - class DirEntry(PathLike[AnyStr]): - # This is what the scandir interator yields - # The constructor is hidden - - name: AnyStr - path: AnyStr - def inode(self) -> int: ... - def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... - def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... - def is_symlink(self) -> bool: ... - def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... +class DirEntry(Generic[AnyStr]): + # This is what the scandir interator yields + # The constructor is hidden + + name: AnyStr + path: AnyStr + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + def __fspath__(self) -> AnyStr: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... - def __fspath__(self) -> AnyStr: ... -else: - class DirEntry(Generic[AnyStr]): - # This is what the scandir interator yields - # The constructor is hidden - - name: AnyStr - path: AnyStr - def inode(self) -> int: ... - def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... - def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... - def is_symlink(self) -> bool: ... - def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... - - -if sys.platform != 'win32': +if sys.platform != "win32": + _Tuple10Int = Tuple[int, int, int, int, int, int, int, int, int, int] + _Tuple11Int = Tuple[int, int, int, int, int, int, int, int, int, int, int] if sys.version_info >= (3, 7): # f_fsid was added in https://github.com/python/cpython/pull/4571 - class statvfs_result(NamedTuple): # Unix only + class statvfs_result(_Tuple10Int): # Unix only + def __new__(cls, seq: Union[_Tuple10Int, _Tuple11Int], dict: Dict[str, int] = ...) -> statvfs_result: ... + n_fields: int + n_sequence_fields: int + n_unnamed_fields: int + f_bsize: int f_frsize: int f_blocks: int @@ -288,9 +311,13 @@ if sys.platform != 'win32': f_favail: int f_flag: int f_namemax: int - f_fsid: int + f_fsid: int = ... else: - class statvfs_result(NamedTuple): # Unix only + class statvfs_result(_Tuple10Int): # Unix only + n_fields: int + n_sequence_fields: int + n_unnamed_fields: int + f_bsize: int f_frsize: int f_blocks: int @@ -302,27 +329,17 @@ if sys.platform != 'win32': f_flag: int f_namemax: int - # ----- os function stubs ----- -if sys.version_info >= (3, 6): - def fsencode(filename: Union[str, bytes, PathLike[Any]]) -> bytes: ... -else: - def fsencode(filename: Union[str, bytes]) -> bytes: ... - -if sys.version_info >= (3, 6): - def fsdecode(filename: Union[str, bytes, PathLike[Any]]) -> str: ... -else: - def fsdecode(filename: Union[str, bytes]) -> str: ... - -if sys.version_info >= (3, 6): - @overload - def fspath(path: str) -> str: ... - @overload - def fspath(path: bytes) -> bytes: ... - @overload - def fspath(path: PathLike[AnyStr]) -> AnyStr: ... - +def fsencode(filename: Union[str, bytes, PathLike[Any]]) -> bytes: ... +def fsdecode(filename: Union[str, bytes, PathLike[Any]]) -> str: ... +@overload +def fspath(path: str) -> str: ... +@overload +def fspath(path: bytes) -> bytes: ... +@overload +def fspath(path: PathLike[AnyStr]) -> AnyStr: ... def get_exec_path(env: Optional[Mapping[str, str]] = ...) -> List[str]: ... + # NOTE: get_exec_path(): returns List[bytes] when env not None def getlogin() -> str: ... def getpid() -> int: ... @@ -330,7 +347,7 @@ def getppid() -> int: ... def strerror(__code: int) -> str: ... def umask(__mask: int) -> int: ... -if sys.platform != 'win32': +if sys.platform != "win32": # Unix only def ctermid() -> str: ... def getegid() -> int: ... @@ -373,35 +390,115 @@ if sys.platform != "win32": @overload def getenvb(key: bytes) -> Optional[bytes]: ... @overload - def getenvb(key: bytes, default: _T = ...) -> Union[bytes, _T]: ... + def getenvb(key: bytes, default: _T) -> Union[bytes, _T]: ... + def putenv(__name: Union[bytes, str], __value: Union[bytes, str]) -> None: ... + if sys.platform != "win32": def unsetenv(__name: Union[bytes, str]) -> None: ... -# Return IO or TextIO -def fdopen(fd: int, mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., - errors: str = ..., newline: str = ..., closefd: bool = ...) -> Any: ... +_Opener = Callable[[str, int], int] +@overload +def fdopen( + fd: int, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> _TextIOWrapper: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> FileIO: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedRandom: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedWriter: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BufferedReader: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryMode, + buffering: int, + encoding: None = ..., + errors: None = ..., + newline: None = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> BinaryIO: ... +@overload +def fdopen( + fd: int, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., + opener: Optional[_Opener] = ..., +) -> IO[Any]: ... def close(fd: int) -> None: ... def closerange(__fd_low: int, __fd_high: int) -> None: ... def device_encoding(fd: int) -> Optional[str]: ... def dup(__fd: int) -> int: ... + if sys.version_info >= (3, 7): def dup2(fd: int, fd2: int, inheritable: bool = ...) -> int: ... + else: def dup2(fd: int, fd2: int, inheritable: bool = ...) -> None: ... + def fstat(fd: int) -> stat_result: ... -def fsync(fd: int) -> None: ... +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 pipe() -> Tuple[int, int]: ... def read(__fd: int, __length: int) -> bytes: ... -if sys.platform != 'win32': +if sys.platform != "win32": # Unix only def fchmod(fd: int, mode: int) -> None: ... def fchown(fd: int, uid: int, gid: int) -> None: ... if sys.platform != "darwin": - def fdatasync(fd: int) -> None: ... # Unix only, not Mac + def fdatasync(fd: FileDescriptorLike) -> None: ... # Unix only, not Mac def fpathconf(__fd: int, __name: Union[str, int]) -> int: ... def fstatvfs(__fd: int) -> statvfs_result: ... def ftruncate(__fd: int, __length: int) -> None: ... @@ -419,119 +516,118 @@ if sys.platform != 'win32': @overload def sendfile(__out_fd: int, __in_fd: int, offset: Optional[int], count: int) -> int: ... @overload - def sendfile(__out_fd: int, __in_fd: int, offset: int, count: int, - headers: Sequence[bytes] = ..., trailers: Sequence[bytes] = ..., flags: int = ...) -> int: ... # FreeBSD and Mac OS X only + def sendfile( + __out_fd: int, + __in_fd: int, + offset: int, + count: int, + headers: Sequence[bytes] = ..., + trailers: Sequence[bytes] = ..., + flags: int = ..., + ) -> int: ... # FreeBSD and Mac OS X only def readv(__fd: int, __buffers: Sequence[bytearray]) -> int: ... def writev(__fd: int, __buffers: Sequence[bytes]) -> int: ... class terminal_size(Tuple[int, int]): columns: int lines: int -def get_terminal_size(fd: int = ...) -> terminal_size: ... +def get_terminal_size(fd: int = ...) -> terminal_size: ... def get_inheritable(__fd: int) -> bool: ... def set_inheritable(__fd: int, __inheritable: bool) -> None: ... -if sys.platform != 'win32': +if sys.platform != "win32": # Unix only def tcgetpgrp(__fd: int) -> int: ... def tcsetpgrp(__fd: int, __pgid: int) -> None: ... def ttyname(__fd: int) -> str: ... + def write(__fd: int, __data: bytes) -> int: ... def access( - path: _FdOrAnyPath, - mode: int, - *, - dir_fd: Optional[int] = ..., - effective_ids: bool = ..., - follow_symlinks: bool = ..., + path: _FdOrAnyPath, mode: int, *, dir_fd: Optional[int] = ..., effective_ids: bool = ..., follow_symlinks: bool = ... ) -> bool: ... def chdir(path: _FdOrAnyPath) -> None: ... if sys.platform != "win32": - def fchdir(fd: int) -> None: ... + def fchdir(fd: FileDescriptorLike) -> None: ... + def getcwd() -> str: ... def getcwdb() -> bytes: ... def chmod(path: _FdOrAnyPath, mode: int, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> None: ... -if sys.platform != 'win32': + +if sys.platform != "win32": def chflags(path: AnyPath, 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': + 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 link( - src: AnyPath, - dst: AnyPath, - *, - src_dir_fd: Optional[int] = ..., - dst_dir_fd: Optional[int] = ..., - follow_symlinks: bool = ..., + src: AnyPath, dst: AnyPath, *, 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: ... -if sys.platform != 'win32': + +if sys.platform != "win32": def mkfifo(path: AnyPath, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... # Unix only + def makedirs(name: AnyPath, mode: int = ..., exist_ok: bool = ...) -> None: ... + if sys.platform != "win32": def mknod(path: AnyPath, 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 -if sys.version_info >= (3, 6): - def readlink(path: Union[AnyStr, PathLike[AnyStr]], *, dir_fd: Optional[int] = ...) -> AnyStr: ... -else: - def readlink(path: AnyStr, *, dir_fd: Optional[int] = ...) -> AnyStr: ... + +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: ... + +class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): + def __next__(self) -> DirEntry[AnyStr]: ... + def close(self) -> None: ... + if sys.version_info >= (3, 7): - class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): - def __next__(self) -> DirEntry[AnyStr]: ... - def close(self) -> None: ... @overload def scandir(path: None = ...) -> _ScandirIterator[str]: ... @overload def scandir(path: int) -> _ScandirIterator[str]: ... @overload def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... -elif sys.version_info >= (3, 6): - class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): - def __next__(self) -> DirEntry[AnyStr]: ... - def close(self) -> None: ... + +else: @overload def scandir(path: None = ...) -> _ScandirIterator[str]: ... @overload def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... -else: - @overload - def scandir(path: None = ...) -> Iterator[DirEntry[str]]: ... - @overload - def scandir(path: AnyStr) -> Iterator[DirEntry[AnyStr]]: ... + def stat(path: _FdOrAnyPath, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> stat_result: ... + if sys.version_info < (3, 7): @overload def stat_float_times() -> bool: ... @overload def stat_float_times(__newvalue: bool) -> None: ... -if sys.platform != 'win32': + +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: ... -if sys.platform != 'win32': + +def symlink(src: AnyPath, dst: AnyPath, 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 utime( @@ -545,41 +641,49 @@ def utime( _OnError = Callable[[OSError], Any] -if sys.version_info >= (3, 6): - def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ..., - onerror: Optional[_OnError] = ..., - followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], - List[AnyStr]]]: ... -else: - def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[_OnError] = ..., - followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], - List[AnyStr]]]: ... -if sys.platform != 'win32': +def walk( + top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ..., onerror: Optional[_OnError] = ..., followlinks: bool = ... +) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... + +if sys.platform != "win32": if sys.version_info >= (3, 7): @overload - def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., - onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., - dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + def fwalk( + top: Union[str, PathLike[str]] = ..., + topdown: bool = ..., + onerror: Optional[_OnError] = ..., + *, + follow_symlinks: bool = ..., + dir_fd: Optional[int] = ..., + ) -> Iterator[Tuple[str, List[str], List[str], int]]: ... @overload - def fwalk(top: bytes, topdown: bool = ..., - onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., - dir_fd: Optional[int] = ...) -> Iterator[Tuple[bytes, List[bytes], List[bytes], int]]: ... - elif sys.version_info >= (3, 6): - def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., - onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., - dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + def fwalk( + top: bytes, + topdown: bool = ..., + onerror: Optional[_OnError] = ..., + *, + follow_symlinks: bool = ..., + dir_fd: Optional[int] = ..., + ) -> Iterator[Tuple[bytes, List[bytes], List[bytes], int]]: ... else: - def fwalk(top: str = ..., topdown: bool = ..., - onerror: Optional[_OnError] = ..., *, follow_symlinks: bool = ..., - dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + def fwalk( + top: Union[str, PathLike[str]] = ..., + topdown: bool = ..., + onerror: Optional[_OnError] = ..., + *, + follow_symlinks: bool = ..., + 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 listxattr(path: _FdOrAnyPath, *, follow_symlinks: bool = ...) -> List[str]: ... def removexattr(path: _FdOrAnyPath, attribute: AnyPath, *, follow_symlinks: bool = ...) -> None: ... - def setxattr(path: _FdOrAnyPath, attribute: AnyPath, value: bytes, flags: int = ..., *, - follow_symlinks: bool = ...) -> None: ... + def setxattr( + path: _FdOrAnyPath, attribute: AnyPath, 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: ... @@ -590,26 +694,29 @@ def execlpe(file: AnyPath, __arg0: AnyPath, *args: Any) -> NoReturn: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. -if sys.version_info >= (3, 6): - # Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference - # 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, ...], List[bytes], List[str], List[PathLike[Any]], List[Union[bytes, str]], - List[Union[bytes, PathLike[Any]]], List[Union[str, PathLike[Any]]], List[Union[bytes, str, PathLike[Any]]] - ] -else: - _ExecVArgs = Union[Tuple[AnyPath, ...], List[bytes], List[str], List[Union[bytes, str]]] - +# Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference +# 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, ...], + List[bytes], + List[str], + List[PathLike[Any]], + List[Union[bytes, str]], + List[Union[bytes, PathLike[Any]]], + List[Union[str, PathLike[Any]]], + List[Union[bytes, str, PathLike[Any]]], +] _ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] + def execv(__path: AnyPath, __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 _exit(status: int) -> NoReturn: ... def kill(__pid: int, __signal: int) -> None: ... -if sys.platform != 'win32': + +if sys.platform != "win32": # Unix only def fork() -> int: ... def forkpty() -> Tuple[int, int]: ... # some flavors of Unix @@ -620,22 +727,26 @@ if sys.platform != 'win32': class _wrap_close(_TextIOWrapper): def close(self) -> Optional[int]: ... # type: ignore -def popen(cmd: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... +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 + if sys.platform != "win32": def spawnv(mode: int, file: AnyPath, args: _ExecVArgs) -> int: ... def spawnve(mode: int, file: AnyPath, 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 system(command: AnyPath) -> int: ... def times() -> times_result: ... def waitpid(__pid: int, __options: int) -> Tuple[int, int]: ... -if sys.platform == 'win32': +if sys.platform == "win32": def startfile(path: AnyPath, operation: Optional[str] = ...) -> None: ... + else: # Unix only def spawnlp(mode: int, file: AnyPath, arg0: AnyPath, *args: AnyPath) -> int: ... @@ -656,7 +767,7 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... -if sys.platform != 'win32': +if sys.platform != "win32": from posix import sched_param def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix @@ -670,14 +781,16 @@ if sys.platform != 'win32': def sched_getaffinity(pid: int) -> Set[int]: ... # some flavors of Unix def cpu_count() -> Optional[int]: ... -if sys.platform != 'win32': + +if sys.platform != "win32": # Unix only def confstr(__name: Union[str, int]) -> Optional[str]: ... def getloadavg() -> Tuple[float, float, float]: ... def sysconf(__name: Union[str, int]) -> int: ... -if sys.version_info >= (3, 6): - if sys.platform == "linux": - def getrandom(size: int, flags: int = ...) -> bytes: ... + +if sys.platform == "linux": + def getrandom(size: int, flags: int = ...) -> bytes: ... + def urandom(__size: int) -> bytes: ... if sys.version_info >= (3, 7) and sys.platform != "win32": @@ -692,6 +805,7 @@ if sys.version_info >= (3, 8): if sys.platform == "win32": class _AddedDllDirectory: path: Optional[str] + def __init__(self, path: Optional[str], cookie: _T, remove_dll_directory: Callable[[_T], Any]) -> None: ... def close(self) -> None: ... def __enter__(self: _T) -> _T: ... def __exit__(self, *args: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/os/path.pyi b/mypy/typeshed/stdlib/os/path.pyi index ef4b48331d89..9fe5a7df6c85 100644 --- a/mypy/typeshed/stdlib/os/path.pyi +++ b/mypy/typeshed/stdlib/os/path.pyi @@ -1,14 +1,11 @@ -# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! import os import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from _typeshed import AnyPath, BytesPath, StrPath +from builtins import _PathLike from genericpath import exists as exists -from _typeshed import StrPath, BytesPath, AnyPath +from typing import Any, AnyStr, Optional, Sequence, Tuple, TypeVar, overload -_T = TypeVar('_T') - -if sys.version_info >= (3, 6): - from builtins import _PathLike +_T = TypeVar("_T") # ----- os.path variables ----- supports_unicode_filenames: bool @@ -16,7 +13,7 @@ supports_unicode_filenames: bool curdir: str pardir: str sep: str -if sys.platform == 'win32': +if sys.platform == "win32": altsep: str else: altsep: Optional[str] @@ -26,72 +23,55 @@ defpath: str devnull: str # ----- os.path function stubs ----- -if sys.version_info >= (3, 6): - # Overloads are necessary to work around python/mypy#3644. - @overload - def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def abspath(path: AnyStr) -> AnyStr: ... - @overload - def basename(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(p: AnyStr) -> AnyStr: ... - @overload - def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(p: AnyStr) -> AnyStr: ... - @overload - def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expanduser(path: AnyStr) -> AnyStr: ... - @overload - def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expandvars(path: AnyStr) -> AnyStr: ... - @overload - def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(s: AnyStr) -> AnyStr: ... +# Overloads are necessary to work around python/mypy#3644. +@overload +def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def abspath(path: AnyStr) -> AnyStr: ... +@overload +def basename(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def basename(p: AnyStr) -> AnyStr: ... +@overload +def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def dirname(p: AnyStr) -> AnyStr: ... +@overload +def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expanduser(path: AnyStr) -> AnyStr: ... +@overload +def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expandvars(path: AnyStr) -> AnyStr: ... +@overload +def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normcase(s: AnyStr) -> AnyStr: ... +@overload +def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": @overload - def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... @overload - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - @overload - def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - else: - @overload - def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(filename: AnyStr) -> AnyStr: ... + def realpath(path: AnyStr) -> AnyStr: ... else: - def abspath(path: AnyStr) -> AnyStr: ... - def basename(p: AnyStr) -> AnyStr: ... - def dirname(p: AnyStr) -> AnyStr: ... - def expanduser(path: AnyStr) -> AnyStr: ... - def expandvars(path: AnyStr) -> AnyStr: ... - def normcase(s: AnyStr) -> AnyStr: ... - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - def realpath(path: AnyStr) -> AnyStr: ... - else: - def realpath(filename: AnyStr) -> AnyStr: ... + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... -if sys.version_info >= (3, 6): - # In reality it returns str for sequences of StrPath and bytes for sequences - # of BytesPath, but mypy does not accept such a signature. - def commonpath(paths: Sequence[AnyPath]) -> Any: ... -elif sys.version_info >= (3, 5): - def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... +# In reality it returns str for sequences of StrPath and bytes for sequences +# of BytesPath, but mypy does not accept such a signature. +def commonpath(paths: Sequence[AnyPath]) -> Any: ... # 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: ... # These return float if os.stat_float_times() == True, @@ -99,66 +79,35 @@ def lexists(path: AnyPath) -> bool: ... 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: ... - -if sys.version_info < (3, 0): - # 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: ... -elif sys.version_info >= (3, 6): - @overload - def join(a: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(a: BytesPath, *paths: BytesPath) -> bytes: ... -else: - def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... - +@overload +def join(a: StrPath, *paths: StrPath) -> str: ... +@overload +def join(a: BytesPath, *paths: BytesPath) -> bytes: ... @overload def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... - +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> str: ... 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: ... +@overload +def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -if sys.version_info >= (3, 6): - @overload - def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -else: - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.version_info < (3, 7) and sys.platform == 'win32': +if sys.version_info < (3, 7) and sys.platform == "win32": def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -if sys.version_info < (3,): - def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/ossaudiodev.pyi b/mypy/typeshed/stdlib/ossaudiodev.pyi new file mode 100644 index 000000000000..af3e2c210930 --- /dev/null +++ b/mypy/typeshed/stdlib/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/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index ca1cd4d526e7..799f25cf6a48 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,6 +1,6 @@ -from typing import Any, List, Sequence, Text, Tuple -from types import CodeType from _typeshed import AnyPath +from types import CodeType +from typing import Any, List, Sequence, Text, Tuple def expr(source: Text) -> STType: ... def suite(source: Text) -> STType: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index fd7d55b8b175..cd00398fe74e 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -1,16 +1,18 @@ -from _typeshed import OpenBinaryMode, OpenTextMode -from typing import (Any, BinaryIO, Generator, IO, List, Optional, Sequence, - TextIO, Tuple, Type, TypeVar, Union, overload) -from types import TracebackType import os import sys +from _typeshed import OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from types import TracebackType +from typing import IO, Any, BinaryIO, Generator, List, Optional, Sequence, Tuple, Type, TypeVar, Union, overload +from typing_extensions import Literal + +if sys.version_info >= (3, 9): + from types import GenericAlias -_P = TypeVar('_P', bound=PurePath) +_P = TypeVar("_P", bound=PurePath) -if sys.version_info >= (3, 6): - _PurePathBase = os.PathLike[str] -else: - _PurePathBase = object +_PurePathBase = os.PathLike[str] +_PathLike = os.PathLike[str] class PurePath(_PurePathBase): parts: Tuple[str, ...] @@ -21,25 +23,14 @@ class PurePath(_PurePathBase): suffix: str suffixes: List[str] stem: str - if sys.version_info < (3, 5): - def __init__(self, *pathsegments: str) -> None: ... - elif sys.version_info < (3, 6): - def __new__(cls: Type[_P], *args: Union[str, PurePath]) -> _P: ... - else: - def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]]) -> _P: ... + def __new__(cls: Type[_P], *args: Union[str, _PathLike]) -> _P: ... def __hash__(self) -> int: ... def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... def __gt__(self, other: PurePath) -> bool: ... def __ge__(self, other: PurePath) -> bool: ... - if sys.version_info < (3, 6): - def __truediv__(self: _P, key: Union[str, PurePath]) -> _P: ... - def __rtruediv__(self: _P, key: Union[str, PurePath]) -> _P: ... - else: - def __truediv__(self: _P, key: Union[str, os.PathLike[str]]) -> _P: ... - def __rtruediv__(self: _P, key: Union[str, os.PathLike[str]]) -> _P: ... - if sys.version_info < (3,): - def __div__(self: _P, key: Union[str, PurePath]) -> _P: ... + def __truediv__(self: _P, key: Union[str, _PathLike]) -> _P: ... + def __rtruediv__(self: _P, key: Union[str, _PathLike]) -> _P: ... def __bytes__(self) -> bytes: ... def as_posix(self) -> str: ... def as_uri(self) -> str: ... @@ -48,38 +39,34 @@ class PurePath(_PurePathBase): if sys.version_info >= (3, 9): def is_relative_to(self, *other: Union[str, os.PathLike[str]]) -> bool: ... def match(self, path_pattern: str) -> bool: ... - if sys.version_info < (3, 6): - def relative_to(self: _P, *other: Union[str, PurePath]) -> _P: ... - else: - def relative_to(self: _P, *other: Union[str, os.PathLike[str]]) -> _P: ... + def relative_to(self: _P, *other: Union[str, _PathLike]) -> _P: ... def with_name(self: _P, name: str) -> _P: ... if sys.version_info >= (3, 9): def with_stem(self: _P, stem: str) -> _P: ... def with_suffix(self: _P, suffix: str) -> _P: ... - if sys.version_info < (3, 6): - def joinpath(self: _P, *other: Union[str, PurePath]) -> _P: ... - else: - def joinpath(self: _P, *other: Union[str, os.PathLike[str]]) -> _P: ... - + def joinpath(self: _P, *other: Union[str, _PathLike]) -> _P: ... @property def parents(self: _P) -> Sequence[_P]: ... @property def parent(self: _P) -> _P: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, type: Any) -> GenericAlias: ... class PurePosixPath(PurePath): ... class PureWindowsPath(PurePath): ... class Path(PurePath): - def __enter__(self) -> Path: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType]) -> Optional[bool]: ... + def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ... + def __enter__(self: _P) -> _P: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> Optional[bool]: ... @classmethod def cwd(cls: Type[_P]) -> _P: ... def stat(self) -> os.stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... - def glob(self, pattern: str) -> Generator[Path, None, None]: ... + def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... @@ -90,24 +77,69 @@ class Path(PurePath): def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... - def iterdir(self) -> Generator[Path, None, None]: ... + def iterdir(self: _P) -> Generator[_P, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> os.stat_result: ... - if sys.version_info < (3, 5): - def mkdir(self, mode: int = ..., - parents: bool = ...) -> None: ... - else: - def mkdir(self, mode: int = ..., parents: bool = ..., - exist_ok: bool = ...) -> None: ... + def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... + # Adapted from builtins.open + # Text mode: always returns a TextIOWrapper @overload - def open(self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., - newline: Optional[str] = ...) -> TextIO: ... + def open( + self, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + ) -> TextIOWrapper: ... + # Unbuffered binary mode: returns a FileIO @overload - def open(self, mode: OpenBinaryMode, buffering: int = ..., encoding: None = ..., errors: None = ..., - newline: None = ...) -> BinaryIO: ... + def open( + self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... + ) -> FileIO: ... + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter @overload - def open(self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., - newline: Optional[str] = ...) -> IO[Any]: ... + def open( + self, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + ) -> BufferedRandom: ... + @overload + def open( + self, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + ) -> BufferedWriter: ... + @overload + def open( + self, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., + ) -> BufferedReader: ... + # Buffering cannot be determined: fall back to BinaryIO + @overload + def open( + self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... + ) -> BinaryIO: ... + # Fallback if mode is not specified + @overload + def open( + self, + mode: str, + buffering: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): def readlink(self: _P) -> _P: ... @@ -117,42 +149,26 @@ class Path(PurePath): else: def rename(self, target: Union[str, PurePath]) -> None: ... def replace(self, target: Union[str, PurePath]) -> None: ... - if sys.version_info < (3, 6): - def resolve(self: _P) -> _P: ... - else: - def resolve(self: _P, strict: bool = ...) -> _P: ... - def rglob(self, pattern: str) -> Generator[Path, None, None]: ... + def resolve(self: _P, strict: bool = ...) -> _P: ... + def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... - def symlink_to(self, target: Union[str, Path], - target_is_directory: bool = ...) -> None: ... + def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... else: def unlink(self) -> None: ... - - if sys.version_info >= (3, 5): - @classmethod - def home(cls: Type[_P]) -> _P: ... - if sys.version_info < (3, 6): - def __new__(cls: Type[_P], *args: Union[str, PurePath], - **kwargs: Any) -> _P: ... - else: - def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]], - **kwargs: Any) -> _P: ... - - def absolute(self: _P) -> _P: ... - def expanduser(self: _P) -> _P: ... - def read_bytes(self) -> bytes: ... - def read_text(self, encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> str: ... - def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... - def write_bytes(self, data: bytes) -> int: ... - def write_text(self, data: str, encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> int: ... + @classmethod + def home(cls: Type[_P]) -> _P: ... + def absolute(self: _P) -> _P: ... + def expanduser(self: _P) -> _P: ... + def read_bytes(self) -> bytes: ... + def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... + def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... + def write_bytes(self, data: bytes) -> int: ... + def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... - class PosixPath(Path, PurePosixPath): ... class WindowsPath(Path, PureWindowsPath): ... diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index 3913a43aec60..2750e9ea0f4b 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -1,26 +1,25 @@ +import signal +import sys from bdb import Bdb from cmd import Cmd from inspect import _SourceObjectType -import signal -import sys from types import CodeType, FrameType, TracebackType -from typing import Any, Callable, ClassVar, Dict, IO, Iterable, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union +from typing import IO, Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union -_T = TypeVar('_T') +_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 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]: ... if sys.version_info >= (3, 7): def set_trace(*, header: Optional[str] = ...) -> None: ... + else: def set_trace() -> None: ... @@ -234,7 +233,6 @@ class Pdb(Bdb, Cmd): 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 diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index 2b0124274a8a..ddf8a4401399 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,49 +1,49 @@ import sys -from typing import Any, IO, Mapping, Union, Tuple, Callable, Optional, Iterable, Iterator +from typing import IO, Any, Callable, Iterable, Iterator, Mapping, Optional, Tuple, Type, Union HIGHEST_PROTOCOL: int if sys.version_info >= (3, 0): DEFAULT_PROTOCOL: int +bytes_types: Tuple[Type[Any], ...] # undocumented if sys.version_info >= (3, 8): # TODO: holistic design for buffer interface (typing.Buffer?) - class PickleBuffer: # buffer must be a buffer-providing object def __init__(self, buffer: Any) -> None: ... def raw(self) -> memoryview: ... def release(self) -> None: ... - _BufferCallback = Optional[Callable[[PickleBuffer], Any]] - def dump( - obj: Any, file: IO[bytes], protocol: Optional[int] = ..., *, + obj: Any, + file: IO[bytes], + protocol: Optional[int] = ..., + *, fix_imports: bool = ..., - buffer_callback: _BufferCallback = ... + buffer_callback: _BufferCallback = ..., ) -> None: ... def dumps( - obj: Any, protocol: Optional[int] = ..., *, - fix_imports: bool = ..., - buffer_callback: _BufferCallback = ... + obj: Any, protocol: Optional[int] = ..., *, fix_imports: bool = ..., buffer_callback: _BufferCallback = ... ) -> bytes: ... def load( - file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., - errors: str = ..., buffers: Optional[Iterable[Any]] = ... + file: IO[bytes], + *, + fix_imports: bool = ..., + encoding: str = ..., + errors: str = ..., + buffers: Optional[Iterable[Any]] = ..., ) -> Any: ... def loads( - data: bytes, *, fix_imports: bool = ..., encoding: str = ..., - errors: str = ..., buffers: Optional[Iterable[Any]] = ... + __data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ..., buffers: Optional[Iterable[Any]] = ... ) -> Any: ... + elif sys.version_info >= (3, 0): - 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: ... + 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: ... @@ -54,14 +54,13 @@ 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]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, - Optional[Iterator], Optional[Iterator]]] - +_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 @@ -69,33 +68,40 @@ class Pickler: dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] if sys.version_info >= (3, 8): - def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *, - fix_imports: bool = ..., buffer_callback: _BufferCallback = ... - ) -> None: ... + def __init__( + self, + file: IO[bytes], + protocol: Optional[int] = ..., + *, + fix_imports: bool = ..., + 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: ... + 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 dump(self, obj: Any) -> None: ... + def dump(self, __obj: Any) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... class Unpickler: if sys.version_info >= (3, 8): - def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., - encoding: str = ..., errors: str = ..., - buffers: Optional[Iterable[Any]] = ...) -> None: ... + def __init__( + self, + file: IO[bytes], + *, + fix_imports: bool = ..., + encoding: str = ..., + 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: ... + def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> None: ... else: def __init__(self, file: IO[bytes]) -> None: ... - def load(self) -> Any: ... - def find_class(self, module: str, name: str) -> 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: ... @@ -175,3 +181,6 @@ if sys.version_info >= (3, 4): STACK_GLOBAL: bytes MEMOIZE: bytes FRAME: bytes + +def encode_long(x: int) -> bytes: ... # undocumented +def decode_long(data: bytes) -> int: ... # undocumented diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index c03664697bab..ec279524bc50 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,6 +1,5 @@ -# Stubs for pickletools (Python 2 and 3) import sys -from typing import Any, Callable, IO, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union _Reader = Callable[[IO[bytes]], Any] @@ -23,12 +22,15 @@ class ArgumentDescriptor(object): 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 if sys.version_info >= (3, 3): @@ -40,24 +42,28 @@ if sys.version_info >= (3, 5): uint8: 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 if sys.version_info >= (3, 3): def read_bytes1(f: IO[bytes]) -> bytes: ... bytes1: ArgumentDescriptor - def read_bytes4(f: IO[bytes]) -> bytes: ... bytes4: ArgumentDescriptor @@ -66,6 +72,7 @@ if sys.version_info >= (3, 4): bytes8: ArgumentDescriptor def read_unicodestringnl(f: IO[bytes]) -> Text: ... + unicodestringnl: ArgumentDescriptor if sys.version_info >= (3, 4): @@ -73,6 +80,7 @@ if sys.version_info >= (3, 4): unicodestring1: ArgumentDescriptor def read_unicodestring4(f: IO[bytes]) -> Text: ... + unicodestring4: ArgumentDescriptor if sys.version_info >= (3, 4): @@ -81,19 +89,24 @@ if sys.version_info >= (3, 4): 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): @@ -132,14 +145,35 @@ class OpcodeInfo(object): 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: ... + 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: ... + 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: ... + 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 = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/pipes.pyi b/mypy/typeshed/stdlib/pipes.pyi index 658373e4cdb3..2c2fd400a0c8 100644 --- a/mypy/typeshed/stdlib/pipes.pyi +++ b/mypy/typeshed/stdlib/pipes.pyi @@ -1,7 +1,3 @@ -# Stubs for pipes - -# Based on http://docs.python.org/3.5/library/pipes.html - import os class Template: diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 138a0f8b52d7..5fd025411325 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,22 +1,22 @@ -# Stubs for pkgutil - -from typing import Any, Callable, Generator, IO, Iterable, Optional, Tuple, NamedTuple import sys +from _typeshed import SupportsRead +from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple, Optional, Tuple, Union if sys.version_info >= (3,): - from importlib.abc import Loader + 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: Any + module_finder: Union[MetaPathFinder, PathEntryFinder] name: str ispkg: bool - _YMFNI = Generator[ModuleInfo, None, None] + _ModuleInfoLike = ModuleInfo else: - _YMFNI = Generator[Tuple[Any, str, bool], None, None] - + _ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] def extend_path(path: Iterable[str], name: str) -> Iterable[str]: ... @@ -24,15 +24,15 @@ class ImpImporter: def __init__(self, dirname: Optional[str] = ...) -> None: ... class ImpLoader: - def __init__(self, fullname: str, file: IO[str], filename: str, - etc: Tuple[str, str, int]) -> None: ... + 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) -> Any: ... # TODO precise type +def get_importer(path_item: str) -> Optional[PathEntryFinder]: ... def get_loader(module_or_name: str) -> Loader: ... -def iter_importers(fullname: str = ...) -> Generator[Any, None, None]: ... # TODO precise type -def iter_modules(path: Optional[Iterable[str]] = ..., - prefix: str = ...) -> _YMFNI: ... # TODO precise type -def walk_packages(path: Optional[Iterable[str]] = ..., prefix: str = ..., - onerror: Optional[Callable[[str], None]] = ...) -> _YMFNI: ... +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/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index c854930cd800..73579dff3887 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -1,22 +1,43 @@ -# Stubs for platform (Python 3.5) - -from os import devnull as DEV_NULL -from typing import Optional, Tuple, NamedTuple import sys +if sys.version_info < (3, 9): + import os + + DEV_NULL = os.devnull +from typing import NamedTuple, Optional, Tuple + if sys.version_info >= (3, 8): - def libc_ver(executable: Optional[str] = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> Tuple[str, str]: ... + def libc_ver( + executable: Optional[str] = ..., lib: str = ..., version: str = ..., chunksize: int = ... + ) -> Tuple[str, str]: ... + else: def libc_ver(executable: str = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> Tuple[str, str]: ... + if sys.version_info < (3, 8): - def linux_distribution(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ..., full_distribution_name: bool = ...) -> Tuple[str, str, str]: ... - def dist(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ...) -> Tuple[str, str, str]: ... + def linux_distribution( + distname: str = ..., + version: str = ..., + id: str = ..., + supported_dists: Tuple[str, ...] = ..., + full_distribution_name: bool = ..., + ) -> Tuple[str, str, str]: ... + def dist( + distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ... + ) -> Tuple[str, str, str]: ... + def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... + if sys.version_info >= (3, 8): def win32_edition() -> str: ... def win32_is_iot() -> bool: ... -def mac_ver(release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ...) -> Tuple[str, Tuple[str, str, str], str]: ... -def java_ver(release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ...) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... + +def mac_ver( + release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ... +) -> Tuple[str, Tuple[str, str, str], str]: ... +def java_ver( + release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ... +) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... def system_alias(system: str, release: str, version: str) -> Tuple[str, str, str]: ... def architecture(executable: str = ..., bits: str = ..., linkage: str = ...) -> Tuple[str, str]: ... @@ -35,7 +56,6 @@ def release() -> str: ... def version() -> str: ... def machine() -> str: ... def processor() -> str: ... - def python_implementation() -> str: ... def python_version() -> str: ... def python_version_tuple() -> Tuple[str, str, str]: ... @@ -43,5 +63,4 @@ def python_branch() -> str: ... def python_revision() -> str: ... def python_build() -> Tuple[str, str]: ... def python_compiler() -> str: ... - def platform(aliased: bool = ..., terse: bool = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index e3f542d26ea2..5aadae9fc97b 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -1,64 +1,52 @@ -from typing import ( - Any, IO, Mapping, MutableMapping, Optional, overload, Union, - Type, TypeVar, Text -) -from typing import Dict as DictT import sys +from typing import IO, Any, Dict as DictT, Mapping, MutableMapping, Optional, Text, 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 -mm = MutableMapping[str, Any] -_D = TypeVar('_D', bound=mm) _Path = Union[str, Text] if sys.version_info >= (3, 9): - @overload - def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ...) -> DictT[str, Any]: ... - @overload - def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., dict_type: Type[_D]) -> _D: ... - @overload - def loads(value: bytes, *, fmt: Optional[PlistFormat] = ...) -> DictT[str, Any]: ... - @overload - def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., dict_type: Type[_D]) -> _D: ... + 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): - @overload - def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., - use_builtin_types: bool = ...) -> DictT[str, Any]: ... - @overload - def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., - use_builtin_types: bool = ..., dict_type: Type[_D]) -> _D: ... - @overload - def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., - use_builtin_types: bool = ...) -> DictT[str, Any]: ... - @overload - def loads(value: bytes, *, fmt: Optional[PlistFormat] = ..., - use_builtin_types: bool = ..., dict_type: Type[_D]) -> _D: ... + def load( + fp: IO[bytes], + *, + fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., + dict_type: Type[MutableMapping[str, Any]] = ..., + ) -> Any: ... + def loads( + value: bytes, + *, + fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., + 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]]) -> DictT[str, Any]: ... + def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> Any: ... def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ... - def readPlistFromBytes(data: bytes) -> DictT[str, Any]: ... + 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 = ...) -> DictT[str, Any]: ... - def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, - restype: str = ..., - resid: int = ...) -> None: ... - def readPlistFromString(data: str) -> DictT[str, Any]: ... + 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): diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index d2b7dab6cf5c..2c08f3586c0f 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -1,12 +1,7 @@ -# Stubs for poplib (Python 2 and 3) - import socket import ssl import sys -from typing import ( - Any, BinaryIO, Dict, List, NoReturn, Optional, overload, Pattern, Text, - Tuple, -) +from typing import Any, BinaryIO, Dict, List, Optional, Pattern, Text, Tuple, overload _LongResp = Tuple[bytes, List[bytes], int] @@ -18,7 +13,6 @@ CR: bytes LF: bytes CRLF: bytes - class POP3: if sys.version_info >= (3, 0): encoding: Text @@ -28,7 +22,6 @@ class POP3: 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: ... @@ -43,7 +36,6 @@ class POP3: def quit(self) -> bytes: ... def close(self) -> None: ... def rpop(self, user: Text) -> bytes: ... - timestamp: Pattern[Text] if sys.version_info < (3, 0): @@ -51,27 +43,31 @@ class POP3: else: def apop(self, user: Text, password: Text) -> 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: ... - 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: ... + 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: ... - + 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: ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index c6092ead447c..9080d5b90245 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -1,14 +1,7 @@ -# Stubs for posix - -# NOTE: These are incomplete! - import sys -from typing import List, NamedTuple, Optional, overload - +from builtins import _PathLike # See comment in builtins from os import stat_result as stat_result - -if sys.version_info >= (3, 6): - from builtins import _PathLike # See comment in builtins +from typing import Dict, List, NamedTuple, Optional, overload class uname_result(NamedTuple): sysname: str @@ -34,6 +27,11 @@ class waitid_result(NamedTuple): class sched_param(NamedTuple): sched_priority: int +CLD_CONTINUED: int +CLD_DUMPED: int +CLD_EXITED: int +CLD_TRAPPED: int + EX_CANTCREAT: int EX_CONFIG: int EX_DATAERR: int @@ -57,9 +55,13 @@ R_OK: int W_OK: int X_OK: int -if sys.version_info >= (3, 6): - GRND_NONBLOCK: int - GRND_RANDOM: int +F_LOCK: int +F_TEST: int +F_TLOCK: int +F_ULOCK: int + +GRND_NONBLOCK: int +GRND_RANDOM: int NGROUPS_MAX: int O_APPEND: int @@ -83,6 +85,39 @@ O_SYNC: int O_TRUNC: int O_WRONLY: int +POSIX_FADV_DONTNEED: int +POSIX_FADV_NOREUSE: int +POSIX_FADV_NORMAL: int +POSIX_FADV_RANDOM: int +POSIX_FADV_SEQUENTIAL: int +POSIX_FADV_WILLNEED: int + +PRIO_PGRP: int +PRIO_PROCESS: int +PRIO_USER: int + +P_ALL: int +P_PGID: int +P_PID: int + +RTLD_DEEPBIND: int +RTLD_GLOBAL: int +RTLD_LAZY: int +RTLD_LOCAL: int +RTLD_NODELETE: int +RTLD_NOLOAD: int +RTLD_NOW: int + +SCHED_BATCH: int +SCHED_FIFO: int +SCHED_IDLE: int +SCHED_OTHER: int +SCHED_RESET_ON_FORK: int +SCHED_RR: int + +SEEK_DATA: int +SEEK_HOLE: int + ST_APPEND: int ST_MANDLOCK: int ST_NOATIME: int @@ -97,30 +132,34 @@ ST_WRITE: int TMP_MAX: int WCONTINUED: int -WCOREDUMP: int -WEXITSTATUS: int -WIFCONTINUED: int -WIFEXITED: int -WIFSIGNALED: int -WIFSTOPPED: int + +def WCOREDUMP(__status: int) -> bool: ... +def WEXITSTATUS(status: int) -> int: ... +def WIFCONTINUED(status: int) -> bool: ... +def WIFEXITED(status: int) -> bool: ... +def WIFSIGNALED(status: int) -> bool: ... +def WIFSTOPPED(status: int) -> bool: ... + WNOHANG: int -WSTOPSIG: int -WTERMSIG: int + +def WSTOPSIG(status: int) -> int: ... +def WTERMSIG(status: int) -> int: ... + WUNTRACED: int -if sys.version_info >= (3, 6): - @overload - def listdir(path: Optional[str] = ...) -> List[str]: ... - @overload - def listdir(path: bytes) -> List[bytes]: ... - @overload - def listdir(path: int) -> List[str]: ... - @overload - def listdir(path: _PathLike[str]) -> List[str]: ... +XATTR_CREATE: int +XATTR_REPLACE: int +XATTR_SIZE_MAX: int +@overload +def listdir(path: Optional[str] = ...) -> List[str]: ... +@overload +def listdir(path: bytes) -> List[bytes]: ... +@overload +def listdir(path: int) -> List[str]: ... +@overload +def listdir(path: _PathLike[str]) -> List[str]: ... + +if sys.platform == "win32": + environ: Dict[str, str] else: - @overload - def listdir(path: Optional[str] = ...) -> List[str]: ... - @overload - def listdir(path: bytes) -> List[bytes]: ... - @overload - def listdir(path: int) -> List[str]: ... + environ: Dict[bytes, bytes] diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index ef4b48331d89..9fe5a7df6c85 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -1,14 +1,11 @@ -# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! import os import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional +from _typeshed import AnyPath, BytesPath, StrPath +from builtins import _PathLike from genericpath import exists as exists -from _typeshed import StrPath, BytesPath, AnyPath +from typing import Any, AnyStr, Optional, Sequence, Tuple, TypeVar, overload -_T = TypeVar('_T') - -if sys.version_info >= (3, 6): - from builtins import _PathLike +_T = TypeVar("_T") # ----- os.path variables ----- supports_unicode_filenames: bool @@ -16,7 +13,7 @@ supports_unicode_filenames: bool curdir: str pardir: str sep: str -if sys.platform == 'win32': +if sys.platform == "win32": altsep: str else: altsep: Optional[str] @@ -26,72 +23,55 @@ defpath: str devnull: str # ----- os.path function stubs ----- -if sys.version_info >= (3, 6): - # Overloads are necessary to work around python/mypy#3644. - @overload - def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def abspath(path: AnyStr) -> AnyStr: ... - @overload - def basename(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(p: AnyStr) -> AnyStr: ... - @overload - def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(p: AnyStr) -> AnyStr: ... - @overload - def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expanduser(path: AnyStr) -> AnyStr: ... - @overload - def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expandvars(path: AnyStr) -> AnyStr: ... - @overload - def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(s: AnyStr) -> AnyStr: ... +# Overloads are necessary to work around python/mypy#3644. +@overload +def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def abspath(path: AnyStr) -> AnyStr: ... +@overload +def basename(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def basename(p: AnyStr) -> AnyStr: ... +@overload +def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def dirname(p: AnyStr) -> AnyStr: ... +@overload +def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expanduser(path: AnyStr) -> AnyStr: ... +@overload +def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def expandvars(path: AnyStr) -> AnyStr: ... +@overload +def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normcase(s: AnyStr) -> AnyStr: ... +@overload +def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... +@overload +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": @overload - def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... @overload - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - @overload - def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - else: - @overload - def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(filename: AnyStr) -> AnyStr: ... + def realpath(path: AnyStr) -> AnyStr: ... else: - def abspath(path: AnyStr) -> AnyStr: ... - def basename(p: AnyStr) -> AnyStr: ... - def dirname(p: AnyStr) -> AnyStr: ... - def expanduser(path: AnyStr) -> AnyStr: ... - def expandvars(path: AnyStr) -> AnyStr: ... - def normcase(s: AnyStr) -> AnyStr: ... - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - def realpath(path: AnyStr) -> AnyStr: ... - else: - def realpath(filename: AnyStr) -> AnyStr: ... + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... -if sys.version_info >= (3, 6): - # In reality it returns str for sequences of StrPath and bytes for sequences - # of BytesPath, but mypy does not accept such a signature. - def commonpath(paths: Sequence[AnyPath]) -> Any: ... -elif sys.version_info >= (3, 5): - def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... +# In reality it returns str for sequences of StrPath and bytes for sequences +# of BytesPath, but mypy does not accept such a signature. +def commonpath(paths: Sequence[AnyPath]) -> Any: ... # 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: ... # These return float if os.stat_float_times() == True, @@ -99,66 +79,35 @@ def lexists(path: AnyPath) -> bool: ... 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: ... - -if sys.version_info < (3, 0): - # 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: ... -elif sys.version_info >= (3, 6): - @overload - def join(a: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(a: BytesPath, *paths: BytesPath) -> bytes: ... -else: - def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... - +@overload +def join(a: StrPath, *paths: StrPath) -> str: ... +@overload +def join(a: BytesPath, *paths: BytesPath) -> bytes: ... @overload def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... @overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... - +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> str: ... 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: ... +@overload +def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... +@overload +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -if sys.version_info >= (3, 6): - @overload - def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -else: - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.version_info < (3, 7) and sys.platform == 'win32': +if sys.version_info < (3, 7) and sys.platform == "win32": def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -if sys.version_info < (3,): - def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi index 6b14e7d8ac8b..6c1133aa5c10 100644 --- a/mypy/typeshed/stdlib/pprint.pyi +++ b/mypy/typeshed/stdlib/pprint.pyi @@ -1,22 +1,24 @@ -# Stubs for pprint - -# Based on http://docs.python.org/2/library/pprint.html -# Based on http://docs.python.org/3/library/pprint.html - import sys -from typing import Any, Dict, Tuple, IO, Optional +from typing import IO, Any, Dict, Optional, Tuple if sys.version_info >= (3, 8): def pformat( - object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ..., *, compact: bool = ..., sort_dicts: bool = ... + object: object, + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + *, + compact: bool = ..., + sort_dicts: bool = ..., ) -> str: ... elif sys.version_info >= (3, 4): - def pformat(object: object, indent: int = ..., width: int = ..., - depth: Optional[int] = ..., *, compact: bool = ...) -> str: ... + 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: ... + def pformat(object: object, indent: int = ..., width: int = ..., depth: Optional[int] = ...) -> str: ... if sys.version_info >= (3, 8): def pp( @@ -43,11 +45,20 @@ if sys.version_info >= (3, 8): ) -> None: ... elif sys.version_info >= (3, 4): - def pprint(object: object, stream: Optional[IO[str]] = ..., indent: int = ..., width: int = ..., - depth: Optional[int] = ..., *, compact: bool = ...) -> None: ... + def pprint( + object: object, + stream: Optional[IO[str]] = ..., + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + *, + compact: bool = ..., + ) -> None: ... + else: - def pprint(object: object, stream: Optional[IO[str]] = ..., indent: int = ..., width: int = ..., - depth: Optional[int] = ...) -> None: ... + 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: ... @@ -66,15 +77,21 @@ class PrettyPrinter: sort_dicts: bool = ..., ) -> None: ... elif sys.version_info >= (3, 4): - def __init__(self, indent: int = ..., width: int = ..., depth: Optional[int] = ..., - stream: Optional[IO[str]] = ..., *, compact: bool = ...) -> None: ... + def __init__( + self, + indent: int = ..., + width: int = ..., + depth: Optional[int] = ..., + stream: Optional[IO[str]] = ..., + *, + compact: bool = ..., + ) -> None: ... else: - def __init__(self, indent: int = ..., width: int = ..., depth: Optional[int] = ..., - stream: Optional[IO[str]] = ...) -> None: ... - + 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]: ... + def format(self, object: object, context: Dict[int, Any], maxlevels: int, level: int) -> Tuple[str, bool, bool]: ... diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index d32c8b67abdb..d5f4bd4d5271 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -2,14 +2,15 @@ from _typeshed import AnyPath from typing import Any, Callable, Dict, Optional, 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: ... +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') +_SelfT = TypeVar("_SelfT", bound=Profile) +_T = TypeVar("_T") class Profile: bias: int - 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: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 53c8e6755fca..9c74aeb9c3de 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -1,16 +1,33 @@ -from profile import Profile -from cProfile import Profile as _cProfile +import sys from _typeshed import AnyPath -from typing import Any, Dict, IO, Iterable, List, Optional, Text, Tuple, TypeVar, Union, overload +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) +_T = TypeVar("_T", bound=Stats) + +if sys.version_info >= (3, 7): + from enum import Enum + class SortKey(str, Enum): + CALLS: str + CUMULATIVE: str + FILENAME: str + LINE: str + NAME: str + NFL: str + PCALLS: str + STDNAME: str + TIME: str 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: _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: ... diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index 3931bb0a91e2..f31e2c61ca9b 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,4 +1,3 @@ -# Stubs for pty (Python 2 and 3) import sys from typing import Callable, Iterable, Tuple, Union @@ -14,7 +13,9 @@ 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: ... diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 7613fd511320..7f6815b33197 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -1,8 +1,6 @@ -# Stubs for py_compile (Python 2 and 3) import enum import sys - -from typing import Optional, List, Text, AnyStr, Union, Type +from typing import AnyStr, List, Optional, Text, Type, Union _EitherStr = Union[bytes, Text] @@ -21,12 +19,34 @@ if sys.version_info >= (3, 7): def _get_default_invalidation_mode() -> PycInvalidationMode: ... if sys.version_info >= (3, 8): - def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., quiet: int = ...) -> Optional[AnyStr]: ... + def compile( + file: AnyStr, + cfile: Optional[AnyStr] = ..., + dfile: Optional[AnyStr] = ..., + doraise: bool = ..., + optimize: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + quiet: int = ..., + ) -> Optional[AnyStr]: ... + elif sys.version_info >= (3, 7): - def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ...) -> Optional[AnyStr]: ... + def compile( + file: AnyStr, + cfile: Optional[AnyStr] = ..., + dfile: Optional[AnyStr] = ..., + doraise: bool = ..., + optimize: int = ..., + invalidation_mode: Optional[PycInvalidationMode] = ..., + ) -> Optional[AnyStr]: ... + elif sys.version_info >= (3, 2): - def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ...) -> Optional[AnyStr]: ... + 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 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/pyclbr.pyi b/mypy/typeshed/stdlib/pyclbr.pyi index 0e2936058fc2..665ea43c0d4a 100644 --- a/mypy/typeshed/stdlib/pyclbr.pyi +++ b/mypy/typeshed/stdlib/pyclbr.pyi @@ -1,6 +1,5 @@ import sys -from typing import List, Union, Sequence, Optional, Dict - +from typing import Dict, List, Optional, Sequence, Union class Class: module: str @@ -11,11 +10,18 @@ class Class: lineno: int if sys.version_info >= (3, 7): - def __init__(self, module: str, name: str, super: Optional[List[Union[Class, str]]], file: str, lineno: int, parent: Optional[Class] = ...) -> None: ... + def __init__( + self, + module: str, + name: str, + super: Optional[List[Union[Class, str]]], + file: str, + lineno: int, + parent: Optional[Class] = ..., + ) -> None: ... else: def __init__(self, module: str, name: str, super: Optional[List[Union[Class, str]]], file: str, lineno: int) -> None: ... - class Function: module: str name: str @@ -27,12 +33,5 @@ class Function: else: 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]]]: ... +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/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index c3254dfefab9..39252dd9f725 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,7 +1,24 @@ import sys -from typing import Any, AnyStr, Callable, Container, Dict, IO, List, Mapping, MutableMapping, NoReturn, Optional, Text, Tuple, Type, Union -from types import FunctionType, MethodType, ModuleType, TracebackType 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, +) + if sys.version_info >= (3,): from reprlib import Repr else: @@ -26,7 +43,6 @@ 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]: ... @@ -73,8 +89,18 @@ class HTMLDoc(Doc): 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) -> 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: ... @@ -82,15 +108,46 @@ class HTMLDoc(Doc): 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) -> str: ... - def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., *ignored) -> 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) -> str: ... - def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... - def docother(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored) -> str: ... - def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> 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: ... @@ -111,14 +168,35 @@ class TextDoc(Doc): 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) -> str: ... - def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored) -> 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) -> str: ... - def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... - def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... - def docother(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., parent: Optional[str] = ..., maxlen: Optional[int] = ..., doc: Optional[Any] = ..., *ignored) -> 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]: ... @@ -137,7 +215,9 @@ 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 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: ... @@ -174,12 +254,20 @@ help: Helper 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 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: ... if sys.version_info < (3,): - def serve(port: int, callback: Optional[Callable[[Any], None]] = ..., completer: Optional[Callable[[], None]] = ...) -> 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/distutils/__init__.pyi b/mypy/typeshed/stdlib/pydoc_data/__init__.pyi similarity index 100% rename from mypy/typeshed/stdlib/python2/distutils/__init__.pyi rename to mypy/typeshed/stdlib/pydoc_data/__init__.pyi diff --git a/mypy/typeshed/stdlib/pydoc_data/topics.pyi b/mypy/typeshed/stdlib/pydoc_data/topics.pyi new file mode 100644 index 000000000000..1c48f4022fd6 --- /dev/null +++ b/mypy/typeshed/stdlib/pydoc_data/topics.pyi @@ -0,0 +1,3 @@ +from typing import Dict + +topics: Dict[str, str] diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index edefe954b30f..c8305567e92e 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,8 +1,7 @@ -from typing import List, Tuple, Optional, Callable, Any, Union, Dict, Text -from _typeshed import SupportsRead - 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 @@ -49,10 +48,13 @@ class XMLParserType(object): 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]]] + 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]] @@ -70,5 +72,8 @@ class XMLParserType(object): 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: ... +def ParserCreate( + encoding: Optional[Text] = ..., namespace_separator: Optional[Text] = ..., intern: Optional[Dict[str, Any]] = ... +) -> XMLParserType: ... diff --git a/mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi b/mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi deleted file mode 100644 index ad5f24e21ad1..000000000000 --- a/mypy/typeshed/stdlib/python2/BaseHTTPServer.pyi +++ /dev/null @@ -1,47 +0,0 @@ -# Stubs for BaseHTTPServer (Python 2.7) - -from typing import Any, BinaryIO, Callable, Mapping, Optional, Tuple, Union -import SocketServer -import mimetools - -class HTTPServer(SocketServer.TCPServer): - server_name: str - server_port: int - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... - -class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): - client_address: Tuple[str, int] - server: SocketServer.BaseServer - close_connection: bool - command: str - path: str - request_version: str - headers: mimetools.Message - rfile: BinaryIO - wfile: BinaryIO - server_version: str - sys_version: str - error_message_format: str - error_content_type: str - protocol_version: str - MessageClass: type - responses: Mapping[int, Tuple[str, str]] - def __init__(self, request: bytes, client_address: Tuple[str, int], - server: SocketServer.BaseServer) -> None: ... - def handle(self) -> None: ... - def handle_one_request(self) -> None: ... - def send_error(self, code: int, message: Optional[str] = ...) -> None: ... - def send_response(self, code: int, - message: Optional[str] = ...) -> None: ... - def send_header(self, keyword: str, value: str) -> None: ... - def end_headers(self) -> None: ... - def flush_headers(self) -> None: ... - def log_request(self, code: Union[int, str] = ..., - size: Union[int, str] = ...) -> None: ... - def log_error(self, format: str, *args: Any) -> None: ... - def log_message(self, format: str, *args: Any) -> None: ... - def version_string(self) -> str: ... - def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... - def log_date_time_string(self) -> str: ... - def address_string(self) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi b/mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi deleted file mode 100644 index 4eae666d86d0..000000000000 --- a/mypy/typeshed/stdlib/python2/CGIHTTPServer.pyi +++ /dev/null @@ -1,8 +0,0 @@ -# Stubs for CGIHTTPServer (Python 2.7) - -from typing import List -import SimpleHTTPServer - -class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - cgi_directories: List[str] - def do_POST(self) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/ConfigParser.pyi b/mypy/typeshed/stdlib/python2/ConfigParser.pyi deleted file mode 100644 index d727ded105b8..000000000000 --- a/mypy/typeshed/stdlib/python2/ConfigParser.pyi +++ /dev/null @@ -1,97 +0,0 @@ -from typing import Any, IO, Sequence, Tuple, Union, List, Dict, Optional -from _typeshed import SupportsReadline - -DEFAULTSECT: str -MAX_INTERPOLATION_DEPTH: int - -class Error(Exception): - message: Any - def __init__(self, msg: str = ...) -> None: ... - def _get_message(self) -> None: ... - def _set_message(self, value: str) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - -class NoSectionError(Error): - section: str - def __init__(self, section: str) -> None: ... - -class DuplicateSectionError(Error): - section: str - def __init__(self, section: str) -> None: ... - -class NoOptionError(Error): - section: str - option: str - def __init__(self, option: str, section: str) -> None: ... - -class InterpolationError(Error): - section: str - option: str - msg: str - def __init__(self, option: str, section: str, msg: str) -> None: ... - -class InterpolationMissingOptionError(InterpolationError): - reference: str - def __init__(self, option: str, section: str, rawval: str, reference: str) -> None: ... - -class InterpolationSyntaxError(InterpolationError): ... - -class InterpolationDepthError(InterpolationError): - def __init__(self, option: str, section: str, rawval: str) -> None: ... - -class ParsingError(Error): - filename: str - errors: List[Tuple[Any, Any]] - def __init__(self, filename: str) -> None: ... - def append(self, lineno: Any, line: Any) -> None: ... - -class MissingSectionHeaderError(ParsingError): - lineno: Any - line: Any - def __init__(self, filename: str, lineno: Any, line: Any) -> None: ... - -class RawConfigParser: - _dict: Any - _sections: Dict[Any, Any] - _defaults: Dict[Any, Any] - _optcre: Any - SECTCRE: Any - OPTCRE: Any - OPTCRE_NV: Any - def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... - def defaults(self) -> Dict[Any, Any]: ... - def sections(self) -> List[str]: ... - def add_section(self, section: str) -> None: ... - def has_section(self, section: str) -> bool: ... - def options(self, section: str) -> List[str]: ... - def read(self, filenames: Union[str, Sequence[str]]) -> List[str]: ... - def readfp(self, fp: SupportsReadline[str], filename: str = ...) -> None: ... - def get(self, section: str, option: str) -> str: ... - def items(self, section: str) -> List[Tuple[Any, Any]]: ... - def _get(self, section: str, conv: type, option: str) -> Any: ... - def getint(self, section: str, option: str) -> int: ... - def getfloat(self, section: str, option: str) -> float: ... - _boolean_states: Dict[str, bool] - def getboolean(self, section: str, option: str) -> bool: ... - def optionxform(self, optionstr: str) -> str: ... - def has_option(self, section: str, option: str) -> bool: ... - def set(self, section: str, option: str, value: Any = ...) -> None: ... - def write(self, fp: IO[str]) -> None: ... - def remove_option(self, section: str, option: Any) -> bool: ... - def remove_section(self, section: str) -> bool: ... - def _read(self, fp: IO[str], fpname: str) -> None: ... - -class ConfigParser(RawConfigParser): - _KEYCRE: Any - def get(self, section: str, option: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> Any: ... - def items(self, section: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> List[Tuple[str, Any]]: ... - def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... - def _interpolation_replace(self, match: Any) -> str: ... - -class SafeConfigParser(ConfigParser): - _interpvar_re: Any - def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... - def _interpolate_some( - self, option: str, accum: List[Any], rest: str, section: str, map: Dict[Any, Any], depth: int, - ) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/Cookie.pyi b/mypy/typeshed/stdlib/python2/Cookie.pyi deleted file mode 100644 index 91dd93221c73..000000000000 --- a/mypy/typeshed/stdlib/python2/Cookie.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Any, Dict, Optional - -class CookieError(Exception): ... - -class Morsel(Dict[Any, Any]): - key: Any - def __init__(self): ... - def __setitem__(self, K, V): ... - def isReservedKey(self, K): ... - value: Any - coded_value: Any - def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ... - def output(self, attrs: Optional[Any] = ..., header=...): ... - def js_output(self, attrs: Optional[Any] = ...): ... - def OutputString(self, attrs: Optional[Any] = ...): ... - -class BaseCookie(Dict[Any, Any]): - def value_decode(self, val): ... - def value_encode(self, val): ... - def __init__(self, input: Optional[Any] = ...): ... - def __setitem__(self, key, value): ... - def output(self, attrs: Optional[Any] = ..., header=..., sep=...): ... - def js_output(self, attrs: Optional[Any] = ...): ... - def load(self, rawdata): ... - -class SimpleCookie(BaseCookie): - def value_decode(self, val): ... - def value_encode(self, val): ... - -class SerialCookie(BaseCookie): - def __init__(self, input: Optional[Any] = ...): ... - def value_decode(self, val): ... - def value_encode(self, val): ... - -class SmartCookie(BaseCookie): - def __init__(self, input: Optional[Any] = ...): ... - def value_decode(self, val): ... - def value_encode(self, val): ... - -Cookie: Any diff --git a/mypy/typeshed/stdlib/python2/HTMLParser.pyi b/mypy/typeshed/stdlib/python2/HTMLParser.pyi deleted file mode 100644 index 0f6c7e399a9c..000000000000 --- a/mypy/typeshed/stdlib/python2/HTMLParser.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import List, Tuple, AnyStr -from markupbase import ParserBase - -class HTMLParser(ParserBase): - def __init__(self) -> None: ... - def feed(self, feed: AnyStr) -> None: ... - def close(self) -> None: ... - def reset(self) -> None: ... - - def get_starttag_text(self) -> AnyStr: ... - def set_cdata_mode(self, AnyStr) -> None: ... - def clear_cdata_mode(self) -> None: ... - - def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... - def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... - def handle_endtag(self, tag: AnyStr): ... - def handle_charref(self, name: AnyStr): ... - def handle_entityref(self, name: AnyStr): ... - def handle_data(self, data: AnyStr): ... - def handle_comment(self, data: AnyStr): ... - def handle_decl(self, decl: AnyStr): ... - def handle_pi(self, data: AnyStr): ... - - def unknown_decl(self, data: AnyStr): ... - - def unescape(self, s: AnyStr) -> AnyStr: ... - -class HTMLParseError(Exception): - msg: str - lineno: int - offset: int diff --git a/mypy/typeshed/stdlib/python2/Queue.pyi b/mypy/typeshed/stdlib/python2/Queue.pyi deleted file mode 100644 index 76e3dcb5024f..000000000000 --- a/mypy/typeshed/stdlib/python2/Queue.pyi +++ /dev/null @@ -1,31 +0,0 @@ -# Stubs for Queue (Python 2) - -from collections import deque -from typing import Any, Deque, TypeVar, Generic, Optional - -_T = TypeVar('_T') - -class Empty(Exception): ... -class Full(Exception): ... - -class Queue(Generic[_T]): - maxsize: Any - mutex: Any - not_empty: Any - not_full: Any - all_tasks_done: Any - unfinished_tasks: Any - queue: Deque[Any] # undocumented - def __init__(self, maxsize: int = ...) -> None: ... - def task_done(self) -> None: ... - def join(self) -> None: ... - def qsize(self) -> int: ... - def empty(self) -> bool: ... - def full(self) -> bool: ... - def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... - def put_nowait(self, item: _T) -> None: ... - def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... - def get_nowait(self) -> _T: ... - -class PriorityQueue(Queue[_T]): ... -class LifoQueue(Queue[_T]): ... diff --git a/mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi b/mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi deleted file mode 100644 index 4a36cc5bdfe4..000000000000 --- a/mypy/typeshed/stdlib/python2/SimpleHTTPServer.pyi +++ /dev/null @@ -1,16 +0,0 @@ -# Stubs for SimpleHTTPServer (Python 2) - -from typing import Any, AnyStr, IO, Mapping, Optional, Union -import BaseHTTPServer -from StringIO import StringIO - -class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): - server_version: str - def do_GET(self) -> None: ... - def do_HEAD(self) -> None: ... - def send_head(self) -> Optional[IO[str]]: ... - def list_directory(self, path: Union[str, unicode]) -> Optional[StringIO[Any]]: ... - def translate_path(self, path: AnyStr) -> AnyStr: ... - def copyfile(self, source: IO[AnyStr], outputfile: IO[AnyStr]): ... - def guess_type(self, path: Union[str, unicode]) -> str: ... - extensions_map: Mapping[str, str] diff --git a/mypy/typeshed/stdlib/python2/SocketServer.pyi b/mypy/typeshed/stdlib/python2/SocketServer.pyi deleted file mode 100644 index 3f57efbe9766..000000000000 --- a/mypy/typeshed/stdlib/python2/SocketServer.pyi +++ /dev/null @@ -1,135 +0,0 @@ -# NB: SocketServer.pyi and socketserver.pyi must remain consistent! -# Stubs for socketserver - -from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, Text, Union -from socket import SocketType -import sys -import types - -class BaseServer: - address_family: int - RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: Tuple[str, int] - socket: SocketType - allow_reuse_address: bool - request_queue_size: int - socket_type: int - timeout: Optional[float] - def __init__(self, server_address: Any, - RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... - def fileno(self) -> int: ... - def handle_request(self) -> None: ... - def serve_forever(self, poll_interval: float = ...) -> None: ... - def shutdown(self) -> None: ... - def server_close(self) -> None: ... - def finish_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - def get_request(self) -> None: ... - def handle_error(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - def handle_timeout(self) -> None: ... - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - def server_activate(self) -> None: ... - def server_bind(self) -> None: ... - def verify_request(self, request: bytes, - client_address: Tuple[str, int]) -> bool: ... - if sys.version_info >= (3, 6): - def __enter__(self) -> BaseServer: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[types.TracebackType]) -> None: ... - if sys.version_info >= (3, 3): - def service_actions(self) -> None: ... - -class TCPServer(BaseServer): - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... - -class UDPServer(BaseServer): - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... - -if sys.platform != 'win32': - class UnixStreamServer(BaseServer): - def __init__(self, server_address: Union[Text, bytes], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... - - class UnixDatagramServer(BaseServer): - def __init__(self, server_address: Union[Text, bytes], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... - -if sys.platform != "win32": - class ForkingMixIn: - timeout: Optional[float] # undocumented - active_children: Optional[List[int]] # undocumented - max_children: int # undocumented - if sys.version_info >= (3, 7): - block_on_close: bool - if sys.version_info >= (3, 6): - def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented - else: - def collect_children(self) -> None: ... # undocumented - def handle_timeout(self) -> None: ... # undocumented - if sys.version_info >= (3, 3): - def service_actions(self) -> None: ... # undocumented - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - if sys.version_info >= (3, 6): - def server_close(self) -> None: ... - -class ThreadingMixIn: - daemon_threads: bool - if sys.version_info >= (3, 7): - block_on_close: bool - def process_request_thread(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... # undocumented - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - if sys.version_info >= (3, 6): - def server_close(self) -> None: ... - -if sys.platform != "win32": - class ForkingTCPServer(ForkingMixIn, TCPServer): ... - class ForkingUDPServer(ForkingMixIn, UDPServer): ... -class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... -class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... -if sys.platform != 'win32': - class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... - class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... - - -class BaseRequestHandler: - # Those are technically of types, respectively: - # * Union[SocketType, Tuple[bytes, SocketType]] - # * Union[Tuple[str, int], str] - # But there are some concerns that having unions here would cause - # too much inconvenience to people using it (see - # https://github.com/python/typeshed/pull/384#issuecomment-234649696) - request: Any - client_address: Any - server: BaseServer - - def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... - def setup(self) -> None: ... - def handle(self) -> None: ... - def finish(self) -> None: ... - -class StreamRequestHandler(BaseRequestHandler): - rbufsize: ClassVar[int] # Undocumented - wbufsize: ClassVar[int] # Undocumented - timeout: ClassVar[Optional[float]] # Undocumented - disable_nagle_algorithm: ClassVar[bool] # Undocumented - connection: SocketType # Undocumented - rfile: BinaryIO - wfile: BinaryIO - -class DatagramRequestHandler(BaseRequestHandler): - packet: SocketType # Undocumented - socket: SocketType # Undocumented - rfile: BinaryIO - wfile: BinaryIO diff --git a/mypy/typeshed/stdlib/python2/StringIO.pyi b/mypy/typeshed/stdlib/python2/StringIO.pyi deleted file mode 100644 index de17f6abadfa..000000000000 --- a/mypy/typeshed/stdlib/python2/StringIO.pyi +++ /dev/null @@ -1,30 +0,0 @@ -# Stubs for StringIO (Python 2) - -from typing import Any, IO, AnyStr, Iterator, Iterable, Generic, List, Optional - -class StringIO(IO[AnyStr], Generic[AnyStr]): - closed: bool - softspace: int - len: int - name: str - def __init__(self, buf: AnyStr = ...) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - def next(self) -> AnyStr: ... - def close(self) -> None: ... - def isatty(self) -> bool: ... - def seek(self, pos: int, mode: int = ...) -> int: ... - def tell(self) -> int: ... - def read(self, n: int = ...) -> AnyStr: ... - def readline(self, length: int = ...) -> AnyStr: ... - def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... - def truncate(self, size: Optional[int] = ...) -> int: ... - def write(self, s: AnyStr) -> int: ... - def writelines(self, iterable: Iterable[AnyStr]) -> None: ... - def flush(self) -> None: ... - def getvalue(self) -> AnyStr: ... - def __enter__(self) -> Any: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> Any: ... - def fileno(self) -> int: ... - def readable(self) -> bool: ... - def seekable(self) -> bool: ... - def writable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/python2/UserDict.pyi b/mypy/typeshed/stdlib/python2/UserDict.pyi deleted file mode 100644 index 1d850cfc2750..000000000000 --- a/mypy/typeshed/stdlib/python2/UserDict.pyi +++ /dev/null @@ -1,44 +0,0 @@ -from typing import (Any, Container, Dict, Generic, Iterable, Iterator, List, - Mapping, Optional, Sized, Tuple, TypeVar, Union, overload) - -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') -_T = TypeVar('_T') - -class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): - data: Dict[_KT, _VT] - - def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... - - # TODO: __iter__ is not available for UserDict - -class IterableUserDict(UserDict[_KT, _VT], Generic[_KT, _VT]): - ... - -class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): - def has_key(self, key: _KT) -> bool: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_KT]: ... - - # From typing.Mapping[_KT, _VT] - # (can't inherit because of keys()) - @overload - def get(self, k: _KT) -> Optional[_VT]: ... - @overload - def get(self, k: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ... - 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 __contains__(self, o: Any) -> bool: ... - - # From typing.MutableMapping[_KT, _VT] - def clear(self) -> None: ... - def pop(self, k: _KT, default: _VT = ...) -> _VT: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... - @overload - def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/UserList.pyi b/mypy/typeshed/stdlib/python2/UserList.pyi deleted file mode 100644 index 3c71e8292e3f..000000000000 --- a/mypy/typeshed/stdlib/python2/UserList.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Iterable, MutableSequence, TypeVar, Union, overload, List - -_T = TypeVar("_T") -_S = TypeVar("_S") - -class UserList(MutableSequence[_T]): - data: List[_T] - def insert(self, index: int, object: _T) -> None: ... - @overload - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: Union[int, slice]) -> None: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self: _S, s: slice) -> _S: ... - def sort(self) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/UserString.pyi b/mypy/typeshed/stdlib/python2/UserString.pyi deleted file mode 100644 index 704a93bc0962..000000000000 --- a/mypy/typeshed/stdlib/python2/UserString.pyi +++ /dev/null @@ -1,75 +0,0 @@ -import collections -from typing import Any, Iterable, List, MutableSequence, Sequence, Optional, overload, Text, TypeVar, Tuple, Union - -_UST = TypeVar("_UST", bound=UserString) -_MST = TypeVar("_MST", bound=MutableString) - -class UserString(Sequence[UserString]): - data: unicode - def __init__(self, seq: object) -> None: ... - def __int__(self) -> int: ... - def __long__(self) -> long: ... - def __float__(self) -> float: ... - def __complex__(self) -> complex: ... - def __hash__(self) -> int: ... - def __len__(self) -> int: ... - @overload - def __getitem__(self: _UST, i: int) -> _UST: ... - @overload - def __getitem__(self: _UST, s: slice) -> _UST: ... - def __add__(self: _UST, other: Any) -> _UST: ... - def __radd__(self: _UST, other: Any) -> _UST: ... - def __mul__(self: _UST, other: int) -> _UST: ... - def __rmul__(self: _UST, other: int) -> _UST: ... - def __mod__(self: _UST, args: Any) -> _UST: ... - def capitalize(self: _UST) -> _UST: ... - def center(self: _UST, width: int, *args: Any) -> _UST: ... - def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... - def decode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... - def encode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... - def endswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... - def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... - def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def isalpha(self) -> bool: ... - def isalnum(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, seq: Iterable[Text]) -> Text: ... - def ljust(self: _UST, width: int, *args: Any) -> _UST: ... - def lower(self: _UST) -> _UST: ... - def lstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... - def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... - def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UST, width: int, *args: Any) -> _UST: ... - def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def rstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... - def split(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... - def rsplit(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... - def splitlines(self, keepends: int = ...) -> List[Text]: ... - def startswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... - def strip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... - def swapcase(self: _UST) -> _UST: ... - def title(self: _UST) -> _UST: ... - def translate(self: _UST, *args: Any) -> _UST: ... - def upper(self: _UST) -> _UST: ... - def zfill(self: _UST, width: int) -> _UST: ... - -class MutableString(UserString, MutableSequence[MutableString]): - @overload - def __getitem__(self: _MST, i: int) -> _MST: ... - @overload - def __getitem__(self: _MST, s: slice) -> _MST: ... - def __setitem__(self, index: Union[int, slice], sub: Any) -> None: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - def immutable(self) -> UserString: ... - def __iadd__(self: _MST, other: Any) -> _MST: ... - def __imul__(self, n: int) -> _MST: ... - def insert(self, index: int, value: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/__builtin__.pyi b/mypy/typeshed/stdlib/python2/__builtin__.pyi deleted file mode 100644 index c644038d1446..000000000000 --- a/mypy/typeshed/stdlib/python2/__builtin__.pyi +++ /dev/null @@ -1,1842 +0,0 @@ -# True and False are deliberately omitted because they are keywords in -# Python 3, and stub files conform to Python 3 syntax. - -from typing import ( - TypeVar, Iterator, Iterable, NoReturn, overload, Container, - Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, - Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, - SupportsComplex, IO, BinaryIO, Union, - ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, - Protocol, -) -from abc import ABCMeta -from ast import mod, AST -from io import ( - TextIOWrapper, FileIO, BufferedRandom, BufferedReader, BufferedWriter -) -from types import TracebackType, CodeType -from _typeshed import ( - AnyPath, OpenBinaryMode, OpenTextMode, - OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenBinaryModeReading, - SupportsWrite, ReadableBuffer, -) -from typing_extensions import Literal -import sys - -if sys.version_info >= (3,): - from typing import SupportsBytes, SupportsRound - -if sys.version_info >= (3, 9): - from types import GenericAlias - -class _SupportsIndex(Protocol): - def __index__(self) -> int: ... - -class _SupportsLessThan(Protocol): - def __lt__(self, other: Any) -> bool: ... - -_T = TypeVar('_T') -_T_co = TypeVar('_T_co', covariant=True) -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') -_S = TypeVar('_S') -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_T3 = TypeVar('_T3') -_T4 = TypeVar('_T4') -_T5 = TypeVar('_T5') -_TT = TypeVar('_TT', bound='type') -_LT = TypeVar('_LT', bound=_SupportsLessThan) - -class object: - __doc__: Optional[str] - __dict__: Dict[str, Any] - __slots__: Union[Text, Iterable[Text]] - __module__: str - if sys.version_info >= (3, 6): - __annotations__: Dict[str, Any] - - @property - def __class__(self: _T) -> Type[_T]: ... - @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 - def __init__(self) -> None: ... - def __new__(cls) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __eq__(self, o: object) -> bool: ... - def __ne__(self, o: object) -> bool: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __hash__(self) -> int: ... - def __format__(self, format_spec: str) -> str: ... - def __getattribute__(self, name: str) -> Any: ... - def __delattr__(self, name: str) -> None: ... - def __sizeof__(self) -> int: ... - def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... - def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... - if sys.version_info >= (3,): - def __dir__(self) -> Iterable[str]: ... - if sys.version_info >= (3, 6): - def __init_subclass__(cls) -> None: ... - -class staticmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - if sys.version_info >= (3,): - __isabstractmethod__: bool - - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... - -class classmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] - if sys.version_info >= (3,): - __isabstractmethod__: bool - - def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... - -class type(object): - __base__: type - __bases__: Tuple[type, ...] - __basicsize__: int - __dict__: Dict[str, Any] - __dictoffset__: int - __flags__: int - __itemsize__: int - __module__: str - __mro__: Tuple[type, ...] - __name__: str - if sys.version_info >= (3,): - __qualname__: str - __text_signature__: Optional[str] - __weakrefoffset__: int - - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... - @overload - def __new__(cls, o: object) -> type: ... - @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... - def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> List[_TT]: ... - # Note: the documentation doesnt specify what the return type is, the standard - # implementation seems to be returning a list. - def mro(self) -> List[type]: ... - def __instancecheck__(self, instance: Any) -> bool: ... - def __subclasscheck__(self, subclass: type) -> bool: ... - if sys.version_info >= (3,): - @classmethod - def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class super(object): - if sys.version_info >= (3,): - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... - @overload - def __init__(self) -> None: ... - else: - @overload - def __init__(self, t: Any, obj: Any) -> None: ... - @overload - def __init__(self, t: Any) -> None: ... - -class int: - @overload - def __init__(self, x: Union[Text, bytes, SupportsInt, _SupportsIndex] = ...) -> None: ... - @overload - def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... - - if sys.version_info >= (3, 8): - def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... - @property - def real(self) -> int: ... - @property - def imag(self) -> int: ... - @property - def numerator(self) -> int: ... - @property - def denominator(self) -> int: ... - def conjugate(self) -> int: ... - - def bit_length(self) -> int: ... - if sys.version_info >= (3,): - def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... - @classmethod - def from_bytes(cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, - signed: bool = ...) -> int: ... # TODO buffer object argument - - def __add__(self, x: int) -> int: ... - def __sub__(self, x: int) -> int: ... - def __mul__(self, x: int) -> int: ... - def __floordiv__(self, x: int) -> int: ... - if sys.version_info < (3,): - def __div__(self, x: int) -> int: ... - def __truediv__(self, x: int) -> float: ... - def __mod__(self, x: int) -> int: ... - def __divmod__(self, x: int) -> Tuple[int, int]: ... - def __radd__(self, x: int) -> int: ... - def __rsub__(self, x: int) -> int: ... - def __rmul__(self, x: int) -> int: ... - def __rfloordiv__(self, x: int) -> int: ... - if sys.version_info < (3,): - def __rdiv__(self, x: int) -> int: ... - def __rtruediv__(self, x: int) -> float: ... - def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> Tuple[int, int]: ... - def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. - def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... - def __and__(self, n: int) -> int: ... - def __or__(self, n: int) -> int: ... - def __xor__(self, n: int) -> int: ... - def __lshift__(self, n: int) -> int: ... - def __rshift__(self, n: int) -> int: ... - def __rand__(self, n: int) -> int: ... - def __ror__(self, n: int) -> int: ... - def __rxor__(self, n: int) -> int: ... - def __rlshift__(self, n: int) -> int: ... - def __rrshift__(self, n: int) -> int: ... - def __neg__(self) -> int: ... - def __pos__(self) -> int: ... - def __invert__(self) -> int: ... - def __trunc__(self) -> int: ... - if sys.version_info >= (3,): - def __ceil__(self) -> int: ... - def __floor__(self) -> int: ... - def __round__(self, ndigits: Optional[int] = ...) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: int) -> bool: ... - def __le__(self, x: int) -> bool: ... - def __gt__(self, x: int) -> bool: ... - def __ge__(self, x: int) -> bool: ... - - def __str__(self) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - def __abs__(self) -> int: ... - def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - def __index__(self) -> int: ... - -class float: - def __init__(self, x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> None: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... - def hex(self) -> str: ... - def is_integer(self) -> bool: ... - @classmethod - def fromhex(cls, __s: str) -> float: ... - - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - def conjugate(self) -> float: ... - - def __add__(self, x: float) -> float: ... - def __sub__(self, x: float) -> float: ... - def __mul__(self, x: float) -> float: ... - def __floordiv__(self, x: float) -> float: ... - if sys.version_info < (3,): - def __div__(self, x: float) -> float: ... - def __truediv__(self, x: float) -> float: ... - def __mod__(self, x: float) -> float: ... - def __divmod__(self, x: float) -> Tuple[float, float]: ... - def __pow__(self, x: float, mod: None = ...) -> float: ... # In Python 3, returns complex if self is negative and x is not whole - def __radd__(self, x: float) -> float: ... - def __rsub__(self, x: float) -> float: ... - def __rmul__(self, x: float) -> float: ... - def __rfloordiv__(self, x: float) -> float: ... - if sys.version_info < (3,): - def __rdiv__(self, x: float) -> float: ... - def __rtruediv__(self, x: float) -> float: ... - def __rmod__(self, x: float) -> float: ... - def __rdivmod__(self, x: float) -> Tuple[float, float]: ... - def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... - def __trunc__(self) -> int: ... - if sys.version_info >= (3,): - @overload - def __round__(self, ndigits: None = ...) -> int: ... - @overload - def __round__(self, ndigits: int) -> float: ... - - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: float) -> bool: ... - def __le__(self, x: float) -> bool: ... - def __gt__(self, x: float) -> bool: ... - def __ge__(self, x: float) -> bool: ... - def __neg__(self) -> float: ... - def __pos__(self) -> float: ... - - def __str__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - -class complex: - @overload - def __init__(self, real: float = ..., imag: float = ...) -> None: ... - @overload - def __init__(self, real: Union[str, SupportsComplex, _SupportsIndex]) -> None: ... - - @property - def real(self) -> float: ... - @property - def imag(self) -> float: ... - - def conjugate(self) -> complex: ... - - def __add__(self, x: complex) -> complex: ... - def __sub__(self, x: complex) -> complex: ... - def __mul__(self, x: complex) -> complex: ... - def __pow__(self, x: complex, mod: None = ...) -> complex: ... - if sys.version_info < (3,): - def __div__(self, x: complex) -> complex: ... - def __truediv__(self, x: complex) -> complex: ... - def __radd__(self, x: complex) -> complex: ... - def __rsub__(self, x: complex) -> complex: ... - def __rmul__(self, x: complex) -> complex: ... - def __rpow__(self, x: complex, mod: None = ...) -> complex: ... - if sys.version_info < (3,): - def __rdiv__(self, x: complex) -> complex: ... - def __rtruediv__(self, x: complex) -> complex: ... - - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __neg__(self) -> complex: ... - def __pos__(self) -> complex: ... - - def __str__(self) -> str: ... - def __complex__(self) -> complex: ... - def __abs__(self) -> float: ... - def __hash__(self) -> int: ... - if sys.version_info >= (3,): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - -if sys.version_info >= (3,): - _str_base = object -else: - class basestring(metaclass=ABCMeta): ... - - class unicode(basestring, Sequence[unicode]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: object) -> None: ... - @overload - def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... - def capitalize(self) -> unicode: ... - def center(self, width: int, fillchar: unicode = ...) -> unicode: ... - def count(self, x: unicode) -> int: ... - def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... - def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., - end: int = ...) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> unicode: ... - def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> unicode: ... - def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - def isidentifier(self) -> bool: ... - def islower(self) -> bool: ... - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, iterable: Iterable[unicode]) -> unicode: ... - def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def lower(self) -> unicode: ... - def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... - def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... - def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... - def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., - end: int = ...) -> bool: ... - def strip(self, chars: unicode = ...) -> unicode: ... - def swapcase(self) -> unicode: ... - def title(self) -> unicode: ... - def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... - def upper(self) -> unicode: ... - def zfill(self, width: int) -> unicode: ... - - @overload - def __getitem__(self, i: int) -> unicode: ... - @overload - def __getitem__(self, s: slice) -> unicode: ... - def __getslice__(self, start: int, stop: int) -> unicode: ... - def __add__(self, s: unicode) -> unicode: ... - def __mul__(self, n: int) -> unicode: ... - def __rmul__(self, n: int) -> unicode: ... - def __mod__(self, x: Any) -> unicode: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: unicode) -> bool: ... - def __le__(self, x: unicode) -> bool: ... - def __gt__(self, x: unicode) -> bool: ... - def __ge__(self, x: unicode) -> bool: ... - - def __len__(self) -> int: ... - # The argument type is incompatible with Sequence - def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore - def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... - - _str_base = basestring - -class _FormatMapMapping(Protocol): - def __getitem__(self, __key: str) -> Any: ... - -class str(Sequence[str], _str_base): - if sys.version_info >= (3,): - @overload - def __init__(self, o: object = ...) -> None: ... - @overload - def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... - else: - def __init__(self, o: object = ...) -> None: ... - - def capitalize(self) -> str: ... - if sys.version_info >= (3, 3): - def casefold(self) -> str: ... - def center(self, __width: int, __fillchar: str = ...) -> str: ... - def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - if sys.version_info < (3,): - def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... - def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - if sys.version_info >= (3,): - def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., - end: Optional[int] = ...) -> bool: ... - else: - def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> str: ... - if sys.version_info >= (3,): - def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... - if sys.version_info >= (3,): - def isdecimal(self) -> bool: ... - def isdigit(self) -> bool: ... - if sys.version_info >= (3,): - def isidentifier(self) -> bool: ... - def islower(self) -> bool: ... - if sys.version_info >= (3,): - def isnumeric(self) -> bool: ... - def isprintable(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - if sys.version_info >= (3,): - def join(self, __iterable: Iterable[str]) -> str: ... - else: - def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... - def ljust(self, __width: int, __fillchar: str = ...) -> str: ... - def lower(self) -> str: ... - if sys.version_info >= (3,): - def lstrip(self, __chars: Optional[str] = ...) -> str: ... - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... - else: - @overload - def lstrip(self, __chars: str = ...) -> str: ... - @overload - def lstrip(self, __chars: unicode) -> unicode: ... - @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: str) -> str: ... - def removesuffix(self, __suffix: str) -> str: ... - def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rjust(self, __width: int, __fillchar: str = ...) -> str: ... - if sys.version_info >= (3,): - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - def rstrip(self, __chars: Optional[str] = ...) -> str: ... - def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - else: - @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... - @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - @overload - def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - @overload - def rstrip(self, __chars: str = ...) -> str: ... - @overload - def rstrip(self, __chars: unicode) -> unicode: ... - @overload - def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... - @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[str]: ... - if sys.version_info >= (3,): - def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., - end: Optional[int] = ...) -> bool: ... - def strip(self, __chars: Optional[str] = ...) -> str: ... - else: - def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... - @overload - def strip(self, __chars: str = ...) -> str: ... - @overload - def strip(self, chars: unicode) -> unicode: ... - def swapcase(self) -> str: ... - def title(self) -> str: ... - if sys.version_info >= (3,): - def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... - else: - def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... - def upper(self) -> str: ... - def zfill(self, __width: int) -> str: ... - if sys.version_info >= (3,): - @staticmethod - @overload - def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... - @staticmethod - @overload - def maketrans(__x: str, __y: str, __z: Optional[str] = ...) -> Dict[int, Union[int, None]]: ... - - if sys.version_info >= (3,): - def __add__(self, s: str) -> str: ... - else: - def __add__(self, s: AnyStr) -> AnyStr: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ge__(self, x: Text) -> bool: ... - def __getitem__(self, i: Union[int, slice]) -> str: ... - def __gt__(self, x: Text) -> bool: ... - def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... - def __le__(self, x: Text) -> bool: ... - def __len__(self) -> int: ... - def __lt__(self, x: Text) -> bool: ... - def __mod__(self, x: Any) -> str: ... - def __mul__(self, n: int) -> str: ... - def __ne__(self, x: object) -> bool: ... - def __repr__(self) -> str: ... - def __rmul__(self, n: int) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> Tuple[str]: ... - - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> str: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - -if sys.version_info >= (3,): - class bytes(ByteString): - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str, encoding: str, - errors: str = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, o: SupportsBytes) -> None: ... - def capitalize(self) -> bytes: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def decode(self, encoding: str = ..., errors: str = ...) -> str: ... - def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytes: ... - def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... - elif sys.version_info >= (3, 5): - def hex(self) -> str: ... - def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def lower(self) -> bytes: ... - def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytes: ... - def removesuffix(self, __suffix: bytes) -> bytes: ... - def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... - def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... - def splitlines(self, keepends: bool = ...) -> List[bytes]: ... - def startswith( - self, - prefix: Union[bytes, Tuple[bytes, ...]], - start: Optional[int] = ..., - end: Optional[int] = ..., - ) -> bool: ... - def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def swapcase(self) -> bytes: ... - def title(self) -> bytes: ... - def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... - def upper(self) -> bytes: ... - def zfill(self, __width: int) -> bytes: ... - @classmethod - def fromhex(cls, __s: str) -> bytes: ... - @classmethod - def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... - - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - def __hash__(self) -> int: ... - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> bytes: ... - def __add__(self, s: bytes) -> bytes: ... - def __mul__(self, n: int) -> bytes: ... - def __rmul__(self, n: int) -> bytes: ... - if sys.version_info >= (3, 5): - def __mod__(self, value: Any) -> bytes: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... - def __getnewargs__(self) -> Tuple[bytes]: ... -else: - bytes = str - -class bytearray(MutableSequence[int], ByteString): - if sys.version_info >= (3,): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - else: - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, ints: Iterable[int]) -> None: ... - @overload - def __init__(self, string: str) -> None: ... - @overload - def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... - @overload - def __init__(self, length: int) -> None: ... - def capitalize(self) -> bytearray: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - if sys.version_info >= (3,): - def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def copy(self) -> bytearray: ... - else: - def count(self, __sub: str) -> int: ... - def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... - def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - if sys.version_info < (3,): - def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... - if sys.version_info >= (3,): - def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - if sys.version_info >= (3, 5): - def hex(self) -> str: ... - def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - else: - def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... - def insert(self, __index: int, __item: int) -> None: ... - def isalnum(self) -> bool: ... - def isalpha(self) -> bool: ... - if sys.version_info >= (3, 7): - def isascii(self) -> bool: ... - def isdigit(self) -> bool: ... - def islower(self) -> bool: ... - def isspace(self) -> bool: ... - def istitle(self) -> bool: ... - def isupper(self) -> bool: ... - if sys.version_info >= (3,): - def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - else: - def join(self, __iterable: Iterable[str]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... - def lower(self) -> bytearray: ... - def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytearray: ... - def removesuffix(self, __suffix: bytes) -> bytearray: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... - if sys.version_info >= (3,): - def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - else: - def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... - def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... - def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith( - self, - __prefix: Union[bytes, Tuple[bytes, ...]], - __start: Optional[int] = ..., - __end: Optional[int] = ..., - ) -> bool: ... - def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... - def swapcase(self) -> bytearray: ... - def title(self) -> bytearray: ... - if sys.version_info >= (3,): - def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... - else: - def translate(self, __table: str) -> bytearray: ... - def upper(self) -> bytearray: ... - def zfill(self, __width: int) -> bytearray: ... - @classmethod - def fromhex(cls, __string: str) -> bytearray: ... - if sys.version_info >= (3,): - @classmethod - def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... - - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def __int__(self) -> int: ... - def __float__(self) -> float: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> bytearray: ... - @overload - def __setitem__(self, i: int, x: int) -> None: ... - @overload - def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... - def __delitem__(self, i: Union[int, slice]) -> None: ... - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> bytearray: ... - def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, s: bytes) -> bytearray: ... - if sys.version_info >= (3,): - def __iadd__(self, s: Iterable[int]) -> bytearray: ... - def __mul__(self, n: int) -> bytearray: ... - if sys.version_info >= (3,): - def __rmul__(self, n: int) -> bytearray: ... - def __imul__(self, n: int) -> bytearray: ... - if sys.version_info >= (3, 5): - def __mod__(self, value: Any) -> bytes: ... - # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... - -if sys.version_info >= (3,): - _mv_container_type = int -else: - _mv_container_type = str - -class memoryview(Sized, Container[_mv_container_type]): - format: str - itemsize: int - shape: Optional[Tuple[int, ...]] - strides: Optional[Tuple[int, ...]] - suboffsets: Optional[Tuple[int, ...]] - readonly: bool - ndim: int - - if sys.version_info >= (3,): - obj: Union[bytes, bytearray] - c_contiguous: bool - f_contiguous: bool - contiguous: bool - nbytes: int - def __init__(self, obj: ReadableBuffer) -> None: ... - def __enter__(self) -> memoryview: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... - def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... - else: - def __init__(self, obj: ReadableBuffer) -> None: ... - - @overload - def __getitem__(self, i: int) -> _mv_container_type: ... - @overload - def __getitem__(self, s: slice) -> memoryview: ... - - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[_mv_container_type]: ... - def __len__(self) -> int: ... - - @overload - def __setitem__(self, s: slice, o: memoryview) -> None: ... - @overload - def __setitem__(self, i: int, o: bytes) -> None: ... - @overload - def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... - - if sys.version_info >= (3, 8): - def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... - else: - def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... - if sys.version_info >= (3, 8): - def toreadonly(self) -> memoryview: ... - - if sys.version_info >= (3, 2): - def release(self) -> None: ... - - if sys.version_info >= (3, 5): - def hex(self) -> str: ... - -class bool(int): - def __init__(self, o: object = ...) -> None: ... - @overload - def __and__(self, x: bool) -> bool: ... - @overload - def __and__(self, x: int) -> int: ... - @overload - def __or__(self, x: bool) -> bool: ... - @overload - def __or__(self, x: int) -> int: ... - @overload - def __xor__(self, x: bool) -> bool: ... - @overload - def __xor__(self, x: int) -> int: ... - @overload - def __rand__(self, x: bool) -> bool: ... - @overload - def __rand__(self, x: int) -> int: ... - @overload - def __ror__(self, x: bool) -> bool: ... - @overload - def __ror__(self, x: int) -> int: ... - @overload - def __rxor__(self, x: bool) -> bool: ... - @overload - def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... - -class slice(object): - start: Any - step: Any - stop: Any - @overload - def __init__(self, stop: Any) -> None: ... - @overload - def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... - -class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... - def __len__(self) -> int: ... - def __contains__(self, x: object) -> bool: ... - @overload - def __getitem__(self, x: int) -> _T_co: ... - @overload - def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... - @overload - def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... - @overload - def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... - def count(self, __value: Any) -> int: ... - if sys.version_info >= (3, 5): - def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... - else: - def index(self, __value: Any) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class function: - # TODO not defined in builtins! - __name__: str - __module__: str - __code__: CodeType - if sys.version_info >= (3,): - __qualname__: str - __annotations__: Dict[str, Any] - -class list(MutableSequence[_T], Generic[_T]): - @overload - def __init__(self) -> None: ... - @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... - if sys.version_info >= (3,): - def clear(self) -> None: ... - def copy(self) -> List[_T]: ... - def append(self, __object: _T) -> None: ... - def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: int = ...) -> _T: ... - def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... - def count(self, __value: _T) -> int: ... - def insert(self, __index: int, __object: _T) -> None: ... - def remove(self, __value: _T) -> None: ... - def reverse(self) -> None: ... - if sys.version_info >= (3,): - @overload - def sort(self: List[_LT], *, key: None = ..., reverse: bool = ...) -> None: ... - @overload - def sort(self, *, key: Callable[[_T], _SupportsLessThan], reverse: bool = ...) -> None: ... - else: - def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... - - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - @overload - def __getitem__(self, i: int) -> _T: ... - @overload - def __getitem__(self, s: slice) -> List[_T]: ... - @overload - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: Union[int, slice]) -> None: ... - if sys.version_info < (3,): - def __getslice__(self, start: int, stop: int) -> List[_T]: ... - def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... - def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, x: List[_T]) -> List[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... - if sys.version_info >= (3,): - def __imul__(self: _S, n: int) -> _S: ... - def __contains__(self, o: object) -> bool: ... - def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, x: List[_T]) -> bool: ... - def __ge__(self, x: List[_T]) -> bool: ... - def __lt__(self, x: List[_T]) -> bool: ... - def __le__(self, x: List[_T]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - # NOTE: Keyword arguments are special. If they are used, _KT must include - # str, but we have no way of enforcing it here. - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... - - if sys.version_info < (3,): - def has_key(self, k: _KT) -> bool: ... - def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - if sys.version_info >= (3,): - def keys(self) -> KeysView[_KT]: ... - def values(self) -> ValuesView[_VT]: ... - def items(self) -> ItemsView[_KT, _VT]: ... - else: - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... - def viewkeys(self) -> KeysView[_KT]: ... - def viewvalues(self) -> ValuesView[_VT]: ... - def viewitems(self) -> ItemsView[_KT, _VT]: ... - @classmethod - @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... - @classmethod - @overload - 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: ... - def __delitem__(self, v: _KT) -> None: ... - def __iter__(self) -> Iterator[_KT]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... - __hash__: None # type: ignore - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class set(MutableSet[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ...) -> None: ... - def add(self, element: _T) -> None: ... - def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... - def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... - def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, s: Iterable[Any]) -> bool: ... - def issubset(self, s: Iterable[Any]) -> bool: ... - def issuperset(self, s: Iterable[Any]) -> bool: ... - def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... - def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... - def update(self, *s: Iterable[_T]) -> None: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... - def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - __hash__: None # type: ignore - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... - def issubset(self, s: Iterable[object]) -> bool: ... - def issuperset(self, s: Iterable[object]) -> bool: ... - def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): - def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... - def __iter__(self) -> Iterator[Tuple[int, _T]]: ... - if sys.version_info >= (3,): - def __next__(self) -> Tuple[int, _T]: ... - else: - def next(self) -> Tuple[int, _T]: ... - -if sys.version_info >= (3,): - class range(Sequence[int]): - start: int - stop: int - step: int - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def count(self, value: int) -> int: ... - def index(self, value: int) -> int: ... # type: ignore - def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[int]: ... - @overload - def __getitem__(self, i: int) -> int: ... - @overload - def __getitem__(self, s: slice) -> range: ... - def __repr__(self) -> str: ... - def __reversed__(self) -> Iterator[int]: ... -else: - class xrange(Sized, Iterable[int], Reversible[int]): - @overload - def __init__(self, stop: int) -> None: ... - @overload - def __init__(self, start: int, stop: int, step: int = ...) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[int]: ... - def __getitem__(self, i: int) -> int: ... - def __reversed__(self) -> Iterator[int]: ... - -class property(object): - def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., - fset: Optional[Callable[[Any, Any], None]] = ..., - fdel: Optional[Callable[[Any], None]] = ..., - doc: Optional[str] = ...) -> None: ... - def getter(self, fget: Callable[[Any], Any]) -> property: ... - def setter(self, fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, fdel: Callable[[Any], None]) -> property: ... - def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... - def __set__(self, obj: Any, value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - def fget(self) -> Any: ... - def fset(self, value: Any) -> None: ... - def fdel(self) -> None: ... - -if sys.version_info < (3,): - long = int - -class _NotImplementedType(Any): # type: ignore - # A little weird, but typing the __call__ as NotImplemented makes the error message - # for NotImplemented() much better - __call__: NotImplemented # type: ignore - -NotImplemented: _NotImplementedType - -def abs(__x: SupportsAbs[_T]) -> _T: ... -def all(__iterable: Iterable[object]) -> bool: ... -def any(__iterable: Iterable[object]) -> bool: ... -if sys.version_info < (3,): - def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... -if sys.version_info >= (3,): - def ascii(__obj: object) -> str: ... - -def bin(__number: Union[int, _SupportsIndex]) -> str: ... - -if sys.version_info >= (3, 7): - def breakpoint(*args: Any, **kws: Any) -> None: ... -def callable(__obj: object) -> bool: ... -def chr(__i: int) -> str: ... -if sys.version_info < (3,): - def cmp(__x: Any, __y: Any) -> int: ... - _N1 = TypeVar('_N1', bool, int, float, complex) - def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... -if sys.version_info >= (3, 6): - # This class is to be exported as PathLike from os, - # but we define it here as _PathLike to avoid import cycle issues. - # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 - class _PathLike(Generic[AnyStr]): - def __fspath__(self) -> AnyStr: ... - def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes, _PathLike[Any]], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... -elif sys.version_info >= (3,): - def compile(source: Union[str, bytes, mod, AST], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... -else: - def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... -if sys.version_info >= (3,): - def copyright() -> None: ... - def credits() -> None: ... -def delattr(__obj: Any, __name: Text) -> None: ... -def dir(__o: object = ...) -> List[str]: ... -_N2 = TypeVar('_N2', int, float) -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... -def eval(__source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... -if sys.version_info >= (3,): - def exec(__source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ...) -> Any: ... -else: - def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... -def exit(code: object = ...) -> NoReturn: ... -if sys.version_info >= (3,): - @overload - def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... - @overload - def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... -else: - @overload - def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore - @overload - def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore - @overload - def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore - @overload - 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: ... -def globals() -> Dict[str, Any]: ... -def hasattr(__obj: Any, __name: Text) -> bool: ... -def hash(__obj: object) -> int: ... -if sys.version_info >= (3,): - def help(*args: Any, **kwds: Any) -> None: ... -def hex(__number: Union[int, _SupportsIndex]) -> str: ... -def id(__obj: object) -> int: ... -if sys.version_info >= (3,): - def input(__prompt: Any = ...) -> str: ... -else: - def input(__prompt: Any = ...) -> Any: ... - def intern(__string: str) -> str: ... -@overload -def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -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: ... -def len(__obj: Sized) -> int: ... -if sys.version_info >= (3,): - def license() -> None: ... -def locals() -> Dict[str, Any]: ... -if sys.version_info >= (3,): - @overload - def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> Iterator[_S]: ... - @overload - def map(__func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[_S]: ... -else: - @overload - def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def map(__func: None, - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def map(__func: None, - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... - @overload - def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[_S]: ... - @overload - def map(__func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5]) -> List[_S]: ... - @overload - def map(__func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[_S]: ... -if sys.version_info >= (3,): - @overload - def max(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... - @overload - def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... - @overload - def max(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... - @overload - def max(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... - @overload - def max(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... - @overload - def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... -else: - @overload - def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... - @overload - def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -if sys.version_info >= (3,): - @overload - def min(__arg1: _LT, __arg2: _LT, *_args: _LT, key: None = ...) -> _LT: ... - @overload - def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], _LT]) -> _T: ... - @overload - def min(__iterable: Iterable[_LT], *, key: None = ...) -> _LT: ... - @overload - def min(__iterable: Iterable[_T], *, key: Callable[[_T], _LT]) -> _T: ... - @overload - def min(__iterable: Iterable[_LT], *, key: None = ..., default: _T) -> Union[_LT, _T]: ... - @overload - def min(__iterable: Iterable[_T1], *, key: Callable[[_T1], _LT], default: _T2) -> Union[_T1, _T2]: ... -else: - @overload - def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... - @overload - def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... -@overload -def next(__i: Iterator[_T]) -> _T: ... -@overload -def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... -def oct(__number: Union[int, _SupportsIndex]) -> str: ... - -if sys.version_info >= (3,): - _OpenFile = Union[AnyPath, int] - _Opener = Callable[[str, int], int] - - # Text mode: always returns a TextIOWrapper - @overload - def open( - file: _OpenFile, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> TextIOWrapper: ... - - # Unbuffered binary mode: returns a FileIO - @overload - def open( - file: _OpenFile, - mode: OpenBinaryMode, - buffering: Literal[0], - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> FileIO: ... - - # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeUpdating, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedRandom: ... - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedWriter: ... - @overload - def open( - file: _OpenFile, - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = ..., - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BufferedReader: ... - - # Buffering cannot be determined: fall back to BinaryIO - @overload - def open( - file: _OpenFile, - mode: OpenBinaryMode, - buffering: int, - encoding: None = ..., - errors: None = ..., - newline: None = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> BinaryIO: ... - - # Fallback if mode is not specified - @overload - def open( - file: _OpenFile, - mode: str, - buffering: int = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - newline: Optional[str] = ..., - closefd: bool = ..., - opener: Optional[_Opener] = ..., - ) -> IO[Any]: ... - -else: - def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... - -def ord(__c: Union[Text, bytes]) -> int: ... -if sys.version_info >= (3,): - def print( - *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[str]] = ..., flush: bool = ... - ) -> None: ... - -else: - # This is only available after from __future__ import print_function. - def print(*values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ...) -> None: ... - -_E = TypeVar("_E", contravariant=True) -_M = TypeVar("_M", contravariant=True) -class _SupportsPow2(Protocol[_E, _T_co]): - def __pow__(self, __other: _E) -> _T_co: ... -class _SupportsPow3(Protocol[_E, _M, _T_co]): - def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... -if sys.version_info >= (3, 8): - @overload - def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative - @overload - def pow(base: int, exp: int, mod: int) -> int: ... - @overload - def pow(base: float, exp: float, mod: None = ...) -> float: ... - @overload - def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... - @overload - def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... -else: - @overload - def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative - @overload - def pow(__base: int, __exp: int, __mod: int) -> int: ... - @overload - def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... - @overload - def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... - @overload - def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... -def quit(code: object = ...) -> NoReturn: ... -if sys.version_info < (3,): - def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 - def raw_input(__prompt: Any = ...) -> str: ... - @overload - def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... - @overload - def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... - def reload(__module: Any) -> Any: ... -@overload -def reversed(__object: Sequence[_T]) -> Iterator[_T]: ... -@overload -def reversed(__object: Reversible[_T]) -> Iterator[_T]: ... -def repr(__obj: object) -> str: ... -if sys.version_info >= (3,): - @overload - def round(number: float) -> int: ... - @overload - def round(number: float, ndigits: None) -> int: ... - @overload - def round(number: float, ndigits: int) -> float: ... - @overload - def round(number: SupportsRound[_T]) -> int: ... - @overload - def round(number: SupportsRound[_T], ndigits: None) -> int: ... - @overload - def round(number: SupportsRound[_T], ndigits: int) -> _T: ... -else: - @overload - def round(number: float) -> float: ... - @overload - def round(number: float, ndigits: int) -> float: ... - @overload - def round(number: SupportsFloat) -> float: ... - @overload - def round(number: SupportsFloat, ndigits: int) -> float: ... -def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... -if sys.version_info >= (3,): - @overload - def sorted(__iterable: Iterable[_LT], *, - key: None = ..., - reverse: bool = ...) -> List[_LT]: ... - @overload - def sorted(__iterable: Iterable[_T], *, - key: Callable[[_T], _SupportsLessThan], - reverse: bool = ...) -> List[_T]: ... -else: - def sorted(__iterable: Iterable[_T], *, - cmp: Callable[[_T, _T], int] = ..., - key: Optional[Callable[[_T], Any]] = ..., - reverse: bool = ...) -> List[_T]: ... -if sys.version_info >= (3, 8): - @overload - def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... - @overload - def sum(__iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... -else: - @overload - def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... - @overload - def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... -if sys.version_info < (3,): - def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... -if sys.version_info >= (3,): - # Some overloads to better support zipping heterogeneous tuples - @overload - def zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3, _T4]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...]]: ... # type: ignore - @overload - def zip(*iterables: Tuple[_T1, _T2, _T3, _T4, _T5]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...], Tuple[_T4, ...], Tuple[_T5, ...]]: ... # type: ignore - - @overload - def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], - __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... -else: - @overload - def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... - @overload - def zip(__iter1: Iterable[_T1], - __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], - __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], - __iter4: Iterable[_T4], __iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def zip(__iter1: Iterable[Any], __iter2: Iterable[Any], __iter3: Iterable[Any], - __iter4: Iterable[Any], __iter5: Iterable[Any], __iter6: Iterable[Any], - *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... -def __import__(name: Text, globals: Optional[Mapping[str, Any]] = ..., - locals: Optional[Mapping[str, Any]] = ..., - fromlist: Sequence[str] = ..., - level: int = ...) -> Any: ... - -# Actually the type of Ellipsis is , but since it's -# not exposed anywhere under that name, we make it private here. -class ellipsis: ... -Ellipsis: ellipsis - -if sys.version_info < (3,): - # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. - _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) - - class buffer(Sized): - def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... - def __add__(self, other: _AnyBuffer) -> str: ... - def __cmp__(self, other: _AnyBuffer) -> bool: ... - def __getitem__(self, key: Union[int, slice]) -> str: ... - def __getslice__(self, i: int, j: int) -> str: ... - def __len__(self) -> int: ... - def __mul__(self, x: int) -> str: ... - -class BaseException(object): - args: Tuple[Any, ...] - if sys.version_info < (3,): - message: Any - if sys.version_info >= (3,): - __cause__: Optional[BaseException] - __context__: Optional[BaseException] - __suppress_context__: bool - __traceback__: Optional[TracebackType] - def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - if sys.version_info < (3,): - def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... - if sys.version_info >= (3,): - def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... - -class GeneratorExit(BaseException): ... -class KeyboardInterrupt(BaseException): ... -class SystemExit(BaseException): - code: int -class Exception(BaseException): ... -class StopIteration(Exception): - if sys.version_info >= (3,): - value: Any -if sys.version_info >= (3,): - _StandardError = Exception - class OSError(Exception): - errno: int - strerror: str - # filename, filename2 are actually Union[str, bytes, None] - filename: Any - filename2: Any - EnvironmentError = OSError - IOError = OSError -else: - class StandardError(Exception): ... - _StandardError = StandardError - class EnvironmentError(StandardError): - errno: int - strerror: str - # TODO can this be unicode? - filename: str - class OSError(EnvironmentError): ... - class IOError(EnvironmentError): ... - -class ArithmeticError(_StandardError): ... -class AssertionError(_StandardError): ... -class AttributeError(_StandardError): ... -class BufferError(_StandardError): ... -class EOFError(_StandardError): ... -class ImportError(_StandardError): - if sys.version_info >= (3, 3): - def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... - name: Optional[str] - path: Optional[str] -class LookupError(_StandardError): ... -class MemoryError(_StandardError): ... -class NameError(_StandardError): ... -class ReferenceError(_StandardError): ... -class RuntimeError(_StandardError): ... -if sys.version_info >= (3, 5): - class StopAsyncIteration(Exception): - value: Any -class SyntaxError(_StandardError): - msg: str - lineno: Optional[int] - offset: Optional[int] - text: Optional[str] - filename: Optional[str] -class SystemError(_StandardError): ... -class TypeError(_StandardError): ... -class ValueError(_StandardError): ... - -class FloatingPointError(ArithmeticError): ... -class OverflowError(ArithmeticError): ... -class ZeroDivisionError(ArithmeticError): ... - -if sys.version_info >= (3, 6): - class ModuleNotFoundError(ImportError): ... - -class IndexError(LookupError): ... -class KeyError(LookupError): ... - -class UnboundLocalError(NameError): ... - -class WindowsError(OSError): - winerror: int -if sys.version_info >= (3,): - class BlockingIOError(OSError): - characters_written: int - class ChildProcessError(OSError): ... - class ConnectionError(OSError): ... - class BrokenPipeError(ConnectionError): ... - class ConnectionAbortedError(ConnectionError): ... - class ConnectionRefusedError(ConnectionError): ... - class ConnectionResetError(ConnectionError): ... - class FileExistsError(OSError): ... - class FileNotFoundError(OSError): ... - class InterruptedError(OSError): ... - class IsADirectoryError(OSError): ... - class NotADirectoryError(OSError): ... - class PermissionError(OSError): ... - class ProcessLookupError(OSError): ... - class TimeoutError(OSError): ... - -class NotImplementedError(RuntimeError): ... -if sys.version_info >= (3, 5): - class RecursionError(RuntimeError): ... - -class IndentationError(SyntaxError): ... -class TabError(IndentationError): ... - -class UnicodeError(ValueError): ... -class UnicodeDecodeError(UnicodeError): - encoding: str - object: bytes - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, - __reason: str) -> None: ... -class UnicodeEncodeError(UnicodeError): - encoding: str - object: Text - start: int - end: int - reason: str - def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, - __reason: str) -> None: ... -class UnicodeTranslateError(UnicodeError): ... - -class Warning(Exception): ... -class UserWarning(Warning): ... -class DeprecationWarning(Warning): ... -class SyntaxWarning(Warning): ... -class RuntimeWarning(Warning): ... -class FutureWarning(Warning): ... -class PendingDeprecationWarning(Warning): ... -class ImportWarning(Warning): ... -class UnicodeWarning(Warning): ... -class BytesWarning(Warning): ... -if sys.version_info >= (3, 2): - class ResourceWarning(Warning): ... - -if sys.version_info < (3,): - class file(BinaryIO): - @overload - def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... - @overload - def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def __enter__(self) -> BinaryIO: ... - def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> Optional[bool]: ... - def flush(self) -> None: ... - def fileno(self) -> int: ... - def isatty(self) -> bool: ... - def close(self) -> None: ... - - def readable(self) -> bool: ... - def writable(self) -> bool: ... - def seekable(self) -> bool: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def write(self, data: str) -> int: ... - def writelines(self, data: Iterable[str]) -> None: ... - def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/_ast.pyi b/mypy/typeshed/stdlib/python2/_ast.pyi deleted file mode 100644 index c461bb412805..000000000000 --- a/mypy/typeshed/stdlib/python2/_ast.pyi +++ /dev/null @@ -1,330 +0,0 @@ -import typing -from typing import Optional - -__version__: str -PyCF_ONLY_AST: int -_identifier = str - -class AST: - _attributes: typing.Tuple[str, ...] - _fields: typing.Tuple[str, ...] - def __init__(self, *args, **kwargs) -> None: ... - -class mod(AST): - ... - -class Module(mod): - body: typing.List[stmt] - -class Interactive(mod): - body: typing.List[stmt] - -class Expression(mod): - body: expr - -class Suite(mod): - body: typing.List[stmt] - - -class stmt(AST): - lineno: int - col_offset: int - -class FunctionDef(stmt): - name: _identifier - args: arguments - body: typing.List[stmt] - decorator_list: typing.List[expr] - -class ClassDef(stmt): - name: _identifier - bases: typing.List[expr] - body: typing.List[stmt] - decorator_list: typing.List[expr] - -class Return(stmt): - value: Optional[expr] - -class Delete(stmt): - targets: typing.List[expr] - -class Assign(stmt): - targets: typing.List[expr] - value: expr - -class AugAssign(stmt): - target: expr - op: operator - value: expr - -class Print(stmt): - dest: Optional[expr] - values: typing.List[expr] - nl: bool - -class For(stmt): - target: expr - iter: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class While(stmt): - test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class If(stmt): - test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] - -class With(stmt): - context_expr: expr - optional_vars: Optional[expr] - body: typing.List[stmt] - -class Raise(stmt): - type: Optional[expr] - inst: Optional[expr] - tback: Optional[expr] - -class TryExcept(stmt): - body: typing.List[stmt] - handlers: typing.List[ExceptHandler] - orelse: typing.List[stmt] - -class TryFinally(stmt): - body: typing.List[stmt] - finalbody: typing.List[stmt] - -class Assert(stmt): - test: expr - msg: Optional[expr] - -class Import(stmt): - names: typing.List[alias] - -class ImportFrom(stmt): - module: Optional[_identifier] - names: typing.List[alias] - level: Optional[int] - -class Exec(stmt): - body: expr - globals: Optional[expr] - locals: Optional[expr] - -class Global(stmt): - names: typing.List[_identifier] - -class Expr(stmt): - value: expr - -class Pass(stmt): ... -class Break(stmt): ... -class Continue(stmt): ... - - -class slice(AST): - ... - -_slice = slice # this lets us type the variable named 'slice' below - -class Slice(slice): - lower: Optional[expr] - upper: Optional[expr] - step: Optional[expr] - -class ExtSlice(slice): - dims: typing.List[slice] - -class Index(slice): - value: expr - -class Ellipsis(slice): ... - - -class expr(AST): - lineno: int - col_offset: int - -class BoolOp(expr): - op: boolop - values: typing.List[expr] - -class BinOp(expr): - left: expr - op: operator - right: expr - -class UnaryOp(expr): - op: unaryop - operand: expr - -class Lambda(expr): - args: arguments - body: expr - -class IfExp(expr): - test: expr - body: expr - orelse: expr - -class Dict(expr): - keys: typing.List[expr] - values: typing.List[expr] - -class Set(expr): - elts: typing.List[expr] - -class ListComp(expr): - elt: expr - generators: typing.List[comprehension] - -class SetComp(expr): - elt: expr - generators: typing.List[comprehension] - -class DictComp(expr): - key: expr - value: expr - generators: typing.List[comprehension] - -class GeneratorExp(expr): - elt: expr - generators: typing.List[comprehension] - -class Yield(expr): - value: Optional[expr] - -class Compare(expr): - left: expr - ops: typing.List[cmpop] - comparators: typing.List[expr] - -class Call(expr): - func: expr - args: typing.List[expr] - keywords: typing.List[keyword] - starargs: Optional[expr] - kwargs: Optional[expr] - -class Repr(expr): - value: expr - -class Num(expr): - n: float - -class Str(expr): - s: str - -class Attribute(expr): - value: expr - attr: _identifier - ctx: expr_context - -class Subscript(expr): - value: expr - slice: _slice - ctx: expr_context - -class Name(expr): - id: _identifier - ctx: expr_context - -class List(expr): - elts: typing.List[expr] - ctx: expr_context - -class Tuple(expr): - elts: typing.List[expr] - ctx: expr_context - - -class expr_context(AST): - ... - -class AugLoad(expr_context): ... -class AugStore(expr_context): ... -class Del(expr_context): ... -class Load(expr_context): ... -class Param(expr_context): ... -class Store(expr_context): ... - - -class boolop(AST): - ... - -class And(boolop): ... -class Or(boolop): ... - -class operator(AST): - ... - -class Add(operator): ... -class BitAnd(operator): ... -class BitOr(operator): ... -class BitXor(operator): ... -class Div(operator): ... -class FloorDiv(operator): ... -class LShift(operator): ... -class Mod(operator): ... -class Mult(operator): ... -class Pow(operator): ... -class RShift(operator): ... -class Sub(operator): ... - -class unaryop(AST): - ... - -class Invert(unaryop): ... -class Not(unaryop): ... -class UAdd(unaryop): ... -class USub(unaryop): ... - -class cmpop(AST): - ... - -class Eq(cmpop): ... -class Gt(cmpop): ... -class GtE(cmpop): ... -class In(cmpop): ... -class Is(cmpop): ... -class IsNot(cmpop): ... -class Lt(cmpop): ... -class LtE(cmpop): ... -class NotEq(cmpop): ... -class NotIn(cmpop): ... - - -class comprehension(AST): - target: expr - iter: expr - ifs: typing.List[expr] - - -class excepthandler(AST): - ... - - -class ExceptHandler(excepthandler): - type: Optional[expr] - name: Optional[expr] - body: typing.List[stmt] - lineno: int - col_offset: int - - -class arguments(AST): - args: typing.List[expr] - vararg: Optional[_identifier] - kwarg: Optional[_identifier] - defaults: typing.List[expr] - -class keyword(AST): - arg: _identifier - value: expr - -class alias(AST): - name: _identifier - asname: Optional[_identifier] diff --git a/mypy/typeshed/stdlib/python2/_collections.pyi b/mypy/typeshed/stdlib/python2/_collections.pyi deleted file mode 100644 index bee5d67b0918..000000000000 --- a/mypy/typeshed/stdlib/python2/_collections.pyi +++ /dev/null @@ -1,38 +0,0 @@ -"""Stub file for the '_collections' module.""" - -from typing import Any, Callable, Dict, Generic, Iterator, TypeVar, Optional, Union - -_K = TypeVar("_K") -_V = TypeVar("_V") -_T = TypeVar('_T') -_T2 = TypeVar('_T2') - -class defaultdict(Dict[_K, _V]): - default_factory: None - def __init__(self, __default_factory: Callable[[], _V] = ..., init: Any = ...) -> None: ... - def __missing__(self, key: _K) -> _V: ... - def __copy__(self: _T) -> _T: ... - def copy(self: _T) -> _T: ... - -class deque(Generic[_T]): - maxlen: Optional[int] - def __init__(self, iterable: Iterator[_T] = ..., maxlen: int = ...) -> None: ... - def append(self, x: _T) -> None: ... - def appendleft(self, x: _T) -> None: ... - def clear(self) -> None: ... - def count(self, x: Any) -> int: ... - def extend(self, iterable: Iterator[_T]) -> None: ... - def extendleft(self, iterable: Iterator[_T]) -> None: ... - def pop(self) -> _T: ... - def popleft(self) -> _T: ... - def remove(self, value: _T) -> None: ... - def reverse(self) -> None: ... - def rotate(self, n: int = ...) -> None: ... - def __contains__(self, o: Any) -> bool: ... - def __copy__(self) -> deque[_T]: ... - def __getitem__(self, i: int) -> _T: ... - def __iadd__(self, other: deque[_T2]) -> deque[Union[_T, _T2]]: ... - def __iter__(self) -> Iterator[_T]: ... - def __len__(self) -> int: ... - def __reversed__(self) -> Iterator[_T]: ... - def __setitem__(self, i: int, x: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_functools.pyi b/mypy/typeshed/stdlib/python2/_functools.pyi deleted file mode 100644 index 876974e45429..000000000000 --- a/mypy/typeshed/stdlib/python2/_functools.pyi +++ /dev/null @@ -1,20 +0,0 @@ -"""Stub file for the '_functools' module.""" - -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Tuple, overload - -_T = TypeVar("_T") -_S = TypeVar("_S") - -@overload -def reduce(function: Callable[[_T, _T], _T], - sequence: Iterable[_T]) -> _T: ... -@overload -def reduce(function: Callable[[_T, _S], _T], - sequence: Iterable[_S], initial: _T) -> _T: ... - -class partial(object): - func: Callable[..., Any] - args: Tuple[Any, ...] - keywords: Dict[str, Any] - def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/python2/_hotshot.pyi b/mypy/typeshed/stdlib/python2/_hotshot.pyi deleted file mode 100644 index a4404b0c7f8d..000000000000 --- a/mypy/typeshed/stdlib/python2/_hotshot.pyi +++ /dev/null @@ -1,24 +0,0 @@ -"""Stub file for the '_hotshot' module.""" -# This is an autogenerated file. It serves as a starting point -# for a more precise manual annotation of this module. -# Feel free to edit the source below, but remove this header when you do. - -from typing import Any, List, Tuple, Dict, Generic - -def coverage(a: str) -> Any: ... -def logreader(a: str) -> LogReaderType: ... -def profiler(a: str, *args, **kwargs) -> Any: ... -def resolution() -> Tuple[Any, ...]: ... - -class LogReaderType(object): - def close(self) -> None: ... - def fileno(self) -> int: ... - -class ProfilerType(object): - def addinfo(self, a: str, b: str) -> None: ... - def close(self) -> None: ... - def fileno(self) -> int: ... - def runcall(self, *args, **kwargs) -> Any: ... - def runcode(self, a, b, *args, **kwargs) -> Any: ... - def start(self) -> None: ... - def stop(self) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_io.pyi b/mypy/typeshed/stdlib/python2/_io.pyi deleted file mode 100644 index e8e448f2c8ed..000000000000 --- a/mypy/typeshed/stdlib/python2/_io.pyi +++ /dev/null @@ -1,186 +0,0 @@ -from typing import Any, AnyStr, BinaryIO, IO, Text, TextIO, Iterable, Iterator, List, Optional, Type, Tuple, TypeVar, Union -from mmap import mmap -from types import TracebackType - -_bytearray_like = Union[bytearray, mmap] - -DEFAULT_BUFFER_SIZE: int - -class BlockingIOError(IOError): - characters_written: int - -class UnsupportedOperation(ValueError, IOError): ... - -_T = TypeVar("_T") - -class _IOBase(BinaryIO): - @property - def closed(self) -> bool: ... - def _checkClosed(self, msg: Optional[str] = ...) -> None: ... # undocumented - def _checkReadable(self) -> None: ... - def _checkSeekable(self) -> None: ... - def _checkWritable(self) -> None: ... - # All these methods are concrete here (you can instantiate this) - def close(self) -> None: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def readable(self) -> bool: ... - 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 __enter__(self: _T) -> _T: ... - def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> Optional[bool]: ... - def __iter__(self: _T) -> _T: ... - # The parameter type of writelines[s]() is determined by that of write(): - def writelines(self, lines: Iterable[bytes]) -> None: ... - # The return type of readline[s]() and next() is determined by that of read(): - def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... - def next(self) -> bytes: ... - # These don't actually exist but we need to pretend that it does - # so that this class is concrete. - def write(self, s: bytes) -> int: ... - def read(self, n: int = ...) -> bytes: ... - -class _BufferedIOBase(_IOBase): - def read1(self, n: int) -> bytes: ... - def read(self, size: int = ...) -> bytes: ... - def readinto(self, buffer: _bytearray_like) -> int: ... - def write(self, s: bytes) -> int: ... - def detach(self) -> _IOBase: ... - -class BufferedRWPair(_BufferedIOBase): - def __init__(self, reader: _RawIOBase, writer: _RawIOBase, - buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - def __enter__(self) -> BufferedRWPair: ... - -class BufferedRandom(_BufferedIOBase): - mode: str - name: str - raw: _IOBase - def __init__(self, raw: _IOBase, - buffer_size: int = ..., - max_buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - -class BufferedReader(_BufferedIOBase): - mode: str - name: str - raw: _IOBase - def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ... - def peek(self, n: int = ...) -> bytes: ... - -class BufferedWriter(_BufferedIOBase): - name: str - raw: _IOBase - mode: str - def __init__(self, raw: _IOBase, - buffer_size: int = ..., - max_buffer_size: int = ...) -> None: ... - -class BytesIO(_BufferedIOBase): - def __init__(self, initial_bytes: bytes = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... - # BytesIO does not contain a "name" field. This workaround is necessary - # to allow BytesIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def getvalue(self) -> bytes: ... - def write(self, s: bytes) -> int: ... - def writelines(self, lines: Iterable[bytes]) -> None: ... - def read1(self, size: int) -> bytes: ... - def next(self) -> bytes: ... - -class _RawIOBase(_IOBase): - def readall(self) -> str: ... - def read(self, n: int = ...) -> str: ... - -class FileIO(_RawIOBase, BytesIO): - mode: str - closefd: bool - def __init__(self, file: Union[str, int], mode: str = ..., closefd: bool = ...) -> None: ... - def readinto(self, buffer: _bytearray_like) -> int: ... - def write(self, pbuf: str) -> int: ... - -class IncrementalNewlineDecoder(object): - newlines: Union[str, unicode] - def __init__(self, decoder, translate, z=...) -> None: ... - def decode(self, input, final) -> Any: ... - def getstate(self) -> Tuple[Any, int]: ... - def setstate(self, state: Tuple[Any, int]) -> None: ... - def reset(self) -> None: ... - - -# Note: In the actual _io.py, _TextIOBase inherits from _IOBase. -class _TextIOBase(TextIO): - errors: Optional[str] - # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses. - newlines: Union[None, unicode, bytes] - encoding: str - @property - def closed(self) -> bool: ... - def _checkClosed(self) -> None: ... - def _checkReadable(self) -> None: ... - def _checkSeekable(self) -> None: ... - def _checkWritable(self) -> None: ... - def close(self) -> None: ... - def detach(self) -> IO[Any]: ... - def fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def next(self) -> unicode: ... - def read(self, size: int = ...) -> unicode: ... - def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> unicode: ... - def readlines(self, hint: int = ...) -> list[unicode]: ... - 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, pbuf: unicode) -> int: ... - def writelines(self, lines: Iterable[unicode]) -> None: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> Optional[bool]: ... - def __iter__(self: _T) -> _T: ... - -class StringIO(_TextIOBase): - line_buffering: bool - def __init__(self, - initial_value: Optional[unicode] = ..., - newline: Optional[unicode] = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... - # StringIO does not contain a "name" field. This workaround is necessary - # to allow StringIO sub-classes to add this field, as it is defined - # as a read-only property on IO[]. - name: Any - def getvalue(self) -> unicode: ... - -class TextIOWrapper(_TextIOBase): - name: str - line_buffering: bool - buffer: BinaryIO - _CHUNK_SIZE: int - def __init__( - self, - buffer: IO[Any], - encoding: Optional[Text] = ..., - errors: Optional[Text] = ..., - newline: Optional[Text] = ..., - line_buffering: bool = ..., - write_through: bool = ..., - ) -> None: ... - -def open(file: Union[str, unicode, int], - mode: Text = ..., - buffering: int = ..., - encoding: Optional[Text] = ..., - errors: Optional[Text] = ..., - newline: Optional[Text] = ..., - closefd: bool = ...) -> IO[Any]: ... diff --git a/mypy/typeshed/stdlib/python2/_json.pyi b/mypy/typeshed/stdlib/python2/_json.pyi deleted file mode 100644 index 1c8e0409feaf..000000000000 --- a/mypy/typeshed/stdlib/python2/_json.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Any, Dict, Generic, List, Tuple - -def encode_basestring_ascii(*args, **kwargs) -> str: ... -def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... - -class Encoder(object): ... -class Scanner(object): ... diff --git a/mypy/typeshed/stdlib/python2/_md5.pyi b/mypy/typeshed/stdlib/python2/_md5.pyi deleted file mode 100644 index 96111b70af9b..000000000000 --- a/mypy/typeshed/stdlib/python2/_md5.pyi +++ /dev/null @@ -1,13 +0,0 @@ -blocksize: int -digest_size: int - -class MD5Type(object): - name: str - block_size: int - digest_size: int - def copy(self) -> MD5Type: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -def new(arg: str = ...) -> MD5Type: ... diff --git a/mypy/typeshed/stdlib/python2/_sha.pyi b/mypy/typeshed/stdlib/python2/_sha.pyi deleted file mode 100644 index 7c472562fc17..000000000000 --- a/mypy/typeshed/stdlib/python2/_sha.pyi +++ /dev/null @@ -1,15 +0,0 @@ -blocksize: int -block_size: int -digest_size: int - -class sha(object): # not actually exposed - name: str - block_size: int - digest_size: int - digestsize: int - def copy(self) -> sha: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -def new(arg: str = ...) -> sha: ... diff --git a/mypy/typeshed/stdlib/python2/_sha256.pyi b/mypy/typeshed/stdlib/python2/_sha256.pyi deleted file mode 100644 index b6eb47d4bc83..000000000000 --- a/mypy/typeshed/stdlib/python2/_sha256.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Optional - -class sha224(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: Optional[str]) -> None: ... - def copy(self) -> sha224: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -class sha256(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: Optional[str]) -> None: ... - def copy(self) -> sha256: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_sha512.pyi b/mypy/typeshed/stdlib/python2/_sha512.pyi deleted file mode 100644 index b1ca9aee004c..000000000000 --- a/mypy/typeshed/stdlib/python2/_sha512.pyi +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Optional - -class sha384(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: Optional[str]) -> None: ... - def copy(self) -> sha384: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... - -class sha512(object): - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, init: Optional[str]) -> None: ... - def copy(self) -> sha512: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def update(self, arg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_socket.pyi b/mypy/typeshed/stdlib/python2/_socket.pyi deleted file mode 100644 index f6a058acac2f..000000000000 --- a/mypy/typeshed/stdlib/python2/_socket.pyi +++ /dev/null @@ -1,283 +0,0 @@ -from typing import Tuple, Union, IO, Any, Optional, overload - -AF_APPLETALK: int -AF_ASH: int -AF_ATMPVC: int -AF_ATMSVC: int -AF_AX25: int -AF_BLUETOOTH: int -AF_BRIDGE: int -AF_DECnet: int -AF_ECONET: int -AF_INET: int -AF_INET6: int -AF_IPX: int -AF_IRDA: int -AF_KEY: int -AF_LLC: int -AF_NETBEUI: int -AF_NETLINK: int -AF_NETROM: int -AF_PACKET: int -AF_PPPOX: int -AF_ROSE: int -AF_ROUTE: int -AF_SECURITY: int -AF_SNA: int -AF_TIPC: int -AF_UNIX: int -AF_UNSPEC: int -AF_WANPIPE: int -AF_X25: int -AI_ADDRCONFIG: int -AI_ALL: int -AI_CANONNAME: int -AI_NUMERICHOST: int -AI_NUMERICSERV: int -AI_PASSIVE: int -AI_V4MAPPED: int -BDADDR_ANY: str -BDADDR_LOCAL: str -BTPROTO_HCI: int -BTPROTO_L2CAP: int -BTPROTO_RFCOMM: int -BTPROTO_SCO: int -EAI_ADDRFAMILY: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_OVERFLOW: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -EAI_SYSTEM: int -EBADF: int -EINTR: int -HCI_DATA_DIR: int -HCI_FILTER: int -HCI_TIME_STAMP: 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_DSTOPTS: int -IPPROTO_EGP: int -IPPROTO_ESP: int -IPPROTO_FRAGMENT: int -IPPROTO_GRE: int -IPPROTO_HOPOPTS: int -IPPROTO_ICMP: int -IPPROTO_ICMPV6: int -IPPROTO_IDP: int -IPPROTO_IGMP: int -IPPROTO_IP: int -IPPROTO_IPIP: int -IPPROTO_IPV6: int -IPPROTO_NONE: int -IPPROTO_PIM: int -IPPROTO_PUP: int -IPPROTO_RAW: int -IPPROTO_ROUTING: int -IPPROTO_RSVP: int -IPPROTO_TCP: int -IPPROTO_TP: int -IPPROTO_UDP: int -IPV6_CHECKSUM: 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_PKTINFO: int -IPV6_RECVDSTOPTS: int -IPV6_RECVHOPLIMIT: int -IPV6_RECVHOPOPTS: 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_V6ONLY: 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_RECVOPTS: int -IP_RECVRETOPTS: int -IP_RETOPTS: int -IP_TOS: int -IP_TTL: int -MSG_CTRUNC: int -MSG_DONTROUTE: int -MSG_DONTWAIT: int -MSG_EOR: int -MSG_OOB: int -MSG_PEEK: int -MSG_TRUNC: int -MSG_WAITALL: int -MethodType: type -NETLINK_DNRTMSG: int -NETLINK_FIREWALL: int -NETLINK_IP6_FW: int -NETLINK_NFLOG: int -NETLINK_ROUTE: int -NETLINK_USERSOCK: int -NETLINK_XFRM: int -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -PACKET_BROADCAST: int -PACKET_FASTROUTE: int -PACKET_HOST: int -PACKET_LOOPBACK: int -PACKET_MULTICAST: int -PACKET_OTHERHOST: int -PACKET_OUTGOING: int -PF_PACKET: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOCK_DGRAM: int -SOCK_RAW: int -SOCK_RDM: int -SOCK_SEQPACKET: int -SOCK_STREAM: int -SOL_HCI: int -SOL_IP: int -SOL_SOCKET: int -SOL_TCP: int -SOL_TIPC: int -SOL_UDP: int -SOMAXCONN: int -SO_ACCEPTCONN: int -SO_BROADCAST: int -SO_DEBUG: int -SO_DONTROUTE: int -SO_ERROR: int -SO_KEEPALIVE: int -SO_LINGER: int -SO_OOBINLINE: int -SO_RCVBUF: int -SO_RCVLOWAT: int -SO_RCVTIMEO: int -SO_REUSEADDR: int -SO_REUSEPORT: int -SO_SNDBUF: int -SO_SNDLOWAT: int -SO_SNDTIMEO: int -SO_TYPE: int -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 -TCP_CORK: int -TCP_DEFER_ACCEPT: 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 -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 - -# PyCapsule -CAPI: Any - -has_ipv6: bool - -class error(IOError): ... -class gaierror(error): ... -class timeout(error): ... - -class SocketType(object): - family: int - type: int - proto: int - timeout: float - - def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... - def accept(self) -> Tuple[SocketType, Tuple[Any, ...]]: ... - def bind(self, address: Tuple[Any, ...]) -> None: ... - def close(self) -> None: ... - def connect(self, address: Tuple[Any, ...]) -> None: ... - def connect_ex(self, address: Tuple[Any, ...]) -> int: ... - def dup(self) -> SocketType: ... - def fileno(self) -> int: ... - def getpeername(self) -> Tuple[Any, ...]: ... - def getsockname(self) -> Tuple[Any, ...]: ... - def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... - def gettimeout(self) -> float: ... - def listen(self, backlog: int) -> None: ... - def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... - def recv(self, buffersize: int, flags: int = ...) -> str: ... - def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... - def recvfrom(self, buffersize: int, flags: int = ...) -> Tuple[Any, ...]: ... - def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., - flags: int = ...) -> int: ... - def send(self, data: str, flags: int = ...) -> int: ... - def sendall(self, data: str, flags: int = ...) -> None: ... - @overload - def sendto(self, data: str, address: Tuple[Any, ...]) -> int: ... - @overload - def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... - def setblocking(self, flag: bool) -> None: ... - def setsockopt(self, level: int, option: int, value: Union[int, str]) -> None: ... - def settimeout(self, value: Optional[float]) -> None: ... - def shutdown(self, flag: int) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_sre.pyi b/mypy/typeshed/stdlib/python2/_sre.pyi deleted file mode 100644 index 93300f0f2999..000000000000 --- a/mypy/typeshed/stdlib/python2/_sre.pyi +++ /dev/null @@ -1,55 +0,0 @@ -"""Stub file for the '_sre' module.""" - -from typing import Any, Union, Iterable, Optional, Mapping, Sequence, Dict, List, Tuple, overload - -CODESIZE: int -MAGIC: int -MAXREPEAT: long -copyright: str - -class SRE_Match(object): - def start(self, group: int = ...) -> int: ... - def end(self, group: int = ...) -> int: ... - def expand(self, s: str) -> Any: ... - @overload - def group(self) -> str: ... - @overload - def group(self, group: int = ...) -> Optional[str]: ... - def groupdict(self) -> Dict[int, Optional[str]]: ... - def groups(self) -> Tuple[Optional[str], ...]: ... - def span(self) -> Tuple[int, int]: ... - @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented - -class SRE_Scanner(object): - pattern: str - def match(self) -> SRE_Match: ... - def search(self) -> SRE_Match: ... - -class SRE_Pattern(object): - pattern: str - flags: int - groups: int - groupindex: Mapping[str, int] - indexgroup: Sequence[int] - def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Union[Tuple[Any, ...], str]]: ... - def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Union[Tuple[Any, ...], str]]: ... - def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... - def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... - def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... - def split(self, source: str, maxsplit: int = ...) -> List[Optional[str]]: ... - def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - -def compile( - pattern: str, - flags: int, - code: List[int], - groups: int = ..., - groupindex: Mapping[str, int] = ..., - indexgroup: Sequence[int] = ..., -) -> SRE_Pattern: ... - -def getcodesize() -> int: ... - -def getlower(a: int, b: int) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/_struct.pyi b/mypy/typeshed/stdlib/python2/_struct.pyi deleted file mode 100644 index 49f44f2c58a3..000000000000 --- a/mypy/typeshed/stdlib/python2/_struct.pyi +++ /dev/null @@ -1,22 +0,0 @@ -"""Stub file for the '_struct' module.""" - -from typing import Any, AnyStr, Tuple - -class error(Exception): ... - -class Struct(object): - size: int - format: str - - def __init__(self, fmt: str) -> None: ... - def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... - def pack(self, *args) -> str: ... - def unpack(self, s: str) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... - -def _clearcache() -> None: ... -def calcsize(fmt: str) -> int: ... -def pack(fmt: AnyStr, obj: Any) -> str: ... -def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... -def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... -def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/python2/_symtable.pyi b/mypy/typeshed/stdlib/python2/_symtable.pyi deleted file mode 100644 index fbf5424405ca..000000000000 --- a/mypy/typeshed/stdlib/python2/_symtable.pyi +++ /dev/null @@ -1,39 +0,0 @@ -from typing import List, Dict - -CELL: int -DEF_BOUND: int -DEF_FREE: int -DEF_FREE_CLASS: int -DEF_GLOBAL: int -DEF_IMPORT: int -DEF_LOCAL: int -DEF_PARAM: int -FREE: int -GLOBAL_EXPLICIT: int -GLOBAL_IMPLICIT: int -LOCAL: int -OPT_BARE_EXEC: int -OPT_EXEC: int -OPT_IMPORT_STAR: int -SCOPE_MASK: int -SCOPE_OFF: int -TYPE_CLASS: int -TYPE_FUNCTION: int -TYPE_MODULE: int -USE: int - -class _symtable_entry(object): - ... - -class symtable(object): - children: List[_symtable_entry] - id: int - lineno: int - name: str - nested: int - optimized: int - symbols: Dict[str, int] - type: int - varnames: List[str] - - def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_threading_local.pyi b/mypy/typeshed/stdlib/python2/_threading_local.pyi deleted file mode 100644 index 1a7e03de4967..000000000000 --- a/mypy/typeshed/stdlib/python2/_threading_local.pyi +++ /dev/null @@ -1,12 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/_threading_local.py -from typing import Any - -class _localbase(object): ... - -class local(_localbase): - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... - def __del__(self) -> None: ... - -def _patch(self: local) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/_winreg.pyi b/mypy/typeshed/stdlib/python2/_winreg.pyi deleted file mode 100644 index d1ed6a67d499..000000000000 --- a/mypy/typeshed/stdlib/python2/_winreg.pyi +++ /dev/null @@ -1,99 +0,0 @@ - -import sys - -from typing import Optional, Type, Union, Tuple, Any -from types import TracebackType - -_KeyType = Union[HKEYType, int] - -def CloseKey(__hkey: _KeyType): ... -def ConnectRegistry(__computer_name: Optional[str], __key: _KeyType) -> HKEYType: ... -def CreateKey(__key: _KeyType, __sub_key: Optional[str]) -> HKEYType: ... -def CreateKeyEx(key: _KeyType, sub_key: Optional[str], reserved: int = ..., access: int = ...) -> HKEYType: ... -def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... -def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... -def DeleteValue(__key: _KeyType, __value: str) -> None: ... -def EnumKey(__key: _KeyType, __index: int) -> str: ... -def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... -def ExpandEnvironmentStrings(__str: str) -> str: ... -def FlushKey(__key: _KeyType) -> None: ... -def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... -def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... -def QueryValue(__key: _KeyType, __sub_key: Optional[str]) -> str: ... -def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... -def SaveKey(__key: _KeyType, __file_name: str) -> None: ... -def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx(__key: _KeyType, __value_name: str, __reserved: Any, __type: int, __value: str) -> None: ... # reserved is ignored -def DisableReflectionKey(__key: _KeyType) -> None: ... -def EnableReflectionKey(__key: _KeyType) -> None: ... -def QueryReflectionKey(__key: _KeyType) -> bool: ... - -HKEY_CLASSES_ROOT: int -HKEY_CURRENT_USER: int -HKEY_LOCAL_MACHINE: int -HKEY_USERS: int -HKEY_PERFORMANCE_DATA: int -HKEY_CURRENT_CONFIG: int -HKEY_DYN_DATA: int - -KEY_ALL_ACCESS: int -KEY_WRITE: int -KEY_READ: int -KEY_EXECUTE: int -KEY_QUERY_VALUE: int -KEY_SET_VALUE: int -KEY_CREATE_SUB_KEY: int -KEY_ENUMERATE_SUB_KEYS: int -KEY_NOTIFY: int -KEY_CREATE_LINK: int - -KEY_WOW64_64KEY: int -KEY_WOW64_32KEY: int - -REG_BINARY: int -REG_DWORD: int -REG_DWORD_LITTLE_ENDIAN: int -REG_DWORD_BIG_ENDIAN: int -REG_EXPAND_SZ: int -REG_LINK: int -REG_MULTI_SZ: int -REG_NONE: int -if sys.version_info >= (3, 6): - REG_QWORD: int - REG_QWORD_LITTLE_ENDIAN: int -REG_RESOURCE_LIST: int -REG_FULL_RESOURCE_DESCRIPTOR: int -REG_RESOURCE_REQUIREMENTS_LIST: int -REG_SZ: int - -REG_CREATED_NEW_KEY: int # undocumented -REG_LEGAL_CHANGE_FILTER: int # undocumented -REG_LEGAL_OPTION: int # undocumented -REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented -REG_NOTIFY_CHANGE_LAST_SET: int # undocumented -REG_NOTIFY_CHANGE_NAME: int # undocumented -REG_NOTIFY_CHANGE_SECURITY: int # undocumented -REG_NO_LAZY_FLUSH: int # undocumented -REG_OPENED_EXISTING_KEY: int # undocumented -REG_OPTION_BACKUP_RESTORE: int # undocumented -REG_OPTION_CREATE_LINK: int # undocumented -REG_OPTION_NON_VOLATILE: int # undocumented -REG_OPTION_OPEN_LINK: int # undocumented -REG_OPTION_RESERVED: int # undocumented -REG_OPTION_VOLATILE: int # undocumented -REG_REFRESH_HIVE: int # undocumented -REG_WHOLE_HIVE_VOLATILE: int # undocumented - -error = OSError - -# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason -class HKEYType: - def __bool__(self) -> bool: ... - def __int__(self) -> int: ... - def __enter__(self) -> HKEYType: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: ... - - def Close(self) -> None: ... - def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/abc.pyi b/mypy/typeshed/stdlib/python2/abc.pyi deleted file mode 100644 index 64fbb50bc706..000000000000 --- a/mypy/typeshed/stdlib/python2/abc.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar -import _weakrefset - -_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) - -# NOTE: mypy has special processing for ABCMeta and abstractmethod. - -def abstractmethod(funcobj: _FuncT) -> _FuncT: ... - -class ABCMeta(type): - # TODO: FrozenSet - __abstractmethods__: Set[Any] - _abc_cache: _weakrefset.WeakSet[Any] - _abc_invalidation_counter: int - _abc_negative_cache: _weakrefset.WeakSet[Any] - _abc_negative_cache_version: int - _abc_registry: _weakrefset.WeakSet[Any] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[Any, Any]) -> None: ... - def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... - def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... - def _dump_registry(cls: ABCMeta, *args: Any, **kwargs: Any) -> None: ... - def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... - -# TODO: The real abc.abstractproperty inherits from "property". -class abstractproperty(object): - def __new__(cls, func: Any) -> Any: ... - __isabstractmethod__: bool - doc: Any - fdel: Any - fget: Any - fset: Any diff --git a/mypy/typeshed/stdlib/python2/ast.pyi b/mypy/typeshed/stdlib/python2/ast.pyi deleted file mode 100644 index c5ffd65562b9..000000000000 --- a/mypy/typeshed/stdlib/python2/ast.pyi +++ /dev/null @@ -1,28 +0,0 @@ -# Python 2.7 ast - -# Rename typing to _typing, as not to conflict with typing imported -# from _ast below when loaded in an unorthodox way by the Dropbox -# internal Bazel integration. -import typing as _typing -from typing import Any, Iterator, Optional, Union - -from _ast import * -from _ast import AST, Module - -def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ... -def copy_location(new_node: AST, old_node: AST) -> AST: ... -def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... -def fix_missing_locations(node: AST) -> AST: ... -def get_docstring(node: AST, clean: bool = ...) -> str: ... -def increment_lineno(node: AST, n: int = ...) -> AST: ... -def iter_child_nodes(node: AST) -> Iterator[AST]: ... -def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... -def literal_eval(node_or_string: Union[str, unicode, AST]) -> Any: ... -def walk(node: AST) -> Iterator[AST]: ... - -class NodeVisitor(): - def visit(self, node: AST) -> Any: ... - def generic_visit(self, node: AST) -> Any: ... - -class NodeTransformer(NodeVisitor): - def generic_visit(self, node: AST) -> Optional[AST]: ... diff --git a/mypy/typeshed/stdlib/python2/atexit.pyi b/mypy/typeshed/stdlib/python2/atexit.pyi deleted file mode 100644 index 13d2602b0dc4..000000000000 --- a/mypy/typeshed/stdlib/python2/atexit.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import TypeVar, Any - -_FT = TypeVar('_FT') - -def register(func: _FT, *args: Any, **kargs: Any) -> _FT: ... diff --git a/mypy/typeshed/stdlib/python2/cPickle.pyi b/mypy/typeshed/stdlib/python2/cPickle.pyi deleted file mode 100644 index 0421c50efe17..000000000000 --- a/mypy/typeshed/stdlib/python2/cPickle.pyi +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Any, IO, List - -HIGHEST_PROTOCOL: int -compatible_formats: List[str] -format_version: str - -class Pickler: - def __init__(self, file: IO[str], protocol: int = ...) -> None: ... - - def dump(self, obj: Any) -> None: ... - - def clear_memo(self) -> None: ... - - -class Unpickler: - def __init__(self, file: IO[str]) -> None: ... - - def load(self) -> Any: ... - - def noload(self) -> Any: ... - - -def dump(obj: Any, file: IO[str], protocol: int = ...) -> None: ... -def dumps(obj: Any, protocol: int = ...) -> str: ... -def load(file: IO[str]) -> Any: ... -def loads(str: str) -> Any: ... - -class PickleError(Exception): ... -class UnpicklingError(PickleError): ... -class BadPickleGet(UnpicklingError): ... -class PicklingError(PickleError): ... -class UnpickleableError(PicklingError): ... diff --git a/mypy/typeshed/stdlib/python2/cStringIO.pyi b/mypy/typeshed/stdlib/python2/cStringIO.pyi deleted file mode 100644 index 380e3a4be269..000000000000 --- a/mypy/typeshed/stdlib/python2/cStringIO.pyi +++ /dev/null @@ -1,54 +0,0 @@ -# Stubs for cStringIO (Python 2.7) -# See https://docs.python.org/2/library/stringio.html - -from abc import ABCMeta -from typing import overload, IO, List, Iterable, Iterator, Optional, Union -from types import TracebackType - -# TODO the typing.IO[] generics should be split into input and output. - -# This class isn't actually abstract, but you can't instantiate it -# directly, so we might as well treat it as abstract in the stub. -class InputType(IO[str], Iterator[str], metaclass=ABCMeta): - def getvalue(self) -> str: ... - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def read(self, size: int = ...) -> str: ... - def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def truncate(self, size: Optional[int] = ...) -> int: ... - def __iter__(self) -> InputType: ... - def next(self) -> str: ... - def reset(self) -> None: ... - - -class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): - @property - def softspace(self) -> int: ... - def getvalue(self) -> str: ... - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def read(self, size: int = ...) -> str: ... - def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... - def truncate(self, size: Optional[int] = ...) -> int: ... - def __iter__(self) -> OutputType: ... - def next(self) -> str: ... - def reset(self) -> None: ... - def write(self, b: Union[str, unicode]) -> int: ... - def writelines(self, lines: Iterable[Union[str, unicode]]) -> None: ... - -@overload -def StringIO() -> OutputType: ... -@overload -def StringIO(s: str) -> InputType: ... diff --git a/mypy/typeshed/stdlib/python2/collections.pyi b/mypy/typeshed/stdlib/python2/collections.pyi deleted file mode 100644 index 988e9202f674..000000000000 --- a/mypy/typeshed/stdlib/python2/collections.pyi +++ /dev/null @@ -1,120 +0,0 @@ -# These are not exported. -from typing import Any, Dict, Generic, TypeVar, Tuple, overload, Type, Optional, List, Union, Reversible - -# These are exported. -from typing import ( - Callable as Callable, - Container as Container, - Hashable as Hashable, - ItemsView as ItemsView, - Iterable as Iterable, - Iterator as Iterator, - KeysView as KeysView, - Mapping as Mapping, - MappingView as MappingView, - MutableMapping as MutableMapping, - MutableSequence as MutableSequence, - MutableSet as MutableSet, - Sequence as Sequence, - AbstractSet as Set, - Sized as Sized, - ValuesView as ValuesView, -) - -_S = TypeVar('_S') -_T = TypeVar('_T') -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') - -# namedtuple is special-cased in the type checker; the initializer is ignored. -def namedtuple(typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], - verbose: bool = ..., rename: bool = ...) -> Type[Tuple[Any, ...]]: ... - -class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ..., - maxlen: int = ...) -> None: ... - @property - def maxlen(self) -> Optional[int]: ... - def append(self, x: _T) -> None: ... - def appendleft(self, x: _T) -> None: ... - def clear(self) -> None: ... - def count(self, x: _T) -> int: ... - def extend(self, iterable: Iterable[_T]) -> None: ... - def extendleft(self, iterable: Iterable[_T]) -> None: ... - def pop(self) -> _T: ... - def popleft(self) -> _T: ... - def remove(self, value: _T) -> None: ... - def reverse(self) -> None: ... - def rotate(self, n: int) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... - def __hash__(self) -> int: ... - def __getitem__(self, i: int) -> _T: ... - def __setitem__(self, i: int, x: _T) -> None: ... - def __contains__(self, o: _T) -> bool: ... - def __reversed__(self) -> Iterator[_T]: ... - def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... - -class Counter(Dict[_T, int], Generic[_T]): - @overload - def __init__(self, **kwargs: int) -> None: ... - @overload - def __init__(self, mapping: Mapping[_T, int]) -> None: ... - @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... - def copy(self: _S) -> _S: ... - def elements(self) -> Iterator[_T]: ... - def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... - @overload - def subtract(self, __mapping: Mapping[_T, int]) -> None: ... - @overload - def subtract(self, iterable: Iterable[_T]) -> None: ... - # The Iterable[Tuple[...]] argument type is not actually desirable - # (the tuples will be added as keys, breaking type safety) but - # it's included so that the signature is compatible with - # Dict.update. Not sure if we should use '# type: ignore' instead - # and omit the type from the union. - @overload - def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... - @overload - def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... - @overload - def update(self, **kwargs: int) -> None: ... - - def __add__(self, other: Counter[_T]) -> Counter[_T]: ... - def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... - def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... - def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... - def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... - def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... - def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... - -class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): - def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... - def copy(self: _S) -> _S: ... - def __reversed__(self) -> Iterator[_KT]: ... - -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): - default_factory: Callable[[], _VT] - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - map: Mapping[_KT, _VT]) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... - @overload - def __init__(self, default_factory: Optional[Callable[[], _VT]], - iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __missing__(self, key: _KT) -> _VT: ... - def copy(self: _S) -> _S: ... diff --git a/mypy/typeshed/stdlib/python2/commands.pyi b/mypy/typeshed/stdlib/python2/commands.pyi deleted file mode 100644 index e321f0844349..000000000000 --- a/mypy/typeshed/stdlib/python2/commands.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import overload, AnyStr, Text, Tuple - -def getstatus(file: Text) -> str: ... -def getoutput(cmd: Text) -> str: ... -def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... - -@overload -def mk2arg(head: bytes, x: bytes) -> bytes: ... -@overload -def mk2arg(head: Text, x: Text) -> Text: ... - -def mkarg(x: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/compileall.pyi b/mypy/typeshed/stdlib/python2/compileall.pyi deleted file mode 100644 index 22662f46023d..000000000000 --- a/mypy/typeshed/stdlib/python2/compileall.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from _typeshed import AnyPath -from typing import Any, Optional, Pattern - -# rx can be any object with a 'search' method; once we have Protocols we can change the type -def compile_dir( - dir: AnyPath, - maxlevels: int = ..., - ddir: Optional[AnyPath] = ..., - 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 = ..., -) -> int: ... -def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/cookielib.pyi b/mypy/typeshed/stdlib/python2/cookielib.pyi deleted file mode 100644 index abbf29894635..000000000000 --- a/mypy/typeshed/stdlib/python2/cookielib.pyi +++ /dev/null @@ -1,112 +0,0 @@ -from typing import Any, Optional - -class Cookie: - version: Any - name: Any - value: Any - port: Any - port_specified: Any - domain: Any - domain_specified: Any - domain_initial_dot: Any - path: Any - path_specified: Any - secure: Any - expires: Any - discard: Any - comment: Any - comment_url: Any - rfc2109: Any - def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, - path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109: bool = ...): ... - def has_nonstandard_attr(self, name): ... - def get_nonstandard_attr(self, name, default: Optional[Any] = ...): ... - def set_nonstandard_attr(self, name, value): ... - def is_expired(self, now: Optional[Any] = ...): ... - -class CookiePolicy: - def set_ok(self, cookie, request): ... - def return_ok(self, cookie, request): ... - def domain_return_ok(self, domain, request): ... - def path_return_ok(self, path, request): ... - -class DefaultCookiePolicy(CookiePolicy): - DomainStrictNoDots: Any - DomainStrictNonDomain: Any - DomainRFC2965Match: Any - DomainLiberal: Any - DomainStrict: Any - netscape: Any - rfc2965: Any - rfc2109_as_netscape: Any - hide_cookie2: Any - strict_domain: Any - strict_rfc2965_unverifiable: Any - strict_ns_unverifiable: Any - strict_ns_domain: Any - strict_ns_set_initial_dollar: Any - strict_ns_set_path: Any - def __init__(self, blocked_domains: Optional[Any] = ..., allowed_domains: Optional[Any] = ..., netscape: bool = ..., - rfc2965: bool = ..., rfc2109_as_netscape: Optional[Any] = ..., hide_cookie2: bool = ..., - strict_domain: bool = ..., strict_rfc2965_unverifiable: bool = ..., strict_ns_unverifiable: bool = ..., - strict_ns_domain=..., strict_ns_set_initial_dollar: bool = ..., strict_ns_set_path: bool = ...): ... - def blocked_domains(self): ... - def set_blocked_domains(self, blocked_domains): ... - def is_blocked(self, domain): ... - def allowed_domains(self): ... - def set_allowed_domains(self, allowed_domains): ... - def is_not_allowed(self, domain): ... - def set_ok(self, cookie, request): ... - def set_ok_version(self, cookie, request): ... - def set_ok_verifiability(self, cookie, request): ... - def set_ok_name(self, cookie, request): ... - def set_ok_path(self, cookie, request): ... - def set_ok_domain(self, cookie, request): ... - def set_ok_port(self, cookie, request): ... - def return_ok(self, cookie, request): ... - def return_ok_version(self, cookie, request): ... - def return_ok_verifiability(self, cookie, request): ... - def return_ok_secure(self, cookie, request): ... - def return_ok_expires(self, cookie, request): ... - def return_ok_port(self, cookie, request): ... - def return_ok_domain(self, cookie, request): ... - def domain_return_ok(self, domain, request): ... - def path_return_ok(self, path, request): ... - -class Absent: ... - -class CookieJar: - non_word_re: Any - quote_re: Any - strict_domain_re: Any - domain_re: Any - dots_re: Any - magic_re: Any - def __init__(self, policy: Optional[Any] = ...): ... - def set_policy(self, policy): ... - def add_cookie_header(self, request): ... - def make_cookies(self, response, request): ... - def set_cookie_if_ok(self, cookie, request): ... - def set_cookie(self, cookie): ... - def extract_cookies(self, response, request): ... - def clear(self, domain: Optional[Any] = ..., path: Optional[Any] = ..., name: Optional[Any] = ...): ... - def clear_session_cookies(self): ... - def clear_expired_cookies(self): ... - def __iter__(self): ... - def __len__(self): ... - -class LoadError(IOError): ... - -class FileCookieJar(CookieJar): - filename: Any - delayload: Any - def __init__(self, filename: Optional[Any] = ..., delayload: bool = ..., policy: Optional[Any] = ...): ... - def save(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - def load(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - def revert(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... - -class LWPCookieJar(FileCookieJar): - def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented - -MozillaCookieJar = FileCookieJar -def lwp_cookie_str(cookie: Cookie) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/copy_reg.pyi b/mypy/typeshed/stdlib/python2/copy_reg.pyi deleted file mode 100644 index a64a82c700d0..000000000000 --- a/mypy/typeshed/stdlib/python2/copy_reg.pyi +++ /dev/null @@ -1,14 +0,0 @@ - -from typing import TypeVar, Callable, Union, Tuple, Any, Optional, SupportsInt, Hashable, List - - -_Type = TypeVar("_Type", bound=type) -_Reduce = Union[Tuple[Callable[..., _Type], Tuple[Any, ...]], Tuple[Callable[..., _Type], Tuple[Any, ...], Optional[Any]]] - -__all__: List[str] - -def pickle(ob_type: _Type, pickle_function: Callable[[_Type], Union[str, _Reduce[_Type]]], constructor_ob: Optional[Callable[[_Reduce[_Type]], _Type]] = ...) -> None: ... -def constructor(object: Callable[[_Reduce[_Type]], _Type]) -> 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/dircache.pyi b/mypy/typeshed/stdlib/python2/dircache.pyi deleted file mode 100644 index ac6732b6c16a..000000000000 --- a/mypy/typeshed/stdlib/python2/dircache.pyi +++ /dev/null @@ -1,10 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/dircache.py - -from typing import List, MutableSequence, Text, Union - -def reset() -> None: ... -def listdir(path: Text) -> List[str]: ... - -opendir = listdir - -def annotate(head: Text, list: Union[MutableSequence[str], MutableSequence[Text], MutableSequence[Union[str, Text]]]) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi b/mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi deleted file mode 100644 index 97e4a29adda8..000000000000 --- a/mypy/typeshed/stdlib/python2/distutils/emxccompiler.pyi +++ /dev/null @@ -1,5 +0,0 @@ -# Stubs for emxccompiler - -from distutils.unixccompiler import UnixCCompiler - -class EMXCCompiler(UnixCCompiler): ... diff --git a/mypy/typeshed/stdlib/python2/dummy_thread.pyi b/mypy/typeshed/stdlib/python2/dummy_thread.pyi deleted file mode 100644 index 28041002a708..000000000000 --- a/mypy/typeshed/stdlib/python2/dummy_thread.pyi +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any, Callable, Dict, NoReturn, Optional, Tuple - -class error(Exception): - def __init__(self, *args: Any) -> None: ... - -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... -def exit() -> NoReturn: ... -def get_ident() -> int: ... -def allocate_lock() -> LockType: ... -def stack_size(size: Optional[int] = ...) -> int: ... - -class LockType(object): - locked_status: bool - def __init__(self) -> None: ... - def acquire(self, waitflag: Optional[bool] = ...) -> bool: ... - def __enter__(self, waitflag: Optional[bool] = ...) -> bool: ... - def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... - def release(self) -> bool: ... - def locked(self) -> bool: ... - -def interrupt_main() -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/MIMEText.pyi b/mypy/typeshed/stdlib/python2/email/MIMEText.pyi deleted file mode 100644 index 3b059778aa66..000000000000 --- a/mypy/typeshed/stdlib/python2/email/MIMEText.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEText(MIMENonMultipart): - def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/__init__.pyi b/mypy/typeshed/stdlib/python2/email/__init__.pyi deleted file mode 100644 index 384d9567f7b0..000000000000 --- a/mypy/typeshed/stdlib/python2/email/__init__.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import IO, Any, AnyStr - -def message_from_string(s: AnyStr, *args, **kwargs): ... -def message_from_bytes(s: str, *args, **kwargs): ... -def message_from_file(fp: IO[AnyStr], *args, **kwargs): ... -def message_from_binary_file(fp: IO[str], *args, **kwargs): ... diff --git a/mypy/typeshed/stdlib/python2/email/_parseaddr.pyi b/mypy/typeshed/stdlib/python2/email/_parseaddr.pyi deleted file mode 100644 index 424ade705f77..000000000000 --- a/mypy/typeshed/stdlib/python2/email/_parseaddr.pyi +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Any, Optional - -def parsedate_tz(data): ... -def parsedate(data): ... -def mktime_tz(data): ... -def quote(str): ... - -class AddrlistClass: - specials: Any - pos: Any - LWS: Any - CR: Any - FWS: Any - atomends: Any - phraseends: Any - field: Any - commentlist: Any - def __init__(self, field): ... - def gotonext(self): ... - def getaddrlist(self): ... - def getaddress(self): ... - def getrouteaddr(self): ... - def getaddrspec(self): ... - def getdomain(self): ... - def getdelimited(self, beginchar, endchars, allowcomments: bool = ...): ... - def getquote(self): ... - def getcomment(self): ... - def getdomainliteral(self): ... - def getatom(self, atomends: Optional[Any] = ...): ... - def getphraselist(self): ... - -class AddressList(AddrlistClass): - addresslist: Any - def __init__(self, field): ... - def __len__(self): ... - def __add__(self, other): ... - def __iadd__(self, other): ... - def __sub__(self, other): ... - def __isub__(self, other): ... - def __getitem__(self, index): ... diff --git a/mypy/typeshed/stdlib/python2/email/base64mime.pyi b/mypy/typeshed/stdlib/python2/email/base64mime.pyi deleted file mode 100644 index f05003b8d5a7..000000000000 --- a/mypy/typeshed/stdlib/python2/email/base64mime.pyi +++ /dev/null @@ -1,8 +0,0 @@ -def base64_len(s: bytes) -> int: ... -def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ... -def encode(s, binary=..., maxlinelen=..., eol=...): ... -body_encode = encode -encodestring = encode -def decode(s, convert_eols=...): ... -body_decode = decode -decodestring = decode diff --git a/mypy/typeshed/stdlib/python2/email/charset.pyi b/mypy/typeshed/stdlib/python2/email/charset.pyi deleted file mode 100644 index 88b5f88d1843..000000000000 --- a/mypy/typeshed/stdlib/python2/email/charset.pyi +++ /dev/null @@ -1,26 +0,0 @@ -def add_charset(charset, header_enc=..., body_enc=..., output_charset=...) -> None: ... -def add_alias(alias, canonical) -> None: ... -def add_codec(charset, codecname) -> None: ... - -QP: int # undocumented -BASE64: int # undocumented -SHORTEST: int # undocumented - -class Charset: - input_charset = ... - header_encoding = ... - body_encoding = ... - output_charset = ... - input_codec = ... - output_codec = ... - def __init__(self, input_charset=...) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def get_body_encoding(self): ... - def convert(self, s): ... - def to_splittable(self, s): ... - def from_splittable(self, ustr, to_output: bool = ...): ... - def get_output_charset(self): ... - def encoded_header_len(self, s): ... - def header_encode(self, s, convert: bool = ...): ... - def body_encode(self, s, convert: bool = ...): ... diff --git a/mypy/typeshed/stdlib/python2/email/encoders.pyi b/mypy/typeshed/stdlib/python2/email/encoders.pyi deleted file mode 100644 index 5670cbaf08ed..000000000000 --- a/mypy/typeshed/stdlib/python2/email/encoders.pyi +++ /dev/null @@ -1,4 +0,0 @@ -def encode_base64(msg) -> None: ... -def encode_quopri(msg) -> None: ... -def encode_7or8bit(msg) -> None: ... -def encode_noop(msg) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/feedparser.pyi b/mypy/typeshed/stdlib/python2/email/feedparser.pyi deleted file mode 100644 index 51f825939347..000000000000 --- a/mypy/typeshed/stdlib/python2/email/feedparser.pyi +++ /dev/null @@ -1,18 +0,0 @@ -class BufferedSubFile: - def __init__(self) -> None: ... - def push_eof_matcher(self, pred) -> None: ... - def pop_eof_matcher(self): ... - def close(self) -> None: ... - def readline(self): ... - def unreadline(self, line) -> None: ... - def push(self, data): ... - def pushlines(self, lines) -> None: ... - def is_closed(self): ... - def __iter__(self): ... - def next(self): ... - - -class FeedParser: - def __init__(self, _factory=...) -> None: ... - def feed(self, data) -> None: ... - def close(self): ... diff --git a/mypy/typeshed/stdlib/python2/email/generator.pyi b/mypy/typeshed/stdlib/python2/email/generator.pyi deleted file mode 100644 index 96cfe2d214a5..000000000000 --- a/mypy/typeshed/stdlib/python2/email/generator.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class Generator: - def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ...) -> None: ... - def write(self, s) -> None: ... - def flatten(self, msg, unixfrom: bool = ...) -> None: ... - def clone(self, fp): ... - - -class DecodedGenerator(Generator): - def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ..., fmt=...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/header.pyi b/mypy/typeshed/stdlib/python2/email/header.pyi deleted file mode 100644 index 69c936300cce..000000000000 --- a/mypy/typeshed/stdlib/python2/email/header.pyi +++ /dev/null @@ -1,11 +0,0 @@ -def decode_header(header): ... -def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ... - -class Header: - def __init__(self, s=..., charset=..., maxlinelen=..., header_name=..., continuation_ws=..., - errors=...) -> None: ... - def __unicode__(self): ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def append(self, s, charset=..., errors=...) -> None: ... - def encode(self, splitchars=...): ... diff --git a/mypy/typeshed/stdlib/python2/email/iterators.pyi b/mypy/typeshed/stdlib/python2/email/iterators.pyi deleted file mode 100644 index 5002644117a4..000000000000 --- a/mypy/typeshed/stdlib/python2/email/iterators.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any, Generator - -def walk(self) -> Generator[Any, Any, Any]: ... -def body_line_iterator(msg, decode: bool = ...) -> Generator[Any, Any, Any]: ... -def typed_subpart_iterator(msg, maintype=..., subtype=...) -> Generator[Any, Any, Any]: ... diff --git a/mypy/typeshed/stdlib/python2/email/message.pyi b/mypy/typeshed/stdlib/python2/email/message.pyi deleted file mode 100644 index 642bba7c0102..000000000000 --- a/mypy/typeshed/stdlib/python2/email/message.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Any, Generator - -class Message: - preamble = ... - epilogue = ... - defects = ... - def __init__(self): ... - def as_string(self, unixfrom=...): ... - def is_multipart(self) -> bool: ... - def set_unixfrom(self, unixfrom) -> None: ... - def get_unixfrom(self): ... - def attach(self, payload) -> None: ... - def get_payload(self, i=..., decode: bool = ...): ... - def set_payload(self, payload, charset=...) -> None: ... - def set_charset(self, charset): ... - def get_charset(self): ... - def __len__(self): ... - def __getitem__(self, name): ... - def __setitem__(self, name, val) -> None: ... - def __delitem__(self, name) -> None: ... - def __contains__(self, name): ... - def has_key(self, name) -> bool: ... - def keys(self): ... - def values(self): ... - def items(self): ... - def get(self, name, failobj=...): ... - def get_all(self, name, failobj=...): ... - def add_header(self, _name, _value, **_params) -> None: ... - def replace_header(self, _name, _value) -> None: ... - def get_content_type(self): ... - def get_content_maintype(self): ... - def get_content_subtype(self): ... - def get_default_type(self): ... - def set_default_type(self, ctype) -> None: ... - def get_params(self, failobj=..., header=..., unquote: bool = ...): ... - def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... - def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... - def del_param(self, param, header=..., requote: bool = ...): ... - def set_type(self, type, header=..., requote: bool = ...): ... - def get_filename(self, failobj=...): ... - def get_boundary(self, failobj=...): ... - def set_boundary(self, boundary) -> None: ... - def get_content_charset(self, failobj=...): ... - def get_charsets(self, failobj=...): ... - def walk(self) -> Generator[Any, Any, Any]: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/__init__.pyi b/mypy/typeshed/stdlib/python2/email/mime/__init__.pyi deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/mypy/typeshed/stdlib/python2/email/mime/application.pyi b/mypy/typeshed/stdlib/python2/email/mime/application.pyi deleted file mode 100644 index 99da67287bd5..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/application.pyi +++ /dev/null @@ -1,11 +0,0 @@ -# Stubs for email.mime.application - -from typing import Callable, Optional, Tuple, Union -from email.mime.nonmultipart import MIMENonMultipart - -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] - -class MIMEApplication(MIMENonMultipart): - def __init__(self, _data: bytes, _subtype: str = ..., - _encoder: Callable[[MIMEApplication], None] = ..., - **_params: _ParamsType) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/audio.pyi b/mypy/typeshed/stdlib/python2/email/mime/audio.pyi deleted file mode 100644 index 406ade11b362..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/audio.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - - -class MIMEAudio(MIMENonMultipart): - def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/base.pyi b/mypy/typeshed/stdlib/python2/email/mime/base.pyi deleted file mode 100644 index 4bde4f073395..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/base.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email import message - -class MIMEBase(message.Message): - def __init__(self, _maintype, _subtype, **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/image.pyi b/mypy/typeshed/stdlib/python2/email/mime/image.pyi deleted file mode 100644 index 2dfb098b8567..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/image.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - - -class MIMEImage(MIMENonMultipart): - def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/message.pyi b/mypy/typeshed/stdlib/python2/email/mime/message.pyi deleted file mode 100644 index 33552faf2ca6..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/message.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - - -class MIMEMessage(MIMENonMultipart): - def __init__(self, _msg, _subtype=...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/multipart.pyi b/mypy/typeshed/stdlib/python2/email/mime/multipart.pyi deleted file mode 100644 index 0a7d3fa8acb0..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/multipart.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.base import MIMEBase - -class MIMEMultipart(MIMEBase): - def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi deleted file mode 100644 index 04d130e3da88..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/nonmultipart.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.base import MIMEBase - -class MIMENonMultipart(MIMEBase): - def attach(self, payload): ... diff --git a/mypy/typeshed/stdlib/python2/email/mime/text.pyi b/mypy/typeshed/stdlib/python2/email/mime/text.pyi deleted file mode 100644 index 3b059778aa66..000000000000 --- a/mypy/typeshed/stdlib/python2/email/mime/text.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from email.mime.nonmultipart import MIMENonMultipart - -class MIMEText(MIMENonMultipart): - def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/email/parser.pyi b/mypy/typeshed/stdlib/python2/email/parser.pyi deleted file mode 100644 index 4f2282834ca5..000000000000 --- a/mypy/typeshed/stdlib/python2/email/parser.pyi +++ /dev/null @@ -1,10 +0,0 @@ -from .feedparser import FeedParser as FeedParser # not in __all__ but listed in documentation - -class Parser: - def __init__(self, *args, **kws) -> None: ... - def parse(self, fp, headersonly: bool = ...): ... - def parsestr(self, text, headersonly: bool = ...): ... - -class HeaderParser(Parser): - def parse(self, fp, headersonly: bool = ...): ... - def parsestr(self, text, headersonly: bool = ...): ... diff --git a/mypy/typeshed/stdlib/python2/email/quoprimime.pyi b/mypy/typeshed/stdlib/python2/email/quoprimime.pyi deleted file mode 100644 index 3f2963c06e6d..000000000000 --- a/mypy/typeshed/stdlib/python2/email/quoprimime.pyi +++ /dev/null @@ -1,18 +0,0 @@ -def header_quopri_check(c): ... -def body_quopri_check(c): ... -def header_quopri_len(s): ... -def body_quopri_len(str): ... -def unquote(s): ... -def quote(c): ... -def header_encode(header, charset: str = ..., keep_eols: bool = ..., maxlinelen: int = ..., eol=...): ... -def encode(body, binary: bool = ..., maxlinelen: int = ..., eol=...): ... - -body_encode = encode -encodestring = encode - -def decode(encoded, eol=...): ... - -body_decode = decode -decodestring = decode - -def header_decode(s): ... diff --git a/mypy/typeshed/stdlib/python2/email/utils.pyi b/mypy/typeshed/stdlib/python2/email/utils.pyi deleted file mode 100644 index 7b868efce86c..000000000000 --- a/mypy/typeshed/stdlib/python2/email/utils.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from email._parseaddr import AddressList as _AddressList -from email._parseaddr import mktime_tz as mktime_tz -from email._parseaddr import parsedate as _parsedate -from email._parseaddr import parsedate_tz as _parsedate_tz -from quopri import decodestring as _qdecode -from typing import Optional, Any - -def formataddr(pair): ... -def getaddresses(fieldvalues): ... -def formatdate(timeval: Optional[Any] = ..., localtime: bool = ..., usegmt: bool = ...): ... -def make_msgid(idstring: Optional[Any] = ...): ... -def parsedate(data): ... -def parsedate_tz(data): ... -def parseaddr(addr): ... -def unquote(str): ... -def decode_rfc2231(s): ... -def encode_rfc2231(s, charset: Optional[Any] = ..., language: Optional[Any] = ...): ... -def decode_params(params): ... -def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ... diff --git a/mypy/typeshed/stdlib/python2/encodings/__init__.pyi b/mypy/typeshed/stdlib/python2/encodings/__init__.pyi deleted file mode 100644 index 23e7ea7003f1..000000000000 --- a/mypy/typeshed/stdlib/python2/encodings/__init__.pyi +++ /dev/null @@ -1,8 +0,0 @@ -import codecs - -from typing import Any - -def search_function(encoding: str) -> codecs.CodecInfo: ... - -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/python2/encodings/utf_8.pyi b/mypy/typeshed/stdlib/python2/encodings/utf_8.pyi deleted file mode 100644 index d38bd58d0e43..000000000000 --- a/mypy/typeshed/stdlib/python2/encodings/utf_8.pyi +++ /dev/null @@ -1,15 +0,0 @@ -import codecs -from typing import Text, Tuple - -class IncrementalEncoder(codecs.IncrementalEncoder): - def encode(self, input: Text, final: bool = ...) -> bytes: ... - -class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... - -class StreamWriter(codecs.StreamWriter): ... -class StreamReader(codecs.StreamReader): ... - -def getregentry() -> codecs.CodecInfo: ... -def encode(input: Text, errors: Text = ...) -> bytes: ... -def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/mypy/typeshed/stdlib/python2/exceptions.pyi b/mypy/typeshed/stdlib/python2/exceptions.pyi deleted file mode 100644 index 6e4bafc9a00f..000000000000 --- a/mypy/typeshed/stdlib/python2/exceptions.pyi +++ /dev/null @@ -1,48 +0,0 @@ -from __builtin__ import ArithmeticError as ArithmeticError -from __builtin__ import AssertionError as AssertionError -from __builtin__ import AttributeError as AttributeError -from __builtin__ import BaseException as BaseException -from __builtin__ import BufferError as BufferError -from __builtin__ import BytesWarning as BytesWarning -from __builtin__ import DeprecationWarning as DeprecationWarning -from __builtin__ import EOFError as EOFError -from __builtin__ import EnvironmentError as EnvironmentError -from __builtin__ import Exception as Exception -from __builtin__ import FloatingPointError as FloatingPointError -from __builtin__ import FutureWarning as FutureWarning -from __builtin__ import GeneratorExit as GeneratorExit -from __builtin__ import IOError as IOError -from __builtin__ import ImportError as ImportError -from __builtin__ import ImportWarning as ImportWarning -from __builtin__ import IndentationError as IndentationError -from __builtin__ import IndexError as IndexError -from __builtin__ import KeyError as KeyError -from __builtin__ import KeyboardInterrupt as KeyboardInterrupt -from __builtin__ import LookupError as LookupError -from __builtin__ import MemoryError as MemoryError -from __builtin__ import NameError as NameError -from __builtin__ import NotImplementedError as NotImplementedError -from __builtin__ import OSError as OSError -from __builtin__ import OverflowError as OverflowError -from __builtin__ import PendingDeprecationWarning as PendingDeprecationWarning -from __builtin__ import ReferenceError as ReferenceError -from __builtin__ import RuntimeError as RuntimeError -from __builtin__ import RuntimeWarning as RuntimeWarning -from __builtin__ import StandardError as StandardError -from __builtin__ import StopIteration as StopIteration -from __builtin__ import SyntaxError as SyntaxError -from __builtin__ import SyntaxWarning as SyntaxWarning -from __builtin__ import SystemError as SystemError -from __builtin__ import SystemExit as SystemExit -from __builtin__ import TabError as TabError -from __builtin__ import TypeError as TypeError -from __builtin__ import UnboundLocalError as UnboundLocalError -from __builtin__ import UnicodeError as UnicodeError -from __builtin__ import UnicodeDecodeError as UnicodeDecodeError -from __builtin__ import UnicodeEncodeError as UnicodeEncodeError -from __builtin__ import UnicodeTranslateError as UnicodeTranslateError -from __builtin__ import UnicodeWarning as UnicodeWarning -from __builtin__ import UserWarning as UserWarning -from __builtin__ import ValueError as ValueError -from __builtin__ import Warning as Warning -from __builtin__ import ZeroDivisionError as ZeroDivisionError diff --git a/mypy/typeshed/stdlib/python2/fcntl.pyi b/mypy/typeshed/stdlib/python2/fcntl.pyi deleted file mode 100644 index a8f054cc81e0..000000000000 --- a/mypy/typeshed/stdlib/python2/fcntl.pyi +++ /dev/null @@ -1,85 +0,0 @@ -from typing import Any, Union -from _typeshed import FileDescriptorLike - -FASYNC: int -FD_CLOEXEC: int - -DN_ACCESS: int -DN_ATTRIB: int -DN_CREATE: int -DN_DELETE: int -DN_MODIFY: int -DN_MULTISHOT: int -DN_RENAME: int -F_DUPFD: int -F_EXLCK: int -F_GETFD: int -F_GETFL: int -F_GETLEASE: int -F_GETLK: int -F_GETLK64: int -F_GETOWN: int -F_GETSIG: int -F_NOTIFY: int -F_RDLCK: int -F_SETFD: int -F_SETFL: int -F_SETLEASE: int -F_SETLK: int -F_SETLK64: int -F_SETLKW: int -F_SETLKW64: int -F_SETOWN: int -F_SETSIG: int -F_SHLCK: int -F_UNLCK: int -F_WRLCK: int -I_ATMARK: int -I_CANPUT: int -I_CKBAND: int -I_FDINSERT: int -I_FIND: int -I_FLUSH: int -I_FLUSHBAND: int -I_GETBAND: int -I_GETCLTIME: int -I_GETSIG: int -I_GRDOPT: int -I_GWROPT: int -I_LINK: int -I_LIST: int -I_LOOK: int -I_NREAD: int -I_PEEK: int -I_PLINK: int -I_POP: int -I_PUNLINK: int -I_PUSH: int -I_RECVFD: int -I_SENDFD: int -I_SETCLTIME: int -I_SETSIG: int -I_SRDOPT: int -I_STR: int -I_SWROPT: int -I_UNLINK: int -LOCK_EX: int -LOCK_MAND: int -LOCK_NB: int -LOCK_READ: int -LOCK_RW: int -LOCK_SH: int -LOCK_UN: int -LOCK_WRITE: int - -# TODO All these return either int or bytes depending on the value of -# cmd (not on the type of arg). -def fcntl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ...) -> Any: ... - -# TODO: arg: int or read-only buffer interface or read-write buffer interface -def ioctl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ..., - mutate_flag: bool = ...) -> Any: ... - -def flock(fd: FileDescriptorLike, op: int) -> None: ... -def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., - whence: int = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/python2/fnmatch.pyi b/mypy/typeshed/stdlib/python2/fnmatch.pyi deleted file mode 100644 index e933b7b2cb62..000000000000 --- a/mypy/typeshed/stdlib/python2/fnmatch.pyi +++ /dev/null @@ -1,8 +0,0 @@ -from typing import AnyStr, Iterable, List, Union - -_EitherStr = Union[str, unicode] - -def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... -def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... -def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... -def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/functools.pyi b/mypy/typeshed/stdlib/python2/functools.pyi deleted file mode 100644 index 42bc622ebd1a..000000000000 --- a/mypy/typeshed/stdlib/python2/functools.pyi +++ /dev/null @@ -1,33 +0,0 @@ -# Stubs for functools (Python 2.7) - -# NOTE: These are incomplete! - -from abc import ABCMeta, abstractmethod -from typing import Any, Callable, Generic, Dict, Iterable, Optional, Sequence, Tuple, Type, TypeVar, overload - -_AnyCallable = Callable[..., Any] - -_T = TypeVar("_T") -_S = TypeVar("_S") -@overload -def reduce(function: Callable[[_T, _T], _T], - sequence: Iterable[_T]) -> _T: ... -@overload -def reduce(function: Callable[[_T, _S], _T], - sequence: Iterable[_S], initial: _T) -> _T: ... - -WRAPPER_ASSIGNMENTS: Sequence[str] -WRAPPER_UPDATES: Sequence[str] - -def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., - updated: Sequence[str] = ...) -> _AnyCallable: ... -def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... -def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... - -class partial(Generic[_T]): - func = ... # Callable[..., _T] - args: Tuple[Any, ...] - keywords: Dict[str, Any] - def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/python2/future_builtins.pyi b/mypy/typeshed/stdlib/python2/future_builtins.pyi deleted file mode 100644 index a9b25b2fec6e..000000000000 --- a/mypy/typeshed/stdlib/python2/future_builtins.pyi +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Any - -from itertools import ifilter as filter -from itertools import imap as map -from itertools import izip as zip - - -def ascii(obj: Any) -> str: ... - - -def hex(x: int) -> str: ... - - -def oct(x: int) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/gc.pyi b/mypy/typeshed/stdlib/python2/gc.pyi deleted file mode 100644 index cdfae7491dfb..000000000000 --- a/mypy/typeshed/stdlib/python2/gc.pyi +++ /dev/null @@ -1,29 +0,0 @@ -# Stubs for gc - -from typing import Any, List, Tuple - - -def enable() -> None: ... -def disable() -> None: ... -def isenabled() -> bool: ... -def collect(generation: int = ...) -> int: ... -def set_debug(flags: int) -> None: ... -def get_debug() -> int: ... -def get_objects() -> List[Any]: ... -def set_threshold(threshold0: int, threshold1: int = ..., - threshold2: int = ...) -> None: ... -def get_count() -> Tuple[int, int, int]: ... -def get_threshold() -> Tuple[int, int, int]: ... -def get_referrers(*objs: Any) -> List[Any]: ... -def get_referents(*objs: Any) -> List[Any]: ... -def is_tracked(obj: Any) -> bool: ... - -garbage: List[Any] - -DEBUG_STATS: int -DEBUG_COLLECTABLE: int -DEBUG_UNCOLLECTABLE: int -DEBUG_INSTANCES: int -DEBUG_OBJECTS: int -DEBUG_SAVEALL: int -DEBUG_LEAK: int diff --git a/mypy/typeshed/stdlib/python2/getopt.pyi b/mypy/typeshed/stdlib/python2/getopt.pyi deleted file mode 100644 index 370d4d5c1cba..000000000000 --- a/mypy/typeshed/stdlib/python2/getopt.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import List, Tuple - -class GetoptError(Exception): - opt: str - msg: str - def __init__(self, msg: str, opt: str = ...) -> None: ... - def __str__(self) -> str: ... - -error = GetoptError - -def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... -def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/mypy/typeshed/stdlib/python2/getpass.pyi b/mypy/typeshed/stdlib/python2/getpass.pyi deleted file mode 100644 index 011fc8e7924c..000000000000 --- a/mypy/typeshed/stdlib/python2/getpass.pyi +++ /dev/null @@ -1,8 +0,0 @@ -# Stubs for getpass (Python 2) - -from typing import Any, IO - -class GetPassWarning(UserWarning): ... - -def getpass(prompt: str = ..., stream: IO[Any] = ...) -> str: ... -def getuser() -> str: ... diff --git a/mypy/typeshed/stdlib/python2/gettext.pyi b/mypy/typeshed/stdlib/python2/gettext.pyi deleted file mode 100644 index c7bfceb7b82c..000000000000 --- a/mypy/typeshed/stdlib/python2/gettext.pyi +++ /dev/null @@ -1,41 +0,0 @@ -from typing import Any, Container, Dict, IO, List, Optional, Sequence, Type, Union - -def bindtextdomain(domain: str, localedir: str = ...) -> str: ... -def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... -def textdomain(domain: str = ...) -> str: ... -def gettext(message: str) -> str: ... -def lgettext(message: str) -> str: ... -def dgettext(domain: str, message: str) -> str: ... -def ldgettext(domain: str, message: str) -> str: ... -def ngettext(singular: str, plural: str, n: int) -> str: ... -def lngettext(singular: str, plural: str, n: int) -> str: ... -def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... -def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... - -class NullTranslations(object): - def __init__(self, fp: IO[str] = ...) -> None: ... - def _parse(self, fp: IO[str]) -> None: ... - def add_fallback(self, fallback: NullTranslations) -> None: ... - def gettext(self, message: str) -> str: ... - def lgettext(self, message: str) -> str: ... - def ugettext(self, message: Union[str, unicode]) -> unicode: ... - def ngettext(self, singular: str, plural: str, n: int) -> str: ... - def lngettext(self, singular: str, plural: str, n: int) -> str: ... - def ungettext(self, singular: Union[str, unicode], plural: Union[str, unicode], n: int) -> unicode: ... - def info(self) -> Dict[str, str]: ... - def charset(self) -> Optional[str]: ... - def output_charset(self) -> Optional[str]: ... - def set_output_charset(self, charset: Optional[str]) -> None: ... - def install(self, unicode: bool = ..., names: Container[str] = ...) -> None: ... - -class GNUTranslations(NullTranslations): - LE_MAGIC: int - BE_MAGIC: int - -def find(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., - all: Any = ...) -> Optional[Union[str, List[str]]]: ... - -def translation(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., - class_: Optional[Type[NullTranslations]] = ..., fallback: bool = ..., codeset: Optional[str] = ...) -> NullTranslations: ... -def install(domain: str, localedir: Optional[str] = ..., unicode: bool = ..., codeset: Optional[str] = ..., - names: Container[str] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/glob.pyi b/mypy/typeshed/stdlib/python2/glob.pyi deleted file mode 100644 index 5caa166f8e26..000000000000 --- a/mypy/typeshed/stdlib/python2/glob.pyi +++ /dev/null @@ -1,7 +0,0 @@ -from typing import List, Iterator, Union, AnyStr - -def glob(pathname: AnyStr) -> List[AnyStr]: ... -def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... -def glob1(dirname: Union[str, unicode], pattern: AnyStr) -> List[AnyStr]: ... -def glob0(dirname: Union[str, unicode], basename: AnyStr) -> List[AnyStr]: ... -def has_magic(s: Union[str, unicode]) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/python2/gzip.pyi b/mypy/typeshed/stdlib/python2/gzip.pyi deleted file mode 100644 index 50c38e426208..000000000000 --- a/mypy/typeshed/stdlib/python2/gzip.pyi +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Any, IO, Text -import io - -class GzipFile(io.BufferedIOBase): - myfileobj: Any - max_read_chunk: Any - mode: Any - extrabuf: Any - extrasize: Any - extrastart: Any - name: Any - min_readsize: Any - compress: Any - fileobj: Any - offset: Any - mtime: Any - def __init__(self, filename: str = ..., mode: Text = ..., compresslevel: int = ..., - fileobj: IO[str] = ..., mtime: float = ...) -> None: ... - @property - def filename(self): ... - size: Any - crc: Any - def write(self, data): ... - def read(self, size=...): ... - @property - def closed(self): ... - def close(self): ... - def flush(self, zlib_mode=...): ... - def fileno(self): ... - def rewind(self): ... - def readable(self): ... - def writable(self): ... - def seekable(self): ... - def seek(self, offset, whence=...): ... - def readline(self, size=...): ... - -def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ... diff --git a/mypy/typeshed/stdlib/python2/hashlib.pyi b/mypy/typeshed/stdlib/python2/hashlib.pyi deleted file mode 100644 index 70423742ea61..000000000000 --- a/mypy/typeshed/stdlib/python2/hashlib.pyi +++ /dev/null @@ -1,31 +0,0 @@ -# Stubs for hashlib (Python 2) - -from typing import Tuple, Union - -_DataType = Union[str, unicode, bytearray, buffer, memoryview] - -class _hash(object): # This is not actually in the module namespace. - name: str - block_size: int - digest_size: int - digestsize: int - def __init__(self, arg: _DataType = ...) -> None: ... - def update(self, arg: _DataType) -> None: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def copy(self) -> _hash: ... - -def new(name: str, data: str = ...) -> _hash: ... - -def md5(s: _DataType = ...) -> _hash: ... -def sha1(s: _DataType = ...) -> _hash: ... -def sha224(s: _DataType = ...) -> _hash: ... -def sha256(s: _DataType = ...) -> _hash: ... -def sha384(s: _DataType = ...) -> _hash: ... -def sha512(s: _DataType = ...) -> _hash: ... - -algorithms: Tuple[str, ...] -algorithms_guaranteed: Tuple[str, ...] -algorithms_available: Tuple[str, ...] - -def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/heapq.pyi b/mypy/typeshed/stdlib/python2/heapq.pyi deleted file mode 100644 index 0e706c5f6ca3..000000000000 --- a/mypy/typeshed/stdlib/python2/heapq.pyi +++ /dev/null @@ -1,18 +0,0 @@ -from typing import TypeVar, List, Iterable, Any, Callable, Optional, Protocol - -_T = TypeVar('_T') - -class _Sortable(Protocol): - def __lt__(self: _T, other: _T) -> bool: ... - -def cmp_lt(x, y) -> bool: ... -def heappush(heap: List[_T], item: _T) -> None: ... -def heappop(heap: List[_T]) -> _T: ... -def heappushpop(heap: List[_T], item: _T) -> _T: ... -def heapify(x: List[_T]) -> None: ... -def heapreplace(heap: List[_T], item: _T) -> _T: ... -def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], - key: Optional[Callable[[_T], _Sortable]] = ...) -> List[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], - key: Optional[Callable[[_T], _Sortable]] = ...) -> List[_T]: ... diff --git a/mypy/typeshed/stdlib/python2/htmlentitydefs.pyi b/mypy/typeshed/stdlib/python2/htmlentitydefs.pyi deleted file mode 100644 index 749b3039dfc3..000000000000 --- a/mypy/typeshed/stdlib/python2/htmlentitydefs.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Dict - -name2codepoint: Dict[str, int] -codepoint2name: Dict[int, str] -entitydefs: Dict[str, str] diff --git a/mypy/typeshed/stdlib/python2/httplib.pyi b/mypy/typeshed/stdlib/python2/httplib.pyi deleted file mode 100644 index 4e3843c1414d..000000000000 --- a/mypy/typeshed/stdlib/python2/httplib.pyi +++ /dev/null @@ -1,205 +0,0 @@ -# Stubs for httplib (Python 2) -# -# Generated by stubgen and manually massaged a bit. -# Needs lots more work! - -from typing import Any, Dict, Optional, Protocol -import mimetools -import ssl - -class HTTPMessage(mimetools.Message): - def addcontinue(self, key: str, more: str) -> None: ... - dict: Dict[str, str] - def addheader(self, key: str, value: str) -> None: ... - unixfrom: str - headers: Any - status: str - seekable: bool - def readheaders(self) -> None: ... - -class HTTPResponse: - fp: Any - debuglevel: Any - strict: Any - msg: Any - version: Any - status: Any - reason: Any - chunked: Any - chunk_left: Any - length: Any - will_close: Any - def __init__(self, sock, debuglevel: int = ..., strict: int = ..., method: Optional[Any] = ..., - buffering: bool = ...) -> None: ... - def begin(self): ... - def close(self): ... - def isclosed(self): ... - def read(self, amt: Optional[Any] = ...): ... - def fileno(self): ... - def getheader(self, name, default: Optional[Any] = ...): ... - def getheaders(self): ... - -# This is an API stub only for HTTPConnection and HTTPSConnection, as used in -# urllib2.AbstractHTTPHandler.do_open, which takes either the class -# HTTPConnection or the class HTTPSConnection, *not* an instance of either -# class. do_open does not use all of the parameters of HTTPConnection.__init__ -# or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the -# parameters that do_open does use. -class HTTPConnectionProtocol(Protocol): - def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ... - -class HTTPConnection: - response_class: Any - default_port: Any - auto_open: Any - debuglevel: Any - strict: Any - timeout: Any - source_address: Any - sock: Any - host: str = ... - port: int = ... - def __init__(self, host, port: Optional[Any] = ..., strict: Optional[Any] = ..., timeout=..., - source_address: Optional[Any] = ...) -> None: ... - def set_tunnel(self, host, port: Optional[Any] = ..., headers: Optional[Any] = ...): ... - def set_debuglevel(self, level): ... - def connect(self): ... - def close(self): ... - def send(self, data): ... - def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ... - def putheader(self, header, *values): ... - def endheaders(self, message_body: Optional[Any] = ...): ... - def request(self, method, url, body: Optional[Any] = ..., headers=...): ... - def getresponse(self, buffering: bool = ...): ... - -class HTTP: - debuglevel: Any - def __init__(self, host: str = ..., port: Optional[Any] = ..., strict: Optional[Any] = ...) -> None: ... - def connect(self, host: Optional[Any] = ..., port: Optional[Any] = ...): ... - def getfile(self): ... - file: Any - headers: Any - def getreply(self, buffering: bool = ...): ... - def close(self): ... - -class HTTPSConnection(HTTPConnection): - default_port: Any - key_file: Any - cert_file: Any - def __init__(self, host, port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., - strict: Optional[Any] = ..., timeout=..., source_address: Optional[Any] = ..., - context: Optional[Any] = ...) -> None: ... - sock: Any - def connect(self): ... - -class HTTPS(HTTP): - key_file: Any - cert_file: Any - def __init__(self, host: str = ..., port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., strict: Optional[Any] = ..., context: Optional[Any] = ...) -> None: ... - -class HTTPException(Exception): ... -class NotConnected(HTTPException): ... -class InvalidURL(HTTPException): ... - -class UnknownProtocol(HTTPException): - args: Any - version: Any - def __init__(self, version) -> None: ... - -class UnknownTransferEncoding(HTTPException): ... -class UnimplementedFileMode(HTTPException): ... - -class IncompleteRead(HTTPException): - args: Any - partial: Any - expected: Any - def __init__(self, partial, expected: Optional[Any] = ...) -> None: ... - -class ImproperConnectionState(HTTPException): ... -class CannotSendRequest(ImproperConnectionState): ... -class CannotSendHeader(ImproperConnectionState): ... -class ResponseNotReady(ImproperConnectionState): ... - -class BadStatusLine(HTTPException): - args: Any - line: Any - def __init__(self, line) -> None: ... - -class LineTooLong(HTTPException): - def __init__(self, line_type) -> None: ... - -error: Any - -class LineAndFileWrapper: - def __init__(self, line, file) -> None: ... - def __getattr__(self, attr): ... - def read(self, amt: Optional[Any] = ...): ... - def readline(self): ... - def readlines(self, size: Optional[Any] = ...): ... - -# Constants - -responses: Dict[int, str] - -HTTP_PORT: int -HTTPS_PORT: int - -# status codes -# informational -CONTINUE: int -SWITCHING_PROTOCOLS: int -PROCESSING: int - -# successful -OK: int -CREATED: int -ACCEPTED: int -NON_AUTHORITATIVE_INFORMATION: int -NO_CONTENT: int -RESET_CONTENT: int -PARTIAL_CONTENT: int -MULTI_STATUS: int -IM_USED: int - -# redirection -MULTIPLE_CHOICES: int -MOVED_PERMANENTLY: int -FOUND: int -SEE_OTHER: int -NOT_MODIFIED: int -USE_PROXY: int -TEMPORARY_REDIRECT: int - -# client error -BAD_REQUEST: int -UNAUTHORIZED: int -PAYMENT_REQUIRED: int -FORBIDDEN: int -NOT_FOUND: int -METHOD_NOT_ALLOWED: int -NOT_ACCEPTABLE: int -PROXY_AUTHENTICATION_REQUIRED: int -REQUEST_TIMEOUT: int -CONFLICT: int -GONE: int -LENGTH_REQUIRED: int -PRECONDITION_FAILED: int -REQUEST_ENTITY_TOO_LARGE: int -REQUEST_URI_TOO_LONG: int -UNSUPPORTED_MEDIA_TYPE: int -REQUESTED_RANGE_NOT_SATISFIABLE: int -EXPECTATION_FAILED: int -UNPROCESSABLE_ENTITY: int -LOCKED: int -FAILED_DEPENDENCY: int -UPGRADE_REQUIRED: int - -# server error -INTERNAL_SERVER_ERROR: int -NOT_IMPLEMENTED: int -BAD_GATEWAY: int -SERVICE_UNAVAILABLE: int -GATEWAY_TIMEOUT: int -HTTP_VERSION_NOT_SUPPORTED: int -INSUFFICIENT_STORAGE: int -NOT_EXTENDED: int diff --git a/mypy/typeshed/stdlib/python2/imp.pyi b/mypy/typeshed/stdlib/python2/imp.pyi deleted file mode 100644 index 8ff9e1aed52b..000000000000 --- a/mypy/typeshed/stdlib/python2/imp.pyi +++ /dev/null @@ -1,35 +0,0 @@ -"""Stubs for the 'imp' module.""" - -from typing import List, Optional, Tuple, Iterable, IO, Any -import types - -C_BUILTIN: int -C_EXTENSION: int -IMP_HOOK: int -PKG_DIRECTORY: int -PY_CODERESOURCE: int -PY_COMPILED: int -PY_FROZEN: int -PY_RESOURCE: int -PY_SOURCE: int -SEARCH_ERROR: int - -def acquire_lock() -> None: ... -def find_module(name: str, path: Iterable[str] = ...) -> Optional[Tuple[IO[Any], str, Tuple[str, str, int]]]: ... -def get_magic() -> str: ... -def get_suffixes() -> List[Tuple[str, str, int]]: ... -def init_builtin(name: str) -> types.ModuleType: ... -def init_frozen(name: str) -> types.ModuleType: ... -def is_builtin(name: str) -> int: ... -def is_frozen(name: str) -> bool: ... -def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... -def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def lock_held() -> bool: ... -def new_module(name: str) -> types.ModuleType: ... -def release_lock() -> None: ... - -class NullImporter: - def __init__(self, path_string: str) -> None: ... - def find_module(self, fullname: str, path: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/importlib.pyi b/mypy/typeshed/stdlib/python2/importlib.pyi deleted file mode 100644 index 8bb179a4bd9a..000000000000 --- a/mypy/typeshed/stdlib/python2/importlib.pyi +++ /dev/null @@ -1,4 +0,0 @@ -import types -from typing import Optional, Text - -def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/python2/inspect.pyi b/mypy/typeshed/stdlib/python2/inspect.pyi deleted file mode 100644 index 6f6fea49cae7..000000000000 --- a/mypy/typeshed/stdlib/python2/inspect.pyi +++ /dev/null @@ -1,129 +0,0 @@ -from types import CodeType, TracebackType, FrameType, FunctionType, MethodType, ModuleType -from typing import Any, Dict, Callable, List, NamedTuple, Optional, Sequence, Tuple, Type, Union, AnyStr - -# Types and members -class EndOfBlock(Exception): ... - -class BlockFinder: - indent: int - islambda: bool - started: bool - passline: bool - last: int - def tokeneater(self, type: int, token: AnyStr, srow_scol: Tuple[int, int], - erow_ecol: Tuple[int, int], line: AnyStr) -> None: ... - -CO_GENERATOR: int -CO_NESTED: int -CO_NEWLOCALS: int -CO_NOFREE: int -CO_OPTIMIZED: int -CO_VARARGS: int -CO_VARKEYWORDS: int -TPFLAGS_IS_ABSTRACT: int - -class ModuleInfo(NamedTuple): - name: str - suffix: str - mode: str - module_type: int - -def getmembers( - object: object, - predicate: Optional[Callable[[Any], bool]] = ... -) -> List[Tuple[str, Any]]: ... -def getmoduleinfo(path: Union[str, unicode]) -> Optional[ModuleInfo]: ... -def getmodulename(path: AnyStr) -> Optional[AnyStr]: ... - -def ismodule(object: object) -> bool: ... -def isclass(object: object) -> bool: ... -def ismethod(object: object) -> bool: ... -def isfunction(object: object) -> bool: ... -def isgeneratorfunction(object: object) -> bool: ... -def isgenerator(object: object) -> bool: ... -def istraceback(object: object) -> bool: ... -def isframe(object: object) -> bool: ... -def iscode(object: object) -> bool: ... -def isbuiltin(object: object) -> bool: ... -def isroutine(object: object) -> bool: ... -def isabstract(object: object) -> bool: ... -def ismethoddescriptor(object: object) -> bool: ... -def isdatadescriptor(object: object) -> bool: ... -def isgetsetdescriptor(object: object) -> bool: ... -def ismemberdescriptor(object: object) -> bool: ... - -# Retrieving source code -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] - -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... -def getabsfile(object: _SourceObjectType) -> str: ... -def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... -def getdoc(object: object) -> Optional[str]: ... -def getcomments(object: object) -> Optional[str]: ... -def getfile(object: _SourceObjectType) -> str: ... -def getmodule(object: object) -> Optional[ModuleType]: ... -def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... -def getsource(object: _SourceObjectType) -> str: ... -def cleandoc(doc: AnyStr) -> AnyStr: ... -def indentsize(line: Union[str, unicode]) -> int: ... - -# Classes and functions -def getclasstree(classes: List[type], unique: bool = ...) -> List[Union[Tuple[type, Tuple[type, ...]], List[Any]]]: ... - -class ArgSpec(NamedTuple): - args: List[str] - varargs: Optional[str] - keywords: Optional[str] - defaults: Tuple[Any, ...] - -class ArgInfo(NamedTuple): - args: List[str] - varargs: Optional[str] - keywords: Optional[str] - locals: Dict[str, Any] - -class Arguments(NamedTuple): - args: List[Union[str, List[Any]]] - varargs: Optional[str] - keywords: Optional[str] - -def getargs(co: CodeType) -> Arguments: ... -def getargspec(func: object) -> ArgSpec: ... -def getargvalues(frame: FrameType) -> ArgInfo: ... -def formatargspec(args, varargs=..., varkw=..., defaults=..., - formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., - join=...) -> str: ... -def formatargvalues(args, varargs=..., varkw=..., defaults=..., - formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., - join=...) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... - -# The interpreter stack - -class Traceback(NamedTuple): - filename: str - lineno: int - function: str - code_context: Optional[List[str]] - index: Optional[int] # type: ignore - -_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] - -def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... -def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... -def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... -def getlineno(frame: FrameType) -> int: ... - -def currentframe(depth: int = ...) -> FrameType: ... -def stack(context: int = ...) -> List[_FrameInfo]: ... -def trace(context: int = ...) -> List[_FrameInfo]: ... - -class Attribute(NamedTuple): - name: str - kind: str - defining_class: type - object: object - -def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/mypy/typeshed/stdlib/python2/io.pyi b/mypy/typeshed/stdlib/python2/io.pyi deleted file mode 100644 index e6cfb36b41f0..000000000000 --- a/mypy/typeshed/stdlib/python2/io.pyi +++ /dev/null @@ -1,42 +0,0 @@ -# Stubs for io - -# Based on https://docs.python.org/2/library/io.html - -# Only a subset of functionality is included. - -from typing import IO, Any, Union -import _io - -from _io import BlockingIOError as BlockingIOError -from _io import BufferedRWPair as BufferedRWPair -from _io import BufferedRandom as BufferedRandom -from _io import BufferedReader as BufferedReader -from _io import BufferedWriter as BufferedWriter -from _io import BytesIO as BytesIO -from _io import DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE -from _io import FileIO as FileIO -from _io import IncrementalNewlineDecoder as IncrementalNewlineDecoder -from _io import StringIO as StringIO -from _io import TextIOWrapper as TextIOWrapper -from _io import UnsupportedOperation as UnsupportedOperation -from _io import open as open - -def _OpenWrapper(file: Union[str, unicode, int], - mode: unicode = ..., buffering: int = ..., encoding: unicode = ..., - errors: unicode = ..., newline: unicode = ..., - closefd: bool = ...) -> IO[Any]: ... - -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int - - -class IOBase(_io._IOBase): ... - -class RawIOBase(_io._RawIOBase, IOBase): ... - -class BufferedIOBase(_io._BufferedIOBase, IOBase): ... - -# Note: In the actual io.py, TextIOBase subclasses IOBase. -# (Which we don't do here because we don't want to subclass both TextIO and BinaryIO.) -class TextIOBase(_io._TextIOBase): ... diff --git a/mypy/typeshed/stdlib/python2/itertools.pyi b/mypy/typeshed/stdlib/python2/itertools.pyi deleted file mode 100644 index 97e69f8027c1..000000000000 --- a/mypy/typeshed/stdlib/python2/itertools.pyi +++ /dev/null @@ -1,167 +0,0 @@ -# Stubs for itertools - -# Based on https://docs.python.org/2/library/itertools.html - -from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, - Union, Sequence, Generic, Optional) - -_T = TypeVar('_T') -_S = TypeVar('_S') - -def count(start: int = ..., - step: int = ...) -> Iterator[int]: ... # more general types? - -class cycle(Iterator[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T]) -> None: ... - def next(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - -def repeat(object: _T, times: int = ...) -> Iterator[_T]: ... - -class chain(Iterator[_T], Generic[_T]): - def __init__(self, *iterables: Iterable[_T]) -> None: ... - def next(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... - @staticmethod - def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... - -def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... -def dropwhile(predicate: Callable[[_T], Any], - iterable: Iterable[_T]) -> Iterator[_T]: ... -def ifilter(predicate: Optional[Callable[[_T], Any]], - iterable: Iterable[_T]) -> Iterator[_T]: ... -def ifilterfalse(predicate: Optional[Callable[[_T], Any]], - iterable: Iterable[_T]) -> Iterator[_T]: ... - -@overload -def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... -@overload -def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... - -@overload -def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... -@overload -def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], - step: Optional[int] = ...) -> Iterator[_T]: ... - -_T1 = TypeVar('_T1') -_T2 = TypeVar('_T2') -_T3 = TypeVar('_T3') -_T4 = TypeVar('_T4') -_T5 = TypeVar('_T5') -_T6 = TypeVar('_T6') - -@overload -def imap(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... -@overload -def imap(func: Callable[[_T1, _T2], _S], - iter1: Iterable[_T1], - iter2: Iterable[_T2]) -> Iterator[_S]: ... -@overload -def imap(func: Callable[[_T1, _T2, _T3], _S], - iter1: Iterable[_T1], iter2: Iterable[_T2], - iter3: Iterable[_T3]) -> Iterator[_S]: ... - -@overload -def imap(func: Callable[[_T1, _T2, _T3, _T4], _S], - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], - iter4: Iterable[_T4]) -> Iterator[_S]: ... - -@overload -def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], - iter4: Iterable[_T4], iter5: Iterable[_T5]) -> Iterator[_S]: ... - -@overload -def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5, _T6], _S], - iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], - iter4: Iterable[_T4], iter5: Iterable[_T5], - iter6: Iterable[_T6]) -> Iterator[_S]: ... - -@overload -def imap(func: Callable[..., _S], - iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], - iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], - iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[_S]: ... - -def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... -def takewhile(predicate: Callable[[_T], Any], - iterable: Iterable[_T]) -> Iterator[_T]: ... -def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... - -@overload -def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def izip(iter1: Iterable[_T1], - iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], - iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], - iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, - _T3, _T4]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], - iter3: Iterable[_T3], iter4: Iterable[_T4], - iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, - _T3, _T4, _T5]]: ... -@overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], - iter3: Iterable[_T3], iter4: Iterable[_T4], - iter5: Iterable[_T5], iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, - _T4, _T5, _T6]]: ... -@overload -def izip(iter1: Iterable[Any], iter2: Iterable[Any], - iter3: Iterable[Any], iter4: Iterable[Any], - iter5: Iterable[Any], iter6: Iterable[Any], - iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... - -def izip_longest(*p: Iterable[Any], - fillvalue: Any = ...) -> Iterator[Any]: ... - -@overload -def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def product(iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... -@overload -def product(iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - iter7: Iterable[Any], - *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... -@overload -def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... - -def permutations(iterable: Iterable[_T], - r: int = ...) -> Iterator[Sequence[_T]]: ... -def combinations(iterable: Iterable[_T], - r: int) -> Iterator[Sequence[_T]]: ... -def combinations_with_replacement(iterable: Iterable[_T], - r: int) -> Iterator[Sequence[_T]]: ... diff --git a/mypy/typeshed/stdlib/python2/json.pyi b/mypy/typeshed/stdlib/python2/json.pyi deleted file mode 100644 index 949e3daf7f23..000000000000 --- a/mypy/typeshed/stdlib/python2/json.pyi +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Text, Type -from _typeshed import SupportsRead - -class JSONDecodeError(ValueError): - def dumps(self, obj: Any) -> str: ... - def dump(self, obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... - def loads(self, s: str) -> Any: ... - def load(self, fp: IO[str]) -> Any: ... - -def dumps(obj: Any, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Optional[Type[JSONEncoder]] = ..., - indent: Optional[int] = ..., - separators: Optional[Tuple[str, str]] = ..., - encoding: str = ..., - default: Optional[Callable[[Any], Any]] = ..., - sort_keys: bool = ..., - **kwds: Any) -> str: ... - -def dump(obj: Any, - fp: Union[IO[str], IO[Text]], - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - cls: Optional[Type[JSONEncoder]] = ..., - indent: Optional[int] = ..., - separators: Optional[Tuple[str, str]] = ..., - encoding: str = ..., - default: Optional[Callable[[Any], Any]] = ..., - sort_keys: bool = ..., - **kwds: Any) -> None: ... - -def loads(s: Union[Text, bytes], - encoding: Any = ..., - cls: Optional[Type[JSONDecoder]] = ..., - object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., - **kwds: Any) -> Any: ... - -def load(fp: SupportsRead[Union[Text, bytes]], - encoding: Optional[str] = ..., - cls: Optional[Type[JSONDecoder]] = ..., - object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., - parse_float: Optional[Callable[[str], Any]] = ..., - parse_int: Optional[Callable[[str], Any]] = ..., - parse_constant: Optional[Callable[[str], Any]] = ..., - object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., - **kwds: Any) -> Any: ... - -class JSONDecoder(object): - def __init__(self, - encoding: Union[Text, bytes] = ..., - object_hook: Callable[..., Any] = ..., - parse_float: Callable[[str], float] = ..., - parse_int: Callable[[str], int] = ..., - parse_constant: Callable[[str], Any] = ..., - strict: bool = ..., - object_pairs_hook: Callable[..., Any] = ...) -> None: ... - def decode(self, s: Union[Text, bytes], _w: Any = ...) -> Any: ... - def raw_decode(self, s: Union[Text, bytes], idx: int = ...) -> Tuple[Any, Any]: ... - -class JSONEncoder(object): - item_separator: str - key_separator: str - skipkeys: bool - ensure_ascii: bool - check_circular: bool - allow_nan: bool - sort_keys: bool - indent: Optional[int] - - def __init__(self, - skipkeys: bool = ..., - ensure_ascii: bool = ..., - check_circular: bool = ..., - allow_nan: bool = ..., - sort_keys: bool = ..., - indent: Optional[int] = ..., - separators: Tuple[Union[Text, bytes], Union[Text, bytes]] = ..., - encoding: Union[Text, bytes] = ..., - default: Callable[..., Any] = ...) -> None: ... - - def default(self, o: Any) -> Any: ... - - def encode(self, o: Any) -> str: ... - - def iterencode(self, o: Any, _one_shot: bool = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/markupbase.pyi b/mypy/typeshed/stdlib/python2/markupbase.pyi deleted file mode 100644 index 358ba16c3487..000000000000 --- a/mypy/typeshed/stdlib/python2/markupbase.pyi +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Tuple - -class ParserBase(object): - 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/md5.pyi b/mypy/typeshed/stdlib/python2/md5.pyi deleted file mode 100644 index 96eabd146acd..000000000000 --- a/mypy/typeshed/stdlib/python2/md5.pyi +++ /dev/null @@ -1,6 +0,0 @@ -# Stubs for Python 2.7 md5 stdlib module - -from hashlib import md5 as md5, md5 as new - -blocksize: int -digest_size: int diff --git a/mypy/typeshed/stdlib/python2/mimetools.pyi b/mypy/typeshed/stdlib/python2/mimetools.pyi deleted file mode 100644 index f565202f4f80..000000000000 --- a/mypy/typeshed/stdlib/python2/mimetools.pyi +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any -import rfc822 - -class Message(rfc822.Message): - encodingheader: Any - typeheader: Any - def __init__(self, fp, seekable: int = ...): ... - plisttext: Any - type: Any - maintype: Any - subtype: Any - def parsetype(self): ... - plist: Any - def parseplist(self): ... - def getplist(self): ... - def getparam(self, name): ... - def getparamnames(self): ... - def getencoding(self): ... - def gettype(self): ... - def getmaintype(self): ... - def getsubtype(self): ... - -def choose_boundary(): ... -def decode(input, output, encoding): ... -def encode(input, output, encoding): ... -def copyliteral(input, output): ... -def copybinary(input, output): ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi deleted file mode 100644 index fb00b245c2e5..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/__init__.pyi +++ /dev/null @@ -1,50 +0,0 @@ -from typing import Any, Callable, Optional, TypeVar, Iterable - -from multiprocessing import pool -from multiprocessing.process import Process as Process, current_process as current_process, active_children as active_children -from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING -from Queue import Queue as _BaseQueue - -class ProcessError(Exception): ... -class BufferTooShort(ProcessError): ... -class TimeoutError(ProcessError): ... -class AuthenticationError(ProcessError): ... - -_T = TypeVar('_T') - -class Queue(_BaseQueue[_T]): - def __init__(self, maxsize: int = ...) -> None: ... - def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... - def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... - def qsize(self) -> int: ... - def empty(self) -> bool: ... - def full(self) -> bool: ... - def put_nowait(self, item: _T) -> None: ... - def get_nowait(self) -> _T: ... - def close(self) -> None: ... - def join_thread(self) -> None: ... - def cancel_join_thread(self) -> None: ... - -def Manager(): ... -def Pipe(duplex: bool = ...): ... -def cpu_count() -> int: ... -def freeze_support(): ... -def get_logger(): ... -def log_to_stderr(level: Optional[Any] = ...): ... -def allow_connection_pickling(): ... -def Lock(): ... -def RLock(): ... -def Condition(lock: Optional[Any] = ...): ... -def Semaphore(value: int = ...): ... -def BoundedSemaphore(value: int = ...): ... -def Event(): ... -def JoinableQueue(maxsize: int = ...): ... -def RawValue(typecode_or_type, *args): ... -def RawArray(typecode_or_type, size_or_initializer): ... -def Value(typecode_or_type, *args, **kwds): ... -def Array(typecode_or_type, size_or_initializer, **kwds): ... - -def Pool(processes: Optional[int] = ..., - initializer: Optional[Callable[..., Any]] = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi deleted file mode 100644 index ea41a4cf8ada..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/dummy/__init__.pyi +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any, Optional, List, Type - -import threading -import sys -import weakref -import array -import itertools - -from multiprocessing import TimeoutError, cpu_count -from multiprocessing.dummy.connection import Pipe -from threading import Lock, RLock, Semaphore, BoundedSemaphore -from threading import Event -from Queue import Queue - - -class DummyProcess(threading.Thread): - _children: weakref.WeakKeyDictionary[Any, Any] - _parent: threading.Thread - _pid: None - _start_called: bool - def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... - @property - def exitcode(self) -> Optional[int]: ... - - -Process = DummyProcess - -# This should be threading._Condition but threading.pyi exports it as Condition -class Condition(threading.Condition): - notify_all: Any - -class Namespace(object): - def __init__(self, **kwds) -> None: ... - -class Value(object): - _typecode: Any - _value: Any - value: Any - def __init__(self, typecode, value, lock=...) -> None: ... - def _get(self) -> Any: ... - def _set(self, value) -> None: ... - -JoinableQueue = Queue - -def Array(typecode, sequence, lock=...) -> array.array[Any]: ... -def Manager() -> Any: ... -def Pool(processes=..., initializer=..., initargs=...) -> Any: ... -def active_children() -> List[Any]: ... -def current_process() -> threading.Thread: ... -def freeze_support() -> None: ... -def shutdown() -> None: ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi deleted file mode 100644 index 663d39434cef..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/dummy/connection.pyi +++ /dev/null @@ -1,26 +0,0 @@ -from Queue import Queue -from typing import Any, List, Optional, Tuple, Type - -families: List[None] - -class Connection(object): - _in: Any - _out: Any - recv: Any - recv_bytes: Any - send: Any - send_bytes: Any - def __init__(self, _in, _out) -> None: ... - def close(self) -> None: ... - def poll(self, timeout=...) -> Any: ... - -class Listener(object): - _backlog_queue: Optional[Queue[Any]] - address: Any - def __init__(self, address=..., family=..., backlog=...) -> None: ... - def accept(self) -> Connection: ... - def close(self) -> None: ... - - -def Client(address) -> Connection: ... -def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi deleted file mode 100644 index 014efd452b7a..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/pool.pyi +++ /dev/null @@ -1,54 +0,0 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar - -_T = TypeVar('_T', bound=Pool) - -class AsyncResult(): - def get(self, timeout: Optional[float] = ...) -> Any: ... - def wait(self, timeout: Optional[float] = ...) -> None: ... - def ready(self) -> bool: ... - def successful(self) -> bool: ... - -class IMapIterator(Iterator[Any]): - def __iter__(self) -> Iterator[Any]: ... - def next(self, timeout: Optional[float] = ...) -> Any: ... - -class IMapUnorderedIterator(IMapIterator): ... - -class Pool(object): - def __init__(self, processes: Optional[int] = ..., - initializer: Optional[Callable[..., None]] = ..., - initargs: Iterable[Any] = ..., - maxtasksperchild: Optional[int] = ...) -> None: ... - def apply(self, - func: Callable[..., Any], - args: Iterable[Any] = ..., - kwds: Dict[str, Any] = ...) -> Any: ... - def apply_async(self, - func: Callable[..., Any], - args: Iterable[Any] = ..., - kwds: Dict[str, Any] = ..., - callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... - def map(self, - func: Callable[..., Any], - iterable: Iterable[Any] = ..., - chunksize: Optional[int] = ...) -> List[Any]: ... - def map_async(self, func: Callable[..., Any], - iterable: Iterable[Any] = ..., - chunksize: Optional[int] = ..., - callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... - def imap(self, - func: Callable[..., Any], - iterable: Iterable[Any] = ..., - chunksize: Optional[int] = ...) -> IMapIterator: ... - def imap_unordered(self, - func: Callable[..., Any], - iterable: Iterable[Any] = ..., - chunksize: Optional[int] = ...) -> IMapIterator: ... - def close(self) -> None: ... - def terminate(self) -> None: ... - def join(self) -> None: ... - -class ThreadPool(Pool): - def __init__(self, processes: Optional[int] = ..., - initializer: Optional[Callable[..., Any]] = ..., - initargs: Iterable[Any] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/process.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/process.pyi deleted file mode 100644 index 476b40324fd2..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/process.pyi +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Any, Optional - -def current_process(): ... -def active_children(): ... - -class Process: - def __init__(self, group: Optional[Any] = ..., target: Optional[Any] = ..., name: Optional[Any] = ..., args=..., - kwargs=...): ... - def run(self): ... - def start(self): ... - def terminate(self): ... - def join(self, timeout: Optional[Any] = ...): ... - def is_alive(self): ... - @property - def name(self): ... - @name.setter - def name(self, name): ... - @property - def daemon(self): ... - @daemon.setter - def daemon(self, daemonic): ... - @property - def authkey(self): ... - @authkey.setter - def authkey(self, authkey): ... - @property - def exitcode(self): ... - @property - def ident(self): ... - pid: Any - -class AuthenticationString(bytes): - def __reduce__(self): ... - -class _MainProcess(Process): - def __init__(self): ... diff --git a/mypy/typeshed/stdlib/python2/multiprocessing/util.pyi b/mypy/typeshed/stdlib/python2/multiprocessing/util.pyi deleted file mode 100644 index 14d44f6e3929..000000000000 --- a/mypy/typeshed/stdlib/python2/multiprocessing/util.pyi +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Any, Optional -import threading - -SUBDEBUG: Any -SUBWARNING: Any - -def sub_debug(msg, *args): ... -def debug(msg, *args): ... -def info(msg, *args): ... -def sub_warning(msg, *args): ... -def get_logger(): ... -def log_to_stderr(level: Optional[Any] = ...): ... -def get_temp_dir(): ... -def register_after_fork(obj, func): ... - -class Finalize: - def __init__(self, obj, callback, args=..., kwargs: Optional[Any] = ..., exitpriority: Optional[Any] = ...): ... - def __call__(self, wr: Optional[Any] = ...): ... - def cancel(self): ... - def still_active(self): ... - -def is_exiting(): ... - -class ForkAwareThreadLock: - def __init__(self): ... - -class ForkAwareLocal(threading.local): - def __init__(self): ... - def __reduce__(self): ... diff --git a/mypy/typeshed/stdlib/python2/mutex.pyi b/mypy/typeshed/stdlib/python2/mutex.pyi deleted file mode 100644 index fa41bbb4fcec..000000000000 --- a/mypy/typeshed/stdlib/python2/mutex.pyi +++ /dev/null @@ -1,14 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/mutex.py - -from typing import Any, Callable, Deque, TypeVar - -_ArgType = TypeVar('_ArgType') - -class mutex: - locked: bool - queue: Deque[Any] - def __init__(self) -> None: ... - def test(self) -> bool: ... - def testandset(self) -> bool: ... - def lock(self, function: Callable[[_ArgType], Any], argument: _ArgType) -> None: ... - def unlock(self) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/nturl2path.pyi b/mypy/typeshed/stdlib/python2/nturl2path.pyi deleted file mode 100644 index b87b008e4cec..000000000000 --- a/mypy/typeshed/stdlib/python2/nturl2path.pyi +++ /dev/null @@ -1,4 +0,0 @@ -from typing import AnyStr - -def url2pathname(url: AnyStr) -> AnyStr: ... -def pathname2url(p: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/os/__init__.pyi b/mypy/typeshed/stdlib/python2/os/__init__.pyi deleted file mode 100644 index 7de81929d4fb..000000000000 --- a/mypy/typeshed/stdlib/python2/os/__init__.pyi +++ /dev/null @@ -1,357 +0,0 @@ -from builtins import OSError as error -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 -import sys -from typing import ( - Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr, - Optional, Generic, Set, Callable, Text, Sequence, IO, NamedTuple, NoReturn, TypeVar -) -from _typeshed import AnyPath -from . import path as path - -# We need to use something from path, or flake8 and pytype get unhappy -_supports_unicode_filenames = path.supports_unicode_filenames - -_T = TypeVar("_T") - -# ----- os variables ----- - -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 - -O_RDONLY: int -O_WRONLY: int -O_RDWR: int -O_APPEND: int -O_CREAT: int -O_EXCL: int -O_TRUNC: int -# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, -# including tests for mypy, use a more finer way than sys.platform before using these APIs -# See https://github.com/python/typeshed/pull/2286 for discussions -O_DSYNC: int # Unix only -O_RSYNC: int # Unix only -O_SYNC: int # Unix only -O_NDELAY: int # Unix only -O_NONBLOCK: int # Unix only -O_NOCTTY: int # Unix only -O_SHLOCK: int # Unix only -O_EXLOCK: int # Unix only -O_BINARY: int # Windows only -O_NOINHERIT: int # Windows only -O_SHORT_LIVED: int # Windows only -O_TEMPORARY: int # Windows only -O_RANDOM: int # Windows only -O_SEQUENTIAL: int # Windows only -O_TEXT: int # Windows only -O_ASYNC: int # Gnu extension if in C library -O_DIRECT: int # Gnu extension if in C library -O_DIRECTORY: int # Gnu extension if in C library -O_NOFOLLOW: int # Gnu extension if in C library -O_NOATIME: int # Gnu extension if in C library -O_LARGEFILE: int # Gnu extension if in C library - -curdir: str -pardir: str -sep: str -if sys.platform == 'win32': - altsep: str -else: - altsep: Optional[str] -extsep: str -pathsep: str -defpath: str -linesep: str -devnull: str -name: str - -F_OK: int -R_OK: int -W_OK: int -X_OK: int - -class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): - def copy(self) -> Dict[AnyStr, AnyStr]: ... - def __delitem__(self, key: AnyStr) -> None: ... - def __getitem__(self, key: AnyStr) -> AnyStr: ... - def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... - def __iter__(self) -> Iterator[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] - pathconf_names: Dict[str, int] - sysconf_names: Dict[str, int] - - EX_OK: int - EX_USAGE: int - EX_DATAERR: int - EX_NOINPUT: int - EX_NOUSER: int - EX_NOHOST: int - EX_UNAVAILABLE: int - EX_SOFTWARE: int - EX_OSERR: int - EX_OSFILE: int - EX_CANTCREAT: int - EX_IOERR: int - EX_TEMPFAIL: int - EX_PROTOCOL: int - EX_NOPERM: int - EX_CONFIG: int - EX_NOTFOUND: int - -P_NOWAIT: int -P_NOWAITO: int -P_WAIT: int -if sys.platform == 'win32': - P_DETACH: int - P_OVERLAY: int - -# wait()/waitpid() options -if sys.platform != 'win32': - WNOHANG: int # Unix only - WCONTINUED: int # some Unix systems - WUNTRACED: int # Unix only - -TMP_MAX: int # Undocumented, but used by tempfile - -# ----- os classes (structures) ----- -if sys.version_info >= (3, 6): - from builtins import _PathLike as PathLike # See comment in builtins - -class _StatVFS(NamedTuple): - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int - -def getlogin() -> str: ... -def getpid() -> int: ... -def getppid() -> int: ... -def strerror(code: int) -> str: ... -def umask(mask: int) -> int: ... - -if sys.platform != 'win32': - def ctermid() -> str: ... - def getegid() -> int: ... - def geteuid() -> int: ... - def getgid() -> int: ... - def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac - def initgroups(username: str, gid: int) -> None: ... - def getpgid(pid: int) -> int: ... - def getpgrp() -> int: ... - def getresuid() -> Tuple[int, int, int]: ... - def getresgid() -> Tuple[int, int, int]: ... - def getuid() -> int: ... - def setegid(egid: int) -> None: ... - def seteuid(euid: int) -> None: ... - def setgid(gid: int) -> None: ... - def setgroups(groups: Sequence[int]) -> None: ... - def setpgrp() -> None: ... - def setpgid(pid: int, pgrp: int) -> None: ... - def setregid(rgid: int, egid: int) -> None: ... - def setresgid(rgid: int, egid: int, sgid: int) -> None: ... - def setresuid(ruid: int, euid: int, suid: int) -> None: ... - def setreuid(ruid: int, euid: int) -> None: ... - def getsid(pid: int) -> int: ... - def setsid() -> None: ... - def setuid(uid: int) -> None: ... - def uname() -> Tuple[str, str, str, str, str]: ... - -@overload -def getenv(key: Text) -> Optional[str]: ... -@overload -def getenv(key: Text, default: _T) -> Union[str, _T]: ... -def putenv(key: Union[bytes, Text], value: Union[bytes, Text]) -> None: ... -def unsetenv(key: Union[bytes, Text]) -> None: ... - -def fdopen(fd: int, *args, **kwargs) -> IO[Any]: ... -def close(fd: int) -> None: ... -def closerange(fd_low: int, fd_high: int) -> None: ... -def dup(fd: int) -> int: ... -def dup2(fd: int, fd2: int) -> None: ... -def fstat(fd: int) -> Any: ... -def fsync(fd: int) -> None: ... -def lseek(fd: int, pos: int, how: int) -> int: ... -def open(file: AnyPath, 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 fchdir(fd: int) -> 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 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 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: ... -@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: ... -# 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: ... - -if sys.platform != 'win32': - # Unix only - def fchmod(fd: int, mode: int) -> None: ... - def fchown(fd: int, uid: int, gid: int) -> None: ... - if sys.platform != 'darwin': - def fdatasync(fd: int) -> None: ... # Unix only, not Mac - def fpathconf(fd: int, name: Union[str, int]) -> int: ... - def fstatvfs(fd: int) -> _StatVFS: ... - def ftruncate(fd: int, length: int) -> None: ... - def isatty(fd: int) -> bool: ... - def openpty() -> Tuple[int, int]: ... # some flavors of Unix - 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 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: ... - -# 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: ... - -# 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 _exit(n: int) -> NoReturn: ... -def kill(pid: int, sig: int) -> None: ... - -if sys.platform != 'win32': - # Unix only - def fork() -> int: ... - def forkpty() -> Tuple[int, int]: ... # some flavors of Unix - def killpg(__pgid: int, __signal: int) -> None: ... - 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 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: ... -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 wait() -> Tuple[int, int]: ... - def wait3(options: int) -> Tuple[int, int, Any]: ... - def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... - def WCOREDUMP(status: int) -> bool: ... - def WIFCONTINUED(status: int) -> bool: ... - def WIFSTOPPED(status: int) -> bool: ... - def WIFSIGNALED(status: int) -> bool: ... - def WIFEXITED(status: int) -> bool: ... - def WEXITSTATUS(status: int) -> int: ... - def WSTOPSIG(status: int) -> int: ... - def WTERMSIG(status: int) -> int: ... - def confstr(name: Union[str, int]) -> Optional[str]: ... - 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: ... - -P_ALL: int -WEXITED: int -WNOWAIT: int diff --git a/mypy/typeshed/stdlib/python2/os/path.pyi b/mypy/typeshed/stdlib/python2/os/path.pyi deleted file mode 100644 index ef4b48331d89..000000000000 --- a/mypy/typeshed/stdlib/python2/os/path.pyi +++ /dev/null @@ -1,164 +0,0 @@ -# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! -import os -import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional -from genericpath import exists as exists -from _typeshed import StrPath, BytesPath, AnyPath - -_T = TypeVar('_T') - -if sys.version_info >= (3, 6): - from builtins import _PathLike - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == 'win32': - altsep: str -else: - altsep: Optional[str] -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -if sys.version_info >= (3, 6): - # Overloads are necessary to work around python/mypy#3644. - @overload - def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def abspath(path: AnyStr) -> AnyStr: ... - @overload - def basename(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(p: AnyStr) -> AnyStr: ... - @overload - def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(p: AnyStr) -> AnyStr: ... - @overload - def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expanduser(path: AnyStr) -> AnyStr: ... - @overload - def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expandvars(path: AnyStr) -> AnyStr: ... - @overload - def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(s: AnyStr) -> AnyStr: ... - @overload - def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - @overload - def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - else: - @overload - def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(filename: AnyStr) -> AnyStr: ... - -else: - def abspath(path: AnyStr) -> AnyStr: ... - def basename(p: AnyStr) -> AnyStr: ... - def dirname(p: AnyStr) -> AnyStr: ... - def expanduser(path: AnyStr) -> AnyStr: ... - def expandvars(path: AnyStr) -> AnyStr: ... - def normcase(s: AnyStr) -> AnyStr: ... - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - def realpath(path: AnyStr) -> AnyStr: ... - else: - def realpath(filename: AnyStr) -> AnyStr: ... - -if sys.version_info >= (3, 6): - # In reality it returns str for sequences of StrPath and bytes for sequences - # of BytesPath, but mypy does not accept such a signature. - def commonpath(paths: Sequence[AnyPath]) -> Any: ... -elif sys.version_info >= (3, 5): - def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... - -# 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: ... - -# 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: ... - -if sys.version_info < (3, 0): - # 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: ... -elif sys.version_info >= (3, 6): - @overload - def join(a: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(a: BytesPath, *paths: BytesPath) -> bytes: ... -else: - def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... - -@overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... -@overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... - -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: ... - -if sys.version_info >= (3, 6): - @overload - def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -else: - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.version_info < (3, 7) and sys.platform == 'win32': - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -if sys.version_info < (3,): - def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/os2emxpath.pyi b/mypy/typeshed/stdlib/python2/os2emxpath.pyi deleted file mode 100644 index ef4b48331d89..000000000000 --- a/mypy/typeshed/stdlib/python2/os2emxpath.pyi +++ /dev/null @@ -1,164 +0,0 @@ -# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! -import os -import sys -from typing import overload, List, Any, AnyStr, Sequence, Tuple, TypeVar, Text, Callable, Optional -from genericpath import exists as exists -from _typeshed import StrPath, BytesPath, AnyPath - -_T = TypeVar('_T') - -if sys.version_info >= (3, 6): - from builtins import _PathLike - -# ----- os.path variables ----- -supports_unicode_filenames: bool -# aliases (also in os) -curdir: str -pardir: str -sep: str -if sys.platform == 'win32': - altsep: str -else: - altsep: Optional[str] -extsep: str -pathsep: str -defpath: str -devnull: str - -# ----- os.path function stubs ----- -if sys.version_info >= (3, 6): - # Overloads are necessary to work around python/mypy#3644. - @overload - def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def abspath(path: AnyStr) -> AnyStr: ... - @overload - def basename(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def basename(p: AnyStr) -> AnyStr: ... - @overload - def dirname(p: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def dirname(p: AnyStr) -> AnyStr: ... - @overload - def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expanduser(path: AnyStr) -> AnyStr: ... - @overload - def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def expandvars(path: AnyStr) -> AnyStr: ... - @overload - def normcase(s: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normcase(s: AnyStr) -> AnyStr: ... - @overload - def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - @overload - def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(path: AnyStr) -> AnyStr: ... - else: - @overload - def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... - @overload - def realpath(filename: AnyStr) -> AnyStr: ... - -else: - def abspath(path: AnyStr) -> AnyStr: ... - def basename(p: AnyStr) -> AnyStr: ... - def dirname(p: AnyStr) -> AnyStr: ... - def expanduser(path: AnyStr) -> AnyStr: ... - def expandvars(path: AnyStr) -> AnyStr: ... - def normcase(s: AnyStr) -> AnyStr: ... - def normpath(path: AnyStr) -> AnyStr: ... - if sys.platform == 'win32': - def realpath(path: AnyStr) -> AnyStr: ... - else: - def realpath(filename: AnyStr) -> AnyStr: ... - -if sys.version_info >= (3, 6): - # In reality it returns str for sequences of StrPath and bytes for sequences - # of BytesPath, but mypy does not accept such a signature. - def commonpath(paths: Sequence[AnyPath]) -> Any: ... -elif sys.version_info >= (3, 5): - def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... - -# 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: ... - -# 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: ... - -if sys.version_info < (3, 0): - # 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: ... -elif sys.version_info >= (3, 6): - @overload - def join(a: StrPath, *paths: StrPath) -> Text: ... - @overload - def join(a: BytesPath, *paths: BytesPath) -> bytes: ... -else: - def join(a: AnyStr, *paths: AnyStr) -> AnyStr: ... - -@overload -def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... -@overload -def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... - -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: ... - -if sys.version_info >= (3, 6): - @overload - def split(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... - @overload - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -else: - def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... - -if sys.version_info < (3, 7) and sys.platform == 'win32': - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated - -if sys.version_info < (3,): - def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/pipes.pyi b/mypy/typeshed/stdlib/python2/pipes.pyi deleted file mode 100644 index e25ef3ad945f..000000000000 --- a/mypy/typeshed/stdlib/python2/pipes.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any, IO, AnyStr - -class Template: - def __init__(self) -> None: ... - def reset(self) -> None: ... - def clone(self) -> Template: ... - def debug(self, flag: bool) -> None: ... - def append(self, cmd: str, kind: str) -> None: ... - def prepend(self, cmd: str, kind: str) -> None: ... - def open(self, file: str, mode: str) -> IO[Any]: ... - def copy(self, infile: str, outfile: str) -> None: ... - -def quote(s: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/platform.pyi b/mypy/typeshed/stdlib/python2/platform.pyi deleted file mode 100644 index e6e037804ae2..000000000000 --- a/mypy/typeshed/stdlib/python2/platform.pyi +++ /dev/null @@ -1,45 +0,0 @@ -# Stubs for platform (Python 2) -# -# Based on stub generated by stubgen. - -from typing import Any, Optional, Tuple - -__copyright__: Any -DEV_NULL: Any - -def libc_ver(executable=..., lib=..., version=..., chunksize: int = ...): ... -def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name: int = ...): ... -def dist(distname=..., version=..., id=..., supported_dists=...): ... - -class _popen: - tmpfile: Any - pipe: Any - bufsize: Any - mode: Any - def __init__(self, cmd, mode=..., bufsize: Optional[Any] = ...): ... - def read(self): ... - def readlines(self): ... - def close(self, remove=..., error=...): ... - __del__: Any - -def popen(cmd, mode=..., bufsize: Optional[Any] = ...): ... -def win32_ver(release=..., version=..., csd=..., ptype=...): ... -def mac_ver(release=..., versioninfo=..., machine=...): ... -def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ... -def system_alias(system, release, version): ... -def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... -def uname() -> Tuple[str, str, str, str, str, str]: ... -def system() -> str: ... -def node() -> str: ... -def release() -> str: ... -def version() -> str: ... -def machine() -> str: ... -def processor() -> str: ... -def python_implementation() -> str: ... -def python_version() -> str: ... -def python_version_tuple() -> Tuple[str, str, str]: ... -def python_branch() -> str: ... -def python_revision() -> str: ... -def python_build() -> Tuple[str, str]: ... -def python_compiler() -> str: ... -def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/popen2.pyi b/mypy/typeshed/stdlib/python2/popen2.pyi deleted file mode 100644 index b39ba5f074b0..000000000000 --- a/mypy/typeshed/stdlib/python2/popen2.pyi +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Any, Iterable, List, Optional, Union, TextIO, Tuple, TypeVar - -_T = TypeVar('_T') - - -class Popen3: - sts: int - cmd: Iterable[Any] - pid: int - tochild: TextIO - fromchild: TextIO - childerr: Optional[TextIO] - def __init__(self, cmd: Iterable[Any] = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... - def __del__(self) -> None: ... - def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ... - def wait(self) -> int: ... - -class Popen4(Popen3): - childerr: None - cmd: Iterable[Any] - pid: int - tochild: TextIO - fromchild: TextIO - def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... - -def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... -def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... -def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/mypy/typeshed/stdlib/python2/posix.pyi b/mypy/typeshed/stdlib/python2/posix.pyi deleted file mode 100644 index e85a2a55f4c9..000000000000 --- a/mypy/typeshed/stdlib/python2/posix.pyi +++ /dev/null @@ -1,198 +0,0 @@ -from typing import AnyStr, Dict, IO, List, Mapping, NamedTuple, Optional, Sequence, Tuple, TypeVar, Union - -error = OSError - -confstr_names: Dict[str, int] -environ: Dict[str, str] -pathconf_names: Dict[str, int] -sysconf_names: Dict[str, int] - -_T = TypeVar("_T") - -EX_CANTCREAT: int -EX_CONFIG: int -EX_DATAERR: int -EX_IOERR: int -EX_NOHOST: int -EX_NOINPUT: int -EX_NOPERM: int -EX_NOUSER: int -EX_OK: int -EX_OSERR: int -EX_OSFILE: int -EX_PROTOCOL: int -EX_SOFTWARE: int -EX_TEMPFAIL: int -EX_UNAVAILABLE: int -EX_USAGE: int -F_OK: int -NGROUPS_MAX: int -O_APPEND: int -O_ASYNC: int -O_CREAT: int -O_DIRECT: int -O_DIRECTORY: int -O_DSYNC: int -O_EXCL: int -O_LARGEFILE: int -O_NDELAY: int -O_NOATIME: int -O_NOCTTY: int -O_NOFOLLOW: int -O_NONBLOCK: int -O_RDONLY: int -O_RDWR: int -O_RSYNC: int -O_SYNC: int -O_TRUNC: int -O_WRONLY: int -R_OK: int -TMP_MAX: int -WCONTINUED: int -WNOHANG: int -WUNTRACED: int -W_OK: int -X_OK: int - -def WCOREDUMP(status: int) -> bool: ... -def WEXITSTATUS(status: int) -> bool: ... -def WIFCONTINUED(status: int) -> bool: ... -def WIFEXITED(status: int) -> bool: ... -def WIFSIGNALED(status: int) -> bool: ... -def WIFSTOPPED(status: int) -> bool: ... -def WSTOPSIG(status: int) -> bool: ... -def WTERMSIG(status: int) -> bool: ... - -class stat_result(object): - n_fields: int - n_sequence_fields: int - n_unnamed_fields: int - st_mode: int - st_ino: int - st_dev: int - st_nlink: int - st_uid: int - st_gid: int - st_size: int - st_atime: int - st_mtime: int - st_ctime: int - -class statvfs_result(NamedTuple): - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int - -def _exit(status: int) -> None: ... -def abort() -> None: ... -def access(path: unicode, mode: int) -> bool: ... -def chdir(path: unicode) -> None: ... -def chmod(path: unicode, mode: int) -> None: ... -def chown(path: unicode, uid: int, gid: int) -> None: ... -def chroot(path: unicode) -> None: ... -def close(fd: int) -> None: ... -def closerange(fd_low: int, fd_high: int) -> None: ... -def confstr(name: Union[str, int]) -> str: ... -def ctermid() -> str: ... -def dup(fd: int) -> int: ... -def dup2(fd: int, fd2: int) -> None: ... -def execv(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... -def execve(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... -def fchdir(fd: int) -> None: ... -def fchmod(fd: int, mode: int) -> None: ... -def fchown(fd: int, uid: int, gid: int) -> None: ... -def fdatasync(fd: int) -> None: ... -def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... -def fork() -> int: ... -def forkpty() -> Tuple[int, int]: ... -def fpathconf(fd: int, name: str) -> None: ... -def fstat(fd: int) -> stat_result: ... -def fstatvfs(fd: int) -> statvfs_result: ... -def fsync(fd: int) -> None: ... -def ftruncate(fd: int, length: int) -> None: ... -def getcwd() -> str: ... -def getcwdu() -> unicode: ... -def getegid() -> int: ... -def geteuid() -> int: ... -def getgid() -> int: ... -def getgroups() -> List[int]: ... -def getloadavg() -> Tuple[float, float, float]: ... -def getlogin() -> str: ... -def getpgid(pid: int) -> int: ... -def getpgrp() -> int: ... -def getpid() -> int: ... -def getppid() -> int: ... -def getresgid() -> Tuple[int, int, int]: ... -def getresuid() -> Tuple[int, int, int]: ... -def getsid(pid: int) -> int: ... -def getuid() -> int: ... -def initgroups(username: str, gid: int) -> None: ... -def isatty(fd: int) -> bool: ... -def kill(pid: int, sig: int) -> None: ... -def killpg(pgid: int, sig: int) -> None: ... -def lchown(path: unicode, uid: int, gid: int) -> None: ... -def link(source: unicode, link_name: str) -> None: ... -def listdir(path: AnyStr) -> List[AnyStr]: ... -def lseek(fd: int, pos: int, how: int) -> None: ... -def lstat(path: unicode) -> stat_result: ... -def major(device: int) -> int: ... -def makedev(major: int, minor: int) -> int: ... -def minor(device: int) -> int: ... -def mkdir(path: unicode, mode: int = ...) -> None: ... -def mkfifo(path: unicode, mode: int = ...) -> None: ... -def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... -def nice(increment: int) -> int: ... -def open(file: unicode, flags: int, mode: int = ...) -> int: ... -def openpty() -> Tuple[int, int]: ... -def pathconf(path: unicode, name: str) -> str: ... -def pipe() -> Tuple[int, int]: ... -def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... -def putenv(varname: str, value: str) -> None: ... -def read(fd: int, n: int) -> str: ... -def readlink(path: _T) -> _T: ... -def remove(path: unicode) -> None: ... -def rename(src: unicode, dst: unicode) -> None: ... -def rmdir(path: unicode) -> None: ... -def setegid(egid: int) -> None: ... -def seteuid(euid: int) -> None: ... -def setgid(gid: int) -> None: ... -def setgroups(groups: Sequence[int]) -> None: ... -def setpgid(pid: int, pgrp: int) -> None: ... -def setpgrp() -> None: ... -def setregid(rgid: int, egid: int) -> None: ... -def setresgid(rgid: int, egid: int, sgid: int) -> None: ... -def setresuid(ruid: int, euid: int, suid: int) -> None: ... -def setreuid(ruid: int, euid: int) -> None: ... -def setsid() -> None: ... -def setuid(pid: int) -> None: ... -def stat(path: unicode) -> stat_result: ... -def statvfs(path: unicode) -> statvfs_result: ... -def stat_float_times(fd: int) -> None: ... -def strerror(code: int) -> str: ... -def symlink(source: unicode, link_name: unicode) -> None: ... -def sysconf(name: Union[str, int]) -> int: ... -def system(command: unicode) -> int: ... -def tcgetpgrp(fd: int) -> int: ... -def tcsetpgrp(fd: int, pg: int) -> None: ... -def times() -> Tuple[float, float, float, float, float]: ... -def tmpfile() -> IO[str]: ... -def ttyname(fd: int) -> str: ... -def umask(mask: int) -> int: ... -def uname() -> Tuple[str, str, str, str, str]: ... -def unlink(path: unicode) -> None: ... -def unsetenv(varname: str) -> None: ... -def urandom(n: int) -> str: ... -def utime(path: unicode, times: Optional[Tuple[int, int]]) -> None: ... -def wait() -> int: ... -_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] -def wait3(options: int) -> Tuple[int, int, _r]: ... -def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... -def waitpid(pid: int, options: int) -> int: ... -def write(fd: int, str: str) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/random.pyi b/mypy/typeshed/stdlib/python2/random.pyi deleted file mode 100644 index 65d323db1d35..000000000000 --- a/mypy/typeshed/stdlib/python2/random.pyi +++ /dev/null @@ -1,77 +0,0 @@ -# Stubs for random -# Ron Murawski -# Updated by Jukka Lehtosalo - -# based on https://docs.python.org/2/library/random.html - -# ----- random classes ----- - -import _random -from typing import AbstractSet, Any, Callable, Iterator, List, Protocol, Sequence, TypeVar, Union, overload - -_T = TypeVar("_T") -_T_co = TypeVar('_T_co', covariant=True) - -class _Sampleable(Protocol[_T_co]): - def __iter__(self) -> Iterator[_T_co]: ... - def __len__(self) -> int: ... - -class Random(_random.Random): - def __init__(self, x: object = ...) -> None: ... - def seed(self, x: object = ...) -> None: ... - def getstate(self) -> _random._State: ... - def setstate(self, state: _random._State) -> None: ... - def jumpahead(self, n: int) -> None: ... - def getrandbits(self, k: int) -> int: ... - @overload - def randrange(self, stop: int) -> int: ... - @overload - def randrange(self, start: int, stop: int, step: int = ...) -> int: ... - def randint(self, a: int, b: int) -> int: ... - def choice(self, seq: Sequence[_T]) -> _T: ... - def shuffle(self, x: List[Any], random: Callable[[], None] = ...) -> None: ... - def sample(self, population: _Sampleable[_T], k: int) -> List[_T]: ... - def random(self) -> float: ... - def uniform(self, a: float, b: float) -> float: ... - def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... - def betavariate(self, alpha: float, beta: float) -> float: ... - def expovariate(self, lambd: float) -> float: ... - def gammavariate(self, alpha: float, beta: float) -> float: ... - def gauss(self, mu: float, sigma: float) -> float: ... - def lognormvariate(self, mu: float, sigma: float) -> float: ... - def normalvariate(self, mu: float, sigma: float) -> float: ... - def vonmisesvariate(self, mu: float, kappa: float) -> float: ... - def paretovariate(self, alpha: float) -> float: ... - def weibullvariate(self, alpha: float, beta: float) -> float: ... - -# SystemRandom is not implemented for all OS's; good on Windows & Linux -class SystemRandom(Random): - ... - -# ----- random function stubs ----- -def seed(x: object = ...) -> None: ... -def getstate() -> object: ... -def setstate(state: object) -> None: ... -def jumpahead(n: int) -> None: ... -def getrandbits(k: int) -> int: ... -@overload -def randrange(stop: int) -> int: ... -@overload -def randrange(start: int, stop: int, step: int = ...) -> int: ... -def randint(a: int, b: int) -> int: ... -def choice(seq: Sequence[_T]) -> _T: ... -def shuffle(x: List[Any], random: Callable[[], float] = ...) -> None: ... -def sample(population: _Sampleable[_T], k: int) -> List[_T]: ... -def random() -> float: ... -def uniform(a: float, b: float) -> float: ... -def triangular(low: float = ..., high: float = ..., - mode: float = ...) -> float: ... -def betavariate(alpha: float, beta: float) -> float: ... -def expovariate(lambd: float) -> float: ... -def gammavariate(alpha: float, beta: float) -> float: ... -def gauss(mu: float, sigma: float) -> float: ... -def lognormvariate(mu: float, sigma: float) -> float: ... -def normalvariate(mu: float, sigma: float) -> float: ... -def vonmisesvariate(mu: float, kappa: float) -> float: ... -def paretovariate(alpha: float) -> float: ... -def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/mypy/typeshed/stdlib/python2/re.pyi b/mypy/typeshed/stdlib/python2/re.pyi deleted file mode 100644 index 71486692f9fd..000000000000 --- a/mypy/typeshed/stdlib/python2/re.pyi +++ /dev/null @@ -1,100 +0,0 @@ -# Stubs for re -# Ron Murawski -# 'bytes' support added by Jukka Lehtosalo - -# based on: http: //docs.python.org/2.7/library/re.html - -from typing import ( - List, Iterator, overload, Callable, Tuple, Sequence, Dict, - Generic, AnyStr, Match, Pattern, Any, Optional, Union -) - -# ----- re variables and constants ----- -DEBUG: int -I: int -IGNORECASE: int -L: int -LOCALE: int -M: int -MULTILINE: int -S: int -DOTALL: int -X: int -VERBOSE: int -U: int -UNICODE: int -T: int -TEMPLATE: int - -class error(Exception): ... - -@overload -def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ... -@overload -def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... - -@overload -def search(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... -@overload -def search(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... - -@overload -def match(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... -@overload -def match(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... - -@overload -def split(pattern: Union[str, unicode], string: AnyStr, - maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... -@overload -def split(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, - maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... - -@overload -def findall(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... -@overload -def findall(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> List[Any]: ... - -# Return an iterator yielding match objects over all non-overlapping matches -# for the RE pattern in string. The string is scanned left-to-right, and -# matches are returned in the order found. Empty matches are included in the -# result unless they touch the beginning of another match. -@overload -def finditer(pattern: Union[str, unicode], string: AnyStr, - flags: int = ...) -> Iterator[Match[AnyStr]]: ... -@overload -def finditer(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, - flags: int = ...) -> Iterator[Match[AnyStr]]: ... - -@overload -def sub(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., - flags: int = ...) -> AnyStr: ... -@overload -def sub(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... -@overload -def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., - flags: int = ...) -> AnyStr: ... -@overload -def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... - -@overload -def subn(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., - flags: int = ...) -> Tuple[AnyStr, int]: ... -@overload -def subn(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., - flags: int = ...) -> Tuple[AnyStr, int]: ... -@overload -def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., - flags: int = ...) -> Tuple[AnyStr, int]: ... -@overload -def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., - flags: int = ...) -> Tuple[AnyStr, int]: ... - -def escape(string: AnyStr) -> AnyStr: ... - -def purge() -> None: ... -def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/python2/repr.pyi b/mypy/typeshed/stdlib/python2/repr.pyi deleted file mode 100644 index a24e59bc9fec..000000000000 --- a/mypy/typeshed/stdlib/python2/repr.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any, List - -class Repr: - maxarray: int - maxdeque: int - maxdict: int - maxfrozenset: int - maxlevel: int - maxlist: int - maxlong: int - maxother: int - maxset: int - maxstring: int - maxtuple: int - def __init__(self) -> None: ... - def _repr_iterable(self, x, level: complex, left, right, maxiter, trail=...) -> str: ... - def repr(self, x) -> str: ... - def repr1(self, x, level: complex) -> str: ... - def repr_array(self, x, level: complex) -> str: ... - def repr_deque(self, x, level: complex) -> str: ... - def repr_dict(self, x, level: complex) -> str: ... - def repr_frozenset(self, x, level: complex) -> str: ... - def repr_instance(self, x, level: complex) -> str: ... - def repr_list(self, x, level: complex) -> str: ... - def repr_long(self, x, level: complex) -> str: ... - def repr_set(self, x, level: complex) -> str: ... - def repr_str(self, x, level: complex) -> str: ... - def repr_tuple(self, x, level: complex) -> str: ... - -def _possibly_sorted(x) -> List[Any]: ... - -aRepr: Repr -def repr(x) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/resource.pyi b/mypy/typeshed/stdlib/python2/resource.pyi deleted file mode 100644 index 3763bc25b91d..000000000000 --- a/mypy/typeshed/stdlib/python2/resource.pyi +++ /dev/null @@ -1,45 +0,0 @@ -from typing import Tuple, NamedTuple - -class error(Exception): ... - -RLIM_INFINITY: int -def getrlimit(resource: int) -> Tuple[int, int]: ... -def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... - -RLIMIT_CORE: int -RLIMIT_CPU: int -RLIMIT_FSIZE: int -RLIMIT_DATA: int -RLIMIT_STACK: int -RLIMIT_RSS: int -RLIMIT_NPROC: int -RLIMIT_NOFILE: int -RLIMIT_OFILE: int -RLIMIT_MEMLOCK: int -RLIMIT_VMEM: int -RLIMIT_AS: int - -class _RUsage(NamedTuple): - ru_utime: float - ru_stime: float - ru_maxrss: int - ru_ixrss: int - ru_idrss: int - ru_isrss: int - ru_minflt: int - ru_majflt: int - ru_nswap: int - ru_inblock: int - ru_oublock: int - ru_msgsnd: int - ru_msgrcv: int - ru_nsignals: int - ru_nvcsw: int - ru_nivcsw: int - -def getrusage(who: int) -> _RUsage: ... -def getpagesize() -> int: ... - -RUSAGE_SELF: int -RUSAGE_CHILDREN: int -RUSAGE_BOTH: int diff --git a/mypy/typeshed/stdlib/python2/rfc822.pyi b/mypy/typeshed/stdlib/python2/rfc822.pyi deleted file mode 100644 index 20cd1d6394fa..000000000000 --- a/mypy/typeshed/stdlib/python2/rfc822.pyi +++ /dev/null @@ -1,79 +0,0 @@ -# Stubs for rfc822 (Python 2) -# -# Based on stub generated by stubgen. - -from typing import Any, Optional - -class Message: - fp: Any - seekable: Any - startofheaders: Any - startofbody: Any - def __init__(self, fp, seekable: int = ...): ... - def rewindbody(self): ... - dict: Any - unixfrom: Any - headers: Any - status: Any - def readheaders(self): ... - def isheader(self, line): ... - def islast(self, line): ... - def iscomment(self, line): ... - def getallmatchingheaders(self, name): ... - def getfirstmatchingheader(self, name): ... - def getrawheader(self, name): ... - def getheader(self, name, default: Optional[Any] = ...): ... - get: Any - def getheaders(self, name): ... - def getaddr(self, name): ... - def getaddrlist(self, name): ... - def getdate(self, name): ... - def getdate_tz(self, name): ... - def __len__(self): ... - def __getitem__(self, name): ... - def __setitem__(self, name, value): ... - def __delitem__(self, name): ... - def setdefault(self, name, default=...): ... - def has_key(self, name): ... - def __contains__(self, name): ... - def __iter__(self): ... - def keys(self): ... - def values(self): ... - def items(self): ... - -class AddrlistClass: - specials: Any - pos: Any - LWS: Any - CR: Any - atomends: Any - phraseends: Any - field: Any - commentlist: Any - def __init__(self, field): ... - def gotonext(self): ... - def getaddrlist(self): ... - def getaddress(self): ... - def getrouteaddr(self): ... - def getaddrspec(self): ... - def getdomain(self): ... - def getdelimited(self, beginchar, endchars, allowcomments: int = ...): ... - def getquote(self): ... - def getcomment(self): ... - def getdomainliteral(self): ... - def getatom(self, atomends: Optional[Any] = ...): ... - def getphraselist(self): ... - -class AddressList(AddrlistClass): - addresslist: Any - def __init__(self, field): ... - def __len__(self): ... - def __add__(self, other): ... - def __iadd__(self, other): ... - def __sub__(self, other): ... - def __isub__(self, other): ... - def __getitem__(self, index): ... - -def parsedate_tz(data): ... -def parsedate(data): ... -def mktime_tz(data): ... diff --git a/mypy/typeshed/stdlib/python2/robotparser.pyi b/mypy/typeshed/stdlib/python2/robotparser.pyi deleted file mode 100644 index 403039ae91c9..000000000000 --- a/mypy/typeshed/stdlib/python2/robotparser.pyi +++ /dev/null @@ -1,7 +0,0 @@ -class RobotFileParser: - def set_url(self, url: str): ... - def read(self): ... - def parse(self, lines: str): ... - def can_fetch(self, user_agent: str, url: str): ... - def mtime(self): ... - def modified(self): ... diff --git a/mypy/typeshed/stdlib/python2/runpy.pyi b/mypy/typeshed/stdlib/python2/runpy.pyi deleted file mode 100644 index 6674af077d5d..000000000000 --- a/mypy/typeshed/stdlib/python2/runpy.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any, Optional - -class _TempModule: - mod_name: Any - module: Any - def __init__(self, mod_name): ... - def __enter__(self): ... - def __exit__(self, *args): ... - -class _ModifiedArgv0: - value: Any - def __init__(self, value): ... - def __enter__(self): ... - def __exit__(self, *args): ... - -def run_module(mod_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ..., alter_sys: bool = ...): ... -def run_path(path_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ...): ... diff --git a/mypy/typeshed/stdlib/python2/sets.pyi b/mypy/typeshed/stdlib/python2/sets.pyi deleted file mode 100644 index 3ec4cae2fc44..000000000000 --- a/mypy/typeshed/stdlib/python2/sets.pyi +++ /dev/null @@ -1,61 +0,0 @@ -# Stubs for sets (Python 2) -from typing import Any, Callable, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union - -_T = TypeVar('_T') -_Setlike = Union[BaseSet[_T], Iterable[_T]] -_SelfT = TypeVar('_SelfT') - -class BaseSet(Iterable[_T]): - def __init__(self) -> None: ... - def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - def __iter__(self) -> Iterator[_T]: ... - def __cmp__(self, other: Any) -> int: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - def copy(self: _SelfT) -> _SelfT: ... - def __copy__(self: _SelfT) -> _SelfT: ... - def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... - def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def union(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... - def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def symmetric_difference(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def difference(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... - def __contains__(self, element: Any) -> bool: ... - def issubset(self, other: BaseSet[_T]) -> bool: ... - def issuperset(self, other: BaseSet[_T]) -> bool: ... - def __le__(self, other: BaseSet[_T]) -> bool: ... - def __ge__(self, other: BaseSet[_T]) -> bool: ... - def __lt__(self, other: BaseSet[_T]) -> bool: ... - def __gt__(self, other: BaseSet[_T]) -> bool: ... - -class ImmutableSet(BaseSet[_T], Hashable): - def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... - def __hash__(self) -> int: ... - -class Set(BaseSet[_T]): - def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... - def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def union_update(self, other: _Setlike[_T]) -> None: ... - def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def intersection_update(self, other: _Setlike[Any]) -> None: ... - def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... - def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def difference_update(self, other: _Setlike[Any]) -> None: ... - def update(self, iterable: _Setlike[_T]) -> None: ... - def clear(self) -> None: ... - def add(self, element: _T) -> None: ... - def remove(self, element: _T) -> None: ... - def discard(self, element: _T) -> None: ... - def pop(self) -> _T: ... - def __as_immutable__(self) -> ImmutableSet[_T]: ... - def __as_temporarily_immutable__(self) -> _TemporarilyImmutableSet[_T]: ... - -class _TemporarilyImmutableSet(BaseSet[_T]): - def __init__(self, set: BaseSet[_T]) -> None: ... - def __hash__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/sha.pyi b/mypy/typeshed/stdlib/python2/sha.pyi deleted file mode 100644 index 00ad4d9f49a8..000000000000 --- a/mypy/typeshed/stdlib/python2/sha.pyi +++ /dev/null @@ -1,11 +0,0 @@ -# Stubs for Python 2.7 sha stdlib module - -class sha(object): - def update(self, arg: str) -> None: ... - def digest(self) -> str: ... - def hexdigest(self) -> str: ... - def copy(self) -> sha: ... - -def new(string: str = ...) -> sha: ... -blocksize: int -digest_size: int diff --git a/mypy/typeshed/stdlib/python2/shelve.pyi b/mypy/typeshed/stdlib/python2/shelve.pyi deleted file mode 100644 index 15828bc1793a..000000000000 --- a/mypy/typeshed/stdlib/python2/shelve.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Any, Dict, Iterator, List, Optional, Tuple -import collections - - -class Shelf(collections.MutableMapping[Any, Any]): - def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... - def __iter__(self) -> Iterator[str]: ... - def keys(self) -> List[Any]: ... - def __len__(self) -> int: ... - def has_key(self, key: Any) -> bool: ... - def __contains__(self, key: Any) -> bool: ... - def get(self, key: Any, default: Any = ...) -> Any: ... - def __getitem__(self, key: Any) -> Any: ... - def __setitem__(self, key: Any, value: Any) -> None: ... - def __delitem__(self, key: Any) -> None: ... - def __enter__(self) -> Shelf: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... - def close(self) -> None: ... - def __del__(self) -> None: ... - def sync(self) -> None: ... - -class BsdDbShelf(Shelf): - def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... - def set_location(self, key: Any) -> Tuple[str, Any]: ... - def next(self) -> Tuple[str, Any]: ... - def previous(self) -> Tuple[str, Any]: ... - def first(self) -> Tuple[str, Any]: ... - def last(self) -> Tuple[str, Any]: ... - -class DbfilenameShelf(Shelf): - def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... - -def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/mypy/typeshed/stdlib/python2/shlex.pyi b/mypy/typeshed/stdlib/python2/shlex.pyi deleted file mode 100644 index a29b83eb1362..000000000000 --- a/mypy/typeshed/stdlib/python2/shlex.pyi +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Any, IO, List, Optional, TypeVar - -def split(s: Optional[str], comments: bool = ..., posix: bool = ...) -> List[str]: ... - -_SLT = TypeVar('_SLT', bound=shlex) - -class shlex: - def __init__(self, instream: IO[Any] = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... - def next(self) -> str: ... - def get_token(self) -> Optional[str]: ... - def push_token(self, _str: str) -> None: ... - def read_token(self) -> str: ... - def sourcehook(self, filename: str) -> None: ... - def push_source(self, stream: IO[Any], filename: str = ...) -> None: ... - def pop_source(self) -> IO[Any]: ... - def error_leader(self, file: str = ..., line: int = ...) -> str: ... - - commenters: str - wordchars: str - whitespace: str - escape: str - quotes: str - escapedquotes: str - whitespace_split: bool - infile: IO[Any] - source: Optional[str] - debug: int - lineno: int - token: Any - eof: Optional[str] diff --git a/mypy/typeshed/stdlib/python2/signal.pyi b/mypy/typeshed/stdlib/python2/signal.pyi deleted file mode 100644 index 24bfbf07789a..000000000000 --- a/mypy/typeshed/stdlib/python2/signal.pyi +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Callable, Any, Tuple, Union -from types import FrameType - -SIG_DFL: int = ... -SIG_IGN: int = ... - -ITIMER_REAL: int = ... -ITIMER_VIRTUAL: int = ... -ITIMER_PROF: int = ... - -NSIG: int = ... - -SIGABRT: int = ... -SIGALRM: int = ... -SIGBREAK: int = ... # Windows -SIGBUS: int = ... -SIGCHLD: int = ... -SIGCLD: int = ... -SIGCONT: int = ... -SIGEMT: int = ... -SIGFPE: int = ... -SIGHUP: int = ... -SIGILL: int = ... -SIGINFO: int = ... -SIGINT: int = ... -SIGIO: int = ... -SIGIOT: int = ... -SIGKILL: int = ... -SIGPIPE: int = ... -SIGPOLL: int = ... -SIGPROF: int = ... -SIGPWR: int = ... -SIGQUIT: int = ... -SIGRTMAX: int = ... -SIGRTMIN: int = ... -SIGSEGV: int = ... -SIGSTOP: int = ... -SIGSYS: int = ... -SIGTERM: int = ... -SIGTRAP: int = ... -SIGTSTP: int = ... -SIGTTIN: int = ... -SIGTTOU: int = ... -SIGURG: int = ... -SIGUSR1: int = ... -SIGUSR2: int = ... -SIGVTALRM: int = ... -SIGWINCH: int = ... -SIGXCPU: int = ... -SIGXFSZ: int = ... - -# Windows -CTRL_C_EVENT: int = ... -CTRL_BREAK_EVENT: int = ... - -class ItimerError(IOError): ... - -_HANDLER = Union[Callable[[int, FrameType], None], int, None] - -def alarm(time: int) -> int: ... -def getsignal(signalnum: int) -> _HANDLER: ... -def pause() -> None: ... -def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... -def getitimer(which: int) -> Tuple[float, float]: ... -def set_wakeup_fd(fd: int) -> int: ... -def siginterrupt(signalnum: int, flag: bool) -> None: ... -def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: ... -def default_int_handler(signum: int, frame: FrameType) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/smtplib.pyi b/mypy/typeshed/stdlib/python2/smtplib.pyi deleted file mode 100644 index 438221a439b7..000000000000 --- a/mypy/typeshed/stdlib/python2/smtplib.pyi +++ /dev/null @@ -1,86 +0,0 @@ -from typing import Any - -class SMTPException(Exception): ... -class SMTPServerDisconnected(SMTPException): ... - -class SMTPResponseException(SMTPException): - smtp_code: Any - smtp_error: Any - args: Any - def __init__(self, code, msg) -> None: ... - -class SMTPSenderRefused(SMTPResponseException): - smtp_code: Any - smtp_error: Any - sender: Any - args: Any - def __init__(self, code, msg, sender) -> None: ... - -class SMTPRecipientsRefused(SMTPException): - recipients: Any - args: Any - def __init__(self, recipients) -> None: ... - -class SMTPDataError(SMTPResponseException): ... -class SMTPConnectError(SMTPResponseException): ... -class SMTPHeloError(SMTPResponseException): ... -class SMTPAuthenticationError(SMTPResponseException): ... - -def quoteaddr(addr): ... -def quotedata(data): ... - -class SSLFakeFile: - sslobj: Any - def __init__(self, sslobj) -> None: ... - def readline(self, size=...): ... - def close(self): ... - -class SMTP: - debuglevel: Any - file: Any - helo_resp: Any - ehlo_msg: Any - ehlo_resp: Any - does_esmtp: Any - default_port: Any - timeout: Any - esmtp_features: Any - local_hostname: Any - def __init__(self, host: str = ..., port: int = ..., local_hostname=..., timeout=...) -> None: ... - def set_debuglevel(self, debuglevel): ... - sock: Any - def connect(self, host=..., port=...): ... - def send(self, str): ... - def putcmd(self, cmd, args=...): ... - def getreply(self): ... - def docmd(self, cmd, args=...): ... - def helo(self, name=...): ... - def ehlo(self, name=...): ... - def has_extn(self, opt): ... - def help(self, args=...): ... - def rset(self): ... - def noop(self): ... - def mail(self, sender, options=...): ... - def rcpt(self, recip, options=...): ... - def data(self, msg): ... - def verify(self, address): ... - vrfy: Any - def expn(self, address): ... - def ehlo_or_helo_if_needed(self): ... - def login(self, user, password): ... - def starttls(self, keyfile=..., certfile=...): ... - def sendmail(self, from_addr, to_addrs, msg, mail_options=..., rcpt_options=...): ... - def close(self): ... - def quit(self): ... - -class SMTP_SSL(SMTP): - default_port: Any - keyfile: Any - certfile: Any - def __init__(self, host=..., port=..., local_hostname=..., keyfile=..., certfile=..., timeout=...) -> None: ... - -class LMTP(SMTP): - ehlo_msg: Any - def __init__(self, host=..., port=..., local_hostname=...) -> None: ... - sock: Any - def connect(self, host=..., port=...): ... diff --git a/mypy/typeshed/stdlib/python2/spwd.pyi b/mypy/typeshed/stdlib/python2/spwd.pyi deleted file mode 100644 index 756c142a61da..000000000000 --- a/mypy/typeshed/stdlib/python2/spwd.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from typing import List, NamedTuple - -class struct_spwd(NamedTuple): - sp_nam: str - sp_pwd: str - sp_lstchg: int - sp_min: int - sp_max: int - sp_warn: int - sp_inact: int - sp_expire: int - sp_flag: int - -def getspall() -> List[struct_spwd]: ... -def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/python2/sre_constants.pyi b/mypy/typeshed/stdlib/python2/sre_constants.pyi deleted file mode 100644 index 89d453ea22da..000000000000 --- a/mypy/typeshed/stdlib/python2/sre_constants.pyi +++ /dev/null @@ -1,94 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_constants.py - -from typing import Dict, List, TypeVar - -MAGIC: int -MAXREPEAT: int - -class error(Exception): ... - -FAILURE: str -SUCCESS: str -ANY: str -ANY_ALL: str -ASSERT: str -ASSERT_NOT: str -AT: str -BIGCHARSET: str -BRANCH: str -CALL: str -CATEGORY: str -CHARSET: str -GROUPREF: str -GROUPREF_IGNORE: str -GROUPREF_EXISTS: str -IN: str -IN_IGNORE: str -INFO: str -JUMP: str -LITERAL: str -LITERAL_IGNORE: str -MARK: str -MAX_REPEAT: str -MAX_UNTIL: str -MIN_REPEAT: str -MIN_UNTIL: str -NEGATE: str -NOT_LITERAL: str -NOT_LITERAL_IGNORE: str -RANGE: str -REPEAT: str -REPEAT_ONE: str -SUBPATTERN: str -MIN_REPEAT_ONE: str -AT_BEGINNING: str -AT_BEGINNING_LINE: str -AT_BEGINNING_STRING: str -AT_BOUNDARY: str -AT_NON_BOUNDARY: str -AT_END: str -AT_END_LINE: str -AT_END_STRING: str -AT_LOC_BOUNDARY: str -AT_LOC_NON_BOUNDARY: str -AT_UNI_BOUNDARY: str -AT_UNI_NON_BOUNDARY: str -CATEGORY_DIGIT: str -CATEGORY_NOT_DIGIT: str -CATEGORY_SPACE: str -CATEGORY_NOT_SPACE: str -CATEGORY_WORD: str -CATEGORY_NOT_WORD: str -CATEGORY_LINEBREAK: str -CATEGORY_NOT_LINEBREAK: str -CATEGORY_LOC_WORD: str -CATEGORY_LOC_NOT_WORD: str -CATEGORY_UNI_DIGIT: str -CATEGORY_UNI_NOT_DIGIT: str -CATEGORY_UNI_SPACE: str -CATEGORY_UNI_NOT_SPACE: str -CATEGORY_UNI_WORD: str -CATEGORY_UNI_NOT_WORD: str -CATEGORY_UNI_LINEBREAK: str -CATEGORY_UNI_NOT_LINEBREAK: str - -_T = TypeVar('_T') -def makedict(list: List[_T]) -> Dict[_T, int]: ... - -OP_IGNORE: Dict[str, str] -AT_MULTILINE: Dict[str, str] -AT_LOCALE: Dict[str, str] -AT_UNICODE: Dict[str, str] -CH_LOCALE: Dict[str, str] -CH_UNICODE: Dict[str, str] -SRE_FLAG_TEMPLATE: int -SRE_FLAG_IGNORECASE: int -SRE_FLAG_LOCALE: int -SRE_FLAG_MULTILINE: int -SRE_FLAG_DOTALL: int -SRE_FLAG_UNICODE: int -SRE_FLAG_VERBOSE: int -SRE_FLAG_DEBUG: int -SRE_INFO_PREFIX: int -SRE_INFO_LITERAL: int -SRE_INFO_CHARSET: int diff --git a/mypy/typeshed/stdlib/python2/sre_parse.pyi b/mypy/typeshed/stdlib/python2/sre_parse.pyi deleted file mode 100644 index d23753527d12..000000000000 --- a/mypy/typeshed/stdlib/python2/sre_parse.pyi +++ /dev/null @@ -1,63 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_parse.py - -from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union - -SPECIAL_CHARS: str -REPEAT_CHARS: str -DIGITS: Set[Any] -OCTDIGITS: Set[Any] -HEXDIGITS: Set[Any] -WHITESPACE: Set[Any] -ESCAPES: Dict[str, Tuple[str, int]] -CATEGORIES: Dict[str, Union[Tuple[str, str], Tuple[str, List[Tuple[str, str]]]]] -FLAGS: Dict[str, int] - -class Pattern: - flags: int - open: List[int] - groups: int - groupdict: Dict[str, int] - lookbehind: int - def __init__(self) -> None: ... - def opengroup(self, name: str = ...) -> int: ... - def closegroup(self, gid: int) -> None: ... - def checkgroup(self, gid: int) -> bool: ... - - -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] -_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] -_OpInType = List[Tuple[str, int]] -_OpBranchType = Tuple[None, List[SubPattern]] -_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] -_CodeType = Union[str, _AvType] - -class SubPattern: - pattern: str - data: List[_CodeType] - width: Optional[int] - def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... - def dump(self, level: int = ...) -> None: ... - def __len__(self) -> int: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... - def __setitem__(self, index: Union[int, slice], code: _CodeType): ... - def insert(self, index, code: _CodeType) -> None: ... - def append(self, code: _CodeType) -> None: ... - def getwidth(self) -> int: ... - -class Tokenizer: - string: str - index: int - def __init__(self, string: str) -> None: ... - def match(self, char: str, skip: int = ...) -> int: ... - def get(self) -> Optional[str]: ... - def tell(self) -> Tuple[int, Optional[str]]: ... - def seek(self, index: int) -> None: ... - -def isident(char: str) -> bool: ... -def isdigit(char: str) -> bool: ... -def isname(name: str) -> bool: ... -def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... -_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] -def parse_template(source: str, pattern: _Pattern[Any]) -> _Template: ... -def expand_template(template: _Template, match: Match[Any]) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/stat.pyi b/mypy/typeshed/stdlib/python2/stat.pyi deleted file mode 100644 index 5230d670f080..000000000000 --- a/mypy/typeshed/stdlib/python2/stat.pyi +++ /dev/null @@ -1,59 +0,0 @@ -def S_ISDIR(mode: int) -> bool: ... -def S_ISCHR(mode: int) -> bool: ... -def S_ISBLK(mode: int) -> bool: ... -def S_ISREG(mode: int) -> bool: ... -def S_ISFIFO(mode: int) -> bool: ... -def S_ISLNK(mode: int) -> bool: ... -def S_ISSOCK(mode: int) -> bool: ... - -def S_IMODE(mode: int) -> int: ... -def S_IFMT(mode: int) -> int: ... - -ST_MODE: int -ST_INO: int -ST_DEV: int -ST_NLINK: int -ST_UID: int -ST_GID: int -ST_SIZE: int -ST_ATIME: int -ST_MTIME: int -ST_CTIME: int -S_IFSOCK: int -S_IFLNK: int -S_IFREG: int -S_IFBLK: int -S_IFDIR: int -S_IFCHR: int -S_IFIFO: int -S_ISUID: int -S_ISGID: int -S_ISVTX: int -S_IRWXU: int -S_IRUSR: int -S_IWUSR: int -S_IXUSR: int -S_IRWXG: int -S_IRGRP: int -S_IWGRP: int -S_IXGRP: int -S_IRWXO: int -S_IROTH: int -S_IWOTH: int -S_IXOTH: int -S_ENFMT: int -S_IREAD: int -S_IWRITE: int -S_IEXEC: int -UF_NODUMP: int -UF_IMMUTABLE: int -UF_APPEND: int -UF_OPAQUE: int -UF_NOUNLINK: int -UF_COMPRESSED: int -UF_HIDDEN: int -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_APPEND: int -SF_NOUNLINK: int -SF_SNAPSHOT: int diff --git a/mypy/typeshed/stdlib/python2/string.pyi b/mypy/typeshed/stdlib/python2/string.pyi deleted file mode 100644 index bf55e922a408..000000000000 --- a/mypy/typeshed/stdlib/python2/string.pyi +++ /dev/null @@ -1,75 +0,0 @@ -# Stubs for string - -# Based on http://docs.python.org/3.2/library/string.html - -from typing import Any, AnyStr, Iterable, List, Mapping, Optional, overload, Sequence, Text, Tuple, Union - -ascii_letters: str -ascii_lowercase: str -ascii_uppercase: str -digits: str -hexdigits: str -letters: str -lowercase: str -octdigits: str -punctuation: str -printable: str -uppercase: str -whitespace: str - -def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... -# TODO: originally named 'from' -def maketrans(_from: str, to: str) -> str: ... -def atof(s: unicode) -> float: ... -def atoi(s: unicode, base: int = ...) -> int: ... -def atol(s: unicode, base: int = ...) -> int: ... -def capitalize(word: AnyStr) -> AnyStr: ... -def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def lower(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def rstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def strip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... -def swapcase(s: AnyStr) -> AnyStr: ... -def translate(s: str, table: str, deletechars: str = ...) -> str: ... -def upper(s: AnyStr) -> AnyStr: ... -def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def zfill(s: AnyStr, width: int) -> AnyStr: ... -def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... - -class Template: - template: Text - - def __init__(self, template: Text) -> None: ... - @overload - def substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... - @overload - def substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]] = ..., **kwds: Text) -> Text: ... - @overload - def safe_substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... - @overload - def safe_substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]], **kwds: Text) -> Text: ... - -# TODO(MichalPokorny): This is probably badly and/or loosely typed. -class Formatter(object): - def format(self, format_string: str, *args, **kwargs) -> str: ... - def vformat(self, format_string: str, args: Sequence[Any], - kwargs: Mapping[str, Any]) -> str: ... - def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... - def get_field(self, field_name: str, args: Sequence[Any], - kwargs: Mapping[str, Any]) -> Any: ... - def get_value(self, key: Union[int, str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], - kwargs: Mapping[str, Any]) -> None: ... - def format_field(self, value: Any, format_spec: str) -> Any: ... - def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/python2/stringold.pyi b/mypy/typeshed/stdlib/python2/stringold.pyi deleted file mode 100644 index ab3e764ed213..000000000000 --- a/mypy/typeshed/stdlib/python2/stringold.pyi +++ /dev/null @@ -1,46 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/stringold.py -from typing import AnyStr, Iterable, List, Optional, Type - -whitespace: str -lowercase: str -uppercase: str -letters: str -digits: str -hexdigits: str -octdigits: str -_idmap: str -_idmapL: Optional[List[str]] -index_error = ValueError -atoi_error = ValueError -atof_error = ValueError -atol_error = ValueError - - -def lower(s: AnyStr) -> AnyStr: ... -def upper(s: AnyStr) -> AnyStr: ... -def swapcase(s: AnyStr) -> AnyStr: ... -def strip(s: AnyStr) -> AnyStr: ... -def lstrip(s: AnyStr) -> AnyStr: ... -def rstrip(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... -def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... -def atof(s: unicode) -> float: ... -def atoi(s: unicode, base: int = ...) -> int: ... -def atol(s: unicode, base: int = ...) -> long: ... -def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... -def zfill(s: AnyStr, width: int) -> AnyStr: ... -def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... -def translate(s: str, table: str, deletions: str = ...) -> str: ... -def capitalize(s: AnyStr) -> AnyStr: ... -def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... -def maketrans(fromstr: str, tostr: str) -> str: ... -def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/strop.pyi b/mypy/typeshed/stdlib/python2/strop.pyi deleted file mode 100644 index 578a47758df5..000000000000 --- a/mypy/typeshed/stdlib/python2/strop.pyi +++ /dev/null @@ -1,29 +0,0 @@ -"""Stub file for the 'strop' module.""" - -from typing import List, Sequence - -lowercase: str -uppercase: str -whitespace: str - -def atof(a: str) -> float: ... -def atoi(a: str, base: int = ...) -> int: ... -def atol(a: str, base: int = ...) -> long: ... -def capitalize(s: str) -> str: ... -def count(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def expandtabs(string: str, tabsize: int = ...) -> str: ... -def find(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def join(list: Sequence[str], sep: str = ...) -> str: ... -def joinfields(list: Sequence[str], sep: str = ...) -> str: ... -def lower(s: str) -> str: ... -def lstrip(s: str) -> str: ... -def maketrans(frm: str, to: str) -> str: ... -def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: ... -def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... -def rstrip(s: str) -> str: ... -def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... -def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... -def strip(s: str) -> str: ... -def swapcase(s: str) -> str: ... -def translate(s: str, table: str, deletechars: str = ...) -> str: ... -def upper(s: str) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/subprocess.pyi b/mypy/typeshed/stdlib/python2/subprocess.pyi deleted file mode 100644 index 4c2f2d8c2f6a..000000000000 --- a/mypy/typeshed/stdlib/python2/subprocess.pyi +++ /dev/null @@ -1,120 +0,0 @@ -# Stubs for subprocess - -# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub - -from typing import ( - Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text, TypeVar, Generic, -) - -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, Text] -_CMD = Union[_TXT, Sequence[_TXT]] -_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] - -# Same args as Popen.__init__ -def call(args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[_TXT] = ..., - env: _ENV = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ...) -> int: ... - -def check_call(args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[_TXT] = ..., - env: _ENV = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ...) -> int: ... - -# Same args as Popen.__init__ except for stdout -def check_output(args: _CMD, - bufsize: int = ..., - executable: _TXT = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[_TXT] = ..., - env: _ENV = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ...) -> bytes: ... - -PIPE: int -STDOUT: int - -class CalledProcessError(Exception): - returncode: int - # morally: _CMD - cmd: Any - # morally: Optional[bytes] - output: bytes - - def __init__(self, - returncode: int, - cmd: _CMD, - output: Optional[bytes] = ...) -> None: ... - -# We use a dummy type variable used to make Popen generic like it is in python 3 -_T = TypeVar('_T', bound=bytes) - -class Popen(Generic[_T]): - stdin: Optional[IO[bytes]] - stdout: Optional[IO[bytes]] - stderr: Optional[IO[bytes]] - pid: int - returncode: int - - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[_TXT] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[_TXT] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ...) -> Popen[bytes]: ... - - def poll(self) -> Optional[int]: ... - def wait(self) -> int: ... - # morally: -> Tuple[Optional[bytes], Optional[bytes]] - def communicate(self, input: Optional[_TXT] = ...) -> Tuple[bytes, bytes]: ... - def send_signal(self, signal: int) -> None: ... - def terminate(self) -> None: ... - def kill(self) -> None: ... - -def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented - -# Windows-only: STARTUPINFO etc. - -STD_INPUT_HANDLE: Any -STD_OUTPUT_HANDLE: Any -STD_ERROR_HANDLE: Any -SW_HIDE: Any -STARTF_USESTDHANDLES: Any -STARTF_USESHOWWINDOW: Any -CREATE_NEW_CONSOLE: Any -CREATE_NEW_PROCESS_GROUP: Any diff --git a/mypy/typeshed/stdlib/python2/symbol.pyi b/mypy/typeshed/stdlib/python2/symbol.pyi deleted file mode 100644 index 55d25a6b2ee8..000000000000 --- a/mypy/typeshed/stdlib/python2/symbol.pyi +++ /dev/null @@ -1,91 +0,0 @@ -# Stubs for symbol (Python 2) - -from typing import Dict - -single_input: int -file_input: int -eval_input: int -decorator: int -decorators: int -decorated: int -funcdef: int -parameters: int -varargslist: int -fpdef: int -fplist: int -stmt: int -simple_stmt: int -small_stmt: int -expr_stmt: int -augassign: int -print_stmt: int -del_stmt: int -pass_stmt: int -flow_stmt: int -break_stmt: int -continue_stmt: int -return_stmt: int -yield_stmt: int -raise_stmt: int -import_stmt: int -import_name: int -import_from: int -import_as_name: int -dotted_as_name: int -import_as_names: int -dotted_as_names: int -dotted_name: int -global_stmt: int -exec_stmt: int -assert_stmt: int -compound_stmt: int -if_stmt: int -while_stmt: int -for_stmt: int -try_stmt: int -with_stmt: int -with_item: int -except_clause: int -suite: int -testlist_safe: int -old_test: int -old_lambdef: int -test: int -or_test: int -and_test: int -not_test: int -comparison: int -comp_op: int -expr: int -xor_expr: int -and_expr: int -shift_expr: int -arith_expr: int -term: int -factor: int -power: int -atom: int -listmaker: int -testlist_comp: int -lambdef: int -trailer: int -subscriptlist: int -subscript: int -sliceop: int -exprlist: int -testlist: int -dictorsetmaker: int -classdef: int -arglist: int -argument: int -list_iter: int -list_for: int -list_if: int -comp_iter: int -comp_for: int -comp_if: int -testlist1: int -encoding_decl: int -yield_expr: int - -sym_name: Dict[int, str] diff --git a/mypy/typeshed/stdlib/python2/sys.pyi b/mypy/typeshed/stdlib/python2/sys.pyi deleted file mode 100644 index f8651abdb506..000000000000 --- a/mypy/typeshed/stdlib/python2/sys.pyi +++ /dev/null @@ -1,136 +0,0 @@ -"""Stubs for the 'sys' module.""" - -from typing import ( - IO, NoReturn, Union, List, Sequence, Any, Dict, Tuple, BinaryIO, Optional, - Callable, overload, Text, Type, -) -from types import FrameType, ModuleType, TracebackType, ClassType - -# The following type alias are stub-only and do not exist during runtime -_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] - -class _flags: - bytes_warning: int - debug: int - division_new: int - division_warning: int - dont_write_bytecode: int - hash_randomization: int - ignore_environment: int - inspect: int - interactive: int - no_site: int - no_user_site: int - optimize: int - py3k_warning: int - tabcheck: int - unicode: int - verbose: int - -class _float_info: - max: float - max_exp: int - max_10_exp: int - min: float - min_exp: int - min_10_exp: int - dig: int - mant_dig: int - epsilon: float - radix: int - rounds: int - -class _version_info(Tuple[int, int, int, str, int]): - major: int - minor: int - micro: int - releaselevel: str - serial: int - -_mercurial: Tuple[str, str, str] -api_version: int -argv: List[str] -builtin_module_names: Tuple[str, ...] -byteorder: str -copyright: str -dont_write_bytecode: bool -exec_prefix: str -executable: str -flags: _flags -float_repr_style: str -hexversion: int -long_info: object -maxint: int -maxsize: int -maxunicode: int -modules: Dict[str, Any] -path: List[str] -platform: str -prefix: str -py3kwarning: bool -__stderr__: IO[str] -__stdin__: IO[str] -__stdout__: IO[str] -stderr: IO[str] -stdin: IO[str] -stdout: IO[str] -subversion: Tuple[str, str, str] -version: str -warnoptions: object -float_info: _float_info -version_info: _version_info -ps1: str -ps2: str -last_type: type -last_value: BaseException -last_traceback: TracebackType -# TODO precise types -meta_path: List[Any] -path_hooks: List[Any] -path_importer_cache: Dict[str, Any] -displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] -exc_type: Optional[type] -exc_value: Union[BaseException, ClassType] -exc_traceback: TracebackType - -class _WindowsVersionType: - major: Any - minor: Any - build: Any - platform: Any - service_pack: Any - service_pack_major: Any - service_pack_minor: Any - suite_mask: Any - product_type: Any - -def getwindowsversion() -> _WindowsVersionType: ... - -def _clear_type_cache() -> None: ... -def _current_frames() -> Dict[int, FrameType]: ... -def _getframe(depth: int = ...) -> FrameType: ... -def call_tracing(fn: Any, args: Any) -> Any: ... -def __displayhook__(value: object) -> None: ... -def __excepthook__(type_: type, value: BaseException, traceback: TracebackType) -> None: ... -def exc_clear() -> None: ... -def exc_info() -> _OptExcInfo: ... - -# sys.exit() accepts an optional argument of anything printable -def exit(arg: Any = ...) -> NoReturn: ... -def getcheckinterval() -> int: ... # deprecated -def getdefaultencoding() -> str: ... -def getdlopenflags() -> int: ... -def getfilesystemencoding() -> str: ... # In practice, never returns None -def getrefcount(arg: Any) -> int: ... -def getrecursionlimit() -> int: ... -def getsizeof(obj: object, default: int = ...) -> int: ... -def getprofile() -> Optional[Any]: ... -def gettrace() -> Optional[Any]: ... -def setcheckinterval(interval: int) -> None: ... # deprecated -def setdlopenflags(n: int) -> None: ... -def setdefaultencoding(encoding: Text) -> None: ... # only exists after reload(sys) -def setprofile(profilefunc: Any) -> None: ... # TODO type -def setrecursionlimit(limit: int) -> None: ... -def settrace(tracefunc: Any) -> None: ... # TODO type diff --git a/mypy/typeshed/stdlib/python2/tempfile.pyi b/mypy/typeshed/stdlib/python2/tempfile.pyi deleted file mode 100644 index 536b391ad4d0..000000000000 --- a/mypy/typeshed/stdlib/python2/tempfile.pyi +++ /dev/null @@ -1,111 +0,0 @@ -from typing import Any, AnyStr, IO, Iterable, Iterator, List, Optional, overload, Text, Tuple, Union -from thread import LockType -from random import Random - -TMP_MAX: int -tempdir: str -template: str -_name_sequence: Optional[_RandomNameSequence] - -class _RandomNameSequence: - characters: str = ... - mutex: LockType - @property - def rng(self) -> Random: ... - def __iter__(self) -> _RandomNameSequence: ... - def next(self) -> str: ... - # from os.path: - def normcase(self, path: AnyStr) -> AnyStr: ... - -class _TemporaryFileWrapper(IO[str]): - delete: bool - file: IO[str] - name: Any - def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... - def __del__(self) -> None: ... - def __enter__(self) -> _TemporaryFileWrapper: ... - def __exit__(self, exc, value, tb) -> Optional[bool]: ... - def __getattr__(self, name: unicode) -> Any: ... - def close(self) -> None: ... - def unlink(self, path: unicode) -> 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 fileno(self) -> int: ... - def flush(self) -> None: ... - def isatty(self) -> bool: ... - def next(self) -> str: ... - def read(self, n: int = ...) -> str: ... - def readable(self) -> bool: ... - def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... - 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: Text) -> int: ... - def writelines(self, lines: Iterable[str]) -> None: ... - - -# TODO text files - -def TemporaryFile( - mode: Union[bytes, unicode] = ..., - bufsize: int = ..., - suffix: Union[bytes, unicode] = ..., - prefix: Union[bytes, unicode] = ..., - dir: Union[bytes, unicode] = ... -) -> _TemporaryFileWrapper: - ... - -def NamedTemporaryFile( - mode: Union[bytes, unicode] = ..., - bufsize: int = ..., - suffix: Union[bytes, unicode] = ..., - prefix: Union[bytes, unicode] = ..., - dir: Union[bytes, unicode] = ..., - delete: bool = ... -) -> _TemporaryFileWrapper: - ... - -def SpooledTemporaryFile( - max_size: int = ..., - mode: Union[bytes, unicode] = ..., - buffering: int = ..., - suffix: Union[bytes, unicode] = ..., - prefix: Union[bytes, unicode] = ..., - dir: Union[bytes, unicode] = ... -) -> _TemporaryFileWrapper: - ... - -class TemporaryDirectory: - name: Any - def __init__(self, - suffix: Union[bytes, unicode] = ..., - prefix: Union[bytes, unicode] = ..., - dir: Union[bytes, unicode] = ...) -> None: ... - def cleanup(self) -> None: ... - def __enter__(self) -> Any: ... # Can be str or unicode - def __exit__(self, type, value, traceback) -> None: ... - -@overload -def mkstemp() -> Tuple[int, str]: ... -@overload -def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ..., - text: bool = ...) -> Tuple[int, AnyStr]: ... -@overload -def mkdtemp() -> str: ... -@overload -def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... -@overload -def mktemp() -> str: ... -@overload -def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... -def gettempdir() -> str: ... -def gettempprefix() -> str: ... - -def _candidate_tempdir_list() -> List[str]: ... -def _get_candidate_names() -> Optional[_RandomNameSequence]: ... -def _get_default_tempdir() -> str: ... diff --git a/mypy/typeshed/stdlib/python2/textwrap.pyi b/mypy/typeshed/stdlib/python2/textwrap.pyi deleted file mode 100644 index 60498a65acd0..000000000000 --- a/mypy/typeshed/stdlib/python2/textwrap.pyi +++ /dev/null @@ -1,61 +0,0 @@ -from typing import AnyStr, List, Dict, Pattern - -class TextWrapper(object): - width: int = ... - initial_indent: str = ... - subsequent_indent: str = ... - expand_tabs: bool = ... - replace_whitespace: bool = ... - fix_sentence_endings: bool = ... - drop_whitespace: bool = ... - break_long_words: bool = ... - break_on_hyphens: bool = ... - - # Attributes not present in documentation - sentence_end_re: Pattern[str] = ... - wordsep_re: Pattern[str] = ... - wordsep_simple_re: Pattern[str] = ... - whitespace_trans: str = ... - unicode_whitespace_trans: Dict[int, int] = ... - uspace: int = ... - x: int = ... - - def __init__( - self, - width: int = ..., - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ...) -> None: - ... - - def wrap(self, text: AnyStr) -> List[AnyStr]: ... - def fill(self, text: AnyStr) -> AnyStr: ... - -def wrap(text: AnyStr, - width: int = ..., - initial_indent: AnyStr = ..., - subsequent_indent: AnyStr = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ...) -> List[AnyStr]: ... - -def fill(text: AnyStr, - width: int = ..., - initial_indent: AnyStr = ..., - subsequent_indent: AnyStr = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ...) -> AnyStr: ... - -def dedent(text: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/python2/thread.pyi b/mypy/typeshed/stdlib/python2/thread.pyi deleted file mode 100644 index 5bc40f4ba8a8..000000000000 --- a/mypy/typeshed/stdlib/python2/thread.pyi +++ /dev/null @@ -1,28 +0,0 @@ -"""Stubs for the "thread" module.""" -from typing import Callable, Any - -def _count() -> int: ... - -class error(Exception): ... - -class LockType: - def acquire(self, waitflag: int = ...) -> bool: ... - def acquire_lock(self, waitflag: int = ...) -> bool: ... - def release(self) -> None: ... - def release_lock(self) -> None: ... - def locked(self) -> bool: ... - def locked_lock(self) -> bool: ... - def __enter__(self) -> LockType: ... - def __exit__(self, typ: Any, value: Any, traceback: Any) -> None: ... - -class _local(object): ... -class _localdummy(object): ... - -def start_new(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... -def start_new_thread(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... -def interrupt_main() -> None: ... -def exit() -> None: ... -def exit_thread() -> Any: ... -def allocate_lock() -> LockType: ... -def get_ident() -> int: ... -def stack_size(size: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/python2/toaiff.pyi b/mypy/typeshed/stdlib/python2/toaiff.pyi deleted file mode 100644 index f3e1b29d50b3..000000000000 --- a/mypy/typeshed/stdlib/python2/toaiff.pyi +++ /dev/null @@ -1,14 +0,0 @@ -# Stubs for toaiff (Python 2) - -# Source: https://hg.python.org/cpython/file/2.7/Lib/toaiff.py -from pipes import Template -from typing import Dict, List - -table: Dict[str, Template] -t: Template -uncompress: Template - -class error(Exception): ... - -def toaiff(filename: str) -> str: ... -def _toaiff(filename: str, temps: List[str]) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/tokenize.pyi b/mypy/typeshed/stdlib/python2/tokenize.pyi deleted file mode 100644 index 43457b6a95de..000000000000 --- a/mypy/typeshed/stdlib/python2/tokenize.pyi +++ /dev/null @@ -1,136 +0,0 @@ -# Automatically generated by pytype, manually fixed up. May still contain errors. - -from typing import Any, Callable, Dict, Generator, Iterator, List, Tuple, Union, Iterable - -__author__: str -__credits__: str - -AMPER: int -AMPEREQUAL: int -AT: int -BACKQUOTE: int -Binnumber: str -Bracket: str -CIRCUMFLEX: int -CIRCUMFLEXEQUAL: int -COLON: int -COMMA: int -COMMENT: int -Comment: str -ContStr: str -DEDENT: int -DOT: int -DOUBLESLASH: int -DOUBLESLASHEQUAL: int -DOUBLESTAR: int -DOUBLESTAREQUAL: int -Decnumber: str -Double: str -Double3: str -ENDMARKER: int -EQEQUAL: int -EQUAL: int -ERRORTOKEN: int -Expfloat: str -Exponent: str -Floatnumber: str -Funny: str -GREATER: int -GREATEREQUAL: int -Hexnumber: str -INDENT: int - -def ISEOF(x: int) -> bool: ... -def ISNONTERMINAL(x: int) -> bool: ... -def ISTERMINAL(x: int) -> bool: ... - -Ignore: str -Imagnumber: str -Intnumber: str -LBRACE: int -LEFTSHIFT: int -LEFTSHIFTEQUAL: int -LESS: int -LESSEQUAL: int -LPAR: int -LSQB: int -MINEQUAL: int -MINUS: int -NAME: int -NEWLINE: int -NL: int -NOTEQUAL: int -NT_OFFSET: int -NUMBER: int -N_TOKENS: int -Name: str -Number: str -OP: int -Octnumber: str -Operator: str -PERCENT: int -PERCENTEQUAL: int -PLUS: int -PLUSEQUAL: int -PlainToken: str -Pointfloat: str -PseudoExtras: str -PseudoToken: str -RBRACE: int -RIGHTSHIFT: int -RIGHTSHIFTEQUAL: int -RPAR: int -RSQB: int -SEMI: int -SLASH: int -SLASHEQUAL: int -STAR: int -STAREQUAL: int -STRING: int -Single: str -Single3: str -Special: str -String: str -TILDE: int -Token: str -Triple: str -VBAR: int -VBAREQUAL: int -Whitespace: str -chain: type -double3prog: type -endprogs: Dict[str, Any] -pseudoprog: type -single3prog: type -single_quoted: Dict[str, str] -t: str -tabsize: int -tok_name: Dict[int, str] -tokenprog: type -triple_quoted: Dict[str, str] -x: str - -_Pos = Tuple[int, int] -_TokenType = Tuple[int, str, _Pos, _Pos, str] - -def any(*args, **kwargs) -> str: ... -def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... -def group(*args: str) -> str: ... -def maybe(*args: str) -> str: ... -def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... -def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... -def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... -def untokenize(iterable: Iterable[_TokenType]) -> str: ... - -class StopTokenizing(Exception): ... - -class TokenError(Exception): ... - -class Untokenizer: - prev_col: int - prev_row: int - tokens: List[str] - def __init__(self) -> None: ... - def add_whitespace(self, _Pos) -> None: ... - def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... - def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/mypy/typeshed/stdlib/python2/types.pyi b/mypy/typeshed/stdlib/python2/types.pyi deleted file mode 100644 index 63b296b7030a..000000000000 --- a/mypy/typeshed/stdlib/python2/types.pyi +++ /dev/null @@ -1,187 +0,0 @@ -# Stubs for types -# Note, all classes "defined" here require special handling. - -from typing import ( - Any, Callable, Dict, Iterable, Iterator, List, Optional, - Tuple, Type, TypeVar, Union, overload, -) - -_T = TypeVar('_T') - -class NoneType: ... -TypeType = type -ObjectType = object - -IntType = int -LongType = int # Really long, but can't reference that due to a mypy import cycle -FloatType = float -BooleanType = bool -ComplexType = complex -StringType = str -UnicodeType = unicode -StringTypes: Tuple[Type[StringType], Type[UnicodeType]] -BufferType = buffer -TupleType = tuple -ListType = list -DictType = dict -DictionaryType = dict - -class _Cell: - cell_contents: Any - -class FunctionType: - func_closure: Optional[Tuple[_Cell, ...]] = ... - func_code: CodeType = ... - func_defaults: Optional[Tuple[Any, ...]] = ... - func_dict: Dict[str, Any] = ... - func_doc: Optional[str] = ... - func_globals: Dict[str, Any] = ... - func_name: str = ... - __closure__ = func_closure - __code__ = func_code - __defaults__ = func_defaults - __dict__ = func_dict - __globals__ = func_globals - __name__ = func_name - def __init__(self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ...) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Optional[object], type: Optional[type]) -> UnboundMethodType: ... - -LambdaType = FunctionType - -class CodeType: - co_argcount: int - co_cellvars: Tuple[str, ...] - co_code: str - co_consts: Tuple[Any, ...] - co_filename: str - co_firstlineno: int - co_flags: int - co_freevars: Tuple[str, ...] - co_lnotab: str - co_name: str - co_names: Tuple[str, ...] - co_nlocals: int - co_stacksize: int - co_varnames: Tuple[str, ...] - def __init__( - self, - argcount: int, - nlocals: int, - stacksize: int, - flags: int, - codestring: str, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], - filename: str, - name: str, - firstlineno: int, - lnotab: str, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., - ) -> None: ... - -class GeneratorType: - gi_code: CodeType - gi_frame: FrameType - gi_running: int - def __iter__(self) -> GeneratorType: ... - def close(self) -> None: ... - def next(self) -> Any: ... - def send(self, __arg: Any) -> Any: ... - @overload - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... - @overload - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... - -class ClassType: ... -class UnboundMethodType: - im_class: type = ... - im_func: FunctionType = ... - im_self: object = ... - __name__: str - __func__ = im_func - __self__ = im_self - def __init__(self, func: Callable[..., Any], obj: object) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - -class InstanceType(object): ... - -MethodType = UnboundMethodType - -class BuiltinFunctionType: - __self__: Optional[object] - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... -BuiltinMethodType = BuiltinFunctionType - -class ModuleType: - __doc__: Optional[str] - __file__: Optional[str] - __name__: str - __package__: Optional[str] - __path__: Optional[Iterable[str]] - __dict__: Dict[str, Any] - def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... -FileType = file -XRangeType = xrange - -class TracebackType: - tb_frame: FrameType - tb_lasti: int - tb_lineno: int - tb_next: TracebackType - -class FrameType: - f_back: FrameType - f_builtins: Dict[str, Any] - f_code: CodeType - f_exc_type: None - f_exc_value: None - f_exc_traceback: None - f_globals: Dict[str, Any] - f_lasti: int - f_lineno: int - f_locals: Dict[str, Any] - f_restricted: bool - f_trace: Callable[[], None] - - def clear(self) -> None: ... - -SliceType = slice -class EllipsisType: ... - -class DictProxyType: - # TODO is it possible to have non-string keys? - # no __init__ - def copy(self) -> Dict[Any, Any]: ... - def get(self, key: str, default: _T = ...) -> Union[Any, _T]: ... - def has_key(self, key: str) -> bool: ... - def items(self) -> List[Tuple[str, Any]]: ... - def iteritems(self) -> Iterator[Tuple[str, Any]]: ... - def iterkeys(self) -> Iterator[str]: ... - def itervalues(self) -> Iterator[Any]: ... - def keys(self) -> List[str]: ... - def values(self) -> List[Any]: ... - def __contains__(self, key: str) -> bool: ... - def __getitem__(self, key: str) -> Any: ... - def __iter__(self) -> Iterator[str]: ... - def __len__(self) -> int: ... - -class NotImplementedType: ... - -class GetSetDescriptorType: - __name__: str - __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... -# Same type on Jython, different on CPython and PyPy, unknown on IronPython. -class MemberDescriptorType: - __name__: str - __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/python2/typing.pyi b/mypy/typeshed/stdlib/python2/typing.pyi deleted file mode 100644 index 7f677ec858fe..000000000000 --- a/mypy/typeshed/stdlib/python2/typing.pyi +++ /dev/null @@ -1,510 +0,0 @@ -# Stubs for typing (Python 2.7) - -from abc import abstractmethod, ABCMeta -from types import CodeType, FrameType, TracebackType -import collections # Needed by aliases like DefaultDict, see mypy issue 2986 - -# Definitions of special type checking related constructs. Their definitions -# are not used, so their value does not matter. - -overload = object() -Any = object() - -class TypeVar: - __name__: str - __bound__: Optional[Type[Any]] - __constraints__: Tuple[Type[Any], ...] - __covariant__: bool - __contravariant__: bool - def __init__(self, name: str, *constraints: Type[Any], bound: Optional[Type[Any]] = ..., covariant: bool = ..., contravariant: bool = ...) -> None: ... - -_promote = object() - -class _SpecialForm(object): - def __getitem__(self, typeargs: Any) -> object: ... - -Union: _SpecialForm = ... -Optional: _SpecialForm = ... -Tuple: _SpecialForm = ... -Generic: _SpecialForm = ... -Protocol: _SpecialForm = ... -Callable: _SpecialForm = ... -Type: _SpecialForm = ... -ClassVar: _SpecialForm = ... -Final: _SpecialForm = ... -_F = TypeVar('_F', bound=Callable[..., Any]) -def final(f: _F) -> _F: ... -Literal: _SpecialForm = ... -# TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... - -class GenericMeta(type): ... - -# Return type that indicates a function does not return. -# This type is equivalent to the None type, but the no-op Union is necessary to -# distinguish the None type from the None value. -NoReturn = Union[None] - -# These type variables are used by the container types. -_T = TypeVar('_T') -_S = TypeVar('_S') -_KT = TypeVar('_KT') # Key type. -_VT = TypeVar('_VT') # Value type. -_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. -_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. -_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. -_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. -_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. -_TC = TypeVar('_TC', bound=Type[object]) -_C = TypeVar("_C", bound=Callable[..., Any]) - -no_type_check = object() -def no_type_check_decorator(decorator: _C) -> _C: ... - -# Type aliases and type constructors - -class _Alias: - # Class for defining generic aliases for library types. - def __getitem__(self, typeargs: Any) -> Any: ... - -List = _Alias() -Dict = _Alias() -DefaultDict = _Alias() -Set = _Alias() -FrozenSet = _Alias() -Counter = _Alias() -Deque = _Alias() - -# Predefined type variables. -AnyStr = TypeVar('AnyStr', str, unicode) - -# Abstract base classes. - -def runtime_checkable(cls: _TC) -> _TC: ... - -@runtime_checkable -class SupportsInt(Protocol, metaclass=ABCMeta): - @abstractmethod - def __int__(self) -> int: ... - -@runtime_checkable -class SupportsFloat(Protocol, metaclass=ABCMeta): - @abstractmethod - def __float__(self) -> float: ... - -@runtime_checkable -class SupportsComplex(Protocol, metaclass=ABCMeta): - @abstractmethod - def __complex__(self) -> complex: ... - -@runtime_checkable -class SupportsAbs(Protocol[_T_co]): - @abstractmethod - def __abs__(self) -> _T_co: ... - -@runtime_checkable -class Reversible(Protocol[_T_co]): - @abstractmethod - def __reversed__(self) -> Iterator[_T_co]: ... - -@runtime_checkable -class Sized(Protocol, metaclass=ABCMeta): - @abstractmethod - def __len__(self) -> int: ... - -@runtime_checkable -class Hashable(Protocol, metaclass=ABCMeta): - # TODO: This is special, in that a subclass of a hashable class may not be hashable - # (for example, list vs. object). It's not obvious how to represent this. This class - # is currently mostly useless for static checking. - @abstractmethod - def __hash__(self) -> int: ... - -@runtime_checkable -class Iterable(Protocol[_T_co]): - @abstractmethod - def __iter__(self) -> Iterator[_T_co]: ... - -@runtime_checkable -class Iterator(Iterable[_T_co], Protocol[_T_co]): - @abstractmethod - def next(self) -> _T_co: ... - def __iter__(self) -> Iterator[_T_co]: ... - -class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): - @abstractmethod - def next(self) -> _T_co: ... - - @abstractmethod - def send(self, __value: _T_contra) -> _T_co: ... - - @overload - @abstractmethod - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... - @overload - @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... - - @abstractmethod - def close(self) -> None: ... - @property - def gi_code(self) -> CodeType: ... - @property - def gi_frame(self) -> FrameType: ... - @property - def gi_running(self) -> bool: ... - -@runtime_checkable -class Container(Protocol[_T_co]): - @abstractmethod - def __contains__(self, x: object) -> bool: ... - -class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): - @overload - @abstractmethod - def __getitem__(self, i: int) -> _T_co: ... - @overload - @abstractmethod - def __getitem__(self, s: slice) -> Sequence[_T_co]: ... - # Mixin methods - def index(self, x: Any) -> int: ... - def count(self, x: Any) -> int: ... - def __contains__(self, x: object) -> bool: ... - def __iter__(self) -> Iterator[_T_co]: ... - def __reversed__(self) -> Iterator[_T_co]: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class MutableSequence(Sequence[_T], Generic[_T]): - @abstractmethod - def insert(self, index: int, object: _T) -> None: ... - @overload - @abstractmethod - def __getitem__(self, i: int) -> _T: ... - @overload - @abstractmethod - def __getitem__(self, s: slice) -> MutableSequence[_T]: ... - @overload - @abstractmethod - def __setitem__(self, i: int, o: _T) -> None: ... - @overload - @abstractmethod - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - @overload - @abstractmethod - def __delitem__(self, i: int) -> None: ... - @overload - @abstractmethod - def __delitem__(self, i: slice) -> None: ... - # Mixin methods - def append(self, object: _T) -> None: ... - def extend(self, iterable: Iterable[_T]) -> None: ... - def reverse(self) -> None: ... - def pop(self, index: int = ...) -> _T: ... - def remove(self, object: _T) -> None: ... - def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... - -class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): - @abstractmethod - def __contains__(self, x: object) -> bool: ... - # Mixin methods - def __le__(self, s: AbstractSet[Any]) -> bool: ... - def __lt__(self, s: AbstractSet[Any]) -> bool: ... - def __gt__(self, s: AbstractSet[Any]) -> bool: ... - def __ge__(self, s: AbstractSet[Any]) -> bool: ... - def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... - def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... - # TODO: argument can be any container? - def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - - -class MutableSet(AbstractSet[_T], Generic[_T]): - @abstractmethod - def add(self, x: _T) -> None: ... - @abstractmethod - def discard(self, x: _T) -> None: ... - # Mixin methods - def clear(self) -> None: ... - def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... - def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... - def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - -class MappingView(object): - def __len__(self) -> int: ... - -class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... - -class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_KT_co]: ... - -class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... - def __contains__(self, o: object) -> bool: ... - def __iter__(self) -> Iterator[_VT_co]: ... - -@runtime_checkable -class ContextManager(Protocol[_T_co]): - def __enter__(self) -> _T_co: ... - def __exit__(self, __exc_type: Optional[Type[BaseException]], - __exc_value: Optional[BaseException], - __traceback: Optional[TracebackType]) -> Optional[bool]: ... - -class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): - # TODO: We wish the key type could also be covariant, but that doesn't work, - # see discussion in https: //github.com/python/typing/pull/273. - @abstractmethod - def __getitem__(self, k: _KT) -> _VT_co: - ... - # Mixin methods - @overload - def get(self, k: _KT) -> Optional[_VT_co]: ... - @overload - def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... - def keys(self) -> list[_KT]: ... - def values(self) -> list[_VT_co]: ... - def items(self) -> list[Tuple[_KT, _VT_co]]: ... - def iterkeys(self) -> Iterator[_KT]: ... - def itervalues(self) -> Iterator[_VT_co]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... - def __contains__(self, o: object) -> bool: ... - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - -class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): - @abstractmethod - def __setitem__(self, k: _KT, v: _VT) -> None: ... - @abstractmethod - def __delitem__(self, v: _KT) -> None: ... - - def clear(self) -> None: ... - @overload - def pop(self, k: _KT) -> _VT: ... - @overload - def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - -Text = unicode - -TYPE_CHECKING = True - -class IO(Iterator[AnyStr], Generic[AnyStr]): - # TODO detach - # TODO use abstract properties - @property - def mode(self) -> str: ... - @property - def name(self) -> str: ... - @abstractmethod - def close(self) -> None: ... - @property - def closed(self) -> bool: ... - @abstractmethod - def fileno(self) -> int: ... - @abstractmethod - def flush(self) -> None: ... - @abstractmethod - def isatty(self) -> bool: ... - # TODO what if n is None? - @abstractmethod - def read(self, n: int = ...) -> AnyStr: ... - @abstractmethod - def readable(self) -> bool: ... - @abstractmethod - def readline(self, limit: int = ...) -> AnyStr: ... - @abstractmethod - def readlines(self, hint: int = ...) -> list[AnyStr]: ... - @abstractmethod - def seek(self, offset: int, whence: int = ...) -> int: ... - @abstractmethod - def seekable(self) -> bool: ... - @abstractmethod - def tell(self) -> int: ... - @abstractmethod - def truncate(self, size: Optional[int] = ...) -> int: ... - @abstractmethod - def writable(self) -> bool: ... - # TODO buffer objects - @abstractmethod - def write(self, s: AnyStr) -> int: ... - @abstractmethod - def writelines(self, lines: Iterable[AnyStr]) -> None: ... - - @abstractmethod - def next(self) -> AnyStr: ... - @abstractmethod - def __iter__(self) -> Iterator[AnyStr]: ... - @abstractmethod - def __enter__(self) -> IO[AnyStr]: ... - @abstractmethod - def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], - traceback: Optional[TracebackType]) -> Optional[bool]: ... - -class BinaryIO(IO[str]): - # TODO readinto - # TODO read1? - # TODO peek? - @abstractmethod - def __enter__(self) -> BinaryIO: ... - -class TextIO(IO[unicode]): - # TODO use abstractproperty - @property - def buffer(self) -> BinaryIO: ... - @property - def encoding(self) -> str: ... - @property - def errors(self) -> Optional[str]: ... - @property - def line_buffering(self) -> bool: ... - @property - def newlines(self) -> Any: ... # None, str or tuple - @abstractmethod - def __enter__(self) -> TextIO: ... - -class ByteString(Sequence[int], metaclass=ABCMeta): ... - -class Match(Generic[AnyStr]): - pos: int - endpos: int - lastindex: Optional[int] - string: AnyStr - - # The regular expression object whose match() or search() method produced - # this match instance. This should not be Pattern[AnyStr] because the type - # of the pattern is independent of the type of the matched string in - # Python 2. Strictly speaking Match should be generic over AnyStr twice: - # once for the type of the pattern and once for the type of the matched - # string. - re: Pattern[Any] - # Can be None if there are no groups or if the last group was unnamed; - # otherwise matches the type of the pattern. - lastgroup: Optional[Any] - - def expand(self, template: Union[str, Text]) -> Any: ... - - @overload - def group(self, group1: int = ...) -> AnyStr: ... - @overload - def group(self, group1: str) -> AnyStr: ... - @overload - def group(self, group1: int, group2: int, - *groups: int) -> Tuple[AnyStr, ...]: ... - @overload - def group(self, group1: str, group2: str, - *groups: str) -> Tuple[AnyStr, ...]: ... - - def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... - def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... - def start(self, __group: Union[int, str] = ...) -> int: ... - def end(self, __group: Union[int, str] = ...) -> int: ... - def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... - @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented - -# We need a second TypeVar with the same definition as AnyStr, because -# Pattern is generic over AnyStr (determining the type of its .pattern -# attribute), but at the same time its methods take either bytes or -# Text and return the same type, regardless of the type of the pattern. -_AnyStr2 = TypeVar('_AnyStr2', bytes, Text) - -class Pattern(Generic[AnyStr]): - flags: int - groupindex: Dict[AnyStr, int] - groups: int - pattern: AnyStr - - def search(self, string: _AnyStr2, pos: int = ..., - endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... - def match(self, string: _AnyStr2, pos: int = ..., - endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... - def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... - # Returns either a list of _AnyStr2 or a list of tuples, depending on - # whether there are groups in the pattern. - def findall(self, string: Union[bytes, Text], pos: int = ..., - endpos: int = ...) -> List[Any]: ... - def finditer(self, string: _AnyStr2, pos: int = ..., - endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... - - @overload - def sub(self, repl: _AnyStr2, string: _AnyStr2, - count: int = ...) -> _AnyStr2: ... - @overload - def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, - count: int = ...) -> _AnyStr2: ... - - @overload - def subn(self, repl: _AnyStr2, string: _AnyStr2, - count: int = ...) -> Tuple[_AnyStr2, int]: ... - @overload - def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, - count: int = ...) -> Tuple[_AnyStr2, int]: ... - -# Functions - -def get_type_hints( - obj: Callable[..., Any], globalns: Optional[Dict[Text, Any]] = ..., localns: Optional[Dict[Text, Any]] = ..., -) -> None: ... - -@overload -def cast(tp: Type[_T], obj: Any) -> _T: ... -@overload -def cast(tp: str, obj: Any) -> Any: ... - -# Type constructors - -# NamedTuple is special-cased in the type checker -class NamedTuple(Tuple[Any, ...]): - _fields: Tuple[str, ...] - - def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., - **kwargs: Any) -> None: ... - - @classmethod - def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... - - def _asdict(self) -> Dict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... - -# Internal mypy fallback type for all typed dicts (does not exist at runtime) -class _TypedDict(Mapping[str, object], metaclass=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: ... - 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: ... - -def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... - -# This itself is only available during type checking -def type_check_only(func_or_cls: _C) -> _C: ... diff --git a/mypy/typeshed/stdlib/python2/unittest.pyi b/mypy/typeshed/stdlib/python2/unittest.pyi deleted file mode 100644 index b138216feaf1..000000000000 --- a/mypy/typeshed/stdlib/python2/unittest.pyi +++ /dev/null @@ -1,290 +0,0 @@ -# Stubs for unittest - -# Based on http://docs.python.org/2.7/library/unittest.html - -from typing import (Any, Callable, Dict, FrozenSet, Iterable, Iterator, - List, Mapping, NoReturn, Optional, overload, Pattern, - Sequence, Set, Text, TextIO, Tuple, Type, TypeVar, Union) -from abc import abstractmethod, ABCMeta -import datetime -import types - -_T = TypeVar('_T') -_FT = TypeVar('_FT') - -_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] -_Regexp = Union[Text, Pattern[Text]] - -_SysExcInfoType = Union[ - Tuple[Type[BaseException], BaseException, types.TracebackType], - Tuple[None, None, None], -] - -class Testable(metaclass=ABCMeta): - @abstractmethod - def run(self, result: TestResult) -> None: ... - @abstractmethod - def debug(self) -> None: ... - @abstractmethod - def countTestCases(self) -> int: ... - -# TODO ABC for test runners? - -class TestResult: - errors: List[Tuple[TestCase, str]] - failures: List[Tuple[TestCase, str]] - skipped: List[Tuple[TestCase, str]] - expectedFailures: List[Tuple[TestCase, str]] - unexpectedSuccesses: List[TestCase] - shouldStop: bool - testsRun: int - buffer: bool - failfast: bool - - def wasSuccessful(self) -> bool: ... - def stop(self) -> None: ... - def startTest(self, test: TestCase) -> None: ... - def stopTest(self, test: TestCase) -> None: ... - def startTestRun(self) -> None: ... - def stopTestRun(self) -> None: ... - def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... - def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... - def addSuccess(self, test: TestCase) -> None: ... - def addSkip(self, test: TestCase, reason: str) -> None: ... - def addExpectedFailure(self, test: TestCase, err: str) -> None: ... - def addUnexpectedSuccess(self, test: TestCase) -> None: ... - -class _AssertRaisesBaseContext: - expected: Any - failureException: Type[BaseException] - obj_name: str - expected_regex: Pattern[str] - -class _AssertRaisesContext(_AssertRaisesBaseContext): - exception: Any - def __enter__(self) -> _AssertRaisesContext: ... - def __exit__(self, exc_type, exc_value, tb) -> bool: ... - -class TestCase(Testable): - failureException: Type[BaseException] - longMessage: bool - maxDiff: Optional[int] - # undocumented - _testMethodName: str - def __init__(self, methodName: str = ...) -> None: ... - def setUp(self) -> None: ... - def tearDown(self) -> None: ... - @classmethod - def setUpClass(cls) -> None: ... - @classmethod - def tearDownClass(cls) -> None: ... - def run(self, result: TestResult = ...) -> None: ... - def debug(self) -> None: ... - def assert_(self, expr: Any, msg: object = ...) -> None: ... - def failUnless(self, expr: Any, msg: object = ...) -> None: ... - def assertTrue(self, expr: Any, msg: object = ...) -> None: ... - def assertEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertEquals(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def failUnlessEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertNotEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertNotEquals(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def failIfEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - @overload - def assertAlmostEqual(self, first: float, second: float, - places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertAlmostEqual(self, first: float, second: float, *, - msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertAlmostEqual(self, first: datetime.datetime, - second: datetime.datetime, *, - msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... - @overload - def assertAlmostEquals(self, first: float, second: float, - places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertAlmostEquals(self, first: float, second: float, *, - msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertAlmostEquals(self, first: datetime.datetime, - second: datetime.datetime, *, - msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... - def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., - msg: object = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: float, second: float, - places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: float, second: float, *, - msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: datetime.datetime, - second: datetime.datetime, *, - msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... - @overload - def assertNotAlmostEquals(self, first: float, second: float, - places: int = ..., msg: Any = ...) -> None: ... - @overload - def assertNotAlmostEquals(self, first: float, second: float, *, - msg: Any = ..., delta: float = ...) -> None: ... - @overload - def assertNotAlmostEquals(self, first: datetime.datetime, - second: datetime.datetime, *, - msg: Any = ..., delta: datetime.timedelta = ...) -> None: ... - def failIfAlmostEqual(self, first: float, second: float, places: int = ..., - msg: object = ..., - delta: float = ...) -> None: ... - def assertGreater(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertGreaterEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertMultiLineEqual(self, first: str, second: str, - msg: object = ...) -> None: ... - def assertSequenceEqual(self, first: Sequence[Any], second: Sequence[Any], - msg: object = ..., seq_type: type = ...) -> None: ... - def assertListEqual(self, first: List[Any], second: List[Any], - msg: object = ...) -> None: ... - def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], - msg: object = ...) -> None: ... - def assertSetEqual(self, first: Union[Set[Any], FrozenSet[Any]], - second: Union[Set[Any], FrozenSet[Any]], msg: object = ...) -> None: ... - def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], - msg: object = ...) -> None: ... - def assertLess(self, first: Any, second: Any, - msg: object = ...) -> None: ... - def assertLessEqual(self, first: Any, second: Any, - msg: object = ...) -> None: ... - @overload - def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - @overload - def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... - @overload - def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - @overload - def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... - def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... - def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... - def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... - def assertDictContainsSubset(self, - expected: Mapping[Any, Any], - actual: Mapping[Any, Any], - msg: object = ...) -> None: ... - def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... - @overload - def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... - @overload - def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... - def failIf(self, expr: Any, msg: object = ...) -> None: ... - def assertFalse(self, expr: Any, msg: object = ...) -> None: ... - def assertIs(self, first: object, second: object, - msg: object = ...) -> None: ... - def assertIsNot(self, first: object, second: object, - msg: object = ...) -> None: ... - def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... - def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... - def assertIn(self, first: _T, second: Iterable[_T], - msg: object = ...) -> None: ... - def assertNotIn(self, first: _T, second: Iterable[_T], - msg: object = ...) -> None: ... - def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], - msg: object = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], - msg: object = ...) -> None: ... - def fail(self, msg: object = ...) -> NoReturn: ... - def countTestCases(self) -> int: ... - def defaultTestResult(self) -> TestResult: ... - def id(self) -> str: ... - def shortDescription(self) -> str: ... # May return None - def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... - def doCleanups(self) -> bool: ... - def skipTest(self, reason: Any) -> None: ... - def _formatMessage(self, msg: Optional[Text], standardMsg: Text) -> str: ... # undocumented - def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented - -class FunctionTestCase(TestCase): - def __init__(self, testFunc: Callable[[], None], - setUp: Optional[Callable[[], None]] = ..., - tearDown: Optional[Callable[[], None]] = ..., - description: Optional[str] = ...) -> None: ... - def debug(self) -> None: ... - def countTestCases(self) -> int: ... - -class TestSuite(Testable): - def __init__(self, tests: Iterable[Testable] = ...) -> None: ... - def addTest(self, test: Testable) -> None: ... - def addTests(self, tests: Iterable[Testable]) -> None: ... - def run(self, result: TestResult) -> None: ... - def debug(self) -> None: ... - def countTestCases(self) -> int: ... - def __iter__(self) -> Iterator[Testable]: ... - -class TestLoader: - testMethodPrefix: str - sortTestMethodsUsing: Optional[Callable[[str, str], int]] - suiteClass: Callable[[List[TestCase]], TestSuite] - def loadTestsFromTestCase(self, - testCaseClass: Type[TestCase]) -> TestSuite: ... - def loadTestsFromModule(self, module: types.ModuleType = ..., - use_load_tests: bool = ...) -> TestSuite: ... - def loadTestsFromName(self, name: str = ..., - module: Optional[types.ModuleType] = ...) -> TestSuite: ... - def loadTestsFromNames(self, names: List[str] = ..., - module: Optional[types.ModuleType] = ...) -> TestSuite: ... - def discover(self, start_dir: str, pattern: str = ..., - top_level_dir: Optional[str] = ...) -> TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... - -defaultTestLoader: TestLoader - -class TextTestResult(TestResult): - def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... - def getDescription(self, test: TestCase) -> str: ... # undocumented - def printErrors(self) -> None: ... # undocumented - def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented - -class TextTestRunner: - def __init__(self, stream: Optional[TextIO] = ..., descriptions: bool = ..., - verbosity: int = ..., failfast: bool = ..., buffer: bool = ..., - resultclass: Optional[Type[TestResult]] = ...) -> None: ... - def _makeResult(self) -> TestResult: ... - def run(self, test: Testable) -> TestResult: ... # undocumented - -class SkipTest(Exception): - ... - -# TODO precise types -def skipUnless(condition: Any, reason: Union[str, unicode]) -> Any: ... -def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ... -def expectedFailure(func: _FT) -> _FT: ... -def skip(reason: Union[str, unicode]) -> Any: ... - -# not really documented -class TestProgram: - result: TestResult - def runTests(self) -> None: ... # undocumented - -def main(module: Union[None, Text, types.ModuleType] = ..., defaultTest: Optional[str] = ..., - argv: Optional[Sequence[str]] = ..., - testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ..., - testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., - failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., - buffer: Optional[bool] = ...) -> TestProgram: ... - -def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[Text]) -> TestSuite: ... - -def installHandler() -> None: ... -def registerResult(result: TestResult) -> None: ... -def removeResult(result: TestResult) -> bool: ... -@overload -def removeHandler() -> None: ... -@overload -def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... - -# private but occasionally used -util: types.ModuleType diff --git a/mypy/typeshed/stdlib/python2/urllib.pyi b/mypy/typeshed/stdlib/python2/urllib.pyi deleted file mode 100644 index fe04494897cb..000000000000 --- a/mypy/typeshed/stdlib/python2/urllib.pyi +++ /dev/null @@ -1,134 +0,0 @@ -from typing import Any, AnyStr, IO, List, Mapping, Sequence, Text, Tuple, TypeVar, Union - -def url2pathname(pathname: AnyStr) -> AnyStr: ... -def pathname2url(pathname: AnyStr) -> AnyStr: ... -def urlopen(url: str, data=..., proxies: Mapping[str, str] = ..., context=...) -> IO[Any]: ... -def urlretrieve(url, filename=..., reporthook=..., data=..., context=...): ... -def urlcleanup() -> None: ... - -class ContentTooShortError(IOError): - content: Any - def __init__(self, message, content) -> None: ... - -class URLopener: - version: Any - proxies: Any - key_file: Any - cert_file: Any - context: Any - addheaders: Any - tempcache: Any - ftpcache: Any - def __init__(self, proxies: Mapping[str, str] = ..., context=..., **x509) -> None: ... - def __del__(self): ... - def close(self): ... - def cleanup(self): ... - def addheader(self, *args): ... - type: Any - def open(self, fullurl: str, data=...): ... - def open_unknown(self, fullurl, data=...): ... - def open_unknown_proxy(self, proxy, fullurl, data=...): ... - def retrieve(self, url, filename=..., reporthook=..., data=...): ... - def open_http(self, url, data=...): ... - def http_error(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_default(self, url, fp, errcode, errmsg, headers): ... - def open_https(self, url, data=...): ... - def open_file(self, url): ... - def open_local_file(self, url): ... - def open_ftp(self, url): ... - def open_data(self, url, data=...): ... - -class FancyURLopener(URLopener): - auth_cache: Any - tries: Any - maxtries: Any - def __init__(self, *args, **kwargs) -> None: ... - def http_error_default(self, url, fp, errcode, errmsg, headers): ... - def http_error_302(self, url, fp, errcode, errmsg, headers, data=...): ... - def redirect_internal(self, url, fp, errcode, errmsg, headers, data): ... - def http_error_301(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_303(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_307(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_401(self, url, fp, errcode, errmsg, headers, data=...): ... - def http_error_407(self, url, fp, errcode, errmsg, headers, data=...): ... - def retry_proxy_http_basic_auth(self, url, realm, data=...): ... - def retry_proxy_https_basic_auth(self, url, realm, data=...): ... - def retry_http_basic_auth(self, url, realm, data=...): ... - def retry_https_basic_auth(self, url, realm, data=...): ... - def get_user_passwd(self, host, realm, clear_cache=...): ... - def prompt_user_passwd(self, host, realm): ... - -class ftpwrapper: - user: Any - passwd: Any - host: Any - port: Any - dirs: Any - timeout: Any - refcount: Any - keepalive: Any - def __init__(self, user, passwd, host, port, dirs, timeout=..., persistent=...) -> None: ... - busy: Any - ftp: Any - def init(self): ... - def retrfile(self, file, type): ... - def endtransfer(self): ... - def close(self): ... - def file_close(self): ... - def real_close(self): ... - -_AIUT = TypeVar("_AIUT", bound=addbase) - -class addbase: - fp: Any - def read(self, n: int = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... - def fileno(self) -> int: ... # Optional[int], but that is rare - def __iter__(self: _AIUT) -> _AIUT: ... - def next(self) -> bytes: ... - def __init__(self, fp) -> None: ... - def close(self) -> None: ... - -class addclosehook(addbase): - closehook: Any - hookargs: Any - def __init__(self, fp, closehook, *hookargs) -> None: ... - def close(self): ... - -class addinfo(addbase): - headers: Any - def __init__(self, fp, headers) -> None: ... - def info(self): ... - -class addinfourl(addbase): - headers: Any - url: Any - code: Any - def __init__(self, fp, headers, url, code=...) -> None: ... - def info(self): ... - def getcode(self): ... - def geturl(self): ... - -def unwrap(url): ... -def splittype(url): ... -def splithost(url): ... -def splituser(host): ... -def splitpasswd(user): ... -def splitport(host): ... -def splitnport(host, defport=...): ... -def splitquery(url): ... -def splittag(url): ... -def splitattr(url): ... -def splitvalue(attr): ... -def unquote(s: AnyStr) -> AnyStr: ... -def unquote_plus(s: AnyStr) -> AnyStr: ... -def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... -def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... -def urlencode(query: Union[Sequence[Tuple[Any, Any]], Mapping[Any, Any]], doseq=...) -> str: ... - -def getproxies() -> Mapping[str, str]: ... -def proxy_bypass(host: str) -> Any: ... # Undocumented - -# Names in __all__ with no definition: -# basejoin diff --git a/mypy/typeshed/stdlib/python2/urllib2.pyi b/mypy/typeshed/stdlib/python2/urllib2.pyi deleted file mode 100644 index 6611ad240a96..000000000000 --- a/mypy/typeshed/stdlib/python2/urllib2.pyi +++ /dev/null @@ -1,182 +0,0 @@ - -import ssl -from typing import Any, AnyStr, Dict, List, Union, Optional, Mapping, Callable, Sequence, Text, Tuple, Type -from urllib import addinfourl -from httplib import HTTPConnectionProtocol, HTTPResponse - -_string = Union[str, unicode] - -class URLError(IOError): - reason: Union[str, BaseException] - -class HTTPError(URLError, addinfourl): - code: int - headers: Mapping[str, str] - def __init__(self, url, code: int, msg: str, hdrs: Mapping[str, str], fp: addinfourl) -> None: ... - -class Request(object): - host: str - port: str - data: str - headers: Dict[str, str] - unverifiable: bool - type: Optional[str] - origin_req_host = ... - unredirected_hdrs: Dict[str, str] - - def __init__(self, url: str, data: Optional[str] = ..., headers: Dict[str, str] = ..., - origin_req_host: Optional[str] = ..., unverifiable: bool = ...) -> None: ... - def __getattr__(self, attr): ... - def get_method(self) -> str: ... - def add_data(self, data) -> None: ... - def has_data(self) -> bool: ... - def get_data(self) -> str: ... - def get_full_url(self) -> str: ... - def get_type(self): ... - def get_host(self) -> str: ... - def get_selector(self): ... - def set_proxy(self, host, type) -> None: ... - def has_proxy(self) -> bool: ... - def get_origin_req_host(self) -> str: ... - def is_unverifiable(self) -> bool: ... - def add_header(self, key: str, val: str) -> None: ... - def add_unredirected_header(self, key: str, val: str) -> None: ... - def has_header(self, header_name: str) -> bool: ... - def get_header(self, header_name: str, default: Optional[str] = ...) -> str: ... - def header_items(self): ... - -class OpenerDirector(object): - addheaders: List[Tuple[str, str]] - - def add_handler(self, handler: BaseHandler) -> None: ... - def open(self, fullurl: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ...) -> Optional[addinfourl]: ... - def error(self, proto: _string, *args: Any): ... - -# Note that this type is somewhat a lie. The return *can* be None if -# a custom opener has been installed that fails to handle the request. -def urlopen(url: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ..., - cafile: Optional[_string] = ..., capath: Optional[_string] = ..., cadefault: bool = ..., - context: Optional[ssl.SSLContext] = ...) -> addinfourl: ... -def install_opener(opener: OpenerDirector) -> None: ... -def build_opener(*handlers: Union[BaseHandler, Type[BaseHandler]]) -> OpenerDirector: ... - -class BaseHandler: - handler_order: int - parent: OpenerDirector - - def add_parent(self, parent: OpenerDirector) -> None: ... - def close(self) -> None: ... - def __lt__(self, other: Any) -> bool: ... - -class HTTPErrorProcessor(BaseHandler): - def http_response(self, request, response): ... - -class HTTPDefaultErrorHandler(BaseHandler): - def http_error_default(self, req: Request, fp: addinfourl, code: int, msg: str, hdrs: Mapping[str, str]): ... - -class HTTPRedirectHandler(BaseHandler): - max_repeats: int - max_redirections: int - def redirect_request(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str], newurl): ... - def http_error_301(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_302(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_303(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - def http_error_307(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - inf_msg: str - - -class ProxyHandler(BaseHandler): - proxies: Mapping[str, str] - - def __init__(self, proxies: Optional[Mapping[str, str]] = ...): ... - def proxy_open(self, req: Request, proxy, type): ... - -class HTTPPasswordMgr: - def __init__(self) -> None: ... - def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... - def find_user_password(self, realm: Optional[Text], authuri: Text) -> Tuple[Any, Any]: ... - def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... - def is_suburi(self, base: _string, test: _string) -> bool: ... - -class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... - -class AbstractBasicAuthHandler: - def __init__(self, password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... - def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... - def http_error_auth_reqed(self, authreq, host, req: Request, headers: Mapping[str, str]): ... - def retry_http_basic_auth(self, host, req: Request, realm): ... - -class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - auth_header: str - def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - auth_header: str - def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class AbstractDigestAuthHandler: - def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... - def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... - def reset_retry_count(self) -> None: ... - def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, - headers: Mapping[str, str]) -> None: ... - def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[HTTPResponse]: ... - def get_cnonce(self, nonce: str) -> str: ... - def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... - def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... - def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... - -class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - auth_header: str - handler_order: int - def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - auth_header: str - handler_order: int - def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... - -class AbstractHTTPHandler(BaseHandler): # undocumented - def __init__(self, debuglevel: int = ...) -> None: ... - def set_http_debuglevel(self, level: int) -> None: ... - def do_request_(self, request: Request) -> Request: ... - def do_open(self, - http_class: HTTPConnectionProtocol, - req: Request, - **http_conn_args: Optional[Any]) -> addinfourl: ... - -class HTTPHandler(AbstractHTTPHandler): - def http_open(self, req: Request) -> addinfourl: ... - def http_request(self, request: Request) -> Request: ... # undocumented - -class HTTPSHandler(AbstractHTTPHandler): - def __init__(self, debuglevel: int = ..., context: Optional[ssl.SSLContext] = ...) -> None: ... - def https_open(self, req: Request) -> addinfourl: ... - def https_request(self, request: Request) -> Request: ... # undocumented - -class HTTPCookieProcessor(BaseHandler): - def __init__(self, cookiejar: Optional[Any] = ...): ... - def http_request(self, request: Request): ... - def http_response(self, request: Request, response): ... - -class UnknownHandler(BaseHandler): - def unknown_open(self, req: Request): ... - -class FileHandler(BaseHandler): - def file_open(self, req: Request): ... - def get_names(self): ... - def open_local_file(self, req: Request): ... - -class FTPHandler(BaseHandler): - def ftp_open(self, req: Request): ... - def connect_ftp(self, user, passwd, host, port, dirs, timeout): ... - -class CacheFTPHandler(FTPHandler): - def __init__(self) -> None: ... - def setTimeout(self, t: Optional[float]): ... - def setMaxConns(self, m: int): ... - def check_cache(self): ... - def clear_cache(self): ... - -def parse_http_list(s: AnyStr) -> List[AnyStr]: ... -def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/python2/urlparse.pyi b/mypy/typeshed/stdlib/python2/urlparse.pyi deleted file mode 100644 index 12a04529ad9e..000000000000 --- a/mypy/typeshed/stdlib/python2/urlparse.pyi +++ /dev/null @@ -1,66 +0,0 @@ -# Stubs for urlparse (Python 2) - -from typing import AnyStr, Dict, List, NamedTuple, Tuple, Sequence, Union, overload, Optional - -_String = Union[str, unicode] - -uses_relative: List[str] -uses_netloc: List[str] -uses_params: List[str] -non_hierarchical: List[str] -uses_query: List[str] -uses_fragment: List[str] -scheme_chars: str -MAX_CACHE_SIZE: int - -def clear_cache() -> None: ... - -class ResultMixin(object): - @property - def username(self) -> Optional[_String]: ... - @property - def password(self) -> Optional[_String]: ... - @property - def hostname(self) -> Optional[_String]: ... - @property - def port(self) -> Optional[int]: ... - -class _SplitResult(NamedTuple): - scheme: _String - netloc: _String - path: _String - query: _String - fragment: _String -class SplitResult(_SplitResult, ResultMixin): - def geturl(self) -> _String: ... - -class _ParseResult(NamedTuple): - scheme: _String - netloc: _String - path: _String - params: _String - query: _String - fragment: _String -class ParseResult(_ParseResult, ResultMixin): - def geturl(self) -> _String: ... - -def urlparse(url: _String, scheme: _String = ..., - allow_fragments: bool = ...) -> ParseResult: ... -def urlsplit(url: _String, scheme: _String = ..., - allow_fragments: bool = ...) -> SplitResult: ... -@overload -def urlunparse(data: Tuple[_String, _String, _String, _String, _String, _String]) -> _String: ... -@overload -def urlunparse(data: Sequence[_String]) -> _String: ... -@overload -def urlunsplit(data: Tuple[_String, _String, _String, _String, _String]) -> _String: ... -@overload -def urlunsplit(data: Sequence[_String]) -> _String: ... -def urljoin(base: _String, url: _String, - allow_fragments: bool = ...) -> _String: ... -def urldefrag(url: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def unquote(s: AnyStr) -> AnyStr: ... -def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., - strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... -def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., - strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... diff --git a/mypy/typeshed/stdlib/python2/user.pyi b/mypy/typeshed/stdlib/python2/user.pyi deleted file mode 100644 index e857a3a9516e..000000000000 --- a/mypy/typeshed/stdlib/python2/user.pyi +++ /dev/null @@ -1,9 +0,0 @@ -# Stubs for user (Python 2) - -# Docs: https://docs.python.org/2/library/user.html -# Source: https://hg.python.org/cpython/file/2.7/Lib/user.py -from typing import Any - -def __getattr__(name) -> Any: ... -home: str -pythonrc: str diff --git a/mypy/typeshed/stdlib/python2/whichdb.pyi b/mypy/typeshed/stdlib/python2/whichdb.pyi deleted file mode 100644 index b1a69f4816c4..000000000000 --- a/mypy/typeshed/stdlib/python2/whichdb.pyi +++ /dev/null @@ -1,5 +0,0 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/whichdb.py - -from typing import Optional, Text - -def whichdb(filename: Text) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/python2/xmlrpclib.pyi deleted file mode 100644 index d1d293718dae..000000000000 --- a/mypy/typeshed/stdlib/python2/xmlrpclib.pyi +++ /dev/null @@ -1,231 +0,0 @@ -# Stubs for xmlrpclib (Python 2) - -from typing import Any, AnyStr, Callable, IO, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, TypeVar, Union -from types import InstanceType -from datetime import datetime -from time import struct_time -from httplib import HTTPConnection, HTTPResponse, HTTPSConnection -from ssl import SSLContext -from StringIO import StringIO -from gzip import GzipFile - -_Unmarshaller = Any -_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] -# Represents types that can be compared against a DateTime object -_dateTimeComp = Union[unicode, DateTime, datetime] -# A "host description" used by Transport factories -_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] - -def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... - -MAXINT: int -MININT: int -PARSE_ERROR: int -SERVER_ERROR: int -APPLICATION_ERROR: int -SYSTEM_ERROR: int -TRANSPORT_ERROR: int -NOT_WELLFORMED_ERROR: int -UNSUPPORTED_ENCODING: int -INVALID_ENCODING_CHAR: int -INVALID_XMLRPC: int -METHOD_NOT_FOUND: int -INVALID_METHOD_PARAMS: int -INTERNAL_ERROR: int - -class Error(Exception): ... - -class ProtocolError(Error): - url: str - errcode: int - errmsg: str - headers: Any - def __init__(self, url: str, errcode: int, errmsg: str, headers: Any) -> None: ... - -class ResponseError(Error): ... - -class Fault(Error): - faultCode: Any - faultString: str - def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... - -boolean: Type[bool] -Boolean: Type[bool] - -class DateTime: - value: str - def __init__(self, value: Union[str, unicode, datetime, float, int, _timeTuple, struct_time] = ...) -> None: ... - def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... - def __lt__(self, other: _dateTimeComp) -> bool: ... - def __le__(self, other: _dateTimeComp) -> bool: ... - def __gt__(self, other: _dateTimeComp) -> bool: ... - def __ge__(self, other: _dateTimeComp) -> bool: ... - def __eq__(self, other: _dateTimeComp) -> bool: ... # type: ignore - def __ne__(self, other: _dateTimeComp) -> bool: ... # type: ignore - def timetuple(self) -> struct_time: ... - def __cmp__(self, other: _dateTimeComp) -> int: ... - def decode(self, data: Any) -> None: ... - def encode(self, out: IO[str]) -> None: ... - -class Binary: - data: str - def __init__(self, data: Optional[str] = ...) -> None: ... - def __cmp__(self, other: Any) -> int: ... - def decode(self, data: str) -> None: ... - def encode(self, out: IO[str]) -> None: ... - -WRAPPERS: Tuple[Type[Any], ...] - -# Still part of the public API, but see http://bugs.python.org/issue1773632 -FastParser: None -FastUnmarshaller: None -FastMarshaller: None - -# xmlrpclib.py will leave ExpatParser undefined if it can't import expat from -# xml.parsers. Because this is Python 2.7, the import will succeed. -class ExpatParser: - def __init__(self, target: _Unmarshaller) -> None: ... - def feed(self, data: str): ... - def close(self): ... - -# TODO: Add xmllib.XMLParser as base class -class SlowParser: - handle_xml: Callable[[str, bool], None] - unknown_starttag: Callable[[str, Any], None] - handle_data: Callable[[str], None] - handle_cdata: Callable[[str], None] - unknown_endtag: Callable[[str, Callable[[Iterable[str], str], str]], None] - def __init__(self, target: _Unmarshaller) -> None: ... - -class Marshaller: - memo: MutableMapping[int, Any] - data: Optional[str] - encoding: Optional[str] - allow_none: bool - def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... - dispatch: Mapping[type, Callable[[Marshaller, str, Callable[[str], None]], None]] - def dumps( - self, - values: Union[ - Iterable[ - Union[ - None, - int, - bool, - long, - float, - str, - unicode, - List[Any], - Tuple[Any, ...], - Mapping[Any, Any], - datetime, - InstanceType, - ], - ], - Fault, - ], - ) -> str: ... - def dump_nil(self, value: None, write: Callable[[str], None]) -> None: ... - def dump_int(self, value: int, write: Callable[[str], None]) -> None: ... - def dump_bool(self, value: bool, write: Callable[[str], None]) -> None: ... - def dump_long(self, value: long, write: Callable[[str], None]) -> None: ... - def dump_double(self, value: float, write: Callable[[str], None]) -> None: ... - def dump_string(self, value: str, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... - def dump_unicode(self, value: unicode, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... - def dump_array(self, value: Iterable[Any], write: Callable[[str], None]) -> None: ... - def dump_struct( - self, - value: Mapping[unicode, Any], - write: Callable[[str], None], - escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., - ) -> None: ... - def dump_datetime(self, value: datetime, write: Callable[[str], None]) -> None: ... - def dump_instance(self, value: InstanceType, write: Callable[[str], None]) -> None: ... - -class Unmarshaller: - def append(self, object: Any) -> None: ... - def __init__(self, use_datetime: bool = ...) -> None: ... - def close(self) -> Tuple[Any, ...]: ... - def getmethodname(self) -> Optional[str]: ... - def xml(self, encoding: str, standalone: bool) -> None: ... - def start(self, tag: str, attrs: Any) -> None: ... - def data(self, text: str) -> None: ... - def end(self, tag: str, join: Callable[[Iterable[str], str], str] = ...) -> None: ... - def end_dispatch(self, tag: str, data: str) -> None: ... - dispatch: Mapping[str, Callable[[Unmarshaller, str], None]] - def end_nil(self, data: str): ... - def end_boolean(self, data: str) -> None: ... - def end_int(self, data: str) -> None: ... - def end_double(self, data: str) -> None: ... - def end_string(self, data: str) -> None: ... - def end_array(self, data: str) -> None: ... - def end_struct(self, data: str) -> None: ... - def end_base64(self, data: str) -> None: ... - def end_dateTime(self, data: str) -> None: ... - def end_value(self, data: str) -> None: ... - def end_params(self, data: str) -> None: ... - def end_fault(self, data: str) -> None: ... - def end_methodName(self, data: str) -> None: ... - -class _MultiCallMethod: - def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... -class MultiCallIterator: - def __init__(self, results: List[Any]) -> None: ... - -class MultiCall: - def __init__(self, server: ServerProxy) -> None: ... - def __getattr__(self, name: str) -> _MultiCallMethod: ... - def __call__(self) -> MultiCallIterator: ... - -def getparser(use_datetime: bool = ...) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... -def dumps( - params: Union[Tuple[Any, ...], Fault], - methodname: Optional[str] = ..., - methodresponse: Optional[bool] = ..., - encoding: Optional[str] = ..., - allow_none: bool = ..., -) -> str: ... -def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], Optional[str]]: ... - -def gzip_encode(data: str) -> str: ... -def gzip_decode(data: str, max_decode: int = ...) -> str: ... - -class GzipDecodedResponse(GzipFile): - stringio: StringIO[Any] - def __init__(self, response: HTTPResponse) -> None: ... - def close(self): ... - -class _Method: - def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... - def __getattr__(self, name: str) -> _Method: ... - def __call__(self, *args: Any) -> Any: ... - -class Transport: - user_agent: str - accept_gzip_encoding: bool - encode_threshold: Optional[int] - def __init__(self, use_datetime: bool = ...) -> None: ... - def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... - verbose: bool - def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... - def getparser(self) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... - def get_host_info(self, host: _hostDesc) -> Tuple[str, Optional[List[Tuple[str, str]]], Optional[Mapping[Any, Any]]]: ... - def make_connection(self, host: _hostDesc) -> HTTPConnection: ... - def close(self) -> None: ... - def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... - def send_host(self, connection: HTTPConnection, host: str) -> None: ... - def send_user_agent(self, connection: HTTPConnection) -> None: ... - def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... - def parse_response(self, response: HTTPResponse) -> Tuple[Any, ...]: ... - -class SafeTransport(Transport): - def __init__(self, use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... - def make_connection(self, host: _hostDesc) -> HTTPSConnection: ... - -class ServerProxy: - def __init__(self, uri: str, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... - def __getattr__(self, name: str) -> _Method: ... - def __call__(self, attr: str) -> Optional[Transport]: ... - -Server = ServerProxy diff --git a/mypy/typeshed/stdlib/queue.pyi b/mypy/typeshed/stdlib/queue.pyi index ba995e743dee..82fde5989d34 100644 --- a/mypy/typeshed/stdlib/queue.pyi +++ b/mypy/typeshed/stdlib/queue.pyi @@ -1,12 +1,11 @@ -# Stubs for queue - -# NOTE: These are incomplete! - -from threading import Condition, Lock -from typing import Any, TypeVar, Generic, Optional import sys +from threading import Condition, Lock +from typing import Any, Generic, Optional, TypeVar + +if sys.version_info >= (3, 9): + from types import GenericAlias -_T = TypeVar('_T') +_T = TypeVar("_T") class Empty(Exception): ... class Full(Exception): ... @@ -20,7 +19,6 @@ class Queue(Generic[_T]): all_tasks_done: Condition # undocumented unfinished_tasks: int # undocumented queue: Any # undocumented - def __init__(self, maxsize: int = ...) -> None: ... def _init(self, maxsize: int) -> None: ... def empty(self) -> bool: ... @@ -35,6 +33,8 @@ class Queue(Generic[_T]): def qsize(self) -> int: ... def _qsize(self) -> int: ... def task_done(self) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class PriorityQueue(Queue[_T]): ... class LifoQueue(Queue[_T]): ... @@ -48,3 +48,5 @@ if sys.version_info >= (3, 7): def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... def put_nowait(self, item: _T) -> None: ... def qsize(self) -> int: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/quopri.pyi b/mypy/typeshed/stdlib/quopri.pyi index 2823f8c40b53..c2ffabe7d531 100644 --- a/mypy/typeshed/stdlib/quopri.pyi +++ b/mypy/typeshed/stdlib/quopri.pyi @@ -1,5 +1,3 @@ -# Stubs for quopri (Python 2 and 3) - from typing import BinaryIO def encode(input: BinaryIO, output: BinaryIO, quotetabs: int, header: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index fab7770a4dd9..9a28024c2c39 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -1,16 +1,8 @@ -# Stubs for random -# Ron Murawski -# Updated by Jukka Lehtosalo - -# based on http://docs.python.org/3.2/library/random.html - -# ----- random classes ----- - import _random import sys -from typing import Any, TypeVar, Sequence, Iterable, List, Callable, AbstractSet, Union, Optional, Tuple +from typing import AbstractSet, Any, Callable, Iterable, List, MutableSequence, Optional, Sequence, Tuple, TypeVar, Union -_T = TypeVar('_T') +_T = TypeVar("_T") class Random(_random.Random): def __init__(self, x: Any = ...) -> None: ... @@ -18,16 +10,24 @@ class Random(_random.Random): def getstate(self) -> Tuple[Any, ...]: ... def setstate(self, state: Tuple[Any, ...]) -> None: ... def getrandbits(self, __k: int) -> int: ... - def randrange(self, start: int, stop: Union[int, None] = ..., step: int = ...) -> int: ... + def randrange(self, start: int, stop: Optional[int] = ..., step: int = ...) -> int: ... def randint(self, a: int, b: int) -> int: ... if sys.version_info >= (3, 9): def randbytes(self, n: int) -> bytes: ... def choice(self, seq: Sequence[_T]) -> _T: ... - if sys.version_info >= (3, 6): - def choices(self, population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... - def shuffle(self, x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... + def choices( + self, + population: Sequence[_T], + weights: Optional[Sequence[float]] = ..., + *, + cum_weights: Optional[Sequence[float]] = ..., + k: int = ..., + ) -> List[_T]: ... + def shuffle(self, x: MutableSequence[Any], random: Optional[Callable[[], float]] = ...) -> None: ... if sys.version_info >= (3, 9): - def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> List[_T]: ... + def sample( + self, population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ... + ) -> List[_T]: ... else: def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... def random(self) -> float: ... @@ -44,8 +44,7 @@ class Random(_random.Random): def weibullvariate(self, alpha: float, beta: float) -> float: ... # SystemRandom is not implemented for all OS's; good on Windows & Linux -class SystemRandom(Random): - ... +class SystemRandom(Random): ... # ----- random function stubs ----- def seed(a: Any = ..., version: int = ...) -> None: ... @@ -54,20 +53,29 @@ def setstate(state: object) -> None: ... def getrandbits(__k: int) -> int: ... def randrange(start: int, stop: Union[None, int] = ..., step: int = ...) -> int: ... def randint(a: int, b: int) -> int: ... + if sys.version_info >= (3, 9): def randbytes(n: int) -> bytes: ... + def choice(seq: Sequence[_T]) -> _T: ... -if sys.version_info >= (3, 6): - def choices(population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... -def shuffle(x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... +def choices( + population: Sequence[_T], + weights: Optional[Sequence[float]] = ..., + *, + cum_weights: Optional[Sequence[float]] = ..., + k: int = ..., +) -> List[_T]: ... +def shuffle(x: MutableSequence[Any], random: Optional[Callable[[], float]] = ...) -> None: ... + if sys.version_info >= (3, 9): def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> List[_T]: ... + else: def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def random() -> float: ... def uniform(a: float, b: float) -> float: ... -def triangular(low: float = ..., high: float = ..., - mode: Optional[float] = ...) -> float: ... +def triangular(low: float = ..., high: float = ..., mode: Optional[float] = ...) -> float: ... def betavariate(alpha: float, beta: float) -> float: ... def expovariate(lambd: float) -> float: ... def gammavariate(alpha: float, beta: float) -> float: ... diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index bfab4819a78c..264174440956 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,62 +1,14 @@ -# Stubs for re -# Ron Murawski -# 'bytes' support added by Jukka Lehtosalo - -# based on: http://docs.python.org/3.2/library/re.html -# and http://hg.python.org/cpython/file/618ea5612e83/Lib/re.py - +import enum import sys -from typing import ( - List, Iterator, overload, Callable, Tuple, - AnyStr, Any, Optional, Union -) +from typing import Any, AnyStr, Callable, Iterator, List, Optional, Tuple, Union, overload # ----- re variables and constants ----- if sys.version_info >= (3, 7): - from typing import Pattern as Pattern, Match as Match + from typing import Match as Match, Pattern as Pattern else: - from typing import Pattern, Match + from typing import Match, Pattern -if sys.version_info >= (3, 6): - import enum - class RegexFlag(enum.IntFlag): - A: int - ASCII: int - DEBUG: int - I: int - IGNORECASE: int - L: int - LOCALE: int - M: int - MULTILINE: int - S: int - DOTALL: int - X: int - VERBOSE: int - U: int - UNICODE: int - T: int - TEMPLATE: int - - A = RegexFlag.A - ASCII = RegexFlag.ASCII - DEBUG = RegexFlag.DEBUG - I = RegexFlag.I - IGNORECASE = RegexFlag.IGNORECASE - L = RegexFlag.L - LOCALE = RegexFlag.LOCALE - M = RegexFlag.M - MULTILINE = RegexFlag.MULTILINE - S = RegexFlag.S - DOTALL = RegexFlag.DOTALL - X = RegexFlag.X - VERBOSE = RegexFlag.VERBOSE - U = RegexFlag.U - UNICODE = RegexFlag.UNICODE - T = RegexFlag.T - TEMPLATE = RegexFlag.TEMPLATE - _FlagsType = Union[int, RegexFlag] -else: +class RegexFlag(enum.IntFlag): A: int ASCII: int DEBUG: int @@ -74,24 +26,45 @@ else: UNICODE: int T: int TEMPLATE: int - _FlagsType = int + +A = RegexFlag.A +ASCII = RegexFlag.ASCII +DEBUG = RegexFlag.DEBUG +I = RegexFlag.I +IGNORECASE = RegexFlag.IGNORECASE +L = RegexFlag.L +LOCALE = RegexFlag.LOCALE +M = RegexFlag.M +MULTILINE = RegexFlag.MULTILINE +S = RegexFlag.S +DOTALL = RegexFlag.DOTALL +X = RegexFlag.X +VERBOSE = RegexFlag.VERBOSE +U = RegexFlag.U +UNICODE = RegexFlag.UNICODE +T = RegexFlag.T +TEMPLATE = RegexFlag.TEMPLATE +_FlagsType = Union[int, RegexFlag] if sys.version_info < (3, 7): # undocumented _pattern_type: type -class error(Exception): ... +class error(Exception): + msg: str + pattern: str + pos: Optional[int] + lineno: Optional[int] + colno: Optional[int] @overload def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... @overload def compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... - @overload def search(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... @overload def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... - @overload def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... @overload @@ -102,14 +75,10 @@ def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... @overload def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... - @overload -def split(pattern: AnyStr, string: AnyStr, - maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... +def split(pattern: AnyStr, string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... @overload -def split(pattern: Pattern[AnyStr], string: AnyStr, - maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... - +def split(pattern: Pattern[AnyStr], string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... @overload def findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> List[Any]: ... @overload @@ -120,41 +89,35 @@ def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) - # matches are returned in the order found. Empty matches are included in the # result unless they touch the beginning of another match. @overload -def finditer(pattern: AnyStr, string: AnyStr, - flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +def finditer(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... @overload -def finditer(pattern: Pattern[AnyStr], string: AnyStr, - flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... - +def finditer(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... @overload -def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> AnyStr: ... +def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... @overload -def sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... +def sub( + pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... +) -> AnyStr: ... @overload -def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> AnyStr: ... +def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... @overload -def sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... - +def sub( + pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... +) -> AnyStr: ... @overload -def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... @overload -def subn(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +def subn( + pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... +) -> Tuple[AnyStr, int]: ... @overload -def subn(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +def subn( + pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ... +) -> Tuple[AnyStr, int]: ... @overload -def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], - string: AnyStr, count: int = ..., - flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... - +def subn( + pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... +) -> Tuple[AnyStr, int]: ... def escape(pattern: AnyStr) -> AnyStr: ... - def purge() -> None: ... def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index aff2debf266a..9b8e05f09942 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,26 +1,22 @@ -# Stubs for readline - -from typing import Callable, Optional, Sequence import sys +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: str = ...) -> None: ... - def get_line_buffer() -> str: ... def insert_text(string: str) -> None: ... def redisplay() -> None: ... - def read_history_file(filename: str = ...) -> None: ... def write_history_file(filename: str = ...) -> None: ... + if sys.version_info >= (3, 5): def append_history_file(nelements: int, filename: str = ...) -> 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: ... @@ -28,9 +24,11 @@ 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_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: ... diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 7ff879bc7704..39828ffc9f29 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -1,5 +1,3 @@ -# Stubs for reprlib (Python 3) - from array import array from typing import Any, Callable, Deque, Dict, FrozenSet, List, Set, Tuple @@ -34,4 +32,5 @@ class Repr: def repr_instance(self, x: Any, level: int) -> str: ... aRepr: Repr + def repr(x: object) -> str: ... diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 280b581d0291..38e28898a1e4 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -1,7 +1,5 @@ -# Stubs for resource - import sys -from typing import Tuple, Optional, NamedTuple +from typing import NamedTuple, Tuple, overload RLIMIT_AS: int RLIMIT_CORE: int @@ -47,7 +45,11 @@ def getpagesize() -> int: ... def getrlimit(__resource: int) -> Tuple[int, int]: ... def getrusage(__who: int) -> _RUsage: ... def setrlimit(__resource: int, __limits: Tuple[int, int]) -> None: ... + if sys.platform == "linux": - def prlimit(pid: int, resource: int, limits: Optional[Tuple[int, int]]) -> Tuple[int, int]: ... + @overload + def prlimit(pid: int, resource: int, limits: Tuple[int, int]) -> Tuple[int, int]: ... + @overload + def prlimit(pid: int, resource: int) -> Tuple[int, int]: ... error = OSError diff --git a/mypy/typeshed/stdlib/rlcompleter.pyi b/mypy/typeshed/stdlib/rlcompleter.pyi index 3db9d0c40799..3733cc13110c 100644 --- a/mypy/typeshed/stdlib/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/rlcompleter.pyi @@ -1,14 +1,11 @@ -# Stubs for rlcompleter - -from typing import Any, Dict, Optional, Union import sys +from typing import Any, Dict, Optional, Union if sys.version_info >= (3,): _Text = str else: _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/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi index 654c53c8ebb3..e27849d9c480 100644 --- a/mypy/typeshed/stdlib/runpy.pyi +++ b/mypy/typeshed/stdlib/runpy.pyi @@ -1,23 +1,22 @@ from types import ModuleType -from typing import Dict, Optional, Any +from typing import Any, Dict, Optional, TypeVar + +_T = TypeVar("_T") class _TempModule: mod_name: str = ... module: ModuleType = ... - def __init__(self, mod_name): ... - def __enter__(self): ... - def __exit__(self, *args): ... + def __init__(self, mod_name: str) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, *args: Any) -> None: ... class _ModifiedArgv0: value: Any = ... - def __init__(self, value): ... - def __enter__(self): ... - def __exit__(self, *args): ... + def __init__(self, value: Any) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, *args: Any) -> None: ... -def run_module(mod_name: str, - init_globals: Optional[Dict[str, Any]] = ..., - run_name: Optional[str] = ..., - alter_sys: bool = ...): ... -def run_path(path_name: str, - init_globals: Optional[Dict[str, Any]] = ..., - run_name: str = ...): ... +def run_module( + mod_name: str, init_globals: Optional[Dict[str, Any]] = ..., run_name: Optional[str] = ..., alter_sys: bool = ... +) -> None: ... +def run_path(path_name: str, init_globals: Optional[Dict[str, Any]] = ..., run_name: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index 6a820c836ae9..21d81e16ec60 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -11,15 +11,28 @@ class Event(NamedTuple): 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 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 cancel(self, event: Event) -> None: ... def empty(self) -> bool: ... @property diff --git a/mypy/typeshed/stdlib/secrets.pyi b/mypy/typeshed/stdlib/secrets.pyi index 5069dba25c67..84b2fea8379a 100644 --- a/mypy/typeshed/stdlib/secrets.pyi +++ b/mypy/typeshed/stdlib/secrets.pyi @@ -1,10 +1,8 @@ -# Stubs for secrets (Python 3.6) - -from typing import Optional, Sequence, TypeVar from hmac import compare_digest as compare_digest from random import SystemRandom as SystemRandom +from typing import Optional, Sequence, TypeVar -_T = TypeVar('_T') +_T = TypeVar("_T") def randbelow(exclusive_upper_bound: int) -> int: ... def randbits(k: int) -> int: ... diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index 697e867b419d..e0cf3bdd4d75 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -1,8 +1,7 @@ import sys -from typing import Any, Iterable, List, Optional, Tuple, Type -from types import TracebackType from _typeshed import FileDescriptorLike - +from types import TracebackType +from typing import Any, Iterable, List, Optional, Tuple, Type if sys.platform != "win32": PIPE_BUF: int @@ -25,8 +24,9 @@ class poll: 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]]: ... +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 @@ -42,18 +42,26 @@ if sys.platform != "linux" and sys.platform != "win32": flags: int ident: int udata: Any - def __init__(self, ident: FileDescriptorLike, filter: int = ..., flags: int = ..., fflags: int = ..., data: Any = ..., udata: Any = ...) -> None: ... - + 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 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 @@ -101,7 +109,12 @@ if sys.platform == "linux": 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 __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: ... @@ -111,7 +124,6 @@ if sys.platform == "linux": 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 diff --git a/mypy/typeshed/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi index 9f55e853f61e..b019c4f9c442 100644 --- a/mypy/typeshed/stdlib/selectors.pyi +++ b/mypy/typeshed/stdlib/selectors.pyi @@ -1,7 +1,7 @@ import sys +from _typeshed import FileDescriptor, FileDescriptorLike from abc import ABCMeta, abstractmethod from typing import Any, List, Mapping, NamedTuple, Optional, Tuple -from _typeshed import FileDescriptor, FileDescriptorLike _EventMask = int @@ -17,24 +17,16 @@ class SelectorKey(NamedTuple): class BaseSelector(metaclass=ABCMeta): @abstractmethod def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - @abstractmethod def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... - @abstractmethod def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... - def close(self) -> None: ... - def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - @abstractmethod def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... - def __enter__(self) -> BaseSelector: ... - def __exit__(self, *args: Any) -> None: ... class SelectSelector(BaseSelector): @@ -44,13 +36,11 @@ class SelectSelector(BaseSelector): def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... if sys.platform != "win32": - class PollSelector(BaseSelector): def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... - class EpollSelector(BaseSelector): def fileno(self) -> int: ... def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index 97a045e0e849..bbbd72e44b24 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,9 +1,10 @@ -from typing import Any, Dict, Iterator, Optional, Tuple import collections - +from typing import Any, Dict, Iterator, Optional, Tuple class Shelf(collections.MutableMapping[Any, Any]): - def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __init__( + self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ... + ) -> None: ... def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... def __contains__(self, key: Any) -> bool: ... # key should be str, but it would conflict with superclass's type signature @@ -18,7 +19,9 @@ class Shelf(collections.MutableMapping[Any, Any]): def sync(self) -> None: ... class BsdDbShelf(Shelf): - def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __init__( + self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ... + ) -> None: ... def set_location(self, key: Any) -> Tuple[str, Any]: ... def next(self) -> Tuple[str, Any]: ... def previous(self) -> Tuple[str, Any]: ... diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index 51ed42d94172..0eb89d33cc8b 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,12 +1,14 @@ -from typing import List, Tuple, Any, TextIO, Union, Optional, Iterable, TypeVar import sys +from typing import Any, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union def split(s: str, comments: bool = ..., posix: bool = ...) -> List[str]: ... + if sys.version_info >= (3, 8): def join(split_command: Iterable[str]) -> str: ... + def quote(s: str) -> str: ... -_SLT = TypeVar('_SLT', bound=shlex) +_SLT = TypeVar("_SLT", bound=shlex) class shlex(Iterable[str]): commenters: str @@ -23,15 +25,14 @@ class shlex(Iterable[str]): lineno: int token: str eof: str - if sys.version_info >= (3, 6): - punctuation_chars: str - - if sys.version_info >= (3, 6): - def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., - posix: bool = ..., punctuation_chars: Union[bool, str] = ...) -> None: ... - else: - def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., - posix: bool = ...) -> None: ... + punctuation_chars: str + def __init__( + self, + instream: Union[str, TextIO] = ..., + infile: Optional[str] = ..., + posix: bool = ..., + punctuation_chars: Union[bool, str] = ..., + ) -> None: ... def get_token(self) -> str: ... def push_token(self, tok: str) -> None: ... def read_token(self) -> str: ... @@ -39,7 +40,6 @@ class shlex(Iterable[str]): # TODO argument types def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... def pop_source(self) -> None: ... - def error_leader(self, infile: str = ..., - lineno: int = ...) -> None: ... + def error_leader(self, infile: str = ..., lineno: int = ...) -> None: ... def __iter__(self: _SLT) -> _SLT: ... def __next__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 780a52e3cb79..b814112a175a 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,11 +1,22 @@ import os import sys - +from _typeshed import StrPath, SupportsRead, SupportsWrite from typing import ( - List, Iterable, Callable, Any, Tuple, Sequence, NamedTuple, - AnyStr, Optional, Union, Set, TypeVar, overload, Type, Text + Any, + AnyStr, + Callable, + Iterable, + List, + NamedTuple, + Optional, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + overload, ) -from _typeshed import StrPath, SupportsRead, SupportsWrite if sys.version_info >= (3, 6): _AnyStr = str @@ -29,25 +40,21 @@ if sys.version_info >= (3,): class ExecError(OSError): ... class ReadError(OSError): ... class RegistryError(Exception): ... + else: class Error(EnvironmentError): ... class SpecialFileError(EnvironmentError): ... class ExecError(EnvironmentError): ... -def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], - length: int = ...) -> None: ... +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: ... + 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: ... + else: def copyfile(src: StrPath, dst: StrPath) -> None: ... def copymode(src: StrPath, dst: StrPath) -> None: ... @@ -67,35 +74,44 @@ if sys.version_info >= (3, 8): ignore_dangling_symlinks: bool = ..., dirs_exist_ok: bool = ..., ) -> _PathReturn: ... + elif sys.version_info >= (3,): - def copytree(src: StrPath, dst: StrPath, symlinks: bool = ..., - ignore: Union[None, - Callable[[str, List[str]], Iterable[str]], - Callable[[StrPath, List[str]], Iterable[str]]] = ..., - copy_function: Callable[[str, str], None] = ..., - ignore_dangling_symlinks: bool = ...) -> _PathReturn: ... + def copytree( + src: StrPath, + dst: StrPath, + symlinks: bool = ..., + ignore: Union[None, Callable[[str, List[str]], Iterable[str]], Callable[[StrPath, List[str]], Iterable[str]]] = ..., + copy_function: Callable[[str, str], None] = ..., + ignore_dangling_symlinks: bool = ..., + ) -> _PathReturn: ... + else: - def copytree(src: AnyStr, dst: AnyStr, symlinks: bool = ..., - ignore: Union[None, - Callable[[AnyStr, List[AnyStr]], - Iterable[AnyStr]]] = ...) -> _PathReturn: ... + 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: ... + 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: _AnyPath, ignore_errors: bool = ..., onerror: Optional[Callable[[Any, _AnyPath, 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: ... + def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... + elif sys.version_info >= (3, 5): # See https://bugs.python.org/issue32689 - def move(src: str, dst: StrPath, - copy_function: _CopyFn = ...) -> _PathReturn: ... + def move(src: str, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... + else: def move(src: StrPath, dst: StrPath) -> _PathReturn: ... @@ -105,39 +121,46 @@ if sys.version_info >= (3,): used: int free: int def disk_usage(path: StrPath) -> _ntuple_diskusage: ... - def chown(path: StrPath, user: Optional[str] = ..., - group: Optional[str] = ...) -> None: ... + def chown(path: StrPath, user: Optional[Union[str, int]] = ..., group: Optional[Union[str, int]] = ...) -> None: ... + if sys.version_info >= (3, 8): @overload def which(cmd: StrPath, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[str]: ... @overload def which(cmd: bytes, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[bytes]: ... + elif sys.version_info >= (3,): def which(cmd: StrPath, mode: int = ..., path: Optional[StrPath] = ...) -> Optional[str]: ... -def make_archive(base_name: _AnyStr, format: str, root_dir: Optional[StrPath] = ..., - base_dir: Optional[StrPath] = ..., verbose: bool = ..., - dry_run: bool = ..., owner: Optional[str] = ..., group: Optional[str] = ..., - logger: Optional[Any] = ...) -> _AnyStr: ... +def make_archive( + base_name: _AnyStr, + format: str, + root_dir: Optional[StrPath] = ..., + base_dir: Optional[StrPath] = ..., + 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 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: ... if sys.version_info >= (3,): if sys.version_info >= (3, 7): - def unpack_archive(filename: StrPath, extract_dir: Optional[StrPath] = ..., - format: Optional[str] = ...) -> None: ... + 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: Sequence[Tuple[str, Any]] = ..., - description: str = ...) -> None: ... + 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: 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/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 26fa36f5b23b..53d8caaca471 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -1,13 +1,10 @@ -"""Stub file for the 'signal' module.""" - import sys from enum import IntEnum -from typing import Any, Callable, Tuple, Union, Optional, Iterable, Set from types import FrameType +from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union if sys.platform != "win32": class ItimerError(IOError): ... - ITIMER_PROF: int ITIMER_REAL: int ITIMER_VIRTUAL: int @@ -78,13 +75,12 @@ if sys.platform != "win32": SIG_BLOCK: int SIG_UNBLOCK: int SIG_SETMASK: int - SIG_BLOCK = Sigmasks.SIG_BLOCK SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK SIG_SETMASK = Sigmasks.SIG_SETMASK _SIGNUM = Union[int, Signals] -_HANDLER = Union[Callable[[Signals, FrameType], None], int, Handlers, None] +_HANDLER = Union[Callable[[Signals, FrameType], Any], int, Handlers, None] SIGABRT: Signals if sys.platform != "win32": @@ -161,23 +157,36 @@ if sys.platform != "win32": if sys.platform != "win32": def alarm(__seconds: int) -> int: ... + def default_int_handler(signum: int, frame: FrameType) -> None: ... + if sys.platform != "win32": def getitimer(__which: int) -> Tuple[float, float]: ... + def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... + if sys.version_info >= (3, 8): def strsignal(__signalnum: _SIGNUM) -> Optional[str]: ... def valid_signals() -> Set[Signals]: ... def raise_signal(__signalnum: _SIGNUM) -> None: ... + if sys.platform != "win32": def pause() -> None: ... def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... def pthread_sigmask(__how: int, __mask: Iterable[int]) -> Set[_SIGNUM]: ... -def set_wakeup_fd(fd: int) -> int: ... + +if sys.version_info >= (3, 7): + def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... + +else: + def set_wakeup_fd(fd: int) -> int: ... + if sys.platform != "win32": def setitimer(__which: int, __seconds: float, __interval: float = ...) -> Tuple[float, float]: ... def siginterrupt(__signalnum: int, __flag: bool) -> None: ... + def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... + if sys.platform != "win32": def sigpending() -> Any: ... def sigtimedwait(sigset: Iterable[int], timeout: float) -> Optional[struct_siginfo]: ... diff --git a/mypy/typeshed/stdlib/site.pyi b/mypy/typeshed/stdlib/site.pyi index 4fdbad8ee3cf..e91176ac4db4 100644 --- a/mypy/typeshed/stdlib/site.pyi +++ b/mypy/typeshed/stdlib/site.pyi @@ -1,7 +1,5 @@ -# Stubs for site - -from typing import List, Iterable, Optional import sys +from typing import Iterable, List, Optional PREFIXES: List[str] ENABLE_USER_SITE: Optional[bool] @@ -10,8 +8,8 @@ USER_BASE: Optional[str] if sys.version_info < (3,): def main() -> None: ... -def addsitedir(sitedir: str, - known_paths: Optional[Iterable[str]] = ...) -> 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/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 870a50147a1a..051fe72eabd7 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -1,14 +1,11 @@ -# Stubs for smtpd (Python 2 and 3) -import sys -import socket -import asyncore import asynchat - +import asyncore +import socket +import sys from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type _Address = Tuple[str, int] # (host, port) - class SMTPChannel(asynchat.async_chat): COMMAND: int DATA: int @@ -31,13 +28,19 @@ class SMTPChannel(asynchat.async_chat): 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: ... + 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: ... # base asynchat.async_chat.push() accepts bytes @@ -64,12 +67,17 @@ class SMTPServer(asyncore.dispatcher): 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: ... + 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 = ...) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message(self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: str, **kwargs: Any) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 60e3a35b83ba..fa9d37e4065f 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -2,7 +2,7 @@ from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, Pattern, Type, Protocol, overload +from typing import Any, Dict, List, Optional, Pattern, Protocol, Sequence, Tuple, Type, Union, overload _Reply = Tuple[int, bytes] _SendErrs = Dict[str, _Reply] @@ -67,16 +67,20 @@ class SMTP: command_encoding: str source_address: Optional[_SourceAddress] local_hostname: str - def __init__(self, host: str = ..., port: int = ..., - local_hostname: Optional[str] = ..., timeout: float = ..., - source_address: Optional[_SourceAddress] = ...) -> None: ... + def __init__( + self, + host: str = ..., + port: int = ..., + local_hostname: Optional[str] = ..., + timeout: float = ..., + source_address: Optional[_SourceAddress] = ..., + ) -> None: ... def __enter__(self) -> SMTP: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - tb: Optional[TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], tb: Optional[TracebackType] + ) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... - def connect(self, host: str = ..., port: int = ..., - source_address: Optional[_SourceAddress] = ...) -> _Reply: ... + def connect(self, host: str = ..., port: int = ..., source_address: Optional[_SourceAddress] = ...) -> _Reply: ... def send(self, s: Union[bytes, str]) -> None: ... def putcmd(self, cmd: str, args: str = ...) -> None: ... def getreply(self) -> _Reply: ... @@ -104,15 +108,25 @@ class SMTP: def auth_plain(self, challenge: Optional[bytes] = ...) -> str: ... def auth_login(self, challenge: Optional[bytes] = ...) -> str: ... def login(self, user: str, password: str, *, initial_response_ok: bool = ...) -> _Reply: ... - def starttls(self, keyfile: Optional[str] = ..., certfile: Optional[str] = ..., - context: Optional[SSLContext] = ...) -> _Reply: ... - def sendmail(self, from_addr: str, to_addrs: Union[str, Sequence[str]], - msg: Union[bytes, str], mail_options: Sequence[str] = ..., - rcpt_options: List[str] = ...) -> _SendErrs: ... - def send_message(self, msg: _Message, from_addr: Optional[str] = ..., - to_addrs: Optional[Union[str, Sequence[str]]] = ..., - mail_options: List[str] = ..., - rcpt_options: Sequence[str] = ...) -> _SendErrs: ... + def starttls( + self, keyfile: Optional[str] = ..., certfile: Optional[str] = ..., context: Optional[SSLContext] = ... + ) -> _Reply: ... + def sendmail( + self, + from_addr: str, + to_addrs: Union[str, Sequence[str]], + msg: Union[bytes, str], + mail_options: Sequence[str] = ..., + rcpt_options: List[str] = ..., + ) -> _SendErrs: ... + def send_message( + self, + msg: _Message, + from_addr: Optional[str] = ..., + to_addrs: Optional[Union[str, Sequence[str]]] = ..., + mail_options: List[str] = ..., + rcpt_options: Sequence[str] = ..., + ) -> _SendErrs: ... def close(self) -> None: ... def quit(self) -> _Reply: ... @@ -121,16 +135,25 @@ class SMTP_SSL(SMTP): keyfile: Optional[str] certfile: Optional[str] context: SSLContext - def __init__(self, host: str = ..., port: int = ..., - local_hostname: Optional[str] = ..., - keyfile: Optional[str] = ..., certfile: Optional[str] = ..., - timeout: float = ..., - source_address: Optional[_SourceAddress] = ..., - context: Optional[SSLContext] = ...) -> None: ... + def __init__( + self, + host: str = ..., + port: int = ..., + local_hostname: Optional[str] = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + timeout: float = ..., + source_address: Optional[_SourceAddress] = ..., + context: Optional[SSLContext] = ..., + ) -> None: ... LMTP_PORT: int class LMTP(SMTP): - def __init__(self, host: str = ..., port: int = ..., - local_hostname: Optional[str] = ..., - source_address: Optional[_SourceAddress] = ...) -> None: ... + def __init__( + self, + host: str = ..., + port: int = ..., + local_hostname: Optional[str] = ..., + source_address: Optional[_SourceAddress] = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index d74101fe36be..da8fbcf566fc 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -1,24 +1,7 @@ -"""Stub for the socket module - -This file is organized to mirror the module's documentation, with a very small -number of exceptions. - -To avoid requiring tests on all platforms, platform checks are included only -where the documentation notes platform availability (as opposed to following -actual availability), with one or two exceptions. - -Module documentation: https://docs.python.org/3/library/socket.html -CPython module source: https://github.com/python/cpython/blob/master/Lib/socket.py -CPython C source: https://github.com/python/cpython/blob/master/Modules/socketmodule.c -""" -# Authorship from original mypy stubs (not in typeshed git history): -# Ron Murawski -# adapted for Python 2.7 by Michal Pokorny import sys from typing import Any, BinaryIO, Iterable, List, Optional, Text, TextIO, Tuple, TypeVar, Union, overload from typing_extensions import Literal - # ----- 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 @@ -52,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" and sys.version_info >= (3,): SOCK_CLOEXEC: SocketKind SOCK_NONBLOCK: SocketKind @@ -94,7 +77,7 @@ AI_NUMERICSERV: AddressInfo AI_PASSIVE: AddressInfo AI_V4MAPPED: AddressInfo AI_V4MAPPED_CFG: AddressInfo -EAIEAI_ADDRFAMILY: int +EAI_ADDRFAMILY: int EAI_AGAIN: int EAI_BADFLAGS: int EAI_BADHINTS: int @@ -285,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" and sys.version_info >= (3,): AF_CAN: AddressFamily PF_CAN: int SOL_CAN_BASE: int @@ -318,7 +301,7 @@ if sys.platform == 'linux' and sys.version_info >= (3,): CAN_RAW_FD_FRAMES: int -if sys.platform == 'linux' and sys.version_info >= (3, 8): +if sys.platform == "linux" and sys.version_info >= (3, 8): CAN_BCM_SETTIMER: int CAN_BCM_STARTTIMER: int CAN_BCM_TX_COUNTEVT: int @@ -332,10 +315,10 @@ if sys.platform == 'linux' and sys.version_info >= (3, 8): CAN_BCM_RX_RTR_FRAME: int CAN_BCM_CAN_FD_FRAME: int -if sys.platform == 'linux' and sys.version_info >= (3, 7): +if sys.platform == "linux" and sys.version_info >= (3, 7): CAN_ISOTP: int -if sys.platform == 'linux' and sys.version_info >= (3, 9): +if sys.platform == "linux" and sys.version_info >= (3, 9): CAN_J1939: int J1939_MAX_UNICAST_ADDR: int @@ -367,7 +350,7 @@ if sys.platform == 'linux' and sys.version_info >= (3, 9): J1939_FILTER_MAX: int -if sys.platform == 'linux': +if sys.platform == "linux": AF_PACKET: AddressFamily PF_PACKET: int PACKET_BROADCAST: int @@ -378,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" and sys.version_info >= (3,): AF_RDS: AddressFamily PF_RDS: int SOL_RDS: int @@ -401,7 +384,7 @@ if sys.platform == 'linux' and sys.version_info >= (3,): RDS_RDMA_USE_ONCE: int RDS_RECVERR: int -if sys.platform == 'win32': +if sys.platform == "win32": SIO_RCVALL: int SIO_KEEPALIVE_VALS: int if sys.version_info >= (3, 6): @@ -412,7 +395,7 @@ if sys.platform == 'win32': RCVALL_ON: int RCVALL_SOCKETLEVELONLY: int -if sys.platform == 'linux': +if sys.platform == "linux": AF_TIPC: AddressFamily SOL_TIPC: int TIPC_ADDR_ID: int @@ -439,7 +422,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" and sys.version_info >= (3, 6): AF_ALG: AddressFamily SOL_ALG: int ALG_OP_DECRYPT: int @@ -453,7 +436,7 @@ if sys.platform == 'linux' and sys.version_info >= (3, 6): ALG_SET_OP: int ALG_SET_PUBKEY: int -if sys.platform == 'linux' and sys.version_info >= (3, 7): +if sys.platform == "linux" and sys.version_info >= (3, 7): AF_VSOCK: AddressFamily IOCTL_VM_SOCKETS_GET_LOCAL_CID: int VMADDR_CID_ANY: int @@ -476,14 +459,13 @@ if sys.version_info >= (3, 6): TCP_CONGESTION: int TCP_USER_TIMEOUT: int -if sys.platform == 'linux' and sys.version_info >= (3, 8): +if sys.platform == "linux" and sys.version_info >= (3, 8): AF_QIPCRTR: AddressFamily - # Semi-documented constants # (Listed under "Socket families" in the docs, but not "Constants") -if sys.platform == 'linux': +if sys.platform == "linux": # Netlink is defined by Linux AF_NETLINK: AddressFamily NETLINK_ARPD: int @@ -501,7 +483,7 @@ if sys.platform == 'linux': NETLINK_W1: int NETLINK_XFRM: int -if sys.platform != 'win32' and sys.platform != 'darwin': +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 @@ -518,16 +500,14 @@ if sys.platform != 'win32' and sys.platform != 'darwin': HCI_TIME_STAMP: int HCI_DATA_DIR: int -if sys.platform == 'darwin': +if sys.platform == "darwin": # PF_SYSTEM is defined by macOS PF_SYSTEM: int 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 @@ -566,7 +546,6 @@ if sys.version_info >= (3, 4): AF_VSOCK: int AF_WANPIPE: int AF_X25: int - class SocketKind(IntEnum): SOCK_STREAM: int SOCK_DGRAM: int @@ -575,13 +554,13 @@ if sys.version_info >= (3, 4): 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 @@ -590,7 +569,6 @@ if sys.version_info >= (3, 6): AI_NUMERICSERV: int AI_PASSIVE: int AI_V4MAPPED: int - class MsgFlag(IntFlag): MSG_CTRUNC: int MSG_DONTROUTE: int @@ -600,15 +578,16 @@ if sys.version_info >= (3, 6): MSG_PEEK: int MSG_TRUNC: int MSG_WAITALL: int + else: AddressInfo = int MsgFlag = int - # ----- Exceptions ----- if sys.version_info < (3,): class error(IOError): ... + else: error = OSError @@ -621,7 +600,6 @@ class gaierror(error): class timeout(error): def __init__(self, error: int = ..., string: str = ...) -> None: ... - # ----- Classes ----- # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, @@ -633,7 +611,7 @@ _RetAddress = Any _WriteBuffer = Union[bytearray, memoryview] _CMSG = Tuple[int, int, bytes] -_SelfT = TypeVar('_SelfT', bound=socket) +_SelfT = TypeVar("_SelfT", bound=socket) class socket: family: int @@ -646,7 +624,6 @@ class socket: 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: ... @@ -660,21 +637,17 @@ class socket: def get_inheritable(self) -> bool: ... 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: ... - 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" and sys.version_info >= (3, 6): def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> None: ... - elif sys.platform == 'win32': + 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: @@ -683,32 +656,34 @@ class socket: 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: ... + 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 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: ... 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": 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 = ...) -> Tuple[int, List[_CMSG], int, Any]: ... + def recvmsg_into( + self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... + ) -> Tuple[int, List[_CMSG], int, Any]: ... 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: ... @@ -718,22 +693,18 @@ class socket: @overload def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... if sys.version_info >= (3, 3) and 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): - # TODO add the parameter types for sendmsg_afalg - def sendmsg_afalg(self, msg=..., *, op, iv=..., assoclen=..., flags=...) -> int: ... - + def sendmsg( + self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... + ) -> int: ... + if sys.platform == "linux" and sys.version_info >= (3, 6): + def sendmsg_afalg( + self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + ) -> int: ... if sys.version_info >= (3,): - # TODO determine legal types for file parameter - def sendfile(self, file, offset: int = ..., count: Optional[int] = ...) -> int: ... + 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: @@ -741,60 +712,59 @@ class socket: 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': + if sys.platform == "win32": def share(self, process_id: int) -> bytes: ... - def shutdown(self, how: int) -> None: ... - # ----- Functions ----- if sys.version_info >= (3, 7): def close(fd: int) -> None: ... -def create_connection(address: Tuple[Optional[str], int], - timeout: Optional[float] = ..., - source_address: Optional[Tuple[Union[bytearray, bytes, Text], int]] = ...) -> socket: ... +def create_connection( + address: Tuple[Optional[str], int], + timeout: Optional[float] = ..., + source_address: Optional[Tuple[Union[bytearray, bytes, Text], int]] = ..., +) -> socket: ... if sys.version_info >= (3, 8): - def create_server(address: _Address, - *, - family: int = ..., - backlog: Optional[int] = ..., - reuse_port: bool = ..., - dualstack_ipv6: bool = ...) -> socket: ... + def create_server( + address: _Address, *, family: int = ..., backlog: Optional[int] = ..., reuse_port: bool = ..., dualstack_ipv6: bool = ... + ) -> socket: ... def has_dualstack_ipv6() -> bool: ... 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" and sys.version_info >= (3, 3): def fromshare(info: bytes) -> socket: ... # the 5th tuple item is an address -# TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers -# https://github.com/python/mypy/issues/2509 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, Tuple[Any, ...]]]: ... + 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, 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, int]: ... +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: ... @@ -807,11 +777,22 @@ 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: ... + +if sys.version_info >= (3, 9): + if sys.platform != "win32": + # flags and address appear to be unused in send_fds and recv_fds + def send_fds( + sock: socket, buffers: Iterable[bytes], fds: Union[bytes, Iterable[int]], flags: int = ..., address: None = ... + ) -> 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 getdefaulttimeout() -> Optional[float]: ... def setdefaulttimeout(timeout: Optional[float]) -> None: ... + if sys.version_info >= (3, 3): if sys.platform != "win32": def sethostname(name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index 3f57efbe9766..f0617e393b7e 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -1,10 +1,9 @@ -# NB: SocketServer.pyi and socketserver.pyi must remain consistent! -# Stubs for socketserver - -from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, Text, Union -from socket import SocketType import sys import types +from socket import SocketType +from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, TypeVar, Union + +_T = TypeVar("_T") class BaseServer: address_family: int @@ -15,53 +14,57 @@ class BaseServer: request_queue_size: int socket_type: int timeout: Optional[float] - def __init__(self, server_address: Any, - RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... + def __init__(self, server_address: Any, RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... def fileno(self) -> int: ... def handle_request(self) -> None: ... def serve_forever(self, poll_interval: float = ...) -> None: ... def shutdown(self) -> None: ... def server_close(self) -> None: ... - def finish_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - def get_request(self) -> None: ... - def handle_error(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... + def finish_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> Tuple[SocketType, Tuple[str, int]]: ... + def handle_error(self, request: bytes, client_address: Tuple[str, int]) -> None: ... def handle_timeout(self) -> None: ... - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... def server_activate(self) -> None: ... def server_bind(self) -> None: ... - def verify_request(self, request: bytes, - client_address: Tuple[str, int]) -> bool: ... - if sys.version_info >= (3, 6): - def __enter__(self) -> BaseServer: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[types.TracebackType]) -> None: ... - if sys.version_info >= (3, 3): - def service_actions(self) -> None: ... + def verify_request(self, request: bytes, client_address: Tuple[str, int]) -> bool: ... + def __enter__(self: _T) -> _T: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[types.TracebackType] + ) -> None: ... + def service_actions(self) -> None: ... class TCPServer(BaseServer): - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... + def __init__( + self, + server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... class UDPServer(BaseServer): - def __init__(self, server_address: Tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... + def __init__( + self, + server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... -if sys.platform != 'win32': +if sys.platform != "win32": class UnixStreamServer(BaseServer): - def __init__(self, server_address: Union[Text, bytes], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... - + def __init__( + self, + server_address: Union[str, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... class UnixDatagramServer(BaseServer): - def __init__(self, server_address: Union[Text, bytes], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ...) -> None: ... + def __init__( + self, + server_address: Union[str, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... if sys.platform != "win32": class ForkingMixIn: @@ -70,39 +73,31 @@ if sys.platform != "win32": max_children: int # undocumented if sys.version_info >= (3, 7): block_on_close: bool - if sys.version_info >= (3, 6): - def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented - else: - def collect_children(self) -> None: ... # undocumented + def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented def handle_timeout(self) -> None: ... # undocumented - if sys.version_info >= (3, 3): - def service_actions(self) -> None: ... # undocumented - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - if sys.version_info >= (3, 6): - def server_close(self) -> None: ... + def service_actions(self) -> None: ... # undocumented + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def server_close(self) -> None: ... class ThreadingMixIn: daemon_threads: bool if sys.version_info >= (3, 7): block_on_close: bool - def process_request_thread(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... # undocumented - def process_request(self, request: bytes, - client_address: Tuple[str, int]) -> None: ... - if sys.version_info >= (3, 6): - def server_close(self) -> None: ... + def process_request_thread(self, request: bytes, client_address: Tuple[str, int]) -> None: ... # undocumented + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def server_close(self) -> None: ... if sys.platform != "win32": class ForkingTCPServer(ForkingMixIn, TCPServer): ... class ForkingUDPServer(ForkingMixIn, UDPServer): ... + class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... -if sys.platform != 'win32': + +if sys.platform != "win32": class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... - class BaseRequestHandler: # Those are technically of types, respectively: # * Union[SocketType, Tuple[bytes, SocketType]] @@ -113,7 +108,6 @@ class BaseRequestHandler: request: Any client_address: Any server: BaseServer - def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... def setup(self) -> None: ... def handle(self) -> None: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 13dae97d968d..ae3b01bfb5ca 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,12 +1,9 @@ -# Filip Hron -# based heavily on Andrey Vlasovskikh's python-skeletons https://github.com/JetBrains/python-skeletons/blob/master/sqlite3.py - import os import sys +from datetime import date, datetime, time from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Text, Tuple, Type, TypeVar, Union -from datetime import date, time, datetime -_T = TypeVar('_T') +_T = TypeVar("_T") paramstyle: str threadsafety: int @@ -15,9 +12,9 @@ Date = date Time = time Timestamp = datetime -def DateFromTicks(ticks): ... -def TimeFromTicks(ticks): ... -def TimestampFromTicks(ticks): ... +def DateFromTicks(ticks: float) -> Date: ... +def TimeFromTicks(ticks: float) -> Time: ... +def TimestampFromTicks(ticks: float) -> Timestamp: ... version_info: str sqlite_version_info: Tuple[int, int, int] @@ -26,8 +23,6 @@ if sys.version_info >= (3,): else: Binary = buffer -def register_adapters_and_converters(): ... - # The remaining definitions are imported from _sqlite3. PARSE_COLNAMES: int @@ -71,32 +66,42 @@ version: str # TODO: adapt needs to get probed def adapt(obj, protocol, alternate): ... 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: ... + 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], - timeout: float = ..., - detect_types: int = ..., - isolation_level: Optional[str] = ..., - check_same_thread: bool = ..., - factory: Optional[Type[Connection]] = ..., - cached_statements: int = ..., - uri: bool = ...) -> Connection: ... + 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 = ..., + uri: bool = ..., + ) -> Connection: ... + else: - 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 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(flag: bool) -> None: ... def enable_shared_cache(do_enable: int) -> None: ... def register_adapter(type: Type[_T], callable: Callable[[_T], Union[int, float, str, bytes]]) -> None: ... @@ -124,7 +129,7 @@ class Connection(object): row_factory: Any text_factory: Any total_changes: Any - def __init__(self, *args, **kwargs): ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... def close(self) -> None: ... def commit(self) -> None: ... def create_aggregate(self, name: str, num_params: int, aggregate_class: type) -> None: ... @@ -138,27 +143,33 @@ class Connection(object): # TODO: please check in executemany() if seq_of_parameters type is possible like this def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... def executescript(self, sql_script: Union[bytes, Text]) -> Cursor: ... - def interrupt(self, *args, **kwargs) -> None: ... - def iterdump(self, *args, **kwargs) -> Generator[str, None, None]: ... - def rollback(self, *args, **kwargs) -> None: ... + 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, **kwargs) -> None: ... + 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, **kwargs) -> None: ... - def set_trace_callback(self, *args, **kwargs): ... + 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: ... if sys.version_info >= (3, 7): - def backup(self, target: Connection, *, pages: int = ..., - progress: Optional[Callable[[int, int, int], object]] = ..., name: str = ..., - sleep: float = ...) -> None: ... - def __call__(self, *args, **kwargs): ... - def __enter__(self, *args, **kwargs) -> Connection: ... - def __exit__(self, *args, **kwargs): ... + def backup( + self, + target: Connection, + *, + pages: int = ..., + progress: Optional[Callable[[int, int, int], object]] = ..., + name: str = ..., + sleep: float = ..., + ) -> 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 @@ -170,37 +181,29 @@ class Cursor(Iterator[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, **kwargs) -> None: ... - def close(self, *args, **kwargs) -> None: ... + 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, **kwargs) -> None: ... - def setoutputsize(self, *args, **kwargs) -> None: ... + 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: ... - class DataError(DatabaseError): ... - class DatabaseError(Error): ... - class Error(Exception): ... - class IntegrityError(DatabaseError): ... - class InterfaceError(Error): ... - class InternalError(DatabaseError): ... - class NotSupportedError(DatabaseError): ... - class OperationalError(DatabaseError): ... if sys.version_info >= (3,): @@ -272,13 +275,13 @@ else: def __rmul__(self, other): ... class PrepareProtocol(object): - def __init__(self, *args, **kwargs): ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... class ProgrammingError(DatabaseError): ... class Row(object): - def __init__(self, *args, **kwargs): ... - def keys(self, *args, **kwargs): ... + 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): ... @@ -286,7 +289,7 @@ class Row(object): def __hash__(self): ... def __iter__(self): ... def __le__(self, other): ... - def __len__(self, *args, **kwargs): ... + def __len__(self, *args: Any, **kwargs: Any): ... def __lt__(self, other): ... def __ne__(self, other): ... diff --git a/mypy/typeshed/stdlib/sre_compile.pyi b/mypy/typeshed/stdlib/sre_compile.pyi index e6036e205454..9b50b75d8c31 100644 --- a/mypy/typeshed/stdlib/sre_compile.pyi +++ b/mypy/typeshed/stdlib/sre_compile.pyi @@ -1,9 +1,22 @@ -# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_compile.py -# and https://github.com/python/cpython/blob/master/Lib/sre_compile.py - import sys +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, TypeVar, Union +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 MAXCODE: int if sys.version_info < (3, 0): diff --git a/mypy/typeshed/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi index e51fff5597a9..2b411d5c69c9 100644 --- a/mypy/typeshed/stdlib/sre_constants.pyi +++ b/mypy/typeshed/stdlib/sre_constants.pyi @@ -1,5 +1,3 @@ -# Source: https://github.com/python/cpython/blob/master/Lib/sre_constants.py - from typing import Any, Dict, List, Optional, Union MAGIC: int @@ -39,7 +37,6 @@ SRE_INFO_PREFIX: int SRE_INFO_LITERAL: int SRE_INFO_CHARSET: int - # Stubgen above; manually defined constants below (dynamic at runtime) # from OPCODES diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index c9c1622377ed..4c7b6157d8a9 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -1,11 +1,6 @@ -# Source: https://github.com/python/cpython/blob/master/Lib/sre_parse.py - -from typing import ( - Any, Dict, FrozenSet, Iterable, List, Match, - Optional, Pattern as _Pattern, Tuple, Union -) import sys from sre_constants import _NamedIntConstant as _NIC, error as _Error +from typing import Any, Dict, FrozenSet, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload SPECIAL_CHARS: str REPEAT_CHARS: str @@ -17,10 +12,9 @@ WHITESPACE: FrozenSet[str] ESCAPES: Dict[str, Tuple[_NIC, int]] CATEGORIES: Dict[str, Union[Tuple[_NIC, _NIC], Tuple[_NIC, List[Tuple[_NIC, _NIC]]]]] FLAGS: Dict[str, int] -if sys.version_info >= (3, 6): - GLOBAL_FLAGS: int +GLOBAL_FLAGS: int - class Verbose(Exception): ... +class Verbose(Exception): ... class _State: flags: int @@ -40,7 +34,6 @@ if sys.version_info >= (3, 8): else: Pattern = _State - _OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] _OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] _OpInType = List[Tuple[_NIC, int]] @@ -48,7 +41,6 @@ _OpBranchType = Tuple[None, List[SubPattern]] _AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] _CodeType = Tuple[_NIC, _AvType] - class SubPattern: data: List[_CodeType] width: Optional[int] @@ -59,7 +51,6 @@ class SubPattern: else: pattern: Pattern def __init__(self, pattern: Pattern, data: Optional[List[_CodeType]] = ...) -> None: ... - def dump(self, level: int = ...) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: Union[int, slice]) -> None: ... @@ -69,7 +60,6 @@ class SubPattern: def append(self, code: _CodeType) -> None: ... def getwidth(self) -> int: ... - class Tokenizer: istext: bool string: Any @@ -84,19 +74,28 @@ class Tokenizer: def getuntil(self, terminator: str, name: str) -> str: ... else: def getuntil(self, terminator: str) -> str: ... - if sys.version_info >= (3, 6): - @property - def pos(self) -> int: ... + @property + def pos(self) -> int: ... def tell(self) -> int: ... def seek(self, index: int) -> None: ... def error(self, msg: str, offset: int = ...) -> _Error: ... def fix_flags(src: Union[str, bytes], flags: int) -> int: ... -_TemplateType = Tuple[List[Tuple[int, int]], List[str]] + +_TemplateType = Tuple[List[Tuple[int, int]], List[Optional[str]]] +_TemplateByteType = Tuple[List[Tuple[int, int]], List[Optional[bytes]]] if sys.version_info >= (3, 8): def parse(str: str, flags: int = ..., state: Optional[State] = ...) -> SubPattern: ... + @overload def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... + @overload + def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ... + else: def parse(str: str, flags: int = ..., pattern: Optional[Pattern] = ...) -> SubPattern: ... + @overload def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... + @overload + def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... + def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index cc2380abf6de..36656f5534ab 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -1,12 +1,9 @@ -from _typeshed import StrPath -from typing import ( - Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Type, Tuple, Union, - overload -) -from typing_extensions import Literal 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_extensions import Literal _PCTRTT = Tuple[Tuple[str, str], ...] _PCTRTTT = Tuple[_PCTRTT, ...] @@ -24,6 +21,7 @@ _SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] class SSLError(OSError): library: str reason: str + class SSLZeroReturnError(SSLError): ... class SSLWantReadError(SSLError): ... class SSLWantWriteError(SSLError): ... @@ -34,65 +32,69 @@ if sys.version_info >= (3, 7): class SSLCertVerificationError(SSLError, ValueError): verify_code: int verify_message: str - CertificateError = SSLCertVerificationError else: 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 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] = ..., + purpose: Any = ..., *, cafile: Optional[str] = ..., capath: Optional[str] = ..., cadata: Union[Text, bytes, None] = ... ) -> SSLContext: ... if sys.version_info >= (3, 7): - def _create_unverified_context(protocol: int = ..., *, - cert_reqs: int = ..., - check_hostname: bool = ..., - purpose: Any = ..., - certfile: Optional[str] = ..., - keyfile: Optional[str] = ..., - cafile: Optional[str] = ..., - capath: Optional[str] = ..., - cadata: Union[Text, bytes, None] = ...) -> SSLContext: ... + def _create_unverified_context( + protocol: int = ..., + *, + cert_reqs: int = ..., + check_hostname: bool = ..., + purpose: Any = ..., + certfile: Optional[str] = ..., + keyfile: Optional[str] = ..., + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Union[Text, bytes, None] = ..., + ) -> SSLContext: ... + else: - 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: ... + 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] if sys.version_info >= (3, 3): 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: ... - - 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 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 @@ -100,13 +102,13 @@ class DefaultVerifyPaths(NamedTuple): openssl_cafile: str openssl_capath_env: str openssl_capath: str + def get_default_verify_paths() -> DefaultVerifyPaths: ... -if sys.platform == 'win32': +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 @@ -146,7 +148,6 @@ if sys.version_info >= (3, 6): OP_NO_TLSv1_3: int if sys.version_info >= (3, 8): OP_ENABLE_MIDDLEBOX_COMPAT: int - OP_ALL: Options OP_NO_SSLv2: Options OP_NO_SSLv3: Options @@ -226,10 +227,12 @@ class _ASN1Object(NamedTuple): shortname: str longname: str oid: str + if sys.version_info < (3,): class Purpose(_ASN1Object): SERVER_AUTH: ClassVar[Purpose] CLIENT_AUTH: ClassVar[Purpose] + else: class Purpose(_ASN1Object, enum.Enum): SERVER_AUTH: _ASN1Object @@ -242,9 +245,7 @@ class SSLSocket(socket.socket): if sys.version_info >= (3, 6): session: Optional[SSLSession] session_reused: Optional[bool] - - def read(self, len: int = ..., - buffer: Optional[bytearray] = ...) -> bytes: ... + 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 @@ -294,14 +295,12 @@ class SSLContext: else: 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_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[Text, bytes, None] = ... ) -> None: ... def get_ca_certs(self, binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ... def set_default_verify_paths(self) -> None: ... @@ -318,32 +317,43 @@ class SSLContext: 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: ... + 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: ... + 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: ... + 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_bio( + self, incoming: MemoryBIO, outgoing: MemoryBIO, server_side: bool = ..., server_hostname: Optional[str] = ... + ) -> 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 @@ -352,8 +362,7 @@ if sys.version_info >= (3, 5): if sys.version_info >= (3, 6): session: Optional[SSLSession] session_reused: bool - def read(self, len: int = ..., - buffer: Optional[bytearray] = ...) -> bytes: ... + 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]: ... @@ -373,7 +382,6 @@ if sys.version_info >= (3, 5): 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 @@ -388,14 +396,12 @@ if sys.version_info >= (3, 6): 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 diff --git a/mypy/typeshed/stdlib/stat.pyi b/mypy/typeshed/stdlib/stat.pyi index b8cff23ceef7..6fd2bc0814f0 100644 --- a/mypy/typeshed/stdlib/stat.pyi +++ b/mypy/typeshed/stdlib/stat.pyi @@ -1,7 +1,3 @@ -# Stubs for stat - -# Based on http://docs.python.org/3.2/library/stat.html - import sys def S_ISDIR(mode: int) -> bool: ... @@ -11,10 +7,8 @@ def S_ISREG(mode: int) -> bool: ... def S_ISFIFO(mode: int) -> bool: ... def S_ISLNK(mode: int) -> bool: ... def S_ISSOCK(mode: int) -> bool: ... - def S_IMODE(mode: int) -> int: ... def S_IFMT(mode: int) -> int: ... - def filemode(mode: int) -> str: ... ST_MODE: int @@ -64,9 +58,9 @@ UF_IMMUTABLE: int UF_APPEND: int UF_OPAQUE: int UF_NOUNLINK: int -if sys.platform == 'darwin': +if sys.platform == "darwin": UF_COMPRESSED: int # OS X 10.6+ only - UF_HIDDEN: int # OX X 10.5+ only + UF_HIDDEN: int # OX X 10.5+ only SF_ARCHIVED: int SF_IMMUTABLE: int SF_APPEND: int diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index f2165f0ce9c0..d842965247f5 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -1,18 +1,12 @@ -# Stubs for statistics - +import sys +from _typeshed import SupportsLessThanT from decimal import Decimal from fractions import Fraction -import sys -from typing import Any, Iterable, List, Optional, SupportsFloat, Type, TypeVar, Union, Protocol, Hashable +from typing import Any, Hashable, Iterable, List, Optional, SupportsFloat, Type, TypeVar, Union _T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types -_Number = TypeVar('_Number', float, Decimal, Fraction) - -# Used in median_high, median_low -class _Sortable(Protocol): - def __lt__(self, other) -> bool: ... -_SortableT = TypeVar("_SortableT", bound=_Sortable) +_NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode _HashableT = TypeVar("_HashableT", bound=Hashable) @@ -22,22 +16,26 @@ class StatisticsError(ValueError): ... if sys.version_info >= (3, 8): def fmean(data: Iterable[SupportsFloat]) -> float: ... def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... -def mean(data: Iterable[_Number]) -> _Number: ... -if sys.version_info >= (3, 6): - def harmonic_mean(data: Iterable[_Number]) -> _Number: ... -def median(data: Iterable[_Number]) -> _Number: ... -def median_low(data: Iterable[_SortableT]) -> _SortableT: ... -def median_high(data: Iterable[_SortableT]) -> _SortableT: ... -def median_grouped(data: Iterable[_Number], interval: _Number = ...) -> _Number: ... + +def mean(data: Iterable[_NumberT]) -> _NumberT: ... +def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: ... +def median(data: Iterable[_NumberT]) -> _NumberT: ... +def median_low(data: Iterable[SupportsLessThanT]) -> SupportsLessThanT: ... +def median_high(data: Iterable[SupportsLessThanT]) -> SupportsLessThanT: ... +def median_grouped(data: Iterable[_NumberT], interval: _NumberT = ...) -> _NumberT: ... def mode(data: Iterable[_HashableT]) -> _HashableT: ... + if sys.version_info >= (3, 8): def multimode(data: Iterable[_HashableT]) -> List[_HashableT]: ... -def pstdev(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... -def pvariance(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... + +def pstdev(data: Iterable[_NumberT], mu: Optional[_NumberT] = ...) -> _NumberT: ... +def pvariance(data: Iterable[_NumberT], mu: Optional[_NumberT] = ...) -> _NumberT: ... + if sys.version_info >= (3, 8): - def quantiles(data: Iterable[_Number], *, n: int = ..., method: str = ...) -> List[_Number]: ... -def stdev(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... -def variance(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... + def quantiles(data: Iterable[_NumberT], *, n: int = ..., method: str = ...) -> List[_NumberT]: ... + +def stdev(data: Iterable[_NumberT], xbar: Optional[_NumberT] = ...) -> _NumberT: ... +def variance(data: Iterable[_NumberT], xbar: Optional[_NumberT] = ...) -> _NumberT: ... if sys.version_info >= (3, 8): class NormalDist: diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 2347d6cd6ee9..a39e64dd32ca 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -1,8 +1,4 @@ -# Stubs for string - -# Based on http://docs.python.org/3.2/library/string.html - -from typing import Mapping, Sequence, Any, Optional, Union, Tuple, Iterable +from typing import Any, Iterable, Mapping, Optional, Sequence, Tuple, Union ascii_letters: str ascii_lowercase: str @@ -18,22 +14,17 @@ def capwords(s: str, sep: Optional[str] = ...) -> str: ... class Template: template: str - def __init__(self, template: str) -> None: ... def substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... - def safe_substitute(self, __mapping: Mapping[str, object] = ..., - **kwds: object) -> str: ... + def safe_substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... # TODO(MichalPokorny): This is probably badly and/or loosely typed. class Formatter: def format(self, __format_string: str, *args: Any, **kwargs: Any) -> str: ... - def vformat(self, format_string: str, args: Sequence[Any], - kwargs: Mapping[str, Any]) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... def parse(self, format_string: str) -> Iterable[Tuple[str, Optional[str], Optional[str], Optional[str]]]: ... - def get_field(self, field_name: str, args: Sequence[Any], - kwargs: Mapping[str, Any]) -> Any: ... + def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... def get_value(self, key: Union[int, str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... - def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], - kwargs: Mapping[str, Any]) -> None: ... + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... def format_field(self, value: Any, format_spec: str) -> Any: ... def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/stringprep.pyi b/mypy/typeshed/stdlib/stringprep.pyi index e3b7e9dc2fee..604fd2f2cae7 100644 --- a/mypy/typeshed/stdlib/stringprep.pyi +++ b/mypy/typeshed/stdlib/stringprep.pyi @@ -1,5 +1,3 @@ -# Stubs for stringprep (Python 2 and 3) - from typing import Text def in_table_a1(code: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index c672b924fda0..9edf6842be3d 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -1,12 +1,7 @@ -# Stubs for struct - -# Based on http://docs.python.org/3.2/library/struct.html -# Based on http://docs.python.org/2/library/struct.html - import sys -from typing import Any, Tuple, Text, Union, Iterator from array import array from mmap import mmap +from typing import Any, Iterator, Text, Tuple, Union class error(Exception): ... @@ -22,6 +17,7 @@ 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, ...]]: ... @@ -33,9 +29,7 @@ class Struct: else: 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, ...]: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 1507079373ee..b9d7108a96e6 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,8 +1,11 @@ import sys -from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union, Type, Generic, TypeVar, AnyStr, overload +from _typeshed import AnyPath 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 -from _typeshed import AnyPath + +if sys.version_info >= (3, 9): + from types import GenericAlias # We prefer to annotate inputs to methods (eg subprocess.check_call) with these # union types. @@ -25,8 +28,8 @@ _TXT = Union[bytes, str] _CMD = Union[_TXT, Sequence[AnyPath]] _ENV = Union[Mapping[bytes, _TXT], Mapping[str, _TXT]] -_S = TypeVar('_S') -_T = TypeVar('_T') +_S = TypeVar("_S") +_T = TypeVar("_T") class CompletedProcess(Generic[_T]): # morally: _CMD @@ -38,6 +41,8 @@ class CompletedProcess(Generic[_T]): stderr: _T def __init__(self, args: _CMD, returncode: int, stdout: Optional[_T] = ..., stderr: Optional[_T] = ...) -> None: ... def check_returncode(self) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 7): # Nearly the same args as for 3.6, except for capture_output and text @@ -45,11 +50,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -73,11 +78,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -101,11 +106,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -129,11 +134,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -158,11 +163,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -186,11 +191,11 @@ if sys.version_info >= (3, 7): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -210,17 +215,18 @@ if sys.version_info >= (3, 7): text: Optional[bool] = ..., timeout: Optional[float] = ..., ) -> CompletedProcess[Any]: ... -elif sys.version_info >= (3, 6): + +else: # Nearly same args as Popen.__init__ except for timeout, input, and check @overload def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -242,11 +248,11 @@ elif sys.version_info >= (3, 6): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -268,11 +274,11 @@ elif sys.version_info >= (3, 6): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -295,11 +301,11 @@ elif sys.version_info >= (3, 6): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -321,11 +327,11 @@ elif sys.version_info >= (3, 6): def run( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -343,17 +349,137 @@ elif sys.version_info >= (3, 6): input: Optional[_TXT] = ..., timeout: Optional[float] = ..., ) -> CompletedProcess[Any]: ... -else: - # Nearly same args as Popen.__init__ except for timeout, input, and check + +# Same args as Popen.__init__ +def call( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., +) -> int: ... + +# Same args as Popen.__init__ +def check_call( + args: _CMD, + bufsize: int = ..., + executable: AnyPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: Optional[float] = ..., +) -> int: ... + +if sys.version_info >= (3, 7): + # 3.7 added text @overload - def run( + def check_output( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Literal[True], + ) -> str: ... + @overload + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: str, + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> str: ... + @overload + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: str, + text: Optional[bool] = ..., + ) -> str: ... + @overload + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., - stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -365,20 +491,21 @@ else: restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., - # where the *real* keyword only args start - check: bool = ..., - input: Optional[str] = ..., + # where the real keyword only ones start timeout: Optional[float] = ..., - ) -> CompletedProcess[str]: ... + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> str: ... @overload - def run( + def check_output( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., - stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -390,19 +517,20 @@ else: start_new_session: bool = ..., pass_fds: Any = ..., *, - check: bool = ..., - input: Optional[bytes] = ..., timeout: Optional[float] = ..., - ) -> CompletedProcess[bytes]: ... + input: _TXT = ..., + encoding: None = ..., + errors: None = ..., + text: Literal[None, False] = ..., + ) -> bytes: ... @overload - def run( + def check_output( args: _CMD, bufsize: int = ..., - executable: AnyPath = ..., + executable: Optional[AnyPath] = ..., stdin: _FILE = ..., - stdout: _FILE = ..., stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., @@ -414,386 +542,141 @@ else: start_new_session: bool = ..., pass_fds: Any = ..., *, - check: bool = ..., - input: Optional[_TXT] = ..., timeout: Optional[float] = ..., - ) -> CompletedProcess[Any]: ... - -# Same args as Popen.__init__ -def call(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ...) -> int: ... - -# Same args as Popen.__init__ -def check_call(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - timeout: Optional[float] = ...) -> int: ... + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> Any: ... # morally: -> _TXT -if sys.version_info >= (3, 7): - # 3.7 added text - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - text: Literal[True], - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: str, - errors: Optional[str] = ..., - text: Optional[bool] = ..., - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: str, - text: Optional[bool] = ..., - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - *, - universal_newlines: Literal[True], - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - # where the real keyword only ones start - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - text: Optional[bool] = ..., - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: None = ..., - errors: None = ..., - text: Literal[None, False] = ..., - ) -> bytes: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - text: Optional[bool] = ..., - ) -> Any: ... # morally: -> _TXT -elif sys.version_info >= (3, 6): - # 3.6 added encoding and errors - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: str, - errors: Optional[str] = ..., - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: str, - ) -> str: ... - @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - universal_newlines: Literal[True], - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - ) -> str: ... +else: @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: None = ..., - errors: None = ..., - ) -> bytes: ... + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: str, + errors: Optional[str] = ..., + ) -> str: ... @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: Optional[float] = ..., - input: _TXT = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ..., - ) -> Any: ... # morally: -> _TXT -else: + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: str, + ) -> str: ... @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - input: _TXT = ..., - *, - timeout: Optional[float] = ..., - universal_newlines: Literal[True], - ) -> str: ... + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + universal_newlines: Literal[True], + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> str: ... @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - input: _TXT = ..., - *, - timeout: Optional[float] = ..., - ) -> bytes: ... + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: None = ..., + errors: None = ..., + ) -> bytes: ... @overload - def check_output(args: _CMD, - bufsize: int = ..., - executable: AnyPath = ..., - stdin: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - input: _TXT = ..., - *, - timeout: Optional[float] = ..., - ) -> Any: ... # morally: -> _TXT - + def check_output( + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: Optional[float] = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Any: ... # morally: -> _TXT PIPE: int STDOUT: int DEVNULL: int + class SubprocessError(Exception): ... + class TimeoutExpired(SubprocessError): def __init__(self, cmd: _CMD, timeout: float, output: Optional[_TXT] = ..., stderr: Optional[_TXT] = ...) -> None: ... # morally: _CMD @@ -804,7 +687,6 @@ class TimeoutExpired(SubprocessError): stdout: Any stderr: Any - class CalledProcessError(SubprocessError): returncode: int # morally: _CMD @@ -815,12 +697,7 @@ class CalledProcessError(SubprocessError): # morally: Optional[_TXT] stdout: Any stderr: Any - - def __init__(self, - returncode: int, - cmd: _CMD, - output: Optional[_TXT] = ..., - stderr: Optional[_TXT] = ...) -> None: ... + def __init__(self, returncode: int, cmd: _CMD, output: Optional[_TXT] = ..., stderr: Optional[_TXT] = ...) -> None: ... class Popen(Generic[AnyStr]): args: _CMD @@ -837,344 +714,318 @@ class Popen(Generic[AnyStr]): if sys.version_info >= (3, 7): # text is added in 3.7 @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - text: Optional[bool] = ..., - encoding: str, - errors: Optional[str] = ...) -> Popen[str]: ... - @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - text: Optional[bool] = ..., - encoding: Optional[str] = ..., - errors: str) -> Popen[str]: ... - @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - *, - universal_newlines: Literal[True], - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - # where the *real* keyword only args start - text: Optional[bool] = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> Popen[str]: ... - @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - text: Literal[True], - encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> Popen[str]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: str, + errors: Optional[str] = ..., + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - text: Literal[None, False] = ..., - encoding: None = ..., - errors: None = ...) -> Popen[bytes]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: str, + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - text: Optional[bool] = ..., - encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> Popen[Any]: ... - elif sys.version_info >= (3, 6): + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - encoding: str, - errors: Optional[str] = ...) -> Popen[str]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[True], + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - encoding: Optional[str] = ..., - errors: str) -> Popen[str]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[None, False] = ..., + encoding: None = ..., + errors: None = ..., + ) -> Popen[bytes]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - *, - universal_newlines: Literal[True], - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - # where the *real* keyword only args start - encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> Popen[str]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Popen[Any]: ... + else: @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: Literal[False] = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - encoding: None = ..., - errors: None = ...) -> Popen[bytes]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: str, + errors: Optional[str] = ..., + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - encoding: Optional[str] = ..., - errors: Optional[str] = ...) -> Popen[Any]: ... - else: + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: Optional[str] = ..., + errors: str, + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - *, - universal_newlines: Literal[True], - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ...) -> Popen[str]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + *, + universal_newlines: Literal[True], + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Popen[str]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - *, - universal_newlines: Literal[False] = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ...) -> Popen[bytes]: ... + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: None = ..., + errors: None = ..., + ) -> Popen[bytes]: ... @overload - def __new__(cls, - args: _CMD, - bufsize: int = ..., - executable: Optional[AnyPath] = ..., - stdin: Optional[_FILE] = ..., - stdout: Optional[_FILE] = ..., - stderr: Optional[_FILE] = ..., - preexec_fn: Optional[Callable[[], Any]] = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: Optional[AnyPath] = ..., - env: Optional[_ENV] = ..., - universal_newlines: bool = ..., - startupinfo: Optional[Any] = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ...) -> Popen[Any]: ... - + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[AnyPath] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[AnyPath] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Popen[Any]: ... def poll(self) -> Optional[int]: ... if sys.version_info >= (3, 7): def wait(self, timeout: Optional[float] = ...) -> int: ... else: def wait(self, timeout: Optional[float] = ..., endtime: Optional[float] = ...) -> int: ... # Return str/bytes - def communicate(self, - input: Optional[AnyStr] = ..., - timeout: Optional[float] = ..., - # morally this should be optional - ) -> Tuple[AnyStr, AnyStr]: ... + def communicate( + self, + input: Optional[AnyStr] = ..., + timeout: Optional[float] = ..., + # morally this should be optional + ) -> Tuple[AnyStr, AnyStr]: ... def send_signal(self, sig: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... def __enter__(self: _S) -> _S: ... - def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: ... + def __exit__( + self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # The result really is always a str. def getstatusoutput(cmd: _TXT) -> Tuple[int, str]: ... def getoutput(cmd: _TXT) -> str: ... - def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented -if sys.platform == 'win32': +if sys.platform == "win32": class STARTUPINFO: if sys.version_info >= (3, 7): - def __init__(self, *, dwFlags: int = ..., hStdInput: Optional[Any] = ..., hStdOutput: Optional[Any] = ..., hStdError: Optional[Any] = ..., wShowWindow: int = ..., lpAttributeList: Optional[Mapping[str, Any]] = ...) -> None: ... + def __init__( + self, + *, + dwFlags: int = ..., + hStdInput: Optional[Any] = ..., + hStdOutput: Optional[Any] = ..., + hStdError: Optional[Any] = ..., + wShowWindow: int = ..., + lpAttributeList: Optional[Mapping[str, Any]] = ..., + ) -> None: ... dwFlags: int hStdInput: Optional[Any] hStdOutput: Optional[Any] @@ -1182,7 +1033,6 @@ if sys.platform == 'win32': wShowWindow: int if sys.version_info >= (3, 7): lpAttributeList: Mapping[str, Any] - STD_INPUT_HANDLE: Any STD_OUTPUT_HANDLE: Any STD_ERROR_HANDLE: Any diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 782ff721418a..b9475937c012 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,7 +1,5 @@ -# Stubs for sunau (Python 2 and 3) - import sys -from typing import Any, NamedTuple, NoReturn, Optional, Text, IO, Union, Tuple +from typing import IO, Any, NamedTuple, NoReturn, Optional, Text, Tuple, Union _File = Union[Text, IO[bytes]] @@ -83,5 +81,6 @@ class Au_write: # Returns a Au_read if mode is rb and Au_write if mode is wb def open(f: _File, mode: Optional[str] = ...) -> Any: ... + if sys.version_info < (3, 9): openfp = open diff --git a/mypy/typeshed/stdlib/symbol.pyi b/mypy/typeshed/stdlib/symbol.pyi index 59be5776560b..6fbe306fabe9 100644 --- a/mypy/typeshed/stdlib/symbol.pyi +++ b/mypy/typeshed/stdlib/symbol.pyi @@ -1,6 +1,3 @@ -# Stubs for symbol (Python 3) - -import sys from typing import Dict single_input: int @@ -20,8 +17,7 @@ stmt: int simple_stmt: int small_stmt: int expr_stmt: int -if sys.version_info >= (3, 6): - annassign: int +annassign: int testlist_star_expr: int augassign: int del_stmt: int diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index fd8b9ad79bb8..9fe53402d4ec 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,5 +1,5 @@ import sys -from typing import List, Sequence, Tuple, Text +from typing import List, Sequence, Text, Tuple def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index fb53b7b50291..9052ce32b765 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -1,18 +1,25 @@ -# Stubs for sys -# Ron Murawski - -# based on http://docs.python.org/3.2/library/sys.html - -from typing import ( - List, NoReturn, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, - Union, TypeVar, Callable, Type -) import sys +from builtins import object as _object +from importlib.abc import MetaPathFinder, PathEntryFinder from types import FrameType, ModuleType, TracebackType +from typing import ( + Any, + AsyncGenerator, + Callable, + Dict, + List, + NoReturn, + Optional, + Sequence, + TextIO, + Tuple, + Type, + TypeVar, + Union, + overload, +) -from importlib.abc import MetaPathFinder - -_T = TypeVar('_T') +_T = TypeVar("_T") # The following type alias are stub-only and do not exist during runtime _ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] @@ -45,7 +52,7 @@ meta_path: List[MetaPathFinder] modules: Dict[str, ModuleType] path: List[str] path_hooks: List[Any] # TODO precise type; function, path to finder -path_importer_cache: Dict[str, Any] # TODO precise type +path_importer_cache: Dict[str, Optional[PathEntryFinder]] platform: str if sys.version_info >= (3, 9): platlibdir: str @@ -70,8 +77,8 @@ if sys.platform == "win32": winver: str _xoptions: Dict[Any, Any] - flags: _flags + class _flags: debug: int division_warning: int @@ -91,20 +98,22 @@ class _flags: utf8_mode: int float_info: _float_info + class _float_info: - epsilon: float # DBL_EPSILON - dig: int # DBL_DIG - mant_dig: int # DBL_MANT_DIG - max: float # DBL_MAX - max_exp: int # DBL_MAX_EXP + epsilon: float # DBL_EPSILON + dig: int # DBL_DIG + mant_dig: int # DBL_MANT_DIG + max: float # DBL_MAX + max_exp: int # DBL_MAX_EXP max_10_exp: int # DBL_MAX_10_EXP - min: float # DBL_MIN - min_exp: int # DBL_MIN_EXP + min: float # DBL_MIN + min_exp: int # DBL_MIN_EXP min_10_exp: int # DBL_MIN_10_EXP - radix: int # FLT_RADIX - rounds: int # FLT_ROUNDS + radix: int # FLT_RADIX + rounds: int # FLT_ROUNDS hash_info: _hash_info + class _hash_info: width: int modulus: int @@ -113,6 +122,7 @@ class _hash_info: imag: int implementation: _implementation + class _implementation: name: str version: _version_info @@ -120,6 +130,7 @@ class _implementation: cache_tag: str int_info: _int_info + class _int_info: bits_per_digit: int sizeof_digit: int @@ -130,46 +141,46 @@ class _version_info(Tuple[int, int, int, str, int]): micro: int releaselevel: str serial: int + version_info: _version_info def call_tracing(__func: Callable[..., _T], __args: Any) -> _T: ... def _clear_type_cache() -> None: ... -def _current_frames() -> Dict[int, Any]: ... +def _current_frames() -> Dict[int, FrameType]: ... +def _getframe(__depth: int = ...) -> FrameType: ... def _debugmallocstats() -> None: ... def __displayhook__(value: object) -> None: ... -def __excepthook__(type_: Type[BaseException], value: BaseException, - traceback: TracebackType) -> None: ... +def __excepthook__(type_: Type[BaseException], value: BaseException, traceback: TracebackType) -> None: ... def exc_info() -> _OptExcInfo: ... + # sys.exit() accepts an optional argument of anything printable def exit(__status: object = ...) -> NoReturn: ... def getdefaultencoding() -> str: ... -if sys.platform != 'win32': + +if sys.platform != "win32": def getdlopenflags() -> int: ... + def getfilesystemencoding() -> str: ... +def getfilesystemencodeerrors() -> str: ... def getrefcount(__object: Any) -> int: ... def getrecursionlimit() -> int: ... - @overload def getsizeof(obj: object) -> int: ... @overload def getsizeof(obj: object, default: int) -> int: ... - def getswitchinterval() -> float: ... -def _getframe(__depth: int = ...) -> FrameType: ... - _ProfileFunc = Callable[[FrameType, str, Any], Any] + def getprofile() -> Optional[_ProfileFunc]: ... def setprofile(profilefunc: Optional[_ProfileFunc]) -> None: ... _TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] + def gettrace() -> Optional[_TraceFunc]: ... def settrace(tracefunc: Optional[_TraceFunc]) -> None: ... - -class _WinVersion(Tuple[int, int, int, int, - str, int, int, int, int, - Tuple[int, int, int]]): +class _WinVersion(Tuple[int, int, int, int, str, int, int, int, int, Tuple[int, int, int]]): major: int minor: int build: int @@ -185,7 +196,6 @@ if sys.platform == "win32": def getwindowsversion() -> _WinVersion: ... def intern(__string: str) -> str: ... - def is_finalizing() -> bool: ... if sys.version_info >= (3, 7): @@ -194,9 +204,9 @@ if sys.version_info >= (3, 7): if sys.platform != "win32": def setdlopenflags(__flags: int) -> None: ... + def setrecursionlimit(__limit: int) -> None: ... def setswitchinterval(__interval: float) -> None: ... - def gettotalrefcount() -> int: ... # Debug builds only if sys.version_info < (3, 9): @@ -210,16 +220,16 @@ if sys.version_info >= (3, 8): exc_value: Optional[BaseException] exc_traceback: Optional[TracebackType] err_msg: Optional[str] - object: Optional[object] + object: Optional[_object] unraisablehook: Callable[[UnraisableHookArgs], Any] def addaudithook(hook: Callable[[str, Tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... -if sys.version_info >= (3, 6): - from typing import AsyncGenerator - _AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] - class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): - firstiter: _AsyncgenHook - finalizer: _AsyncgenHook - def get_asyncgen_hooks() -> _asyncgen_hooks: ... - def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... +_AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] + +class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): + firstiter: _AsyncgenHook + finalizer: _AsyncgenHook + +def get_asyncgen_hooks() -> _asyncgen_hooks: ... +def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index 6548f40588c8..ed0aa6d5b501 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -1,4 +1,4 @@ -from typing import overload, Any, Dict, IO, List, Optional, Tuple, Union +from typing import IO, Any, Dict, List, Optional, Tuple, overload def get_config_var(name: str) -> Optional[str]: ... @overload diff --git a/mypy/typeshed/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi index 1237a6b0b241..49169f40db5c 100644 --- a/mypy/typeshed/stdlib/syslog.pyi +++ b/mypy/typeshed/stdlib/syslog.pyi @@ -37,7 +37,6 @@ 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 diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 8a64902de56f..12e80480cc17 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -1,10 +1,7 @@ -from typing import ( - Callable, IO, Iterable, Iterator, List, Mapping, Optional, Type, - Union, Tuple, Dict, Set -) import sys -from _typeshed import AnyPath +from _typeshed import AnyPath, StrPath from types import TracebackType +from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, Type, Union # tar constants NUL: bytes @@ -51,30 +48,36 @@ PAX_NUMBER_FIELDS: Dict[str, type] if sys.version_info >= (3,): PAX_NAME_FIELDS: Set[str] - ENCODING: str if sys.version_info < (3,): TAR_PLAIN: int TAR_GZIPPED: int -def open(name: Optional[AnyPath] = ..., mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., - *, format: Optional[int] = ..., tarinfo: Optional[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: ... +def open( + name: Optional[AnyPath] = ..., + 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 TarFile(Iterable[TarInfo]): name: Optional[AnyPath] mode: str fileobj: Optional[IO[bytes]] format: Optional[int] - tarinfo: Optional[TarInfo] + tarinfo: Type[TarInfo] dereference: Optional[bool] ignore_zeros: Optional[bool] encoding: Optional[str] @@ -84,57 +87,66 @@ class TarFile(Iterable[TarInfo]): errorlevel: Optional[int] if sys.version_info < (3,): posix: bool - def __init__(self, name: Optional[AnyPath] = ..., mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., - format: Optional[int] = ..., tarinfo: Optional[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] = ...) -> None: ... + def __init__( + self, + name: Optional[AnyPath] = ..., + 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 __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[AnyPath] = ..., mode: str = ..., - fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., - *, format: Optional[int] = ..., tarinfo: Optional[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: ... + def open( + cls, + name: Optional[AnyPath] = ..., + 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: ... 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: ... + def list(self, verbose: bool = ..., *, members: Optional[List[TarInfo]] = ...) -> None: ... else: def list(self, verbose: bool = ...) -> None: ... def next(self) -> Optional[TarInfo]: ... if sys.version_info >= (3, 5): - def extractall(self, path: AnyPath = ..., - members: Optional[List[TarInfo]] = ..., - *, numeric_owner: bool = ...) -> None: ... + def extractall( + self, path: AnyPath = ..., members: Optional[List[TarInfo]] = ..., *, numeric_owner: bool = ... + ) -> None: ... else: - def extractall(self, path: AnyPath = ..., - members: Optional[List[TarInfo]] = ...) -> None: ... + def extractall(self, path: AnyPath = ..., members: Optional[List[TarInfo]] = ...) -> None: ... if sys.version_info >= (3, 5): - def extract(self, member: Union[str, TarInfo], path: AnyPath = ..., - set_attrs: bool = ..., - *, numeric_owner: bool = ...) -> None: ... + 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 extractfile(self, - member: Union[str, TarInfo]) -> Optional[IO[bytes]]: ... + def extract(self, member: Union[str, TarInfo], path: AnyPath = ...) -> 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 @@ -148,28 +160,42 @@ class TarFile(Iterable[TarInfo]): def chmod(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented def utime(self, tarinfo: TarInfo, targetpath: AnyPath) -> None: ... # undocumented if sys.version_info >= (3, 7): - def add(self, name: str, arcname: Optional[str] = ..., - recursive: bool = ..., *, - filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + def add( + self, + name: StrPath, + arcname: Optional[StrPath] = ..., + recursive: bool = ..., + *, + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ..., + ) -> None: ... elif sys.version_info >= (3,): - def add(self, name: str, arcname: Optional[str] = ..., - recursive: bool = ..., - exclude: Optional[Callable[[str], bool]] = ..., *, - filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + def add( + self, + name: StrPath, + arcname: Optional[StrPath] = ..., + recursive: bool = ..., + exclude: Optional[Callable[[str], bool]] = ..., + *, + 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]] = ...) -> TarInfo: ... + 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: ... if sys.version_info >= (3, 9): def is_tarfile(name: Union[AnyPath, IO[bytes]]) -> bool: ... + else: def is_tarfile(name: AnyPath) -> bool: ... @@ -178,8 +204,7 @@ if sys.version_info < (3, 8): if sys.version_info < (3,): class TarFileCompat: - def __init__(self, filename: str, mode: str = ..., - compression: int = ...) -> None: ... + def __init__(self, filename: str, mode: str = ..., compression: int = ...) -> None: ... class TarError(Exception): ... class ReadError(TarError): ... @@ -190,6 +215,7 @@ class HeaderError(TarError): ... class TarInfo: name: str + path: str size: int mtime: int mode: int @@ -209,8 +235,7 @@ class TarInfo: def frombuf(cls, buf: bytes) -> TarInfo: ... @classmethod def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... - def tobuf(self, format: Optional[int] = ..., - encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... + def tobuf(self, format: Optional[int] = ..., encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... def isfile(self) -> bool: ... def isreg(self) -> bool: ... def isdir(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index 50b90b58dfe2..1f5be7a73c98 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -1,5 +1,3 @@ -# Stubs for telnetlib (Python 2 and 3) - import socket import sys from typing import Any, Callable, Match, Optional, Pattern, Sequence, Tuple, Union @@ -84,8 +82,8 @@ EXOPL: bytes NOOPT: bytes class Telnet: - def __init__(self, host: Optional[str] = ..., port: int = ..., - timeout: int = ...) -> None: ... + host: Optional[str] # undocumented + def __init__(self, host: Optional[str] = ..., port: int = ..., timeout: int = ...) -> None: ... def open(self, host: str, port: int = ..., timeout: int = ...) -> None: ... def msg(self, msg: str, *args: Any) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... @@ -109,7 +107,9 @@ class Telnet: def interact(self) -> None: ... def mt_interact(self) -> None: ... def listener(self) -> None: ... - def expect(self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[int] = ...) -> Tuple[int, Optional[Match[bytes]], bytes]: ... + def expect( + self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[int] = ... + ) -> 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: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 0f5cdecf4ee6..7b87fd46e368 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -1,9 +1,12 @@ import os import sys from types import TracebackType -from typing import Any, AnyStr, Generic, IO, Iterable, Iterator, List, Optional, overload, Tuple, Type, TypeVar, Union +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List, Optional, Tuple, Type, TypeVar, Union, overload from typing_extensions import Literal +if sys.version_info >= (3, 9): + from types import GenericAlias + # global variables TMP_MAX: int tempdir: Optional[str] @@ -11,10 +14,7 @@ template: str _S = TypeVar("_S") _T = TypeVar("_T") # for pytype, define typevar in same file as alias -if sys.version_info >= (3, 6): - _DirT = Union[_T, os.PathLike[_T]] -else: - _DirT = Union[_T] +_DirT = Union[_T, os.PathLike[_T]] if sys.version_info >= (3, 8): @overload @@ -28,7 +28,7 @@ if sys.version_info >= (3, 8): dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[str]: ... @overload def NamedTemporaryFile( @@ -41,7 +41,7 @@ if sys.version_info >= (3, 8): dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[bytes]: ... @overload def NamedTemporaryFile( @@ -54,8 +54,9 @@ if sys.version_info >= (3, 8): dir: Optional[_DirT[AnyStr]] = ..., delete: bool = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[Any]: ... + else: @overload def NamedTemporaryFile( @@ -105,7 +106,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[str]: ... @overload def TemporaryFile( @@ -117,7 +118,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[bytes]: ... @overload def TemporaryFile( @@ -129,7 +130,7 @@ else: prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> IO[Any]: ... else: @overload @@ -180,7 +181,7 @@ class SpooledTemporaryFile(IO[AnyStr]): prefix: Optional[str] = ..., dir: Optional[str] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> None: ... @overload def __init__( @@ -194,7 +195,7 @@ class SpooledTemporaryFile(IO[AnyStr]): prefix: Optional[str] = ..., dir: Optional[str] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> None: ... @overload def __init__( @@ -208,9 +209,8 @@ class SpooledTemporaryFile(IO[AnyStr]): prefix: Optional[str] = ..., dir: Optional[str] = ..., *, - errors: Optional[str] = ... + errors: Optional[str] = ..., ) -> None: ... - @property def errors(self) -> Optional[str]: ... else: @@ -287,6 +287,8 @@ class TemporaryDirectory(Generic[AnyStr]): def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... def mkstemp( suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., text: bool = ... diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index 9c8a9553e2af..9eecbf68136f 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -1,7 +1,7 @@ -from typing import List, Union from _typeshed import FileDescriptorLike +from typing import Any, List, Union -_Attr = List[Union[int, List[bytes]]] +_Attr = List[Union[int, List[Union[bytes, int]]]] # TODO constants not really documented B0: int @@ -236,7 +236,7 @@ VWERASE: int XCASE: int XTABS: int -def tcgetattr(fd: FileDescriptorLike) -> _Attr: ... +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: ... diff --git a/mypy/typeshed/stdlib/textwrap.pyi b/mypy/typeshed/stdlib/textwrap.pyi index 4cec8c50c828..0fd80bcb6cff 100644 --- a/mypy/typeshed/stdlib/textwrap.pyi +++ b/mypy/typeshed/stdlib/textwrap.pyi @@ -1,4 +1,4 @@ -from typing import Callable, List, Optional, Dict, Pattern +from typing import Callable, Dict, List, Optional, Pattern class TextWrapper: width: int = ... @@ -22,24 +22,22 @@ class TextWrapper: unicode_whitespace_trans: Dict[int, int] = ... uspace: int = ... x: str = ... # leaked loop variable - def __init__( - self, - width: int = ..., - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - drop_whitespace: bool = ..., - break_on_hyphens: bool = ..., - tabsize: int = ..., - *, - max_lines: Optional[int] = ..., - placeholder: str = ...) -> None: - ... - + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., + tabsize: int = ..., + *, + max_lines: Optional[int] = ..., + placeholder: str = ..., + ) -> None: ... # Private methods *are* part of the documented API for subclasses. def _munge_whitespace(self, text: str) -> str: ... def _split(self, text: str) -> List[str]: ... @@ -47,67 +45,56 @@ class TextWrapper: def _handle_long_word(self, reversed_chunks: List[str], cur_line: List[str], cur_len: int, width: int) -> None: ... def _wrap_chunks(self, chunks: List[str]) -> List[str]: ... def _split_chunks(self, text: str) -> List[str]: ... - def wrap(self, text: str) -> List[str]: ... def fill(self, text: str) -> str: ... - def wrap( - text: str, - width: int = ..., - *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., - max_lines: int = ..., - placeholder: str = ... -) -> List[str]: - ... - + text: str, + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ..., +) -> List[str]: ... def fill( - text: str, - width: int = ..., - *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., - max_lines: int = ..., - placeholder: str = ... -) -> str: - ... - + text: str, + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ..., +) -> str: ... def shorten( - text: str, - width: int, - *, - initial_indent: str = ..., - subsequent_indent: str = ..., - expand_tabs: bool = ..., - tabsize: int = ..., - replace_whitespace: bool = ..., - fix_sentence_endings: bool = ..., - break_long_words: bool = ..., - break_on_hyphens: bool = ..., - drop_whitespace: bool = ..., - # Omit `max_lines: int = None`, it is forced to 1 here. - placeholder: str = ... -) -> str: - ... - -def dedent(text: str) -> str: - ... - -def indent(text: str, prefix: str, predicate: Optional[Callable[[str], bool]] = ...) -> str: - ... + text: str, + width: int, + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + # Omit `max_lines: int = None`, it is forced to 1 here. + placeholder: str = ..., +) -> str: ... +def dedent(text: str) -> str: ... +def indent(text: str, prefix: str, predicate: Optional[Callable[[str], bool]] = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/this.pyi b/mypy/typeshed/stdlib/this.pyi index c347e431d539..0687a6675cca 100644 --- a/mypy/typeshed/stdlib/this.pyi +++ b/mypy/typeshed/stdlib/this.pyi @@ -1,4 +1,3 @@ - from typing import Dict s: str diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index ae8997251322..625ec7b5c4f6 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,20 +1,17 @@ - -from typing import ( - Any, Callable, Iterable, List, Mapping, Optional, Text, Tuple, Type, Union, - TypeVar, -) -from types import FrameType, TracebackType import sys +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') +_T = TypeVar("_T") __all__: List[str] def active_count() -> int: ... + if sys.version_info < (3,): def activeCount() -> int: ... @@ -41,30 +38,35 @@ if sys.version_info >= (3,): 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 if sys.version_info >= (3,): - def __init__(self, group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[str] = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] = ..., - *, daemon: Optional[bool] = ...) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[str, Any] = ..., + *, + daemon: Optional[bool] = ..., + ) -> None: ... else: - def __init__(self, group: None = ..., - target: Optional[Callable[..., Any]] = ..., - name: Optional[Text] = ..., - args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] = ...) -> None: ... + def __init__( + self, + group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[Text] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[Text, Any] = ..., + ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: Optional[float] = ...) -> None: ... @@ -79,16 +81,14 @@ class Thread: 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 __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: @@ -96,29 +96,26 @@ class Lock: 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 __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 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 __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: @@ -126,19 +123,17 @@ class Condition: 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: ... - class Semaphore: def __init__(self, value: int = ...) -> None: ... def __enter__(self) -> bool: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + 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: @@ -150,7 +145,6 @@ class Semaphore: class BoundedSemaphore(Semaphore): ... - class Event: def __init__(self) -> None: ... def is_set(self) -> bool: ... @@ -161,30 +155,33 @@ class Event: def wait(self, timeout: Optional[float] = ...) -> bool: ... if sys.version_info >= (3, 8): - from _thread import _ExceptHookArgs as ExceptHookArgs, ExceptHookArgs as _ExceptHookArgs # don't ask - excepthook: Callable[[_ExceptHookArgs], Any] + from _thread import _excepthook, _ExceptHookArgs + + excepthook = _excepthook + 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: ... + 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: Iterable[Any] = ..., kwargs: 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 __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 08703e0a9f82..e3315733510e 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,8 +1,6 @@ -"""Stub file for the 'time' module.""" -# See https://docs.python.org/3/library/time.html - import sys -from typing import Any, NamedTuple, Tuple, Union, Optional +from typing import Any, NamedTuple, Optional, Tuple, Union + if sys.version_info >= (3, 3): from types import SimpleNamespace @@ -15,12 +13,12 @@ daylight: int timezone: int tzname: Tuple[str, str] -if sys.version_info >= (3, 7) and sys.platform != 'win32': +if sys.version_info >= (3, 7) and sys.platform != "win32": CLOCK_BOOTTIME: int # Linux CLOCK_PROF: int # FreeBSD, NetBSD, OpenBSD CLOCK_UPTIME: int # FreeBSD, OpenBSD -if sys.version_info >= (3, 3) and sys.platform != 'win32': +if sys.version_info >= (3, 3) and sys.platform != "win32": CLOCK_HIGHRES: int # Solaris only CLOCK_MONOTONIC: int # Unix only CLOCK_MONOTONIC_RAW: int # Linux 2.6.28 or later @@ -41,13 +39,13 @@ class _struct_time(NamedTuple): 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: ... + if sys.version_info >= (3, 3): class struct_time(_struct_time): def __init__( @@ -55,7 +53,7 @@ if sys.version_info >= (3, 3): 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] + Tuple[int, int, int, int, int, int, int, int, int, str, int], ], _arg: Any = ..., ) -> None: ... @@ -64,22 +62,26 @@ if sys.version_info >= (3, 3): 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] + 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: ... + 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: ... def asctime(t: Union[_TimeTuple, struct_time] = ...) -> str: ... + if sys.version_info < (3, 8): def clock() -> float: ... + def ctime(secs: Optional[float] = ...) -> str: ... def gmtime(secs: Optional[float] = ...) -> struct_time: ... def localtime(secs: Optional[float] = ...) -> struct_time: ... @@ -88,7 +90,8 @@ 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': + +if sys.platform != "win32": def tzset() -> None: ... # Unix only if sys.version_info >= (3, 3): @@ -96,7 +99,7 @@ if sys.version_info >= (3, 3): def monotonic() -> float: ... def perf_counter() -> float: ... def process_time() -> float: ... - if sys.platform != 'win32': + 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 diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index bc4cbba87d36..336dd5c69c69 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,7 +1,5 @@ -# Stubs for timeit (Python 2 and 3) - import sys -from typing import Any, Callable, Dict, IO, List, Optional, Sequence, Text, Tuple, Union +from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Text, Tuple, Union _str = Union[str, Text] _Timer = Callable[[], float] @@ -11,8 +9,9 @@ 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: ... + 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 print_exc(self, file: Optional[IO[str]] = ...) -> None: ... @@ -22,13 +21,22 @@ class Timer: 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]: ... + 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 = ...) -> float: ... + def repeat( + stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ... + ) -> List[float]: ... + def main(args: Optional[Sequence[str]]) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 26b5ffee6bf1..c5ea645a1e8e 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -1,58 +1,172 @@ +import _tkinter import sys +from _typeshed import AnyPath from enum import Enum +from tkinter.constants import * # comment this out to find undefined identifier names with flake8 +from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Optional, Dict, Callable, Tuple, Type, Union -from tkinter.constants import * # noqa: F403 - -TclError: Any -wantobjects: Any -TkVersion: Any -TclVersion: Any -READABLE: Any -WRITABLE: Any -EXCEPTION: Any - -if sys.version_info >= (3, 6): - class EventType(str, Enum): - Activate: str = ... - ButtonPress: str = ... - ButtonRelease: str = ... - Circulate: str = ... - CirculateRequest: str = ... - ClientMessage: str = ... - Colormap: str = ... - Configure: str = ... - ConfigureRequest: str = ... - Create: str = ... - Deactivate: str = ... - Destroy: str = ... - Enter: str = ... - Expose: str = ... - FocusIn: str = ... - FocusOut: str = ... - GraphicsExpose: str = ... - Gravity: str = ... - KeyPress: str = ... - KeyRelease: str = ... - Keymap: str = ... - Leave: str = ... - Map: str = ... - MapRequest: str = ... - Mapping: str = ... - Motion: str = ... - MouseWheel: str = ... - NoExpose: str = ... - Property: str = ... - Reparent: str = ... - ResizeRequest: str = ... - Selection: str = ... - SelectionClear: str = ... - SelectionRequest: str = ... - Unmap: str = ... - VirtualEvent: str = ... - Visibility: str = ... - -class Event: +from typing import ( + Any, + Callable, + Dict, + Generic, + List, + Mapping, + Optional, + Protocol, + Sequence, + Tuple, + Type, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal, TypedDict + +# Using anything from tkinter.font in this file means that 'import tkinter' +# seems to also load tkinter.font. That's not how it actually works, but +# unfortunately not much can be done about it. https://github.com/python/typeshed/pull/4346 + +TclError = _tkinter.TclError +wantobjects: int +TkVersion: float +TclVersion: float +READABLE = _tkinter.READABLE +WRITABLE = _tkinter.WRITABLE +EXCEPTION = _tkinter.EXCEPTION + +# Quick guide for figuring out which widget class to choose: +# - Misc: any widget (don't use BaseWidget because Tk doesn't inherit from BaseWidget) +# - Widget: anything that is meant to be put into another widget with e.g. pack or grid +# +# Instructions for figuring out the correct type of each widget option: +# - See discussion on #4363. +# +# - Find the option from the manual page of the widget. Usually the manual +# page of a non-ttk widget has the same name as the tkinter class, in the +# 3tk section: +# +# $ sudo apt install tk-doc +# $ man 3tk label +# +# Ttk manual pages tend to have ttk_ prefixed names: +# +# $ man 3tk ttk_label +# +# Non-GUI things like the .after() method are often in the 3tcl section: +# +# $ sudo apt install tcl-doc +# $ man 3tcl after +# +# If you don't have man or apt, you can read these manual pages online: +# +# https://www.tcl.tk/doc/ +# +# Every option has '-' in front of its name in the manual page (and in Tcl). +# For example, there's an option named '-text' in the label manual page. +# +# - Tkinter has some options documented in docstrings, but don't rely on them. +# They aren't updated when a new version of Tk comes out, so the latest Tk +# manual pages (see above) are much more likely to actually contain all +# possible options. +# +# Also, reading tkinter's source code typically won't help much because it +# uses a lot of **kwargs and duck typing. Typically every argument goes into +# self.tk.call, which is _tkinter.TkappType.call, and the return value is +# whatever that returns. The type of that depends on how the Tcl interpreter +# represents the return value of the executed Tcl code. +# +# - If you think that int is an appropriate type for something, then you may +# actually want _ScreenUnits instead. +# +# - If you think that Callable[something] is an appropriate type for +# something, then you may actually want Union[Callable[something], str], +# because it's often possible to specify a string of Tcl code. +# +# - Some options can be set only in __init__, but all options are available +# when getting their values with configure's return value or cget. +# +# - Asks other tkinter users if you haven't worked much with tkinter. + +# _TkinterSequence[T] represents a sequence that tkinter understands. It +# differs from typing.Sequence[T]. For example, collections.deque a valid +# Sequence but not a valid _TkinterSequence: +# +# >>> tkinter.Label(font=('Helvetica', 12, collections.deque(['bold']))) +# Traceback (most recent call last): +# ... +# _tkinter.TclError: unknown font style "deque(['bold'])" +_T = TypeVar("_T") +_TkinterSequence = Union[List[_T], Tuple[_T, ...]] +_TkinterSequence2D = Union[List[List[_T]], List[Tuple[_T, ...]], Tuple[List[_T], ...], Tuple[Tuple[_T, ...], ...]] + +# Some widgets have an option named -compound that accepts different values +# than the _Compound defined here. Many other options have similar things. +_Anchor = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor +_Bitmap = str # manual page: Tk_GetBitmap +_ButtonCommand = Union[str, Callable[[], Any]] # return value is returned from Button.invoke() +_Color = str # typically '#rrggbb', '#rgb' or color names. +_Compound = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' +_Cursor = Union[str, Tuple[str], Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]] # manual page: Tk_GetCursor +_EntryValidateCommand = Union[ + Callable[[], bool], str, _TkinterSequence[str] +] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] +_ImageSpec = Union[_Image, str] # str can be from e.g. tkinter.image_names() +_Padding = Union[ + _ScreenUnits, + Tuple[_ScreenUnits], + Tuple[_ScreenUnits, _ScreenUnits], + Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], + Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], +] +_Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief +_ScreenUnits = Union[str, float] # manual page: Tk_GetPixels +_XYScrollCommand = Union[str, Callable[[float, float], Any]] # -xscrollcommand and -yscrollcommand in 'options' manual page +_TakeFocusValue = Union[int, Literal[""], Callable[[str], Optional[bool]]] # -takefocus in manual page named 'options' + +class EventType(str, Enum): + Activate: str = ... + ButtonPress: str = ... + ButtonRelease: str = ... + Circulate: str = ... + CirculateRequest: str = ... + ClientMessage: str = ... + Colormap: str = ... + Configure: str = ... + ConfigureRequest: str = ... + Create: str = ... + Deactivate: str = ... + Destroy: str = ... + Enter: str = ... + Expose: str = ... + FocusIn: str = ... + FocusOut: str = ... + GraphicsExpose: str = ... + Gravity: str = ... + KeyPress: str = ... + KeyRelease: str = ... + Keymap: str = ... + Leave: str = ... + Map: str = ... + MapRequest: str = ... + Mapping: str = ... + Motion: str = ... + MouseWheel: str = ... + NoExpose: str = ... + Property: str = ... + Reparent: str = ... + ResizeRequest: str = ... + Selection: str = ... + SelectionClear: str = ... + SelectionRequest: str = ... + Unmap: str = ... + VirtualEvent: str = ... + Visibility: str = ... + +# Events considered covariant because you should never assign to event.widget. +_W = TypeVar("_W", covariant=True, bound="Misc") + +class Event(Generic[_W]): serial: int num: int focus: bool @@ -69,50 +183,52 @@ class Event: send_event: bool keysym: str keysym_num: int - if sys.version_info >= (3, 6): - type: EventType - else: - type: str - widget: Misc + type: EventType + widget: _W delta: int def NoDefaultRoot(): ... +_TraceMode = Literal["array", "read", "write", "unset"] + class Variable: - def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... - def __del__(self): ... - def set(self, value): ... - initialize: Any - def get(self): ... - def trace_variable(self, mode, callback): ... - trace: Any - def trace_vdelete(self, mode, cbname): ... - def trace_vinfo(self): ... - def __eq__(self, other): ... - if sys.version_info >= (3, 6): - def trace_add(self, mode, callback): ... - def trace_remove(self, mode, cbname) -> None: ... - def trace_info(self): ... + def __init__(self, master: Optional[Misc] = ..., value: Optional[Any] = ..., name: Optional[str] = ...) -> None: ... + def set(self, value: Any) -> None: ... + initialize = set + def get(self) -> Any: ... + def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], Any]) -> str: ... + def trace_remove(self, mode: _TraceMode, cbname: str) -> None: ... + def trace_info(self) -> List[Tuple[Tuple[_TraceMode, ...], str]]: ... + def trace_variable(self, mode, callback): ... # deprecated + def trace_vdelete(self, mode, cbname): ... # deprecated + def trace_vinfo(self): ... # deprecated + trace = trace_variable # deprecated class StringVar(Variable): - def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... - def get(self): ... + def __init__(self, master: Optional[Misc] = ..., value: Optional[str] = ..., name: Optional[str] = ...) -> None: ... + def set(self, value: str) -> None: ... + initialize = set + def get(self) -> str: ... class IntVar(Variable): - def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... - def get(self): ... + def __init__(self, master: Optional[Misc] = ..., value: Optional[int] = ..., name: Optional[str] = ...) -> None: ... + def set(self, value: int) -> None: ... + initialize = set + def get(self) -> int: ... class DoubleVar(Variable): - def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... - def get(self): ... + def __init__(self, master: Optional[Misc] = ..., value: Optional[float] = ..., name: Optional[str] = ...) -> None: ... + def set(self, value: float) -> None: ... + initialize = set + def get(self) -> float: ... class BooleanVar(Variable): - def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... - def set(self, value): ... - initialize: Any - def get(self): ... + def __init__(self, master: Optional[Misc] = ..., value: Optional[bool] = ..., name: Optional[str] = ...) -> None: ... + def set(self, value: bool) -> None: ... + initialize = set + def get(self) -> bool: ... -def mainloop(n: int = ...): ... +def mainloop(n: int = ...) -> None: ... getint: Any getdouble: Any @@ -120,38 +236,43 @@ getdouble: Any def getboolean(s): ... class Misc: - def destroy(self): ... - def deletecommand(self, name): ... + master: Optional[Misc] + tk: _tkinter.TkappType + children: Dict[str, Widget] + def destroy(self) -> None: ... + def deletecommand(self, name: str) -> None: ... def tk_strictMotif(self, boolean: Optional[Any] = ...): ... def tk_bisque(self): ... def tk_setPalette(self, *args, **kw): ... - if sys.version_info < (3, 6): - def tk_menuBar(self, *args): ... - def wait_variable(self, name: Union[str, Variable] = ...): ... - waitvar: Any - def wait_window(self, window: Optional[Any] = ...): ... - def wait_visibility(self, window: Optional[Any] = ...): ... + def wait_variable(self, name: Union[str, Variable] = ...) -> None: ... + waitvar = wait_variable + def wait_window(self, window: Optional[Misc] = ...) -> None: ... + def wait_visibility(self, window: Optional[Misc] = ...) -> None: ... def setvar(self, name: str = ..., value: str = ...): ... def getvar(self, name: str = ...): ... def getint(self, s): ... def getdouble(self, s): ... def getboolean(self, s): ... - def focus_set(self): ... - focus: Any - def focus_force(self): ... - def focus_get(self): ... - def focus_displayof(self): ... - def focus_lastfor(self): ... - def tk_focusFollowsMouse(self): ... - def tk_focusNext(self): ... - def tk_focusPrev(self): ... - def after(self, ms, func: Optional[Any] = ..., *args): ... - def after_idle(self, func, *args): ... - def after_cancel(self, id): ... - def bell(self, displayof: int = ...): ... - def clipboard_get(self, **kw): ... - def clipboard_clear(self, **kw): ... - def clipboard_append(self, string, **kw): ... + def focus_set(self) -> None: ... + focus = focus_set + def focus_force(self) -> None: ... + def focus_get(self) -> Optional[Misc]: ... + def focus_displayof(self) -> Optional[Misc]: ... + def focus_lastfor(self) -> Optional[Misc]: ... + def tk_focusFollowsMouse(self) -> None: ... + def tk_focusNext(self) -> Optional[Misc]: ... + def tk_focusPrev(self) -> Optional[Misc]: ... + @overload + def after(self, ms: int, func: None = ...) -> None: ... + @overload + def after(self, ms: Union[int, Literal["idle"]], func: Callable[..., Any], *args: Any) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[..., Any], *args: Any) -> str: ... + def after_cancel(self, id: str) -> None: ... + def bell(self, displayof: Union[Literal[0], Misc, None] = ...): ... + def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: ... + def clipboard_clear(self, *, displayof: Misc = ...) -> None: ... + def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...): ... def grab_current(self): ... def grab_release(self): ... def grab_set(self): ... @@ -169,100 +290,182 @@ class Misc: def send(self, interp, cmd, *args): ... def lower(self, belowThis: Optional[Any] = ...): ... def tkraise(self, aboveThis: Optional[Any] = ...): ... - lift: Any - def winfo_atom(self, name, displayof: int = ...): ... - def winfo_atomname(self, id, displayof: int = ...): ... - def winfo_cells(self): ... - def winfo_children(self): ... - def winfo_class(self): ... - def winfo_colormapfull(self): ... - def winfo_containing(self, rootX, rootY, displayof: int = ...): ... - def winfo_depth(self): ... - def winfo_exists(self): ... - def winfo_fpixels(self, number): ... - def winfo_geometry(self): ... - def winfo_height(self): ... - def winfo_id(self): ... - def winfo_interps(self, displayof: int = ...): ... - def winfo_ismapped(self): ... - def winfo_manager(self): ... - def winfo_name(self): ... - def winfo_parent(self): ... - def winfo_pathname(self, id, displayof: int = ...): ... - def winfo_pixels(self, number): ... - def winfo_pointerx(self): ... - def winfo_pointerxy(self): ... - def winfo_pointery(self): ... - def winfo_reqheight(self): ... - def winfo_reqwidth(self): ... - def winfo_rgb(self, color): ... - def winfo_rootx(self): ... - def winfo_rooty(self): ... - def winfo_screen(self): ... - def winfo_screencells(self): ... - def winfo_screendepth(self): ... - def winfo_screenheight(self): ... - def winfo_screenmmheight(self): ... - def winfo_screenmmwidth(self): ... - def winfo_screenvisual(self): ... - def winfo_screenwidth(self): ... - def winfo_server(self): ... - def winfo_toplevel(self): ... - def winfo_viewable(self): ... - def winfo_visual(self): ... - def winfo_visualid(self): ... - def winfo_visualsavailable(self, includeids: int = ...): ... - def winfo_vrootheight(self): ... - def winfo_vrootwidth(self): ... - def winfo_vrootx(self): ... - def winfo_vrooty(self): ... - def winfo_width(self): ... - def winfo_x(self): ... - def winfo_y(self): ... - def update(self): ... - def update_idletasks(self): ... + lift = tkraise + def winfo_atom(self, name: str, displayof: Union[Literal[0], Misc, None] = ...): ... + def winfo_atomname(self, id: int, displayof: Union[Literal[0], Misc, None] = ...): ... + def winfo_cells(self) -> int: ... + def winfo_children(self) -> List[Widget]: ... # Widget because it can't be Toplevel or Tk + def winfo_class(self) -> str: ... + def winfo_colormapfull(self) -> bool: ... + def winfo_containing(self, rootX: int, rootY: int, displayof: Union[Literal[0], Misc, None] = ...) -> Optional[Misc]: ... + def winfo_depth(self) -> int: ... + def winfo_exists(self) -> bool: ... + def winfo_fpixels(self, number: _ScreenUnits) -> float: ... + def winfo_geometry(self) -> str: ... + def winfo_height(self) -> int: ... + def winfo_id(self) -> int: ... + def winfo_interps(self, displayof: Union[Literal[0], Misc, None] = ...) -> Tuple[str, ...]: ... + def winfo_ismapped(self) -> bool: ... + def winfo_manager(self) -> str: ... + def winfo_name(self) -> str: ... + def winfo_parent(self) -> str: ... # return value needs nametowidget() + def winfo_pathname(self, id: int, displayof: Union[Literal[0], Misc, None] = ...): ... + def winfo_pixels(self, number: _ScreenUnits) -> int: ... + def winfo_pointerx(self) -> int: ... + def winfo_pointerxy(self) -> Tuple[int, int]: ... + def winfo_pointery(self) -> int: ... + def winfo_reqheight(self) -> int: ... + def winfo_reqwidth(self) -> int: ... + def winfo_rgb(self, color: _Color) -> Tuple[int, int, int]: ... + def winfo_rootx(self) -> int: ... + def winfo_rooty(self) -> int: ... + def winfo_screen(self) -> str: ... + def winfo_screencells(self) -> int: ... + def winfo_screendepth(self) -> int: ... + def winfo_screenheight(self) -> int: ... + def winfo_screenmmheight(self) -> int: ... + def winfo_screenmmwidth(self) -> int: ... + def winfo_screenvisual(self) -> str: ... + def winfo_screenwidth(self) -> int: ... + def winfo_server(self) -> str: ... + def winfo_toplevel(self) -> Union[Tk, Toplevel]: ... + def winfo_viewable(self) -> bool: ... + def winfo_visual(self) -> str: ... + def winfo_visualid(self) -> str: ... + def winfo_visualsavailable(self, includeids: int = ...) -> List[Tuple[str, int]]: ... + def winfo_vrootheight(self) -> int: ... + def winfo_vrootwidth(self) -> int: ... + def winfo_vrootx(self) -> int: ... + def winfo_vrooty(self) -> int: ... + def winfo_width(self) -> int: ... + def winfo_x(self) -> int: ... + def winfo_y(self) -> int: ... + def update(self) -> None: ... + def update_idletasks(self) -> None: ... def bindtags(self, tagList: Optional[Any] = ...): ... - def bind(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... - def unbind(self, sequence, funcid: Optional[Any] = ...): ... - def bind_all(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... - def unbind_all(self, sequence): ... - def bind_class(self, className, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... - def unbind_class(self, className, sequence): ... - def mainloop(self, n: int = ...): ... + # bind with isinstance(func, str) doesn't return anything, but all other + # binds do. The default value of func is not str. + @overload + def bind( + self, + sequence: Optional[str] = ..., + func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + add: Optional[bool] = ..., + ) -> str: ... + @overload + def bind(self, sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + @overload + def bind(self, *, func: str, add: Optional[bool] = ...) -> None: ... + # There's no way to know what type of widget bind_all and bind_class + # callbacks will get, so those are Misc. + @overload + def bind_all( + self, + sequence: Optional[str] = ..., + func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + add: Optional[bool] = ..., + ) -> str: ... + @overload + def bind_all(self, sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + @overload + def bind_all(self, *, func: str, add: Optional[bool] = ...) -> None: ... + @overload + def bind_class( + self, + className: str, + sequence: Optional[str] = ..., + func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + add: Optional[bool] = ..., + ) -> str: ... + @overload + def bind_class(self, className: str, sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + @overload + def bind_class(self, className: str, *, func: str, add: Optional[bool] = ...) -> None: ... + def unbind(self, sequence: str, funcid: Optional[str] = ...) -> None: ... + def unbind_all(self, sequence: str) -> None: ... + def unbind_class(self, className: str, sequence: str) -> None: ... + def mainloop(self, n: int = ...) -> None: ... def quit(self): ... - def nametowidget(self, name): ... - register: Any - def configure(self, cnf: Optional[Any] = ..., **kw): ... - config: Any - def cget(self, key): ... - __getitem__: Any - def __setitem__(self, key, value): ... - def keys(self): ... - def pack_propagate(self, flag=...): ... - propagate: Any - def pack_slaves(self): ... - slaves: Any - def place_slaves(self): ... - def grid_anchor(self, anchor: Optional[Any] = ...): ... - anchor: Any - def grid_bbox(self, column: Optional[Any] = ..., row: Optional[Any] = ..., col2: Optional[Any] = ..., - row2: Optional[Any] = ...): ... - bbox: Any - def grid_columnconfigure(self, index, cnf=..., **kw): ... - columnconfigure: Any - def grid_location(self, x, y): ... - def grid_propagate(self, flag=...): ... - def grid_rowconfigure(self, index, cnf=..., **kw): ... - rowconfigure: Any - def grid_size(self): ... - size: Any - def grid_slaves(self, row: Optional[Any] = ..., column: Optional[Any] = ...): ... - def event_add(self, virtual, *sequences): ... - def event_delete(self, virtual, *sequences): ... - def event_generate(self, sequence, **kw): ... - def event_info(self, virtual: Optional[Any] = ...): ... - def image_names(self): ... - def image_types(self): ... + def nametowidget(self, name: Union[str, Misc, _tkinter.Tcl_Obj]) -> Any: ... + def register( + self, func: Callable[..., Any], subst: Optional[Callable[..., Sequence[Any]]] = ..., needcleanup: int = ... + ) -> str: ... + def keys(self) -> List[str]: ... + @overload + def pack_propagate(self, flag: bool) -> Optional[bool]: ... + @overload + def pack_propagate(self) -> None: ... + propagate = pack_propagate + def grid_anchor(self, anchor: Optional[_Anchor] = ...) -> None: ... + anchor = grid_anchor + @overload + def grid_bbox( + self, column: None = ..., row: None = ..., col2: None = ..., row2: None = ... + ) -> Optional[Tuple[int, int, int, int]]: ... + @overload + def grid_bbox(self, column: int, row: int, col2: None = ..., row2: None = ...) -> Optional[Tuple[int, int, int, int]]: ... + @overload + def grid_bbox(self, column: int, row: int, col2: int, row2: int) -> Optional[Tuple[int, int, int, int]]: ... + bbox = grid_bbox + def grid_columnconfigure(self, index, cnf=..., **kw): ... # TODO + def grid_rowconfigure(self, index, cnf=..., **kw): ... # TODO + columnconfigure = grid_columnconfigure + rowconfigure = grid_rowconfigure + def grid_location(self, x: _ScreenUnits, y: _ScreenUnits) -> Tuple[int, int]: ... + @overload + def grid_propagate(self, flag: bool) -> None: ... + @overload + def grid_propagate(self) -> bool: ... + def grid_size(self) -> Tuple[int, int]: ... + size = grid_size + # Widget because Toplevel or Tk is never a slave + def pack_slaves(self) -> List[Widget]: ... + def grid_slaves(self, row: Optional[int] = ..., column: Optional[int] = ...) -> List[Widget]: ... + def place_slaves(self) -> List[Widget]: ... + slaves = pack_slaves + def event_add(self, virtual: str, *sequences: str) -> None: ... + def event_delete(self, virtual: str, *sequences: str) -> None: ... + def event_generate( + self, + sequence: str, + *, + above: Union[Misc, int] = ..., + borderwidth: _ScreenUnits = ..., + button: int = ..., + count: int = ..., + data: Any = ..., # anything with usable str() value + delta: int = ..., + detail: str = ..., + focus: bool = ..., + height: _ScreenUnits = ..., + keycode: int = ..., + keysym: str = ..., + mode: str = ..., + override: bool = ..., + place: Literal["PlaceOnTop", "PlaceOnBottom"] = ..., + root: Union[Misc, int] = ..., + rootx: _ScreenUnits = ..., + rooty: _ScreenUnits = ..., + sendevent: bool = ..., + serial: int = ..., + state: Union[int, str] = ..., + subwindow: Union[Misc, int] = ..., + time: int = ..., + warp: bool = ..., + width: _ScreenUnits = ..., + when: Literal["now", "tail", "head", "mark"] = ..., + x: _ScreenUnits = ..., + y: _ScreenUnits = ..., + ) -> None: ... + def event_info(self, virtual: Optional[str] = ...) -> Tuple[str, ...]: ... + def image_names(self) -> Tuple[str, ...]: ... + def image_types(self) -> Tuple[str, ...]: ... + # See #4363 and #4891 + def __setitem__(self, key: str, value: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def cget(self, key: str) -> Any: ... + def configure(self, cnf: Any = ...) -> Any: ... + # TODO: config is an alias of configure, but adding that here creates lots of mypy errors class CallWrapper: func: Any @@ -282,137 +485,607 @@ class YView: def yview_scroll(self, number, what): ... class Wm: - def wm_aspect(self, minNumer: Optional[Any] = ..., minDenom: Optional[Any] = ..., maxNumer: Optional[Any] = ..., - maxDenom: Optional[Any] = ...): ... - aspect: Any - def wm_attributes(self, *args): ... - attributes: Any - def wm_client(self, name: Optional[Any] = ...): ... - client: Any - def wm_colormapwindows(self, *wlist): ... - colormapwindows: Any - def wm_command(self, value: Optional[Any] = ...): ... - command: Any - def wm_deiconify(self): ... - deiconify: Any + @overload + def wm_aspect(self, minNumer: int, minDenom: int, maxNumer: int, maxDenom: int) -> None: ... + @overload + def wm_aspect( + self, minNumer: None = ..., minDenom: None = ..., maxNumer: None = ..., maxDenom: None = ... + ) -> Optional[Tuple[int, int, int, int]]: ... + aspect = wm_aspect + @overload + def wm_attributes(self) -> Tuple[Any, ...]: ... + @overload + def wm_attributes(self, __option: str) -> Any: ... + @overload + def wm_attributes(self, __option: str, __value: Any, *__other_option_value_pairs: Any) -> None: ... + attributes = wm_attributes + def wm_client(self, name: Optional[str] = ...) -> str: ... + client = wm_client + @overload + def wm_colormapwindows(self) -> List[Misc]: ... + @overload + def wm_colormapwindows(self, __wlist: _TkinterSequence[Misc]) -> None: ... + @overload + def wm_colormapwindows(self, __first_wlist_item: Misc, *other_wlist_items: Misc) -> None: ... + colormapwindows = wm_colormapwindows + def wm_command(self, value: Optional[str] = ...) -> str: ... + command = wm_command + # Some of these always return empty string, but return type is set to None to prevent accidentally using it + def wm_deiconify(self) -> None: ... + deiconify = wm_deiconify def wm_focusmodel(self, model: Optional[Any] = ...): ... - focusmodel: Any - def wm_forget(self, window): ... - forget: Any + focusmodel = wm_focusmodel + def wm_forget(self, window: Wm) -> None: ... + forget = wm_forget def wm_frame(self): ... - frame: Any - def wm_geometry(self, newGeometry: Optional[Any] = ...): ... - geometry: Any - def wm_grid(self, baseWidth: Optional[Any] = ..., baseHeight: Optional[Any] = ..., widthInc: Optional[Any] = ..., - heightInc: Optional[Any] = ...): ... - grid: Any + frame = wm_frame + @overload + def wm_geometry(self, newGeometry: None = ...) -> str: ... + @overload + def wm_geometry(self, newGeometry: str) -> None: ... + geometry = wm_geometry + def wm_grid( + self, + baseWidth: Optional[Any] = ..., + baseHeight: Optional[Any] = ..., + widthInc: Optional[Any] = ..., + heightInc: Optional[Any] = ..., + ): ... + grid = wm_grid def wm_group(self, pathName: Optional[Any] = ...): ... - group: Any + group = wm_group def wm_iconbitmap(self, bitmap: Optional[Any] = ..., default: Optional[Any] = ...): ... - iconbitmap: Any - def wm_iconify(self): ... - iconify: Any + iconbitmap = wm_iconbitmap + def wm_iconify(self) -> None: ... + iconify = wm_iconify def wm_iconmask(self, bitmap: Optional[Any] = ...): ... - iconmask: Any + iconmask = wm_iconmask def wm_iconname(self, newName: Optional[Any] = ...): ... - iconname: Any - def wm_iconphoto(self, default: bool = ..., *args): ... - iconphoto: Any + iconname = wm_iconname + def wm_iconphoto(self, default: bool, __image1: Image, *args: Image) -> None: ... + iconphoto = wm_iconphoto def wm_iconposition(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... - iconposition: Any + iconposition = wm_iconposition def wm_iconwindow(self, pathName: Optional[Any] = ...): ... - iconwindow: Any + iconwindow = wm_iconwindow def wm_manage(self, widget): ... - manage: Any - def wm_maxsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... - maxsize: Any - def wm_minsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... - minsize: Any - def wm_overrideredirect(self, boolean: Optional[Any] = ...): ... - overrideredirect: Any + manage = wm_manage + @overload + def wm_maxsize(self, width: None = ..., height: None = ...) -> Tuple[int, int]: ... + @overload + def wm_maxsize(self, width: int, height: int) -> None: ... + maxsize = wm_maxsize + @overload + def wm_minsize(self, width: None = ..., height: None = ...) -> Tuple[int, int]: ... + @overload + def wm_minsize(self, width: int, height: int) -> None: ... + minsize = wm_minsize + @overload + def wm_overrideredirect(self, boolean: None = ...) -> Optional[bool]: ... # returns True or None + @overload + def wm_overrideredirect(self, boolean: bool) -> None: ... + overrideredirect = wm_overrideredirect def wm_positionfrom(self, who: Optional[Any] = ...): ... - positionfrom: Any - def wm_protocol(self, name: Optional[Any] = ..., func: Optional[Any] = ...): ... - protocol: Any - def wm_resizable(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... - resizable: Any + positionfrom = wm_positionfrom + @overload + def wm_protocol(self, name: str, func: Union[Callable[[], Any], str]) -> None: ... + @overload + def wm_protocol(self, name: str, func: None = ...) -> str: ... + @overload + def wm_protocol(self, name: None = ..., func: None = ...) -> Tuple[str, ...]: ... + protocol = wm_protocol + @overload + def wm_resizable(self, width: None = ..., height: None = ...) -> Tuple[bool, bool]: ... + @overload + def wm_resizable(self, width: bool, height: bool) -> None: ... + resizable = wm_resizable def wm_sizefrom(self, who: Optional[Any] = ...): ... - sizefrom: Any - def wm_state(self, newstate: Optional[Any] = ...): ... - state: Any - def wm_title(self, string: Optional[Any] = ...): ... - title: Any - def wm_transient(self, master: Optional[Any] = ...): ... - transient: Any - def wm_withdraw(self): ... - withdraw: Any + sizefrom = wm_sizefrom + @overload + def wm_state(self, newstate: None = ...) -> str: ... + @overload + def wm_state(self, newstate: str) -> None: ... + state = wm_state + @overload + def wm_title(self, string: None = ...) -> str: ... + @overload + def wm_title(self, string: str) -> None: ... + title = wm_title + @overload + def wm_transient(self, master: None = ...) -> _tkinter.Tcl_Obj: ... + @overload + def wm_transient(self, master: Union[Wm, _tkinter.Tcl_Obj]) -> None: ... + transient = wm_transient + def wm_withdraw(self) -> None: ... + withdraw = wm_withdraw + +class _ExceptionReportingCallback(Protocol): + def __call__(self, __exc: Type[BaseException], __val: BaseException, __tb: TracebackType) -> Any: ... class Tk(Misc, Wm): - master: Optional[Any] - children: Dict[str, Any] - tk: Any - def __init__(self, screenName: Optional[str] = ..., baseName: Optional[str] = ..., className: str = ..., useTk: bool = ..., - sync: bool = ..., use: Optional[str] = ...) -> None: ... - def loadtk(self) -> None: ... + master: None + def __init__( + self, + screenName: Optional[str] = ..., + baseName: Optional[str] = ..., + className: str = ..., + useTk: bool = ..., + sync: bool = ..., + use: Optional[str] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + menu: Menu = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure + def loadtk(self) -> None: ... # differs from _tkinter.TkappType.loadtk def destroy(self) -> None: ... def readprofile(self, baseName: str, className: str) -> None: ... - report_callback_exception: Callable[[Type[BaseException], BaseException, TracebackType], Any] - def __getattr__(self, attr: str) -> Any: ... + report_callback_exception: _ExceptionReportingCallback + # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo + # Please keep in sync with _tkinter.TkappType + call: Callable[..., Any] + eval: Callable[[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 + mainloop: Any + quit: Any + record: Any + setvar: Any + split: Any + splitlist: Any + unsetvar: Any + wantobjects: Any + willdispatch: Any def Tcl(screenName: Optional[Any] = ..., baseName: Optional[Any] = ..., className: str = ..., useTk: bool = ...): ... +_InMiscTotal = TypedDict("_InMiscTotal", {"in": Misc}) +_InMiscNonTotal = TypedDict("_InMiscNonTotal", {"in": Misc}, total=False) + +class _PackInfo(_InMiscTotal): + # 'before' and 'after' never appear in _PackInfo + anchor: _Anchor + expand: bool + fill: Literal["none", "x", "y", "both"] + side: Literal["left", "right", "top", "bottom"] + # Paddings come out as int or tuple of int, even though any _ScreenUnits + # can be specified in pack(). + ipadx: int + ipady: int + padx: Union[int, Tuple[int, int]] + pady: Union[int, Tuple[int, int]] + class Pack: - def pack_configure(self, cnf=..., **kw): ... - pack: Any - def pack_forget(self): ... - forget: Any - def pack_info(self): ... - info: Any - propagate: Any - slaves: Any + # _PackInfo is not the valid type for cnf because pad stuff accepts any + # _ScreenUnits instead of int only. I didn't bother to create another + # TypedDict for cnf because it appears to be a legacy thing that was + # replaced by **kwargs. + def pack_configure( + self, + cnf: Optional[Mapping[str, Any]] = ..., + *, + after: Misc = ..., + anchor: _Anchor = ..., + before: Misc = ..., + expand: int = ..., + fill: Literal["none", "x", "y", "both"] = ..., + side: Literal["left", "right", "top", "bottom"] = ..., + ipadx: _ScreenUnits = ..., + ipady: _ScreenUnits = ..., + padx: Union[_ScreenUnits, Tuple[_ScreenUnits, _ScreenUnits]] = ..., + pady: Union[_ScreenUnits, Tuple[_ScreenUnits, _ScreenUnits]] = ..., + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def pack_forget(self) -> None: ... + def pack_info(self) -> _PackInfo: ... # errors if widget hasn't been packed + pack = pack_configure + forget = pack_forget + propagate = Misc.pack_propagate + # commented out to avoid mypy getting confused with multiple + # inheritance and how things get overrided with different things + # info = pack_info + # pack_propagate = Misc.pack_propagate + # configure = pack_configure + # config = pack_configure + # slaves = Misc.pack_slaves + # pack_slaves = Misc.pack_slaves + +class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed + anchor: _Anchor + bordermode: Literal["inside", "outside", "ignore"] + width: str # can be int()ed (even after e.g. widget.place(height='2.3c') or similar) + height: str # can be int()ed + x: str # can be int()ed + y: str # can be int()ed + relheight: str # can be float()ed if not empty string + relwidth: str # can be float()ed if not empty string + relx: str # can be float()ed if not empty string + rely: str # can be float()ed if not empty string class Place: - def place_configure(self, cnf=..., **kw): ... - place: Any - def place_forget(self): ... - forget: Any - def place_info(self): ... - info: Any - slaves: Any + def place_configure( + self, + cnf: Optional[Mapping[str, Any]] = ..., + *, + anchor: _Anchor = ..., + bordermode: Literal["inside", "outside", "ignore"] = ..., + width: _ScreenUnits = ..., + height: _ScreenUnits = ..., + x: _ScreenUnits = ..., + y: _ScreenUnits = ..., + # str allowed for compatibility with place_info() + relheight: Union[str, float] = ..., + relwidth: Union[str, float] = ..., + relx: Union[str, float] = ..., + rely: Union[str, float] = ..., + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def place_forget(self) -> None: ... + def place_info(self) -> _PlaceInfo: ... + place = place_configure + info = place_info + # commented out to avoid mypy getting confused with multiple + # inheritance and how things get overrided with different things + # config = place_configure + # configure = place_configure + # forget = place_forget + # slaves = Misc.place_slaves + # place_slaves = Misc.place_slaves + +class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded + column: int + columnspan: int + row: int + rowspan: int + ipadx: int + ipady: int + padx: Union[int, Tuple[int, int]] + pady: Union[int, Tuple[int, int]] + sticky: str # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty class Grid: - def grid_configure(self, cnf=..., **kw): ... - grid: Any - bbox: Any - columnconfigure: Any - def grid_forget(self): ... - forget: Any - def grid_remove(self): ... - def grid_info(self): ... - info: Any - location: Any - propagate: Any - rowconfigure: Any - size: Any - slaves: Any + def grid_configure( + self, + cnf: Optional[Mapping[str, Any]] = ..., + *, + column: int = ..., + columnspan: int = ..., + row: int = ..., + rowspan: int = ..., + ipadx: _ScreenUnits = ..., + ipady: _ScreenUnits = ..., + padx: Union[_ScreenUnits, Tuple[_ScreenUnits, _ScreenUnits]] = ..., + pady: Union[_ScreenUnits, Tuple[_ScreenUnits, _ScreenUnits]] = ..., + sticky: str = ..., # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def grid_forget(self) -> None: ... + def grid_remove(self) -> None: ... + def grid_info(self) -> _GridInfo: ... + grid = grid_configure + location = Misc.grid_location + size = Misc.grid_size + # commented out to avoid mypy getting confused with multiple + # inheritance and how things get overrided with different things + # bbox = Misc.grid_bbox + # grid_bbox = Misc.grid_bbox + # forget = grid_forget + # info = grid_info + # grid_location = Misc.grid_location + # grid_propagate = Misc.grid_propagate + # grid_size = Misc.grid_size + # rowconfigure = Misc.grid_rowconfigure + # grid_rowconfigure = Misc.grid_rowconfigure + # grid_columnconfigure = Misc.grid_columnconfigure + # columnconfigure = Misc.grid_columnconfigure + # config = grid_configure + # configure = grid_configure + # propagate = Misc.grid_propagate + # slaves = Misc.grid_slaves + # grid_slaves = Misc.grid_slaves class BaseWidget(Misc): + master: Misc widgetName: Any def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ... - def destroy(self): ... + def destroy(self) -> None: ... -class Widget(BaseWidget, Pack, Place, Grid): ... +# This class represents any widget except Toplevel or Tk. +class Widget(BaseWidget, Pack, Place, Grid): + # Allow bind callbacks to take e.g. Event[Label] instead of Event[Misc]. + # Tk and Toplevel get notified for their child widgets' events, but other + # widgets don't. + @overload + def bind( + self: _W, + sequence: Optional[str] = ..., + func: Optional[Callable[[Event[_W]], Optional[Literal["break"]]]] = ..., + add: Optional[bool] = ..., + ) -> str: ... + @overload + def bind(self, sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + @overload + def bind(self, *, func: str, add: Optional[bool] = ...) -> None: ... class Toplevel(BaseWidget, Wm): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + # Toplevel and Tk have the same options because they correspond to the same + # Tcl/Tk toplevel widget. For some reason, config and configure must be + # copy/pasted here instead of aliasing as 'config = Tk.config'. + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + class_: str = ..., + colormap: Union[Literal["new", ""], Misc] = ..., + container: bool = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + menu: Menu = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + screen: str = ..., # can't be changed after creating widget + takefocus: _TakeFocusValue = ..., + use: int = ..., + visual: Union[str, Tuple[str, int]] = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + menu: Menu = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Button(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., # same as borderwidth + bg: _Color = ..., # same as background + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., # same as borderwidth + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., # same as foreground + font: _FontDescription = ..., + foreground: _Color = ..., + # width and height must be int for buttons containing just text, but + # ints are also valid _ScreenUnits + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + # We allow the textvariable to be any Variable, not necessarly + # StringVar. This is useful for e.g. a button that displays the value + # of an IntVar. + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def flash(self): ... def invoke(self): ... class Canvas(Widget, XView, YView): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + closeenough: float = ..., + confine: bool = ..., + cursor: _Cursor = ..., + # canvas manual page has a section named COORDINATES, and the first + # part of it describes _ScreenUnits. + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + name: str = ..., + offset: Any = ..., # undocumented + relief: _Relief = ..., + # Setting scrollregion to None doesn't reset it back to empty, + # but setting it to () does. + scrollregion: Union[Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], Tuple[()]] = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + # man page says that state can be 'hidden', but it can't + state: Literal["normal", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + width: _ScreenUnits = ..., + xscrollcommand: _XYScrollCommand = ..., + xscrollincrement: _ScreenUnits = ..., + yscrollcommand: _XYScrollCommand = ..., + yscrollincrement: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + closeenough: float = ..., + confine: bool = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + offset: Any = ..., # undocumented + relief: _Relief = ..., + scrollregion: Union[Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], Tuple[()]] = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + state: Literal["normal", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + width: _ScreenUnits = ..., + xscrollcommand: _XYScrollCommand = ..., + xscrollincrement: _ScreenUnits = ..., + yscrollcommand: _XYScrollCommand = ..., + yscrollincrement: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def addtag(self, *args): ... def addtag_above(self, newtag, tagOrId): ... def addtag_all(self, newtag): ... @@ -422,8 +1095,19 @@ class Canvas(Widget, XView, YView): def addtag_overlapping(self, newtag, x1, y1, x2, y2): ... def addtag_withtag(self, newtag, tagOrId): ... def bbox(self, *args): ... - def tag_unbind(self, tagOrId, sequence, funcid: Optional[Any] = ...): ... - def tag_bind(self, tagOrId, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + @overload + def tag_bind( + self, + tagOrId: Union[str, int], + sequence: Optional[str] = ..., + func: Optional[Callable[[Event[Canvas]], Optional[Literal["break"]]]] = ..., + add: Optional[bool] = ..., + ) -> str: ... + @overload + def tag_bind(self, tagOrId: Union[str, int], sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + @overload + def tag_bind(self, tagOrId: Union[str, int], *, func: str, add: Optional[bool] = ...) -> None: ... + def tag_unbind(self, tagOrId: Union[str, int], sequence: str, funcid: Optional[str] = ...) -> None: ... def canvasx(self, screenx, gridspacing: Optional[Any] = ...): ... def canvasy(self, screeny, gridspacing: Optional[Any] = ...): ... def coords(self, *args): ... @@ -474,7 +1158,116 @@ class Canvas(Widget, XView, YView): def type(self, tagOrId): ... class Checkbutton(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + offrelief: _Relief = ..., + # The checkbutton puts a value to its variable when it's checked or + # unchecked. We don't restrict the type of that value here, so + # Any-typing is fine. + # + # I think Checkbutton shouldn't be generic, because then specifying + # "any checkbutton regardless of what variable it uses" would be + # difficult, and we might run into issues just like how List[float] + # and List[int] are incompatible. Also, we would need a way to + # specify "Checkbutton not associated with any variable", which is + # done by setting variable to empty string (the default). + offvalue: Any = ..., + onvalue: Any = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + tristateimage: _ImageSpec = ..., + tristatevalue: Any = ..., + underline: int = ..., + variable: Union[Variable, Literal[""]] = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + offrelief: _Relief = ..., + offvalue: Any = ..., + onvalue: Any = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + tristateimage: _ImageSpec = ..., + tristatevalue: Any = ..., + underline: int = ..., + variable: Union[Variable, Literal[""]] = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def deselect(self): ... def flash(self): ... def invoke(self): ... @@ -482,7 +1275,96 @@ class Checkbutton(Widget): def toggle(self): ... class Entry(Widget, XView): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledbackground: _Color = ..., + disabledforeground: _Color = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + invalidcommand: _EntryValidateCommand = ..., + invcmd: _EntryValidateCommand = ..., # same as invalidcommand + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + readonlybackground: _Color = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + show: str = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: _TakeFocusValue = ..., + textvariable: Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: _EntryValidateCommand = ..., + vcmd: _EntryValidateCommand = ..., # same as validatecommand + width: int = ..., + xscrollcommand: _XYScrollCommand = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledbackground: _Color = ..., + disabledforeground: _Color = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + invalidcommand: _EntryValidateCommand = ..., + invcmd: _EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + readonlybackground: _Color = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + show: str = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: _TakeFocusValue = ..., + textvariable: Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: _EntryValidateCommand = ..., + vcmd: _EntryValidateCommand = ..., + width: int = ..., + xscrollcommand: _XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def delete(self, first, last: Optional[Any] = ...): ... def get(self): ... def icursor(self, index): ... @@ -504,13 +1386,226 @@ class Entry(Widget, XView): select_to: Any class Frame(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + class_: str = ..., + colormap: Union[Literal["new", ""], Misc] = ..., + container: bool = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + visual: Union[str, Tuple[str, int]] = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Listbox(Widget, XView, YView): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activestyle: Literal["dotbox", "none", "underline"] = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + exportselection: int = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: int = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + justify: Literal["left", "center", "right"] = ..., + # There's no tkinter.ListVar, but seems like bare tkinter.Variable + # actually works for this: + # + # >>> import tkinter + # >>> lb = tkinter.Listbox() + # >>> var = lb['listvariable'] = tkinter.Variable() + # >>> var.set(['foo', 'bar', 'baz']) + # >>> lb.get(0, 'end') + # ('foo', 'bar', 'baz') + listvariable: Variable = ..., + name: str = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + # from listbox man page: "The value of the [selectmode] option may be + # arbitrary, but the default bindings expect it to be ..." + # + # I have never seen anyone setting this to something else than what + # "the default bindings expect", but let's support it anyway. + selectmode: str = ..., + setgrid: bool = ..., + state: Literal["normal", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + width: int = ..., + xscrollcommand: _XYScrollCommand = ..., + yscrollcommand: _XYScrollCommand = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activestyle: Literal["dotbox", "none", "underline"] = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: int = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + justify: Literal["left", "center", "right"] = ..., + listvariable: Variable = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + selectmode: str = ..., + setgrid: bool = ..., + state: Literal["normal", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + width: int = ..., + xscrollcommand: _XYScrollCommand = ..., + yscrollcommand: _XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def activate(self, index): ... def bbox(self, index): ... def curselection(self): ... @@ -535,24 +1630,264 @@ class Listbox(Widget, XView, YView): def itemconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... itemconfig: Any +_MenuIndex = Union[str, int] + class Menu(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... - def tk_popup(self, x, y, entry: str = ...): ... - if sys.version_info < (3, 6): - def tk_bindForTraversal(self): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeborderwidth: _ScreenUnits = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + name: str = ..., + postcommand: Union[Callable[[], Any], str] = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + takefocus: _TakeFocusValue = ..., + tearoff: int = ..., + # I guess tearoffcommand arguments are supposed to be widget objects, + # but they are widget name strings. Use nametowidget() to handle the + # arguments of tearoffcommand. + tearoffcommand: Union[Callable[[str, str], Any], str] = ..., + title: str = ..., + type: Literal["menubar", "tearoff", "normal"] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeborderwidth: _ScreenUnits = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + postcommand: Union[Callable[[], Any], str] = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + takefocus: _TakeFocusValue = ..., + tearoff: bool = ..., + tearoffcommand: Union[Callable[[str, str], Any], str] = ..., + title: str = ..., + type: Literal["menubar", "tearoff", "normal"] = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure + def tk_popup(self, x: int, y: int, entry: _MenuIndex = ...): ... def activate(self, index): ... def add(self, itemType, cnf=..., **kw): ... - def add_cascade(self, cnf=..., **kw): ... - def add_checkbutton(self, cnf=..., **kw): ... - def add_command(self, cnf=..., **kw): ... - def add_radiobutton(self, cnf=..., **kw): ... - def add_separator(self, cnf=..., **kw): ... def insert(self, index, itemType, cnf=..., **kw): ... - def insert_cascade(self, index, cnf=..., **kw): ... - def insert_checkbutton(self, index, cnf=..., **kw): ... - def insert_command(self, index, cnf=..., **kw): ... - def insert_radiobutton(self, index, cnf=..., **kw): ... - def insert_separator(self, index, cnf=..., **kw): ... + def add_cascade( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + label: str = ..., + menu: Menu = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def add_checkbutton( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + label: str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + variable: Variable = ..., + ) -> None: ... + def add_command( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + label: str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def add_radiobutton( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + label: str = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + value: Any = ..., + variable: Variable = ..., + ) -> None: ... + def add_separator(self, cnf: Optional[Dict[str, Any]] = ..., *, background: _Color = ...) -> None: ... + def insert_cascade( + self, + index: _MenuIndex, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + label: str = ..., + menu: Menu = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def insert_checkbutton( + self, + index: _MenuIndex, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + label: str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + variable: Variable = ..., + ) -> None: ... + def insert_command( + self, + index: _MenuIndex, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + label: str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def insert_radiobutton( + self, + index: _MenuIndex, + cnf: Optional[Dict[str, Any]] = ..., + *, + accelerator: str = ..., + activebackground: _Color = ..., + activeforeground: _Color = ..., + background: _Color = ..., + bitmap: _Bitmap = ..., + columnbreak: int = ..., + command: Union[Callable[[], Any], str] = ..., + compound: _Compound = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + hidemargin: bool = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + label: str = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + value: Any = ..., + variable: Variable = ..., + ) -> None: ... + def insert_separator(self, index: _MenuIndex, cnf: Optional[Dict[str, Any]] = ..., *, background: _Color = ...) -> None: ... def delete(self, index1, index2: Optional[Any] = ...): ... def entrycget(self, index, option): ... def entryconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... @@ -566,27 +1901,412 @@ class Menu(Widget): def yposition(self, index): ... class Menubutton(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + menu: Menu = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + menu: Menu = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Message(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + anchor: _Anchor = ..., + aspect: int = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + # there's width but no height + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + anchor: _Anchor = ..., + aspect: int = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + justify: Literal["left", "center", "right"] = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Radiobutton(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + offrelief: _Relief = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + tristateimage: _ImageSpec = ..., + tristatevalue: Any = ..., + underline: int = ..., + value: Any = ..., + variable: Union[Variable, Literal[""]] = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activeforeground: _Color = ..., + anchor: _Anchor = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bitmap: _Bitmap = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: _ButtonCommand = ..., + compound: _Compound = ..., + cursor: _Cursor = ..., + disabledforeground: _Color = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + image: _ImageSpec = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + offrelief: _Relief = ..., + overrelief: _Relief = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectcolor: _Color = ..., + selectimage: _ImageSpec = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + textvariable: Variable = ..., + tristateimage: _ImageSpec = ..., + tristatevalue: Any = ..., + underline: int = ..., + value: Any = ..., + variable: Union[Variable, Literal[""]] = ..., + width: _ScreenUnits = ..., + wraplength: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def deselect(self): ... def flash(self): ... def invoke(self): ... def select(self): ... class Scale(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bigincrement: float = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + # don't know why the callback gets string instead of float + command: Union[str, Callable[[str], Any]] = ..., + cursor: _Cursor = ..., + digits: int = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + from_: float = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + label: str = ..., + length: _ScreenUnits = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + resolution: float = ..., + showvalue: bool = ..., + sliderlength: _ScreenUnits = ..., + sliderrelief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + tickinterval: float = ..., + to: float = ..., + troughcolor: _Color = ..., + variable: DoubleVar = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + bigincrement: float = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: Union[str, Callable[[str], Any]] = ..., + cursor: _Cursor = ..., + digits: int = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + from_: float = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + label: str = ..., + length: _ScreenUnits = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + resolution: float = ..., + showvalue: bool = ..., + sliderlength: _ScreenUnits = ..., + sliderrelief: _Relief = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: _TakeFocusValue = ..., + tickinterval: float = ..., + to: float = ..., + troughcolor: _Color = ..., + variable: DoubleVar = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def get(self): ... def set(self, value): ... def coords(self, value: Optional[Any] = ...): ... def identify(self, x, y): ... class Scrollbar(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activerelief: _Relief = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + # There are many ways how the command may get called. Search for + # 'SCROLLING COMMANDS' in scrollbar man page. There doesn't seem to + # be any way to specify an overloaded callback function, so we say + # that it can take any args while it can't in reality. + command: Union[Callable[..., Optional[Tuple[float, float]]], str] = ..., + cursor: _Cursor = ..., + elementborderwidth: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + jump: bool = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + takefocus: _TakeFocusValue = ..., + troughcolor: _Color = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + activerelief: _Relief = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + command: Union[Callable[..., Optional[Tuple[float, float]]], str] = ..., + cursor: _Cursor = ..., + elementborderwidth: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + jump: bool = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + takefocus: _TakeFocusValue = ..., + troughcolor: _Color = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def activate(self, index: Optional[Any] = ...): ... def delta(self, deltax, deltay): ... def fraction(self, x, y): ... @@ -594,111 +2314,509 @@ class Scrollbar(Widget): def get(self): ... def set(self, first, last): ... +_TextIndex = Union[_tkinter.Tcl_Obj, str, float, Misc] + class Text(Widget, XView, YView): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... - def bbox(self, index): ... - def compare(self, index1, op, index2): ... - def count(self, index1, index2, *args): ... - def debug(self, boolean: Optional[Any] = ...): ... - def delete(self, index1, index2: Optional[Any] = ...): ... - def dlineinfo(self, index): ... - def dump(self, index1, index2: Optional[Any] = ..., command: Optional[Any] = ..., **kw): ... - def edit(self, *args): ... - def edit_modified(self, arg: Optional[Any] = ...): ... - def edit_redo(self): ... - def edit_reset(self): ... - def edit_separator(self): ... - def edit_undo(self): ... - def get(self, index1, index2: Optional[Any] = ...): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + autoseparators: bool = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + blockcursor: bool = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + endline: Union[int, Literal[""]] = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + # width is always int, but height is allowed to be ScreenUnits. + # This doesn't make any sense to me, and this isn't documented. + # The docs seem to say that both should be integers. + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + inactiveselectbackground: _Color = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertunfocussed: Literal["none", "hollow", "solid"] = ..., + insertwidth: _ScreenUnits = ..., + maxundo: int = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + setgrid: bool = ..., + spacing1: _ScreenUnits = ..., + spacing2: _ScreenUnits = ..., + spacing3: _ScreenUnits = ..., + startline: Union[int, Literal[""]] = ..., + state: Literal["normal", "disabled"] = ..., + # Literal inside Tuple doesn't actually work + tabs: Union[_ScreenUnits, str, Tuple[Union[_ScreenUnits, str], ...]] = ..., + tabstyle: Literal["tabular", "wordprocessor"] = ..., + takefocus: _TakeFocusValue = ..., + undo: bool = ..., + width: int = ..., + wrap: Literal["none", "char", "word"] = ..., + xscrollcommand: _XYScrollCommand = ..., + yscrollcommand: _XYScrollCommand = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + autoseparators: bool = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + blockcursor: bool = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + endline: Union[int, Literal[""]] = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + inactiveselectbackground: _Color = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertunfocussed: Literal["none", "hollow", "solid"] = ..., + insertwidth: _ScreenUnits = ..., + maxundo: int = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + setgrid: bool = ..., + spacing1: _ScreenUnits = ..., + spacing2: _ScreenUnits = ..., + spacing3: _ScreenUnits = ..., + startline: Union[int, Literal[""]] = ..., + state: Literal["normal", "disabled"] = ..., + tabs: Union[_ScreenUnits, str, Tuple[Union[_ScreenUnits, str], ...]] = ..., + tabstyle: Literal["tabular", "wordprocessor"] = ..., + takefocus: _TakeFocusValue = ..., + undo: bool = ..., + width: int = ..., + wrap: Literal["none", "char", "word"] = ..., + xscrollcommand: _XYScrollCommand = ..., + yscrollcommand: _XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure + def bbox(self, index: _TextIndex) -> Optional[Tuple[int, int, int, int]]: ... # type: ignore + def compare(self, index1: _TextIndex, op: Literal["<", "<=", "==", ">=", ">", "!="], index2: _TextIndex) -> bool: ... + def count(self, index1, index2, *args): ... # TODO + @overload + def debug(self, boolean: None = ...) -> bool: ... + @overload + def debug(self, boolean: bool) -> None: ... + def delete(self, index1: _TextIndex, index2: Optional[_TextIndex] = ...) -> None: ... + def dlineinfo(self, index: _TextIndex) -> Optional[Tuple[int, int, int, int, int]]: ... + @overload + def dump( + self, + index1: _TextIndex, + index2: Optional[_TextIndex] = ..., + command: None = ..., + *, + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> List[Tuple[str, str, str]]: ... + @overload + def dump( + self, + index1: _TextIndex, + index2: Optional[_TextIndex], + command: Union[Callable[[str, str, str], Any], str], + *, + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> None: ... + @overload + def dump( + self, + index1: _TextIndex, + index2: Optional[_TextIndex] = ..., + *, + command: Union[Callable[[str, str, str], Any], str], + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> None: ... + def edit(self, *args): ... # docstring says "Internal method" + @overload + def edit_modified(self, arg: None = ...) -> bool: ... # actually returns Literal[0, 1] + @overload + def edit_modified(self, arg: bool) -> None: ... # actually returns empty string + def edit_redo(self) -> None: ... # actually returns empty string + def edit_reset(self) -> None: ... # actually returns empty string + def edit_separator(self) -> None: ... # actually returns empty string + def edit_undo(self) -> None: ... # actually returns empty string + def get(self, index1: _TextIndex, index2: Optional[_TextIndex] = ...) -> str: ... + # TODO: image_* methods def image_cget(self, index, option): ... def image_configure(self, index, cnf: Optional[Any] = ..., **kw): ... def image_create(self, index, cnf=..., **kw): ... def image_names(self): ... - def index(self, index): ... - def insert(self, index, chars, *args): ... - def mark_gravity(self, markName, direction: Optional[Any] = ...): ... - def mark_names(self): ... - def mark_set(self, markName, index): ... - def mark_unset(self, *markNames): ... - def mark_next(self, index): ... - def mark_previous(self, index): ... - def peer_create(self, newPathName, cnf=..., **kw): ... - def peer_names(self): ... - def replace(self, index1, index2, chars, *args): ... - def scan_mark(self, x, y): ... - def scan_dragto(self, x, y): ... - def search(self, pattern, index, stopindex: Optional[Any] = ..., forwards: Optional[Any] = ..., - backwards: Optional[Any] = ..., exact: Optional[Any] = ..., regexp: Optional[Any] = ..., - nocase: Optional[Any] = ..., count: Optional[Any] = ..., elide: Optional[Any] = ...): ... - def see(self, index): ... - def tag_add(self, tagName, index1, *args): ... - def tag_unbind(self, tagName, sequence, funcid: Optional[Any] = ...): ... - def tag_bind(self, tagName, sequence, func, add: Optional[Any] = ...): ... - def tag_cget(self, tagName, option): ... - def tag_configure(self, tagName, cnf: Optional[Any] = ..., **kw): ... - tag_config: Any - def tag_delete(self, *tagNames): ... - def tag_lower(self, tagName, belowThis: Optional[Any] = ...): ... - def tag_names(self, index: Optional[Any] = ...): ... - def tag_nextrange(self, tagName, index1, index2: Optional[Any] = ...): ... - def tag_prevrange(self, tagName, index1, index2: Optional[Any] = ...): ... - def tag_raise(self, tagName, aboveThis: Optional[Any] = ...): ... - def tag_ranges(self, tagName): ... - def tag_remove(self, tagName, index1, index2: Optional[Any] = ...): ... + def index(self, index: _TextIndex) -> str: ... + def insert(self, index: _TextIndex, chars: str, *args: Union[str, _TkinterSequence[str]]) -> None: ... + @overload + def mark_gravity(self, markName: str, direction: None = ...) -> Literal["left", "right"]: ... + @overload + def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string + def mark_names(self) -> Tuple[str, ...]: ... + def mark_set(self, markName: str, index: _TextIndex) -> None: ... + def mark_unset(self, *markNames: str) -> None: ... + def mark_next(self, index: _TextIndex) -> Optional[str]: ... + def mark_previous(self, index: _TextIndex): ... + # **kw of peer_create is same as the kwargs of Text.__init__ + def peer_create(self, newPathName: Union[str, Text], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def peer_names(self) -> Tuple[_tkinter.Tcl_Obj, ...]: ... + def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: Union[str, _TkinterSequence[str]]) -> None: ... + def scan_mark(self, x: int, y: int) -> None: ... + def scan_dragto(self, x: int, y: int) -> None: ... + def search( + self, + pattern: str, + index: _TextIndex, + stopindex: Optional[_TextIndex] = ..., + forwards: Optional[bool] = ..., + backwards: Optional[bool] = ..., + exact: Optional[bool] = ..., + regexp: Optional[bool] = ..., + nocase: Optional[bool] = ..., + count: Optional[Variable] = ..., + elide: Optional[bool] = ..., + ) -> str: ... # returns empty string for not found + def see(self, index: _TextIndex) -> None: ... + def tag_add(self, tagName: str, index1: _TextIndex, *args: _TextIndex) -> None: ... + # tag_bind stuff is very similar to Canvas + @overload + def tag_bind( + self, + tagName: str, + sequence: Optional[str], + func: Optional[Callable[[Event[Text]], Optional[Literal["break"]]]], + add: Optional[bool] = ..., + ) -> str: ... + @overload + def tag_bind(self, tagName: str, sequence: Optional[str], func: str, add: Optional[bool] = ...) -> None: ... + def tag_unbind(self, tagName: str, sequence: str, funcid: Optional[str] = ...) -> None: ... + # allowing any string for cget instead of just Literals because there's no other way to look up tag options + def tag_cget(self, tagName: str, option: str) -> Any: ... + @overload + def tag_configure( + self, + tagName: str, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bgstipple: _Bitmap = ..., + borderwidth: _ScreenUnits = ..., + border: _ScreenUnits = ..., # alias for borderwidth + elide: bool = ..., + fgstipple: _Bitmap = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + justify: Literal["left", "right", "center"] = ..., + lmargin1: _ScreenUnits = ..., + lmargin2: _ScreenUnits = ..., + lmargincolor: _Color = ..., + offset: _ScreenUnits = ..., + overstrike: bool = ..., + overstrikefg: _Color = ..., + relief: _Relief = ..., + rmargin: _ScreenUnits = ..., + rmargincolor: _Color = ..., + selectbackground: _Color = ..., + selectforeground: _Color = ..., + spacing1: _ScreenUnits = ..., + spacing2: _ScreenUnits = ..., + spacing3: _ScreenUnits = ..., + tabs: Any = ..., # the exact type is kind of complicated, see manual page + tabstyle: Literal["tabular", "wordprocessor"] = ..., + underline: bool = ..., + underlinefg: _Color = ..., + wrap: Literal["none", "char", "word"] = ..., # be careful with "none" vs None + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def tag_configure(self, tagName: str, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + tag_config = tag_configure + def tag_delete(self, __first_tag_name: str, *tagNames: str) -> None: ... # error if no tag names given + def tag_lower(self, tagName: str, belowThis: Optional[str] = ...) -> None: ... + def tag_names(self, index: Optional[_TextIndex] = ...) -> Tuple[str, ...]: ... + def tag_nextrange( + self, tagName: str, index1: _TextIndex, index2: Optional[_TextIndex] = ... + ) -> Union[Tuple[str, str], Tuple[()]]: ... + def tag_prevrange( + self, tagName: str, index1: _TextIndex, index2: Optional[_TextIndex] = ... + ) -> Union[Tuple[str, str], Tuple[()]]: ... + def tag_raise(self, tagName: str, aboveThis: Optional[str] = ...) -> None: ... + def tag_ranges(self, tagName: str) -> Tuple[_tkinter.Tcl_Obj, ...]: ... + # tag_remove and tag_delete are different + def tag_remove(self, tagName: str, index1: _TextIndex, index2: Optional[_TextIndex] = ...) -> None: ... + # TODO: window_* methods def window_cget(self, index, option): ... def window_configure(self, index, cnf: Optional[Any] = ..., **kw): ... - window_config: Any + window_config = window_configure def window_create(self, index, cnf=..., **kw): ... def window_names(self): ... - def yview_pickplace(self, *what): ... + def yview_pickplace(self, *what): ... # deprecated class _setit: def __init__(self, var, value, callback: Optional[Any] = ...): ... def __call__(self, *args): ... +# manual page: tk_optionMenu class OptionMenu(Menubutton): widgetName: Any menuname: Any - def __init__(self, master, variable, value, *values, **kwargs): ... - def __getitem__(self, name): ... - def destroy(self): ... + def __init__( + # differs from other widgets + self, + master: Optional[Misc], + variable: StringVar, + value: str, + *values: str, + # kwarg only from now on + command: Optional[Callable[[StringVar], Any]] = ..., + ) -> None: ... + # configure, config, cget are inherited from Menubutton + # destroy and __getitem__ are overrided, signature does not change + +class _Image(Protocol): + tk: _tkinter.TkappType + def height(self) -> int: ... + def width(self) -> int: ... class Image: name: Any - tk: Any - def __init__(self, imgtype, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + tk: _tkinter.TkappType + def __init__( + self, imgtype, name: Optional[Any] = ..., cnf=..., master: Optional[Union[Misc, _tkinter.TkappType]] = ..., **kw + ): ... def __del__(self): ... def __setitem__(self, key, value): ... def __getitem__(self, key): ... - def configure(self, **kw): ... + configure: Any config: Any - def height(self): ... + def height(self) -> int: ... def type(self): ... - def width(self): ... + def width(self) -> int: ... class PhotoImage(Image): - def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... - def blank(self): ... - def cget(self, option): ... - def __getitem__(self, key): ... - def copy(self): ... - def zoom(self, x, y: str = ...): ... - def subsample(self, x, y: str = ...): ... - def get(self, x, y): ... - def put(self, data, to: Optional[Any] = ...): ... - def write(self, filename, format: Optional[Any] = ..., from_coords: Optional[Any] = ...): ... + def __init__( + self, + name: Optional[str] = ..., + cnf: Dict[str, Any] = ..., + master: Optional[Union[Misc, _tkinter.TkappType]] = ..., + *, + data: str = ..., # not same as data argument of put() + format: str = ..., + file: AnyPath = ..., + gamma: float = ..., + height: int = ..., + palette: Union[int, str] = ..., + width: int = ..., + ) -> None: ... + def configure( + self, + *, + data: str = ..., + format: str = ..., + file: AnyPath = ..., + gamma: float = ..., + height: int = ..., + palette: Union[int, str] = ..., + width: int = ..., + ) -> None: ... + config = configure + def blank(self) -> None: ... + def cget(self, option: str) -> str: ... + def __getitem__(self, key: str) -> str: ... # always string: image['height'] can be '0' + def copy(self) -> PhotoImage: ... + def zoom(self, x: int, y: Union[int, Literal[""]] = ...) -> PhotoImage: ... + def subsample(self, x: int, y: Union[int, Literal[""]] = ...) -> PhotoImage: ... + def get(self, x: int, y: int) -> Tuple[int, int, int]: ... + 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: ... 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: ... class BitmapImage(Image): - def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + def __init__( + self, + name: Optional[Any] = ..., + cnf: Dict[str, Any] = ..., + master: Optional[Union[Misc, _tkinter.TkappType]] = ..., + *, + background: _Color = ..., + data: str = ..., + file: AnyPath = ..., + foreground: _Color = ..., + maskdata: str = ..., + maskfile: AnyPath = ..., + ) -> None: ... -def image_names(): ... -def image_types(): ... +def image_names() -> Tuple[str, ...]: ... +def image_types() -> Tuple[str, ...]: ... class Spinbox(Widget, XView): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + buttonbackground: _Color = ..., + buttoncursor: _Cursor = ..., + buttondownrelief: _Relief = ..., + buttonuprelief: _Relief = ..., + # percent substitutions don't seem to be supported, it's similar to Entry's validion stuff + command: Union[Callable[[], Any], str, _TkinterSequence[str]] = ..., + cursor: _Cursor = ..., + disabledbackground: _Color = ..., + disabledforeground: _Color = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + format: str = ..., + from_: float = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + increment: float = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + invalidcommand: _EntryValidateCommand = ..., + invcmd: _EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + readonlybackground: _Color = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: _TakeFocusValue = ..., + textvariable: Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: _EntryValidateCommand = ..., + vcmd: _EntryValidateCommand = ..., + values: _TkinterSequence[str] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: _XYScrollCommand = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + activebackground: _Color = ..., + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + buttonbackground: _Color = ..., + buttoncursor: _Cursor = ..., + buttondownrelief: _Relief = ..., + buttonuprelief: _Relief = ..., + command: Union[Callable[[], Any], str, _TkinterSequence[str]] = ..., + cursor: _Cursor = ..., + disabledbackground: _Color = ..., + disabledforeground: _Color = ..., + exportselection: bool = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + format: str = ..., + from_: float = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + increment: float = ..., + insertbackground: _Color = ..., + insertborderwidth: _ScreenUnits = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: _ScreenUnits = ..., + invalidcommand: _EntryValidateCommand = ..., + invcmd: _EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + readonlybackground: _Color = ..., + relief: _Relief = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + selectbackground: _Color = ..., + selectborderwidth: _ScreenUnits = ..., + selectforeground: _Color = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: _TakeFocusValue = ..., + textvariable: Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: _EntryValidateCommand = ..., + vcmd: _EntryValidateCommand = ..., + values: _TkinterSequence[str] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: _XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def bbox(self, index): ... def delete(self, first, last: Optional[Any] = ...): ... def get(self): ... @@ -721,10 +2839,129 @@ class Spinbox(Widget, XView): def selection_to(self, index: int) -> None: ... class LabelFrame(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + class_: str = ..., + colormap: Union[Literal["new", ""], Misc] = ..., + container: bool = ..., # undocumented + cursor: _Cursor = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + # 'ne' and 'en' are valid labelanchors, but only 'ne' is a valid _Anchor. + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: Misc = ..., + name: str = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + visual: Union[str, Tuple[str, int]] = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + fg: _Color = ..., + font: _FontDescription = ..., + foreground: _Color = ..., + height: _ScreenUnits = ..., + highlightbackground: _Color = ..., + highlightcolor: _Color = ..., + highlightthickness: _ScreenUnits = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: Misc = ..., + padx: _ScreenUnits = ..., + pady: _ScreenUnits = ..., + relief: _Relief = ..., + takefocus: _TakeFocusValue = ..., + text: str = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class PanedWindow(Widget): - def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def __init__( + self, + master: Optional[Misc] = ..., + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + handlepad: _ScreenUnits = ..., + handlesize: _ScreenUnits = ..., + height: _ScreenUnits = ..., + name: str = ..., + opaqueresize: bool = ..., + orient: Literal["horizontal", "vertical"] = ..., + proxybackground: _Color = ..., + proxyborderwidth: _ScreenUnits = ..., + proxyrelief: _Relief = ..., + relief: _Relief = ..., + sashcursor: _Cursor = ..., + sashpad: _ScreenUnits = ..., + sashrelief: _Relief = ..., + sashwidth: _ScreenUnits = ..., + showhandle: bool = ..., + width: _ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: _Color = ..., + bd: _ScreenUnits = ..., + bg: _Color = ..., + border: _ScreenUnits = ..., + borderwidth: _ScreenUnits = ..., + cursor: _Cursor = ..., + handlepad: _ScreenUnits = ..., + handlesize: _ScreenUnits = ..., + height: _ScreenUnits = ..., + opaqueresize: bool = ..., + orient: Literal["horizontal", "vertical"] = ..., + proxybackground: _Color = ..., + proxyborderwidth: _ScreenUnits = ..., + proxyrelief: _Relief = ..., + relief: _Relief = ..., + sashcursor: _Cursor = ..., + sashpad: _ScreenUnits = ..., + sashrelief: _Relief = ..., + sashwidth: _ScreenUnits = ..., + showhandle: bool = ..., + width: _ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def add(self, child, **kw): ... def remove(self, child): ... forget: Any diff --git a/mypy/typeshed/stdlib/tkinter/constants.pyi b/mypy/typeshed/stdlib/tkinter/constants.pyi index e21a93e69cea..1383b0f9bf4b 100644 --- a/mypy/typeshed/stdlib/tkinter/constants.pyi +++ b/mypy/typeshed/stdlib/tkinter/constants.pyi @@ -1,79 +1,80 @@ -from typing import Any +from typing_extensions import Literal -NO: Any -YES: Any -TRUE: Any -FALSE: Any -ON: Any -OFF: Any -N: Any -S: Any -W: Any -E: Any -NW: Any -SW: Any -NE: Any -SE: Any -NS: Any -EW: Any -NSEW: Any -CENTER: Any -NONE: Any -X: Any -Y: Any -BOTH: Any -LEFT: Any -TOP: Any -RIGHT: Any -BOTTOM: Any -RAISED: Any -SUNKEN: Any -FLAT: Any -RIDGE: Any -GROOVE: Any -SOLID: Any -HORIZONTAL: Any -VERTICAL: Any -NUMERIC: Any -CHAR: Any -WORD: Any -BASELINE: Any -INSIDE: Any -OUTSIDE: Any -SEL: Any -SEL_FIRST: Any -SEL_LAST: Any -END: Any -INSERT: Any -CURRENT: Any -ANCHOR: Any -ALL: Any -NORMAL: Any -DISABLED: Any -ACTIVE: Any -HIDDEN: Any -CASCADE: Any -CHECKBUTTON: Any -COMMAND: Any -RADIOBUTTON: Any -SEPARATOR: Any -SINGLE: Any -BROWSE: Any -MULTIPLE: Any -EXTENDED: Any -DOTBOX: Any -UNDERLINE: Any -PIESLICE: Any -CHORD: Any -ARC: Any -FIRST: Any -LAST: Any -BUTT: Any -PROJECTING: Any -ROUND: Any -BEVEL: Any -MITER: Any -MOVETO: Any -SCROLL: Any -UNITS: Any -PAGES: Any +# These are not actually bools. See #4669 +NO: bool +YES: bool +TRUE: bool +FALSE: bool +ON: bool +OFF: bool +N: Literal["n"] +S: Literal["s"] +W: Literal["w"] +E: Literal["e"] +NW: Literal["nw"] +SW: Literal["sw"] +NE: Literal["ne"] +SE: Literal["se"] +NS: Literal["ns"] +EW: Literal["ew"] +NSEW: Literal["nsew"] +CENTER: Literal["center"] +NONE: Literal["none"] +X: Literal["x"] +Y: Literal["y"] +BOTH: Literal["both"] +LEFT: Literal["left"] +TOP: Literal["top"] +RIGHT: Literal["right"] +BOTTOM: Literal["bottom"] +RAISED: Literal["raised"] +SUNKEN: Literal["sunken"] +FLAT: Literal["flat"] +RIDGE: Literal["ridge"] +GROOVE: Literal["groove"] +SOLID: Literal["solid"] +HORIZONTAL: Literal["horizontal"] +VERTICAL: Literal["vertical"] +NUMERIC: Literal["numeric"] +CHAR: Literal["char"] +WORD: Literal["word"] +BASELINE: Literal["baseline"] +INSIDE: Literal["inside"] +OUTSIDE: Literal["outside"] +SEL: Literal["sel"] +SEL_FIRST: Literal["sel.first"] +SEL_LAST: Literal["sel.last"] +END: Literal["end"] +INSERT: Literal["insert"] +CURRENT: Literal["current"] +ANCHOR: Literal["anchor"] +ALL: Literal["all"] +NORMAL: Literal["normal"] +DISABLED: Literal["disabled"] +ACTIVE: Literal["active"] +HIDDEN: Literal["hidden"] +CASCADE: Literal["cascade"] +CHECKBUTTON: Literal["checkbutton"] +COMMAND: Literal["command"] +RADIOBUTTON: Literal["radiobutton"] +SEPARATOR: Literal["separator"] +SINGLE: Literal["single"] +BROWSE: Literal["browse"] +MULTIPLE: Literal["multiple"] +EXTENDED: Literal["extended"] +DOTBOX: Literal["dotbox"] +UNDERLINE: Literal["underline"] +PIESLICE: Literal["pieslice"] +CHORD: Literal["chord"] +ARC: Literal["arc"] +FIRST: Literal["first"] +LAST: Literal["last"] +BUTT: Literal["butt"] +PROJECTING: Literal["projecting"] +ROUND: Literal["round"] +BEVEL: Literal["bevel"] +MITER: Literal["miter"] +MOVETO: Literal["moveto"] +SCROLL: Literal["scroll"] +UNITS: Literal["units"] +PAGES: Literal["pages"] diff --git a/mypy/typeshed/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi index 3136f21e663d..d02036a64f10 100644 --- a/mypy/typeshed/stdlib/tkinter/dialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/dialog.pyi @@ -1,5 +1,5 @@ -from typing import Any, Mapping, Optional from tkinter import Widget +from typing import Any, Mapping, Optional DIALOG_ICON: str diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 6d5f165134b0..8c281c6bdbad 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,5 +1,5 @@ +from tkinter import Button, Entry, Frame, Listbox, Scrollbar, Toplevel, commondialog from typing import Any, Dict, Optional, Tuple -from tkinter import Button, commondialog, Entry, Frame, Listbox, Scrollbar, Toplevel dialogstates: Dict[Any, Tuple[Any, Any]] @@ -19,7 +19,9 @@ class FileDialog: ok_button: Button = ... filter_button: Button = ... cancel_button: Button = ... - def __init__(self, master, title: Optional[Any] = ...) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either + def __init__( + self, master, title: Optional[Any] = ... + ) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either how: Optional[Any] = ... def go(self, dir_or_file: Any = ..., pattern: str = ..., default: str = ..., key: Optional[Any] = ...): ... def quit(self, how: Optional[Any] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi new file mode 100644 index 000000000000..791a8a847306 --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -0,0 +1,98 @@ +import tkinter +from typing import Any, List, Optional, Tuple, TypeVar, Union, overload +from typing_extensions import Literal, TypedDict + +NORMAL: Literal["normal"] +ROMAN: Literal["roman"] +BOLD: Literal["bold"] +ITALIC: Literal["italic"] + +def nametofont(name: str) -> Font: ... + +# See 'FONT DESCRIPTIONS' in font man page. This uses str because Literal +# inside Tuple doesn't work. +_FontDescription = Union[str, Font, Tuple[str, int], Tuple[str, int, str], Tuple[str, int, tkinter._TkinterSequence[str]]] + +class _FontDict(TypedDict): + family: str + size: int + weight: Literal["normal", "bold"] + slant: Literal["roman", "italic"] + underline: bool + overstrike: bool + +class _MetricsDict(TypedDict): + ascent: int + descent: int + linespace: int + fixed: bool + +class Font: + name: str + delete_font: bool + def __init__( + self, + # In tkinter, 'root' refers to tkinter.Tk by convention, but the code + # actually works with any tkinter widget so we use tkinter.Misc. + root: Optional[tkinter.Misc] = ..., + font: Optional[_FontDescription] = ..., + name: Optional[str] = ..., + exists: bool = ..., + *, + family: str = ..., + size: int = ..., + weight: Literal["normal", "bold"] = ..., + slant: Literal["roman", "italic"] = ..., + underline: bool = ..., + overstrike: bool = ..., + ) -> None: ... + def __setitem__(self, key: str, value: Any) -> None: ... + @overload + def cget(self, option: Literal["family"]) -> str: ... + @overload + def cget(self, option: Literal["size"]) -> int: ... + @overload + def cget(self, option: Literal["weight"]) -> Literal["normal", "bold"]: ... + @overload + def cget(self, option: Literal["slant"]) -> Literal["roman", "italic"]: ... + @overload + def cget(self, option: Literal["underline", "overstrike"]) -> bool: ... + @overload + def cget(self, option: str) -> Any: ... + __getitem__ = cget + @overload + def actual(self, option: Literal["family"], displayof: Optional[tkinter.Misc] = ...) -> str: ... + @overload + def actual(self, option: Literal["size"], displayof: Optional[tkinter.Misc] = ...) -> int: ... + @overload + def actual(self, option: Literal["weight"], displayof: Optional[tkinter.Misc] = ...) -> Literal["normal", "bold"]: ... + @overload + def actual(self, option: Literal["slant"], displayof: Optional[tkinter.Misc] = ...) -> Literal["roman", "italic"]: ... + @overload + def actual(self, option: Literal["underline", "overstrike"], displayof: Optional[tkinter.Misc] = ...) -> bool: ... + @overload + def actual(self, option: None, displayof: Optional[tkinter.Misc] = ...) -> _FontDict: ... + @overload + def actual(self, *, displayof: Optional[tkinter.Misc] = ...) -> _FontDict: ... + def config( + self, + *, + family: str = ..., + size: int = ..., + weight: Literal["normal", "bold"] = ..., + slant: Literal["roman", "italic"] = ..., + underline: bool = ..., + overstrike: bool = ..., + ) -> Optional[_FontDict]: ... + configure = config + def copy(self) -> Font: ... + @overload + def metrics(self, __option: Literal["ascent", "descent", "linespace"], *, displayof: Optional[tkinter.Misc] = ...) -> int: ... + @overload + def metrics(self, __option: Literal["fixed"], *, displayof: Optional[tkinter.Misc] = ...) -> bool: ... + @overload + def metrics(self, *, displayof: Optional[tkinter.Misc] = ...) -> _MetricsDict: ... + def measure(self, text: str, displayof: Optional[tkinter.Misc] = ...) -> int: ... + +def families(root: Optional[tkinter.Misc] = ..., displayof: Optional[tkinter.Misc] = ...) -> Tuple[str, ...]: ... +def names(root: Optional[tkinter.Misc] = ...) -> Tuple[str, ...]: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 755fb25214dd..1baac3372644 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1,13 +1,19 @@ +import _tkinter import sys -from typing import Any, List, Optional import tkinter +from tkinter.font import _FontDescription +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload +from typing_extensions import Literal def tclobjs_to_py(adict): ... def setup_master(master: Optional[Any] = ...): ... +# from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound +_TtkCompound = Literal["text", "image", tkinter._Compound] + class Style: master: Any - tk: Any + tk: _tkinter.TkappType def __init__(self, master: Optional[Any] = ...): ... def configure(self, style, query_opt: Optional[Any] = ..., **kw): ... def map(self, style, query_opt: Optional[Any] = ..., **kw): ... @@ -22,46 +28,484 @@ class Style: def theme_use(self, themename: Optional[Any] = ...): ... class Widget(tkinter.Widget): - def __init__(self, master, widgetname, kw: Optional[Any] = ...): ... + def __init__(self, master: Optional[tkinter.Misc], widgetname, kw: Optional[Any] = ...): ... def identify(self, x, y): ... def instate(self, statespec, callback: Optional[Any] = ..., *args, **kw): ... def state(self, statespec: Optional[Any] = ...): ... class Button(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + image: tkinter._ImageSpec = ..., + name: str = ..., + padding: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + image: tkinter._ImageSpec = ..., + padding: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self): ... class Checkbutton(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._ImageSpec = ..., + name: str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + padding: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + # Seems like variable can be empty string, but actually setting it to + # empty string segfaults before Tcl 8.6.9. Search for ttk::checkbutton + # here: https://sourceforge.net/projects/tcl/files/Tcl/8.6.9/tcltk-release-notes-8.6.9.txt/view + variable: tkinter.Variable = ..., + width: Union[int, Literal[""]] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._ImageSpec = ..., + offvalue: Any = ..., + onvalue: Any = ..., + padding: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + variable: tkinter.Variable = ..., + width: Union[int, Literal[""]] = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self): ... class Entry(Widget, tkinter.Entry): - def __init__(self, master: Optional[Any] = ..., widget: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + widget: Optional[str] = ..., + *, + background: tkinter._Color = ..., # undocumented + class_: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + show: str = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: tkinter._Color = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + show: str = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why) + @overload # type: ignore + def config( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: tkinter._Color = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + show: str = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... def bbox(self, index): ... def identify(self, x, y): ... def validate(self): ... class Combobox(Entry): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + background: tkinter._Color = ..., # undocumented + class_: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., # undocumented + foreground: tkinter._Color = ..., # undocumented + height: int = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + postcommand: Union[Callable[[], Any], str] = ..., + show: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., # undocumented + validatecommand: tkinter._EntryValidateCommand = ..., # undocumented + values: tkinter._TkinterSequence[str] = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., # undocumented + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: tkinter._Color = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + height: int = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + postcommand: Union[Callable[[], Any], str] = ..., + show: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + values: tkinter._TkinterSequence[str] = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why) + @overload # type: ignore + def config( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: tkinter._Color = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + height: int = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + postcommand: Union[Callable[[], Any], str] = ..., + show: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + values: tkinter._TkinterSequence[str] = ..., + width: int = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... def current(self, newindex: Optional[Any] = ...): ... def set(self, value): ... class Frame(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., + class_: str = ..., + cursor: tkinter._Cursor = ..., + height: tkinter._ScreenUnits = ..., + name: str = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: tkinter._ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., + cursor: tkinter._Cursor = ..., + height: tkinter._ScreenUnits = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: tkinter._ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + anchor: tkinter._Anchor = ..., + background: tkinter._Color = ..., + border: tkinter._ScreenUnits = ..., # alias for borderwidth + borderwidth: tkinter._ScreenUnits = ..., # undocumented + class_: str = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + image: tkinter._ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + wraplength: tkinter._ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + anchor: tkinter._Anchor = ..., + background: tkinter._Color = ..., + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + image: tkinter._ImageSpec = ..., + justify: Literal["left", "center", "right"] = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + wraplength: tkinter._ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Labelframe(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., # undocumented + class_: str = ..., + cursor: tkinter._Cursor = ..., + height: tkinter._ScreenUnits = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: tkinter.Misc = ..., + name: str = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., # undocumented + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + underline: int = ..., + width: tkinter._ScreenUnits = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + border: tkinter._ScreenUnits = ..., + borderwidth: tkinter._ScreenUnits = ..., + cursor: tkinter._Cursor = ..., + height: tkinter._ScreenUnits = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: tkinter.Misc = ..., + padding: tkinter._Padding = ..., + relief: tkinter._Relief = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + underline: int = ..., + width: tkinter._ScreenUnits = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure -LabelFrame: Any +LabelFrame = Labelframe class Menubutton(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + image: tkinter._ImageSpec = ..., + menu: tkinter.Menu = ..., + name: str = ..., + padding: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + image: tkinter._ImageSpec = ..., + menu: tkinter.Menu = ..., + padding: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: Union[int, Literal[""]] = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Notebook(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + cursor: tkinter._Cursor = ..., + height: int = ..., + name: str = ..., + padding: tkinter._Padding = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: int = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + padding: tkinter._Padding = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: int = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def add(self, child, **kw): ... def forget(self, tab_id): ... def hide(self, tab_id): ... @@ -74,46 +518,403 @@ class Notebook(Widget): def enable_traversal(self): ... class Panedwindow(Widget, tkinter.PanedWindow): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + cursor: tkinter._Cursor = ..., + # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units + height: int = ..., + name: str = ..., + orient: Literal["vertical", "horizontal"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: int = ..., + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: int = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why) + @overload # type: ignore + def config( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + width: int = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... forget: Any def insert(self, pos, child, **kw): ... def pane(self, pane, option: Optional[Any] = ..., **kw): ... def sashpos(self, index, newpos: Optional[Any] = ...): ... -PanedWindow: Any +PanedWindow = Panedwindow class Progressbar(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + cursor: tkinter._Cursor = ..., + length: tkinter._ScreenUnits = ..., + maximum: float = ..., + mode: Literal["determinate", "indeterminate"] = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + phase: int = ..., # docs say read-only but assigning int to this works + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + value: float = ..., + variable: tkinter.DoubleVar = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + length: tkinter._ScreenUnits = ..., + maximum: float = ..., + mode: Literal["determinate", "indeterminate"] = ..., + orient: Literal["horizontal", "vertical"] = ..., + phase: int = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + value: float = ..., + variable: tkinter.DoubleVar = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def start(self, interval: Optional[Any] = ...): ... def step(self, amount: Optional[Any] = ...): ... def stop(self): ... class Radiobutton(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._ImageSpec = ..., + name: str = ..., + padding: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + value: Any = ..., + variable: Union[tkinter.Variable, Literal[""]] = ..., + width: Union[int, Literal[""]] = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: tkinter._ButtonCommand = ..., + compound: _TtkCompound = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._ImageSpec = ..., + padding: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + text: str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + value: Any = ..., + variable: Union[tkinter.Variable, Literal[""]] = ..., + width: Union[int, Literal[""]] = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self): ... class Scale(Widget, tkinter.Scale): - def __init__(self, master: Optional[Any] = ..., **kw): ... - def configure(self, cnf: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + command: Union[str, Callable[[str], Any]] = ..., + cursor: tkinter._Cursor = ..., + from_: float = ..., + length: tkinter._ScreenUnits = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + state: str = ..., # undocumented + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + to: float = ..., + value: float = ..., + variable: tkinter.DoubleVar = ..., + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: Union[str, Callable[[str], Any]] = ..., + cursor: tkinter._Cursor = ..., + from_: float = ..., + length: tkinter._ScreenUnits = ..., + orient: Literal["horizontal", "vertical"] = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + to: float = ..., + value: float = ..., + variable: tkinter.DoubleVar = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why) + @overload # type: ignore + def config( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: Union[str, Callable[[str], Any]] = ..., + cursor: tkinter._Cursor = ..., + from_: float = ..., + length: tkinter._ScreenUnits = ..., + orient: Literal["horizontal", "vertical"] = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + to: float = ..., + value: float = ..., + variable: tkinter.DoubleVar = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... def get(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... class Scrollbar(Widget, tkinter.Scrollbar): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + command: Union[Callable[..., Optional[Tuple[float, float]]], str] = ..., + cursor: tkinter._Cursor = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: Union[Callable[..., Optional[Tuple[float, float]]], str] = ..., + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why) + @overload # type: ignore + def config( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + command: Union[Callable[..., Optional[Tuple[float, float]]], str] = ..., + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... class Separator(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + cursor: tkinter._Cursor = ..., + name: str = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure class Sizegrip(Widget): - def __init__(self, master: Optional[Any] = ..., **kw): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + cursor: tkinter._Cursor = ..., + name: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + cursor: tkinter._Cursor = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure if sys.version_info >= (3, 7): class Spinbox(Entry): - def __init__(self, master: Any = ..., **kw: Any) -> None: ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + background: tkinter._Color = ..., # undocumented + class_: str = ..., + command: Union[Callable[[], Any], str, tkinter._TkinterSequence[str]] = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., # undocumented + font: _FontDescription = ..., # undocumented + foreground: tkinter._Color = ..., # undocumented + format: str = ..., + from_: float = ..., + increment: float = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented + justify: Literal["left", "center", "right"] = ..., # undocumented + name: str = ..., + show: Any = ..., # undocumented + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., # undocumented + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + values: tkinter._TkinterSequence[str] = ..., + width: int = ..., # undocumented + wrap: bool = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> None: ... + @overload # type: ignore + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + background: tkinter._Color = ..., + command: Union[Callable[[], Any], str, tkinter._TkinterSequence[str]] = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: tkinter._Color = ..., + format: str = ..., + from_: float = ..., + increment: float = ..., + invalidcommand: tkinter._EntryValidateCommand = ..., + justify: Literal["left", "center", "right"] = ..., + show: Any = ..., + state: str = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + textvariable: tkinter.Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: tkinter._EntryValidateCommand = ..., + values: tkinter._TkinterSequence[str] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure # type: ignore def set(self, value: Any) -> None: ... class Treeview(Widget, tkinter.XView, tkinter.YView): - def __init__(self, master: Optional[Any] = ..., **kw): ... - def bbox(self, item, column: Optional[Any] = ...): ... + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + *, + class_: str = ..., + columns: Union[str, tkinter._TkinterSequence[str]] = ..., + cursor: tkinter._Cursor = ..., + displaycolumns: Union[str, tkinter._TkinterSequence[str], tkinter._TkinterSequence[int], Literal["#all"]] = ..., + height: int = ..., + name: str = ..., + padding: tkinter._Padding = ..., + selectmode: Literal["extended", "browse", "none"] = ..., + # _TkinterSequences of Literal don't actually work, using str instead. + # + # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be + # surprised if someone was using it. + show: Union[Literal["tree", "headings", "tree headings"], tkinter._TkinterSequence[str]] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + yscrollcommand: tkinter._XYScrollCommand = ..., + ) -> None: ... + @overload + def configure( + self, + cnf: Optional[Dict[str, Any]] = ..., + *, + columns: Union[str, tkinter._TkinterSequence[str]] = ..., + cursor: tkinter._Cursor = ..., + displaycolumns: Union[str, tkinter._TkinterSequence[str], tkinter._TkinterSequence[int], Literal["#all"]] = ..., + height: int = ..., + padding: tkinter._Padding = ..., + selectmode: Literal["extended", "browse", "none"] = ..., + show: Union[Literal["tree", "headings", "tree headings"], tkinter._TkinterSequence[str]] = ..., + style: str = ..., + takefocus: tkinter._TakeFocusValue = ..., + xscrollcommand: tkinter._XYScrollCommand = ..., + yscrollcommand: tkinter._XYScrollCommand = ..., + ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... + @overload + def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... + config = configure + def bbox(self, item, column: Optional[Any] = ...): ... # type: ignore def get_children(self, item: Optional[Any] = ...): ... def set_children(self, item, *newchildren): ... def column(self, column, option: Optional[Any] = ..., **kw): ... @@ -145,19 +946,51 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def selection_remove(self, items): ... def selection_toggle(self, items): ... def set(self, item, column: Optional[Any] = ..., value: Optional[Any] = ...): ... - def tag_bind(self, tagname, sequence: Optional[Any] = ..., callback: Optional[Any] = ...): ... + # There's no tag_unbind() or 'add' argument for whatever reason. + # Also, it's 'callback' instead of 'func' here. + @overload + def tag_bind( + self, + tagname: str, + sequence: Optional[str] = ..., + callback: Optional[Callable[[tkinter.Event[Treeview]], Optional[Literal["break"]]]] = ..., + ) -> str: ... + @overload + def tag_bind(self, tagname: str, sequence: Optional[str], callback: str) -> None: ... + @overload + def tag_bind(self, tagname: str, *, callback: str) -> None: ... def tag_configure(self, tagname, option: Optional[Any] = ..., **kw): ... def tag_has(self, tagname, item: Optional[Any] = ...): ... class LabeledScale(Frame): label: Any scale: Any - def __init__(self, master: Optional[Any] = ..., variable: Optional[Any] = ..., from_: int = ..., to: int = ..., **kw): ... - def destroy(self): ... + # TODO: don't any-type **kw. That goes to Frame.__init__. + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + variable: Optional[Union[tkinter.IntVar, tkinter.DoubleVar]] = ..., + from_: float = ..., + to: float = ..., + *, + compound: Union[Literal["top"], Literal["bottom"]] = ..., + **kw: Any, + ) -> None: ... + # destroy is overrided, signature does not change value: Any class OptionMenu(Menubutton): - def __init__(self, master, variable, default: Optional[Any] = ..., *values, **kwargs): ... - def __getitem__(self, item): ... + def __init__( + self, + master, + variable, + default: Optional[str] = ..., + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = ..., + direction: Union[Literal["above"], Literal["below"], Literal["left"], Literal["right"], Literal["flush"]] = ..., + command: Optional[Callable[[tkinter.StringVar], Any]] = ..., + ) -> None: ... + # configure, config, cget, destroy are inherited from Menubutton + # destroy and __setitem__ are overrided, signature does not change def set_menu(self, default: Optional[Any] = ..., *values): ... - def destroy(self): ... diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index 33e1f80453a3..a806a466b8ea 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -78,6 +78,7 @@ if sys.version_info >= (3, 8): TYPE_COMMENT: int TYPE_IGNORE: int COLONEQUAL: int + EXACT_TOKEN_TYPES: Dict[str, int] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index d9b91fa77540..23babea287e3 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -1,7 +1,23 @@ -from typing import Any, Callable, Dict, Generator, Iterable, List, NamedTuple, Optional, Pattern, Union, Sequence, Set, TextIO, Tuple -from builtins import open as _builtin_open import sys +from builtins import open as _builtin_open +from os import PathLike from token import * # noqa: F403 +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + List, + NamedTuple, + Optional, + Pattern, + Sequence, + Set, + TextIO, + Tuple, + Union, +) if sys.version_info < (3, 7): COMMENT: int @@ -46,13 +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 - -if sys.version_info >= (3, 6): - from os import PathLike - def open(filename: Union[str, bytes, int, PathLike[Any]]) -> TextIO: ... -elif sys.version_info >= (3, 2): - def open(filename: Union[str, bytes, int]) -> TextIO: ... - +def open(filename: Union[str, bytes, int, PathLike[Any]]) -> TextIO: ... def group(*choices: str) -> str: ... # undocumented def any(*choices: str) -> str: ... # undocumented def maybe(*choices: str) -> str: ... # undocumented @@ -100,11 +110,7 @@ PseudoExtras: str # undocumented PseudoToken: str # undocumented endpats: Dict[str, str] # undocumented -if sys.version_info < (3, 6): - single_quoted: Dict[str, str] # undocumented - triple_quoted: Dict[str, str] # undocumented -else: - single_quoted: Set[str] # undocumented - triple_quoted: Set[str] # undocumented +single_quoted: Set[str] # undocumented +triple_quoted: Set[str] # undocumented tabsize: int # undocumented diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index cd90b966a9be..6cdb537baa7c 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -1,21 +1,37 @@ -from _typeshed import StrPath import types +from _typeshed import StrPath from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar, Union -_T = TypeVar('_T') +_T = TypeVar("_T") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] class CoverageResults: 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]: ... + 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 __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 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) -> Tuple[str, Optional[str], str]: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 8a507e68e965..3972ca875fa8 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,72 +1,83 @@ -from typing import Any, Dict, Generator, IO, Iterator, List, Mapping, Optional, Tuple, Type, Iterable -from types import FrameType, TracebackType import sys from _typeshed import SupportsWrite +from types import FrameType, TracebackType +from typing import IO, Any, Dict, Generator, Iterable, Iterator, List, Mapping, 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_tb(tb: Optional[TracebackType], limit: Optional[int] = ..., - file: Optional[IO[str]] = ...) -> None: ... if 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: ... - 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_exception( + etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], + limit: Optional[int] = ..., + file: Optional[IO[str]] = ..., + chain: bool = ..., + ) -> 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: ... + else: - 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 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: ... 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 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 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_only(etype: Optional[Type[BaseException]], value: Optional[BaseException]) -> List[str]: ... + if sys.version_info >= (3,): - def format_exception(etype: Optional[Type[BaseException]], value: Optional[BaseException], - tb: Optional[TracebackType], limit: Optional[int] = ..., - chain: bool = ...) -> List[str]: ... + def format_exception( + etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], + limit: Optional[int] = ..., + chain: bool = ..., + ) -> List[str]: ... def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ... + else: - def format_exception(etype: Optional[Type[BaseException]], - value: Optional[BaseException], - tb: Optional[TracebackType], - limit: Optional[int] = ...) -> 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 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 @@ -79,39 +90,51 @@ if sys.version_info >= (3, 5): text: str offset: int msg: str - def __init__(self, exc_type: Type[BaseException], - exc_value: BaseException, exc_traceback: TracebackType, - *, limit: Optional[int] = ..., lookup_lines: bool = ..., - capture_locals: bool = ...) -> None: ... + def __init__( + self, + exc_type: Type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType, + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + ) -> None: ... @classmethod - def from_exception(cls, exc: BaseException, - *, limit: Optional[int] = ..., - lookup_lines: bool = ..., - capture_locals: bool = ...) -> TracebackException: ... + 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: ... + 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: ... + 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/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index de9d5150b47f..593c4edaec65 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,29 +1,30 @@ -# Stubs for tracemalloc (Python 3.4+) - import sys from typing import List, Optional, Sequence, Tuple, Union, overload + from _tracemalloc import * def get_object_traceback(obj: object) -> Optional[Traceback]: ... def take_snapshot() -> Snapshot: ... -if sys.version_info >= (3, 6): - class DomainFilter: - inclusive: bool - domain: int - def __init__(self, inclusive: bool, domain: int) -> None: ... +class DomainFilter: + inclusive: bool + domain: int + def __init__(self, inclusive: bool, domain: int) -> None: ... class Filter: - if sys.version_info >= (3, 6): - domain: Optional[int] + domain: Optional[int] inclusive: bool lineno: Optional[int] filename_pattern: str all_frames: bool - if sys.version_info >= (3, 6): - def __init__(self, inclusive: bool, filename_pattern: str, lineno: Optional[int] = ..., all_frames: bool = ..., domain: Optional[int] = ...) -> None: ... - else: - def __init__(self, inclusive: bool, filename_pattern: str, lineno: Optional[int] = ..., all_frames: bool = ...) -> None: ... + def __init__( + self, + inclusive: bool, + filename_pattern: str, + lineno: Optional[int] = ..., + all_frames: bool = ..., + domain: Optional[int] = ..., + ) -> None: ... class Statistic: count: int @@ -73,15 +74,11 @@ class Traceback(Sequence[Frame]): def __getitem__(self, s: slice) -> Sequence[Frame]: ... def __len__(self) -> int: ... - class Snapshot: def __init__(self, traces: Sequence[_TraceTupleT], traceback_limit: int) -> None: ... def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = ...) -> List[StatisticDiff]: ... def dump(self, filename: str) -> None: ... - if sys.version_info >= (3, 6): - def filter_traces(self, filters: Sequence[Union[DomainFilter, Filter]]) -> Snapshot: ... - else: - def filter_traces(self, filters: Sequence[Filter]) -> Snapshot: ... + def filter_traces(self, filters: Sequence[Union[DomainFilter, Filter]]) -> Snapshot: ... @staticmethod def load(filename: str) -> Snapshot: ... def statistics(self, key_type: str, cumulative: bool = ...) -> List[Statistic]: ... diff --git a/mypy/typeshed/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi index 2bce1eca7dca..c0dc418e9933 100644 --- a/mypy/typeshed/stdlib/tty.pyi +++ b/mypy/typeshed/stdlib/tty.pyi @@ -1,5 +1,3 @@ -# Stubs for tty (Python 3.6) - from typing import IO, Union _FD = Union[int, IO[str]] diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index c3ee65193a40..eee601823a59 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -1,5 +1,6 @@ -from typing import Tuple, overload, Optional, Union, Dict, Any, Sequence, TypeVar, List, Callable, Text 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: @@ -34,7 +35,14 @@ class TurtleScreenBase(object): 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 numinput( + self, + title: str, + prompt: str, + default: Optional[float] = ..., + minval: Optional[float] = ..., + maxval: Optional[float] = ..., + ) -> Optional[float]: ... class Terminator(Exception): ... class TurtleGraphicsError(Exception): ... @@ -142,7 +150,6 @@ class TNavigator(object): setposition = goto seth = setheading - class TPen(object): def __init__(self, resizemode: str = ...) -> None: ... @overload @@ -187,10 +194,21 @@ class TPen(object): @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: ... + 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 @@ -199,10 +217,12 @@ class TPen(object): st = showturtle ht = hideturtle -_T = TypeVar('_T') +_T = TypeVar("_T") class RawTurtle(TPen, TNavigator): - def __init__(self, canvas: Union[Canvas, TurtleScreen, None] = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ... + 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: ... @@ -216,7 +236,9 @@ class RawTurtle(TPen, TNavigator): @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 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: ... @@ -226,7 +248,9 @@ class RawTurtle(TPen, TNavigator): @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 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 @@ -265,7 +289,7 @@ class _Screen(TurtleScreen): width: Union[int, float] = ..., height: Union[int, float] = ..., startx: Optional[int] = ..., - starty: Optional[int] = ... + starty: Optional[int] = ..., ) -> None: ... def title(self, titlestring: str) -> None: ... def bye(self) -> None: ... @@ -295,9 +319,12 @@ 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 numinput( + title: str, prompt: str, default: Optional[float] = ..., minval: Optional[float] = ..., maxval: Optional[float] = ... + ) -> Optional[float]: ... # Functions copied from TurtleScreen: @@ -345,6 +372,7 @@ def bgpic(picname: str) -> None: ... 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 @@ -382,6 +410,7 @@ 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 @@ -393,7 +422,6 @@ setposition = goto seth = setheading # Functions copied from TPen: - @overload def resizemode(rmode: None = ...) -> str: ... @overload @@ -432,14 +460,26 @@ 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: ... +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 @@ -456,11 +496,13 @@ def undobufferentries() -> int: ... 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: ... + if sys.version_info >= (3,): @overload def shearfactor(shear: None = ...) -> float: ... @@ -470,14 +512,18 @@ if sys.version_info >= (3,): @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 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: ... @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. @@ -494,10 +540,13 @@ 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: diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 6c1bbfced061..d5b419c177ed 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -1,23 +1,33 @@ -# Stubs for types -# Note, all classes "defined" here require special handling. - -# TODO parts of this should be conditional on version - import sys from typing import ( - Any, Awaitable, Callable, Dict, Generic, Iterator, Mapping, Optional, Tuple, TypeVar, - Union, overload, Type, Iterable + Any, + Awaitable, + Callable, + Dict, + Generic, + Iterable, + Iterator, + Mapping, + Optional, + Tuple, + Type, + TypeVar, + Union, + overload, ) +from typing_extensions import Literal, final # ModuleType is exported from this module, but for circular import # reasons exists in its own stub file (with ModuleSpec and Loader). from _importlib_modulespec import ModuleType as ModuleType # Exported -_T = TypeVar('_T') -_T_co = TypeVar('_T_co', covariant=True) -_T_contra = TypeVar('_T_contra', contravariant=True) -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') +# Note, all classes "defined" here require special handling. + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") class _Cell: cell_contents: Any @@ -32,13 +42,22 @@ class FunctionType: __qualname__: str __annotations__: Dict[str, Any] __kwdefaults__: Dict[str, Any] - def __init__(self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ...) -> None: ... + def __init__( + self, + code: CodeType, + globals: Dict[str, Any], + name: Optional[str] = ..., + argdefs: Optional[Tuple[object, ...]] = ..., + closure: Optional[Tuple[_Cell, ...]] = ..., + ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... + LambdaType = FunctionType class CodeType: """Create a code object. Not for the faint of heart.""" + co_argcount: int if sys.version_info >= (3, 8): co_posonlyargcount: int @@ -122,7 +141,7 @@ class MappingProxyType(Mapping[_KT, _VT], Generic[_KT, _VT]): def __getitem__(self, k: _KT) -> _VT: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... - def copy(self) -> Mapping[_KT, _VT]: ... + def copy(self) -> Dict[_KT, _VT]: ... class SimpleNamespace: def __init__(self, **kwargs: Any) -> None: ... @@ -140,28 +159,27 @@ class GeneratorType: def close(self) -> None: ... def send(self, __arg: Any) -> Any: ... @overload - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> Any: ... @overload - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... - -if sys.version_info >= (3, 6): - class AsyncGeneratorType(Generic[_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 __anext__(self) -> Awaitable[_T_co]: ... - def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... - @overload - def athrow(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... - @overload - def athrow(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... - def aclose(self) -> Awaitable[None]: ... + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... + +class AsyncGeneratorType(Generic[_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 __anext__(self) -> Awaitable[_T_co]: ... + def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... + @overload + def athrow( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> Awaitable[_T_co]: ... + @overload + def athrow(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + def aclose(self) -> Awaitable[None]: ... class CoroutineType: cr_await: Optional[Any] @@ -171,11 +189,11 @@ class CoroutineType: def close(self) -> None: ... def send(self, __arg: Any) -> Any: ... @overload - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> Any: ... @overload - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> Any: ... + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... class _StaticFunctionType: """Fictional type to correct the type of MethodType.__func__. @@ -190,6 +208,7 @@ class _StaticFunctionType: similar to wrapping a function in staticmethod() at runtime to prevent it being bound as a method. """ + def __get__(self, obj: Optional[object], type: Optional[type]) -> FunctionType: ... class MethodType: @@ -199,11 +218,13 @@ class MethodType: __qualname__: str def __init__(self, func: Callable[..., Any], obj: object) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + class BuiltinFunctionType: __self__: Union[object, ModuleType] __name__: str __qualname__: str def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + BuiltinMethodType = BuiltinFunctionType if sys.version_info >= (3, 7): @@ -213,7 +234,6 @@ if sys.version_info >= (3, 7): __objclass__: type def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Any, type: type = ...) -> Any: ... - class MethodWrapperType: __self__: object __name__: str @@ -222,14 +242,12 @@ if sys.version_info >= (3, 7): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... - class MethodDescriptorType: __name__: str __qualname__: str __objclass__: type def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Any, type: type = ...) -> Any: ... - class ClassMethodDescriptorType: __name__: str __qualname__: str @@ -237,7 +255,6 @@ if sys.version_info >= (3, 7): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Any, type: type = ...) -> Any: ... - class TracebackType: if sys.version_info >= (3, 7): def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ... @@ -261,11 +278,10 @@ class FrameType: f_lasti: int f_lineno: int f_locals: Dict[str, Any] - f_trace: Callable[[], None] + f_trace: Optional[Callable[[FrameType, str, Any], Any]] if sys.version_info >= (3, 7): f_trace_lines: bool f_trace_opcodes: bool - def clear(self) -> None: ... class GetSetDescriptorType: @@ -274,6 +290,7 @@ class GetSetDescriptorType: def __get__(self, obj: Any, type: type = ...) -> Any: ... def __set__(self, obj: Any) -> None: ... def __delete__(self, obj: Any) -> None: ... + class MemberDescriptorType: __name__: str __objclass__: type @@ -282,11 +299,19 @@ class MemberDescriptorType: def __delete__(self, obj: Any) -> None: ... if sys.version_info >= (3, 7): - def new_class(name: str, bases: Iterable[object] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ...) -> type: ... + def new_class( + name: str, bases: Iterable[object] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ... + ) -> type: ... def resolve_bases(bases: Iterable[object]) -> Tuple[Any, ...]: ... + else: - def new_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ...) -> type: ... -def prepare_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ...) -> Tuple[type, Dict[str, Any], Dict[str, Any]]: ... + def new_class( + name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ... + ) -> type: ... + +def prepare_class( + name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ... +) -> Tuple[type, Dict[str, Any], Dict[str, Any]]: ... # Actually a different type, but `property` is special and we want that too. DynamicClassAttribute = property @@ -298,5 +323,12 @@ if sys.version_info >= (3, 9): __origin__: type __args__: Tuple[Any, ...] __parameters__: Tuple[Any, ...] - def __init__(self, origin: type, args: Any): ... + def __init__(self, origin: type, args: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... # incomplete + +if sys.version_info >= (3, 10): + @final + class NoneType: + def __bool__(self) -> Literal[False]: ... + EllipsisType = ellipsis # noqa F811 from builtins + NotImplementedType = _NotImplementedType # noqa F811 from builtins diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index fc8ccd763749..a2ed53cf9557 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,9 +1,13 @@ -# Stubs for typing - -import sys -from abc import abstractmethod, ABCMeta -from types import CodeType, FrameType, TracebackType import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +import sys +from abc import ABCMeta, abstractmethod +from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType + +if sys.version_info >= (3, 7): + from types import MethodDescriptorType, MethodWrapperType, WrapperDescriptorType + +if sys.version_info >= (3, 9): + from types import GenericAlias # Definitions of special type checking related constructs. Their definitions # are not used, so their value does not matter. @@ -17,7 +21,14 @@ class TypeVar: __constraints__: Tuple[Type[Any], ...] __covariant__: bool __contravariant__: bool - def __init__(self, name: str, *constraints: Type[Any], bound: Optional[Type[Any]] = ..., covariant: bool = ..., contravariant: bool = ...) -> None: ... + def __init__( + self, + name: str, + *constraints: Type[Any], + bound: Union[None, Type[Any], str] = ..., + covariant: bool = ..., + contravariant: bool = ..., + ) -> None: ... _promote = object() @@ -35,7 +46,7 @@ Type: _SpecialForm = ... ClassVar: _SpecialForm = ... if sys.version_info >= (3, 8): Final: _SpecialForm = ... - _F = TypeVar('_F', bound=Callable[..., Any]) + _F = TypeVar("_F", bound=Callable[..., Any]) def final(f: _F) -> _F: ... Literal: _SpecialForm = ... # TypedDict is a (non-subscriptable) special form. @@ -44,25 +55,34 @@ if sys.version_info >= (3, 8): if sys.version_info < (3, 7): class GenericMeta(type): ... +if sys.version_info >= (3, 10): + class ParamSpec: + __name__: str + def __init__(self, name: str) -> None: ... + Concatenate: _SpecialForm = ... + TypeAlias: _SpecialForm = ... + TypeGuard: _SpecialForm = ... + # Return type that indicates a function does not return. # This type is equivalent to the None type, but the no-op Union is necessary to # distinguish the None type from the None value. NoReturn = Union[None] # These type variables are used by the container types. -_T = TypeVar('_T') -_S = TypeVar('_S') -_KT = TypeVar('_KT') # Key type. -_VT = TypeVar('_VT') # Value type. -_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. -_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. -_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. -_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. -_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. -_TC = TypeVar('_TC', bound=Type[object]) +_T = TypeVar("_T") +_S = TypeVar("_S") +_KT = TypeVar("_KT") # Key type. +_VT = TypeVar("_VT") # Value type. +_T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. +_V_co = TypeVar("_V_co", covariant=True) # Any type covariant containers. +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. +_T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. +_TC = TypeVar("_TC", bound=Type[object]) _C = TypeVar("_C", bound=Callable[..., Any]) no_type_check = object() + def no_type_check_decorator(decorator: _C) -> _C: ... # Type aliases and type constructors @@ -87,12 +107,11 @@ if sys.version_info >= (3, 9): Annotated: _SpecialForm = ... # Predefined type variables. -AnyStr = TypeVar('AnyStr', str, bytes) +AnyStr = TypeVar("AnyStr", str, bytes) # Abstract base classes. def runtime_checkable(cls: _TC) -> _TC: ... - @runtime_checkable class SupportsInt(Protocol, metaclass=ABCMeta): @abstractmethod @@ -133,11 +152,6 @@ class SupportsRound(Protocol[_T_co]): @abstractmethod def __round__(self, ndigits: int) -> _T_co: ... -@runtime_checkable -class Reversible(Protocol[_T_co]): - @abstractmethod - def __reversed__(self) -> Iterator[_T_co]: ... - @runtime_checkable class Sized(Protocol, metaclass=ABCMeta): @abstractmethod @@ -162,28 +176,25 @@ class Iterator(Iterable[_T_co], Protocol[_T_co]): def __next__(self) -> _T_co: ... def __iter__(self) -> Iterator[_T_co]: ... -class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): +@runtime_checkable +class Reversible(Iterable[_T_co], Protocol[_T_co]): @abstractmethod - def __next__(self) -> _T_co: ... + def __reversed__(self) -> Iterator[_T_co]: ... +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + def __next__(self) -> _T_co: ... @abstractmethod def send(self, __value: _T_contra) -> _T_co: ... - @overload @abstractmethod - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> _T_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... - - @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... def close(self) -> None: ... - - @abstractmethod def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ... - @property def gi_code(self) -> CodeType: ... @property @@ -199,6 +210,8 @@ class Awaitable(Protocol[_T_co]): def __await__(self) -> Generator[Any, None, _T_co]: ... class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): + __name__: str + __qualname__: str @property def cr_await(self) -> Optional[Any]: ... @property @@ -207,27 +220,24 @@ class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): def cr_frame(self) -> FrameType: ... @property def cr_running(self) -> bool: ... - @abstractmethod def send(self, __value: _T_contra) -> _T_co: ... - @overload @abstractmethod - def throw(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> _T_co: ... @overload @abstractmethod - def throw(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> _T_co: ... - + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... @abstractmethod def close(self) -> None: ... - # NOTE: This type does not exist in typing.py or PEP 484. # The parameters correspond to Generator, but the 4th is the original type. -class AwaitableGenerator(Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], - Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta): ... +class AwaitableGenerator( + Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta +): ... @runtime_checkable class AsyncIterable(Protocol[_T_co]): @@ -235,64 +245,49 @@ class AsyncIterable(Protocol[_T_co]): def __aiter__(self) -> AsyncIterator[_T_co]: ... @runtime_checkable -class AsyncIterator(AsyncIterable[_T_co], - Protocol[_T_co]): +class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): @abstractmethod def __anext__(self) -> Awaitable[_T_co]: ... def __aiter__(self) -> AsyncIterator[_T_co]: ... -if sys.version_info >= (3, 6): - class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): - @abstractmethod - def __anext__(self) -> Awaitable[_T_co]: ... - - @abstractmethod - def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... - - @overload - @abstractmethod - def athrow(self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., - __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... - @overload - @abstractmethod - def athrow(self, __typ: BaseException, __val: None = ..., - __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... - - @abstractmethod - def aclose(self) -> Awaitable[None]: ... - - @abstractmethod - def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... - - @property - def ag_await(self) -> Any: ... - @property - def ag_code(self) -> CodeType: ... - @property - def ag_frame(self) -> FrameType: ... - @property - def ag_running(self) -> bool: ... +class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + @abstractmethod + def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... + @overload + @abstractmethod + def athrow( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> Awaitable[_T_co]: ... + @overload + @abstractmethod + def athrow(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... + @abstractmethod + def aclose(self) -> Awaitable[None]: ... + @abstractmethod + def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... + @property + def ag_await(self) -> Any: ... + @property + def ag_code(self) -> CodeType: ... + @property + def ag_frame(self) -> FrameType: ... + @property + def ag_running(self) -> bool: ... @runtime_checkable class Container(Protocol[_T_co]): @abstractmethod def __contains__(self, __x: object) -> bool: ... +@runtime_checkable +class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... -if sys.version_info >= (3, 6): - @runtime_checkable - class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - - _Collection = Collection -else: - @runtime_checkable - class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... +_Collection = Collection[_T_co] class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): @overload @@ -302,15 +297,15 @@ class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): @abstractmethod def __getitem__(self, s: slice) -> Sequence[_T_co]: ... # Mixin methods - def index(self, x: Any, start: int = ..., end: int = ...) -> int: ... - def count(self, x: Any) -> int: ... + def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... + def count(self, value: Any) -> int: ... def __contains__(self, x: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... class MutableSequence(Sequence[_T], Generic[_T]): @abstractmethod - def insert(self, index: int, object: _T) -> None: ... + def insert(self, index: int, value: _T) -> None: ... @overload @abstractmethod def __getitem__(self, i: int) -> _T: ... @@ -330,12 +325,12 @@ class MutableSequence(Sequence[_T], Generic[_T]): @abstractmethod def __delitem__(self, i: slice) -> None: ... # Mixin methods - def append(self, object: _T) -> None: ... + def append(self, value: _T) -> None: ... def clear(self) -> None: ... - def extend(self, iterable: Iterable[_T]) -> None: ... + def extend(self, values: Iterable[_T]) -> None: ... def reverse(self) -> None: ... def pop(self, index: int = ...) -> _T: ... - def remove(self, object: _T) -> None: ... + def remove(self, value: _T) -> None: ... def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... class AbstractSet(_Collection[_T_co], Generic[_T_co]): @@ -350,17 +345,17 @@ class AbstractSet(_Collection[_T_co], Generic[_T_co]): def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... - def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def isdisjoint(self, other: Iterable[Any]) -> bool: ... class MutableSet(AbstractSet[_T], Generic[_T]): @abstractmethod - def add(self, x: _T) -> None: ... + def add(self, value: _T) -> None: ... @abstractmethod - def discard(self, x: _T) -> None: ... + def discard(self, value: _T) -> None: ... # Mixin methods def clear(self) -> None: ... def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... + def remove(self, value: _T) -> None: ... def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... @@ -410,31 +405,30 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): @runtime_checkable class ContextManager(Protocol[_T_co]): def __enter__(self) -> _T_co: ... - def __exit__(self, __exc_type: Optional[Type[BaseException]], - __exc_value: Optional[BaseException], - __traceback: Optional[TracebackType]) -> Optional[bool]: ... + def __exit__( + self, + __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> Optional[bool]: ... @runtime_checkable class AsyncContextManager(Protocol[_T_co]): def __aenter__(self) -> Awaitable[_T_co]: ... def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], + self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Awaitable[Optional[bool]]: ... class Mapping(_Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, # see discussion in https: //github.com/python/typing/pull/273. @abstractmethod - def __getitem__(self, k: _KT) -> _VT_co: - ... + def __getitem__(self, k: _KT) -> _VT_co: ... # Mixin methods @overload - def get(self, k: _KT) -> Optional[_VT_co]: ... + def get(self, key: _KT) -> Optional[_VT_co]: ... @overload - def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def get(self, key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... def items(self) -> AbstractSet[Tuple[_KT, _VT_co]]: ... def keys(self) -> AbstractSet[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... @@ -445,14 +439,13 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): def __setitem__(self, k: _KT, v: _VT) -> None: ... @abstractmethod def __delitem__(self, v: _KT) -> None: ... - def clear(self) -> None: ... @overload - def pop(self, k: _KT) -> _VT: ... + def pop(self, key: _KT) -> _VT: ... @overload - def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def pop(self, key: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... def popitem(self) -> Tuple[_KT, _VT]: ... - def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], @@ -475,7 +468,6 @@ Text = str TYPE_CHECKING = True class IO(Iterator[AnyStr], Generic[AnyStr]): - # TODO detach # TODO use abstract properties @property def mode(self) -> str: ... @@ -491,7 +483,6 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def flush(self) -> None: ... @abstractmethod def isatty(self) -> bool: ... - # TODO what if n is None? @abstractmethod def read(self, n: int = ...) -> AnyStr: ... @abstractmethod @@ -510,12 +501,10 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def truncate(self, size: Optional[int] = ...) -> int: ... @abstractmethod def writable(self) -> bool: ... - # TODO buffer objects @abstractmethod def write(self, s: AnyStr) -> int: ... @abstractmethod def writelines(self, lines: Iterable[AnyStr]) -> None: ... - @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -523,13 +512,11 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): @abstractmethod def __enter__(self) -> IO[AnyStr]: ... @abstractmethod - def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], - traceback: Optional[TracebackType]) -> Optional[bool]: ... + def __exit__( + self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> Optional[bool]: ... class BinaryIO(IO[bytes]): - # TODO readinto - # TODO read1? - # TODO peek? @abstractmethod def __enter__(self) -> BinaryIO: ... @@ -560,20 +547,12 @@ class Match(Generic[AnyStr]): # The regular expression object whose match() or search() method produced # this match instance. re: Pattern[AnyStr] - def expand(self, template: AnyStr) -> AnyStr: ... - # TODO: The return for a group may be None, except if __group is 0 or not given. @overload def group(self, __group: Union[str, int] = ...) -> AnyStr: ... @overload - def group( - self, - __group1: Union[str, int], - __group2: Union[str, int], - *groups: Union[str, int], - ) -> Tuple[AnyStr, ...]: ... - + def group(self, __group1: Union[str, int], __group2: Union[str, int], *groups: Union[str, int]) -> Tuple[AnyStr, ...]: ... def groups(self, default: AnyStr = ...) -> Sequence[AnyStr]: ... def groupdict(self, default: AnyStr = ...) -> dict[str, AnyStr]: ... def start(self, __group: Union[int, str] = ...) -> int: ... @@ -581,53 +560,72 @@ class Match(Generic[AnyStr]): def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... @property def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented - if sys.version_info >= (3, 6): - def __getitem__(self, g: Union[int, str]) -> AnyStr: ... + def __getitem__(self, g: Union[int, str]) -> AnyStr: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Pattern(Generic[AnyStr]): flags: int groupindex: Mapping[str, int] groups: int pattern: AnyStr - - def search(self, string: AnyStr, pos: int = ..., - endpos: int = ...) -> Optional[Match[AnyStr]]: ... - def match(self, string: AnyStr, pos: int = ..., - endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... # New in Python 3.4 - def fullmatch(self, string: AnyStr, pos: int = ..., - endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... - def findall(self, string: AnyStr, pos: int = ..., - endpos: int = ...) -> list[Any]: ... - def finditer(self, string: AnyStr, pos: int = ..., - endpos: int = ...) -> Iterator[Match[AnyStr]]: ... - + def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ... + def finditer(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Iterator[Match[AnyStr]]: ... @overload - def sub(self, repl: AnyStr, string: AnyStr, - count: int = ...) -> AnyStr: ... + def sub(self, repl: AnyStr, string: AnyStr, count: int = ...) -> AnyStr: ... @overload - def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, - count: int = ...) -> AnyStr: ... - + def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> AnyStr: ... @overload - def subn(self, repl: AnyStr, string: AnyStr, - count: int = ...) -> Tuple[AnyStr, int]: ... + def subn(self, repl: AnyStr, string: AnyStr, count: int = ...) -> Tuple[AnyStr, int]: ... @overload - def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, - count: int = ...) -> Tuple[AnyStr, int]: ... + def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> Tuple[AnyStr, int]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... # Functions +if sys.version_info >= (3, 7): + _get_type_hints_obj_allowed_types = Union[ + object, + Callable[..., Any], + FunctionType, + BuiltinFunctionType, + MethodType, + ModuleType, + WrapperDescriptorType, + MethodWrapperType, + MethodDescriptorType, + ] +else: + _get_type_hints_obj_allowed_types = Union[ + object, + Callable[..., Any], + FunctionType, + BuiltinFunctionType, + MethodType, + ModuleType, + ] + if sys.version_info >= (3, 9): def get_type_hints( - obj: Callable[..., Any], globalns: Optional[Dict[str, Any]] = ..., localns: Optional[Dict[str, Any]] = ..., - include_extras: bool = ... + obj: _get_type_hints_obj_allowed_types, + globalns: Optional[Dict[str, Any]] = ..., + localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ..., ) -> Dict[str, Any]: ... + else: def get_type_hints( - obj: Callable[..., Any], globalns: Optional[Dict[str, Any]] = ..., localns: Optional[Dict[str, Any]] = ..., + obj: _get_type_hints_obj_allowed_types, + globalns: Optional[Dict[str, Any]] = ..., + localns: Optional[Dict[str, Any]] = ..., ) -> Dict[str, Any]: ... + if sys.version_info >= (3, 8): def get_origin(tp: Any) -> Optional[Any]: ... def get_args(tp: Any) -> Tuple[Any, ...]: ... @@ -636,6 +634,8 @@ if sys.version_info >= (3, 8): def cast(typ: Type[_T], val: Any) -> _T: ... @overload def cast(typ: str, val: Any) -> Any: ... +@overload +def cast(typ: object, val: Any) -> Any: ... # Type constructors @@ -645,13 +645,9 @@ class NamedTuple(Tuple[Any, ...]): _field_defaults: Dict[str, Any] = ... _fields: Tuple[str, ...] _source: str - - def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., - **kwargs: Any) -> None: ... - + def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., **kwargs: Any) -> None: ... @classmethod def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... - if sys.version_info >= (3, 8): def _asdict(self) -> Dict[str, Any]: ... else: @@ -686,8 +682,7 @@ if sys.version_info >= (3, 7): __forward_value__: Optional[Any] __forward_is_argument__: bool def __init__(self, arg: str, is_argument: bool = ...) -> None: ... - def _evaluate(self, globalns: Optional[Dict[str, Any]], - localns: Optional[Dict[str, Any]]) -> Optional[Any]: ... + def _evaluate(self, globalns: Optional[Dict[str, Any]], localns: Optional[Dict[str, Any]]) -> Optional[Any]: ... def __eq__(self, other: Any) -> bool: ... def __hash__(self) -> int: ... def __repr__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 4a40137b99c6..f103a0faf36d 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,31 +1,47 @@ import abc import sys -from typing import Callable -from typing import ClassVar as ClassVar -from typing import ContextManager as ContextManager -from typing import Counter as Counter -from typing import DefaultDict as DefaultDict -from typing import Deque as Deque -from typing import NewType as NewType -from typing import NoReturn as NoReturn -from typing import overload as overload -from typing import Text as Text -from typing import Type as Type -from typing import TYPE_CHECKING as TYPE_CHECKING -from typing import TypeVar, Any, Mapping, ItemsView, KeysView, Optional, ValuesView, Dict - -_T = TypeVar('_T') -_F = TypeVar('_F', bound=Callable[..., Any]) -_TC = TypeVar('_TC', bound=Type[object]) +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, + ValuesView, + 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) @@ -55,22 +71,47 @@ if sys.version_info >= (3, 3): from typing import ChainMap as ChainMap if sys.version_info >= (3, 5): - from typing import AsyncIterable as AsyncIterable - from typing import AsyncIterator as AsyncIterator - from typing import AsyncContextManager as AsyncContextManager - from typing import Awaitable as Awaitable - from typing import Coroutine as Coroutine + 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]] = ..., localns: Optional[Dict[str, Any]] = ..., - include_extras: bool = ... + obj: Callable[..., Any], + globalns: Optional[Dict[str, Any]] = ..., + localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ..., ) -> Dict[str, Any]: ... +if sys.version_info >= (3, 7): + def get_args(tp: Any) -> Tuple[Any, ...]: ... + def get_origin(tp: Any) -> Optional[Any]: ... + Annotated: _SpecialForm = ... _AnnotatedAlias: Any = ... # undocumented # TypeAlias is a (non-subscriptable) special form. -TypeAlias: object +class TypeAlias: ... + +@runtime_checkable +class SupportsIndex(Protocol, metaclass=abc.ABCMeta): + @abc.abstractmethod + def __index__(self) -> int: ... + +# PEP 612 support for Python < 3.9 +if sys.version_info >= (3, 10): + from typing import Concatenate as Concatenate, ParamSpec as ParamSpec +else: + class ParamSpec: + __name__: str + def __init__(self, name: str) -> None: ... + Concatenate: _SpecialForm = ... + +# PEP 647 +TypeGuard: _SpecialForm = ... diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index ddd10136158d..a83d79ff2ed0 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -5,22 +5,24 @@ ucd_3_2_0: UCD ucnhash_CAPI: Any unidata_version: str -_default = TypeVar('_default') +_T = TypeVar("_T") def bidirectional(__chr: Text) -> Text: ... def category(__chr: Text) -> Text: ... def combining(__chr: Text) -> int: ... -def decimal(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def decimal(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... def decomposition(__chr: Text) -> Text: ... -def digit(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def digit(__chr: Text, __default: _T = ...) -> Union[int, _T]: ... def east_asian_width(__chr: Text) -> Text: ... + 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: _default = ...) -> Union[Text, _default]: ... +def name(__chr: Text, __default: _T = ...) -> Union[Text, _T]: ... def normalize(__form: Text, __unistr: Text) -> Text: ... -def numeric(__chr: Text, __default: _default = ...) -> Union[float, _default]: ... +def numeric(__chr: Text, __default: _T = ...) -> Union[float, _T]: ... class UCD(object): # The methods below are constructed from the same array in C @@ -29,12 +31,12 @@ class UCD(object): def bidirectional(self, __chr: Text) -> str: ... def category(self, __chr: Text) -> str: ... def combining(self, __chr: Text) -> int: ... - def decimal(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + def decimal(self, __chr: Text, __default: _T = ...) -> Union[int, _T]: ... def decomposition(self, __chr: Text) -> str: ... - def digit(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + 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: _default = ...) -> Union[Text, _default]: ... + def name(self, __chr: Text, __default: _T = ...) -> Union[Text, _T]: ... def normalize(self, __form: Text, __unistr: Text) -> Text: ... - def numeric(self, __chr: Text, __default: _default = ...) -> Union[float, _default]: ... + def numeric(self, __chr: Text, __default: _T = ...) -> Union[float, _T]: ... diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index 1c8c668045d3..aadaa610abbd 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -1,7 +1,4 @@ -# Stubs for unittest - from typing import Optional - from unittest.async_case import * from unittest.case import * from unittest.loader import * @@ -11,5 +8,4 @@ from unittest.runner import * from unittest.signals import * from unittest.suite import * -def load_tests(loader: TestLoader, tests: TestSuite, - pattern: Optional[str]) -> TestSuite: ... +def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[str]) -> TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index 23e1c005c7a1..bdf534b37c9f 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,5 +1,6 @@ import sys from typing import Any, Awaitable, Callable + from .case import TestCase if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 2c9de24c4ad8..e3c23f8e97f1 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -2,16 +2,37 @@ import datetime import logging import sys import unittest.result -import warnings from types import TracebackType from typing import ( - Any, AnyStr, Callable, Container, ContextManager, Dict, FrozenSet, Generic, - Iterable, List, Mapping, NoReturn, Optional, overload, Pattern, Sequence, - Set, Tuple, Type, TypeVar, Union, + Any, + AnyStr, + Callable, + Container, + ContextManager, + Dict, + FrozenSet, + Generic, + Iterable, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + overload, ) +from warnings import WarningMessage -_E = TypeVar('_E', bound=BaseException) -_FT = TypeVar('_FT', bound=Callable[..., Any]) +if sys.version_info >= (3, 9): + from types import GenericAlias + +_E = TypeVar("_E", bound=BaseException) +_FT = TypeVar("_FT", bound=Callable[..., Any]) if sys.version_info >= (3, 8): def addModuleCleanup(__function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... @@ -22,11 +43,9 @@ def skip(reason: str) -> Callable[[_FT], _FT]: ... def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... - class SkipTest(Exception): def __init__(self, reason: str) -> None: ... - class TestCase: failureException: Type[BaseException] longMessage: bool @@ -47,132 +66,133 @@ class TestCase: def skipTest(self, reason: Any) -> None: ... def subTest(self, msg: Any = ..., **params: Any) -> ContextManager[None]: ... def debug(self) -> None: ... - def _addSkip( - self, result: unittest.result.TestResult, test_case: unittest.case.TestCase, reason: str - ) -> None: ... + def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertNotEqual(self, first: Any, second: Any, - msg: Any = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... def assertTrue(self, expr: Any, msg: Any = ...) -> None: ... def assertFalse(self, expr: Any, msg: Any = ...) -> None: ... def assertIs(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... def assertIsNot(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... def assertIsNone(self, obj: Any, msg: Any = ...) -> None: ... def assertIsNotNone(self, obj: Any, msg: Any = ...) -> None: ... - def assertIn(self, member: Any, - container: Union[Iterable[Any], Container[Any]], - msg: Any = ...) -> None: ... - def assertNotIn(self, member: Any, - container: Union[Iterable[Any], Container[Any]], - msg: Any = ...) -> None: ... - def assertIsInstance(self, obj: Any, - cls: Union[type, Tuple[type, ...]], - msg: Any = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, - cls: Union[type, Tuple[type, ...]], - msg: Any = ...) -> None: ... + def assertIn(self, member: Any, container: Union[Iterable[Any], Container[Any]], msg: Any = ...) -> None: ... + def assertNotIn(self, member: Any, container: Union[Iterable[Any], Container[Any]], msg: Any = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: Any = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: Any = ...) -> None: ... def assertGreater(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertGreaterEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertLess(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertLessEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... @overload - def assertRaises(self, # type: ignore - expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], - callable: Callable[..., Any], - *args: Any, **kwargs: Any) -> None: ... + def assertRaises( # type: ignore + self, + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def assertRaises(self, - expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], - msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertRaises( + self, expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any = ... + ) -> _AssertRaisesContext[_E]: ... @overload - def assertRaisesRegex(self, # type: ignore - expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - callable: Callable[..., Any], - *args: Any, **kwargs: Any) -> None: ... + def assertRaisesRegex( # type: ignore + self, + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def assertRaisesRegex(self, - expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertRaisesRegex( + self, + expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ..., + ) -> _AssertRaisesContext[_E]: ... @overload - def assertWarns(self, # type: ignore - expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], - callable: Callable[..., Any], - *args: Any, **kwargs: Any) -> None: ... + def assertWarns( # type: ignore + self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def assertWarns(self, - expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], - msg: Any = ...) -> _AssertWarnsContext: ... + def assertWarns( + self, expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], msg: Any = ... + ) -> _AssertWarnsContext: ... @overload - def assertWarnsRegex(self, # type: ignore - expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - callable: Callable[..., Any], - *args: Any, **kwargs: Any) -> None: ... + def assertWarnsRegex( # type: ignore + self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def assertWarnsRegex(self, - expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - msg: Any = ...) -> _AssertWarnsContext: ... + def assertWarnsRegex( + self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ..., + ) -> _AssertWarnsContext: ... def assertLogs( - self, logger: Optional[Union[str, logging.Logger]] = ..., - level: Union[int, str, None] = ... + self, logger: Optional[Union[str, logging.Logger]] = ..., level: Union[int, str, None] = ... ) -> _AssertLogsContext: ... @overload - def assertAlmostEqual(self, first: float, second: float, places: Optional[int] = ..., - msg: Any = ..., delta: Optional[float] = ...) -> None: ... + def assertAlmostEqual( + self, first: float, second: float, places: Optional[int] = ..., msg: Any = ..., delta: Optional[float] = ... + ) -> None: ... @overload - def assertAlmostEqual(self, first: datetime.datetime, second: datetime.datetime, - places: Optional[int] = ..., msg: Any = ..., - delta: Optional[datetime.timedelta] = ...) -> None: ... + def assertAlmostEqual( + self, + first: datetime.datetime, + second: datetime.datetime, + places: Optional[int] = ..., + msg: Any = ..., + delta: Optional[datetime.timedelta] = ..., + ) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, *, - msg: Any = ...) -> None: ... + def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ...) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, - places: Optional[int] = ..., msg: Any = ...) -> None: ... + def assertNotAlmostEqual(self, first: float, second: float, places: Optional[int] = ..., msg: Any = ...) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, *, - msg: Any = ..., delta: Optional[float] = ...) -> None: ... + def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: Optional[float] = ...) -> None: ... @overload - def assertNotAlmostEqual(self, first: datetime.datetime, second: datetime.datetime, - places: Optional[int] = ..., msg: Any = ..., - delta: Optional[datetime.timedelta] = ...) -> None: ... - def assertRegex(self, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], - msg: Any = ...) -> None: ... - def assertNotRegex(self, text: AnyStr, unexpected_regex: Union[AnyStr, Pattern[AnyStr]], - msg: Any = ...) -> None: ... - def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], - msg: Any = ...) -> None: ... - def addTypeEqualityFunc(self, typeobj: Type[Any], - function: Callable[..., None]) -> None: ... - def assertMultiLineEqual(self, first: str, second: str, - msg: Any = ...) -> None: ... - def assertSequenceEqual(self, seq1: Sequence[Any], seq2: Sequence[Any], - msg: Any = ..., - seq_type: Optional[Type[Sequence[Any]]] = ...) -> None: ... - def assertListEqual(self, list1: List[Any], list2: List[Any], - msg: Any = ...) -> None: ... - def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], - msg: Any = ...) -> None: ... - def assertSetEqual(self, set1: Union[Set[Any], FrozenSet[Any]], - set2: Union[Set[Any], FrozenSet[Any]], msg: Any = ...) -> None: ... - def assertDictEqual(self, d1: Dict[Any, Any], d2: Dict[Any, Any], - msg: Any = ...) -> None: ... + def assertNotAlmostEqual( + self, + first: datetime.datetime, + second: datetime.datetime, + places: Optional[int] = ..., + msg: Any = ..., + delta: Optional[datetime.timedelta] = ..., + ) -> None: ... + def assertRegex(self, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], msg: Any = ...) -> None: ... + def assertNotRegex(self, text: AnyStr, unexpected_regex: Union[AnyStr, Pattern[AnyStr]], msg: Any = ...) -> None: ... + def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: Type[Any], function: Callable[..., None]) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, msg: Any = ...) -> None: ... + def assertSequenceEqual( + self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = ..., seq_type: Optional[Type[Sequence[Any]]] = ... + ) -> None: ... + def assertListEqual(self, list1: List[Any], list2: List[Any], msg: Any = ...) -> None: ... + def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], msg: Any = ...) -> None: ... + def assertSetEqual( + self, set1: Union[Set[Any], FrozenSet[Any]], set2: Union[Set[Any], FrozenSet[Any]], msg: Any = ... + ) -> None: ... + def assertDictEqual(self, d1: Dict[Any, Any], d2: Dict[Any, Any], msg: Any = ...) -> None: ... def fail(self, msg: Any = ...) -> NoReturn: ... def countTestCases(self) -> int: ... def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... def shortDescription(self) -> Optional[str]: ... - if sys.version_info >= (3, 8): - def addCleanup(self, __function: Callable[..., Any], *args: Any, - **kwargs: Any) -> None: ... + def addCleanup(self, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... else: - def addCleanup(self, function: Callable[..., Any], *args: Any, - **kwargs: Any) -> None: ... - + def addCleanup(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... def doCleanups(self) -> None: ... if sys.version_info >= (3, 8): @classmethod @@ -182,81 +202,84 @@ class TestCase: def _formatMessage(self, msg: Optional[str], standardMsg: str) -> str: ... # undocumented def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented # below is deprecated - def failUnlessEqual(self, first: Any, second: Any, - msg: Any = ...) -> None: ... + def failUnlessEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertNotEquals(self, first: Any, second: Any, - msg: Any = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... def failUnless(self, expr: bool, msg: Any = ...) -> None: ... def assert_(self, expr: bool, msg: Any = ...) -> None: ... def failIf(self, expr: bool, msg: Any = ...) -> None: ... @overload - def failUnlessRaises(self, # type: ignore - exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], - callable: Callable[..., Any] = ..., - *args: Any, **kwargs: Any) -> None: ... + def failUnlessRaises( # type: ignore + self, + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any] = ..., + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def failUnlessRaises(self, - exception: Union[Type[_E], Tuple[Type[_E], ...]], - msg: Any = ...) -> _AssertRaisesContext[_E]: ... - def failUnlessAlmostEqual(self, first: float, second: float, - places: int = ..., msg: Any = ...) -> None: ... - def assertAlmostEquals(self, first: float, second: float, places: int = ..., - msg: Any = ..., delta: float = ...) -> None: ... - def failIfAlmostEqual(self, first: float, second: float, places: int = ..., - msg: Any = ...) -> None: ... - def assertNotAlmostEquals(self, first: float, second: float, - places: int = ..., msg: Any = ..., - delta: float = ...) -> None: ... - def assertRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], - msg: Any = ...) -> None: ... - def assertNotRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], - msg: Any = ...) -> None: ... + def failUnlessRaises(self, exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + def assertAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ...) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + def assertNotAlmostEquals( + self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... + ) -> None: ... + def assertRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], msg: Any = ...) -> None: ... + def assertNotRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], msg: Any = ...) -> None: ... @overload - def assertRaisesRegexp(self, # type: ignore - exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - callable: Callable[..., Any], - *args: Any, **kwargs: Any) -> None: ... + def assertRaisesRegexp( # type: ignore + self, + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... @overload - def assertRaisesRegexp(self, - exception: Union[Type[_E], Tuple[Type[_E], ...]], - expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], - msg: Any = ...) -> _AssertRaisesContext[_E]: ... - def assertDictContainsSubset(self, - subset: Mapping[Any, Any], - dictionary: Mapping[Any, Any], - msg: object = ...) -> None: ... + def assertRaisesRegexp( + self, + exception: Union[Type[_E], Tuple[Type[_E], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ..., + ) -> _AssertRaisesContext[_E]: ... + def assertDictContainsSubset(self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = ...) -> None: ... class FunctionTestCase(TestCase): - def __init__(self, testFunc: Callable[[], None], - setUp: Optional[Callable[[], None]] = ..., - tearDown: Optional[Callable[[], None]] = ..., - description: Optional[str] = ...) -> None: ... + def __init__( + self, + testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ..., + ) -> None: ... def runTest(self) -> None: ... class _AssertRaisesContext(Generic[_E]): exception: _E def __enter__(self) -> _AssertRaisesContext[_E]: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> bool: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> bool: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class _AssertWarnsContext: - warning: warnings.WarningMessage + warning: WarningMessage filename: str lineno: int - warnings: List[warnings.WarningMessage] + warnings: List[WarningMessage] def __enter__(self) -> _AssertWarnsContext: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... class _AssertLogsContext: LOGGING_FORMAT: str records: List[logging.LogRecord] output: List[str] - def __init__(self, test_case: unittest.case.TestCase, - logger_name: str, level: int) -> None: ... + def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... def __enter__(self) -> _AssertLogsContext: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType]) -> Optional[bool]: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi index b8db7e00759d..48c9f1c5f100 100644 --- a/mypy/typeshed/stdlib/unittest/loader.pyi +++ b/mypy/typeshed/stdlib/unittest/loader.pyi @@ -1,11 +1,10 @@ import sys import unittest.case -import unittest.suite import unittest.result +import unittest.suite from types import ModuleType from typing import Any, Callable, List, Optional, Sequence, Type - _SortComparisonMethod = Callable[[str, str], int] _SuiteClass = Callable[[List[unittest.case.TestCase]], unittest.suite.TestSuite] @@ -18,32 +17,34 @@ class TestLoader: testNamePatterns: Optional[List[str]] suiteClass: _SuiteClass - def loadTestsFromTestCase(self, - testCaseClass: Type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... + def loadTestsFromTestCase(self, testCaseClass: Type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: Any = ...) -> unittest.suite.TestSuite: ... - def loadTestsFromName(self, name: str, - module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... - def loadTestsFromNames(self, names: Sequence[str], - module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... - def getTestCaseNames(self, - testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... - def discover(self, start_dir: str, pattern: str = ..., - top_level_dir: Optional[str] = ...) -> unittest.suite.TestSuite: ... + def loadTestsFromName(self, name: str, module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... + def loadTestsFromNames(self, names: Sequence[str], module: Optional[ModuleType] = ...) -> unittest.suite.TestSuite: ... + def getTestCaseNames(self, testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... + def discover(self, start_dir: str, pattern: str = ..., top_level_dir: Optional[str] = ...) -> unittest.suite.TestSuite: ... defaultTestLoader: TestLoader - if sys.version_info >= (3, 7): - def getTestCaseNames(testCaseClass: Type[unittest.case.TestCase], prefix: str, - sortUsing: _SortComparisonMethod = ..., - testNamePatterns: Optional[List[str]] = ...) -> Sequence[str]: ... -else: - def getTestCaseNames(testCaseClass: Type[unittest.case.TestCase], prefix: str, - sortUsing: _SortComparisonMethod = ...) -> Sequence[str]: ... - -def makeSuite(testCaseClass: Type[unittest.case.TestCase], prefix: str = ..., - sortUsing: _SortComparisonMethod = ..., - suiteClass: _SuiteClass = ...) -> unittest.suite.TestSuite: ... + def getTestCaseNames( + testCaseClass: Type[unittest.case.TestCase], + prefix: str, + sortUsing: _SortComparisonMethod = ..., + testNamePatterns: Optional[List[str]] = ..., + ) -> Sequence[str]: ... -def findTestCases(module, prefix: str = ..., sortUsing: _SortComparisonMethod = ..., - suiteClass: _SuiteClass = ...) -> unittest.suite.TestSuite: ... +else: + def getTestCaseNames( + testCaseClass: Type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... + ) -> Sequence[str]: ... + +def makeSuite( + testCaseClass: Type[unittest.case.TestCase], + prefix: str = ..., + sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ..., +) -> unittest.suite.TestSuite: ... +def findTestCases( + module: ModuleType, prefix: str = ..., sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... +) -> unittest.suite.TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index d6e1ebdbe1dd..5e6151eda3dd 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -1,17 +1,13 @@ import sys -from typing import Any, Iterable, List, Optional, Protocol, Type, Union -from types import ModuleType - import unittest.case import unittest.loader import unittest.result import unittest.suite +from types import ModuleType +from typing import Any, Iterable, List, Optional, Protocol, Type, Union class _TestRunner(Protocol): - def run( - self, test: Union[unittest.suite.TestSuite, unittest.case.TestCase] - ) -> unittest.result.TestResult: ... - + def run(self, test: Union[unittest.suite.TestSuite, unittest.case.TestCase]) -> unittest.result.TestResult: ... # not really documented class TestProgram: @@ -26,26 +22,28 @@ class TestProgram: if sys.version_info >= (3, 7): testNamePatterns: Optional[List[str]] - - def __init__(self, module: Union[None, str, ModuleType] = ..., - defaultTest: Union[str, Iterable[str], None] = ..., - argv: Optional[List[str]] = ..., - testRunner: Union[Type[_TestRunner], _TestRunner, None] = ..., - testLoader: unittest.loader.TestLoader = ..., - exit: bool = ..., verbosity: int = ..., - failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., - buffer: Optional[bool] = ..., - warnings: Optional[str] = ..., *, - tb_locals: bool = ...) -> None: ... + def __init__( + self, + module: Union[None, str, ModuleType] = ..., + defaultTest: Union[str, Iterable[str], None] = ..., + argv: Optional[List[str]] = ..., + testRunner: Union[Type[_TestRunner], _TestRunner, None] = ..., + testLoader: unittest.loader.TestLoader = ..., + exit: bool = ..., + verbosity: int = ..., + failfast: Optional[bool] = ..., + catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ..., + warnings: Optional[str] = ..., + *, + tb_locals: bool = ..., + ) -> None: ... def usageExit(self, msg: Any = ...) -> None: ... def parseArgs(self, argv: List[str]) -> None: ... - if sys.version_info >= (3, 7): - def createTests(self, from_discovery: bool = ..., - Loader: Optional[unittest.loader.TestLoader] = ...) -> None: ... + def createTests(self, from_discovery: bool = ..., Loader: Optional[unittest.loader.TestLoader] = ...) -> None: ... else: def createTests(self) -> None: ... - def runTests(self) -> None: ... # undocumented main = TestProgram diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 1f38f28a0b52..cfa9e38a6316 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,26 +1,27 @@ -# Stubs for mock - import sys -from typing import Any, List, Optional, Sequence, Text, Tuple, Type, TypeVar, Union +from typing import Any, Callable, Generic, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload +_F = TypeVar("_F", bound=Callable[..., Any]) _T = TypeVar("_T") +_TT = TypeVar("_TT", bound=Type[Any]) +_R = TypeVar("_R") __all__ = [ - 'Mock', - 'MagicMock', - 'patch', - 'sentinel', - 'DEFAULT', - 'ANY', - 'call', - 'create_autospec', - 'AsyncMock', - 'FILTER_DIR', - 'NonCallableMock', - 'NonCallableMagicMock', - 'mock_open', - 'PropertyMock', - 'seal', + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", ] __version__: str @@ -40,21 +41,24 @@ sentinel: Any DEFAULT: Any class _Call(Tuple[Any, ...]): - def __new__(cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> Any: ... + def __new__( + cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> Any: ... name: Any parent: Any from_kall: Any - def __init__(self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> None: ... + def __init__( + self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> None: ... def __eq__(self, other: Any) -> bool: ... __ne__: Any - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: Any) -> Any: ... def count(self, *args: Any, **kwargs: Any) -> Any: ... def index(self, *args: Any, **kwargs: Any) -> Any: ... def call_list(self) -> Any: ... -call: Any - +call: _Call class _CallList(List[_Call]): def __contains__(self, value: Any) -> bool: ... @@ -68,57 +72,49 @@ class _MockIter: class Base: def __init__(self, *args: Any, **kwargs: Any) -> None: ... - class NonCallableMock(Base, Any): # type: ignore - def __new__(cls, *args, **kw) -> NonCallableMock: ... - def __init__(self, - spec: Union[List[str], object, Type[object], None] = ..., - wraps: Optional[Any] = ..., - name: Optional[str] = ..., - spec_set: Union[List[str], object, Type[object], None] = ..., - parent: Optional[NonCallableMock] = ..., - _spec_state: Optional[Any] = ..., - _new_name: str = ..., - _new_parent: Optional[NonCallableMock] = ..., - _spec_as_instance: bool = ..., - _eat_self: Optional[bool] = ..., - unsafe: bool = ..., **kwargs) -> None: ... + def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + def __init__( + self, + spec: Union[List[str], object, Type[object], None] = ..., + wraps: Optional[Any] = ..., + name: Optional[str] = ..., + spec_set: Union[List[str], object, Type[object], None] = ..., + parent: Optional[NonCallableMock] = ..., + _spec_state: Optional[Any] = ..., + _new_name: str = ..., + _new_parent: Optional[NonCallableMock] = ..., + _spec_as_instance: bool = ..., + _eat_self: Optional[bool] = ..., + unsafe: bool = ..., + **kwargs: Any, + ) -> None: ... def __getattr__(self, name: str) -> Any: ... if sys.version_info >= (3, 8): def _calls_repr(self, prefix: str = ...) -> str: ... - def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... 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): 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: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... - if sys.version_info >= (3, 8): def assert_called(self) -> None: ... def assert_called_once(self) -> None: ... elif sys.version_info >= (3, 6): def assert_called(_mock_self) -> None: ... def assert_called_once(_mock_self) -> None: ... - - if sys.version_info >= (3, 6): - def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... - elif sys.version_info >= (3, 5): - def reset_mock(self, visited: Any = ...) -> None: ... - + def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... if sys.version_info >= (3, 7): def _extract_mock_name(self) -> str: ... def _get_call_signature_from_name(self, name: str) -> Any: ... - def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... - def _mock_add_spec(self, spec: Any, spec_set, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... def configure_mock(self, **kwargs: Any) -> None: ... return_value: Any @@ -132,40 +128,108 @@ class NonCallableMock(Base, Any): # type: ignore def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... - class CallableMixin(Base): side_effect: Any - def __init__(self, spec: Optional[Any] = ..., side_effect: Optional[Any] = ..., return_value: Any = ..., wraps: Optional[Any] = ..., name: Optional[Any] = ..., spec_set: Optional[Any] = ..., parent: Optional[Any] = ..., _spec_state: Optional[Any] = ..., _new_name: Any = ..., _new_parent: Optional[Any] = ..., **kwargs: Any) -> None: ... + def __init__( + self, + spec: Optional[Any] = ..., + side_effect: Optional[Any] = ..., + return_value: Any = ..., + wraps: Optional[Any] = ..., + name: Optional[Any] = ..., + spec_set: Optional[Any] = ..., + parent: Optional[Any] = ..., + _spec_state: Optional[Any] = ..., + _new_name: Any = ..., + _new_parent: Optional[Any] = ..., + **kwargs: Any, + ) -> None: ... def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... class Mock(CallableMixin, NonCallableMock): ... -class _patch: +class _patch(Generic[_T]): attribute_name: Any - getter: Any - attribute: Any - new: Any + getter: Callable[[], Any] + attribute: str + new: _T new_callable: Any spec: Any create: bool has_local: Any spec_set: Any autospec: Any - kwargs: Any + kwargs: Mapping[str, Any] additional_patchers: Any - def __init__(self, getter: Any, attribute: Any, new: Any, spec: Any, create: Any, spec_set: Any, autospec: Any, new_callable: Any, kwargs: Any) -> None: ... - def copy(self) -> Any: ... - def __call__(self, func: Any) -> Any: ... - def decorate_class(self, klass: Any) -> Any: ... - def decorate_callable(self, func: Any) -> Any: ... - def get_original(self) -> Any: ... + if sys.version_info >= (3, 8): + @overload + def __init__( + self: _patch[Union[MagicMock, AsyncMock]], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + # This overload also covers the case, where new==DEFAULT. In this case, self is _patch[Any]. + # Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + else: + @overload + def __init__( + self: _patch[MagicMock], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + def copy(self) -> _patch[_T]: ... + def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + def decorate_class(self, klass: _TT) -> _TT: ... + def decorate_callable(self, func: _F) -> _F: ... + def get_original(self) -> Tuple[Any, bool]: ... target: Any temp_original: Any - is_local: Any - def __enter__(self) -> Any: ... - def __exit__(self, *exc_info: Any) -> Any: ... - def start(self) -> Any: ... - def stop(self) -> Any: ... + is_local: bool + def __enter__(self) -> _T: ... + def __exit__(self, *exc_info: Any) -> None: ... + def start(self) -> _T: ... + def stop(self) -> None: ... class _patch_dict: in_dict: Any @@ -182,9 +246,123 @@ class _patch_dict: class _patcher: TEST_PREFIX: str dict: Type[_patch_dict] - def __call__(self, target: Any, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... - def object(self, target: Any, attribute: Text, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... - def multiple(self, target: Any, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + if sys.version_info >= (3, 8): + @overload + def __call__( # type: ignore + self, + target: Any, + *, + 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. + @overload + def __call__( + 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]: ... + else: + @overload + def __call__( # type: ignore + self, + target: Any, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def __call__( + 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]: ... + if sys.version_info >= (3, 8): + @overload + def object( # type: ignore + self, + target: Any, + attribute: str, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[Union[MagicMock, AsyncMock]]: ... + @overload + def object( + 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]: ... + else: + @overload + def object( # type: ignore + self, + target: Any, + attribute: str, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def object( + 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]: ... + def multiple( + self, + target: Any, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: _T, + ) -> _patch[_T]: ... def stopall(self) -> None: ... patch: _patcher @@ -199,7 +377,23 @@ class MagicMock(MagicMixin, Mock): def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... if sys.version_info >= (3, 8): - AsyncMock = Any + class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + await_count: int + await_args: Optional[_Call] + await_args_list: _CallList + class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... class MagicProxy: name: Any @@ -215,7 +409,9 @@ class _ANY: ANY: Any -def create_autospec(spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any) -> Any: ... +def create_autospec( + spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any +) -> Any: ... class _SpecState: spec: Any @@ -224,7 +420,15 @@ class _SpecState: parent: Any instance: Any name: Any - def __init__(self, spec: Any, spec_set: Any = ..., parent: Optional[Any] = ..., name: Optional[Any] = ..., ids: Optional[Any] = ..., instance: Any = ...) -> None: ... + def __init__( + self, + spec: Any, + spec_set: Any = ..., + parent: Optional[Any] = ..., + name: Optional[Any] = ..., + ids: Optional[Any] = ..., + instance: Any = ..., + ) -> None: ... def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index b6ba1c48bac9..8c7ff78d6cdf 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -1,19 +1,14 @@ -from typing import Any, Callable, List, Optional, TextIO, Tuple, Type, TypeVar, Union -from types import TracebackType import unittest.case +from types import TracebackType +from typing import Any, Callable, List, Optional, TextIO, Tuple, Type, TypeVar, Union - -_SysExcInfoType = Union[ - Tuple[Type[BaseException], BaseException, TracebackType], - Tuple[None, None, None], -] +_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None]] _F = TypeVar("_F", bound=Callable[..., Any]) # undocumented def failfast(method: _F) -> _F: ... - class TestResult: errors: List[Tuple[unittest.case.TestCase, str]] failures: List[Tuple[unittest.case.TestCase, str]] @@ -25,9 +20,9 @@ class TestResult: buffer: bool failfast: bool tb_locals: bool - def __init__(self, stream: Optional[TextIO] = ..., - descriptions: Optional[bool] = ..., - verbosity: Optional[int] = ...) -> None: ... + def __init__( + self, stream: Optional[TextIO] = ..., descriptions: Optional[bool] = ..., verbosity: Optional[int] = ... + ) -> None: ... def printErrors(self) -> None: ... def wasSuccessful(self) -> bool: ... def stop(self) -> None: ... @@ -39,8 +34,8 @@ class TestResult: def addFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... def addSuccess(self, test: unittest.case.TestCase) -> None: ... def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ... - def addExpectedFailure(self, test: unittest.case.TestCase, - err: _SysExcInfoType) -> None: ... + def addExpectedFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... - def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, - err: Optional[_SysExcInfoType]) -> None: ... + def addSubTest( + self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: Optional[_SysExcInfoType] + ) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index 21423fa998f8..adb5fc50442a 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -1,12 +1,10 @@ -from typing import Callable, Optional, TextIO, Tuple, Type, Union import unittest.case import unittest.result import unittest.suite - +from typing import Callable, Optional, TextIO, Tuple, Type, Union _ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] - class TextTestResult(unittest.result.TestResult): descriptions: bool # undocumented dots: bool # undocumented @@ -14,13 +12,11 @@ class TextTestResult(unittest.result.TestResult): separator2: str showall: bool # undocumented stream: TextIO # undocumented - def __init__(self, stream: TextIO, descriptions: bool, - verbosity: int) -> None: ... + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... def getDescription(self, test: unittest.case.TestCase) -> str: ... def printErrors(self) -> None: ... def printErrorList(self, flavour: str, errors: Tuple[unittest.case.TestCase, str]) -> None: ... - class TextTestRunner(object): resultclass: _ResultClassType def __init__( diff --git a/mypy/typeshed/stdlib/unittest/signals.pyi b/mypy/typeshed/stdlib/unittest/signals.pyi index b925d45c3d07..5a0a1d6220fb 100644 --- a/mypy/typeshed/stdlib/unittest/signals.pyi +++ b/mypy/typeshed/stdlib/unittest/signals.pyi @@ -1,9 +1,7 @@ -from typing import Any, Callable, overload, TypeVar import unittest.result +from typing import Any, Callable, TypeVar, overload - -_F = TypeVar('_F', bound=Callable[..., Any]) - +_F = TypeVar("_F", bound=Callable[..., Any]) def installHandler() -> None: ... def registerResult(result: unittest.result.TestResult) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi index b31804e20a95..62869d2305d6 100644 --- a/mypy/typeshed/stdlib/unittest/suite.pyi +++ b/mypy/typeshed/stdlib/unittest/suite.pyi @@ -1,11 +1,9 @@ -from typing import Iterable, Iterator, List, Union import unittest.case import unittest.result - +from typing import Iterable, Iterator, List, Union _TestType = Union[unittest.case.TestCase, TestSuite] - class BaseTestSuite(Iterable[_TestType]): _tests: List[unittest.case.TestCase] _removed_tests: int @@ -18,7 +16,5 @@ class BaseTestSuite(Iterable[_TestType]): def countTestCases(self) -> int: ... def __iter__(self) -> Iterator[_TestType]: ... - class TestSuite(BaseTestSuite): - def run(self, result: unittest.result.TestResult, - debug: bool = ...) -> unittest.result.TestResult: ... + def run(self, result: unittest.result.TestResult, debug: bool = ...) -> unittest.result.TestResult: ... diff --git a/mypy/typeshed/stdlib/unittest/util.pyi b/mypy/typeshed/stdlib/unittest/util.pyi index 9b56f8bbfa7d..8b0e8ad28adc 100644 --- a/mypy/typeshed/stdlib/unittest/util.pyi +++ b/mypy/typeshed/stdlib/unittest/util.pyi @@ -1,7 +1,6 @@ -# undocumented from typing import Any, List, Sequence, Tuple, TypeVar -_T = TypeVar('_T') +_T = TypeVar("_T") _Mismatch = Tuple[_T, _T, int] _MAX_LENGTH: int diff --git a/mypy/typeshed/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi index 16ceae8fc838..926f32d03598 100644 --- a/mypy/typeshed/stdlib/urllib/error.pyi +++ b/mypy/typeshed/stdlib/urllib/error.pyi @@ -1,11 +1,13 @@ -from typing import Dict, Union +from typing import IO, Mapping, Optional, Union from urllib.response import addinfourl # Stubs for urllib.error class URLError(IOError): reason: Union[str, BaseException] + class HTTPError(URLError, addinfourl): code: int - def __init__(self, url, code, msg, hdrs, fp) -> None: ... + def __init__(self, url: str, code: int, msg: str, hdrs: Mapping[str, str], fp: Optional[IO[bytes]]) -> None: ... + class ContentTooShortError(URLError): ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index 42dfee3248ad..d9ecfa4b6ac0 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,9 +1,10 @@ -# Stubs for urllib.parse -from typing import Any, List, Dict, Tuple, AnyStr, Generic, overload, Sequence, Mapping, Union, NamedTuple, Callable, Optional import sys +from typing import Any, AnyStr, Callable, Dict, Generic, List, Mapping, NamedTuple, Optional, Sequence, Tuple, Union, overload -_Str = Union[bytes, str] +if sys.version_info >= (3, 9): + from types import GenericAlias +_Str = Union[bytes, str] uses_relative: List[str] uses_netloc: List[str] @@ -20,32 +21,31 @@ class _ResultMixinBase(Generic[AnyStr]): class _ResultMixinStr(_ResultMixinBase[str]): def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... - class _ResultMixinBytes(_ResultMixinBase[str]): def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... - class _NetlocResultMixinBase(Generic[AnyStr]): username: Optional[AnyStr] password: Optional[AnyStr] hostname: Optional[AnyStr] port: Optional[int] + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... - class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... class _DefragResultBase(Tuple[Any, ...], Generic[AnyStr]): url: AnyStr fragment: AnyStr - class _SplitResultBase(NamedTuple): scheme: str netloc: str path: str query: str fragment: str + class _SplitResultBytesBase(NamedTuple): scheme: bytes netloc: bytes @@ -60,6 +60,7 @@ class _ParseResultBase(NamedTuple): params: str query: str fragment: str + class _ParseResultBytesBase(NamedTuple): scheme: bytes netloc: bytes @@ -70,16 +71,12 @@ class _ParseResultBytesBase(NamedTuple): # Structured result objects for string data class DefragResult(_DefragResultBase[str], _ResultMixinStr): ... - class SplitResult(_SplitResultBase, _NetlocResultMixinStr): ... - class ParseResult(_ParseResultBase, _NetlocResultMixinStr): ... # Structured result objects for bytes data class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): ... - class SplitResultBytes(_SplitResultBytesBase, _NetlocResultMixinBytes): ... - class ParseResultBytes(_ParseResultBytesBase, _NetlocResultMixinBytes): ... if sys.version_info >= (3, 8): @@ -102,35 +99,28 @@ if sys.version_info >= (3, 8): else: def parse_qs( - qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ..., + qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ... ) -> Dict[AnyStr, List[AnyStr]]: ... def parse_qsl( - qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ..., + qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ... ) -> List[Tuple[AnyStr, AnyStr]]: ... @overload def quote(string: str, safe: _Str = ..., encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... @overload def quote(string: bytes, safe: _Str = ...) -> str: ... - def quote_from_bytes(bs: bytes, safe: _Str = ...) -> str: ... - @overload def quote_plus(string: str, safe: _Str = ..., encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... @overload def quote_plus(string: bytes, safe: _Str = ...) -> str: ... - def unquote(string: str, encoding: str = ..., errors: str = ...) -> str: ... - def unquote_to_bytes(string: _Str) -> bytes: ... - def unquote_plus(string: str, encoding: str = ..., errors: str = ...) -> str: ... - @overload def urldefrag(url: str) -> DefragResult: ... @overload def urldefrag(url: Optional[bytes]) -> DefragResultBytes: ... - def urlencode( query: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]], Sequence[Tuple[Any, Any]], Sequence[Tuple[Any, Sequence[Any]]]], doseq: bool = ..., @@ -139,27 +129,24 @@ def urlencode( errors: str = ..., quote_via: Callable[[str, AnyStr, str, str], str] = ..., ) -> str: ... - def urljoin(base: AnyStr, url: Optional[AnyStr], allow_fragments: bool = ...) -> AnyStr: ... - @overload def urlparse(url: str, scheme: Optional[str] = ..., allow_fragments: bool = ...) -> ParseResult: ... @overload def urlparse(url: Optional[bytes], scheme: Optional[bytes] = ..., allow_fragments: bool = ...) -> ParseResultBytes: ... - @overload def urlsplit(url: str, scheme: Optional[str] = ..., allow_fragments: bool = ...) -> SplitResult: ... @overload def urlsplit(url: Optional[bytes], scheme: Optional[bytes] = ..., allow_fragments: bool = ...) -> SplitResultBytes: ... - @overload def urlunparse( components: Tuple[Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr]] ) -> AnyStr: ... @overload def urlunparse(components: Sequence[Optional[AnyStr]]) -> AnyStr: ... - @overload -def urlunsplit(components: Tuple[Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr]]) -> AnyStr: ... +def urlunsplit( + components: Tuple[Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr], Optional[AnyStr]] +) -> AnyStr: ... @overload def urlunsplit(components: Sequence[Optional[AnyStr]]) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 143b6a8508df..bed840c00663 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -1,30 +1,43 @@ -# Stubs for urllib.request (Python 3.4) - +import os +import ssl +from email.message import Message +from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol +from http.cookiejar import CookieJar from typing import ( - Any, Callable, ClassVar, Dict, List, IO, Mapping, Optional, Sequence, Tuple, - TypeVar, Union, overload, NoReturn, + IO, + Any, + Callable, + ClassVar, + Dict, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Sequence, + Tuple, + TypeVar, + Union, + overload, ) -from http.client import HTTPResponse, HTTPMessage, _HTTPConnectionProtocol -from http.cookiejar import CookieJar -from email.message import Message +from urllib.error import HTTPError from urllib.response import addinfourl -import ssl -import sys -import os -_T = TypeVar('_T') +_T = TypeVar("_T") _UrlopenRet = Any def urlopen( - url: Union[str, Request], data: Optional[bytes] = ..., - timeout: Optional[float] = ..., *, cafile: Optional[str] = ..., - capath: Optional[str] = ..., cadefault: bool = ..., - context: Optional[ssl.SSLContext] = ... + url: Union[str, Request], + data: Optional[bytes] = ..., + timeout: Optional[float] = ..., + *, + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ..., ) -> _UrlopenRet: ... def install_opener(opener: OpenerDirector) -> None: ... -def build_opener( - *handlers: Union[BaseHandler, Callable[[], BaseHandler]] -) -> OpenerDirector: ... +def build_opener(*handlers: Union[BaseHandler, Callable[[], BaseHandler]]) -> OpenerDirector: ... def url2pathname(pathname: str) -> str: ... def pathname2url(pathname: str) -> str: ... def getproxies() -> Dict[str, str]: ... @@ -45,11 +58,19 @@ class Request: selector: str data: Optional[bytes] headers: Dict[str, str] + unredirected_hdrs: Dict[str, str] unverifiable: bool method: Optional[str] - def __init__(self, url: str, data: Optional[bytes] = ..., - headers: Dict[str, str] = ..., origin_req_host: Optional[str] = ..., - unverifiable: bool = ..., method: Optional[str] = ...) -> None: ... + timeout: Optional[float] # Undocumented, only set after __init__() by OpenerDirector.open() + def __init__( + self, + url: str, + data: Optional[bytes] = ..., + headers: Dict[str, str] = ..., + origin_req_host: Optional[str] = ..., + unverifiable: bool = ..., + method: Optional[str] = ..., + ) -> None: ... def get_method(self) -> str: ... def add_header(self, key: str, val: str) -> None: ... def add_unredirected_header(self, key: str, val: str) -> None: ... @@ -62,87 +83,103 @@ class Request: @overload def get_header(self, header_name: str, default: _T) -> Union[str, _T]: ... def header_items(self) -> List[Tuple[str, str]]: ... + def has_proxy(self) -> bool: ... class OpenerDirector: addheaders: List[Tuple[str, str]] def add_handler(self, handler: BaseHandler) -> None: ... - def open(self, fullurl: Union[str, Request], data: Optional[bytes] = ..., - timeout: Optional[float] = ...) -> _UrlopenRet: ... + def open(self, fullurl: Union[str, Request], data: Optional[bytes] = ..., timeout: Optional[float] = ...) -> _UrlopenRet: ... def error(self, proto: str, *args: Any) -> _UrlopenRet: ... - + def close(self) -> None: ... class BaseHandler: handler_order: ClassVar[int] parent: OpenerDirector def add_parent(self, parent: OpenerDirector) -> None: ... def close(self) -> None: ... - def http_error_nnn(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> _UrlopenRet: ... + def http_error_nnn(self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str]) -> _UrlopenRet: ... -class HTTPDefaultErrorHandler(BaseHandler): ... +class HTTPDefaultErrorHandler(BaseHandler): + def http_error_default( + self, req: Request, fp: IO[bytes], code: int, msg: str, hdrs: Mapping[str, str] + ) -> HTTPError: ... # undocumented class HTTPRedirectHandler(BaseHandler): - def redirect_request(self, req: Request, fp: IO[str], code: int, msg: str, - headers: Mapping[str, str], - newurl: str) -> Optional[Request]: ... - def http_error_301(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... - def http_error_302(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... - def http_error_303(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... - def http_error_307(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + max_redirections: ClassVar[int] # undocumented + max_repeats: ClassVar[int] # undocumented + inf_msg: ClassVar[str] # undocumented + def redirect_request( + self, req: Request, fp: IO[str], code: int, msg: str, headers: Mapping[str, str], newurl: str + ) -> Optional[Request]: ... + def http_error_301( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... + def http_error_302( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... + def http_error_303( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... + def http_error_307( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... class HTTPCookieProcessor(BaseHandler): cookiejar: CookieJar def __init__(self, cookiejar: Optional[CookieJar] = ...) -> None: ... + def http_request(self, request: Request) -> Request: ... # undocumented + def http_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def https_request(self, request: Request) -> Request: ... # undocumented + def https_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented class ProxyHandler(BaseHandler): def __init__(self, proxies: Optional[Dict[str, str]] = ...) -> None: ... + def proxy_open(self, req: Request, proxy: str, type: str) -> Optional[_UrlopenRet]: ... # undocumented # TODO add a method for every (common) proxy protocol class HTTPPasswordMgr: - def add_password(self, realm: str, uri: Union[str, Sequence[str]], - user: str, passwd: str) -> None: ... + def add_password(self, realm: str, uri: Union[str, Sequence[str]], user: str, passwd: str) -> None: ... def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ... + def is_suburi(self, base: str, test: str) -> bool: ... # undocumented + def reduce_uri(self, uri: str, default_port: bool = ...) -> str: ... # undocumented class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): - def add_password(self, realm: Optional[str], uri: Union[str, Sequence[str]], - user: str, passwd: str) -> None: ... + def add_password(self, realm: Optional[str], uri: Union[str, Sequence[str]], user: str, passwd: str) -> None: ... def find_user_password(self, realm: Optional[str], authuri: str) -> Tuple[Optional[str], Optional[str]]: ... class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm): def add_password( - self, - realm: Optional[str], - uri: Union[str, Sequence[str]], - user: str, - passwd: str, - is_authenticated: bool = ..., + self, realm: Optional[str], uri: Union[str, Sequence[str]], user: str, passwd: str, is_authenticated: bool = ... ) -> None: ... def update_authenticated(self, uri: Union[str, Sequence[str]], is_authenticated: bool = ...) -> None: ... def is_authenticated(self, authuri: str) -> bool: ... class AbstractBasicAuthHandler: - def __init__(self, - password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... - def http_error_auth_reqed(self, authreq: str, host: str, req: Request, - headers: Mapping[str, str]) -> None: ... + rx: ClassVar[Pattern[str]] # undocumented + def __init__(self, password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def http_error_auth_reqed(self, authreq: str, host: str, req: Request, headers: Mapping[str, str]) -> None: ... + def http_request(self, req: Request) -> Request: ... # undocumented + def http_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def https_request(self, req: Request) -> Request: ... # undocumented + def https_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def retry_http_basic_auth(self, host: str, req: Request, realm: str) -> Optional[_UrlopenRet]: ... # undocumented class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + auth_header: ClassVar[str] # undocumented + def http_error_401( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): - def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + auth_header: ClassVar[str] + def http_error_407( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... class AbstractDigestAuthHandler: def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... def reset_retry_count(self) -> None: ... - def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, - headers: Mapping[str, str]) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: Mapping[str, str]) -> None: ... def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[_UrlopenRet]: ... def get_cnonce(self, nonce: str) -> str: ... def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... @@ -150,73 +187,157 @@ class AbstractDigestAuthHandler: def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + auth_header: ClassVar[str] # undocumented + def http_error_401( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, - headers: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + auth_header: ClassVar[str] # undocumented + def http_error_407( + self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + ) -> Optional[_UrlopenRet]: ... class AbstractHTTPHandler(BaseHandler): # undocumented def __init__(self, debuglevel: int = ...) -> None: ... def set_http_debuglevel(self, level: int) -> None: ... def do_request_(self, request: Request) -> Request: ... - def do_open(self, - http_class: _HTTPConnectionProtocol, - req: Request, - **http_conn_args: Any) -> HTTPResponse: ... + def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: ... class HTTPHandler(AbstractHTTPHandler): def http_open(self, req: Request) -> HTTPResponse: ... def http_request(self, request: Request) -> Request: ... # undocumented class HTTPSHandler(AbstractHTTPHandler): - def __init__(self, debuglevel: int = ..., - context: Optional[ssl.SSLContext] = ..., - check_hostname: Optional[bool] = ...) -> None: ... + def __init__( + self, debuglevel: int = ..., context: Optional[ssl.SSLContext] = ..., check_hostname: Optional[bool] = ... + ) -> None: ... def https_open(self, req: Request) -> HTTPResponse: ... def https_request(self, request: Request) -> Request: ... # undocumented class FileHandler(BaseHandler): + names: ClassVar[Optional[Tuple[str, ...]]] # undocumented def file_open(self, req: Request) -> addinfourl: ... + def get_names(self) -> Tuple[str, ...]: ... # undocumented + def open_local_file(self, req: Request) -> addinfourl: ... # undocumented class DataHandler(BaseHandler): def data_open(self, req: Request) -> addinfourl: ... +class ftpwrapper: # undocumented + def __init__( + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: Optional[float] = ..., persistent: bool = ... + ) -> None: ... + class FTPHandler(BaseHandler): def ftp_open(self, req: Request) -> addinfourl: ... + def connect_ftp( + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float + ) -> ftpwrapper: ... # undocumented class CacheFTPHandler(FTPHandler): def setTimeout(self, t: float) -> None: ... def setMaxConns(self, m: int) -> None: ... + def check_cache(self) -> None: ... # undocumented + def clear_cache(self) -> None: ... # undocumented + def connect_ftp( + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float + ) -> ftpwrapper: ... # undocumented class UnknownHandler(BaseHandler): def unknown_open(self, req: Request) -> NoReturn: ... class HTTPErrorProcessor(BaseHandler): - def http_response(self, request, response) -> _UrlopenRet: ... - def https_response(self, request, response) -> _UrlopenRet: ... - -if sys.version_info >= (3, 6): - def urlretrieve(url: str, filename: Optional[Union[str, os.PathLike[Any]]] = ..., - reporthook: Optional[Callable[[int, int, int], None]] = ..., - data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... -else: - def urlretrieve(url: str, filename: Optional[str] = ..., - reporthook: Optional[Callable[[int, int, int], None]] = ..., - data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... + def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... + def https_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... + +def urlretrieve( + url: str, + filename: Optional[Union[str, os.PathLike[Any]]] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ..., +) -> Tuple[str, HTTPMessage]: ... def urlcleanup() -> None: ... class URLopener: version: ClassVar[str] - def __init__(self, proxies: Optional[Dict[str, str]] = ..., - **x509: str) -> None: ... + def __init__(self, proxies: Optional[Dict[str, str]] = ..., **x509: str) -> None: ... def open(self, fullurl: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... - def open_unknown(self, fullurl: str, - data: Optional[bytes] = ...) -> _UrlopenRet: ... - def retrieve(self, url: str, filename: Optional[str] = ..., - reporthook: Optional[Callable[[int, int, int], None]] = ..., - data: Optional[bytes] = ...) -> Tuple[str, Optional[Message]]: ... + def open_unknown(self, fullurl: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... + def retrieve( + self, + url: str, + filename: Optional[str] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ..., + ) -> Tuple[str, Optional[Message]]: ... + def addheader(self, *args: Tuple[str, str]) -> None: ... # undocumented + def cleanup(self) -> None: ... # undocumented + def close(self) -> None: ... # undocumented + def http_error( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + ) -> _UrlopenRet: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str] + ) -> _UrlopenRet: ... # undocumented + def open_data(self, url: str, data: Optional[bytes] = ...) -> addinfourl: ... # undocumented + def open_file(self, url: str) -> addinfourl: ... # undocumented + def open_ftp(self, url: str) -> addinfourl: ... # undocumented + def open_http(self, url: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... # undocumented + def open_https(self, url: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... # undocumented + def open_local_file(self, url: str) -> addinfourl: ... # undocumented + def open_unknown_proxy(self, proxy: str, fullurl: str, data: Optional[bytes] = ...) -> None: ... # undocumented class FancyURLopener(URLopener): def prompt_user_passwd(self, host: str, realm: str) -> Tuple[str, str]: ... + def get_user_passwd(self, host: str, realm: str, clear_cache: int = ...) -> Tuple[str, str]: ... # undocumented + def http_error_301( + self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented + def http_error_302( + self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented + def http_error_303( + self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented + def http_error_307( + self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented + def http_error_401( + self, + url: str, + fp: IO[str], + errcode: int, + errmsg: str, + headers: Mapping[str, str], + data: Optional[bytes] = ..., + retry: bool = ..., + ) -> Optional[_UrlopenRet]: ... # undocumented + def http_error_407( + self, + url: str, + fp: IO[str], + errcode: int, + errmsg: str, + headers: Mapping[str, str], + data: Optional[bytes] = ..., + retry: bool = ..., + ) -> Optional[_UrlopenRet]: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str] + ) -> addinfourl: ... # undocumented + def redirect_internal( + self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] + ) -> Optional[_UrlopenRet]: ... # undocumented + def retry_http_basic_auth( + self, url: str, realm: str, data: Optional[bytes] = ... + ) -> Optional[_UrlopenRet]: ... # undocumented + def retry_https_basic_auth( + self, url: str, realm: str, data: Optional[bytes] = ... + ) -> Optional[_UrlopenRet]: ... # undocumented + def retry_proxy_http_basic_auth( + self, url: str, realm: str, data: Optional[bytes] = ... + ) -> Optional[_UrlopenRet]: ... # undocumented + def retry_proxy_https_basic_auth( + self, url: str, realm: str, data: Optional[bytes] = ... + ) -> Optional[_UrlopenRet]: ... # undocumented diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index 970fd743770c..c8f9d75d2f14 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -1,8 +1,6 @@ -# private module, we only expose what's needed - -from typing import Any, BinaryIO, Callable, IO, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar from email.message import Message from types import TracebackType +from typing import IO, Any, BinaryIO, Callable, Iterable, List, Optional, Tuple, Type, TypeVar _AIUT = TypeVar("_AIUT", bound=addbase) @@ -10,7 +8,9 @@ class addbase(BinaryIO): fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... def __enter__(self: _AIUT) -> _AIUT: ... - def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: ... + def __exit__( + self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... def __iter__(self: _AIUT) -> _AIUT: ... def __next__(self) -> bytes: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/robotparser.pyi b/mypy/typeshed/stdlib/urllib/robotparser.pyi index fcf46744f159..ad96ca12bfc4 100644 --- a/mypy/typeshed/stdlib/urllib/robotparser.pyi +++ b/mypy/typeshed/stdlib/urllib/robotparser.pyi @@ -1,7 +1,5 @@ -# Stubs for urllib.robotparser (Python 3.4) - -from typing import Iterable, List, NamedTuple, Optional import sys +from typing import Iterable, List, NamedTuple, Optional class _RequestRate(NamedTuple): requests: int @@ -15,8 +13,7 @@ class RobotFileParser: def can_fetch(self, user_agent: str, url: str) -> bool: ... def mtime(self) -> int: ... def modified(self) -> None: ... - if sys.version_info >= (3, 6): - def crawl_delay(self, useragent: str) -> Optional[str]: ... - def request_rate(self, useragent: str) -> Optional[_RequestRate]: ... + def crawl_delay(self, useragent: str) -> Optional[str]: ... + def request_rate(self, useragent: str) -> Optional[_RequestRate]: ... if sys.version_info >= (3, 8): def site_maps(self) -> Optional[List[str]]: ... diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index 3fbbab40ad82..2bb2c2a1c90e 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,13 +1,16 @@ -# Stubs for uu (Python 2 and 3) import sys -from typing import BinaryIO, Union, Optional, Text +from typing import BinaryIO, Optional, Text, Union _File = Union[Text, BinaryIO] class Error(Exception): ... if sys.version_info >= (3, 7): - def encode(in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ..., *, backtick: bool = ...) -> None: ... + def encode( + in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ..., *, backtick: bool = ... + ) -> None: ... + else: 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/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 09f799bcf10b..68b235162210 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,7 +1,5 @@ -# Stubs for uuid - import sys -from typing import Tuple, Optional, Any, Text +from typing import Any, Optional, Text, Tuple # Because UUID has properties called int and bytes we need to rename these temporarily. _Int = int @@ -15,26 +13,31 @@ if sys.version_info >= (3, 7): unsafe: int unknown: None - class UUID: if sys.version_info >= (3, 7): - def __init__(self, hex: Optional[Text] = ..., - bytes: Optional[_Bytes] = ..., - bytes_le: Optional[_Bytes] = ..., - fields: Optional[_FieldsType] = ..., - int: Optional[_Int] = ..., - version: Optional[_Int] = ..., - *, - is_safe: SafeUUID = ...) -> None: ... + def __init__( + self, + hex: Optional[Text] = ..., + bytes: Optional[_Bytes] = ..., + bytes_le: Optional[_Bytes] = ..., + fields: Optional[_FieldsType] = ..., + int: Optional[_Int] = ..., + version: Optional[_Int] = ..., + *, + is_safe: SafeUUID = ..., + ) -> None: ... @property def is_safe(self) -> SafeUUID: ... else: - def __init__(self, hex: Optional[Text] = ..., - bytes: Optional[_Bytes] = ..., - bytes_le: Optional[_Bytes] = ..., - fields: Optional[_FieldsType] = ..., - int: Optional[_Int] = ..., - version: Optional[_Int] = ...) -> None: ... + 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 @@ -67,9 +70,7 @@ class UUID: def variant(self) -> str: ... @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: ... diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index b84d08e72795..d44d17ea9785 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import AnyPath -from typing import Optional, Sequence from types import SimpleNamespace +from typing import Optional, Sequence class EnvBuilder: system_site_packages: bool @@ -9,15 +9,29 @@ class EnvBuilder: symlinks: bool upgrade: bool with_pip: bool - if sys.version_info >= (3, 6): - prompt: Optional[str] + prompt: Optional[str] if sys.version_info >= (3, 9): - def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ..., upgrade_deps: bool = ...) -> None: ... - elif sys.version_info >= (3, 6): - def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ...) -> None: ... + def __init__( + self, + system_site_packages: bool = ..., + clear: bool = ..., + symlinks: bool = ..., + upgrade: bool = ..., + with_pip: bool = ..., + prompt: Optional[str] = ..., + upgrade_deps: bool = ..., + ) -> None: ... else: - def __init__(self, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., upgrade: bool = ..., with_pip: bool = ...) -> None: ... + def __init__( + self, + system_site_packages: bool = ..., + clear: bool = ..., + symlinks: bool = ..., + upgrade: bool = ..., + 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: ... @@ -33,10 +47,24 @@ class EnvBuilder: def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... if sys.version_info >= (3, 9): - def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ..., upgrade_deps: bool = ...) -> None: ... -elif sys.version_info >= (3, 6): - def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ..., prompt: Optional[str] = ...) -> None: ... + def create( + env_dir: AnyPath, + system_site_packages: bool = ..., + clear: bool = ..., + symlinks: bool = ..., + with_pip: bool = ..., + prompt: Optional[str] = ..., + upgrade_deps: bool = ..., + ) -> None: ... + else: - def create(env_dir: AnyPath, system_site_packages: bool = ..., clear: bool = ..., symlinks: bool = ..., with_pip: bool = ...) -> None: ... + def create( + env_dir: AnyPath, + system_site_packages: bool = ..., + clear: bool = ..., + symlinks: bool = ..., + with_pip: bool = ..., + prompt: Optional[str] = ..., + ) -> None: ... def main(args: Optional[Sequence[str]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 662e91a4c011..0e64ec574775 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,15 +1,21 @@ import sys from types import ModuleType, TracebackType -from typing import Any, List, NamedTuple, Optional, TextIO, Type, Union, overload - +from typing import Any, 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] = ... + 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 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: ... diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 99873e3d87b8..c89ba628e59e 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,9 +1,5 @@ -# Stubs for wave (Python 2 and 3) - import sys -from typing import ( - Any, NamedTuple, NoReturn, Optional, Text, BinaryIO, Union, Tuple, IO -) +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Optional, Text, Tuple, Union _File = Union[Text, IO[bytes]] @@ -72,5 +68,6 @@ class Wave_write: # Returns a Wave_read if mode is rb and Wave_write if mode is wb def open(f: _File, mode: Optional[str] = ...) -> Any: ... + if sys.version_info < (3, 9): openfp = open diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index e3ddbf27845e..9dc723388f08 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,27 +1,41 @@ import sys import types +from _weakrefset import WeakSet as WeakSet from typing import ( - TypeVar, Generic, Any, Callable, overload, Mapping, Iterator, Tuple, - Iterable, Optional, Type, MutableMapping, Union, List, Dict + Any, + Callable, + Dict, + Generic, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + Optional, + Tuple, + Type, + TypeVar, + Union, + overload, ) from _weakref import ( + CallableProxyType as CallableProxyType, + ProxyType as ProxyType, + ReferenceType as ReferenceType, getweakrefcount as getweakrefcount, getweakrefs as getweakrefs, - ref as ref, proxy as proxy, - CallableProxyType as CallableProxyType, - ProxyType as ProxyType, - ReferenceType as ReferenceType) -from _weakrefset import WeakSet as WeakSet + ref as ref, +) if sys.version_info < (3, 0): from exceptions import ReferenceError as ReferenceError -_S = TypeVar('_S') -_T = TypeVar('_T') -_KT = TypeVar('_KT') -_VT = TypeVar('_VT') +_S = TypeVar("_S") +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") ProxyTypes: Tuple[Type[Any], ...] @@ -34,8 +48,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ... - + 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: ... @@ -45,9 +58,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): 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): def keys(self) -> List[_KT]: ... def values(self) -> List[_VT]: ... @@ -65,14 +76,14 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT + def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef: ... def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): @overload - def __init__(self) -> None: ... + def __init__(self, dict: None = ...) -> None: ... @overload - def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ... - + 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: ... @@ -82,9 +93,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): 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): def keys(self) -> List[_KT]: ... def values(self) -> List[_VT]: ... @@ -102,7 +111,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): if sys.version_info >= (3, 4): class finalize: - def __init__(self, obj: _S, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __init__(self, __obj: _S, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, _: Any = ...) -> Optional[_T]: ... def detach(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... def peek(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index 977d1363083f..e29238ee07ff 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -1,12 +1,18 @@ import sys -from typing import Any, Optional, Callable, List, Text, Union, Sequence +from typing import Callable, List, Optional, Sequence, Text, Union class Error(Exception): ... if sys.version_info >= (3, 7): - def register(name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., *, preferred: bool = ...) -> None: ... + def register( + name: Text, 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 = ...) -> None: ... + 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: ... @@ -85,16 +91,15 @@ class Konqueror(BaseBrowser): class Grail(BaseBrowser): def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... -if sys.platform == 'win32': +if sys.platform == "win32": class WindowsDefault(BaseBrowser): def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... -if sys.platform == 'darwin': +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/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index d1ed6a67d499..8f25dd61a092 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,12 +1,9 @@ - -import sys - -from typing import Optional, Type, Union, Tuple, Any from types import TracebackType +from typing import Any, Optional, Tuple, Type, Union _KeyType = Union[HKEYType, int] -def CloseKey(__hkey: _KeyType): ... +def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: Optional[str], __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: Optional[str]) -> HKEYType: ... def CreateKeyEx(key: _KeyType, sub_key: Optional[str], reserved: int = ..., access: int = ...) -> HKEYType: ... @@ -25,7 +22,9 @@ def QueryValue(__key: _KeyType, __sub_key: Optional[str]) -> str: ... def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... def SaveKey(__key: _KeyType, __file_name: str) -> None: ... def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx(__key: _KeyType, __value_name: str, __reserved: Any, __type: int, __value: str) -> None: ... # reserved is ignored +def SetValueEx( + __key: _KeyType, __value_name: Optional[str], __reserved: Any, __type: int, __value: Union[str, int] +) -> None: ... # reserved is ignored def DisableReflectionKey(__key: _KeyType) -> None: ... def EnableReflectionKey(__key: _KeyType) -> None: ... def QueryReflectionKey(__key: _KeyType) -> bool: ... @@ -60,9 +59,8 @@ REG_EXPAND_SZ: int REG_LINK: int REG_MULTI_SZ: int REG_NONE: int -if sys.version_info >= (3, 6): - REG_QWORD: int - REG_QWORD_LITTLE_ENDIAN: int +REG_QWORD: int +REG_QWORD_LITTLE_ENDIAN: int REG_RESOURCE_LIST: int REG_FULL_RESOURCE_DESCRIPTOR: int REG_RESOURCE_REQUIREMENTS_LIST: int @@ -93,7 +91,8 @@ class HKEYType: def __bool__(self) -> bool: ... def __int__(self) -> int: ... def __enter__(self) -> HKEYType: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: ... - + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... def Close(self) -> None: ... def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi index 14ca50993b78..be9a8c660781 100644 --- a/mypy/typeshed/stdlib/winsound.pyi +++ b/mypy/typeshed/stdlib/winsound.pyi @@ -18,7 +18,6 @@ if sys.platform == "win32": 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 diff --git a/mypy/typeshed/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi index 3271c881a289..ff764e434169 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,17 +1,16 @@ import sys from abc import abstractmethod from types import TracebackType -from typing import Optional, Dict, MutableMapping, Type, Text, Callable, List, Tuple, IO +from typing import IO, Callable, Dict, List, MutableMapping, Optional, Text, Tuple, Type from .headers import Headers -from .types import WSGIApplication, WSGIEnvironment, StartResponse, InputStream, ErrorStream -from .util import FileWrapper, guess_scheme +from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment +from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], - Optional[BaseException], - Optional[TracebackType]] +_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]: ... @@ -34,15 +33,15 @@ class BaseHandler: 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 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: ... @@ -54,7 +53,6 @@ class BaseHandler: 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 @@ -71,7 +69,15 @@ class SimpleHandler(BaseHandler): 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 __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: ... diff --git a/mypy/typeshed/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi index 853922527b5b..c3e943200e40 100644 --- a/mypy/typeshed/stdlib/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/headers.pyi @@ -1,5 +1,5 @@ import sys -from typing import overload, Pattern, Optional, List, Tuple +from typing import List, Optional, Pattern, Tuple, overload _HeaderList = List[Tuple[str, str]] diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 50b8377e549e..66cd94fa7f7f 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -1,13 +1,13 @@ import sys -from typing import Optional, List, Type, TypeVar, overload +from typing import List, Optional, Type, TypeVar, overload from .handlers import SimpleHandler -from .types import WSGIApplication, WSGIEnvironment, StartResponse, ErrorStream +from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment if sys.version_info < (3,): from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer else: - from http.server import HTTPServer, BaseHTTPRequestHandler + from http.server import BaseHTTPRequestHandler, HTTPServer server_version: str # undocumented sys_version: str # undocumented @@ -33,8 +33,9 @@ class WSGIRequestHandler(BaseHTTPRequestHandler): 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: ... +def make_server( + host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... +) -> _S: ... diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index b03e7889ffc6..570546e6545d 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -1,7 +1,6 @@ import sys -from typing import Any, Iterable, Iterator, Optional, NoReturn, Callable - -from _typeshed.wsgi import WSGIApplication, InputStream, ErrorStream +from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication +from typing import Any, Callable, Iterable, Iterator, NoReturn, Optional class WSGIWarning(Warning): ... diff --git a/mypy/typeshed/stdlib/xdrlib.pyi b/mypy/typeshed/stdlib/xdrlib.pyi index 864aced9c03a..378504c37227 100644 --- a/mypy/typeshed/stdlib/xdrlib.pyi +++ b/mypy/typeshed/stdlib/xdrlib.pyi @@ -1,7 +1,6 @@ -# Structs for xdrlib (Python 2 and 3) from typing import Callable, List, Sequence, TypeVar -_T = TypeVar('_T') +_T = TypeVar("_T") class Error(Exception): msg: str diff --git a/mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi b/mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi index 9bb2c1e530ff..80fb73d23433 100644 --- a/mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi +++ b/mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi @@ -16,5 +16,4 @@ class NodeFilter: SHOW_DOCUMENT_TYPE: int SHOW_DOCUMENT_FRAGMENT: int SHOW_NOTATION: int - def acceptNode(self, node) -> int: ... diff --git a/mypy/typeshed/stdlib/xml/dom/__init__.pyi b/mypy/typeshed/stdlib/xml/dom/__init__.pyi index 91548cd947e8..c5766c326c3e 100644 --- a/mypy/typeshed/stdlib/xml/dom/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/dom/__init__.pyi @@ -1,3 +1,7 @@ +from typing import Any + +from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation + class Node: ELEMENT_NODE: int ATTRIBUTE_NODE: int @@ -12,7 +16,6 @@ class Node: DOCUMENT_FRAGMENT_NODE: int NOTATION_NODE: int - # ExceptionCode INDEX_SIZE_ERR: int DOMSTRING_SIZE_ERR: int @@ -31,11 +34,9 @@ NAMESPACE_ERR: int INVALID_ACCESS_ERR: int VALIDATION_ERR: int - class DOMException(Exception): code: int - - def __init__(self, *args, **kw) -> None: ... + def __init__(self, *args: Any, **kw: Any) -> None: ... def _get_code(self) -> int: ... class IndexSizeErr(DOMException): ... diff --git a/mypy/typeshed/stdlib/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/xml/dom/domreg.pyi new file mode 100644 index 000000000000..6f479b097b65 --- /dev/null +++ b/mypy/typeshed/stdlib/xml/dom/domreg.pyi @@ -0,0 +1,10 @@ +from _typeshed.xml import DOMImplementation +from typing import Any, 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/xml/dom/expatbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 964e6fa3f426..7a6eb192b384 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,3 +1,6 @@ -from typing import Any +from typing import Any, Optional, Text, Union +from xml.sax.xmlreader import XMLReader +def parse(file: str, parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... +def parseString(string: Union[bytes, Text], parser: Optional[XMLReader] = ...): ... def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi new file mode 100644 index 000000000000..964e6fa3f426 --- /dev/null +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index eabfb54daf39..4aa0173fa82f 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -1,5 +1,5 @@ import sys -from typing import Union, Optional, Callable +from typing import Callable, Optional, Union from xml.etree.ElementTree import Element XINCLUDE: str @@ -14,6 +14,12 @@ def default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[ # same signature as default_loader. But default_loader has a keyword argument # Which can't be represented using Callable... if sys.version_info >= (3, 9): - def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ..., base_url: Optional[str] = ..., max_depth: Optional[int] = ...) -> None: ... + def include( + elem: Element, + loader: Optional[Callable[..., Union[str, Element]]] = ..., + base_url: Optional[str] = ..., + max_depth: Optional[int] = ..., + ) -> None: ... + else: def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index 1250f0da42dd..0f269b4e88d3 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -1,6 +1,4 @@ -# Stubs for xml.etree.ElementPath (Python 3.4) - -from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional +from typing import Callable, Dict, Generator, List, Optional, Pattern, Tuple, TypeVar, Union from xml.etree.ElementTree import Element xpath_tokenizer_re: Pattern[str] @@ -25,9 +23,11 @@ class _SelectorContext: root: Element def __init__(self, root: Element) -> None: ... -_T = TypeVar('_T') +_T = TypeVar("_T") def iterfind(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... 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]: ... +def findtext( + elem: Element, path: str, default: Optional[_T] = ..., namespaces: Optional[Dict[str, str]] = ... +) -> Union[_T, str]: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 1dfaf45d8980..b2e2edbe5536 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -1,9 +1,11 @@ +import sys +from _typeshed import AnyPath, FileDescriptor, SupportsWrite from typing import ( + IO, Any, Callable, Dict, Generator, - IO, ItemsView, Iterable, Iterator, @@ -18,8 +20,6 @@ from typing import ( Union, overload, ) -from _typeshed import AnyPath, FileDescriptor, SupportsWrite -import sys from typing_extensions import Literal VERSION: str @@ -30,7 +30,7 @@ class ParseError(SyntaxError): def iselement(element: object) -> bool: ... -_T = TypeVar('_T') +_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 @@ -93,36 +93,50 @@ class Element(MutableSequence[Element]): 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 __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 copy(self) -> Element: ... 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_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]: ... + 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 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 getchildren(self) -> List[Element]: ... - def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... 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]] = ...) -> List[Element]: ... + def iterfind( + self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... + ) -> List[Element]: ... 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 __bool__(self) -> bool: ... def __delitem__(self, i: Union[int, slice]) -> None: ... @overload def __getitem__(self, i: int) -> Element: ... @@ -133,9 +147,16 @@ class Element(MutableSequence[Element]): def __setitem__(self, i: int, o: Element) -> None: ... @overload 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 SubElement(parent: Element, tag: _str_argument_type, attrib: Dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type) -> 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: ... @@ -150,18 +171,48 @@ class ElementTree: 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]: ... + 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]: ... @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_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]] = ...) -> List[Element]: ... + 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]] = ... + ) -> List[Element]: ... 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: ... + 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( + 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: ... @@ -197,7 +248,6 @@ if sys.version_info >= (3, 8): default_namespace: Optional[_str_argument_type] = ..., short_empty_elements: bool = ..., ) -> Any: ... - @overload def tostringlist( element: Element, @@ -231,24 +281,37 @@ if sys.version_info >= (3, 8): elif sys.version_info >= (3,): @overload - def tostring(element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> bytes: ... + def tostring( + element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ... + ) -> bytes: ... @overload - def tostring(element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> str: ... + def tostring( + element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ... + ) -> str: ... @overload def tostring(element: Element, encoding: str, method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> Any: ... - @overload - def tostringlist(element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[bytes]: ... + def tostringlist( + element: Element, encoding: None = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ... + ) -> List[bytes]: ... @overload - def tostringlist(element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[str]: ... + def tostringlist( + element: Element, encoding: Literal["unicode"], method: Optional[str] = ..., *, short_empty_elements: bool = ... + ) -> List[str]: ... @overload - def tostringlist(element: Element, encoding: str, method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[Any]: ... + def tostringlist( + 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: ... 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 iterparse( + source: _file_or_filename, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ... +) -> Iterator[Tuple[str, Any]]: ... if sys.version_info >= (3, 4): class XMLPullParser: @@ -298,17 +361,16 @@ if sys.version_info >= (3, 8): exclude_tags: Optional[Iterable[str]] = ..., ) -> None: ... - class XMLParser: parser: Any - target: TreeBuilder + target: Any # TODO-what is entity used for??? entity: Any version: str if sys.version_info >= (3, 8): - def __init__(self, *, target: Optional[TreeBuilder] = ..., encoding: Optional[str] = ...) -> None: ... + def __init__(self, *, target: Any = ..., encoding: Optional[str] = ...) -> None: ... else: - def __init__(self, html: int = ..., target: Optional[TreeBuilder] = ..., encoding: Optional[str] = ...) -> None: ... + def __init__(self, html: int = ..., target: Any = ..., encoding: Optional[str] = ...) -> None: ... def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... - def close(self) -> Element: ... + def close(self) -> Any: ... def feed(self, __data: _parser_input_type) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi index c384968d08ff..c41e2bee0eb1 100644 --- a/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi @@ -1,3 +1 @@ -# Stubs for xml.etree.cElementTree (Python 3.4) - from xml.etree.ElementTree import * # noqa: F403 diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index faabf4108285..a95fde106535 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,9 +1,7 @@ -from typing import Any, Iterable, List, NoReturn, Optional, Text, Union, IO - import sys -import xml.sax -from xml.sax.xmlreader import InputSource, Locator +from typing import IO, Any, Iterable, 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: ... @@ -25,14 +23,11 @@ class SAXReaderNotAvailable(SAXNotSupportedException): ... default_parser_list: List[str] if sys.version_info >= (3, 8): - def make_parser(parser_list: Iterable[str] = ...) -> xml.sax.xmlreader.XMLReader: ... -else: - def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... + def make_parser(parser_list: Iterable[str] = ...) -> XMLReader: ... -def parse(source: Union[str, IO[str], IO[bytes]], handler: xml.sax.handler.ContentHandler, - errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... - -def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, - errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... +else: + def make_parser(parser_list: List[str] = ...) -> XMLReader: ... -def _create_parser(parser_name: str) -> xml.sax.xmlreader.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/xml/sax/saxutils.pyi b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi index d4c9d442b133..8ae2b80d2a26 100644 --- a/mypy/typeshed/stdlib/xml/sax/saxutils.pyi +++ b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi @@ -1,11 +1,9 @@ import sys -from typing import Mapping, Text, Optional, Union, TextIO -from io import TextIOBase, RawIOBase -from codecs import StreamWriter, StreamReaderWriter from _typeshed import SupportsWrite - -from xml.sax import handler -from xml.sax import xmlreader +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: ... @@ -13,9 +11,18 @@ def quoteattr(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... 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: ... + 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: Text = ..., + ) -> None: ... def startDocument(self): ... def endDocument(self): ... def startPrefixMapping(self, prefix, uri): ... diff --git a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi index d22db4b45fa1..de0d1169a470 100644 --- a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi @@ -1,5 +1,4 @@ - -from typing import Tuple, Mapping, Optional +from typing import Mapping, Optional, Tuple class XMLReader: def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 3b392e471001..7bea294bbfab 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -1,17 +1,17 @@ -import io -import sys -import time import gzip import http.client - +import sys +import time +from _typeshed import SupportsRead, SupportsWrite +from datetime import datetime +from io import BytesIO +from types import TracebackType from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Protocol, Tuple, Type, Union, overload from typing_extensions import Literal -from types import TracebackType -from datetime import datetime -from _typeshed import SupportsRead, SupportsWrite class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... + _DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] _Marshallable = Union[None, bool, int, float, str, bytes, tuple, list, dict, datetime, DateTime, Binary] _XMLDate = Union[int, datetime, Tuple[int, ...], time.struct_time] @@ -41,7 +41,6 @@ class ProtocolError(Error): errcode: int errmsg: str headers: Dict[str, str] - def __init__(self, url: str, errcode: int, errmsg: str, headers: Dict[str, str]) -> None: ... class ResponseError(Error): ... @@ -50,10 +49,8 @@ class Fault(Error): faultCode: str faultString: str - def __init__(self, faultCode: str, faultString: str, **extra: Any) -> None: ... - boolean = bool Boolean = bool @@ -63,8 +60,7 @@ def _strftime(value: _XMLDate) -> str: ... # undocumented class DateTime: value: str # undocumented - - def __init__(self, value: Union[int, str, datetime, time.struct_time, Tuple[int, ...]] = ...): ... + def __init__(self, value: Union[int, str, datetime, time.struct_time, Tuple[int, ...]] = ...) -> None: ... def __lt__(self, other: _DateTimeComparable) -> bool: ... def __le__(self, other: _DateTimeComparable) -> bool: ... def __gt__(self, other: _DateTimeComparable) -> bool: ... @@ -81,7 +77,6 @@ def _datetime_type(data: str) -> datetime: ... # undocumented class Binary: data: bytes - def __init__(self, data: Optional[bytes] = ...) -> None: ... def decode(self, data: bytes) -> None: ... def encode(self, out: SupportsWrite[str]) -> None: ... @@ -91,20 +86,20 @@ def _binary(data: bytes) -> Binary: ... # undocumented WRAPPERS: Tuple[Type[DateTime], Type[Binary]] # undocumented class ExpatParser: # undocumented - def __init__(self, target: Unmarshaller) -> None: ... def feed(self, data: Union[str, bytes]) -> None: ... def close(self) -> None: ... class Marshaller: - dispatch: Dict[Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None]] = ... # TODO: Replace 'Any' with some kind of binding + dispatch: Dict[ + Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] + ] = ... # TODO: Replace 'Any' with some kind of binding memo: Dict[Any, None] data: None encoding: Optional[str] allow_none: bool - def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... def dumps(self, values: Union[Fault, Iterable[_Marshallable]]) -> str: ... def __dump(self, value: Union[_Marshallable], write: Callable[[str], Any]) -> None: ... # undocumented @@ -116,7 +111,9 @@ class Marshaller: def dump_unicode(self, value: str, write: Callable[[str], Any], escape: Callable[[str], str] = ...) -> None: ... def dump_bytes(self, value: bytes, write: Callable[[str], Any]) -> None: ... def dump_array(self, value: Iterable[_Marshallable], write: Callable[[str], Any]) -> None: ... - def dump_struct(self, value: Mapping[str, _Marshallable], write: Callable[[str], Any], escape: Callable[[str], str] = ...) -> None: ... + def dump_struct( + self, value: Mapping[str, _Marshallable], write: Callable[[str], Any], escape: Callable[[str], str] = ... + ) -> None: ... def dump_datetime(self, value: _XMLDate, write: Callable[[str], Any]) -> None: ... def dump_instance(self, value: object, write: Callable[[str], Any]) -> None: ... @@ -134,7 +131,6 @@ class Unmarshaller: append: Callable[[Any], None] _use_datetime: bool _use_builtin_types: bool - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... def close(self) -> Tuple[_Marshallable, ...]: ... def getmethodname(self) -> Optional[str]: ... @@ -147,8 +143,7 @@ class Unmarshaller: def end_boolean(self, data: str) -> None: ... def end_int(self, data: str) -> None: ... def end_double(self, data: str) -> None: ... - if sys.version_info >= (3, 6): - def end_bigdecimal(self, data: str) -> None: ... + def end_bigdecimal(self, data: str) -> None: ... def end_string(self, data: str) -> None: ... def end_array(self, data: str) -> None: ... def end_struct(self, data: str) -> None: ... @@ -163,7 +158,6 @@ class _MultiCallMethod: # undocumented __call_list: List[Tuple[str, Tuple[_Marshallable, ...]]] __name: str - def __init__(self, call_list: List[Tuple[str, _Marshallable]], name: str) -> None: ... def __getattr__(self, name: str) -> _MultiCallMethod: ... def __call__(self, *args: _Marshallable) -> None: ... @@ -171,7 +165,6 @@ class _MultiCallMethod: # undocumented class MultiCallIterator: # undocumented results: List[List[_Marshallable]] - def __init__(self, results: List[List[_Marshallable]]) -> None: ... def __getitem__(self, i: int) -> _Marshallable: ... @@ -179,7 +172,6 @@ class MultiCall: __server: ServerProxy __call_list: List[Tuple[str, Tuple[_Marshallable, ...]]] - def __init__(self, server: ServerProxy) -> None: ... def __getattr__(self, item: str) -> _MultiCallMethod: ... def __call__(self) -> MultiCallIterator: ... @@ -190,16 +182,22 @@ FastParser: Optional[ExpatParser] FastUnmarshaller: Optional[Unmarshaller] def getparser(use_datetime: bool = ..., use_builtin_types: bool = ...) -> Tuple[ExpatParser, Unmarshaller]: ... -def dumps(params: Union[Fault, Tuple[_Marshallable, ...]], methodname: Optional[str] = ..., methodresponse: Optional[bool] = ..., encoding: Optional[str] = ..., allow_none: bool = ...) -> str: ... -def loads(data: str, use_datetime: bool = ..., use_builtin_types: bool = ...) -> Tuple[Tuple[_Marshallable, ...], Optional[str]]: ... - +def dumps( + params: Union[Fault, Tuple[_Marshallable, ...]], + methodname: Optional[str] = ..., + methodresponse: Optional[bool] = ..., + encoding: Optional[str] = ..., + allow_none: bool = ..., +) -> str: ... +def loads( + data: str, use_datetime: bool = ..., use_builtin_types: bool = ... +) -> Tuple[Tuple[_Marshallable, ...], Optional[str]]: ... def gzip_encode(data: bytes) -> bytes: ... # undocumented def gzip_decode(data: bytes, max_decode: int = ...) -> bytes: ... # undocumented class GzipDecodedResponse(gzip.GzipFile): # undocumented - io: io.BytesIO - + io: BytesIO def __init__(self, response: SupportsRead[bytes]) -> None: ... def close(self) -> None: ... @@ -207,7 +205,6 @@ class _Method: # undocumented __send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable] __name: str - def __init__(self, send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... def __getattr__(self, name: str) -> _Method: ... def __call__(self, *args: _Marshallable) -> _Marshallable: ... @@ -225,11 +222,15 @@ class Transport: _extra_headers: List[Tuple[str, str]] if sys.version_info >= (3, 8): - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ...) -> None: ... + def __init__( + self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ... + ) -> None: ... else: def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... def request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... - def single_request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... + def single_request( + self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ... + ) -> Tuple[_Marshallable, ...]: ... def getparser(self) -> Tuple[ExpatParser, Unmarshaller]: ... def get_host_info(self, host: _HostType) -> Tuple[str, List[Tuple[str, str]], Dict[str, str]]: ... def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ... @@ -242,7 +243,14 @@ class Transport: class SafeTransport(Transport): if sys.version_info >= (3, 8): - def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ..., context: Optional[Any] = ...) -> None: ... + def __init__( + self, + use_datetime: bool = ..., + use_builtin_types: bool = ..., + *, + headers: Iterable[Tuple[str, str]] = ..., + context: Optional[Any] = ..., + ) -> None: ... else: def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Optional[Any] = ...) -> None: ... def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... @@ -257,9 +265,32 @@ class ServerProxy: __allow_none: bool if sys.version_info >= (3, 8): - def __init__(self, uri, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., use_builtin_types: bool = ..., *, headers: Iterable[Tuple[str, str]] = ..., context: Optional[Any] = ...) -> None: ... + def __init__( + self, + uri: str, + transport: Optional[Transport] = ..., + encoding: Optional[str] = ..., + verbose: bool = ..., + allow_none: bool = ..., + use_datetime: bool = ..., + use_builtin_types: bool = ..., + *, + headers: Iterable[Tuple[str, str]] = ..., + context: Optional[Any] = ..., + ) -> None: ... else: - def __init__(self, uri, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Optional[Any] = ...) -> None: ... + def __init__( + self, + uri: str, + transport: Optional[Transport] = ..., + encoding: Optional[str] = ..., + verbose: bool = ..., + allow_none: bool = ..., + use_datetime: bool = ..., + use_builtin_types: bool = ..., + *, + context: Optional[Any] = ..., + ) -> None: ... def __getattr__(self, name: str) -> _Method: ... @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... @@ -268,7 +299,9 @@ class ServerProxy: @overload def __call__(self, attr: str) -> Union[Callable[[], None], Transport]: ... def __enter__(self) -> ServerProxy: ... - def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: ... def __close(self) -> None: ... # undocumented def __request(self, methodname: str, params: Tuple[_Marshallable, ...]) -> Tuple[_Marshallable, ...]: ... # undocumented diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 999d58208a6c..8cdcf499ac2a 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -1,29 +1,37 @@ import http.server -import socketserver import pydoc +import socketserver import sys - -from xmlrpc.client import Fault -from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Pattern, Protocol, Tuple, Type, Union from datetime import datetime +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Pattern, Protocol, Tuple, Type, Union +from xmlrpc.client import Fault -_Marshallable = Union[None, bool, int, float, str, bytes, tuple, list, dict, datetime] # TODO: Recursive type on tuple, list, dict +_Marshallable = Union[ + None, bool, int, float, str, bytes, tuple, list, dict, datetime +] # TODO: Recursive type on tuple, list, dict # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy class _DispatchArity0(Protocol): def __call__(self) -> _Marshallable: ... + class _DispatchArity1(Protocol): def __call__(self, __arg1: _Marshallable) -> _Marshallable: ... + class _DispatchArity2(Protocol): def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable) -> _Marshallable: ... + class _DispatchArity3(Protocol): def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable) -> _Marshallable: ... + class _DispatchArity4(Protocol): - def __call__(self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable) -> _Marshallable: ... + def __call__( + self, __arg1: _Marshallable, __arg2: _Marshallable, __arg3: _Marshallable, __arg4: _Marshallable + ) -> _Marshallable: ... + class _DispatchArityN(Protocol): def __call__(self, *args: _Marshallable) -> _Marshallable: ... -_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] +_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented def list_public_methods(obj: Any) -> List[str]: ... # undocumented @@ -35,16 +43,24 @@ class SimpleXMLRPCDispatcher: # undocumented allow_none: bool encoding: str use_builtin_types: bool - def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... def register_instance(self, instance: Any, allow_dotted_names: bool = ...) -> None: ... if sys.version_info >= (3, 7): - def register_function(self, function: Optional[_DispatchProtocol] = ..., name: Optional[str] = ...) -> Callable[..., Any]: ... + def register_function( + self, function: Optional[_DispatchProtocol] = ..., name: Optional[str] = ... + ) -> Callable[..., Any]: ... else: def register_function(self, function: _DispatchProtocol, name: Optional[str] = ...) -> Callable[..., Any]: ... def register_introspection_functions(self) -> None: ... def register_multicall_functions(self) -> None: ... - def _marshaled_dispatch(self, data: str, dispatch_method: Optional[Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]]] = ..., path: Optional[Any] = ...) -> str: ... # undocumented + def _marshaled_dispatch( + self, + data: str, + dispatch_method: Optional[ + Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]] + ] = ..., + path: Optional[Any] = ..., + ) -> str: ... # undocumented def system_listMethods(self) -> List[str]: ... # undocumented def system_methodSignature(self, method_name: str) -> str: ... # undocumented def system_methodHelp(self, method_name: str) -> str: ... # undocumented @@ -56,7 +72,6 @@ class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): rpc_paths: Tuple[str, str] = ... encode_threshold: int = ... # undocumented aepattern: Pattern[str] # undocumented - def accept_encodings(self) -> Dict[str, float]: ... def is_rpc_path_valid(self) -> bool: ... def do_POST(self) -> None: ... @@ -68,29 +83,50 @@ class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): allow_reuse_address: bool = ... _send_traceback_handler: bool = ... - - def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented dispatchers: Dict[str, SimpleXMLRPCDispatcher] allow_none: bool encoding: str - - def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ... def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... - def _marshaled_dispatch(self, data: str, dispatch_method: Optional[Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]]] = ..., path: Optional[Any] = ...) -> str: ... + def _marshaled_dispatch( + self, + data: str, + dispatch_method: Optional[ + Callable[[Optional[str], Tuple[_Marshallable, ...]], Union[Fault, Tuple[_Marshallable, ...]]] + ] = ..., + path: Optional[Any] = ..., + ) -> str: ... class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): - def __init__(self, allow_none: bool = ..., encoding: Optional[str] = ..., use_builtin_types: bool = ...) -> None: ... def handle_xmlrpc(self, request_text: str) -> None: ... def handle_get(self) -> None: ... def handle_request(self, request_text: Optional[str] = ...) -> None: ... class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented - def docroutine(self, object: object, name: str, mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: Optional[type] = ...) -> str: ... # type: ignore def docserver(self, server_name: str, package_documentation: str, methods: Dict[str, str]) -> str: ... @@ -99,7 +135,6 @@ class XMLRPCDocGenerator: # undocumented server_name: str server_documentation: str server_title: str - def __init__(self) -> None: ... def set_server_title(self, server_title: str) -> None: ... def set_server_name(self, server_name: str) -> None: ... @@ -107,13 +142,19 @@ class XMLRPCDocGenerator: # undocumented def generate_html_documentation(self) -> str: ... class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): - def do_GET(self) -> None: ... class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): - - def __init__(self, addr: Tuple[str, int], requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: Optional[str] = ..., bind_and_activate: bool = ..., use_builtin_types: bool = ...) -> None: ... + def __init__( + self, + addr: Tuple[str, int], + requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = ..., + allow_none: bool = ..., + encoding: Optional[str] = ..., + bind_and_activate: bool = ..., + use_builtin_types: bool = ..., + ) -> None: ... class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): - def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xxlimited.pyi b/mypy/typeshed/stdlib/xxlimited.pyi new file mode 100644 index 000000000000..e47694586ab1 --- /dev/null +++ b/mypy/typeshed/stdlib/xxlimited.pyi @@ -0,0 +1,13 @@ +from typing import Any + +class Null: ... +class Str: ... + +class Xxo: + def demo(self) -> None: ... + +class error: ... + +def foo(__i: int, __j: int) -> Any: ... +def new() -> Xxo: ... +def roj(__b: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi index 76354b6ab9d4..e1b38e9711b6 100644 --- a/mypy/typeshed/stdlib/zipapp.pyi +++ b/mypy/typeshed/stdlib/zipapp.pyi @@ -1,7 +1,5 @@ -# Stubs for zipapp (Python 3.5+) - -from pathlib import Path import sys +from pathlib import Path from typing import BinaryIO, Callable, Optional, Union _Path = Union[str, Path, BinaryIO] @@ -9,8 +7,18 @@ _Path = Union[str, Path, BinaryIO] class ZipAppError(ValueError): ... if sys.version_info >= (3, 7): - def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ..., - filter: Optional[Callable[[Path], bool]] = ..., compressed: bool = ...) -> None: ... + def create_archive( + source: _Path, + target: Optional[_Path] = ..., + interpreter: Optional[str] = ..., + main: Optional[str] = ..., + filter: Optional[Callable[[Path], bool]] = ..., + compressed: bool = ..., + ) -> None: ... + else: - def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ...) -> None: ... + def create_archive( + source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ... + ) -> None: ... + def get_interpreter(archive: _Path) -> str: ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index 26547a73cf63..8c02e4a85972 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -1,8 +1,24 @@ -from _typeshed import StrPath -from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, Protocol, Text, Tuple, Type, Union, Sequence, Pattern -from types import TracebackType 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] @@ -32,12 +48,7 @@ class ZipExtFile(io.BufferedIOBase): name: str if sys.version_info >= (3, 7): def __init__( - self, - fileobj: IO[bytes], - mode: str, - zipinfo: ZipInfo, - pwd: Optional[bytes] = ..., - close_fileobj: bool = ..., + self, fileobj: IO[bytes], mode: str, zipinfo: ZipInfo, pwd: Optional[bytes] = ..., close_fileobj: bool = ... ) -> None: ... else: def __init__( @@ -96,7 +107,7 @@ class ZipFile: 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[_SZI] = ..., pwd: Optional[bytes] = ...) -> str: ... + 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: ... @@ -108,11 +119,23 @@ class ZipFile: def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... def testzip(self) -> Optional[str]: ... if sys.version_info >= (3, 7): - def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ..., compresslevel: Optional[int] = ...) -> None: ... + def write( + self, + filename: StrPath, + arcname: Optional[StrPath] = ..., + compress_type: Optional[int] = ..., + compresslevel: Optional[int] = ..., + ) -> None: ... else: def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ...) -> None: ... if sys.version_info >= (3, 7): - def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ..., compresslevel: Optional[int] = ...) -> None: ... + def writestr( + self, + zinfo_or_arcname: _SZI, + 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: @@ -121,7 +144,12 @@ class ZipFile: class PyZipFile(ZipFile): if sys.version_info >= (3,): def __init__( - self, file: Union[str, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., optimize: int = ... + 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: @@ -184,6 +212,9 @@ 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 if sys.version_info >= (3, 3): ZIP_BZIP2: int ZIP_LZMA: int diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index b33a150586ea..0d1a330942d4 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -1,9 +1,8 @@ -"""Stub file for the 'zipimport' module.""" - import os import sys -from typing import Any, List, Optional, Tuple, Union from types import CodeType, ModuleType +from typing import Any, List, Optional, Tuple, Union + if sys.version_info >= (3, 7): from importlib.abc import ResourceReader @@ -17,7 +16,9 @@ class zipimporter(object): 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 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 871f621bf703..3675784675c6 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,7 +1,6 @@ -# Stubs for zlib import sys from array import array -from typing import Union, Any +from typing import Any, Union DEFLATED: int DEF_MEM_LEVEL: int @@ -23,13 +22,11 @@ if sys.version_info >= (3,): 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 @@ -39,19 +36,24 @@ class _Decompress: 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: bytes = ...) -> _Compress: ... + def compressobj( + level: int = ..., method: int = ..., wbits: int = ..., memLevel: int = ..., strategy: int = ..., zdict: 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 = ... + ) -> _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: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 6e56abf2cdcf..46cd6b871555 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,16 +1,7 @@ import os import typing -from datetime import datetime, tzinfo -from typing import ( - Any, - Iterable, - Optional, - Protocol, - Sequence, - Set, - Type, - Union, -) +from datetime import tzinfo +from typing import Any, AnyStr, Iterable, Optional, Protocol, Sequence, Set, Type, Union _T = typing.TypeVar("_T", bound="ZoneInfo") @@ -25,18 +16,14 @@ class ZoneInfo(tzinfo): @classmethod def no_cache(cls: Type[_T], key: str) -> _T: ... @classmethod - def from_file( - cls: Type[_T], __fobj: _IOBytes, key: Optional[str] = ... - ) -> _T: ... + def from_file(cls: Type[_T], __fobj: _IOBytes, key: Optional[str] = ...) -> _T: ... @classmethod def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... # 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, str]]] = ... -) -> None: ... +def reset_tzpath(to: Optional[Sequence[Union[os.PathLike[AnyStr], str]]] = ...) -> None: ... def available_timezones() -> Set[str]: ... TZPATH: Sequence[str] From 93eedd279d7b26ed3c45e75b9e63848e3e2407a6 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 16:23:52 +0000 Subject: [PATCH 28/50] Look up Python 2 stubs under @python2 instead of python2 This was changed recently. --- mypy/modulefinder.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index d1ff86c46356..f0051fa68841 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -34,6 +34,8 @@ PYTHON_EXTENSIONS = ['.pyi', '.py'] # type: Final +PYTHON2_STUB_DIR: Final = '@python2' + # TODO: Consider adding more reasons here? # E.g. if we deduce a module would likely be found if the user were @@ -509,8 +511,8 @@ def default_lib_path(data_dir: str, data_dir = auto typeshed_dir = os.path.join(data_dir, "typeshed", "stdlib") if pyversion[0] == 2: - # Python 2 variants of certain stdlib modules are under python2/. - python2_dir = os.path.join(typeshed_dir, "python2") + # Python 2 variants of certain stdlib modules are in a separate directory. + python2_dir = os.path.join(typeshed_dir, PYTHON2_STUB_DIR) path.append(python2_dir) path.append(typeshed_dir) @@ -697,7 +699,7 @@ def load_stdlib_py_versions() -> Dict[str, Tuple[int, int]]: # Modules that are Python 2 only or have separate Python 2 stubs # have stubs in python2/ and may need an override. - python2_dir = os.path.join(typeshed_dir, "python2") + python2_dir = os.path.join(typeshed_dir, PYTHON2_STUB_DIR) for fnam in os.listdir(python2_dir): fnam = fnam.replace(".pyi", "") result[fnam] = (2, 7) From c5fa53e6ea12129fcd3099bf583c985413ae1ec4 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 16:24:48 +0000 Subject: [PATCH 29/50] Add initial typeshed sync script --- misc/sync-typeshed.py | 82 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 misc/sync-typeshed.py diff --git a/misc/sync-typeshed.py b/misc/sync-typeshed.py new file mode 100644 index 000000000000..02404d20fa46 --- /dev/null +++ b/misc/sync-typeshed.py @@ -0,0 +1,82 @@ +"""Sync stdlib stubs from typeshed. + +Usage: + + python3 misc/sync-typeshed.py [--commit hash] [--typeshed-dir dir] + +By default, sync to the latest typeshed commit. +""" + +import argparse +import glob +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap + + +def check_state() -> None: + if not os.path.isfile('README.md'): + sys.exit('error: The current working directory must be the mypy repository root') + out = subprocess.check_output(['git', 'status', '-s', os.path.join('mypy', 'typeshed')]) + if out: + # If there are local changes under mypy/typeshed, they would be lost. + sys.exit('error: Output of "git status -s mypy/typeshed" must be empty') + + +def update_typeshed(typeshed_dir: str) -> None: + assert os.path.isdir(os.path.join(typeshed_dir, 'stdlib')) + assert os.path.isdir(os.path.join(typeshed_dir, 'stubs')) + stub_dir = os.path.join('mypy', 'typeshed', 'stdlib') + # Remove existing stubs. + shutil.rmtree(stub_dir) + # Copy new stdlib stubs. + shutil.copytree(os.path.join(typeshed_dir, 'stdlib'), stub_dir) + # Also include mypy_extensions and typing_extensions, since they are + # special and shouldn't be updated arbitrarily. + for distribution, fnam in [('mypy-extensions', 'mypy_extensions.pyi'), + ('typing-extensions', 'typing_extensions.pyi')]: + shutil.copy(os.path.join(typeshed_dir, 'stubs', distribution, fnam), stub_dir) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--commit", default=None, + help="Typeshed commit (default to latest master if using a repository clone)" + ) + parser.add_argument( + "--typeshed-dir", default=None, + help="Location of typeshed (default to a temporary repository clone)" + ) + args = parser.parse_args() + check_state() + print('Update contents of mypy/typeshed/stdlib from typeshed? [yN] ', end='') + answer = input() + if answer.lower() != 'y': + sys.exit('Aborting') + + # TODO: Clone typeshed repo if no directory given + assert args.typeshed_dir + update_typeshed(args.typeshed_dir) + + commit = args.commit + # TODO: If cloning typeshd repo, use master commit + assert commit + + # Create a commit + message = textwrap.dedent("""\ + Sync typeshed + + Source commit: + https://github.com/python/typeshed/commit/{commit} + """.format(commit=commit)) + subprocess.run(['git', 'add', '--all', os.path.join('mypy', 'typeshed')], check=True) + subprocess.run(['git', 'commit', '-m', message], check=True) + print('Created typeshed sync commit.') + + +if __name__ == '__main__': + main() From fa092f327335e14d18da66c44c227ec7800c27a0 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 16:47:09 +0000 Subject: [PATCH 30/50] Update legacy bundled packages data --- mypy/stubinfo.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/mypy/stubinfo.py b/mypy/stubinfo.py index 275cd44092f2..b4c1224b4d83 100644 --- a/mypy/stubinfo.py +++ b/mypy/stubinfo.py @@ -2,16 +2,19 @@ # # Map package name to PyPI stub distribution name. legacy_bundled_packages = { + 'aiofiles': 'types-aiofiles', 'atomicwrites': 'types-atomicwrites', 'attr': 'types-attrs', 'backports': 'types-backports', 'backports_abc': 'types-backports_abc', 'bleach': 'types-bleach', 'boto': 'types-boto', + 'cachetools': 'types-cachetools', 'certifi': 'types-certifi', 'characteristic': 'types-characteristic', 'chardet': 'types-chardet', 'click': 'types-click', + 'click_spinner': 'types-click-spinner', 'concurrent': 'types-futures', 'contextvars': 'types-contextvars', 'croniter': 'types-croniter', @@ -22,12 +25,16 @@ 'datetimerange': 'types-DateTimeRange', 'dateutil': 'types-python-dateutil', 'decorator': 'types-decorator', + 'deprecated': 'types-Deprecated', 'docutils': 'types-docutils', 'emoji': 'types-emoji', 'enum': 'types-enum34', 'fb303': 'types-fb303', + 'filelock': 'types-filelock', 'first': 'types-first', 'flask': 'types-Flask', + 'freezegun': 'types-freezegun', + 'frozendict': 'types-frozendict', 'geoip2': 'types-geoip2', 'gflags': 'types-python-gflags', 'google': 'types-protobuf', @@ -36,29 +43,35 @@ 'jinja2': 'types-Jinja2', 'jwt': 'types-jwt', 'kazoo': 'types-kazoo', + 'markdown': 'types-Markdown', 'markupsafe': 'types-MarkupSafe', 'maxminddb': 'types-maxminddb', 'mock': 'types-mock', 'mypy_extensions': 'types-mypy-extensions', 'OpenSSL': 'types-openssl-python', 'orjson': 'types-orjson', + 'paramiko': 'types-paramiko', 'pathlib2': 'types-pathlib2', 'pkg_resources': 'types-pkg_resources', + 'polib': 'types-polib', 'pycurl': 'types-pycurl', 'pymssql': 'types-pymssql', 'pymysql': 'types-PyMySQL', 'pynamodb': 'types-pynamodb', 'pyre_extensions': 'types-pyre-extensions', + 'pyrfc3339': 'types-pyRFC3339', 'python2': 'types-six', 'pytz': 'types-pytz', 'pyVmomi': 'types-pyvmomi', 'redis': 'types-redis', 'requests': 'types-requests', + 'retry': 'types-retry', 'routes': 'types-Routes', 'scribe': 'types-scribe', 'simplejson': 'types-simplejson', 'singledispatch': 'types-singledispatch', 'six': 'types-six', + 'slugify': 'types-python-slugify', 'tabulate': 'types-tabulate', 'termcolor': 'types-termcolor', 'toml': 'types-toml', From 157604f4a18279eab902c9e1f4d8a9afc2f52dbd Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 17:24:55 +0000 Subject: [PATCH 31/50] Fix more tests --- mypy/modulefinder.py | 2 +- mypy/test/testsamples.py | 3 --- test-data/unit/cmdline.test | 9 ++++----- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index f0051fa68841..57028dde6b16 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -64,7 +64,7 @@ def error_message_templates(self) -> Tuple[str, List[str]]: msg = 'Cannot find implementation or library stub for module named "{module}"' notes = [doc_link] elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: - msg = "Cannot find implementation or library stub for module named '{}'" + msg = 'Cannot find implementation or library stub for module named "{module}"' notes = ["You may be running mypy in a subpackage, " "mypy should be run on the package root"] elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: diff --git a/mypy/test/testsamples.py b/mypy/test/testsamples.py index 2bbd791f3b6e..c132c3e3f676 100644 --- a/mypy/test/testsamples.py +++ b/mypy/test/testsamples.py @@ -48,9 +48,6 @@ class SamplesSuite(Suite): def test_samples(self) -> None: for f in find_files(os.path.join('test-data', 'samples'), suffix='.py'): mypy_args = ['--no-strict-optional'] - if f == os.path.join('test-data', 'samples', 'crawl2.py'): - # This test requires 3.5 for async functions - mypy_args.append('--python-version=3.5') run_mypy(mypy_args + [f]) def test_stdlibsamples(self) -> None: diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index cd67c0b646fb..c4d20ee78d61 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -518,10 +518,10 @@ import missing [file main/grandparent.py] [file main/__init__.py] [out] -main.py:1: error: Cannot find implementation or library stub for module named 'parent' +main.py:1: error: Cannot find implementation or library stub for module named "parent" main.py:1: note: You may be running mypy in a subpackage, mypy should be run on the package root -main.py:2: error: Cannot find implementation or library stub for module named 'grandparent' -main.py:3: error: Cannot find implementation or library stub for module named 'missing' +main.py:2: error: Cannot find implementation or library stub for module named "grandparent" +main.py:3: error: Cannot find implementation or library stub for module named "missing" main.py:3: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testImportInParentButNoInit] @@ -532,7 +532,7 @@ import needs_init [file main/needs_init.py] [file main/__init__.py] [out] -main.py:1: error: Cannot find implementation or library stub for module named 'needs_init' +main.py:1: error: Cannot find implementation or library stub for module named "needs_init" main.py:1: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports [case testConfigNoErrorForUnknownXFlagInSubsection] @@ -1281,4 +1281,3 @@ x = 0 # type: str y = 0 # type: str [out] pkg.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str") - From 4e2a60f1f916e76a170c7e955d6fcd4e189dffe7 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 17:27:46 +0000 Subject: [PATCH 32/50] Fix another test case We can no longer import attrs in this test case, since we don't ship the stubs any more, and the test is run with `--no-site-packages` so separately installed stubs don't work. --- test-data/unit/reports.test | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test-data/unit/reports.test b/test-data/unit/reports.test index 68bbb180f984..5e0da3f07a98 100644 --- a/test-data/unit/reports.test +++ b/test-data/unit/reports.test @@ -351,8 +351,6 @@ Total 0 0 0 0 0 [case testTrickyCoverage] # cmd: mypy --linecoverage-report=report n.py [file n.py] -import attr - def blah(x): return x @blah @@ -365,7 +363,7 @@ class Foo: def f(self, x: int) -> None: pass -@attr.s +@blah class Z(object): pass From a7298393fffd645b24e8757d61f6a53fddff51e5 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 17:39:15 +0000 Subject: [PATCH 33/50] Update self checking target to Python 3.6 Typeshed no longer supports 3.5. --- mypy_self_check.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy_self_check.ini b/mypy_self_check.ini index 2b7ed2b157c5..ef8785b6c8bc 100644 --- a/mypy_self_check.ini +++ b/mypy_self_check.ini @@ -18,4 +18,4 @@ show_error_codes = True pretty = True always_false = MYPYC plugins = misc/proper_plugin.py -python_version = 3.5 +python_version = 3.6 From f5b11859bd722735de955da1127f195a7c9de9d4 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 17:39:40 +0000 Subject: [PATCH 34/50] Fix Python 3.5 --- mypy/modulefinder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 57028dde6b16..dfe53580958d 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -34,7 +34,7 @@ PYTHON_EXTENSIONS = ['.pyi', '.py'] # type: Final -PYTHON2_STUB_DIR: Final = '@python2' +PYTHON2_STUB_DIR = '@python2' # type: Final # TODO: Consider adding more reasons here? From 72931091c11a959036e4d667b74bc407d2f8dac6 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 22 Jan 2021 18:18:57 +0000 Subject: [PATCH 35/50] Fix stubtest --- mypy/modulefinder.py | 16 ++++++++++------ mypy/stubtest.py | 30 ++++++++++++++---------------- mypy/test/teststubtest.py | 5 +++++ 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index dfe53580958d..d84696e5ce7b 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -129,7 +129,10 @@ def __init__(self, self.results = {} # type: Dict[str, ModuleSearchResult] self.ns_ancestors = {} # type: Dict[str, str] self.options = options - self.stdlib_py_versions = load_stdlib_py_versions() + custom_typeshed_dir = None + if options: + custom_typeshed_dir = options.custom_typeshed_dir + self.stdlib_py_versions = load_stdlib_py_versions(custom_typeshed_dir) self.python2 = options and options.python_version[0] == 2 def clear(self) -> None: @@ -679,15 +682,16 @@ def compute_search_paths(sources: List[BuildSource], typeshed_path=tuple(lib_path)) -def load_stdlib_py_versions() -> Dict[str, Tuple[int, int]]: +def load_stdlib_py_versions(custom_typeshed_dir: Optional[str]) -> Dict[str, Tuple[int, int]]: """Return dict with minimum Python versions of stdlib modules. The contents look like {..., 'secrets': 3.6, 're': 2.7, ...}. """ - typeshed_dir = os.path.join(os.path.dirname(__file__), "typeshed", "stdlib") + typeshed_dir = custom_typeshed_dir or os.path.join(os.path.dirname(__file__), "typeshed") + stdlib_dir = os.path.join(typeshed_dir, "stdlib") result = {} - versions_path = os.path.join(typeshed_dir, "VERSIONS") + versions_path = os.path.join(stdlib_dir, "VERSIONS") with open(versions_path) as f: for line in f: line = line.strip() @@ -698,8 +702,8 @@ def load_stdlib_py_versions() -> Dict[str, Tuple[int, int]]: result[module] = int(major), int(minor) # Modules that are Python 2 only or have separate Python 2 stubs - # have stubs in python2/ and may need an override. - python2_dir = os.path.join(typeshed_dir, PYTHON2_STUB_DIR) + # have stubs in @python2/ and may need an override. + python2_dir = os.path.join(stdlib_dir, PYTHON2_STUB_DIR) for fnam in os.listdir(python2_dir): fnam = fnam.replace(".pyi", "") result[fnam] = (2, 7) diff --git a/mypy/stubtest.py b/mypy/stubtest.py index aa86b3b887df..9b87551ab3d3 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -1046,27 +1046,25 @@ def get_stub(module: str) -> Optional[nodes.MypyFile]: def get_typeshed_stdlib_modules(custom_typeshed_dir: Optional[str]) -> List[str]: """Returns a list of stdlib modules in typeshed (for current Python version).""" - # This snippet is based on code in mypy.modulefinder.default_lib_path + stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir) + packages = set() + for module, minver in stdlib_py_versions.items(): + if sys.version_info >= minver: + packages.add(module) + if custom_typeshed_dir: typeshed_dir = Path(custom_typeshed_dir) else: - typeshed_dir = Path(mypy.build.default_data_dir()) - if (typeshed_dir / "stubs-auto").exists(): - typeshed_dir /= "stubs-auto" - typeshed_dir /= "typeshed" - - versions = ["2and3", "3"] - for minor in range(sys.version_info.minor + 1): - versions.append("3.{}".format(minor)) + typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed" + stdlib_dir = typeshed_dir / "stdlib" modules = [] - for version in versions: - base = typeshed_dir / "stdlib" / version - if base.exists(): - for path in base.rglob("*.pyi"): - if path.stem == "__init__": - path = path.parent - modules.append(".".join(path.relative_to(base).parts[:-1] + (path.stem,))) + for path in stdlib_dir.rglob("*.pyi"): + if path.stem == "__init__": + path = path.parent + module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,)) + if module.split(".")[0] in packages: + modules.append(module) return sorted(modules) diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index a183af68dfd2..f8f542be2152 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -830,6 +830,11 @@ def test_get_typeshed_stdlib_modules(self) -> None: stdlib = mypy.stubtest.get_typeshed_stdlib_modules(None) assert "builtins" in stdlib assert "os" in stdlib + assert "os.path" in stdlib + assert "mypy_extensions" not in stdlib + assert "typing_extensions" not in stdlib + assert "asyncio" in stdlib + assert ("dataclasses" in stdlib) == (sys.version_info >= (3, 7)) def test_signature(self) -> None: def f(a: int, b: int, *, c: int, d: int = 0, **kwargs: Any) -> None: From 2cf512c6505178d78269bf6a41e7634d7ef3775f Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 11:54:39 +0000 Subject: [PATCH 36/50] Use Python 3.6 typeshed if target is 3.5 Typeshed doesn't support 3.5 any more. --- mypy/modulefinder.py | 13 ++++++++++++- mypy_self_check.ini | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index d84696e5ce7b..effc6d7c7499 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -194,7 +194,8 @@ def find_module(self, id: str) -> ModuleSearchResult: use_typeshed = True if top_level in self.stdlib_py_versions: min_version = self.stdlib_py_versions[top_level] - use_typeshed = self.options is None or self.options.python_version >= min_version + use_typeshed = (self.options is None + or typeshed_py_version(self.options) >= min_version) self.results[id] = self._find_module(id, use_typeshed) if (self.results[id] is ModuleNotFoundReason.NOT_FOUND and self._can_find_module_in_parent_dir(id)): @@ -709,3 +710,13 @@ def load_stdlib_py_versions(custom_typeshed_dir: Optional[str]) -> Dict[str, Tup result[fnam] = (2, 7) return result + + +def typeshed_py_version(options: Options) -> Tuple[int, int]: + """Return Python version used for checking whether module supports typeshed.""" + # Typeshed no longer covers Python 3.x versions before 3.6, so 3.6 is + # the earliest we can support. + if options.python_version[0] >= 3: + return max(options.python_version, (3, 6)) + else: + return options.python_version diff --git a/mypy_self_check.ini b/mypy_self_check.ini index ef8785b6c8bc..2b7ed2b157c5 100644 --- a/mypy_self_check.ini +++ b/mypy_self_check.ini @@ -18,4 +18,4 @@ show_error_codes = True pretty = True always_false = MYPYC plugins = misc/proper_plugin.py -python_version = 3.6 +python_version = 3.5 From 3b87853add36fa64dd79dccca91b57ab9c836708 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 11:58:16 +0000 Subject: [PATCH 37/50] Fix stubtest on 3.5 --- mypy/stubtest.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/mypy/stubtest.py b/mypy/stubtest.py index 9b87551ab3d3..a83e22d09455 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -1048,8 +1048,13 @@ def get_typeshed_stdlib_modules(custom_typeshed_dir: Optional[str]) -> List[str] """Returns a list of stdlib modules in typeshed (for current Python version).""" stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir) packages = set() + # Typeshed doesn't cover Python 3.5. + if sys.version_info < (3, 6): + version_info = (3, 6) + else: + version_info = sys.version_info[0:2] for module, minver in stdlib_py_versions.items(): - if sys.version_info >= minver: + if version_info >= minver: packages.add(module) if custom_typeshed_dir: From 4df2c2cedbb3eecb2a9fb78729bb79f80a94296b Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 13:22:10 +0000 Subject: [PATCH 38/50] Use typing_extensions and mypy_extensions stubs from stub packages --- misc/sync-typeshed.py | 5 - mypy/build.py | 3 +- mypy/typeshed/stdlib/mypy_extensions.pyi | 46 -------- mypy/typeshed/stdlib/typing_extensions.pyi | 117 --------------------- mypy/util.py | 8 ++ 5 files changed, 10 insertions(+), 169 deletions(-) delete mode 100644 mypy/typeshed/stdlib/mypy_extensions.pyi delete mode 100644 mypy/typeshed/stdlib/typing_extensions.pyi diff --git a/misc/sync-typeshed.py b/misc/sync-typeshed.py index 02404d20fa46..0207c64bba0c 100644 --- a/misc/sync-typeshed.py +++ b/misc/sync-typeshed.py @@ -34,11 +34,6 @@ def update_typeshed(typeshed_dir: str) -> None: shutil.rmtree(stub_dir) # Copy new stdlib stubs. shutil.copytree(os.path.join(typeshed_dir, 'stdlib'), stub_dir) - # Also include mypy_extensions and typing_extensions, since they are - # special and shouldn't be updated arbitrarily. - for distribution, fnam in [('mypy-extensions', 'mypy_extensions.pyi'), - ('typing-extensions', 'typing_extensions.pyi')]: - shutil.copy(os.path.join(typeshed_dir, 'stubs', distribution, fnam), stub_dir) def main() -> None: diff --git a/mypy/build.py b/mypy/build.py index f83fb4d56bfe..0ea4f643d20b 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -36,7 +36,7 @@ from mypy.errors import Errors, CompileError, ErrorInfo, report_internal_error from mypy.util import ( DecodeError, decode_python_encoding, is_sub_path, get_mypy_comments, module_prefix, - read_py_file, hash_digest, is_typeshed_file + read_py_file, hash_digest, is_typeshed_file, is_stub_package_file ) if TYPE_CHECKING: from mypy.report import Reports # Avoid unconditional slow import @@ -2397,6 +2397,7 @@ def find_module_and_diagnose(manager: BuildManager, follow_imports = 'silent' if (id in CORE_BUILTIN_MODULES and not is_typeshed_file(result) + and not is_stub_package_file(result) and not options.use_builtins_fixtures and not options.custom_typeshed_dir): raise CompileError([ diff --git a/mypy/typeshed/stdlib/mypy_extensions.pyi b/mypy/typeshed/stdlib/mypy_extensions.pyi deleted file mode 100644 index e5df53ff7dd2..000000000000 --- a/mypy/typeshed/stdlib/mypy_extensions.pyi +++ /dev/null @@ -1,46 +0,0 @@ -import abc -import sys -from typing import Any, Callable, Dict, Generic, ItemsView, KeysView, Mapping, Optional, Type, TypeVar, Union, ValuesView - -_T = TypeVar("_T") -_U = TypeVar("_U") - -# 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: ... - def update(self: _T, __m: _T) -> None: ... - if sys.version_info < (3, 0): - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - else: - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - def __delitem__(self, k: NoReturn) -> None: ... - -def TypedDict(typename: str, fields: Dict[str, Type[_T]], total: bool = ...) -> Type[Dict[str, Any]]: ... -def Arg(type: _T = ..., name: Optional[str] = ...) -> _T: ... -def DefaultArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... -def NamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... -def DefaultNamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ... -def VarArg(type: _T = ...) -> _T: ... -def KwArg(type: _T = ...) -> _T: ... - -# Return type that indicates a function does not return. -# This type is equivalent to the None type, but the no-op Union is necessary to -# distinguish the None type from the None value. -NoReturn = Union[None] # Deprecated: Use typing.NoReturn instead. - -# This is intended as a class decorator, but mypy rejects abstract classes -# when a Type[_T] is expected, so we can't give it the type we want -def trait(cls: Any) -> Any: ... -def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... - -class FlexibleAlias(Generic[_T, _U]): ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi deleted file mode 100644 index f103a0faf36d..000000000000 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ /dev/null @@ -1,117 +0,0 @@ -import abc -import sys -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, - ValuesView, - 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: ... - def update(self: _T, __m: _T) -> None: ... - if sys.version_info < (3, 0): - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - else: - 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. -TypedDict: object = ... - -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]] = ..., - localns: Optional[Dict[str, Any]] = ..., - include_extras: bool = ..., -) -> Dict[str, Any]: ... - -if sys.version_info >= (3, 7): - def get_args(tp: Any) -> Tuple[Any, ...]: ... - def get_origin(tp: Any) -> Optional[Any]: ... - -Annotated: _SpecialForm = ... -_AnnotatedAlias: Any = ... # undocumented - -# TypeAlias is a (non-subscriptable) special form. -class TypeAlias: ... - -@runtime_checkable -class SupportsIndex(Protocol, metaclass=abc.ABCMeta): - @abc.abstractmethod - def __index__(self) -> int: ... - -# PEP 612 support for Python < 3.9 -if sys.version_info >= (3, 10): - from typing import Concatenate as Concatenate, ParamSpec as ParamSpec -else: - class ParamSpec: - __name__: str - def __init__(self, name: str) -> None: ... - Concatenate: _SpecialForm = ... - -# PEP 647 -TypeGuard: _SpecialForm = ... diff --git a/mypy/util.py b/mypy/util.py index 6832f14141da..e34dffcd3ab0 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -703,3 +703,11 @@ def format_error( def is_typeshed_file(file: str) -> bool: # gross, but no other clear way to tell return 'typeshed' in os.path.abspath(file).split(os.sep) + + +def is_stub_package_file(file: str) -> bool: + # Use hacky heuristics to check whether file is part of a PEP 561 stub package. + if not file.endswith('.pyi'): + return False + return any(component.endswith('-stubs') + for component in os.path.abspath(file).split(os.sep)) From ab5701d896a7a0fa19bd93dce549640beaca5935 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 13:29:27 +0000 Subject: [PATCH 39/50] Fix --custom-typeshed-dir --- mypy/modulefinder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index effc6d7c7499..da2c5cab1a32 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -508,7 +508,7 @@ def default_lib_path(data_dir: str, path = [] # type: List[str] if custom_typeshed_dir: - typeshed_dir = custom_typeshed_dir + typeshed_dir = os.path.join(custom_typeshed_dir, "stdlib") else: auto = os.path.join(data_dir, 'stubs-auto') if os.path.isdir(auto): From dc92f4bfd876226553aa4b62899eae9090abacde Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 14:04:47 +0000 Subject: [PATCH 40/50] Fix tests by enabling site packages --- mypy/test/helpers.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mypy/test/helpers.py b/mypy/test/helpers.py index e5f9d6e6253a..077c2f369cda 100644 --- a/mypy/test/helpers.py +++ b/mypy/test/helpers.py @@ -31,8 +31,9 @@ def run_mypy(args: List[str]) -> None: __tracebackhide__ = True + # We must enable site packages even though they could cause problems, + # since stubs for typing_extensions live there. outval, errval, status = api.run(args + ['--show-traceback', - '--no-site-packages', '--no-silence-site-packages']) if status != 0: sys.stdout.write(outval) From bec3b76a436e35faa606eb43c96e55c3ca973799 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 14:05:51 +0000 Subject: [PATCH 41/50] Add necessary stub package deps --- mypy-requirements.txt | 2 ++ setup.py | 2 ++ test-requirements.txt | 3 +++ 3 files changed, 7 insertions(+) diff --git a/mypy-requirements.txt b/mypy-requirements.txt index 66d15c1516f3..21f3ef4ef21f 100644 --- a/mypy-requirements.txt +++ b/mypy-requirements.txt @@ -1,3 +1,5 @@ typing_extensions>=3.7.4 mypy_extensions>=0.4.3,<0.5.0 typed_ast>=1.4.0,<1.5.0 +types-typing-extensions>=3.7.0 +types-mypy-extensions>=0.4.0 diff --git a/setup.py b/setup.py index ded856b0fda5..8f7a7cef467b 100644 --- a/setup.py +++ b/setup.py @@ -193,6 +193,8 @@ def run(self): install_requires=['typed_ast >= 1.4.0, < 1.5.0', 'typing_extensions>=3.7.4', 'mypy_extensions >= 0.4.3, < 0.5.0', + 'types-typing-extensions>=3.7.0', + 'types-mypy-extensions>=0.4.0', ], # Same here. extras_require={'dmypy': 'psutil >= 4.0'}, diff --git a/test-requirements.txt b/test-requirements.txt index f946d3c37921..0adbfe1ce0da 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -15,3 +15,6 @@ py>=1.5.2 virtualenv<20 setuptools!=50 importlib-metadata==0.20 +types-typed-ast>=1.4.0,<1.5.0 +types-toml>=0.0 +types-enum34>=0.0; python_version == '3.5' From 005be26a51831b9fb6e83491d3c25dab07073026 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 14:18:19 +0000 Subject: [PATCH 42/50] Fix Python evaluation tests --- mypy/test/testpythoneval.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/test/testpythoneval.py b/mypy/test/testpythoneval.py index e7e9f1618388..ae4b79c54faa 100644 --- a/mypy/test/testpythoneval.py +++ b/mypy/test/testpythoneval.py @@ -51,10 +51,10 @@ def test_python_evaluation(testcase: DataDrivenTestCase, cache_dir: str) -> None version. """ assert testcase.old_cwd is not None, "test was not properly set up" + # We must enable site packages to get access to installed stubs. # TODO: Enable strict optional for these tests mypy_cmdline = [ '--show-traceback', - '--no-site-packages', '--no-strict-optional', '--no-silence-site-packages', '--no-error-summary', From 8e2d3265ac2ac21d5ad87ae1b709ded651376c95 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 14:20:16 +0000 Subject: [PATCH 43/50] Fix cmdline tests --- mypy/test/testcmdline.py | 1 - 1 file changed, 1 deletion(-) diff --git a/mypy/test/testcmdline.py b/mypy/test/testcmdline.py index 42d756eee690..85b25cf92545 100644 --- a/mypy/test/testcmdline.py +++ b/mypy/test/testcmdline.py @@ -49,7 +49,6 @@ def test_python_cmdline(testcase: DataDrivenTestCase, step: int) -> None: args = parse_args(testcase.input[0]) custom_cwd = parse_cwd(testcase.input[1]) if len(testcase.input) > 1 else None args.append('--show-traceback') - args.append('--no-site-packages') if '--error-summary' not in args: args.append('--no-error-summary') # Type check the program. From e65dfa1632d0abe0049029106772a08081ffea5f Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 14:25:08 +0000 Subject: [PATCH 44/50] Update documentation of --custom-typeshed-dir --- docs/source/command_line.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/source/command_line.rst b/docs/source/command_line.rst index 51edffcd1c62..43a85ad231fd 100644 --- a/docs/source/command_line.rst +++ b/docs/source/command_line.rst @@ -743,12 +743,14 @@ in developing or debugging mypy internals. .. option:: --custom-typeshed-dir DIR - This flag specifies the directory where mypy looks for typeshed + This flag specifies the directory where mypy looks for standard library typeshed stubs, instead of the typeshed that ships with mypy. This is primarily intended to make it easier to test typeshed changes before submitting them upstream, but also allows you to use a forked version of typeshed. + Note that this doesn't affect third-party library stubs. + .. _warn-incomplete-stub: .. option:: --warn-incomplete-stub From 89c7184b00770f28f1948ddaec3fe37930bbcbbc Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 16:40:17 +0000 Subject: [PATCH 45/50] Fix 0.800 -> 0.900 --- docs/source/command_line.rst | 4 ++-- docs/source/getting_started.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/source/command_line.rst b/docs/source/command_line.rst index 43a85ad231fd..8b8e7e6ee928 100644 --- a/docs/source/command_line.rst +++ b/docs/source/command_line.rst @@ -859,8 +859,8 @@ Miscellaneous .. note:: - This is new in mypy 0.800. Previous mypy versions included a - selection of third-party packages, instead of having them + This is new in mypy 0.900. Previous mypy versions included a + selection of third-party package stubs, instead of having them installed separately. .. option:: --junit-xml JUNIT_XML diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index 07b1193e6b4f..655f1c33c9ef 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -369,7 +369,7 @@ often suggest the name of the stub distribution: .. note:: - Starting in mypy 0.800, most third-party package stubs must be + Starting in mypy 0.900, most third-party package stubs must be installed explicitly. This decouples mypy and stub versioning, allowing stubs to updated without updating mypy. This also allows stubs not originally included with mypy to be installed. Earlier From ca99565a68b3debdf082f0768c5466c7a54e5bbe Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 16:59:27 +0000 Subject: [PATCH 46/50] Don't ignore paths starting with @ --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index fb1fa11acf8a..aa4e90943ffa 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ build/ __pycache__ *.py[cod] *~ -@* /build /env*/ docs/build/ From cc34db5d1f71d0b5cabeebcc581579bb92fd906c Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 16:59:46 +0000 Subject: [PATCH 47/50] Add missing python 2 stubs --- .../stdlib/@python2/BaseHTTPServer.pyi | 41 + .../stdlib/@python2/CGIHTTPServer.pyi | 6 + .../typeshed/stdlib/@python2/ConfigParser.pyi | 97 ++ mypy/typeshed/stdlib/@python2/Cookie.pyi | 40 + mypy/typeshed/stdlib/@python2/HTMLParser.pyi | 28 + mypy/typeshed/stdlib/@python2/Queue.pyi | 29 + .../stdlib/@python2/SimpleHTTPServer.pyi | 14 + .../typeshed/stdlib/@python2/SocketServer.pyi | 115 ++ mypy/typeshed/stdlib/@python2/StringIO.pyi | 28 + mypy/typeshed/stdlib/@python2/UserDict.pyi | 53 + mypy/typeshed/stdlib/@python2/UserList.pyi | 19 + mypy/typeshed/stdlib/@python2/UserString.pyi | 75 ++ mypy/typeshed/stdlib/@python2/__builtin__.pyi | 1193 +++++++++++++++++ mypy/typeshed/stdlib/@python2/_ast.pyi | 303 +++++ .../typeshed/stdlib/@python2/_collections.pyi | 36 + mypy/typeshed/stdlib/@python2/_functools.pyi | 15 + mypy/typeshed/stdlib/@python2/_hotshot.pyi | 19 + mypy/typeshed/stdlib/@python2/_io.pyi | 184 +++ mypy/typeshed/stdlib/@python2/_json.pyi | 7 + mypy/typeshed/stdlib/@python2/_md5.pyi | 13 + mypy/typeshed/stdlib/@python2/_sha.pyi | 15 + mypy/typeshed/stdlib/@python2/_sha256.pyi | 23 + mypy/typeshed/stdlib/@python2/_sha512.pyi | 23 + mypy/typeshed/stdlib/@python2/_socket.pyi | 281 ++++ mypy/typeshed/stdlib/@python2/_sre.pyi | 51 + mypy/typeshed/stdlib/@python2/_struct.pyi | 19 + mypy/typeshed/stdlib/@python2/_symtable.pyi | 37 + .../stdlib/@python2/_threading_local.pyi | 11 + mypy/typeshed/stdlib/@python2/_winreg.pyi | 97 ++ mypy/typeshed/stdlib/@python2/abc.pyi | 31 + mypy/typeshed/stdlib/@python2/ast.pyi | 28 + mypy/typeshed/stdlib/@python2/atexit.pyi | 5 + mypy/typeshed/stdlib/@python2/builtins.pyi | 1193 +++++++++++++++++ mypy/typeshed/stdlib/@python2/cPickle.pyi | 26 + mypy/typeshed/stdlib/@python2/cStringIO.pyi | 48 + mypy/typeshed/stdlib/@python2/collections.pyi | 129 ++ mypy/typeshed/stdlib/@python2/commands.pyi | 10 + mypy/typeshed/stdlib/@python2/compileall.pyi | 16 + mypy/typeshed/stdlib/@python2/cookielib.pyi | 142 ++ mypy/typeshed/stdlib/@python2/copy_reg.pyi | 16 + mypy/typeshed/stdlib/@python2/dircache.pyi | 8 + .../stdlib/@python2/distutils/__init__.pyi | 0 .../@python2/distutils/archive_util.pyi | 12 + .../@python2/distutils/bcppcompiler.pyi | 3 + .../stdlib/@python2/distutils/ccompiler.pyi | 150 +++ .../stdlib/@python2/distutils/cmd.pyi | 67 + .../@python2/distutils/command/__init__.pyi | 0 .../@python2/distutils/command/bdist.pyi | 0 .../@python2/distutils/command/bdist_dumb.pyi | 0 .../@python2/distutils/command/bdist_msi.pyi | 6 + .../distutils/command/bdist_packager.pyi | 0 .../@python2/distutils/command/bdist_rpm.pyi | 0 .../distutils/command/bdist_wininst.pyi | 0 .../@python2/distutils/command/build.pyi | 0 .../@python2/distutils/command/build_clib.pyi | 0 .../@python2/distutils/command/build_ext.pyi | 0 .../@python2/distutils/command/build_py.pyi | 6 + .../distutils/command/build_scripts.pyi | 0 .../@python2/distutils/command/check.pyi | 0 .../@python2/distutils/command/clean.pyi | 0 .../@python2/distutils/command/config.pyi | 87 ++ .../@python2/distutils/command/install.pyi | 12 + .../distutils/command/install_data.pyi | 0 .../distutils/command/install_egg_info.pyi | 10 + .../distutils/command/install_headers.pyi | 0 .../distutils/command/install_lib.pyi | 0 .../distutils/command/install_scripts.pyi | 0 .../@python2/distutils/command/register.pyi | 0 .../@python2/distutils/command/sdist.pyi | 0 .../@python2/distutils/command/upload.pyi | 8 + .../stdlib/@python2/distutils/config.pyi | 17 + .../stdlib/@python2/distutils/core.pyi | 48 + .../@python2/distutils/cygwinccompiler.pyi | 4 + .../stdlib/@python2/distutils/debug.pyi | 1 + .../stdlib/@python2/distutils/dep_util.pyi | 5 + .../stdlib/@python2/distutils/dir_util.pyi | 15 + .../stdlib/@python2/distutils/dist.pyi | 9 + .../@python2/distutils/emxccompiler.pyi | 3 + .../stdlib/@python2/distutils/errors.pyi | 19 + .../stdlib/@python2/distutils/extension.pyi | 21 + .../@python2/distutils/fancy_getopt.pyi | 21 + .../stdlib/@python2/distutils/file_util.pyi | 14 + .../stdlib/@python2/distutils/filelist.pyi | 1 + .../stdlib/@python2/distutils/log.pyi | 25 + .../@python2/distutils/msvccompiler.pyi | 3 + .../stdlib/@python2/distutils/spawn.pyi | 4 + .../stdlib/@python2/distutils/sysconfig.pyi | 14 + .../stdlib/@python2/distutils/text_file.pyi | 21 + .../@python2/distutils/unixccompiler.pyi | 3 + .../stdlib/@python2/distutils/util.pyi | 23 + .../stdlib/@python2/distutils/version.pyi | 33 + .../typeshed/stdlib/@python2/dummy_thread.pyi | 21 + .../stdlib/@python2/email/MIMEText.pyi | 4 + .../stdlib/@python2/email/__init__.pyi | 6 + .../stdlib/@python2/email/_parseaddr.pyi | 40 + .../stdlib/@python2/email/base64mime.pyi | 11 + .../stdlib/@python2/email/charset.pyi | 26 + .../stdlib/@python2/email/encoders.pyi | 4 + .../stdlib/@python2/email/feedparser.pyi | 17 + .../stdlib/@python2/email/generator.pyi | 8 + .../typeshed/stdlib/@python2/email/header.pyi | 10 + .../stdlib/@python2/email/iterators.pyi | 5 + .../stdlib/@python2/email/message.pyi | 45 + .../stdlib/@python2/email/mime/__init__.pyi | 0 .../@python2/email/mime/application.pyi | 9 + .../stdlib/@python2/email/mime/audio.pyi | 4 + .../stdlib/@python2/email/mime/base.pyi | 4 + .../stdlib/@python2/email/mime/image.pyi | 4 + .../stdlib/@python2/email/mime/message.pyi | 4 + .../stdlib/@python2/email/mime/multipart.pyi | 4 + .../@python2/email/mime/nonmultipart.pyi | 4 + .../stdlib/@python2/email/mime/text.pyi | 4 + .../typeshed/stdlib/@python2/email/parser.pyi | 10 + .../stdlib/@python2/email/quoprimime.pyi | 18 + mypy/typeshed/stdlib/@python2/email/utils.pyi | 21 + .../stdlib/@python2/encodings/__init__.pyi | 7 + .../stdlib/@python2/encodings/utf_8.pyi | 15 + mypy/typeshed/stdlib/@python2/exceptions.pyi | 50 + mypy/typeshed/stdlib/@python2/fcntl.pyi | 82 ++ mypy/typeshed/stdlib/@python2/fnmatch.pyi | 8 + mypy/typeshed/stdlib/@python2/functools.pyi | 30 + .../stdlib/@python2/future_builtins.pyi | 10 + mypy/typeshed/stdlib/@python2/gc.pyi | 25 + mypy/typeshed/stdlib/@python2/getopt.pyi | 12 + mypy/typeshed/stdlib/@python2/getpass.pyi | 6 + mypy/typeshed/stdlib/@python2/gettext.pyi | 48 + mypy/typeshed/stdlib/@python2/glob.pyi | 7 + mypy/typeshed/stdlib/@python2/gzip.pyi | 38 + mypy/typeshed/stdlib/@python2/hashlib.pyi | 28 + mypy/typeshed/stdlib/@python2/heapq.pyi | 15 + .../stdlib/@python2/htmlentitydefs.pyi | 5 + mypy/typeshed/stdlib/@python2/httplib.pyi | 218 +++ mypy/typeshed/stdlib/@python2/imp.pyi | 33 + mypy/typeshed/stdlib/@python2/importlib.pyi | 4 + mypy/typeshed/stdlib/@python2/inspect.pyi | 129 ++ mypy/typeshed/stdlib/@python2/io.pyi | 40 + mypy/typeshed/stdlib/@python2/itertools.pyi | 164 +++ mypy/typeshed/stdlib/@python2/json.pyi | 93 ++ mypy/typeshed/stdlib/@python2/markupbase.pyi | 8 + mypy/typeshed/stdlib/@python2/md5.pyi | 5 + mypy/typeshed/stdlib/@python2/mimetools.pyi | 27 + .../@python2/multiprocessing/__init__.pyi | 50 + .../multiprocessing/dummy/__init__.pyi | 46 + .../multiprocessing/dummy/connection.pyi | 25 + .../stdlib/@python2/multiprocessing/pool.pyi | 52 + .../@python2/multiprocessing/process.pyi | 37 + .../stdlib/@python2/multiprocessing/util.pyi | 29 + mypy/typeshed/stdlib/@python2/mutex.pyi | 12 + mypy/typeshed/stdlib/@python2/ntpath.pyi | 85 ++ mypy/typeshed/stdlib/@python2/nturl2path.pyi | 4 + mypy/typeshed/stdlib/@python2/os/__init__.pyi | 385 ++++++ mypy/typeshed/stdlib/@python2/os/path.pyi | 85 ++ mypy/typeshed/stdlib/@python2/os2emxpath.pyi | 85 ++ mypy/typeshed/stdlib/@python2/pipes.pyi | 13 + mypy/typeshed/stdlib/@python2/platform.pyi | 41 + mypy/typeshed/stdlib/@python2/popen2.pyi | 27 + mypy/typeshed/stdlib/@python2/posix.pyi | 201 +++ mypy/typeshed/stdlib/@python2/posixpath.pyi | 85 ++ mypy/typeshed/stdlib/@python2/random.pyi | 67 + mypy/typeshed/stdlib/@python2/re.pyi | 108 ++ mypy/typeshed/stdlib/@python2/repr.pyi | 34 + mypy/typeshed/stdlib/@python2/resource.pyi | 46 + mypy/typeshed/stdlib/@python2/rfc822.pyi | 75 ++ mypy/typeshed/stdlib/@python2/robotparser.pyi | 7 + mypy/typeshed/stdlib/@python2/runpy.pyi | 17 + mypy/typeshed/stdlib/@python2/sets.pyi | 60 + mypy/typeshed/stdlib/@python2/sha.pyi | 10 + mypy/typeshed/stdlib/@python2/shelve.pyi | 36 + mypy/typeshed/stdlib/@python2/shlex.pyi | 30 + mypy/typeshed/stdlib/@python2/signal.pyi | 68 + mypy/typeshed/stdlib/@python2/smtplib.pyi | 86 ++ mypy/typeshed/stdlib/@python2/spwd.pyi | 15 + .../stdlib/@python2/sre_constants.pyi | 93 ++ mypy/typeshed/stdlib/@python2/sre_parse.pyi | 62 + mypy/typeshed/stdlib/@python2/stat.pyi | 58 + mypy/typeshed/stdlib/@python2/string.pyi | 68 + mypy/typeshed/stdlib/@python2/stringold.pyi | 44 + mypy/typeshed/stdlib/@python2/strop.pyi | 27 + mypy/typeshed/stdlib/@python2/subprocess.pyi | 115 ++ mypy/typeshed/stdlib/@python2/symbol.pyi | 89 ++ mypy/typeshed/stdlib/@python2/sys.pyi | 130 ++ mypy/typeshed/stdlib/@python2/tempfile.pyi | 102 ++ mypy/typeshed/stdlib/@python2/textwrap.pyi | 61 + mypy/typeshed/stdlib/@python2/thread.pyi | 27 + mypy/typeshed/stdlib/@python2/toaiff.pyi | 11 + mypy/typeshed/stdlib/@python2/tokenize.pyi | 133 ++ mypy/typeshed/stdlib/@python2/types.pyi | 195 +++ mypy/typeshed/stdlib/@python2/typing.pyi | 495 +++++++ mypy/typeshed/stdlib/@python2/unittest.pyi | 280 ++++ mypy/typeshed/stdlib/@python2/urllib.pyi | 133 ++ mypy/typeshed/stdlib/@python2/urllib2.pyi | 187 +++ mypy/typeshed/stdlib/@python2/urlparse.pyi | 61 + mypy/typeshed/stdlib/@python2/user.pyi | 6 + mypy/typeshed/stdlib/@python2/whichdb.pyi | 3 + mypy/typeshed/stdlib/@python2/xmlrpclib.pyi | 248 ++++ 195 files changed, 11128 insertions(+) create mode 100644 mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi create mode 100644 mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi create mode 100644 mypy/typeshed/stdlib/@python2/ConfigParser.pyi create mode 100644 mypy/typeshed/stdlib/@python2/Cookie.pyi create mode 100644 mypy/typeshed/stdlib/@python2/HTMLParser.pyi create mode 100644 mypy/typeshed/stdlib/@python2/Queue.pyi create mode 100644 mypy/typeshed/stdlib/@python2/SimpleHTTPServer.pyi create mode 100644 mypy/typeshed/stdlib/@python2/SocketServer.pyi create mode 100644 mypy/typeshed/stdlib/@python2/StringIO.pyi create mode 100644 mypy/typeshed/stdlib/@python2/UserDict.pyi create mode 100644 mypy/typeshed/stdlib/@python2/UserList.pyi create mode 100644 mypy/typeshed/stdlib/@python2/UserString.pyi create mode 100644 mypy/typeshed/stdlib/@python2/__builtin__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_ast.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_collections.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_functools.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_hotshot.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_io.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_json.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_md5.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_sha.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_sha256.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_sha512.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_socket.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_sre.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_struct.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_symtable.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_threading_local.pyi create mode 100644 mypy/typeshed/stdlib/@python2/_winreg.pyi create mode 100644 mypy/typeshed/stdlib/@python2/abc.pyi create mode 100644 mypy/typeshed/stdlib/@python2/ast.pyi create mode 100644 mypy/typeshed/stdlib/@python2/atexit.pyi create mode 100644 mypy/typeshed/stdlib/@python2/builtins.pyi create mode 100644 mypy/typeshed/stdlib/@python2/cPickle.pyi create mode 100644 mypy/typeshed/stdlib/@python2/cStringIO.pyi create mode 100644 mypy/typeshed/stdlib/@python2/collections.pyi create mode 100644 mypy/typeshed/stdlib/@python2/commands.pyi create mode 100644 mypy/typeshed/stdlib/@python2/compileall.pyi create mode 100644 mypy/typeshed/stdlib/@python2/cookielib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/copy_reg.pyi create mode 100644 mypy/typeshed/stdlib/@python2/dircache.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/archive_util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/bcppcompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/cmd.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist_dumb.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist_packager.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist_rpm.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/bdist_wininst.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/build.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/build_clib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/build_ext.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/build_py.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/build_scripts.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/check.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/clean.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/config.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install_data.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install_headers.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install_lib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/install_scripts.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/register.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/sdist.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/config.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/core.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/cygwinccompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/debug.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/dist.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/emxccompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/errors.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/extension.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/file_util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/filelist.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/log.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/msvccompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/spawn.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/sysconfig.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/text_file.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/unixccompiler.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/distutils/version.pyi create mode 100644 mypy/typeshed/stdlib/@python2/dummy_thread.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/MIMEText.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/_parseaddr.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/base64mime.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/charset.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/encoders.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/feedparser.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/generator.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/header.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/iterators.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/message.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/application.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/audio.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/base.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/image.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/message.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/multipart.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/nonmultipart.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/mime/text.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/parser.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/quoprimime.pyi create mode 100644 mypy/typeshed/stdlib/@python2/email/utils.pyi create mode 100644 mypy/typeshed/stdlib/@python2/encodings/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi create mode 100644 mypy/typeshed/stdlib/@python2/exceptions.pyi create mode 100644 mypy/typeshed/stdlib/@python2/fcntl.pyi create mode 100644 mypy/typeshed/stdlib/@python2/fnmatch.pyi create mode 100644 mypy/typeshed/stdlib/@python2/functools.pyi create mode 100644 mypy/typeshed/stdlib/@python2/future_builtins.pyi create mode 100644 mypy/typeshed/stdlib/@python2/gc.pyi create mode 100644 mypy/typeshed/stdlib/@python2/getopt.pyi create mode 100644 mypy/typeshed/stdlib/@python2/getpass.pyi create mode 100644 mypy/typeshed/stdlib/@python2/gettext.pyi create mode 100644 mypy/typeshed/stdlib/@python2/glob.pyi create mode 100644 mypy/typeshed/stdlib/@python2/gzip.pyi create mode 100644 mypy/typeshed/stdlib/@python2/hashlib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/heapq.pyi create mode 100644 mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi create mode 100644 mypy/typeshed/stdlib/@python2/httplib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/imp.pyi create mode 100644 mypy/typeshed/stdlib/@python2/importlib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/inspect.pyi create mode 100644 mypy/typeshed/stdlib/@python2/io.pyi create mode 100644 mypy/typeshed/stdlib/@python2/itertools.pyi create mode 100644 mypy/typeshed/stdlib/@python2/json.pyi create mode 100644 mypy/typeshed/stdlib/@python2/markupbase.pyi create mode 100644 mypy/typeshed/stdlib/@python2/md5.pyi create mode 100644 mypy/typeshed/stdlib/@python2/mimetools.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/process.pyi create mode 100644 mypy/typeshed/stdlib/@python2/multiprocessing/util.pyi create mode 100644 mypy/typeshed/stdlib/@python2/mutex.pyi create mode 100644 mypy/typeshed/stdlib/@python2/ntpath.pyi create mode 100644 mypy/typeshed/stdlib/@python2/nturl2path.pyi create mode 100644 mypy/typeshed/stdlib/@python2/os/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/os/path.pyi create mode 100644 mypy/typeshed/stdlib/@python2/os2emxpath.pyi create mode 100644 mypy/typeshed/stdlib/@python2/pipes.pyi create mode 100644 mypy/typeshed/stdlib/@python2/platform.pyi create mode 100644 mypy/typeshed/stdlib/@python2/popen2.pyi create mode 100644 mypy/typeshed/stdlib/@python2/posix.pyi create mode 100644 mypy/typeshed/stdlib/@python2/posixpath.pyi create mode 100644 mypy/typeshed/stdlib/@python2/random.pyi create mode 100644 mypy/typeshed/stdlib/@python2/re.pyi create mode 100644 mypy/typeshed/stdlib/@python2/repr.pyi create mode 100644 mypy/typeshed/stdlib/@python2/resource.pyi create mode 100644 mypy/typeshed/stdlib/@python2/rfc822.pyi create mode 100644 mypy/typeshed/stdlib/@python2/robotparser.pyi create mode 100644 mypy/typeshed/stdlib/@python2/runpy.pyi create mode 100644 mypy/typeshed/stdlib/@python2/sets.pyi create mode 100644 mypy/typeshed/stdlib/@python2/sha.pyi create mode 100644 mypy/typeshed/stdlib/@python2/shelve.pyi create mode 100644 mypy/typeshed/stdlib/@python2/shlex.pyi create mode 100644 mypy/typeshed/stdlib/@python2/signal.pyi create mode 100644 mypy/typeshed/stdlib/@python2/smtplib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/spwd.pyi create mode 100644 mypy/typeshed/stdlib/@python2/sre_constants.pyi create mode 100644 mypy/typeshed/stdlib/@python2/sre_parse.pyi create mode 100644 mypy/typeshed/stdlib/@python2/stat.pyi create mode 100644 mypy/typeshed/stdlib/@python2/string.pyi create mode 100644 mypy/typeshed/stdlib/@python2/stringold.pyi create mode 100644 mypy/typeshed/stdlib/@python2/strop.pyi create mode 100644 mypy/typeshed/stdlib/@python2/subprocess.pyi create mode 100644 mypy/typeshed/stdlib/@python2/symbol.pyi create mode 100644 mypy/typeshed/stdlib/@python2/sys.pyi create mode 100644 mypy/typeshed/stdlib/@python2/tempfile.pyi create mode 100644 mypy/typeshed/stdlib/@python2/textwrap.pyi create mode 100644 mypy/typeshed/stdlib/@python2/thread.pyi create mode 100644 mypy/typeshed/stdlib/@python2/toaiff.pyi create mode 100644 mypy/typeshed/stdlib/@python2/tokenize.pyi create mode 100644 mypy/typeshed/stdlib/@python2/types.pyi create mode 100644 mypy/typeshed/stdlib/@python2/typing.pyi create mode 100644 mypy/typeshed/stdlib/@python2/unittest.pyi create mode 100644 mypy/typeshed/stdlib/@python2/urllib.pyi create mode 100644 mypy/typeshed/stdlib/@python2/urllib2.pyi create mode 100644 mypy/typeshed/stdlib/@python2/urlparse.pyi create mode 100644 mypy/typeshed/stdlib/@python2/user.pyi create mode 100644 mypy/typeshed/stdlib/@python2/whichdb.pyi create mode 100644 mypy/typeshed/stdlib/@python2/xmlrpclib.pyi diff --git a/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi new file mode 100644 index 000000000000..28fc4de0409b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi @@ -0,0 +1,41 @@ +import mimetools +import SocketServer +from typing import Any, BinaryIO, Callable, Mapping, Optional, Tuple, Union + +class HTTPServer(SocketServer.TCPServer): + server_name: str + server_port: int + def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + +class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): + client_address: Tuple[str, int] + server: SocketServer.BaseServer + close_connection: bool + command: str + path: str + request_version: str + headers: mimetools.Message + rfile: BinaryIO + wfile: BinaryIO + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, Tuple[str, str]] + def __init__(self, request: bytes, client_address: Tuple[str, int], server: SocketServer.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def send_error(self, code: int, message: Optional[str] = ...) -> None: ... + def send_response(self, code: int, message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi new file mode 100644 index 000000000000..393dcb83217f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi @@ -0,0 +1,6 @@ +import SimpleHTTPServer +from typing import List + +class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): + cgi_directories: List[str] + def do_POST(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ConfigParser.pyi b/mypy/typeshed/stdlib/@python2/ConfigParser.pyi new file mode 100644 index 000000000000..05c90ed2c248 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ConfigParser.pyi @@ -0,0 +1,97 @@ +from _typeshed import SupportsNoArgReadline +from typing import IO, Any, Dict, List, Optional, Sequence, Tuple, Union + +DEFAULTSECT: str +MAX_INTERPOLATION_DEPTH: int + +class Error(Exception): + message: Any + def __init__(self, msg: str = ...) -> None: ... + def _get_message(self) -> None: ... + def _set_message(self, value: str) -> None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + +class NoSectionError(Error): + section: str + def __init__(self, section: str) -> None: ... + +class DuplicateSectionError(Error): + section: str + def __init__(self, section: str) -> None: ... + +class NoOptionError(Error): + section: str + option: str + def __init__(self, option: str, section: str) -> None: ... + +class InterpolationError(Error): + section: str + option: str + msg: str + def __init__(self, option: str, section: str, msg: str) -> None: ... + +class InterpolationMissingOptionError(InterpolationError): + reference: str + def __init__(self, option: str, section: str, rawval: str, reference: str) -> None: ... + +class InterpolationSyntaxError(InterpolationError): ... + +class InterpolationDepthError(InterpolationError): + def __init__(self, option: str, section: str, rawval: str) -> None: ... + +class ParsingError(Error): + filename: str + errors: List[Tuple[Any, Any]] + def __init__(self, filename: str) -> None: ... + def append(self, lineno: Any, line: Any) -> None: ... + +class MissingSectionHeaderError(ParsingError): + lineno: Any + line: Any + def __init__(self, filename: str, lineno: Any, line: Any) -> None: ... + +class RawConfigParser: + _dict: Any + _sections: Dict[Any, Any] + _defaults: Dict[Any, Any] + _optcre: Any + SECTCRE: Any + OPTCRE: Any + OPTCRE_NV: Any + def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... + def defaults(self) -> Dict[Any, Any]: ... + def sections(self) -> List[str]: ... + def add_section(self, section: str) -> None: ... + def has_section(self, section: str) -> bool: ... + def options(self, section: str) -> List[str]: ... + def read(self, filenames: Union[str, Sequence[str]]) -> List[str]: ... + def readfp(self, fp: SupportsNoArgReadline[str], filename: str = ...) -> None: ... + def get(self, section: str, option: str) -> str: ... + def items(self, section: str) -> List[Tuple[Any, Any]]: ... + def _get(self, section: str, conv: type, option: str) -> Any: ... + def getint(self, section: str, option: str) -> int: ... + def getfloat(self, section: str, option: str) -> float: ... + _boolean_states: Dict[str, bool] + def getboolean(self, section: str, option: str) -> bool: ... + def optionxform(self, optionstr: str) -> str: ... + def has_option(self, section: str, option: str) -> bool: ... + def set(self, section: str, option: str, value: Any = ...) -> None: ... + def write(self, fp: IO[str]) -> None: ... + def remove_option(self, section: str, option: Any) -> bool: ... + def remove_section(self, section: str) -> bool: ... + def _read(self, fp: IO[str], fpname: str) -> None: ... + +class ConfigParser(RawConfigParser): + _KEYCRE: Any + def get(self, section: str, option: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> Any: ... + def items(self, section: str, raw: bool = ..., vars: Optional[Dict[Any, Any]] = ...) -> List[Tuple[str, Any]]: ... + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolation_replace(self, match: Any) -> str: ... + +class SafeConfigParser(ConfigParser): + _interpvar_re: Any + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolate_some( + self, option: str, accum: List[Any], rest: str, section: str, map: Dict[Any, Any], depth: int + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/Cookie.pyi b/mypy/typeshed/stdlib/@python2/Cookie.pyi new file mode 100644 index 000000000000..91dd93221c73 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/Cookie.pyi @@ -0,0 +1,40 @@ +from typing import Any, Dict, Optional + +class CookieError(Exception): ... + +class Morsel(Dict[Any, Any]): + key: Any + def __init__(self): ... + def __setitem__(self, K, V): ... + def isReservedKey(self, K): ... + value: Any + coded_value: Any + def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ... + def output(self, attrs: Optional[Any] = ..., header=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def OutputString(self, attrs: Optional[Any] = ...): ... + +class BaseCookie(Dict[Any, Any]): + def value_decode(self, val): ... + def value_encode(self, val): ... + def __init__(self, input: Optional[Any] = ...): ... + def __setitem__(self, key, value): ... + def output(self, attrs: Optional[Any] = ..., header=..., sep=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def load(self, rawdata): ... + +class SimpleCookie(BaseCookie): + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SerialCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SmartCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +Cookie: Any diff --git a/mypy/typeshed/stdlib/@python2/HTMLParser.pyi b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi new file mode 100644 index 000000000000..ebc2735e9c48 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi @@ -0,0 +1,28 @@ +from typing import AnyStr, List, Tuple + +from markupbase import ParserBase + +class HTMLParser(ParserBase): + def __init__(self) -> None: ... + def feed(self, feed: AnyStr) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + def get_starttag_text(self) -> AnyStr: ... + def set_cdata_mode(self, AnyStr) -> None: ... + def clear_cdata_mode(self) -> None: ... + def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_endtag(self, tag: AnyStr): ... + def handle_charref(self, name: AnyStr): ... + def handle_entityref(self, name: AnyStr): ... + def handle_data(self, data: AnyStr): ... + def handle_comment(self, data: AnyStr): ... + def handle_decl(self, decl: AnyStr): ... + def handle_pi(self, data: AnyStr): ... + def unknown_decl(self, data: AnyStr): ... + def unescape(self, s: AnyStr) -> AnyStr: ... + +class HTMLParseError(Exception): + msg: str + lineno: int + offset: int diff --git a/mypy/typeshed/stdlib/@python2/Queue.pyi b/mypy/typeshed/stdlib/@python2/Queue.pyi new file mode 100644 index 000000000000..98dda8722864 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/Queue.pyi @@ -0,0 +1,29 @@ +from collections import deque +from typing import Any, Deque, Generic, Optional, TypeVar + +_T = TypeVar("_T") + +class Empty(Exception): ... +class Full(Exception): ... + +class Queue(Generic[_T]): + maxsize: Any + mutex: Any + not_empty: Any + not_full: Any + all_tasks_done: Any + unfinished_tasks: Any + queue: Deque[Any] # undocumented + def __init__(self, maxsize: int = ...) -> None: ... + def task_done(self) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + +class PriorityQueue(Queue[_T]): ... +class LifoQueue(Queue[_T]): ... diff --git a/mypy/typeshed/stdlib/@python2/SimpleHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/SimpleHTTPServer.pyi new file mode 100644 index 000000000000..7e62b49e8bc6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/SimpleHTTPServer.pyi @@ -0,0 +1,14 @@ +import BaseHTTPServer +from StringIO import StringIO +from typing import IO, Any, AnyStr, Mapping, Optional, Union + +class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): + server_version: str + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + def send_head(self) -> Optional[IO[str]]: ... + def list_directory(self, path: Union[str, unicode]) -> Optional[StringIO[Any]]: ... + def translate_path(self, path: AnyStr) -> AnyStr: ... + def copyfile(self, source: IO[AnyStr], outputfile: IO[AnyStr]): ... + def guess_type(self, path: Union[str, unicode]) -> str: ... + extensions_map: Mapping[str, str] diff --git a/mypy/typeshed/stdlib/@python2/SocketServer.pyi b/mypy/typeshed/stdlib/@python2/SocketServer.pyi new file mode 100644 index 000000000000..b8a2c14ee5e2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/SocketServer.pyi @@ -0,0 +1,115 @@ +import sys +import types +from socket import SocketType +from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Text, Tuple, Type, Union + +class BaseServer: + address_family: int + RequestHandlerClass: Callable[..., BaseRequestHandler] + server_address: Tuple[str, int] + socket: SocketType + allow_reuse_address: bool + request_queue_size: int + socket_type: int + timeout: Optional[float] + def __init__(self, server_address: Any, RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... + def fileno(self) -> int: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = ...) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> Tuple[SocketType, Tuple[str, int]]: ... + def handle_error(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def server_activate(self) -> None: ... + def server_bind(self) -> None: ... + def verify_request(self, request: bytes, client_address: Tuple[str, int]) -> bool: ... + +class TCPServer(BaseServer): + def __init__( + self, + server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... + +class UDPServer(BaseServer): + def __init__( + self, + server_address: Tuple[str, int], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... + +if sys.platform != "win32": + class UnixStreamServer(BaseServer): + def __init__( + self, + server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... + class UnixDatagramServer(BaseServer): + def __init__( + self, + server_address: Union[Text, bytes], + RequestHandlerClass: Callable[..., BaseRequestHandler], + bind_and_activate: bool = ..., + ) -> None: ... + +if sys.platform != "win32": + class ForkingMixIn: + timeout: Optional[float] # undocumented + active_children: Optional[List[int]] # undocumented + max_children: int # undocumented + def collect_children(self) -> None: ... # undocumented + def handle_timeout(self) -> None: ... # undocumented + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + +class ThreadingMixIn: + daemon_threads: bool + def process_request_thread(self, request: bytes, client_address: Tuple[str, int]) -> None: ... # undocumented + def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + +if sys.platform != "win32": + class ForkingTCPServer(ForkingMixIn, TCPServer): ... + class ForkingUDPServer(ForkingMixIn, UDPServer): ... + +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... + +if sys.platform != "win32": + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + +class BaseRequestHandler: + # Those are technically of types, respectively: + # * Union[SocketType, Tuple[bytes, SocketType]] + # * Union[Tuple[str, int], str] + # But there are some concerns that having unions here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + request: Any + client_address: Any + server: BaseServer + def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rbufsize: ClassVar[int] # Undocumented + wbufsize: ClassVar[int] # Undocumented + timeout: ClassVar[Optional[float]] # Undocumented + disable_nagle_algorithm: ClassVar[bool] # Undocumented + connection: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO + +class DatagramRequestHandler(BaseRequestHandler): + packet: SocketType # Undocumented + socket: SocketType # Undocumented + rfile: BinaryIO + wfile: BinaryIO diff --git a/mypy/typeshed/stdlib/@python2/StringIO.pyi b/mypy/typeshed/stdlib/@python2/StringIO.pyi new file mode 100644 index 000000000000..4470b4fc1ad0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/StringIO.pyi @@ -0,0 +1,28 @@ +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List, Optional + +class StringIO(IO[AnyStr], Generic[AnyStr]): + closed: bool + softspace: int + len: int + name: str + def __init__(self, buf: AnyStr = ...) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def next(self) -> AnyStr: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, mode: int = ...) -> int: ... + def tell(self) -> int: ... + def read(self, n: int = ...) -> AnyStr: ... + def readline(self, length: int = ...) -> AnyStr: ... + def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + def flush(self) -> None: ... + def getvalue(self) -> AnyStr: ... + def __enter__(self) -> Any: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> Any: ... + def fileno(self) -> int: ... + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + def writable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/UserDict.pyi b/mypy/typeshed/stdlib/@python2/UserDict.pyi new file mode 100644 index 000000000000..afa07d861a9e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/UserDict.pyi @@ -0,0 +1,53 @@ +from typing import ( + Any, + Container, + Dict, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sized, + Tuple, + TypeVar, + Union, + overload, +) + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): + data: Dict[_KT, _VT] + def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... + # TODO: __iter__ is not available for UserDict + +class IterableUserDict(UserDict[_KT, _VT], Generic[_KT, _VT]): ... + +class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): + def has_key(self, key: _KT) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_KT]: ... + # From typing.Mapping[_KT, _VT] + # (can't inherit because of keys()) + @overload + def get(self, k: _KT) -> Optional[_VT]: ... + @overload + def get(self, k: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ... + 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 __contains__(self, o: Any) -> bool: ... + # From typing.MutableMapping[_KT, _VT] + def clear(self) -> None: ... + def pop(self, k: _KT, default: _VT = ...) -> _VT: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserList.pyi b/mypy/typeshed/stdlib/@python2/UserList.pyi new file mode 100644 index 000000000000..0fc2a31b8651 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/UserList.pyi @@ -0,0 +1,19 @@ +from typing import Iterable, List, MutableSequence, TypeVar, Union, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") + +class UserList(MutableSequence[_T]): + data: List[_T] + def insert(self, index: int, object: _T) -> None: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self: _S, s: slice) -> _S: ... + def sort(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserString.pyi b/mypy/typeshed/stdlib/@python2/UserString.pyi new file mode 100644 index 000000000000..df7bbc363b9f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/UserString.pyi @@ -0,0 +1,75 @@ +import collections +from typing import Any, Iterable, List, MutableSequence, Optional, Sequence, Text, Tuple, TypeVar, Union, overload + +_UST = TypeVar("_UST", bound=UserString) +_MST = TypeVar("_MST", bound=MutableString) + +class UserString(Sequence[UserString]): + data: unicode + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __long__(self) -> long: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self: _UST, i: int) -> _UST: ... + @overload + def __getitem__(self: _UST, s: slice) -> _UST: ... + def __add__(self: _UST, other: Any) -> _UST: ... + def __radd__(self: _UST, other: Any) -> _UST: ... + def __mul__(self: _UST, other: int) -> _UST: ... + def __rmul__(self: _UST, other: int) -> _UST: ... + def __mod__(self: _UST, args: Any) -> _UST: ... + def capitalize(self: _UST) -> _UST: ... + def center(self: _UST, width: int, *args: Any) -> _UST: ... + def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... + def decode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def encode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def endswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... + def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, seq: Iterable[Text]) -> Text: ... + def ljust(self: _UST, width: int, *args: Any) -> _UST: ... + def lower(self: _UST) -> _UST: ... + def lstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... + def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rjust(self: _UST, width: int, *args: Any) -> _UST: ... + def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def rstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def split(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def rsplit(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def splitlines(self, keepends: int = ...) -> List[Text]: ... + def startswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def strip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def swapcase(self: _UST) -> _UST: ... + def title(self: _UST) -> _UST: ... + def translate(self: _UST, *args: Any) -> _UST: ... + def upper(self: _UST) -> _UST: ... + def zfill(self: _UST, width: int) -> _UST: ... + +class MutableString(UserString, MutableSequence[MutableString]): + @overload + def __getitem__(self: _MST, i: int) -> _MST: ... + @overload + def __getitem__(self: _MST, s: slice) -> _MST: ... + def __setitem__(self, index: Union[int, slice], sub: Any) -> None: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def immutable(self) -> UserString: ... + def __iadd__(self: _MST, other: Any) -> _MST: ... + def __imul__(self, n: int) -> _MST: ... + def insert(self, index: int, value: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi new file mode 100644 index 000000000000..0e01b635cf26 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -0,0 +1,1193 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite +from abc import ABCMeta +from ast import mod +from types import CodeType +from typing import ( + AbstractSet, + Any, + AnyStr, + BinaryIO, + ByteString, + Callable, + Container, + Dict, + FrozenSet, + Generic, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + NoReturn, + Optional, + Protocol, + Reversible, + Sequence, + Set, + Sized, + SupportsAbs, + SupportsComplex, + SupportsFloat, + SupportsInt, + Text, + Tuple, + Type, + TypeVar, + Union, + ValuesView, + overload, + runtime_checkable, +) +from typing_extensions import Literal + +class _SupportsIndex(Protocol): + def __index__(self) -> int: ... + +class _SupportsTrunc(Protocol): + def __trunc__(self) -> int: ... + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_TT = TypeVar("_TT", bound="type") +_TBE = TypeVar("_TBE", bound="BaseException") + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... + def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + __weakrefoffset__: int + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + +class super(object): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __new__(cls: Type[_T], x: Union[Text, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc] = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], x: Union[Text, bytes, bytearray], base: int) -> _T: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + def bit_length(self) -> int: ... + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + @overload + def __pow__(self, __x: Literal[2], __modulo: Optional[int] = ...) -> int: ... + @overload + def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __new__(cls: Type[_T], x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> _T: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, __s: str) -> float: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__( + self, x: float, mod: None = ... + ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + def __trunc__(self) -> int: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], real: Union[str, SupportsComplex, _SupportsIndex]) -> _T: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> complex: ... + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex, mod: None = ...) -> complex: ... + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex, mod: None = ...) -> complex: ... + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + +class basestring(metaclass=ABCMeta): ... + +class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + def __len__(self) -> int: ... + # The argument type is incompatible with Sequence + def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + +class _FormatMapMapping(Protocol): + def __getitem__(self, __key: str) -> Any: ... + +class str(Sequence[str], basestring): + def __init__(self, o: object = ...) -> None: ... + def capitalize(self) -> str: ... + def center(self, __width: int, __fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> str: ... + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + @overload + def lstrip(self, __chars: str = ...) -> str: ... + @overload + def lstrip(self, __chars: unicode) -> unicode: ... + @overload + def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + @overload + def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, __chars: str = ...) -> str: ... + @overload + def rstrip(self, __chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, __chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, __width: int) -> str: ... + def __add__(self, s: AnyStr) -> AnyStr: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +bytes = str + +class bytearray(MutableSequence[int], ByteString): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def count(self, __sub: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... + def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def insert(self, __index: int, __item: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable: Iterable[str]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, __prefix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + def translate(self, __table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, __width: int) -> bytearray: ... + @classmethod + def fromhex(cls, __string: str) -> bytearray: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +class memoryview(Sized, Container[str]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + def __init__(self, obj: ReadableBuffer) -> None: ... + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + @overload + def __setitem__(self, s: slice, o: bytes) -> None: ... + @overload + def __setitem__(self, i: int, o: int) -> None: ... + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + +class bool(int): + def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Any + step: Any + stop: Any + @overload + def __init__(self, stop: Any) -> None: ... + @overload + def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... + __hash__: None # type: ignore + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + @overload + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + @overload + def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, __value: Any) -> int: ... + def index(self, __value: Any) -> int: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + __code__: CodeType + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: int = ...) -> _T: ... + def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: int, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + def reverse(self) -> None: ... + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + @classmethod + @overload + 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: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + @overload + def __sub__(self: Set[str], s: AbstractSet[Optional[Text]]) -> Set[_T]: ... + @overload + def __sub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + @overload # type: ignore + def __isub__(self: Set[str], s: AbstractSet[Optional[Text]]) -> Set[_T]: ... + @overload + def __isub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore + +class frozenset(AbstractSet[_T_co], Generic[_T_co]): + def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> FrozenSet[_T_co]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + def next(self) -> Tuple[int, _T]: ... + +class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: _SupportsIndex) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__( + self, + fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ..., + ) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +long = int + +class _NotImplementedType(Any): # type: ignore + # A little weird, but typing the __call__ as NotImplemented makes the error message + # for NotImplemented() much better + __call__: NotImplemented # type: ignore + +NotImplemented: _NotImplementedType + +def abs(__x: SupportsAbs[_T]) -> _T: ... +def all(__iterable: Iterable[object]) -> bool: ... +def any(__iterable: Iterable[object]) -> bool: ... +def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +def bin(__number: Union[int, _SupportsIndex]) -> str: ... +def callable(__obj: object) -> bool: ... +def chr(__i: int) -> str: ... +def cmp(__x: Any, __y: Any) -> int: ... + +_N1 = TypeVar("_N1", bool, int, float, complex) + +def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... + +# This class is to be exported as PathLike from os, +# but we define it here as _PathLike to avoid import cycle issues. +# See https://github.com/python/typeshed/pull/991#issuecomment-288160993 +_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +@runtime_checkable +class _PathLike(Protocol[_AnyStr_co]): + def __fspath__(self) -> _AnyStr_co: ... + +def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +def delattr(__obj: Any, __name: Text) -> None: ... +def dir(__o: object = ...) -> List[str]: ... + +_N2 = TypeVar("_N2", int, float) + +def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def eval( + __source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ... +) -> Any: ... +def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: object = ...) -> NoReturn: ... +@overload +def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore +@overload +def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore +@overload +def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +@overload +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: ... +def globals() -> Dict[str, Any]: ... +def hasattr(__obj: Any, __name: Text) -> bool: ... +def hash(__obj: object) -> int: ... +def hex(__number: Union[int, _SupportsIndex]) -> str: ... +def id(__obj: object) -> int: ... +def input(__prompt: Any = ...) -> Any: ... +def intern(__string: str) -> str: ... +@overload +def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +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: ... +def len(__obj: Sized) -> int: ... +def locals() -> Dict[str, Any]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +@overload +def map( + __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def map( + __func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def map( + __func: None, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[Tuple[Any, ...]]: ... +@overload +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +@overload +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] +) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], +) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> List[_S]: ... +@overload +def map( + __func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[_S]: ... +@overload +def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(__i: Iterator[_T]) -> _T: ... +@overload +def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(__number: Union[int, _SupportsIndex]) -> str: ... +def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... +def ord(__c: Union[Text, bytes]) -> int: ... + +# This is only available after from __future__ import print_function. +def print( + *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ... +) -> None: ... + +_E = TypeVar("_E", contravariant=True) +_M = TypeVar("_M", contravariant=True) + +class _SupportsPow2(Protocol[_E, _T_co]): + def __pow__(self, __other: _E) -> _T_co: ... + +class _SupportsPow3(Protocol[_E, _M, _T_co]): + def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... + +@overload +def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative +@overload +def pow(__base: int, __exp: int, __mod: int) -> int: ... +@overload +def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... +@overload +def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... +@overload +def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... +def quit(code: object = ...) -> NoReturn: ... +def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 +def raw_input(__prompt: Any = ...) -> str: ... +@overload +def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... +@overload +def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... +def reload(__module: Any) -> Any: ... +@overload +def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... +def repr(__obj: object) -> str: ... +@overload +def round(number: float) -> float: ... +@overload +def round(number: float, ndigits: int) -> float: ... +@overload +def round(number: SupportsFloat) -> float: ... +@overload +def round(number: SupportsFloat, ndigits: int) -> float: ... +def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... +def sorted( + __iterable: Iterable[_T], + *, + cmp: Callable[[_T, _T], int] = ..., + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ..., +) -> List[_T]: ... +@overload +def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... +@overload +def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... +def unichr(__i: int) -> unicode: ... +def vars(__object: Any = ...) -> Dict[str, Any]: ... +@overload +def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] +) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def zip( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[Tuple[Any, ...]]: ... +def __import__( + name: Text, + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ..., +) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... + +Ellipsis: ellipsis + +# TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. +_AnyBuffer = TypeVar("_AnyBuffer", str, unicode, bytearray, buffer) + +class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + message: Any + def __init__(self, *args: object) -> None: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... + +class SystemExit(BaseException): + code: int + +class Exception(BaseException): ... +class StopIteration(Exception): ... +class StandardError(Exception): ... + +_StandardError = StandardError + +class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + +class OSError(EnvironmentError): ... +class IOError(EnvironmentError): ... +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): ... +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... + +class SyntaxError(_StandardError): + msg: str + lineno: Optional[int] + offset: Optional[int] + text: Optional[str] + filename: Optional[str] + +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... +class IndexError(LookupError): ... +class KeyError(LookupError): ... +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int + +class NotImplementedError(RuntimeError): ... +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... +class UnicodeError(ValueError): ... + +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeTranslateError(UnicodeError): ... +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... + +class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__( + self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ... + ) -> Optional[bool]: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/_ast.pyi b/mypy/typeshed/stdlib/@python2/_ast.pyi new file mode 100644 index 000000000000..4ca7def60b04 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_ast.pyi @@ -0,0 +1,303 @@ +import typing +from typing import Optional + +__version__: str +PyCF_ONLY_AST: int +_identifier = str + +class AST: + _attributes: typing.Tuple[str, ...] + _fields: typing.Tuple[str, ...] + def __init__(self, *args, **kwargs) -> None: ... + +class mod(AST): ... + +class Module(mod): + body: typing.List[stmt] + +class Interactive(mod): + body: typing.List[stmt] + +class Expression(mod): + body: expr + +class Suite(mod): + body: typing.List[stmt] + +class stmt(AST): + lineno: int + col_offset: int + +class FunctionDef(stmt): + name: _identifier + args: arguments + body: typing.List[stmt] + decorator_list: typing.List[expr] + +class ClassDef(stmt): + name: _identifier + bases: typing.List[expr] + body: typing.List[stmt] + decorator_list: typing.List[expr] + +class Return(stmt): + value: Optional[expr] + +class Delete(stmt): + targets: typing.List[expr] + +class Assign(stmt): + targets: typing.List[expr] + value: expr + +class AugAssign(stmt): + target: expr + op: operator + value: expr + +class Print(stmt): + dest: Optional[expr] + values: typing.List[expr] + nl: bool + +class For(stmt): + target: expr + iter: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class While(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class If(stmt): + test: expr + body: typing.List[stmt] + orelse: typing.List[stmt] + +class With(stmt): + context_expr: expr + optional_vars: Optional[expr] + body: typing.List[stmt] + +class Raise(stmt): + type: Optional[expr] + inst: Optional[expr] + tback: Optional[expr] + +class TryExcept(stmt): + body: typing.List[stmt] + handlers: typing.List[ExceptHandler] + orelse: typing.List[stmt] + +class TryFinally(stmt): + body: typing.List[stmt] + finalbody: typing.List[stmt] + +class Assert(stmt): + test: expr + msg: Optional[expr] + +class Import(stmt): + names: typing.List[alias] + +class ImportFrom(stmt): + module: Optional[_identifier] + names: typing.List[alias] + level: Optional[int] + +class Exec(stmt): + body: expr + globals: Optional[expr] + locals: Optional[expr] + +class Global(stmt): + names: typing.List[_identifier] + +class Expr(stmt): + value: expr + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... +class slice(AST): ... + +_slice = slice # this lets us type the variable named 'slice' below + +class Slice(slice): + lower: Optional[expr] + upper: Optional[expr] + step: Optional[expr] + +class ExtSlice(slice): + dims: typing.List[slice] + +class Index(slice): + value: expr + +class Ellipsis(slice): ... + +class expr(AST): + lineno: int + col_offset: int + +class BoolOp(expr): + op: boolop + values: typing.List[expr] + +class BinOp(expr): + left: expr + op: operator + right: expr + +class UnaryOp(expr): + op: unaryop + operand: expr + +class Lambda(expr): + args: arguments + body: expr + +class IfExp(expr): + test: expr + body: expr + orelse: expr + +class Dict(expr): + keys: typing.List[expr] + values: typing.List[expr] + +class Set(expr): + elts: typing.List[expr] + +class ListComp(expr): + elt: expr + generators: typing.List[comprehension] + +class SetComp(expr): + elt: expr + generators: typing.List[comprehension] + +class DictComp(expr): + key: expr + value: expr + generators: typing.List[comprehension] + +class GeneratorExp(expr): + elt: expr + generators: typing.List[comprehension] + +class Yield(expr): + value: Optional[expr] + +class Compare(expr): + left: expr + ops: typing.List[cmpop] + comparators: typing.List[expr] + +class Call(expr): + func: expr + args: typing.List[expr] + keywords: typing.List[keyword] + starargs: Optional[expr] + kwargs: Optional[expr] + +class Repr(expr): + value: expr + +class Num(expr): + n: float + +class Str(expr): + s: str + +class Attribute(expr): + value: expr + attr: _identifier + ctx: expr_context + +class Subscript(expr): + value: expr + slice: _slice + ctx: expr_context + +class Name(expr): + id: _identifier + ctx: expr_context + +class List(expr): + elts: typing.List[expr] + ctx: expr_context + +class Tuple(expr): + elts: typing.List[expr] + ctx: expr_context + +class expr_context(AST): ... +class AugLoad(expr_context): ... +class AugStore(expr_context): ... +class Del(expr_context): ... +class Load(expr_context): ... +class Param(expr_context): ... +class Store(expr_context): ... +class boolop(AST): ... +class And(boolop): ... +class Or(boolop): ... +class operator(AST): ... +class Add(operator): ... +class BitAnd(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class Div(operator): ... +class FloorDiv(operator): ... +class LShift(operator): ... +class Mod(operator): ... +class Mult(operator): ... +class Pow(operator): ... +class RShift(operator): ... +class Sub(operator): ... +class unaryop(AST): ... +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... +class cmpop(AST): ... +class Eq(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class In(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class NotEq(cmpop): ... +class NotIn(cmpop): ... + +class comprehension(AST): + target: expr + iter: expr + ifs: typing.List[expr] + +class excepthandler(AST): ... + +class ExceptHandler(excepthandler): + type: Optional[expr] + name: Optional[expr] + body: typing.List[stmt] + lineno: int + col_offset: int + +class arguments(AST): + args: typing.List[expr] + vararg: Optional[_identifier] + kwarg: Optional[_identifier] + defaults: typing.List[expr] + +class keyword(AST): + arg: _identifier + value: expr + +class alias(AST): + name: _identifier + asname: Optional[_identifier] diff --git a/mypy/typeshed/stdlib/@python2/_collections.pyi b/mypy/typeshed/stdlib/@python2/_collections.pyi new file mode 100644 index 000000000000..f97b6d5d6dd1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_collections.pyi @@ -0,0 +1,36 @@ +from typing import Any, Callable, Dict, Generic, Iterator, Optional, TypeVar, Union + +_K = TypeVar("_K") +_V = TypeVar("_V") +_T = TypeVar("_T") +_T2 = TypeVar("_T2") + +class defaultdict(Dict[_K, _V]): + default_factory: None + def __init__(self, __default_factory: Callable[[], _V] = ..., init: Any = ...) -> None: ... + def __missing__(self, key: _K) -> _V: ... + def __copy__(self: _T) -> _T: ... + def copy(self: _T) -> _T: ... + +class deque(Generic[_T]): + maxlen: Optional[int] + def __init__(self, iterable: Iterator[_T] = ..., maxlen: int = ...) -> None: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: Any) -> int: ... + def extend(self, iterable: Iterator[_T]) -> None: ... + def extendleft(self, iterable: Iterator[_T]) -> None: ... + def pop(self) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int = ...) -> None: ... + def __contains__(self, o: Any) -> bool: ... + def __copy__(self) -> deque[_T]: ... + def __getitem__(self, i: int) -> _T: ... + def __iadd__(self, other: deque[_T2]) -> deque[Union[_T, _T2]]: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def __reversed__(self) -> Iterator[_T]: ... + def __setitem__(self, i: int, x: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_functools.pyi b/mypy/typeshed/stdlib/@python2/_functools.pyi new file mode 100644 index 000000000000..6143f2a08de7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_functools.pyi @@ -0,0 +1,15 @@ +from typing import Any, Callable, Dict, Iterable, Optional, Tuple, TypeVar, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") +@overload +def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... + +class partial(object): + func: Callable[..., Any] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/_hotshot.pyi b/mypy/typeshed/stdlib/@python2/_hotshot.pyi new file mode 100644 index 000000000000..46c365f4b60b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_hotshot.pyi @@ -0,0 +1,19 @@ +from typing import Any, Dict, Generic, List, Tuple + +def coverage(a: str) -> Any: ... +def logreader(a: str) -> LogReaderType: ... +def profiler(a: str, *args, **kwargs) -> Any: ... +def resolution() -> Tuple[Any, ...]: ... + +class LogReaderType(object): + def close(self) -> None: ... + def fileno(self) -> int: ... + +class ProfilerType(object): + def addinfo(self, a: str, b: str) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def runcall(self, *args, **kwargs) -> Any: ... + def runcode(self, a, b, *args, **kwargs) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi new file mode 100644 index 000000000000..b88f3de0fae3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -0,0 +1,184 @@ +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 + +_bytearray_like = Union[bytearray, mmap] + +DEFAULT_BUFFER_SIZE: int + +class BlockingIOError(IOError): + characters_written: int + +class UnsupportedOperation(ValueError, IOError): ... + +_T = TypeVar("_T") + +class _IOBase(BinaryIO): + @property + def closed(self) -> bool: ... + def _checkClosed(self, msg: Optional[str] = ...) -> None: ... # undocumented + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + # All these methods are concrete here (you can instantiate this) + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + 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 __enter__(self: _T) -> _T: ... + def __exit__( + self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any] + ) -> Optional[bool]: ... + def __iter__(self: _T) -> _T: ... + # The parameter type of writelines[s]() is determined by that of write(): + def writelines(self, lines: Iterable[bytes]) -> None: ... + # The return type of readline[s]() and next() is determined by that of read(): + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def next(self) -> bytes: ... + # These don't actually exist but we need to pretend that it does + # so that this class is concrete. + def write(self, s: bytes) -> int: ... + def read(self, n: int = ...) -> bytes: ... + +class _BufferedIOBase(_IOBase): + def read1(self, n: int) -> bytes: ... + def read(self, size: int = ...) -> bytes: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, s: bytes) -> int: ... + def detach(self) -> _IOBase: ... + +class BufferedRWPair(_BufferedIOBase): + def __init__(self, reader: _RawIOBase, writer: _RawIOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + def __enter__(self) -> BufferedRWPair: ... + +class BufferedRandom(_BufferedIOBase): + mode: str + name: str + raw: _IOBase + def __init__(self, raw: _IOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedReader(_BufferedIOBase): + mode: str + name: str + raw: _IOBase + def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedWriter(_BufferedIOBase): + name: str + raw: _IOBase + mode: str + def __init__(self, raw: _IOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... + +class BytesIO(_BufferedIOBase): + def __init__(self, initial_bytes: bytes = ...) -> None: ... + def __setstate__(self, state: Tuple[Any, ...]) -> None: ... + def __getstate__(self) -> Tuple[Any, ...]: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def write(self, s: bytes) -> int: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + def read1(self, size: int) -> bytes: ... + def next(self) -> bytes: ... + +class _RawIOBase(_IOBase): + def readall(self) -> str: ... + def read(self, n: int = ...) -> str: ... + +class FileIO(_RawIOBase, BytesIO): + mode: str + closefd: bool + def __init__(self, file: Union[str, int], mode: str = ..., closefd: bool = ...) -> None: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, pbuf: str) -> int: ... + +class IncrementalNewlineDecoder(object): + newlines: Union[str, unicode] + def __init__(self, decoder, translate, z=...) -> None: ... + def decode(self, input, final) -> Any: ... + def getstate(self) -> Tuple[Any, int]: ... + def setstate(self, state: Tuple[Any, int]) -> None: ... + def reset(self) -> None: ... + +# Note: In the actual _io.py, _TextIOBase inherits from _IOBase. +class _TextIOBase(TextIO): + errors: Optional[str] + # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses. + newlines: Union[None, unicode, bytes] + encoding: str + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + def close(self) -> None: ... + def detach(self) -> IO[Any]: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> unicode: ... + def read(self, size: int = ...) -> unicode: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> unicode: ... + def readlines(self, hint: int = ...) -> list[unicode]: ... + 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, pbuf: unicode) -> int: ... + def writelines(self, lines: Iterable[unicode]) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__( + self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any] + ) -> Optional[bool]: ... + def __iter__(self: _T) -> _T: ... + +class StringIO(_TextIOBase): + line_buffering: bool + def __init__(self, initial_value: Optional[unicode] = ..., newline: Optional[unicode] = ...) -> None: ... + def __setstate__(self, state: Tuple[Any, ...]) -> None: ... + def __getstate__(self) -> Tuple[Any, ...]: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> unicode: ... + +class TextIOWrapper(_TextIOBase): + name: str + line_buffering: bool + buffer: BinaryIO + _CHUNK_SIZE: int + def __init__( + self, + buffer: IO[Any], + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + line_buffering: bool = ..., + write_through: bool = ..., + ) -> None: ... + +def open( + file: Union[str, unicode, int], + mode: Text = ..., + buffering: int = ..., + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + closefd: bool = ..., +) -> IO[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/_json.pyi b/mypy/typeshed/stdlib/@python2/_json.pyi new file mode 100644 index 000000000000..1c8e0409feaf --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_json.pyi @@ -0,0 +1,7 @@ +from typing import Any, Dict, Generic, List, Tuple + +def encode_basestring_ascii(*args, **kwargs) -> str: ... +def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... + +class Encoder(object): ... +class Scanner(object): ... diff --git a/mypy/typeshed/stdlib/@python2/_md5.pyi b/mypy/typeshed/stdlib/@python2/_md5.pyi new file mode 100644 index 000000000000..96111b70af9b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_md5.pyi @@ -0,0 +1,13 @@ +blocksize: int +digest_size: int + +class MD5Type(object): + name: str + block_size: int + digest_size: int + def copy(self) -> MD5Type: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> MD5Type: ... diff --git a/mypy/typeshed/stdlib/@python2/_sha.pyi b/mypy/typeshed/stdlib/@python2/_sha.pyi new file mode 100644 index 000000000000..7c472562fc17 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_sha.pyi @@ -0,0 +1,15 @@ +blocksize: int +block_size: int +digest_size: int + +class sha(object): # not actually exposed + name: str + block_size: int + digest_size: int + digestsize: int + def copy(self) -> sha: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> sha: ... diff --git a/mypy/typeshed/stdlib/@python2/_sha256.pyi b/mypy/typeshed/stdlib/@python2/_sha256.pyi new file mode 100644 index 000000000000..b6eb47d4bc83 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_sha256.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha224(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha224: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha256(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha256: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_sha512.pyi b/mypy/typeshed/stdlib/@python2/_sha512.pyi new file mode 100644 index 000000000000..b1ca9aee004c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_sha512.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha384(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha384: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha512(object): + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha512: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_socket.pyi b/mypy/typeshed/stdlib/@python2/_socket.pyi new file mode 100644 index 000000000000..61c0def50587 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_socket.pyi @@ -0,0 +1,281 @@ +from typing import IO, Any, Optional, Tuple, Union, overload + +AF_APPLETALK: int +AF_ASH: int +AF_ATMPVC: int +AF_ATMSVC: int +AF_AX25: int +AF_BLUETOOTH: int +AF_BRIDGE: int +AF_DECnet: int +AF_ECONET: int +AF_INET: int +AF_INET6: int +AF_IPX: int +AF_IRDA: int +AF_KEY: int +AF_LLC: int +AF_NETBEUI: int +AF_NETLINK: int +AF_NETROM: int +AF_PACKET: int +AF_PPPOX: int +AF_ROSE: int +AF_ROUTE: int +AF_SECURITY: int +AF_SNA: int +AF_TIPC: int +AF_UNIX: int +AF_UNSPEC: int +AF_WANPIPE: int +AF_X25: int +AI_ADDRCONFIG: int +AI_ALL: int +AI_CANONNAME: int +AI_NUMERICHOST: int +AI_NUMERICSERV: int +AI_PASSIVE: int +AI_V4MAPPED: int +BDADDR_ANY: str +BDADDR_LOCAL: str +BTPROTO_HCI: int +BTPROTO_L2CAP: int +BTPROTO_RFCOMM: int +BTPROTO_SCO: int +EAI_ADDRFAMILY: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_OVERFLOW: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +EAI_SYSTEM: int +EBADF: int +EINTR: int +HCI_DATA_DIR: int +HCI_FILTER: int +HCI_TIME_STAMP: 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_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GRE: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMP: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IP: int +IPPROTO_IPIP: int +IPPROTO_IPV6: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_RAW: int +IPPROTO_ROUTING: int +IPPROTO_RSVP: int +IPPROTO_TCP: int +IPPROTO_TP: int +IPPROTO_UDP: int +IPV6_CHECKSUM: 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_PKTINFO: int +IPV6_RECVDSTOPTS: int +IPV6_RECVHOPLIMIT: int +IPV6_RECVHOPOPTS: 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_V6ONLY: 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_RECVOPTS: int +IP_RECVRETOPTS: int +IP_RETOPTS: int +IP_TOS: int +IP_TTL: int +MSG_CTRUNC: int +MSG_DONTROUTE: int +MSG_DONTWAIT: int +MSG_EOR: int +MSG_OOB: int +MSG_PEEK: int +MSG_TRUNC: int +MSG_WAITALL: int +MethodType: type +NETLINK_DNRTMSG: int +NETLINK_FIREWALL: int +NETLINK_IP6_FW: int +NETLINK_NFLOG: int +NETLINK_ROUTE: int +NETLINK_USERSOCK: int +NETLINK_XFRM: int +NI_DGRAM: int +NI_MAXHOST: int +NI_MAXSERV: int +NI_NAMEREQD: int +NI_NOFQDN: int +NI_NUMERICHOST: int +NI_NUMERICSERV: int +PACKET_BROADCAST: int +PACKET_FASTROUTE: int +PACKET_HOST: int +PACKET_LOOPBACK: int +PACKET_MULTICAST: int +PACKET_OTHERHOST: int +PACKET_OUTGOING: int +PF_PACKET: int +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int +SOCK_DGRAM: int +SOCK_RAW: int +SOCK_RDM: int +SOCK_SEQPACKET: int +SOCK_STREAM: int +SOL_HCI: int +SOL_IP: int +SOL_SOCKET: int +SOL_TCP: int +SOL_TIPC: int +SOL_UDP: int +SOMAXCONN: int +SO_ACCEPTCONN: int +SO_BROADCAST: int +SO_DEBUG: int +SO_DONTROUTE: int +SO_ERROR: int +SO_KEEPALIVE: int +SO_LINGER: int +SO_OOBINLINE: int +SO_RCVBUF: int +SO_RCVLOWAT: int +SO_RCVTIMEO: int +SO_REUSEADDR: int +SO_REUSEPORT: int +SO_SNDBUF: int +SO_SNDLOWAT: int +SO_SNDTIMEO: int +SO_TYPE: int +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 +TCP_CORK: int +TCP_DEFER_ACCEPT: 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 +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 + +# PyCapsule +CAPI: Any + +has_ipv6: bool + +class error(IOError): ... +class gaierror(error): ... +class timeout(error): ... + +class SocketType(object): + family: int + type: int + proto: int + timeout: float + def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... + def accept(self) -> Tuple[SocketType, Tuple[Any, ...]]: ... + def bind(self, address: Tuple[Any, ...]) -> None: ... + def close(self) -> None: ... + def connect(self, address: Tuple[Any, ...]) -> None: ... + def connect_ex(self, address: Tuple[Any, ...]) -> int: ... + def dup(self) -> SocketType: ... + def fileno(self) -> int: ... + def getpeername(self) -> Tuple[Any, ...]: ... + def getsockname(self) -> Tuple[Any, ...]: ... + def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... + def gettimeout(self) -> float: ... + def listen(self, backlog: int) -> None: ... + def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... + def recv(self, buffersize: int, flags: int = ...) -> str: ... + def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... + def recvfrom(self, buffersize: int, flags: int = ...) -> Tuple[Any, ...]: ... + def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... + def send(self, data: str, flags: int = ...) -> int: ... + def sendall(self, data: str, flags: int = ...) -> None: ... + @overload + def sendto(self, data: str, address: Tuple[Any, ...]) -> int: ... + @overload + def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def setsockopt(self, level: int, option: int, value: Union[int, str]) -> None: ... + def settimeout(self, value: Optional[float]) -> None: ... + def shutdown(self, flag: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_sre.pyi b/mypy/typeshed/stdlib/@python2/_sre.pyi new file mode 100644 index 000000000000..263f1da05632 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_sre.pyi @@ -0,0 +1,51 @@ +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, overload + +CODESIZE: int +MAGIC: int +MAXREPEAT: long +copyright: str + +class SRE_Match(object): + def start(self, group: int = ...) -> int: ... + def end(self, group: int = ...) -> int: ... + def expand(self, s: str) -> Any: ... + @overload + def group(self) -> str: ... + @overload + def group(self, group: int = ...) -> Optional[str]: ... + def groupdict(self) -> Dict[int, Optional[str]]: ... + def groups(self) -> Tuple[Optional[str], ...]: ... + def span(self) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + +class SRE_Scanner(object): + pattern: str + def match(self) -> SRE_Match: ... + def search(self) -> SRE_Match: ... + +class SRE_Pattern(object): + pattern: str + flags: int + groups: int + groupindex: Mapping[str, int] + indexgroup: Sequence[int] + def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Union[Tuple[Any, ...], str]]: ... + def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Union[Tuple[Any, ...], str]]: ... + def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... + def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def split(self, source: str, maxsplit: int = ...) -> List[Optional[str]]: ... + def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + +def compile( + pattern: str, + flags: int, + code: List[int], + groups: int = ..., + groupindex: Mapping[str, int] = ..., + indexgroup: Sequence[int] = ..., +) -> SRE_Pattern: ... +def getcodesize() -> int: ... +def getlower(a: int, b: int) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/_struct.pyi b/mypy/typeshed/stdlib/@python2/_struct.pyi new file mode 100644 index 000000000000..316307eaabca --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_struct.pyi @@ -0,0 +1,19 @@ +from typing import Any, AnyStr, Tuple + +class error(Exception): ... + +class Struct(object): + size: int + format: str + def __init__(self, fmt: str) -> None: ... + def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... + def pack(self, *args) -> str: ... + def unpack(self, s: str) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... + +def _clearcache() -> None: ... +def calcsize(fmt: str) -> int: ... +def pack(fmt: AnyStr, obj: Any) -> str: ... +def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... +def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... +def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/_symtable.pyi b/mypy/typeshed/stdlib/@python2/_symtable.pyi new file mode 100644 index 000000000000..5b2370449c31 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_symtable.pyi @@ -0,0 +1,37 @@ +from typing import Dict, List + +CELL: int +DEF_BOUND: int +DEF_FREE: int +DEF_FREE_CLASS: int +DEF_GLOBAL: int +DEF_IMPORT: int +DEF_LOCAL: int +DEF_PARAM: int +FREE: int +GLOBAL_EXPLICIT: int +GLOBAL_IMPLICIT: int +LOCAL: int +OPT_BARE_EXEC: int +OPT_EXEC: int +OPT_IMPORT_STAR: int +SCOPE_MASK: int +SCOPE_OFF: int +TYPE_CLASS: int +TYPE_FUNCTION: int +TYPE_MODULE: int +USE: int + +class _symtable_entry(object): ... + +class symtable(object): + children: List[_symtable_entry] + id: int + lineno: int + name: str + nested: int + optimized: int + symbols: Dict[str, int] + type: int + varnames: List[str] + def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_threading_local.pyi b/mypy/typeshed/stdlib/@python2/_threading_local.pyi new file mode 100644 index 000000000000..481d304578dd --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_threading_local.pyi @@ -0,0 +1,11 @@ +from typing import Any + +class _localbase(object): ... + +class local(_localbase): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __del__(self) -> None: ... + +def _patch(self: local) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_winreg.pyi b/mypy/typeshed/stdlib/@python2/_winreg.pyi new file mode 100644 index 000000000000..f12186cb3d9a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/_winreg.pyi @@ -0,0 +1,97 @@ +import sys +from types import TracebackType +from typing import Any, Optional, Tuple, Type, Union + +_KeyType = Union[HKEYType, int] + +def CloseKey(__hkey: _KeyType) -> None: ... +def ConnectRegistry(__computer_name: Optional[str], __key: _KeyType) -> HKEYType: ... +def CreateKey(__key: _KeyType, __sub_key: Optional[str]) -> HKEYType: ... +def CreateKeyEx(key: _KeyType, sub_key: Optional[str], reserved: int = ..., access: int = ...) -> HKEYType: ... +def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... +def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... +def DeleteValue(__key: _KeyType, __value: str) -> None: ... +def EnumKey(__key: _KeyType, __index: int) -> str: ... +def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... +def ExpandEnvironmentStrings(__str: str) -> str: ... +def FlushKey(__key: _KeyType) -> None: ... +def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... +def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... +def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... +def QueryValue(__key: _KeyType, __sub_key: Optional[str]) -> str: ... +def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... +def SaveKey(__key: _KeyType, __file_name: str) -> None: ... +def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... +def SetValueEx( + __key: _KeyType, __value_name: Optional[str], __reserved: Any, __type: int, __value: Union[str, int] +) -> None: ... # reserved is ignored +def DisableReflectionKey(__key: _KeyType) -> None: ... +def EnableReflectionKey(__key: _KeyType) -> None: ... +def QueryReflectionKey(__key: _KeyType) -> bool: ... + +HKEY_CLASSES_ROOT: int +HKEY_CURRENT_USER: int +HKEY_LOCAL_MACHINE: int +HKEY_USERS: int +HKEY_PERFORMANCE_DATA: int +HKEY_CURRENT_CONFIG: int +HKEY_DYN_DATA: int + +KEY_ALL_ACCESS: int +KEY_WRITE: int +KEY_READ: int +KEY_EXECUTE: int +KEY_QUERY_VALUE: int +KEY_SET_VALUE: int +KEY_CREATE_SUB_KEY: int +KEY_ENUMERATE_SUB_KEYS: int +KEY_NOTIFY: int +KEY_CREATE_LINK: int + +KEY_WOW64_64KEY: int +KEY_WOW64_32KEY: int + +REG_BINARY: int +REG_DWORD: int +REG_DWORD_LITTLE_ENDIAN: int +REG_DWORD_BIG_ENDIAN: int +REG_EXPAND_SZ: int +REG_LINK: int +REG_MULTI_SZ: int +REG_NONE: int +REG_RESOURCE_LIST: int +REG_FULL_RESOURCE_DESCRIPTOR: int +REG_RESOURCE_REQUIREMENTS_LIST: int +REG_SZ: int + +REG_CREATED_NEW_KEY: int # undocumented +REG_LEGAL_CHANGE_FILTER: int # undocumented +REG_LEGAL_OPTION: int # undocumented +REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented +REG_NOTIFY_CHANGE_LAST_SET: int # undocumented +REG_NOTIFY_CHANGE_NAME: int # undocumented +REG_NOTIFY_CHANGE_SECURITY: int # undocumented +REG_NO_LAZY_FLUSH: int # undocumented +REG_OPENED_EXISTING_KEY: int # undocumented +REG_OPTION_BACKUP_RESTORE: int # undocumented +REG_OPTION_CREATE_LINK: int # undocumented +REG_OPTION_NON_VOLATILE: int # undocumented +REG_OPTION_OPEN_LINK: int # undocumented +REG_OPTION_RESERVED: int # undocumented +REG_OPTION_VOLATILE: int # undocumented +REG_REFRESH_HIVE: int # undocumented +REG_WHOLE_HIVE_VOLATILE: int # undocumented + +error = OSError + +# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason +class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> HKEYType: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def Close(self) -> None: ... + def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/abc.pyi b/mypy/typeshed/stdlib/@python2/abc.pyi new file mode 100644 index 000000000000..0bf046a4d877 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/abc.pyi @@ -0,0 +1,31 @@ +import _weakrefset +from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar + +_FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) + +# NOTE: mypy has special processing for ABCMeta and abstractmethod. + +def abstractmethod(funcobj: _FuncT) -> _FuncT: ... + +class ABCMeta(type): + # TODO: FrozenSet + __abstractmethods__: Set[Any] + _abc_cache: _weakrefset.WeakSet[Any] + _abc_invalidation_counter: int + _abc_negative_cache: _weakrefset.WeakSet[Any] + _abc_negative_cache_version: int + _abc_registry: _weakrefset.WeakSet[Any] + def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[Any, Any]) -> None: ... + def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... + def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... + def _dump_registry(cls: ABCMeta, *args: Any, **kwargs: Any) -> None: ... + def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... + +# TODO: The real abc.abstractproperty inherits from "property". +class abstractproperty(object): + def __new__(cls, func: Any) -> Any: ... + __isabstractmethod__: bool + doc: Any + fdel: Any + fget: Any + fset: Any diff --git a/mypy/typeshed/stdlib/@python2/ast.pyi b/mypy/typeshed/stdlib/@python2/ast.pyi new file mode 100644 index 000000000000..a8432dd85978 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ast.pyi @@ -0,0 +1,28 @@ +# Python 2.7 ast + +# Rename typing to _typing, as not to conflict with typing imported +# from _ast below when loaded in an unorthodox way by the Dropbox +# internal Bazel integration. +import typing as _typing +from typing import Any, Iterator, Optional, Union + +from _ast import * +from _ast import AST, Module + +def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ... +def copy_location(new_node: AST, old_node: AST) -> AST: ... +def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... +def fix_missing_locations(node: AST) -> AST: ... +def get_docstring(node: AST, clean: bool = ...) -> str: ... +def increment_lineno(node: AST, n: int = ...) -> AST: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def literal_eval(node_or_string: Union[str, unicode, AST]) -> Any: ... +def walk(node: AST) -> Iterator[AST]: ... + +class NodeVisitor: + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> Optional[AST]: ... diff --git a/mypy/typeshed/stdlib/@python2/atexit.pyi b/mypy/typeshed/stdlib/@python2/atexit.pyi new file mode 100644 index 000000000000..2336bf91149e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/atexit.pyi @@ -0,0 +1,5 @@ +from typing import Any, TypeVar + +_FT = TypeVar("_FT") + +def register(func: _FT, *args: Any, **kargs: Any) -> _FT: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi new file mode 100644 index 000000000000..0e01b635cf26 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -0,0 +1,1193 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite +from abc import ABCMeta +from ast import mod +from types import CodeType +from typing import ( + AbstractSet, + Any, + AnyStr, + BinaryIO, + ByteString, + Callable, + Container, + Dict, + FrozenSet, + Generic, + ItemsView, + Iterable, + Iterator, + KeysView, + List, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + NoReturn, + Optional, + Protocol, + Reversible, + Sequence, + Set, + Sized, + SupportsAbs, + SupportsComplex, + SupportsFloat, + SupportsInt, + Text, + Tuple, + Type, + TypeVar, + Union, + ValuesView, + overload, + runtime_checkable, +) +from typing_extensions import Literal + +class _SupportsIndex(Protocol): + def __index__(self) -> int: ... + +class _SupportsTrunc(Protocol): + def __trunc__(self) -> int: ... + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_TT = TypeVar("_TT", bound="type") +_TBE = TypeVar("_TBE", bound="BaseException") + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... + def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable[..., Any] + def __init__(self, f: Callable[..., Any]) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable[..., Any]: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + __weakrefoffset__: int + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + +class super(object): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __new__(cls: Type[_T], x: Union[Text, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc] = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], x: Union[Text, bytes, bytearray], base: int) -> _T: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + def bit_length(self) -> int: ... + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + @overload + def __pow__(self, __x: Literal[2], __modulo: Optional[int] = ...) -> int: ... + @overload + def __pow__(self, __x: int, __modulo: Optional[int] = ...) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int, mod: Optional[int] = ...) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __new__(cls: Type[_T], x: Union[SupportsFloat, _SupportsIndex, Text, bytes, bytearray] = ...) -> _T: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, __s: str) -> float: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__( + self, x: float, mod: None = ... + ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + def __trunc__(self) -> int: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + @overload + def __new__(cls: Type[_T], real: Union[str, SupportsComplex, _SupportsIndex]) -> _T: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> complex: ... + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex, mod: None = ...) -> complex: ... + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex, mod: None = ...) -> complex: ... + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __nonzero__(self) -> bool: ... + +class basestring(metaclass=ABCMeta): ... + +class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + def __len__(self) -> int: ... + # The argument type is incompatible with Sequence + def __contains__(self, s: Union[unicode, bytes]) -> bool: ... # type: ignore + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + +class _FormatMapMapping(Protocol): + def __getitem__(self, __key: str) -> Any: ... + +class str(Sequence[str], basestring): + def __init__(self, o: object = ...) -> None: ... + def capitalize(self) -> str: ... + def center(self, __width: int, __fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: object, **kwargs: object) -> str: ... + def format_map(self, map: _FormatMapMapping) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + @overload + def lstrip(self, __chars: str = ...) -> str: ... + @overload + def lstrip(self, __chars: unicode) -> unicode: ... + @overload + def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + @overload + def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, __chars: str = ...) -> str: ... + @overload + def rstrip(self, __chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, __chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + def translate(self, __table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, __width: int) -> str: ... + def __add__(self, s: AnyStr) -> AnyStr: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[str, Text]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +bytes = str + +class bytearray(MutableSequence[int], ByteString): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def count(self, __sub: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... + def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def index(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... + def insert(self, __index: int, __item: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, __iterable: Iterable[str]) -> bytearray: ... + def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... + def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, __prefix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... + def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + def translate(self, __table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, __width: int) -> bytearray: ... + @classmethod + def fromhex(cls, __string: str) -> bytearray: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +class memoryview(Sized, Container[str]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + def __init__(self, obj: ReadableBuffer) -> None: ... + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + @overload + def __setitem__(self, s: slice, o: bytes) -> None: ... + @overload + def __setitem__(self, i: int, o: int) -> None: ... + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + +class bool(int): + def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Any + step: Any + stop: Any + @overload + def __init__(self, stop: Any) -> None: ... + @overload + def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... + __hash__: None # type: ignore + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + @overload + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + @overload + def __add__(self, x: Tuple[Any, ...]) -> Tuple[Any, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, __value: Any) -> int: ... + def index(self, __value: Any) -> int: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + __code__: CodeType + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: int = ...) -> _T: ... + def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: int, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + def reverse(self) -> None: ... + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + @classmethod + @overload + 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: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + __hash__: None # type: ignore + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + @overload + def __sub__(self: Set[str], s: AbstractSet[Optional[Text]]) -> Set[_T]: ... + @overload + def __sub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + @overload # type: ignore + def __isub__(self: Set[str], s: AbstractSet[Optional[Text]]) -> Set[_T]: ... + @overload + def __isub__(self, s: AbstractSet[Optional[_T]]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore + +class frozenset(AbstractSet[_T_co], Generic[_T_co]): + def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> FrozenSet[_T_co]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T_co, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + def next(self) -> Tuple[int, _T]: ... + +class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: _SupportsIndex) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__( + self, + fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ..., + ) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +long = int + +class _NotImplementedType(Any): # type: ignore + # A little weird, but typing the __call__ as NotImplemented makes the error message + # for NotImplemented() much better + __call__: NotImplemented # type: ignore + +NotImplemented: _NotImplementedType + +def abs(__x: SupportsAbs[_T]) -> _T: ... +def all(__iterable: Iterable[object]) -> bool: ... +def any(__iterable: Iterable[object]) -> bool: ... +def apply(__func: Callable[..., _T], __args: Optional[Sequence[Any]] = ..., __kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +def bin(__number: Union[int, _SupportsIndex]) -> str: ... +def callable(__obj: object) -> bool: ... +def chr(__i: int) -> str: ... +def cmp(__x: Any, __y: Any) -> int: ... + +_N1 = TypeVar("_N1", bool, int, float, complex) + +def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... + +# This class is to be exported as PathLike from os, +# but we define it here as _PathLike to avoid import cycle issues. +# See https://github.com/python/typeshed/pull/991#issuecomment-288160993 +_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) +@runtime_checkable +class _PathLike(Protocol[_AnyStr_co]): + def __fspath__(self) -> _AnyStr_co: ... + +def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +def delattr(__obj: Any, __name: Text) -> None: ... +def dir(__o: object = ...) -> List[str]: ... + +_N2 = TypeVar("_N2", int, float) + +def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def eval( + __source: Union[Text, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ... +) -> Any: ... +def execfile(__filename: str, __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: object = ...) -> NoReturn: ... +@overload +def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore +@overload +def filter(__function: None, __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... # type: ignore +@overload +def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +@overload +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: ... +def globals() -> Dict[str, Any]: ... +def hasattr(__obj: Any, __name: Text) -> bool: ... +def hash(__obj: object) -> int: ... +def hex(__number: Union[int, _SupportsIndex]) -> str: ... +def id(__obj: object) -> int: ... +def input(__prompt: Any = ...) -> Any: ... +def intern(__string: str) -> str: ... +@overload +def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +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: ... +def len(__obj: Sized) -> int: ... +def locals() -> Dict[str, Any]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +@overload +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +@overload +def map( + __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def map( + __func: None, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def map( + __func: None, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[Tuple[Any, ...]]: ... +@overload +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +@overload +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] +) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], +) -> List[_S]: ... +@overload +def map( + __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> List[_S]: ... +@overload +def map( + __func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[_S]: ... +@overload +def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def max(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def min(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def min(__iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(__i: Iterator[_T]) -> _T: ... +@overload +def next(__i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(__number: Union[int, _SupportsIndex]) -> str: ... +def open(name: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... +def ord(__c: Union[Text, bytes]) -> int: ... + +# This is only available after from __future__ import print_function. +def print( + *values: object, sep: Optional[Text] = ..., end: Optional[Text] = ..., file: Optional[SupportsWrite[Any]] = ... +) -> None: ... + +_E = TypeVar("_E", contravariant=True) +_M = TypeVar("_M", contravariant=True) + +class _SupportsPow2(Protocol[_E, _T_co]): + def __pow__(self, __other: _E) -> _T_co: ... + +class _SupportsPow3(Protocol[_E, _M, _T_co]): + def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... + +@overload +def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative +@overload +def pow(__base: int, __exp: int, __mod: int) -> int: ... +@overload +def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... +@overload +def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... +@overload +def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... +def quit(code: object = ...) -> NoReturn: ... +def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 +def raw_input(__prompt: Any = ...) -> str: ... +@overload +def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... +@overload +def reduce(__function: Callable[[_T, _T], _T], __iterable: Iterable[_T]) -> _T: ... +def reload(__module: Any) -> Any: ... +@overload +def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... +def repr(__obj: object) -> str: ... +@overload +def round(number: float) -> float: ... +@overload +def round(number: float, ndigits: int) -> float: ... +@overload +def round(number: SupportsFloat) -> float: ... +@overload +def round(number: SupportsFloat, ndigits: int) -> float: ... +def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... +def sorted( + __iterable: Iterable[_T], + *, + cmp: Callable[[_T, _T], int] = ..., + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ..., +) -> List[_T]: ... +@overload +def sum(__iterable: Iterable[_T]) -> Union[_T, int]: ... +@overload +def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... +def unichr(__i: int) -> unicode: ... +def vars(__object: Any = ...) -> Dict[str, Any]: ... +@overload +def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +@overload +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] +) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def zip( + __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] +) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def zip( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> List[Tuple[Any, ...]]: ... +def __import__( + name: Text, + globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ..., +) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... + +Ellipsis: ellipsis + +# TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. +_AnyBuffer = TypeVar("_AnyBuffer", str, unicode, bytearray, buffer) + +class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + message: Any + def __init__(self, *args: object) -> None: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... + +class SystemExit(BaseException): + code: int + +class Exception(BaseException): ... +class StopIteration(Exception): ... +class StandardError(Exception): ... + +_StandardError = StandardError + +class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + +class OSError(EnvironmentError): ... +class IOError(EnvironmentError): ... +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): ... +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... + +class SyntaxError(_StandardError): + msg: str + lineno: Optional[int] + offset: Optional[int] + text: Optional[str] + filename: Optional[str] + +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... +class IndexError(LookupError): ... +class KeyError(LookupError): ... +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int + +class NotImplementedError(RuntimeError): ... +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... +class UnicodeError(ValueError): ... + +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, __reason: str) -> None: ... + +class UnicodeTranslateError(UnicodeError): ... +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... + +class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__( + self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ... + ) -> Optional[bool]: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/cPickle.pyi b/mypy/typeshed/stdlib/@python2/cPickle.pyi new file mode 100644 index 000000000000..d8db140cdda1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cPickle.pyi @@ -0,0 +1,26 @@ +from typing import IO, Any, List + +HIGHEST_PROTOCOL: int +compatible_formats: List[str] +format_version: str + +class Pickler: + def __init__(self, file: IO[str], protocol: int = ...) -> None: ... + def dump(self, obj: Any) -> None: ... + def clear_memo(self) -> None: ... + +class Unpickler: + def __init__(self, file: IO[str]) -> None: ... + def load(self) -> Any: ... + def noload(self) -> Any: ... + +def dump(obj: Any, file: IO[str], protocol: int = ...) -> None: ... +def dumps(obj: Any, protocol: int = ...) -> str: ... +def load(file: IO[str]) -> Any: ... +def loads(str: str) -> Any: ... + +class PickleError(Exception): ... +class UnpicklingError(PickleError): ... +class BadPickleGet(UnpicklingError): ... +class PicklingError(PickleError): ... +class UnpickleableError(PicklingError): ... diff --git a/mypy/typeshed/stdlib/@python2/cStringIO.pyi b/mypy/typeshed/stdlib/@python2/cStringIO.pyi new file mode 100644 index 000000000000..603ce3f2403f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cStringIO.pyi @@ -0,0 +1,48 @@ +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 +# directly, so we might as well treat it as abstract in the stub. +class InputType(IO[str], Iterator[str], metaclass=ABCMeta): + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> InputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + +class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): + @property + def softspace(self) -> int: ... + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> OutputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + def write(self, b: Union[str, unicode]) -> int: ... + def writelines(self, lines: Iterable[Union[str, unicode]]) -> None: ... + +@overload +def StringIO() -> OutputType: ... +@overload +def StringIO(s: str) -> InputType: ... diff --git a/mypy/typeshed/stdlib/@python2/collections.pyi b/mypy/typeshed/stdlib/@python2/collections.pyi new file mode 100644 index 000000000000..f6f75cb076c2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/collections.pyi @@ -0,0 +1,129 @@ +from typing import ( + AbstractSet, + Any, + Callable as Callable, + Container as Container, + Dict, + Generic, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + List, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Optional, + Reversible, + Sequence as Sequence, + Sized as Sized, + Tuple, + Type, + TypeVar, + Union, + ValuesView as ValuesView, + overload, +) + +Set = AbstractSet + +_S = TypeVar("_S") +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +# namedtuple is special-cased in the type checker; the initializer is ignored. +def namedtuple( + typename: Union[str, unicode], + field_names: Union[str, unicode, Iterable[Union[str, unicode]]], + verbose: bool = ..., + rename: bool = ..., +) -> Type[Tuple[Any, ...]]: ... + +class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ..., maxlen: int = ...) -> None: ... + @property + def maxlen(self) -> Optional[int]: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: _T) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def extendleft(self, iterable: Iterable[_T]) -> None: ... + def pop(self) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + def __getitem__(self, i: int) -> _T: ... + def __setitem__(self, i: int, x: _T) -> None: ... + def __contains__(self, o: _T) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + +class Counter(Dict[_T, int], Generic[_T]): + @overload + def __init__(self, **kwargs: int) -> None: ... + @overload + def __init__(self, mapping: Mapping[_T, int]) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def copy(self: _S) -> _S: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... + @overload + def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def subtract(self, iterable: Iterable[_T]) -> None: ... + # The Iterable[Tuple[...]] argument type is not actually desirable + # (the tuples will be added as keys, breaking type safety) but + # it's included so that the signature is compatible with + # Dict.update. Not sure if we should use '# type: ignore' instead + # and omit the type from the union. + @overload + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + @overload + def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... + @overload + def update(self, **kwargs: int) -> None: ... + def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... + def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + +class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... + def copy(self: _S) -> _S: ... + def __reversed__(self) -> Iterator[_KT]: ... + +class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + default_factory: Callable[[], _VT] + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + @overload + def __init__( + self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT + ) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + def copy(self: _S) -> _S: ... diff --git a/mypy/typeshed/stdlib/@python2/commands.pyi b/mypy/typeshed/stdlib/@python2/commands.pyi new file mode 100644 index 000000000000..970d6ccf2032 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/commands.pyi @@ -0,0 +1,10 @@ +from typing import AnyStr, Text, Tuple, overload + +def getstatus(file: Text) -> str: ... +def getoutput(cmd: Text) -> str: ... +def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... +@overload +def mk2arg(head: bytes, x: bytes) -> bytes: ... +@overload +def mk2arg(head: Text, x: Text) -> Text: ... +def mkarg(x: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/compileall.pyi b/mypy/typeshed/stdlib/@python2/compileall.pyi new file mode 100644 index 000000000000..59680fd7926d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/compileall.pyi @@ -0,0 +1,16 @@ +from _typeshed import AnyPath +from typing import Any, Optional, Pattern + +# rx can be any object with a 'search' method; once we have Protocols we can change the type +def compile_dir( + dir: AnyPath, + maxlevels: int = ..., + ddir: Optional[AnyPath] = ..., + 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 = ... +) -> int: ... +def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/cookielib.pyi b/mypy/typeshed/stdlib/@python2/cookielib.pyi new file mode 100644 index 000000000000..7405ba91c0ff --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cookielib.pyi @@ -0,0 +1,142 @@ +from typing import Any, Optional + +class Cookie: + version: Any + name: Any + value: Any + port: Any + port_specified: Any + domain: Any + domain_specified: Any + domain_initial_dot: Any + path: Any + path_specified: Any + secure: Any + expires: Any + discard: Any + comment: Any + comment_url: Any + rfc2109: Any + def __init__( + self, + version, + name, + value, + port, + port_specified, + domain, + domain_specified, + domain_initial_dot, + path, + path_specified, + secure, + expires, + discard, + comment, + comment_url, + rest, + rfc2109: bool = ..., + ): ... + def has_nonstandard_attr(self, name): ... + def get_nonstandard_attr(self, name, default: Optional[Any] = ...): ... + def set_nonstandard_attr(self, name, value): ... + def is_expired(self, now: Optional[Any] = ...): ... + +class CookiePolicy: + def set_ok(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class DefaultCookiePolicy(CookiePolicy): + DomainStrictNoDots: Any + DomainStrictNonDomain: Any + DomainRFC2965Match: Any + DomainLiberal: Any + DomainStrict: Any + netscape: Any + rfc2965: Any + rfc2109_as_netscape: Any + hide_cookie2: Any + strict_domain: Any + strict_rfc2965_unverifiable: Any + strict_ns_unverifiable: Any + strict_ns_domain: Any + strict_ns_set_initial_dollar: Any + strict_ns_set_path: Any + def __init__( + self, + blocked_domains: Optional[Any] = ..., + allowed_domains: Optional[Any] = ..., + netscape: bool = ..., + rfc2965: bool = ..., + rfc2109_as_netscape: Optional[Any] = ..., + hide_cookie2: bool = ..., + strict_domain: bool = ..., + strict_rfc2965_unverifiable: bool = ..., + strict_ns_unverifiable: bool = ..., + strict_ns_domain=..., + strict_ns_set_initial_dollar: bool = ..., + strict_ns_set_path: bool = ..., + ): ... + def blocked_domains(self): ... + def set_blocked_domains(self, blocked_domains): ... + def is_blocked(self, domain): ... + def allowed_domains(self): ... + def set_allowed_domains(self, allowed_domains): ... + def is_not_allowed(self, domain): ... + def set_ok(self, cookie, request): ... + def set_ok_version(self, cookie, request): ... + def set_ok_verifiability(self, cookie, request): ... + def set_ok_name(self, cookie, request): ... + def set_ok_path(self, cookie, request): ... + def set_ok_domain(self, cookie, request): ... + def set_ok_port(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def return_ok_version(self, cookie, request): ... + def return_ok_verifiability(self, cookie, request): ... + def return_ok_secure(self, cookie, request): ... + def return_ok_expires(self, cookie, request): ... + def return_ok_port(self, cookie, request): ... + def return_ok_domain(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class Absent: ... + +class CookieJar: + non_word_re: Any + quote_re: Any + strict_domain_re: Any + domain_re: Any + dots_re: Any + magic_re: Any + def __init__(self, policy: Optional[Any] = ...): ... + def set_policy(self, policy): ... + def add_cookie_header(self, request): ... + def make_cookies(self, response, request): ... + def set_cookie_if_ok(self, cookie, request): ... + def set_cookie(self, cookie): ... + def extract_cookies(self, response, request): ... + def clear(self, domain: Optional[Any] = ..., path: Optional[Any] = ..., name: Optional[Any] = ...): ... + def clear_session_cookies(self): ... + def clear_expired_cookies(self): ... + def __iter__(self): ... + def __len__(self): ... + +class LoadError(IOError): ... + +class FileCookieJar(CookieJar): + filename: Any + delayload: Any + def __init__(self, filename: Optional[Any] = ..., delayload: bool = ..., policy: Optional[Any] = ...): ... + def save(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def load(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def revert(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + +class LWPCookieJar(FileCookieJar): + def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented + +MozillaCookieJar = FileCookieJar + +def lwp_cookie_str(cookie: Cookie) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/copy_reg.pyi b/mypy/typeshed/stdlib/@python2/copy_reg.pyi new file mode 100644 index 000000000000..ea07ba410b6d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/copy_reg.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/dircache.pyi b/mypy/typeshed/stdlib/@python2/dircache.pyi new file mode 100644 index 000000000000..fd906f6f2ae1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dircache.pyi @@ -0,0 +1,8 @@ +from typing import List, MutableSequence, Text, Union + +def reset() -> None: ... +def listdir(path: Text) -> List[str]: ... + +opendir = listdir + +def annotate(head: Text, list: Union[MutableSequence[str], MutableSequence[Text], MutableSequence[Union[str, Text]]]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/__init__.pyi b/mypy/typeshed/stdlib/@python2/distutils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/archive_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/archive_util.pyi new file mode 100644 index 000000000000..0e94d3818ae4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/archive_util.pyi @@ -0,0 +1,12 @@ +from typing import Optional + +def make_archive( + base_name: str, + format: str, + root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., + verbose: int = ..., + dry_run: int = ..., +) -> str: ... +def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., verbose: int = ..., dry_run: int = ...) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., dry_run: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/bcppcompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/bcppcompiler.pyi new file mode 100644 index 000000000000..3e432f94b525 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/bcppcompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class BCPPCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi new file mode 100644 index 000000000000..831311d2cb52 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi @@ -0,0 +1,150 @@ +from typing import Any, Callable, List, Optional, Tuple, Union + +_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] + +def gen_lib_options( + compiler: CCompiler, library_dirs: List[str], runtime_library_dirs: List[str], libraries: List[str] +) -> List[str]: ... +def gen_preprocess_options(macros: List[_Macro], include_dirs: List[str]) -> List[str]: ... +def get_default_compiler(osname: Optional[str] = ..., platform: Optional[str] = ...) -> str: ... +def new_compiler( + plat: Optional[str] = ..., compiler: Optional[str] = ..., verbose: int = ..., dry_run: int = ..., force: int = ... +) -> CCompiler: ... +def show_compilers() -> None: ... + +class CCompiler: + dry_run: bool + force: bool + verbose: bool + output_dir: Optional[str] + macros: List[_Macro] + include_dirs: List[str] + libraries: List[str] + library_dirs: List[str] + runtime_library_dirs: List[str] + objects: List[str] + def __init__(self, verbose: int = ..., dry_run: int = ..., force: int = ...) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: List[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: List[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: List[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: List[str]) -> None: ... + def define_macro(self, name: str, value: Optional[str] = ...) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: List[str]) -> None: ... + def detect_language(self, sources: Union[str, List[str]]) -> Optional[str]: ... + def find_library_file(self, dirs: List[str], lib: str, debug: bool = ...) -> Optional[str]: ... + def has_function( + self, + funcname: str, + includes: Optional[List[str]] = ..., + include_dirs: Optional[List[str]] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + ) -> bool: ... + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def set_executables(self, **args: str) -> None: ... + def compile( + self, + sources: List[str], + output_dir: Optional[str] = ..., + macros: Optional[_Macro] = ..., + include_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + depends: Optional[List[str]] = ..., + ) -> List[str]: ... + def create_static_lib( + self, + objects: List[str], + output_libname: str, + output_dir: Optional[str] = ..., + debug: bool = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link( + self, + target_desc: str, + objects: List[str], + output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_executable( + self, + objects: List[str], + output_progname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_shared_lib( + self, + objects: List[str], + output_libname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def link_shared_object( + self, + objects: List[str], + output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ..., + ) -> None: ... + def preprocess( + self, + source: str, + output_file: Optional[str] = ..., + macros: Optional[List[_Macro]] = ..., + include_dirs: Optional[List[str]] = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + ) -> None: ... + def executable_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... + def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... + def object_filenames(self, source_filenames: List[str], strip_dir: int = ..., output_dir: str = ...) -> List[str]: ... + def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... + def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: Optional[str] = ..., level: int = ...) -> None: ... + def spawn(self, cmd: List[str]) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def move_file(self, src: str, dst: str) -> str: ... + def announce(self, msg: str, level: int = ...) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi new file mode 100644 index 000000000000..b888c189f932 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi @@ -0,0 +1,67 @@ +from abc import abstractmethod +from distutils.dist import Distribution +from typing import Any, Callable, Iterable, List, Optional, Text, Tuple, Union + +class Command: + sub_commands: List[Tuple[str, Optional[Callable[[Command], bool]]]] + def __init__(self, dist: Distribution) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + def announce(self, msg: Text, level: int = ...) -> None: ... + def debug_print(self, msg: Text) -> None: ... + def ensure_string(self, option: str, default: Optional[str] = ...) -> None: ... + def ensure_string_list(self, option: Union[str, List[str]]) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... + def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... + def reinitialize_command(self, command: Union[Command, Text], reinit_subcommands: int = ...) -> Command: ... + def run_command(self, command: Text) -> None: ... + def get_sub_commands(self) -> List[str]: ... + def warn(self, msg: Text) -> None: ... + def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[Text] = ..., level: int = ...) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def copy_file( + self, + infile: str, + outfile: str, + preserve_mode: int = ..., + preserve_times: int = ..., + link: Optional[str] = ..., + level: Any = ..., + ) -> Tuple[str, bool]: ... # level is not used + def copy_tree( + self, + infile: str, + outfile: str, + preserve_mode: int = ..., + preserve_times: int = ..., + preserve_symlinks: int = ..., + level: Any = ..., + ) -> List[str]: ... # level is not used + def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used + def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used + def make_archive( + self, + base_name: str, + format: str, + root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., + owner: Optional[str] = ..., + group: Optional[str] = ..., + ) -> str: ... + def make_file( + self, + infiles: Union[str, List[str], Tuple[str]], + outfile: str, + func: Callable[..., Any], + args: List[Any], + exec_msg: Optional[str] = ..., + skip_msg: Optional[str] = ..., + level: Any = ..., + ) -> None: ... # level is not used diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/__init__.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_dumb.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_dumb.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi new file mode 100644 index 000000000000..a761792018a9 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi @@ -0,0 +1,6 @@ +from distutils.cmd import Command + +class bdist_msi(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_packager.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_packager.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_rpm.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_wininst.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_wininst.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/build.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/build.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/build_clib.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/build_clib.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/build_ext.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/build_ext.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/build_py.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/build_py.pyi new file mode 100644 index 000000000000..a29a1f3a12a7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/build_py.pyi @@ -0,0 +1,6 @@ +from distutils.cmd import Command + +class build_py(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/build_scripts.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/build_scripts.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/check.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/check.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/clean.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/clean.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi new file mode 100644 index 000000000000..6b57a64b48b1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi @@ -0,0 +1,87 @@ +from distutils import log as log +from distutils.ccompiler import CCompiler +from distutils.core import Command as Command +from distutils.errors import DistutilsExecError as DistutilsExecError +from distutils.sysconfig import customize_compiler as customize_compiler +from typing import Dict, List, Optional, Pattern, Sequence, Tuple, Union + +LANG_EXT: Dict[str, str] + +class config(Command): + description: str = ... + # Tuple is full name, short name, description + user_options: Sequence[Tuple[str, Optional[str], str]] = ... + compiler: Optional[Union[str, CCompiler]] = ... + cc: Optional[str] = ... + include_dirs: Optional[Sequence[str]] = ... + libraries: Optional[Sequence[str]] = ... + library_dirs: Optional[Sequence[str]] = ... + noisy: int = ... + dump_source: int = ... + temp_files: Sequence[str] = ... + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def try_cpp( + self, + body: Optional[str] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def search_cpp( + self, + pattern: Union[Pattern[str], str], + body: Optional[str] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def try_compile( + self, body: str, headers: Optional[Sequence[str]] = ..., include_dirs: Optional[Sequence[str]] = ..., lang: str = ... + ) -> bool: ... + def try_link( + self, + body: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def try_run( + self, + body: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + def check_func( + self, + func: str, + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + libraries: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + decl: int = ..., + call: int = ..., + ) -> bool: ... + def check_lib( + self, + library: str, + library_dirs: Optional[Sequence[str]] = ..., + headers: Optional[Sequence[str]] = ..., + include_dirs: Optional[Sequence[str]] = ..., + other_libraries: List[str] = ..., + ) -> bool: ... + def check_header( + self, + header: str, + include_dirs: Optional[Sequence[str]] = ..., + library_dirs: Optional[Sequence[str]] = ..., + lang: str = ..., + ) -> bool: ... + +def dump_file(filename: str, head: Optional[str] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install.pyi new file mode 100644 index 000000000000..dc6d96b82a62 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/install.pyi @@ -0,0 +1,12 @@ +from distutils.cmd import Command +from typing import Optional, Text + +class install(Command): + user: bool + prefix: Optional[Text] + home: Optional[Text] + root: Optional[Text] + install_lib: Optional[Text] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_data.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_data.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi new file mode 100644 index 000000000000..80ffb19bda74 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi @@ -0,0 +1,10 @@ +from distutils.cmd import Command +from typing import ClassVar, List, Optional, Tuple + +class install_egg_info(Command): + description: ClassVar[str] + user_options: ClassVar[List[Tuple[str, Optional[str], str]]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_outputs(self) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_headers.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_headers.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_lib.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_lib.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_scripts.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/register.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/register.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/sdist.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/sdist.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi new file mode 100644 index 000000000000..c49a4e5b4937 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi @@ -0,0 +1,8 @@ +from distutils.config import PyPIRCCommand +from typing import ClassVar, List, Optional, Tuple + +class upload(PyPIRCCommand): + description: ClassVar[str] + boolean_options: ClassVar[List[str]] + def run(self) -> None: ... + def upload_file(self, command, pyversion, filename) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/config.pyi b/mypy/typeshed/stdlib/@python2/distutils/config.pyi new file mode 100644 index 000000000000..e60507e0b65a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/config.pyi @@ -0,0 +1,17 @@ +from abc import abstractmethod +from distutils.cmd import Command +from typing import ClassVar, List, Optional, Tuple + +DEFAULT_PYPIRC: str + +class PyPIRCCommand(Command): + DEFAULT_REPOSITORY: ClassVar[str] + DEFAULT_REALM: ClassVar[str] + repository: None + realm: None + user_options: ClassVar[List[Tuple[str, Optional[str], str]]] + boolean_options: ClassVar[List[str]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/core.pyi b/mypy/typeshed/stdlib/@python2/distutils/core.pyi new file mode 100644 index 000000000000..9a3fa70fd381 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/core.pyi @@ -0,0 +1,48 @@ +from distutils.cmd import Command as Command +from distutils.dist import Distribution as Distribution +from distutils.extension import Extension as Extension +from typing import Any, List, Mapping, Optional, Tuple, Type, Union + +def setup( + *, + name: str = ..., + version: str = ..., + description: str = ..., + long_description: str = ..., + author: str = ..., + author_email: str = ..., + maintainer: str = ..., + maintainer_email: str = ..., + url: str = ..., + download_url: str = ..., + packages: List[str] = ..., + py_modules: List[str] = ..., + scripts: List[str] = ..., + ext_modules: List[Extension] = ..., + classifiers: List[str] = ..., + distclass: Type[Distribution] = ..., + script_name: str = ..., + script_args: List[str] = ..., + options: Mapping[str, Any] = ..., + license: str = ..., + keywords: Union[List[str], str] = ..., + platforms: Union[List[str], str] = ..., + cmdclass: Mapping[str, Type[Command]] = ..., + data_files: List[Tuple[str, List[str]]] = ..., + package_dir: Mapping[str, str] = ..., + obsoletes: List[str] = ..., + provides: List[str] = ..., + requires: List[str] = ..., + command_packages: List[str] = ..., + command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ..., + package_data: Mapping[str, List[str]] = ..., + include_package_data: bool = ..., + libraries: List[str] = ..., + headers: List[str] = ..., + ext_package: str = ..., + include_dirs: List[str] = ..., + password: str = ..., + fullname: str = ..., + **attrs: Any, +) -> None: ... +def run_setup(script_name: str, script_args: Optional[List[str]] = ..., stop_after: str = ...) -> Distribution: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/cygwinccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..1f85b254860b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/cygwinccompiler.pyi @@ -0,0 +1,4 @@ +from distutils.unixccompiler import UnixCCompiler + +class CygwinCCompiler(UnixCCompiler): ... +class Mingw32CCompiler(CygwinCCompiler): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/debug.pyi b/mypy/typeshed/stdlib/@python2/distutils/debug.pyi new file mode 100644 index 000000000000..098dc3dee246 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/debug.pyi @@ -0,0 +1 @@ +DEBUG: bool diff --git a/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi new file mode 100644 index 000000000000..6f779d540e5e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi @@ -0,0 +1,5 @@ +from typing import List, Tuple + +def newer(source: str, target: str) -> bool: ... +def newer_pairwise(sources: List[str], targets: List[str]) -> List[Tuple[str, str]]: ... +def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi new file mode 100644 index 000000000000..4c4a22102558 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi @@ -0,0 +1,15 @@ +from typing import List + +def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> List[str]: ... +def create_tree(base_dir: str, files: List[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... +def copy_tree( + src: str, + dst: str, + preserve_mode: int = ..., + preserve_times: int = ..., + preserve_symlinks: int = ..., + update: int = ..., + verbose: int = ..., + dry_run: int = ..., +) -> List[str]: ... +def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dist.pyi b/mypy/typeshed/stdlib/@python2/distutils/dist.pyi new file mode 100644 index 000000000000..685423bda6da --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/dist.pyi @@ -0,0 +1,9 @@ +from distutils.cmd import Command +from typing import Any, Dict, Iterable, Mapping, Optional, Text, Tuple, Type + +class Distribution: + cmdclass: Dict[str, Type[Command]] + def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ... + def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... + def parse_config_files(self, filenames: Optional[Iterable[Text]] = ...) -> None: ... + def get_command_obj(self, command: str, create: bool = ...) -> Optional[Command]: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/emxccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/emxccompiler.pyi new file mode 100644 index 000000000000..19e4023fef04 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/emxccompiler.pyi @@ -0,0 +1,3 @@ +from distutils.unixccompiler import UnixCCompiler + +class EMXCCompiler(UnixCCompiler): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/errors.pyi b/mypy/typeshed/stdlib/@python2/distutils/errors.pyi new file mode 100644 index 000000000000..e483362bfbf1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/errors.pyi @@ -0,0 +1,19 @@ +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... +class CCompilerError(Exception): ... +class PreprocessError(CCompilerError): ... +class CompileError(CCompilerError): ... +class LibError(CCompilerError): ... +class LinkError(CCompilerError): ... +class UnknownFileError(CCompilerError): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/extension.pyi b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi new file mode 100644 index 000000000000..02c1f55617b3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi @@ -0,0 +1,21 @@ +from typing import List, Optional, Tuple + +class Extension: + def __init__( + self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + swig_opts: Optional[str] = ..., # undocumented + depends: List[str] = ..., + language: str = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi new file mode 100644 index 000000000000..8eb4c416fa28 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi @@ -0,0 +1,21 @@ +from typing import Any, List, Mapping, Optional, Tuple, Union, overload + +_Option = Tuple[str, Optional[str], str] +_GR = Tuple[List[str], OptionDummy] + +def fancy_getopt( + options: List[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: Optional[List[str]] +) -> Union[List[str], _GR]: ... +def wrap_text(text: str, width: int) -> List[str]: ... + +class FancyGetopt: + def __init__(self, option_table: Optional[List[_Option]] = ...) -> None: ... + # TODO kinda wrong, `getopt(object=object())` is invalid + @overload + def getopt(self, args: Optional[List[str]] = ...) -> _GR: ... + @overload + def getopt(self, args: Optional[List[str]], object: Any) -> List[str]: ... + def get_option_order(self) -> List[Tuple[str, str]]: ... + def generate_help(self, header: Optional[str] = ...) -> List[str]: ... + +class OptionDummy: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi new file mode 100644 index 000000000000..018339733df0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi @@ -0,0 +1,14 @@ +from typing import Optional, Sequence, Tuple + +def copy_file( + src: str, + dst: str, + preserve_mode: bool = ..., + preserve_times: bool = ..., + update: bool = ..., + link: Optional[str] = ..., + verbose: bool = ..., + dry_run: bool = ..., +) -> Tuple[str, str]: ... +def move_file(src: str, dst: str, verbose: bool = ..., dry_run: bool = ...) -> str: ... +def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/filelist.pyi b/mypy/typeshed/stdlib/@python2/distutils/filelist.pyi new file mode 100644 index 000000000000..8fa55d09d265 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/filelist.pyi @@ -0,0 +1 @@ +class FileList: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/log.pyi b/mypy/typeshed/stdlib/@python2/distutils/log.pyi new file mode 100644 index 000000000000..668adaab99d1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/log.pyi @@ -0,0 +1,25 @@ +from typing import Any, Text + +DEBUG: int +INFO: int +WARN: int +ERROR: int +FATAL: int + +class Log: + def __init__(self, threshold: int = ...) -> None: ... + def log(self, level: int, msg: Text, *args: Any) -> None: ... + def debug(self, msg: Text, *args: Any) -> None: ... + def info(self, msg: Text, *args: Any) -> None: ... + def warn(self, msg: Text, *args: Any) -> None: ... + def error(self, msg: Text, *args: Any) -> None: ... + def fatal(self, msg: Text, *args: Any) -> None: ... + +def log(level: int, msg: Text, *args: Any) -> None: ... +def debug(msg: Text, *args: Any) -> None: ... +def info(msg: Text, *args: Any) -> None: ... +def warn(msg: Text, *args: Any) -> None: ... +def error(msg: Text, *args: Any) -> None: ... +def fatal(msg: Text, *args: Any) -> None: ... +def set_threshold(level: int) -> int: ... +def set_verbosity(v: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/msvccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/msvccompiler.pyi new file mode 100644 index 000000000000..80872a6b739f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/msvccompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class MSVCCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi new file mode 100644 index 000000000000..e12eae99bf29 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi @@ -0,0 +1,4 @@ +from typing import List, Optional + +def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... +def find_executable(executable: str, path: Optional[str] = ...) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/@python2/distutils/sysconfig.pyi new file mode 100644 index 000000000000..9061db75ccf1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/sysconfig.pyi @@ -0,0 +1,14 @@ +from distutils.ccompiler import CCompiler +from typing import Mapping, Optional, Union + +PREFIX: str +EXEC_PREFIX: str + +def get_config_var(name: str) -> Union[int, str, None]: ... +def get_config_vars(*args: str) -> Mapping[str, Union[int, str]]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool = ..., prefix: Optional[str] = ...) -> str: ... +def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., prefix: Optional[str] = ...) -> str: ... +def customize_compiler(compiler: CCompiler) -> None: ... +def set_python_build() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi new file mode 100644 index 000000000000..9872a1f25751 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi @@ -0,0 +1,21 @@ +from typing import IO, List, Optional, Tuple, Union + +class TextFile: + def __init__( + self, + filename: Optional[str] = ..., + file: Optional[IO[str]] = ..., + *, + strip_comments: bool = ..., + lstrip_ws: bool = ..., + rstrip_ws: bool = ..., + skip_blanks: bool = ..., + join_lines: bool = ..., + collapse_join: bool = ..., + ) -> None: ... + def open(self, filename: str) -> None: ... + def close(self) -> None: ... + def warn(self, msg: str, line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... + def readline(self) -> Optional[str]: ... + def readlines(self) -> List[str]: ... + def unreadline(self, line: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/unixccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/unixccompiler.pyi new file mode 100644 index 000000000000..e1d443471af3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/unixccompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class UnixCCompiler(CCompiler): ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/util.pyi b/mypy/typeshed/stdlib/@python2/distutils/util.pyi new file mode 100644 index 000000000000..0086d726af65 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/util.pyi @@ -0,0 +1,23 @@ +from typing import Any, Callable, List, Mapping, Optional, Tuple + +def get_platform() -> str: ... +def convert_path(pathname: str) -> str: ... +def change_root(new_root: str, pathname: str) -> str: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... +def split_quoted(s: str) -> List[str]: ... +def execute( + func: Callable[..., None], args: Tuple[Any, ...], msg: Optional[str] = ..., verbose: bool = ..., dry_run: bool = ... +) -> None: ... +def strtobool(val: str) -> bool: ... +def byte_compile( + py_files: List[str], + optimize: int = ..., + force: bool = ..., + prefix: Optional[str] = ..., + base_dir: Optional[str] = ..., + verbose: bool = ..., + dry_run: bool = ..., + direct: Optional[bool] = ..., +) -> None: ... +def rfc822_escape(header: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/version.pyi b/mypy/typeshed/stdlib/@python2/distutils/version.pyi new file mode 100644 index 000000000000..f55d01d1a172 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/distutils/version.pyi @@ -0,0 +1,33 @@ +from abc import abstractmethod +from typing import Optional, Pattern, Text, Tuple, TypeVar, Union + +_T = TypeVar("_T", bound=Version) + +class Version: + def __repr__(self) -> str: ... + @abstractmethod + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + @abstractmethod + def parse(self: _T, vstring: Text) -> _T: ... + @abstractmethod + def __str__(self) -> str: ... + @abstractmethod + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class StrictVersion(Version): + version_re: Pattern[str] + version: Tuple[int, int, int] + prerelease: Optional[Tuple[Text, int]] + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class LooseVersion(Version): + component_re: Pattern[str] + vstring: Text + version: Tuple[Union[Text, int], ...] + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/dummy_thread.pyi b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi new file mode 100644 index 000000000000..28041002a708 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +class error(Exception): + def __init__(self, *args: Any) -> None: ... + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/MIMEText.pyi b/mypy/typeshed/stdlib/@python2/email/MIMEText.pyi new file mode 100644 index 000000000000..3b059778aa66 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/MIMEText.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/__init__.pyi b/mypy/typeshed/stdlib/@python2/email/__init__.pyi new file mode 100644 index 000000000000..384d9567f7b0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/__init__.pyi @@ -0,0 +1,6 @@ +from typing import IO, Any, AnyStr + +def message_from_string(s: AnyStr, *args, **kwargs): ... +def message_from_bytes(s: str, *args, **kwargs): ... +def message_from_file(fp: IO[AnyStr], *args, **kwargs): ... +def message_from_binary_file(fp: IO[str], *args, **kwargs): ... diff --git a/mypy/typeshed/stdlib/@python2/email/_parseaddr.pyi b/mypy/typeshed/stdlib/@python2/email/_parseaddr.pyi new file mode 100644 index 000000000000..424ade705f77 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/_parseaddr.pyi @@ -0,0 +1,40 @@ +from typing import Any, Optional + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... +def quote(str): ... + +class AddrlistClass: + specials: Any + pos: Any + LWS: Any + CR: Any + FWS: Any + atomends: Any + phraseends: Any + field: Any + commentlist: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: bool = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... diff --git a/mypy/typeshed/stdlib/@python2/email/base64mime.pyi b/mypy/typeshed/stdlib/@python2/email/base64mime.pyi new file mode 100644 index 000000000000..fc6552974e60 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/base64mime.pyi @@ -0,0 +1,11 @@ +def base64_len(s: bytes) -> int: ... +def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ... +def encode(s, binary=..., maxlinelen=..., eol=...): ... + +body_encode = encode +encodestring = encode + +def decode(s, convert_eols=...): ... + +body_decode = decode +decodestring = decode diff --git a/mypy/typeshed/stdlib/@python2/email/charset.pyi b/mypy/typeshed/stdlib/@python2/email/charset.pyi new file mode 100644 index 000000000000..88b5f88d1843 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/charset.pyi @@ -0,0 +1,26 @@ +def add_charset(charset, header_enc=..., body_enc=..., output_charset=...) -> None: ... +def add_alias(alias, canonical) -> None: ... +def add_codec(charset, codecname) -> None: ... + +QP: int # undocumented +BASE64: int # undocumented +SHORTEST: int # undocumented + +class Charset: + input_charset = ... + header_encoding = ... + body_encoding = ... + output_charset = ... + input_codec = ... + output_codec = ... + def __init__(self, input_charset=...) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def get_body_encoding(self): ... + def convert(self, s): ... + def to_splittable(self, s): ... + def from_splittable(self, ustr, to_output: bool = ...): ... + def get_output_charset(self): ... + def encoded_header_len(self, s): ... + def header_encode(self, s, convert: bool = ...): ... + def body_encode(self, s, convert: bool = ...): ... diff --git a/mypy/typeshed/stdlib/@python2/email/encoders.pyi b/mypy/typeshed/stdlib/@python2/email/encoders.pyi new file mode 100644 index 000000000000..5670cbaf08ed --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/encoders.pyi @@ -0,0 +1,4 @@ +def encode_base64(msg) -> None: ... +def encode_quopri(msg) -> None: ... +def encode_7or8bit(msg) -> None: ... +def encode_noop(msg) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/feedparser.pyi b/mypy/typeshed/stdlib/@python2/email/feedparser.pyi new file mode 100644 index 000000000000..fb2aa9f5ff1b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/feedparser.pyi @@ -0,0 +1,17 @@ +class BufferedSubFile: + def __init__(self) -> None: ... + def push_eof_matcher(self, pred) -> None: ... + def pop_eof_matcher(self): ... + def close(self) -> None: ... + def readline(self): ... + def unreadline(self, line) -> None: ... + def push(self, data): ... + def pushlines(self, lines) -> None: ... + def is_closed(self): ... + def __iter__(self): ... + def next(self): ... + +class FeedParser: + def __init__(self, _factory=...) -> None: ... + def feed(self, data) -> None: ... + def close(self): ... diff --git a/mypy/typeshed/stdlib/@python2/email/generator.pyi b/mypy/typeshed/stdlib/@python2/email/generator.pyi new file mode 100644 index 000000000000..a5f5983b48e6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/generator.pyi @@ -0,0 +1,8 @@ +class Generator: + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ...) -> None: ... + def write(self, s) -> None: ... + def flatten(self, msg, unixfrom: bool = ...) -> None: ... + def clone(self, fp): ... + +class DecodedGenerator(Generator): + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ..., fmt=...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/header.pyi b/mypy/typeshed/stdlib/@python2/email/header.pyi new file mode 100644 index 000000000000..429ee16d8917 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/header.pyi @@ -0,0 +1,10 @@ +def decode_header(header): ... +def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ... + +class Header: + def __init__(self, s=..., charset=..., maxlinelen=..., header_name=..., continuation_ws=..., errors=...) -> None: ... + def __unicode__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def append(self, s, charset=..., errors=...) -> None: ... + def encode(self, splitchars=...): ... diff --git a/mypy/typeshed/stdlib/@python2/email/iterators.pyi b/mypy/typeshed/stdlib/@python2/email/iterators.pyi new file mode 100644 index 000000000000..5002644117a4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/iterators.pyi @@ -0,0 +1,5 @@ +from typing import Any, Generator + +def walk(self) -> Generator[Any, Any, Any]: ... +def body_line_iterator(msg, decode: bool = ...) -> Generator[Any, Any, Any]: ... +def typed_subpart_iterator(msg, maintype=..., subtype=...) -> Generator[Any, Any, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/email/message.pyi b/mypy/typeshed/stdlib/@python2/email/message.pyi new file mode 100644 index 000000000000..642bba7c0102 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/message.pyi @@ -0,0 +1,45 @@ +from typing import Any, Generator + +class Message: + preamble = ... + epilogue = ... + defects = ... + def __init__(self): ... + def as_string(self, unixfrom=...): ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom) -> None: ... + def get_unixfrom(self): ... + def attach(self, payload) -> None: ... + def get_payload(self, i=..., decode: bool = ...): ... + def set_payload(self, payload, charset=...) -> None: ... + def set_charset(self, charset): ... + def get_charset(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, val) -> None: ... + def __delitem__(self, name) -> None: ... + def __contains__(self, name): ... + def has_key(self, name) -> bool: ... + def keys(self): ... + def values(self): ... + def items(self): ... + def get(self, name, failobj=...): ... + def get_all(self, name, failobj=...): ... + def add_header(self, _name, _value, **_params) -> None: ... + def replace_header(self, _name, _value) -> None: ... + def get_content_type(self): ... + def get_content_maintype(self): ... + def get_content_subtype(self): ... + def get_default_type(self): ... + def set_default_type(self, ctype) -> None: ... + def get_params(self, failobj=..., header=..., unquote: bool = ...): ... + def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... + def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... + def del_param(self, param, header=..., requote: bool = ...): ... + def set_type(self, type, header=..., requote: bool = ...): ... + def get_filename(self, failobj=...): ... + def get_boundary(self, failobj=...): ... + def set_boundary(self, boundary) -> None: ... + def get_content_charset(self, failobj=...): ... + def get_charsets(self, failobj=...): ... + def walk(self) -> Generator[Any, Any, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/__init__.pyi b/mypy/typeshed/stdlib/@python2/email/mime/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi new file mode 100644 index 000000000000..4245e3e0f980 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi @@ -0,0 +1,9 @@ +from email.mime.nonmultipart import MIMENonMultipart +from typing import Callable, Optional, Tuple, Union + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEApplication(MIMENonMultipart): + def __init__( + self, _data: bytes, _subtype: str = ..., _encoder: Callable[[MIMEApplication], None] = ..., **_params: _ParamsType + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/audio.pyi b/mypy/typeshed/stdlib/@python2/email/mime/audio.pyi new file mode 100644 index 000000000000..5f11f8d79008 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/audio.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEAudio(MIMENonMultipart): + def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/base.pyi b/mypy/typeshed/stdlib/@python2/email/mime/base.pyi new file mode 100644 index 000000000000..4bde4f073395 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/base.pyi @@ -0,0 +1,4 @@ +from email import message + +class MIMEBase(message.Message): + def __init__(self, _maintype, _subtype, **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/image.pyi b/mypy/typeshed/stdlib/@python2/email/mime/image.pyi new file mode 100644 index 000000000000..3fe8249d6ac8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/image.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEImage(MIMENonMultipart): + def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/message.pyi b/mypy/typeshed/stdlib/@python2/email/mime/message.pyi new file mode 100644 index 000000000000..9d6fafa2a19b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/message.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEMessage(MIMENonMultipart): + def __init__(self, _msg, _subtype=...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/multipart.pyi b/mypy/typeshed/stdlib/@python2/email/mime/multipart.pyi new file mode 100644 index 000000000000..0a7d3fa8acb0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/multipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMEMultipart(MIMEBase): + def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/@python2/email/mime/nonmultipart.pyi new file mode 100644 index 000000000000..04d130e3da88 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/nonmultipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMENonMultipart(MIMEBase): + def attach(self, payload): ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/text.pyi b/mypy/typeshed/stdlib/@python2/email/mime/text.pyi new file mode 100644 index 000000000000..3b059778aa66 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/mime/text.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/email/parser.pyi b/mypy/typeshed/stdlib/@python2/email/parser.pyi new file mode 100644 index 000000000000..4f2282834ca5 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/parser.pyi @@ -0,0 +1,10 @@ +from .feedparser import FeedParser as FeedParser # not in __all__ but listed in documentation + +class Parser: + def __init__(self, *args, **kws) -> None: ... + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... + +class HeaderParser(Parser): + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... diff --git a/mypy/typeshed/stdlib/@python2/email/quoprimime.pyi b/mypy/typeshed/stdlib/@python2/email/quoprimime.pyi new file mode 100644 index 000000000000..3f2963c06e6d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/quoprimime.pyi @@ -0,0 +1,18 @@ +def header_quopri_check(c): ... +def body_quopri_check(c): ... +def header_quopri_len(s): ... +def body_quopri_len(str): ... +def unquote(s): ... +def quote(c): ... +def header_encode(header, charset: str = ..., keep_eols: bool = ..., maxlinelen: int = ..., eol=...): ... +def encode(body, binary: bool = ..., maxlinelen: int = ..., eol=...): ... + +body_encode = encode +encodestring = encode + +def decode(encoded, eol=...): ... + +body_decode = decode +decodestring = decode + +def header_decode(s): ... diff --git a/mypy/typeshed/stdlib/@python2/email/utils.pyi b/mypy/typeshed/stdlib/@python2/email/utils.pyi new file mode 100644 index 000000000000..257e4b1c947a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/email/utils.pyi @@ -0,0 +1,21 @@ +from email._parseaddr import ( + AddressList as _AddressList, + mktime_tz as mktime_tz, + parsedate as _parsedate, + parsedate_tz as _parsedate_tz, +) +from quopri import decodestring as _qdecode +from typing import Any, Optional + +def formataddr(pair): ... +def getaddresses(fieldvalues): ... +def formatdate(timeval: Optional[Any] = ..., localtime: bool = ..., usegmt: bool = ...): ... +def make_msgid(idstring: Optional[Any] = ...): ... +def parsedate(data): ... +def parsedate_tz(data): ... +def parseaddr(addr): ... +def unquote(str): ... +def decode_rfc2231(s): ... +def encode_rfc2231(s, charset: Optional[Any] = ..., language: Optional[Any] = ...): ... +def decode_params(params): ... +def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ... diff --git a/mypy/typeshed/stdlib/@python2/encodings/__init__.pyi b/mypy/typeshed/stdlib/@python2/encodings/__init__.pyi new file mode 100644 index 000000000000..d6f4389bc820 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/encodings/__init__.pyi @@ -0,0 +1,7 @@ +import codecs +from typing import Any + +def search_function(encoding: str) -> codecs.CodecInfo: ... + +# Explicitly mark this package as incomplete. +def __getattr__(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi new file mode 100644 index 000000000000..d38bd58d0e43 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi @@ -0,0 +1,15 @@ +import codecs +from typing import Text, Tuple + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: Text, final: bool = ...) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... + +class StreamWriter(codecs.StreamWriter): ... +class StreamReader(codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: Text, errors: Text = ...) -> bytes: ... +def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/mypy/typeshed/stdlib/@python2/exceptions.pyi b/mypy/typeshed/stdlib/@python2/exceptions.pyi new file mode 100644 index 000000000000..fbad89750731 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/exceptions.pyi @@ -0,0 +1,50 @@ +from __builtin__ import ( + ArithmeticError as ArithmeticError, + AssertionError as AssertionError, + AttributeError as AttributeError, + BaseException as BaseException, + BufferError as BufferError, + BytesWarning as BytesWarning, + DeprecationWarning as DeprecationWarning, + EnvironmentError as EnvironmentError, + EOFError as EOFError, + Exception as Exception, + FloatingPointError as FloatingPointError, + FutureWarning as FutureWarning, + GeneratorExit as GeneratorExit, + ImportError as ImportError, + ImportWarning as ImportWarning, + IndentationError as IndentationError, + IndexError as IndexError, + IOError as IOError, + KeyboardInterrupt as KeyboardInterrupt, + KeyError as KeyError, + LookupError as LookupError, + MemoryError as MemoryError, + NameError as NameError, + NotImplementedError as NotImplementedError, + OSError as OSError, + OverflowError as OverflowError, + PendingDeprecationWarning as PendingDeprecationWarning, + ReferenceError as ReferenceError, + RuntimeError as RuntimeError, + RuntimeWarning as RuntimeWarning, + StandardError as StandardError, + StopIteration as StopIteration, + SyntaxError as SyntaxError, + SyntaxWarning as SyntaxWarning, + SystemError as SystemError, + SystemExit as SystemExit, + TabError as TabError, + TypeError as TypeError, + UnboundLocalError as UnboundLocalError, + UnicodeDecodeError as UnicodeDecodeError, + UnicodeEncodeError as UnicodeEncodeError, + UnicodeError as UnicodeError, + UnicodeTranslateError as UnicodeTranslateError, + UnicodeWarning as UnicodeWarning, + UserWarning as UserWarning, + ValueError as ValueError, + Warning as Warning, + ZeroDivisionError as ZeroDivisionError, +) diff --git a/mypy/typeshed/stdlib/@python2/fcntl.pyi b/mypy/typeshed/stdlib/@python2/fcntl.pyi new file mode 100644 index 000000000000..200e2249280c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/fcntl.pyi @@ -0,0 +1,82 @@ +from _typeshed import FileDescriptorLike +from typing import Any, Union + +FASYNC: int +FD_CLOEXEC: int + +DN_ACCESS: int +DN_ATTRIB: int +DN_CREATE: int +DN_DELETE: int +DN_MODIFY: int +DN_MULTISHOT: int +DN_RENAME: int +F_DUPFD: int +F_EXLCK: int +F_GETFD: int +F_GETFL: int +F_GETLEASE: int +F_GETLK: int +F_GETLK64: int +F_GETOWN: int +F_GETSIG: int +F_NOTIFY: int +F_RDLCK: int +F_SETFD: int +F_SETFL: int +F_SETLEASE: int +F_SETLK: int +F_SETLK64: int +F_SETLKW: int +F_SETLKW64: int +F_SETOWN: int +F_SETSIG: int +F_SHLCK: int +F_UNLCK: int +F_WRLCK: int +I_ATMARK: int +I_CANPUT: int +I_CKBAND: int +I_FDINSERT: int +I_FIND: int +I_FLUSH: int +I_FLUSHBAND: int +I_GETBAND: int +I_GETCLTIME: int +I_GETSIG: int +I_GRDOPT: int +I_GWROPT: int +I_LINK: int +I_LIST: int +I_LOOK: int +I_NREAD: int +I_PEEK: int +I_PLINK: int +I_POP: int +I_PUNLINK: int +I_PUSH: int +I_RECVFD: int +I_SENDFD: int +I_SETCLTIME: int +I_SETSIG: int +I_SRDOPT: int +I_STR: int +I_SWROPT: int +I_UNLINK: int +LOCK_EX: int +LOCK_MAND: int +LOCK_NB: int +LOCK_READ: int +LOCK_RW: int +LOCK_SH: int +LOCK_UN: int +LOCK_WRITE: int + +# TODO All these return either int or bytes depending on the value of +# cmd (not on the type of arg). +def fcntl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ...) -> Any: ... + +# TODO: arg: int or read-only buffer interface or read-write buffer interface +def ioctl(fd: FileDescriptorLike, op: int, arg: Union[int, bytes] = ..., mutate_flag: bool = ...) -> Any: ... +def flock(fd: FileDescriptorLike, op: int) -> None: ... +def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., whence: int = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/fnmatch.pyi b/mypy/typeshed/stdlib/@python2/fnmatch.pyi new file mode 100644 index 000000000000..e933b7b2cb62 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/fnmatch.pyi @@ -0,0 +1,8 @@ +from typing import AnyStr, Iterable, List, Union + +_EitherStr = Union[str, unicode] + +def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... +def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/functools.pyi b/mypy/typeshed/stdlib/@python2/functools.pyi new file mode 100644 index 000000000000..1231dd133829 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/functools.pyi @@ -0,0 +1,30 @@ +from abc import ABCMeta, abstractmethod +from typing import Any, Callable, Dict, Generic, Iterable, Optional, Sequence, Tuple, Type, TypeVar, overload + +_AnyCallable = Callable[..., Any] + +_T = TypeVar("_T") +_S = TypeVar("_S") +@overload +def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... + +WRAPPER_ASSIGNMENTS: Sequence[str] +WRAPPER_UPDATES: Sequence[str] + +def update_wrapper( + wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... +) -> _AnyCallable: ... +def wraps( + wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... +) -> Callable[[_AnyCallable], _AnyCallable]: ... +def total_ordering(cls: Type[_T]) -> Type[_T]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... + +class partial(Generic[_T]): + func = ... # Callable[..., _T] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/future_builtins.pyi b/mypy/typeshed/stdlib/@python2/future_builtins.pyi new file mode 100644 index 000000000000..2a06c73cf409 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/future_builtins.pyi @@ -0,0 +1,10 @@ +from itertools import ifilter, imap, izip +from typing import Any + +filter = ifilter +map = imap +zip = izip + +def ascii(obj: Any) -> str: ... +def hex(x: int) -> str: ... +def oct(x: int) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/gc.pyi b/mypy/typeshed/stdlib/@python2/gc.pyi new file mode 100644 index 000000000000..b1fb1acc07d2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/gc.pyi @@ -0,0 +1,25 @@ +from typing import Any, List, Tuple + +def enable() -> None: ... +def disable() -> None: ... +def isenabled() -> bool: ... +def collect(generation: int = ...) -> int: ... +def set_debug(flags: int) -> None: ... +def get_debug() -> int: ... +def get_objects() -> List[Any]: ... +def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... +def get_count() -> Tuple[int, int, int]: ... +def get_threshold() -> Tuple[int, int, int]: ... +def get_referrers(*objs: Any) -> List[Any]: ... +def get_referents(*objs: Any) -> List[Any]: ... +def is_tracked(obj: Any) -> bool: ... + +garbage: List[Any] + +DEBUG_STATS: int +DEBUG_COLLECTABLE: int +DEBUG_UNCOLLECTABLE: int +DEBUG_INSTANCES: int +DEBUG_OBJECTS: int +DEBUG_SAVEALL: int +DEBUG_LEAK: int diff --git a/mypy/typeshed/stdlib/@python2/getopt.pyi b/mypy/typeshed/stdlib/@python2/getopt.pyi new file mode 100644 index 000000000000..370d4d5c1cba --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/getopt.pyi @@ -0,0 +1,12 @@ +from typing import List, Tuple + +class GetoptError(Exception): + opt: str + msg: str + def __init__(self, msg: str, opt: str = ...) -> None: ... + def __str__(self) -> str: ... + +error = GetoptError + +def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/mypy/typeshed/stdlib/@python2/getpass.pyi b/mypy/typeshed/stdlib/@python2/getpass.pyi new file mode 100644 index 000000000000..784eb1a1d760 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/getpass.pyi @@ -0,0 +1,6 @@ +from typing import IO, Any + +class GetPassWarning(UserWarning): ... + +def getpass(prompt: str = ..., stream: IO[Any] = ...) -> str: ... +def getuser() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/gettext.pyi b/mypy/typeshed/stdlib/@python2/gettext.pyi new file mode 100644 index 000000000000..0930fe63813e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/gettext.pyi @@ -0,0 +1,48 @@ +from typing import IO, Any, Container, Dict, List, Optional, Sequence, Type, Union + +def bindtextdomain(domain: str, localedir: str = ...) -> str: ... +def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... +def textdomain(domain: str = ...) -> str: ... +def gettext(message: str) -> str: ... +def lgettext(message: str) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def ldgettext(domain: str, message: str) -> str: ... +def ngettext(singular: str, plural: str, n: int) -> str: ... +def lngettext(singular: str, plural: str, n: int) -> str: ... +def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... +def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... + +class NullTranslations(object): + def __init__(self, fp: IO[str] = ...) -> None: ... + def _parse(self, fp: IO[str]) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def lgettext(self, message: str) -> str: ... + def ugettext(self, message: Union[str, unicode]) -> unicode: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def lngettext(self, singular: str, plural: str, n: int) -> str: ... + def ungettext(self, singular: Union[str, unicode], plural: Union[str, unicode], n: int) -> unicode: ... + def info(self) -> Dict[str, str]: ... + def charset(self) -> Optional[str]: ... + def output_charset(self) -> Optional[str]: ... + def set_output_charset(self, charset: Optional[str]) -> None: ... + def install(self, unicode: bool = ..., names: Container[str] = ...) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC: int + BE_MAGIC: int + +def find( + domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., all: Any = ... +) -> Optional[Union[str, List[str]]]: ... +def translation( + domain: str, + localedir: Optional[str] = ..., + languages: Optional[Sequence[str]] = ..., + class_: Optional[Type[NullTranslations]] = ..., + fallback: bool = ..., + codeset: Optional[str] = ..., +) -> NullTranslations: ... +def install( + domain: str, localedir: Optional[str] = ..., unicode: bool = ..., codeset: Optional[str] = ..., names: Container[str] = ... +) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/glob.pyi b/mypy/typeshed/stdlib/@python2/glob.pyi new file mode 100644 index 000000000000..2804d74a6a3f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/glob.pyi @@ -0,0 +1,7 @@ +from typing import AnyStr, Iterator, List, Union + +def glob(pathname: AnyStr) -> List[AnyStr]: ... +def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... +def glob1(dirname: Union[str, unicode], pattern: AnyStr) -> List[AnyStr]: ... +def glob0(dirname: Union[str, unicode], basename: AnyStr) -> List[AnyStr]: ... +def has_magic(s: Union[str, unicode]) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/gzip.pyi b/mypy/typeshed/stdlib/@python2/gzip.pyi new file mode 100644 index 000000000000..f5c5af9c4c40 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/gzip.pyi @@ -0,0 +1,38 @@ +import io +from typing import IO, Any, Text + +class GzipFile(io.BufferedIOBase): + myfileobj: Any + max_read_chunk: Any + mode: Any + extrabuf: Any + extrasize: Any + extrastart: Any + name: Any + min_readsize: Any + compress: Any + fileobj: Any + offset: Any + mtime: Any + def __init__( + self, filename: str = ..., mode: Text = ..., compresslevel: int = ..., fileobj: IO[str] = ..., mtime: float = ... + ) -> None: ... + @property + def filename(self): ... + size: Any + crc: Any + def write(self, data): ... + def read(self, size=...): ... + @property + def closed(self): ... + def close(self): ... + def flush(self, zlib_mode=...): ... + def fileno(self): ... + def rewind(self): ... + def readable(self): ... + def writable(self): ... + def seekable(self): ... + def seek(self, offset, whence=...): ... + def readline(self, size=...): ... + +def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ... diff --git a/mypy/typeshed/stdlib/@python2/hashlib.pyi b/mypy/typeshed/stdlib/@python2/hashlib.pyi new file mode 100644 index 000000000000..842804b4ccb2 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/hashlib.pyi @@ -0,0 +1,28 @@ +from typing import Tuple, Union + +_DataType = Union[str, unicode, bytearray, buffer, memoryview] + +class _hash(object): # This is not actually in the module namespace. + name: str + block_size: int + digest_size: int + digestsize: int + def __init__(self, arg: _DataType = ...) -> None: ... + def update(self, arg: _DataType) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> _hash: ... + +def new(name: str, data: str = ...) -> _hash: ... +def md5(s: _DataType = ...) -> _hash: ... +def sha1(s: _DataType = ...) -> _hash: ... +def sha224(s: _DataType = ...) -> _hash: ... +def sha256(s: _DataType = ...) -> _hash: ... +def sha384(s: _DataType = ...) -> _hash: ... +def sha512(s: _DataType = ...) -> _hash: ... + +algorithms: Tuple[str, ...] +algorithms_guaranteed: Tuple[str, ...] +algorithms_available: Tuple[str, ...] + +def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/heapq.pyi b/mypy/typeshed/stdlib/@python2/heapq.pyi new file mode 100644 index 000000000000..d6da32d767d3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/heapq.pyi @@ -0,0 +1,15 @@ +from _typeshed import SupportsLessThan +from typing import Any, Callable, Iterable, List, Optional, Protocol, TypeVar + +_T = TypeVar("_T") + +def cmp_lt(x, y) -> bool: ... +def heappush(heap: List[_T], item: _T) -> None: ... +def heappop(heap: List[_T]) -> _T: ... +def heappushpop(heap: List[_T], item: _T) -> _T: ... +def heapify(x: List[_T]) -> None: ... +def heapreplace(heap: List[_T], item: _T) -> _T: ... +def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... +def nlargest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... +def _heapify_max(__x: List[_T]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi b/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi new file mode 100644 index 000000000000..749b3039dfc3 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi @@ -0,0 +1,5 @@ +from typing import Dict + +name2codepoint: Dict[str, int] +codepoint2name: Dict[int, str] +entitydefs: Dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/httplib.pyi b/mypy/typeshed/stdlib/@python2/httplib.pyi new file mode 100644 index 000000000000..59dc658f79ef --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/httplib.pyi @@ -0,0 +1,218 @@ +import mimetools +import ssl +from typing import Any, Dict, Optional, Protocol + +class HTTPMessage(mimetools.Message): + def addcontinue(self, key: str, more: str) -> None: ... + dict: Dict[str, str] + def addheader(self, key: str, value: str) -> None: ... + unixfrom: str + headers: Any + status: str + seekable: bool + def readheaders(self) -> None: ... + +class HTTPResponse: + fp: Any + debuglevel: Any + strict: Any + msg: Any + version: Any + status: Any + reason: Any + chunked: Any + chunk_left: Any + length: Any + will_close: Any + def __init__( + self, sock, debuglevel: int = ..., strict: int = ..., method: Optional[Any] = ..., buffering: bool = ... + ) -> None: ... + def begin(self): ... + def close(self): ... + def isclosed(self): ... + def read(self, amt: Optional[Any] = ...): ... + def fileno(self): ... + def getheader(self, name, default: Optional[Any] = ...): ... + def getheaders(self): ... + +# This is an API stub only for HTTPConnection and HTTPSConnection, as used in +# urllib2.AbstractHTTPHandler.do_open, which takes either the class +# HTTPConnection or the class HTTPSConnection, *not* an instance of either +# class. do_open does not use all of the parameters of HTTPConnection.__init__ +# or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the +# parameters that do_open does use. +class HTTPConnectionProtocol(Protocol): + def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ... + +class HTTPConnection: + response_class: Any + default_port: Any + auto_open: Any + debuglevel: Any + strict: Any + timeout: Any + source_address: Any + sock: Any + host: str = ... + port: int = ... + def __init__( + self, host, port: Optional[Any] = ..., strict: Optional[Any] = ..., timeout=..., source_address: Optional[Any] = ... + ) -> None: ... + def set_tunnel(self, host, port: Optional[Any] = ..., headers: Optional[Any] = ...): ... + def set_debuglevel(self, level): ... + def connect(self): ... + def close(self): ... + def send(self, data): ... + def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ... + def putheader(self, header, *values): ... + def endheaders(self, message_body: Optional[Any] = ...): ... + def request(self, method, url, body: Optional[Any] = ..., headers=...): ... + def getresponse(self, buffering: bool = ...): ... + +class HTTP: + debuglevel: Any + def __init__(self, host: str = ..., port: Optional[Any] = ..., strict: Optional[Any] = ...) -> None: ... + def connect(self, host: Optional[Any] = ..., port: Optional[Any] = ...): ... + def getfile(self): ... + file: Any + headers: Any + def getreply(self, buffering: bool = ...): ... + def close(self): ... + +class HTTPSConnection(HTTPConnection): + default_port: Any + key_file: Any + cert_file: Any + def __init__( + self, + host, + port: Optional[Any] = ..., + key_file: Optional[Any] = ..., + cert_file: Optional[Any] = ..., + strict: Optional[Any] = ..., + timeout=..., + source_address: Optional[Any] = ..., + context: Optional[Any] = ..., + ) -> None: ... + sock: Any + def connect(self): ... + +class HTTPS(HTTP): + key_file: Any + cert_file: Any + def __init__( + self, + host: str = ..., + port: Optional[Any] = ..., + key_file: Optional[Any] = ..., + cert_file: Optional[Any] = ..., + strict: Optional[Any] = ..., + context: Optional[Any] = ..., + ) -> None: ... + +class HTTPException(Exception): ... +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... + +class UnknownProtocol(HTTPException): + args: Any + version: Any + def __init__(self, version) -> None: ... + +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... + +class IncompleteRead(HTTPException): + args: Any + partial: Any + expected: Any + def __init__(self, partial, expected: Optional[Any] = ...) -> None: ... + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): + args: Any + line: Any + def __init__(self, line) -> None: ... + +class LineTooLong(HTTPException): + def __init__(self, line_type) -> None: ... + +error: Any + +class LineAndFileWrapper: + def __init__(self, line, file) -> None: ... + def __getattr__(self, attr): ... + def read(self, amt: Optional[Any] = ...): ... + def readline(self): ... + def readlines(self, size: Optional[Any] = ...): ... + +# Constants + +responses: Dict[int, str] + +HTTP_PORT: int +HTTPS_PORT: int + +# status codes +# informational +CONTINUE: int +SWITCHING_PROTOCOLS: int +PROCESSING: int + +# successful +OK: int +CREATED: int +ACCEPTED: int +NON_AUTHORITATIVE_INFORMATION: int +NO_CONTENT: int +RESET_CONTENT: int +PARTIAL_CONTENT: int +MULTI_STATUS: int +IM_USED: int + +# redirection +MULTIPLE_CHOICES: int +MOVED_PERMANENTLY: int +FOUND: int +SEE_OTHER: int +NOT_MODIFIED: int +USE_PROXY: int +TEMPORARY_REDIRECT: int + +# client error +BAD_REQUEST: int +UNAUTHORIZED: int +PAYMENT_REQUIRED: int +FORBIDDEN: int +NOT_FOUND: int +METHOD_NOT_ALLOWED: int +NOT_ACCEPTABLE: int +PROXY_AUTHENTICATION_REQUIRED: int +REQUEST_TIMEOUT: int +CONFLICT: int +GONE: int +LENGTH_REQUIRED: int +PRECONDITION_FAILED: int +REQUEST_ENTITY_TOO_LARGE: int +REQUEST_URI_TOO_LONG: int +UNSUPPORTED_MEDIA_TYPE: int +REQUESTED_RANGE_NOT_SATISFIABLE: int +EXPECTATION_FAILED: int +UNPROCESSABLE_ENTITY: int +LOCKED: int +FAILED_DEPENDENCY: int +UPGRADE_REQUIRED: int + +# server error +INTERNAL_SERVER_ERROR: int +NOT_IMPLEMENTED: int +BAD_GATEWAY: int +SERVICE_UNAVAILABLE: int +GATEWAY_TIMEOUT: int +HTTP_VERSION_NOT_SUPPORTED: int +INSUFFICIENT_STORAGE: int +NOT_EXTENDED: int diff --git a/mypy/typeshed/stdlib/@python2/imp.pyi b/mypy/typeshed/stdlib/@python2/imp.pyi new file mode 100644 index 000000000000..3cd37648b968 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/imp.pyi @@ -0,0 +1,33 @@ +import types +from typing import IO, Any, Iterable, List, Optional, Tuple + +C_BUILTIN: int +C_EXTENSION: int +IMP_HOOK: int +PKG_DIRECTORY: int +PY_CODERESOURCE: int +PY_COMPILED: int +PY_FROZEN: int +PY_RESOURCE: int +PY_SOURCE: int +SEARCH_ERROR: int + +def acquire_lock() -> None: ... +def find_module(name: str, path: Iterable[str] = ...) -> Optional[Tuple[IO[Any], str, Tuple[str, str, int]]]: ... +def get_magic() -> str: ... +def get_suffixes() -> List[Tuple[str, str, int]]: ... +def init_builtin(name: str) -> types.ModuleType: ... +def init_frozen(name: str) -> types.ModuleType: ... +def is_builtin(name: str) -> int: ... +def is_frozen(name: str) -> bool: ... +def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... +def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def lock_held() -> bool: ... +def new_module(name: str) -> types.ModuleType: ... +def release_lock() -> None: ... + +class NullImporter: + def __init__(self, path_string: str) -> None: ... + def find_module(self, fullname: str, path: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/importlib.pyi b/mypy/typeshed/stdlib/@python2/importlib.pyi new file mode 100644 index 000000000000..8bb179a4bd9a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/importlib.pyi @@ -0,0 +1,4 @@ +import types +from typing import Optional, Text + +def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/@python2/inspect.pyi b/mypy/typeshed/stdlib/@python2/inspect.pyi new file mode 100644 index 000000000000..8e95a92cac10 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/inspect.pyi @@ -0,0 +1,129 @@ +from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType +from typing import Any, AnyStr, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple, Type, Union + +# Types and members +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + last: int + def tokeneater( + self, type: int, token: AnyStr, srow_scol: Tuple[int, int], erow_ecol: Tuple[int, int], line: AnyStr + ) -> None: ... + +CO_GENERATOR: int +CO_NESTED: int +CO_NEWLOCALS: int +CO_NOFREE: int +CO_OPTIMIZED: int +CO_VARARGS: int +CO_VARKEYWORDS: int +TPFLAGS_IS_ABSTRACT: int + +class ModuleInfo(NamedTuple): + name: str + suffix: str + mode: str + module_type: int + +def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> List[Tuple[str, Any]]: ... +def getmoduleinfo(path: Union[str, unicode]) -> Optional[ModuleInfo]: ... +def getmodulename(path: AnyStr) -> Optional[AnyStr]: ... +def ismodule(object: object) -> bool: ... +def isclass(object: object) -> bool: ... +def ismethod(object: object) -> bool: ... +def isfunction(object: object) -> bool: ... +def isgeneratorfunction(object: object) -> bool: ... +def isgenerator(object: object) -> bool: ... +def istraceback(object: object) -> bool: ... +def isframe(object: object) -> bool: ... +def iscode(object: object) -> bool: ... +def isbuiltin(object: object) -> bool: ... +def isroutine(object: object) -> bool: ... +def isabstract(object: object) -> bool: ... +def ismethoddescriptor(object: object) -> bool: ... +def isdatadescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> bool: ... +def ismemberdescriptor(object: object) -> bool: ... + +# Retrieving source code +_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] + +def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getabsfile(object: _SourceObjectType) -> str: ... +def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... +def getdoc(object: object) -> Optional[str]: ... +def getcomments(object: object) -> Optional[str]: ... +def getfile(object: _SourceObjectType) -> str: ... +def getmodule(object: object) -> Optional[ModuleType]: ... +def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... +def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsource(object: _SourceObjectType) -> str: ... +def cleandoc(doc: AnyStr) -> AnyStr: ... +def indentsize(line: Union[str, unicode]) -> int: ... + +# Classes and functions +def getclasstree(classes: List[type], unique: bool = ...) -> List[Union[Tuple[type, Tuple[type, ...]], List[Any]]]: ... + +class ArgSpec(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + defaults: Tuple[Any, ...] + +class ArgInfo(NamedTuple): + args: List[str] + varargs: Optional[str] + keywords: Optional[str] + locals: Dict[str, Any] + +class Arguments(NamedTuple): + args: List[Union[str, List[Any]]] + varargs: Optional[str] + keywords: Optional[str] + +def getargs(co: CodeType) -> Arguments: ... +def getargspec(func: object) -> ArgSpec: ... +def getargvalues(frame: FrameType) -> ArgInfo: ... +def formatargspec( + args, varargs=..., varkw=..., defaults=..., formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., join=... +) -> str: ... +def formatargvalues( + args, varargs=..., varkw=..., defaults=..., formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., join=... +) -> str: ... +def getmro(cls: type) -> Tuple[type, ...]: ... +def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... + +# The interpreter stack + +class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: Optional[List[str]] + index: Optional[int] # type: ignore + +_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] + +def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... +def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... +def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... +def currentframe(depth: int = ...) -> FrameType: ... +def stack(context: int = ...) -> List[_FrameInfo]: ... +def trace(context: int = ...) -> List[_FrameInfo]: ... + +# Create private type alias to avoid conflict with symbol of same +# name created in Attribute class. +_Object = object + +class Attribute(NamedTuple): + name: str + kind: str + defining_class: type + object: _Object + +def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/mypy/typeshed/stdlib/@python2/io.pyi b/mypy/typeshed/stdlib/@python2/io.pyi new file mode 100644 index 000000000000..1e29cc67369f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/io.pyi @@ -0,0 +1,40 @@ +from typing import IO, Any, Union + +import _io +from _io import ( + DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE, + BlockingIOError as BlockingIOError, + BufferedRandom as BufferedRandom, + BufferedReader as BufferedReader, + BufferedRWPair as BufferedRWPair, + BufferedWriter as BufferedWriter, + BytesIO as BytesIO, + FileIO as FileIO, + IncrementalNewlineDecoder as IncrementalNewlineDecoder, + StringIO as StringIO, + TextIOWrapper as TextIOWrapper, + UnsupportedOperation as UnsupportedOperation, + open as open, +) + +def _OpenWrapper( + file: Union[str, unicode, int], + mode: unicode = ..., + buffering: int = ..., + encoding: unicode = ..., + errors: unicode = ..., + newline: unicode = ..., + closefd: bool = ..., +) -> IO[Any]: ... + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int + +class IOBase(_io._IOBase): ... +class RawIOBase(_io._RawIOBase, IOBase): ... +class BufferedIOBase(_io._BufferedIOBase, IOBase): ... + +# Note: In the actual io.py, TextIOBase subclasses IOBase. +# (Which we don't do here because we don't want to subclass both TextIO and BinaryIO.) +class TextIOBase(_io._TextIOBase): ... diff --git a/mypy/typeshed/stdlib/@python2/itertools.pyi b/mypy/typeshed/stdlib/@python2/itertools.pyi new file mode 100644 index 000000000000..59a329f7282f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/itertools.pyi @@ -0,0 +1,164 @@ +from typing import Any, Callable, Generic, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") + +def count(start: int = ..., step: int = ...) -> Iterator[int]: ... # more general types? + +class cycle(Iterator[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def next(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + +def repeat(object: _T, times: int = ...) -> Iterator[_T]: ... + +class chain(Iterator[_T], Generic[_T]): + def __init__(self, *iterables: Iterable[_T]) -> None: ... + def next(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + @staticmethod + def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + +def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... +def dropwhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilter(predicate: Optional[Callable[[_T], Any]], iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilterfalse(predicate: Optional[Callable[[_T], Any]], iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +@overload +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... +@overload +def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +@overload +def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], step: Optional[int] = ...) -> Iterator[_T]: ... + +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") +@overload +def imap(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... +@overload +def imap(func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[_S]: ... +@overload +def imap( + func: Callable[[_T1, _T2, _T3], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3] +) -> Iterator[_S]: ... +@overload +def imap( + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], +) -> Iterator[_S]: ... +@overload +def imap( + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], +) -> Iterator[_S]: ... +@overload +def imap( + func: Callable[[_T1, _T2, _T3, _T4, _T5, _T6], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], +) -> Iterator[_S]: ... +@overload +def imap( + func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[_S]: ... +def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... +def takewhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... +@overload +def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def izip( + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def izip( + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def izip( + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def izip( + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[Tuple[Any, ...]]: ... +def izip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... +@overload +def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def product( + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product( + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product( + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], +) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product( + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... +def permutations(iterable: Iterable[_T], r: int = ...) -> Iterator[Sequence[_T]]: ... +def combinations(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... +def combinations_with_replacement(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... diff --git a/mypy/typeshed/stdlib/@python2/json.pyi b/mypy/typeshed/stdlib/@python2/json.pyi new file mode 100644 index 000000000000..2d38e6b47bb8 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/json.pyi @@ -0,0 +1,93 @@ +from _typeshed import SupportsRead +from typing import IO, Any, Callable, Dict, List, Optional, Text, Tuple, Type, Union + +def dumps( + obj: Any, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> str: ... +def dump( + obj: Any, + fp: Union[IO[str], IO[Text]], + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> None: ... +def loads( + s: Union[Text, bytes], + encoding: Any = ..., + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... +def load( + fp: SupportsRead[Union[Text, bytes]], + encoding: Optional[str] = ..., + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... + +class JSONDecoder(object): + def __init__( + self, + encoding: Union[Text, bytes] = ..., + object_hook: Callable[..., Any] = ..., + parse_float: Callable[[str], float] = ..., + parse_int: Callable[[str], int] = ..., + parse_constant: Callable[[str], Any] = ..., + strict: bool = ..., + object_pairs_hook: Callable[..., Any] = ..., + ) -> None: ... + def decode(self, s: Union[Text, bytes], _w: Any = ...) -> Any: ... + def raw_decode(self, s: Union[Text, bytes], idx: int = ...) -> Tuple[Any, Any]: ... + +class JSONEncoder(object): + item_separator: str + key_separator: str + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: Optional[int] + def __init__( + self, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Tuple[Union[Text, bytes], Union[Text, bytes]] = ..., + encoding: Union[Text, bytes] = ..., + default: Callable[..., Any] = ..., + ) -> None: ... + def default(self, o: Any) -> Any: ... + def encode(self, o: Any) -> str: ... + def iterencode(self, o: Any, _one_shot: bool = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/markupbase.pyi b/mypy/typeshed/stdlib/@python2/markupbase.pyi new file mode 100644 index 000000000000..727daaacf25e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/markupbase.pyi @@ -0,0 +1,8 @@ +from typing import Tuple + +class ParserBase(object): + 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/md5.pyi b/mypy/typeshed/stdlib/@python2/md5.pyi new file mode 100644 index 000000000000..371f61135b7e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/md5.pyi @@ -0,0 +1,5 @@ +from hashlib import md5 as md5 + +new = md5 +blocksize: int +digest_size: int diff --git a/mypy/typeshed/stdlib/@python2/mimetools.pyi b/mypy/typeshed/stdlib/@python2/mimetools.pyi new file mode 100644 index 000000000000..3c6cbfcbacae --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mimetools.pyi @@ -0,0 +1,27 @@ +import rfc822 +from typing import Any + +class Message(rfc822.Message): + encodingheader: Any + typeheader: Any + def __init__(self, fp, seekable: int = ...): ... + plisttext: Any + type: Any + maintype: Any + subtype: Any + def parsetype(self): ... + plist: Any + def parseplist(self): ... + def getplist(self): ... + def getparam(self, name): ... + def getparamnames(self): ... + def getencoding(self): ... + def gettype(self): ... + def getmaintype(self): ... + def getsubtype(self): ... + +def choose_boundary(): ... +def decode(input, output, encoding): ... +def encode(input, output, encoding): ... +def copyliteral(input, output): ... +def copybinary(input, output): ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/__init__.pyi new file mode 100644 index 000000000000..b4f58920f574 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/__init__.pyi @@ -0,0 +1,50 @@ +from multiprocessing import pool +from multiprocessing.process import Process as Process, active_children as active_children, current_process as current_process +from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING +from Queue import Queue as _BaseQueue +from typing import Any, Callable, Iterable, Optional, TypeVar + +class ProcessError(Exception): ... +class BufferTooShort(ProcessError): ... +class TimeoutError(ProcessError): ... +class AuthenticationError(ProcessError): ... + +_T = TypeVar("_T") + +class Queue(_BaseQueue[_T]): + def __init__(self, maxsize: int = ...) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put_nowait(self, item: _T) -> None: ... + def get_nowait(self) -> _T: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + +def Manager(): ... +def Pipe(duplex: bool = ...): ... +def cpu_count() -> int: ... +def freeze_support(): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def allow_connection_pickling(): ... +def Lock(): ... +def RLock(): ... +def Condition(lock: Optional[Any] = ...): ... +def Semaphore(value: int = ...): ... +def BoundedSemaphore(value: int = ...): ... +def Event(): ... +def JoinableQueue(maxsize: int = ...): ... +def RawValue(typecode_or_type, *args): ... +def RawArray(typecode_or_type, size_or_initializer): ... +def Value(typecode_or_type, *args, **kwds): ... +def Array(typecode_or_type, size_or_initializer, **kwds): ... +def Pool( + processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., +) -> pool.Pool: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000000..8f6b2124094d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,46 @@ +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 + +class DummyProcess(threading.Thread): + _children: weakref.WeakKeyDictionary[Any, Any] + _parent: threading.Thread + _pid: None + _start_called: bool + def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + @property + def exitcode(self) -> Optional[int]: ... + +Process = DummyProcess + +# This should be threading._Condition but threading.pyi exports it as Condition +class Condition(threading.Condition): + notify_all: Any + +class Namespace(object): + def __init__(self, **kwds) -> None: ... + +class Value(object): + _typecode: Any + _value: Any + value: Any + def __init__(self, typecode, value, lock=...) -> None: ... + def _get(self) -> Any: ... + def _set(self, value) -> None: ... + +JoinableQueue = Queue + +def Array(typecode, sequence, lock=...) -> array.array[Any]: ... +def Manager() -> Any: ... +def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def active_children() -> List[Any]: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000000..60e456e3918d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi @@ -0,0 +1,25 @@ +from Queue import Queue +from typing import Any, List, Optional, Tuple, Type + +families: List[None] + +class Connection(object): + _in: Any + _out: Any + recv: Any + recv_bytes: Any + send: Any + send_bytes: Any + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout=...) -> Any: ... + +class Listener(object): + _backlog_queue: Optional[Queue[Any]] + address: Any + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + +def Client(address) -> Connection: ... +def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi new file mode 100644 index 000000000000..b20618ca0291 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi @@ -0,0 +1,52 @@ +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar + +_T = TypeVar("_T", bound=Pool) + +class AsyncResult: + def get(self, timeout: Optional[float] = ...) -> Any: ... + def wait(self, timeout: Optional[float] = ...) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + +class IMapIterator(Iterator[Any]): + def __iter__(self) -> Iterator[Any]: ... + def next(self, timeout: Optional[float] = ...) -> Any: ... + +class IMapUnorderedIterator(IMapIterator): ... + +class Pool(object): + def __init__( + self, + processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., + ) -> None: ... + def apply(self, func: Callable[..., Any], args: Iterable[Any] = ..., kwds: Dict[str, Any] = ...) -> Any: ... + def apply_async( + self, + func: Callable[..., Any], + args: Iterable[Any] = ..., + kwds: Dict[str, Any] = ..., + callback: Optional[Callable[..., None]] = ..., + ) -> AsyncResult: ... + def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: Optional[int] = ...) -> List[Any]: ... + def map_async( + self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[..., None]] = ..., + ) -> AsyncResult: ... + def imap(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: Optional[int] = ...) -> IMapIterator: ... + def imap_unordered( + self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: Optional[int] = ... + ) -> IMapIterator: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + +class ThreadPool(Pool): + def __init__( + self, processes: Optional[int] = ..., initializer: Optional[Callable[..., Any]] = ..., initargs: Iterable[Any] = ... + ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/process.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/process.pyi new file mode 100644 index 000000000000..9ab9628e0e32 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/process.pyi @@ -0,0 +1,37 @@ +from typing import Any, Optional + +def current_process(): ... +def active_children(): ... + +class Process: + def __init__( + self, group: Optional[Any] = ..., target: Optional[Any] = ..., name: Optional[Any] = ..., args=..., kwargs=... + ): ... + def run(self): ... + def start(self): ... + def terminate(self): ... + def join(self, timeout: Optional[Any] = ...): ... + def is_alive(self): ... + @property + def name(self): ... + @name.setter + def name(self, name): ... + @property + def daemon(self): ... + @daemon.setter + def daemon(self, daemonic): ... + @property + def authkey(self): ... + @authkey.setter + def authkey(self, authkey): ... + @property + def exitcode(self): ... + @property + def ident(self): ... + pid: Any + +class AuthenticationString(bytes): + def __reduce__(self): ... + +class _MainProcess(Process): + def __init__(self): ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/util.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/util.pyi new file mode 100644 index 000000000000..9520022e2962 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/util.pyi @@ -0,0 +1,29 @@ +import threading +from typing import Any, Optional + +SUBDEBUG: Any +SUBWARNING: Any + +def sub_debug(msg, *args): ... +def debug(msg, *args): ... +def info(msg, *args): ... +def sub_warning(msg, *args): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def get_temp_dir(): ... +def register_after_fork(obj, func): ... + +class Finalize: + def __init__(self, obj, callback, args=..., kwargs: Optional[Any] = ..., exitpriority: Optional[Any] = ...): ... + def __call__(self, wr: Optional[Any] = ...): ... + def cancel(self): ... + def still_active(self): ... + +def is_exiting(): ... + +class ForkAwareThreadLock: + def __init__(self): ... + +class ForkAwareLocal(threading.local): + def __init__(self): ... + def __reduce__(self): ... diff --git a/mypy/typeshed/stdlib/@python2/mutex.pyi b/mypy/typeshed/stdlib/@python2/mutex.pyi new file mode 100644 index 000000000000..e0931dc1188a --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/mutex.pyi @@ -0,0 +1,12 @@ +from typing import Any, Callable, Deque, TypeVar + +_T = TypeVar("_T") + +class mutex: + locked: bool + queue: Deque[Any] + def __init__(self) -> None: ... + def test(self) -> bool: ... + def testandset(self) -> bool: ... + def lock(self, function: Callable[[_T], Any], argument: _T) -> None: ... + def unlock(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ntpath.pyi b/mypy/typeshed/stdlib/@python2/ntpath.pyi new file mode 100644 index 000000000000..f096428602d4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/ntpath.pyi @@ -0,0 +1,85 @@ +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 + +_T = TypeVar("_T") + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == "win32": + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +def abspath(path: AnyStr) -> AnyStr: ... +def basename(p: AnyStr) -> AnyStr: ... +def dirname(p: AnyStr) -> AnyStr: ... +def expanduser(path: AnyStr) -> AnyStr: ... +def expandvars(path: AnyStr) -> AnyStr: ... +def normcase(s: AnyStr) -> AnyStr: ... +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": + def realpath(path: AnyStr) -> AnyStr: ... + +else: + def realpath(filename: AnyStr) -> AnyStr: ... + +# 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: ... + +# 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: ... + +# 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: ... +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... +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 split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == "win32": + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/nturl2path.pyi b/mypy/typeshed/stdlib/@python2/nturl2path.pyi new file mode 100644 index 000000000000..b87b008e4cec --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/nturl2path.pyi @@ -0,0 +1,4 @@ +from typing import AnyStr + +def url2pathname(url: AnyStr) -> AnyStr: ... +def pathname2url(p: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/os/__init__.pyi b/mypy/typeshed/stdlib/@python2/os/__init__.pyi new file mode 100644 index 000000000000..c43b24f2bdb7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/os/__init__.pyi @@ -0,0 +1,385 @@ +import sys +from _typeshed import AnyPath, 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, + Any, + AnyStr, + Callable, + Dict, + Generic, + Iterator, + List, + Mapping, + MutableMapping, + NamedTuple, + NoReturn, + Optional, + Sequence, + Set, + Text, + Tuple, + TypeVar, + Union, + overload, +) + +from . import path as path + +# We need to use something from path, or flake8 and pytype get unhappy +_supports_unicode_filenames = path.supports_unicode_filenames + +_T = TypeVar("_T") + +# ----- os variables ----- + +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 + +O_RDONLY: int +O_WRONLY: int +O_RDWR: int +O_APPEND: int +O_CREAT: int +O_EXCL: int +O_TRUNC: int +# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, +# including tests for mypy, use a more finer way than sys.platform before using these APIs +# See https://github.com/python/typeshed/pull/2286 for discussions +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only +O_NONBLOCK: int # Unix only +O_NOCTTY: int # Unix only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only +O_NOINHERIT: int # Windows only +O_SHORT_LIVED: int # Windows only +O_TEMPORARY: int # Windows only +O_RANDOM: int # Windows only +O_SEQUENTIAL: int # Windows only +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library +O_DIRECTORY: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library +O_LARGEFILE: int # Gnu extension if in C library + +curdir: str +pardir: str +sep: str +if sys.platform == "win32": + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +linesep: str +devnull: str +name: str + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + def copy(self) -> Dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[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] + pathconf_names: Dict[str, int] + sysconf_names: Dict[str, int] + + EX_OK: int + EX_USAGE: int + EX_DATAERR: int + EX_NOINPUT: int + EX_NOUSER: int + EX_NOHOST: int + EX_UNAVAILABLE: int + EX_SOFTWARE: int + EX_OSERR: int + EX_OSFILE: int + EX_CANTCREAT: int + EX_IOERR: int + EX_TEMPFAIL: int + EX_PROTOCOL: int + EX_NOPERM: int + EX_CONFIG: int + EX_NOTFOUND: int + +P_NOWAIT: int +P_NOWAITO: int +P_WAIT: int +if sys.platform == "win32": + P_DETACH: int + P_OVERLAY: int + +# wait()/waitpid() options +if sys.platform != "win32": + WNOHANG: int # Unix only + WCONTINUED: int # some Unix systems + WUNTRACED: int # Unix only + +TMP_MAX: int # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +if sys.version_info >= (3, 6): + from builtins import _PathLike + + PathLike = _PathLike # See comment in builtins + +class _StatVFS(NamedTuple): + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(code: int) -> str: ... +def umask(mask: int) -> int: ... + +if sys.platform != "win32": + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + def getresuid() -> Tuple[int, int, int]: ... + def getresgid() -> Tuple[int, int, int]: ... + def getuid() -> int: ... + def setegid(egid: int) -> None: ... + def seteuid(euid: int) -> None: ... + def setgid(gid: int) -> None: ... + def setgroups(groups: Sequence[int]) -> None: ... + def setpgrp() -> None: ... + def setpgid(pid: int, pgrp: int) -> None: ... + def setregid(rgid: int, egid: int) -> None: ... + def setresgid(rgid: int, egid: int, sgid: int) -> None: ... + def setresuid(ruid: int, euid: int, suid: int) -> None: ... + def setreuid(ruid: int, euid: int) -> None: ... + def getsid(pid: int) -> int: ... + def setsid() -> None: ... + def setuid(uid: int) -> None: ... + def uname() -> Tuple[str, str, str, str, str]: ... + +@overload +def getenv(key: Text) -> Optional[str]: ... +@overload +def getenv(key: Text, default: _T) -> Union[str, _T]: ... +def putenv(key: Union[bytes, Text], value: Union[bytes, Text]) -> None: ... +def unsetenv(key: Union[bytes, Text]) -> None: ... +def fdopen(fd: int, *args, **kwargs) -> IO[Any]: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def dup(fd: int) -> int: ... +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 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 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 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 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: ... +@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: ... + +# 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: ... + +if sys.platform != "win32": + # Unix only + def fchmod(fd: int, mode: int) -> None: ... + def fchown(fd: int, uid: int, gid: int) -> None: ... + if sys.platform != "darwin": + def fdatasync(fd: FileDescriptorLike) -> None: ... # Unix only, not Mac + def fpathconf(fd: int, name: Union[str, int]) -> int: ... + def fstatvfs(fd: int) -> _StatVFS: ... + def ftruncate(fd: int, length: int) -> None: ... + def isatty(fd: int) -> bool: ... + def openpty() -> Tuple[int, int]: ... # some flavors of Unix + 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 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: ... + +# 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: ... + +# 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 _exit(n: int) -> NoReturn: ... +def kill(pid: int, sig: int) -> None: ... + +if sys.platform != "win32": + # Unix only + def fork() -> int: ... + def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def killpg(__pgid: int, __signal: int) -> None: ... + 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 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: ... + +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 wait() -> Tuple[int, int]: ... + def wait3(options: int) -> Tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def WCOREDUMP(status: int) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + def confstr(name: Union[str, int]) -> Optional[str]: ... + 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: ... + +P_ALL: int +WEXITED: int +WNOWAIT: int diff --git a/mypy/typeshed/stdlib/@python2/os/path.pyi b/mypy/typeshed/stdlib/@python2/os/path.pyi new file mode 100644 index 000000000000..f096428602d4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/os/path.pyi @@ -0,0 +1,85 @@ +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 + +_T = TypeVar("_T") + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == "win32": + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +def abspath(path: AnyStr) -> AnyStr: ... +def basename(p: AnyStr) -> AnyStr: ... +def dirname(p: AnyStr) -> AnyStr: ... +def expanduser(path: AnyStr) -> AnyStr: ... +def expandvars(path: AnyStr) -> AnyStr: ... +def normcase(s: AnyStr) -> AnyStr: ... +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": + def realpath(path: AnyStr) -> AnyStr: ... + +else: + def realpath(filename: AnyStr) -> AnyStr: ... + +# 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: ... + +# 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: ... + +# 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: ... +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... +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 split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == "win32": + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi new file mode 100644 index 000000000000..f096428602d4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi @@ -0,0 +1,85 @@ +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 + +_T = TypeVar("_T") + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == "win32": + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +def abspath(path: AnyStr) -> AnyStr: ... +def basename(p: AnyStr) -> AnyStr: ... +def dirname(p: AnyStr) -> AnyStr: ... +def expanduser(path: AnyStr) -> AnyStr: ... +def expandvars(path: AnyStr) -> AnyStr: ... +def normcase(s: AnyStr) -> AnyStr: ... +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": + def realpath(path: AnyStr) -> AnyStr: ... + +else: + def realpath(filename: AnyStr) -> AnyStr: ... + +# 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: ... + +# 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: ... + +# 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: ... +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... +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 split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == "win32": + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pipes.pyi b/mypy/typeshed/stdlib/@python2/pipes.pyi new file mode 100644 index 000000000000..5249543425c6 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/pipes.pyi @@ -0,0 +1,13 @@ +from typing import IO, Any, AnyStr + +class Template: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, mode: str) -> IO[Any]: ... + def copy(self, infile: str, outfile: str) -> None: ... + +def quote(s: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/platform.pyi b/mypy/typeshed/stdlib/@python2/platform.pyi new file mode 100644 index 000000000000..cccb024d4278 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/platform.pyi @@ -0,0 +1,41 @@ +from typing import Any, Optional, Tuple + +__copyright__: Any +DEV_NULL: Any + +def libc_ver(executable=..., lib=..., version=..., chunksize: int = ...): ... +def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name: int = ...): ... +def dist(distname=..., version=..., id=..., supported_dists=...): ... + +class _popen: + tmpfile: Any + pipe: Any + bufsize: Any + mode: Any + def __init__(self, cmd, mode=..., bufsize: Optional[Any] = ...): ... + def read(self): ... + def readlines(self): ... + def close(self, remove=..., error=...): ... + __del__: Any + +def popen(cmd, mode=..., bufsize: Optional[Any] = ...): ... +def win32_ver(release=..., version=..., csd=..., ptype=...): ... +def mac_ver(release=..., versioninfo=..., machine=...): ... +def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ... +def system_alias(system, release, version): ... +def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... +def uname() -> Tuple[str, str, str, str, str, str]: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> Tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> Tuple[str, str]: ... +def python_compiler() -> str: ... +def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/popen2.pyi b/mypy/typeshed/stdlib/@python2/popen2.pyi new file mode 100644 index 000000000000..5101a6f87487 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/popen2.pyi @@ -0,0 +1,27 @@ +from typing import Any, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union + +_T = TypeVar("_T") + +class Popen3: + sts: int + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + childerr: Optional[TextIO] + def __init__(self, cmd: Iterable[Any] = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... + def __del__(self) -> None: ... + def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ... + def wait(self) -> int: ... + +class Popen4(Popen3): + childerr: None + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... + +def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... +def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... +def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/mypy/typeshed/stdlib/@python2/posix.pyi b/mypy/typeshed/stdlib/@python2/posix.pyi new file mode 100644 index 000000000000..ae79286ec50d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/posix.pyi @@ -0,0 +1,201 @@ +from _typeshed import FileDescriptorLike +from typing import IO, AnyStr, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple, TypeVar, Union + +error = OSError + +confstr_names: Dict[str, int] +environ: Dict[str, str] +pathconf_names: Dict[str, int] +sysconf_names: Dict[str, int] + +_T = TypeVar("_T") + +EX_CANTCREAT: int +EX_CONFIG: int +EX_DATAERR: int +EX_IOERR: int +EX_NOHOST: int +EX_NOINPUT: int +EX_NOPERM: int +EX_NOUSER: int +EX_OK: int +EX_OSERR: int +EX_OSFILE: int +EX_PROTOCOL: int +EX_SOFTWARE: int +EX_TEMPFAIL: int +EX_UNAVAILABLE: int +EX_USAGE: int +F_OK: int +NGROUPS_MAX: int +O_APPEND: int +O_ASYNC: int +O_CREAT: int +O_DIRECT: int +O_DIRECTORY: int +O_DSYNC: int +O_EXCL: int +O_LARGEFILE: int +O_NDELAY: int +O_NOATIME: int +O_NOCTTY: int +O_NOFOLLOW: int +O_NONBLOCK: int +O_RDONLY: int +O_RDWR: int +O_RSYNC: int +O_SYNC: int +O_TRUNC: int +O_WRONLY: int +R_OK: int +TMP_MAX: int +WCONTINUED: int +WNOHANG: int +WUNTRACED: int +W_OK: int +X_OK: int + +def WCOREDUMP(status: int) -> bool: ... +def WEXITSTATUS(status: int) -> bool: ... +def WIFCONTINUED(status: int) -> bool: ... +def WIFEXITED(status: int) -> bool: ... +def WIFSIGNALED(status: int) -> bool: ... +def WIFSTOPPED(status: int) -> bool: ... +def WSTOPSIG(status: int) -> bool: ... +def WTERMSIG(status: int) -> bool: ... + +class stat_result(object): + n_fields: int + n_sequence_fields: int + n_unnamed_fields: int + st_mode: int + st_ino: int + st_dev: int + st_nlink: int + st_uid: int + st_gid: int + st_size: int + st_atime: int + st_mtime: int + st_ctime: int + +class statvfs_result(NamedTuple): + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + +def _exit(status: int) -> None: ... +def abort() -> None: ... +def access(path: unicode, mode: int) -> bool: ... +def chdir(path: unicode) -> None: ... +def chmod(path: unicode, mode: int) -> None: ... +def chown(path: unicode, uid: int, gid: int) -> None: ... +def chroot(path: unicode) -> None: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def confstr(name: Union[str, int]) -> str: ... +def ctermid() -> str: ... +def dup(fd: int) -> int: ... +def dup2(fd: int, fd2: int) -> None: ... +def execv(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def execve(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def fchdir(fd: FileDescriptorLike) -> None: ... +def fchmod(fd: int, mode: int) -> None: ... +def fchown(fd: int, uid: int, gid: int) -> None: ... +def fdatasync(fd: FileDescriptorLike) -> None: ... +def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def fork() -> int: ... +def forkpty() -> Tuple[int, int]: ... +def fpathconf(fd: int, name: str) -> None: ... +def fstat(fd: int) -> stat_result: ... +def fstatvfs(fd: int) -> statvfs_result: ... +def fsync(fd: FileDescriptorLike) -> None: ... +def ftruncate(fd: int, length: int) -> None: ... +def getcwd() -> str: ... +def getcwdu() -> unicode: ... +def getegid() -> int: ... +def geteuid() -> int: ... +def getgid() -> int: ... +def getgroups() -> List[int]: ... +def getloadavg() -> Tuple[float, float, float]: ... +def getlogin() -> str: ... +def getpgid(pid: int) -> int: ... +def getpgrp() -> int: ... +def getpid() -> int: ... +def getppid() -> int: ... +def getresgid() -> Tuple[int, int, int]: ... +def getresuid() -> Tuple[int, int, int]: ... +def getsid(pid: int) -> int: ... +def getuid() -> int: ... +def initgroups(username: str, gid: int) -> None: ... +def isatty(fd: int) -> bool: ... +def kill(pid: int, sig: int) -> None: ... +def killpg(pgid: int, sig: int) -> None: ... +def lchown(path: unicode, uid: int, gid: int) -> None: ... +def link(source: unicode, link_name: str) -> None: ... +def listdir(path: AnyStr) -> List[AnyStr]: ... +def lseek(fd: int, pos: int, how: int) -> None: ... +def lstat(path: unicode) -> stat_result: ... +def major(device: int) -> int: ... +def makedev(major: int, minor: int) -> int: ... +def minor(device: int) -> int: ... +def mkdir(path: unicode, mode: int = ...) -> None: ... +def mkfifo(path: unicode, mode: int = ...) -> None: ... +def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... +def nice(increment: int) -> int: ... +def open(file: unicode, flags: int, mode: int = ...) -> int: ... +def openpty() -> Tuple[int, int]: ... +def pathconf(path: unicode, name: str) -> str: ... +def pipe() -> Tuple[int, int]: ... +def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def putenv(varname: str, value: str) -> None: ... +def read(fd: int, n: int) -> str: ... +def readlink(path: _T) -> _T: ... +def remove(path: unicode) -> None: ... +def rename(src: unicode, dst: unicode) -> None: ... +def rmdir(path: unicode) -> None: ... +def setegid(egid: int) -> None: ... +def seteuid(euid: int) -> None: ... +def setgid(gid: int) -> None: ... +def setgroups(groups: Sequence[int]) -> None: ... +def setpgid(pid: int, pgrp: int) -> None: ... +def setpgrp() -> None: ... +def setregid(rgid: int, egid: int) -> None: ... +def setresgid(rgid: int, egid: int, sgid: int) -> None: ... +def setresuid(ruid: int, euid: int, suid: int) -> None: ... +def setreuid(ruid: int, euid: int) -> None: ... +def setsid() -> None: ... +def setuid(pid: int) -> None: ... +def stat(path: unicode) -> stat_result: ... +def statvfs(path: unicode) -> statvfs_result: ... +def stat_float_times(fd: int) -> None: ... +def strerror(code: int) -> str: ... +def symlink(source: unicode, link_name: unicode) -> None: ... +def sysconf(name: Union[str, int]) -> int: ... +def system(command: unicode) -> int: ... +def tcgetpgrp(fd: int) -> int: ... +def tcsetpgrp(fd: int, pg: int) -> None: ... +def times() -> Tuple[float, float, float, float, float]: ... +def tmpfile() -> IO[str]: ... +def ttyname(fd: int) -> str: ... +def umask(mask: int) -> int: ... +def uname() -> Tuple[str, str, str, str, str]: ... +def unlink(path: unicode) -> None: ... +def unsetenv(varname: str) -> None: ... +def urandom(n: int) -> str: ... +def utime(path: unicode, times: Optional[Tuple[int, int]]) -> None: ... +def wait() -> int: ... + +_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] + +def wait3(options: int) -> Tuple[int, int, _r]: ... +def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... +def waitpid(pid: int, options: int) -> int: ... +def write(fd: int, str: str) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/posixpath.pyi b/mypy/typeshed/stdlib/@python2/posixpath.pyi new file mode 100644 index 000000000000..f096428602d4 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/posixpath.pyi @@ -0,0 +1,85 @@ +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 + +_T = TypeVar("_T") + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +if sys.platform == "win32": + altsep: str +else: + altsep: Optional[str] +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +def abspath(path: AnyStr) -> AnyStr: ... +def basename(p: AnyStr) -> AnyStr: ... +def dirname(p: AnyStr) -> AnyStr: ... +def expanduser(path: AnyStr) -> AnyStr: ... +def expandvars(path: AnyStr) -> AnyStr: ... +def normcase(s: AnyStr) -> AnyStr: ... +def normpath(path: AnyStr) -> AnyStr: ... + +if sys.platform == "win32": + def realpath(path: AnyStr) -> AnyStr: ... + +else: + def realpath(filename: AnyStr) -> AnyStr: ... + +# 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: ... + +# 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: ... + +# 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: ... +@overload +def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: StrPath, start: Optional[StrPath] = ...) -> Text: ... +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 split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == "win32": + def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/random.pyi b/mypy/typeshed/stdlib/@python2/random.pyi new file mode 100644 index 000000000000..059bd9360708 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/random.pyi @@ -0,0 +1,67 @@ +import _random +from typing import AbstractSet, Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, Union, overload + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +class _Sampleable(Protocol[_T_co]): + def __iter__(self) -> Iterator[_T_co]: ... + def __len__(self) -> int: ... + +class Random(_random.Random): + def __init__(self, x: object = ...) -> None: ... + def seed(self, x: object = ...) -> None: ... + def getstate(self) -> _random._State: ... + def setstate(self, state: _random._State) -> None: ... + def jumpahead(self, n: int) -> None: ... + def getrandbits(self, k: int) -> int: ... + @overload + def randrange(self, stop: int) -> int: ... + @overload + def randrange(self, start: int, stop: int, step: int = ...) -> int: ... + def randint(self, a: int, b: int) -> int: ... + def choice(self, seq: Sequence[_T]) -> _T: ... + def shuffle(self, x: MutableSequence[Any], random: Callable[[], None] = ...) -> None: ... + def sample(self, population: _Sampleable[_T], k: int) -> List[_T]: ... + def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... + def betavariate(self, alpha: float, beta: float) -> float: ... + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... + def gauss(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): ... + +# ----- random function stubs ----- +def seed(x: object = ...) -> None: ... +def getstate() -> object: ... +def setstate(state: object) -> None: ... +def jumpahead(n: int) -> None: ... +def getrandbits(k: int) -> int: ... +@overload +def randrange(stop: int) -> int: ... +@overload +def randrange(start: int, stop: int, step: int = ...) -> int: ... +def randint(a: int, b: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +def shuffle(x: MutableSequence[Any], random: Callable[[], float] = ...) -> None: ... +def sample(population: _Sampleable[_T], k: int) -> List[_T]: ... +def random() -> float: ... +def uniform(a: float, b: float) -> float: ... +def triangular(low: float = ..., high: float = ..., mode: float = ...) -> float: ... +def betavariate(alpha: float, beta: float) -> float: ... +def expovariate(lambd: float) -> float: ... +def gammavariate(alpha: float, beta: float) -> float: ... +def gauss(mu: float, sigma: float) -> float: ... +def lognormvariate(mu: float, sigma: float) -> float: ... +def normalvariate(mu: float, sigma: float) -> float: ... +def vonmisesvariate(mu: float, kappa: float) -> float: ... +def paretovariate(alpha: float) -> float: ... +def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/re.pyi b/mypy/typeshed/stdlib/@python2/re.pyi new file mode 100644 index 000000000000..11e3d02fcf5c --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/re.pyi @@ -0,0 +1,108 @@ +from typing import ( + Any, + AnyStr, + Callable, + Dict, + Generic, + Iterator, + List, + Match, + Optional, + Pattern, + Sequence, + Tuple, + Union, + overload, +) + +# ----- re variables and constants ----- +DEBUG: int +I: int +IGNORECASE: int +L: int +LOCALE: int +M: int +MULTILINE: int +S: int +DOTALL: int +X: int +VERBOSE: int +U: int +UNICODE: int +T: int +TEMPLATE: int + +class error(Exception): ... + +@overload +def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... +@overload +def search(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def search(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def split(pattern: Union[str, unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +@overload +def split( + pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, maxsplit: int = ..., flags: int = ... +) -> List[AnyStr]: ... +@overload +def findall(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... +@overload +def findall(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> List[Any]: ... + +# Return an iterator yielding match objects over all non-overlapping matches +# for the RE pattern in string. The string is scanned left-to-right, and +# matches are returned in the order found. Empty matches are included in the +# result unless they touch the beginning of another match. +@overload +def finditer(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def finditer(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def sub(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... +@overload +def sub( + pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... +) -> AnyStr: ... +@overload +def sub( + pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... +) -> AnyStr: ... +@overload +def sub( + pattern: Union[Pattern[str], Pattern[unicode]], + repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, + count: int = ..., + flags: int = ..., +) -> AnyStr: ... +@overload +def subn( + pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... +) -> Tuple[AnyStr, int]: ... +@overload +def subn( + pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... +) -> Tuple[AnyStr, int]: ... +@overload +def subn( + pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... +) -> Tuple[AnyStr, int]: ... +@overload +def subn( + pattern: Union[Pattern[str], Pattern[unicode]], + repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, + count: int = ..., + flags: int = ..., +) -> Tuple[AnyStr, int]: ... +def escape(string: AnyStr) -> AnyStr: ... +def purge() -> None: ... +def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/repr.pyi b/mypy/typeshed/stdlib/@python2/repr.pyi new file mode 100644 index 000000000000..bdb8822ac77d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/repr.pyi @@ -0,0 +1,34 @@ +from typing import Any, List + +class Repr: + maxarray: int + maxdeque: int + maxdict: int + maxfrozenset: int + maxlevel: int + maxlist: int + maxlong: int + maxother: int + maxset: int + maxstring: int + maxtuple: int + def __init__(self) -> None: ... + def _repr_iterable(self, x, level: complex, left, right, maxiter, trail=...) -> str: ... + def repr(self, x) -> str: ... + def repr1(self, x, level: complex) -> str: ... + def repr_array(self, x, level: complex) -> str: ... + def repr_deque(self, x, level: complex) -> str: ... + def repr_dict(self, x, level: complex) -> str: ... + def repr_frozenset(self, x, level: complex) -> str: ... + def repr_instance(self, x, level: complex) -> str: ... + def repr_list(self, x, level: complex) -> str: ... + def repr_long(self, x, level: complex) -> str: ... + def repr_set(self, x, level: complex) -> str: ... + def repr_str(self, x, level: complex) -> str: ... + def repr_tuple(self, x, level: complex) -> str: ... + +def _possibly_sorted(x) -> List[Any]: ... + +aRepr: Repr + +def repr(x) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/resource.pyi b/mypy/typeshed/stdlib/@python2/resource.pyi new file mode 100644 index 000000000000..ad9502db1940 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/resource.pyi @@ -0,0 +1,46 @@ +from typing import NamedTuple, Tuple + +class error(Exception): ... + +RLIM_INFINITY: int + +def getrlimit(resource: int) -> Tuple[int, int]: ... +def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... + +RLIMIT_CORE: int +RLIMIT_CPU: int +RLIMIT_FSIZE: int +RLIMIT_DATA: int +RLIMIT_STACK: int +RLIMIT_RSS: int +RLIMIT_NPROC: int +RLIMIT_NOFILE: int +RLIMIT_OFILE: int +RLIMIT_MEMLOCK: int +RLIMIT_VMEM: int +RLIMIT_AS: int + +class _RUsage(NamedTuple): + ru_utime: float + ru_stime: float + ru_maxrss: int + ru_ixrss: int + ru_idrss: int + ru_isrss: int + ru_minflt: int + ru_majflt: int + ru_nswap: int + ru_inblock: int + ru_oublock: int + ru_msgsnd: int + ru_msgrcv: int + ru_nsignals: int + ru_nvcsw: int + ru_nivcsw: int + +def getrusage(who: int) -> _RUsage: ... +def getpagesize() -> int: ... + +RUSAGE_SELF: int +RUSAGE_CHILDREN: int +RUSAGE_BOTH: int diff --git a/mypy/typeshed/stdlib/@python2/rfc822.pyi b/mypy/typeshed/stdlib/@python2/rfc822.pyi new file mode 100644 index 000000000000..f536568b807d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/rfc822.pyi @@ -0,0 +1,75 @@ +from typing import Any, Optional + +class Message: + fp: Any + seekable: Any + startofheaders: Any + startofbody: Any + def __init__(self, fp, seekable: int = ...): ... + def rewindbody(self): ... + dict: Any + unixfrom: Any + headers: Any + status: Any + def readheaders(self): ... + def isheader(self, line): ... + def islast(self, line): ... + def iscomment(self, line): ... + def getallmatchingheaders(self, name): ... + def getfirstmatchingheader(self, name): ... + def getrawheader(self, name): ... + def getheader(self, name, default: Optional[Any] = ...): ... + get: Any + def getheaders(self, name): ... + def getaddr(self, name): ... + def getaddrlist(self, name): ... + def getdate(self, name): ... + def getdate_tz(self, name): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, value): ... + def __delitem__(self, name): ... + def setdefault(self, name, default=...): ... + def has_key(self, name): ... + def __contains__(self, name): ... + def __iter__(self): ... + def keys(self): ... + def values(self): ... + def items(self): ... + +class AddrlistClass: + specials: Any + pos: Any + LWS: Any + CR: Any + atomends: Any + phraseends: Any + field: Any + commentlist: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: int = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... diff --git a/mypy/typeshed/stdlib/@python2/robotparser.pyi b/mypy/typeshed/stdlib/@python2/robotparser.pyi new file mode 100644 index 000000000000..403039ae91c9 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/robotparser.pyi @@ -0,0 +1,7 @@ +class RobotFileParser: + def set_url(self, url: str): ... + def read(self): ... + def parse(self, lines: str): ... + def can_fetch(self, user_agent: str, url: str): ... + def mtime(self): ... + def modified(self): ... diff --git a/mypy/typeshed/stdlib/@python2/runpy.pyi b/mypy/typeshed/stdlib/@python2/runpy.pyi new file mode 100644 index 000000000000..6674af077d5d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/runpy.pyi @@ -0,0 +1,17 @@ +from typing import Any, Optional + +class _TempModule: + mod_name: Any + module: Any + def __init__(self, mod_name): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +class _ModifiedArgv0: + value: Any + def __init__(self, value): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +def run_module(mod_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ..., alter_sys: bool = ...): ... +def run_path(path_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ...): ... diff --git a/mypy/typeshed/stdlib/@python2/sets.pyi b/mypy/typeshed/stdlib/@python2/sets.pyi new file mode 100644 index 000000000000..e0a652053cc5 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sets.pyi @@ -0,0 +1,60 @@ +from typing import Any, Callable, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union + +_T = TypeVar("_T") +_Setlike = Union[BaseSet[_T], Iterable[_T]] +_SelfT = TypeVar("_SelfT") + +class BaseSet(Iterable[_T]): + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __iter__(self) -> Iterator[_T]: ... + def __cmp__(self, other: Any) -> int: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + def copy(self: _SelfT) -> _SelfT: ... + def __copy__(self: _SelfT) -> _SelfT: ... + def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... + def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def union(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... + def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def intersection(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... + def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def symmetric_difference(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... + def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def difference(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... + def __contains__(self, element: Any) -> bool: ... + def issubset(self, other: BaseSet[_T]) -> bool: ... + def issuperset(self, other: BaseSet[_T]) -> bool: ... + def __le__(self, other: BaseSet[_T]) -> bool: ... + def __ge__(self, other: BaseSet[_T]) -> bool: ... + def __lt__(self, other: BaseSet[_T]) -> bool: ... + def __gt__(self, other: BaseSet[_T]) -> bool: ... + +class ImmutableSet(BaseSet[_T], Hashable): + def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... + def __hash__(self) -> int: ... + +class Set(BaseSet[_T]): + def __init__(self, iterable: Optional[_Setlike[_T]] = ...) -> None: ... + def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def union_update(self, other: _Setlike[_T]) -> None: ... + def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def intersection_update(self, other: _Setlike[Any]) -> None: ... + def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... + def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def difference_update(self, other: _Setlike[Any]) -> None: ... + def update(self, iterable: _Setlike[_T]) -> None: ... + def clear(self) -> None: ... + def add(self, element: _T) -> None: ... + def remove(self, element: _T) -> None: ... + def discard(self, element: _T) -> None: ... + def pop(self) -> _T: ... + def __as_immutable__(self) -> ImmutableSet[_T]: ... + def __as_temporarily_immutable__(self) -> _TemporarilyImmutableSet[_T]: ... + +class _TemporarilyImmutableSet(BaseSet[_T]): + def __init__(self, set: BaseSet[_T]) -> None: ... + def __hash__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/sha.pyi b/mypy/typeshed/stdlib/@python2/sha.pyi new file mode 100644 index 000000000000..aac8c8bc57bb --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sha.pyi @@ -0,0 +1,10 @@ +class sha(object): + def update(self, arg: str) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> sha: ... + +def new(string: str = ...) -> sha: ... + +blocksize: int +digest_size: int diff --git a/mypy/typeshed/stdlib/@python2/shelve.pyi b/mypy/typeshed/stdlib/@python2/shelve.pyi new file mode 100644 index 000000000000..442c3fe3d52e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/shelve.pyi @@ -0,0 +1,36 @@ +import collections +from typing import Any, Dict, Iterator, List, Optional, Tuple + +class Shelf(collections.MutableMapping[Any, Any]): + def __init__( + self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ... + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> List[Any]: ... + def __len__(self) -> int: ... + def has_key(self, key: Any) -> bool: ... + def __contains__(self, key: Any) -> bool: ... + def get(self, key: Any, default: Any = ...) -> Any: ... + def __getitem__(self, key: Any) -> Any: ... + def __setitem__(self, key: Any, value: Any) -> None: ... + def __delitem__(self, key: Any) -> None: ... + def __enter__(self) -> Shelf: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + def sync(self) -> None: ... + +class BsdDbShelf(Shelf): + def __init__( + self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ... + ) -> None: ... + def set_location(self, key: Any) -> Tuple[str, Any]: ... + def next(self) -> Tuple[str, Any]: ... + def previous(self) -> Tuple[str, Any]: ... + def first(self) -> Tuple[str, Any]: ... + def last(self) -> Tuple[str, Any]: ... + +class DbfilenameShelf(Shelf): + def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... + +def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/mypy/typeshed/stdlib/@python2/shlex.pyi b/mypy/typeshed/stdlib/@python2/shlex.pyi new file mode 100644 index 000000000000..37c667238f09 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/shlex.pyi @@ -0,0 +1,30 @@ +from typing import IO, Any, List, Optional, Text, TypeVar, Union + +def split(s: Optional[str], comments: bool = ..., posix: bool = ...) -> List[str]: ... + +_SLT = TypeVar("_SLT", bound=shlex) + +class shlex: + def __init__(self, instream: Union[IO[Any], Text] = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... + def __iter__(self: _SLT) -> _SLT: ... + def next(self) -> str: ... + def get_token(self) -> Optional[str]: ... + def push_token(self, _str: str) -> None: ... + def read_token(self) -> str: ... + def sourcehook(self, filename: str) -> None: ... + def push_source(self, stream: IO[Any], filename: str = ...) -> None: ... + def pop_source(self) -> IO[Any]: ... + def error_leader(self, file: str = ..., line: int = ...) -> str: ... + commenters: str + wordchars: str + whitespace: str + escape: str + quotes: str + escapedquotes: str + whitespace_split: bool + infile: IO[Any] + source: Optional[str] + debug: int + lineno: int + token: Any + eof: Optional[str] diff --git a/mypy/typeshed/stdlib/@python2/signal.pyi b/mypy/typeshed/stdlib/@python2/signal.pyi new file mode 100644 index 000000000000..c33ff19dcf10 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/signal.pyi @@ -0,0 +1,68 @@ +from types import FrameType +from typing import Any, Callable, Tuple, Union + +SIG_DFL: int = ... +SIG_IGN: int = ... + +ITIMER_REAL: int = ... +ITIMER_VIRTUAL: int = ... +ITIMER_PROF: int = ... + +NSIG: int = ... + +SIGABRT: int = ... +SIGALRM: int = ... +SIGBREAK: int = ... # Windows +SIGBUS: int = ... +SIGCHLD: int = ... +SIGCLD: int = ... +SIGCONT: int = ... +SIGEMT: int = ... +SIGFPE: int = ... +SIGHUP: int = ... +SIGILL: int = ... +SIGINFO: int = ... +SIGINT: int = ... +SIGIO: int = ... +SIGIOT: int = ... +SIGKILL: int = ... +SIGPIPE: int = ... +SIGPOLL: int = ... +SIGPROF: int = ... +SIGPWR: int = ... +SIGQUIT: int = ... +SIGRTMAX: int = ... +SIGRTMIN: int = ... +SIGSEGV: int = ... +SIGSTOP: int = ... +SIGSYS: int = ... +SIGTERM: int = ... +SIGTRAP: int = ... +SIGTSTP: int = ... +SIGTTIN: int = ... +SIGTTOU: int = ... +SIGURG: int = ... +SIGUSR1: int = ... +SIGUSR2: int = ... +SIGVTALRM: int = ... +SIGWINCH: int = ... +SIGXCPU: int = ... +SIGXFSZ: int = ... + +# Windows +CTRL_C_EVENT: int = ... +CTRL_BREAK_EVENT: int = ... + +class ItimerError(IOError): ... + +_HANDLER = Union[Callable[[int, FrameType], None], int, None] + +def alarm(time: int) -> int: ... +def getsignal(signalnum: int) -> _HANDLER: ... +def pause() -> None: ... +def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... +def getitimer(which: int) -> Tuple[float, float]: ... +def set_wakeup_fd(fd: int) -> int: ... +def siginterrupt(signalnum: int, flag: bool) -> None: ... +def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: ... +def default_int_handler(signum: int, frame: FrameType) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/smtplib.pyi b/mypy/typeshed/stdlib/@python2/smtplib.pyi new file mode 100644 index 000000000000..438221a439b7 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/smtplib.pyi @@ -0,0 +1,86 @@ +from typing import Any + +class SMTPException(Exception): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code: Any + smtp_error: Any + args: Any + def __init__(self, code, msg) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_code: Any + smtp_error: Any + sender: Any + args: Any + def __init__(self, code, msg, sender) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients: Any + args: Any + def __init__(self, recipients) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addr): ... +def quotedata(data): ... + +class SSLFakeFile: + sslobj: Any + def __init__(self, sslobj) -> None: ... + def readline(self, size=...): ... + def close(self): ... + +class SMTP: + debuglevel: Any + file: Any + helo_resp: Any + ehlo_msg: Any + ehlo_resp: Any + does_esmtp: Any + default_port: Any + timeout: Any + esmtp_features: Any + local_hostname: Any + def __init__(self, host: str = ..., port: int = ..., local_hostname=..., timeout=...) -> None: ... + def set_debuglevel(self, debuglevel): ... + sock: Any + def connect(self, host=..., port=...): ... + def send(self, str): ... + def putcmd(self, cmd, args=...): ... + def getreply(self): ... + def docmd(self, cmd, args=...): ... + def helo(self, name=...): ... + def ehlo(self, name=...): ... + def has_extn(self, opt): ... + def help(self, args=...): ... + def rset(self): ... + def noop(self): ... + def mail(self, sender, options=...): ... + def rcpt(self, recip, options=...): ... + def data(self, msg): ... + def verify(self, address): ... + vrfy: Any + def expn(self, address): ... + def ehlo_or_helo_if_needed(self): ... + def login(self, user, password): ... + def starttls(self, keyfile=..., certfile=...): ... + def sendmail(self, from_addr, to_addrs, msg, mail_options=..., rcpt_options=...): ... + def close(self): ... + def quit(self): ... + +class SMTP_SSL(SMTP): + default_port: Any + keyfile: Any + certfile: Any + def __init__(self, host=..., port=..., local_hostname=..., keyfile=..., certfile=..., timeout=...) -> None: ... + +class LMTP(SMTP): + ehlo_msg: Any + def __init__(self, host=..., port=..., local_hostname=...) -> None: ... + sock: Any + def connect(self, host=..., port=...): ... diff --git a/mypy/typeshed/stdlib/@python2/spwd.pyi b/mypy/typeshed/stdlib/@python2/spwd.pyi new file mode 100644 index 000000000000..756c142a61da --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/spwd.pyi @@ -0,0 +1,15 @@ +from typing import List, NamedTuple + +class struct_spwd(NamedTuple): + sp_nam: str + sp_pwd: str + sp_lstchg: int + sp_min: int + sp_max: int + sp_warn: int + sp_inact: int + sp_expire: int + sp_flag: int + +def getspall() -> List[struct_spwd]: ... +def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/@python2/sre_constants.pyi b/mypy/typeshed/stdlib/@python2/sre_constants.pyi new file mode 100644 index 000000000000..bc15754d6fa1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sre_constants.pyi @@ -0,0 +1,93 @@ +from typing import Dict, List, TypeVar + +MAGIC: int +MAXREPEAT: int + +class error(Exception): ... + +FAILURE: str +SUCCESS: str +ANY: str +ANY_ALL: str +ASSERT: str +ASSERT_NOT: str +AT: str +BIGCHARSET: str +BRANCH: str +CALL: str +CATEGORY: str +CHARSET: str +GROUPREF: str +GROUPREF_IGNORE: str +GROUPREF_EXISTS: str +IN: str +IN_IGNORE: str +INFO: str +JUMP: str +LITERAL: str +LITERAL_IGNORE: str +MARK: str +MAX_REPEAT: str +MAX_UNTIL: str +MIN_REPEAT: str +MIN_UNTIL: str +NEGATE: str +NOT_LITERAL: str +NOT_LITERAL_IGNORE: str +RANGE: str +REPEAT: str +REPEAT_ONE: str +SUBPATTERN: str +MIN_REPEAT_ONE: str +AT_BEGINNING: str +AT_BEGINNING_LINE: str +AT_BEGINNING_STRING: str +AT_BOUNDARY: str +AT_NON_BOUNDARY: str +AT_END: str +AT_END_LINE: str +AT_END_STRING: str +AT_LOC_BOUNDARY: str +AT_LOC_NON_BOUNDARY: str +AT_UNI_BOUNDARY: str +AT_UNI_NON_BOUNDARY: str +CATEGORY_DIGIT: str +CATEGORY_NOT_DIGIT: str +CATEGORY_SPACE: str +CATEGORY_NOT_SPACE: str +CATEGORY_WORD: str +CATEGORY_NOT_WORD: str +CATEGORY_LINEBREAK: str +CATEGORY_NOT_LINEBREAK: str +CATEGORY_LOC_WORD: str +CATEGORY_LOC_NOT_WORD: str +CATEGORY_UNI_DIGIT: str +CATEGORY_UNI_NOT_DIGIT: str +CATEGORY_UNI_SPACE: str +CATEGORY_UNI_NOT_SPACE: str +CATEGORY_UNI_WORD: str +CATEGORY_UNI_NOT_WORD: str +CATEGORY_UNI_LINEBREAK: str +CATEGORY_UNI_NOT_LINEBREAK: str + +_T = TypeVar("_T") + +def makedict(list: List[_T]) -> Dict[_T, int]: ... + +OP_IGNORE: Dict[str, str] +AT_MULTILINE: Dict[str, str] +AT_LOCALE: Dict[str, str] +AT_UNICODE: Dict[str, str] +CH_LOCALE: Dict[str, str] +CH_UNICODE: Dict[str, str] +SRE_FLAG_TEMPLATE: int +SRE_FLAG_IGNORECASE: int +SRE_FLAG_LOCALE: int +SRE_FLAG_MULTILINE: int +SRE_FLAG_DOTALL: int +SRE_FLAG_UNICODE: int +SRE_FLAG_VERBOSE: int +SRE_FLAG_DEBUG: int +SRE_INFO_PREFIX: int +SRE_INFO_LITERAL: int +SRE_INFO_CHARSET: int diff --git a/mypy/typeshed/stdlib/@python2/sre_parse.pyi b/mypy/typeshed/stdlib/@python2/sre_parse.pyi new file mode 100644 index 000000000000..e2a0be4e3bf1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sre_parse.pyi @@ -0,0 +1,62 @@ +from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union + +SPECIAL_CHARS: str +REPEAT_CHARS: str +DIGITS: Set[Any] +OCTDIGITS: Set[Any] +HEXDIGITS: Set[Any] +WHITESPACE: Set[Any] +ESCAPES: Dict[str, Tuple[str, int]] +CATEGORIES: Dict[str, Union[Tuple[str, str], Tuple[str, List[Tuple[str, str]]]]] +FLAGS: Dict[str, int] + +class Pattern: + flags: int + open: List[int] + groups: int + groupdict: Dict[str, int] + lookbehind: int + def __init__(self) -> None: ... + def opengroup(self, name: str = ...) -> int: ... + def closegroup(self, gid: int) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + +_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] +_OpInType = List[Tuple[str, int]] +_OpBranchType = Tuple[None, List[SubPattern]] +_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_CodeType = Union[str, _AvType] + +class SubPattern: + pattern: str + data: List[_CodeType] + width: Optional[int] + def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... + def dump(self, level: int = ...) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... + def __setitem__(self, index: Union[int, slice], code: _CodeType): ... + def insert(self, index, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> int: ... + +class Tokenizer: + string: str + index: int + def __init__(self, string: str) -> None: ... + def match(self, char: str, skip: int = ...) -> int: ... + def get(self) -> Optional[str]: ... + def tell(self) -> Tuple[int, Optional[str]]: ... + def seek(self, index: int) -> None: ... + +def isident(char: str) -> bool: ... +def isdigit(char: str) -> bool: ... +def isname(name: str) -> bool: ... +def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... + +_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] + +def parse_template(source: str, pattern: _Pattern[Any]) -> _Template: ... +def expand_template(template: _Template, match: Match[Any]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/stat.pyi b/mypy/typeshed/stdlib/@python2/stat.pyi new file mode 100644 index 000000000000..b75c955d7ed9 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/stat.pyi @@ -0,0 +1,58 @@ +def S_ISDIR(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISBLK(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +ST_MODE: int +ST_INO: int +ST_DEV: int +ST_NLINK: int +ST_UID: int +ST_GID: int +ST_SIZE: int +ST_ATIME: int +ST_MTIME: int +ST_CTIME: int +S_IFSOCK: int +S_IFLNK: int +S_IFREG: int +S_IFBLK: int +S_IFDIR: int +S_IFCHR: int +S_IFIFO: int +S_ISUID: int +S_ISGID: int +S_ISVTX: int +S_IRWXU: int +S_IRUSR: int +S_IWUSR: int +S_IXUSR: int +S_IRWXG: int +S_IRGRP: int +S_IWGRP: int +S_IXGRP: int +S_IRWXO: int +S_IROTH: int +S_IWOTH: int +S_IXOTH: int +S_ENFMT: int +S_IREAD: int +S_IWRITE: int +S_IEXEC: int +UF_NODUMP: int +UF_IMMUTABLE: int +UF_APPEND: int +UF_OPAQUE: int +UF_NOUNLINK: int +UF_COMPRESSED: int +UF_HIDDEN: int +SF_ARCHIVED: int +SF_IMMUTABLE: int +SF_APPEND: int +SF_NOUNLINK: int +SF_SNAPSHOT: int diff --git a/mypy/typeshed/stdlib/@python2/string.pyi b/mypy/typeshed/stdlib/@python2/string.pyi new file mode 100644 index 000000000000..03a6a2dfd800 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/string.pyi @@ -0,0 +1,68 @@ +from typing import Any, AnyStr, Iterable, List, Mapping, Optional, Sequence, Text, Tuple, Union, overload + +ascii_letters: str +ascii_lowercase: str +ascii_uppercase: str +digits: str +hexdigits: str +letters: str +lowercase: str +octdigits: str +punctuation: str +printable: str +uppercase: str +whitespace: str + +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... + +# TODO: originally named 'from' +def maketrans(_from: str, to: str) -> str: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> int: ... +def capitalize(word: AnyStr) -> AnyStr: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def lower(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def rstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def strip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def translate(s: str, table: str, deletechars: str = ...) -> str: ... +def upper(s: AnyStr) -> AnyStr: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... + +class Template: + template: Text + def __init__(self, template: Text) -> None: ... + @overload + def substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... + @overload + def substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]] = ..., **kwds: Text) -> Text: ... + @overload + def safe_substitute(self, mapping: Union[Mapping[str, str], Mapping[unicode, str]] = ..., **kwds: str) -> str: ... + @overload + def safe_substitute(self, mapping: Union[Mapping[str, Text], Mapping[unicode, Text]], **kwds: Text) -> Text: ... + +# TODO(MichalPokorny): This is probably badly and/or loosely typed. +class Formatter(object): + def format(self, format_string: str, *args, **kwargs) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... + def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... + def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: Union[int, str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/stringold.pyi b/mypy/typeshed/stdlib/@python2/stringold.pyi new file mode 100644 index 000000000000..ea11da72575d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/stringold.pyi @@ -0,0 +1,44 @@ +from typing import AnyStr, Iterable, List, Optional, Type + +whitespace: str +lowercase: str +uppercase: str +letters: str +digits: str +hexdigits: str +octdigits: str +_idmap: str +_idmapL: Optional[List[str]] +index_error = ValueError +atoi_error = ValueError +atof_error = ValueError +atol_error = ValueError + +def lower(s: AnyStr) -> AnyStr: ... +def upper(s: AnyStr) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def strip(s: AnyStr) -> AnyStr: ... +def lstrip(s: AnyStr) -> AnyStr: ... +def rstrip(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> long: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... +def translate(s: str, table: str, deletions: str = ...) -> str: ... +def capitalize(s: AnyStr) -> AnyStr: ... +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +def maketrans(fromstr: str, tostr: str) -> str: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/strop.pyi b/mypy/typeshed/stdlib/@python2/strop.pyi new file mode 100644 index 000000000000..81035eaabe79 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/strop.pyi @@ -0,0 +1,27 @@ +from typing import List, Sequence + +lowercase: str +uppercase: str +whitespace: str + +def atof(a: str) -> float: ... +def atoi(a: str, base: int = ...) -> int: ... +def atol(a: str, base: int = ...) -> long: ... +def capitalize(s: str) -> str: ... +def count(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def expandtabs(string: str, tabsize: int = ...) -> str: ... +def find(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def join(list: Sequence[str], sep: str = ...) -> str: ... +def joinfields(list: Sequence[str], sep: str = ...) -> str: ... +def lower(s: str) -> str: ... +def lstrip(s: str) -> str: ... +def maketrans(frm: str, to: str) -> str: ... +def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: ... +def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... +def rstrip(s: str) -> str: ... +def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... +def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... +def strip(s: str) -> str: ... +def swapcase(s: str) -> str: ... +def translate(s: str, table: str, deletechars: str = ...) -> str: ... +def upper(s: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/subprocess.pyi b/mypy/typeshed/stdlib/@python2/subprocess.pyi new file mode 100644 index 000000000000..b3a2e92e7fec --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/subprocess.pyi @@ -0,0 +1,115 @@ +from typing import IO, Any, Callable, Generic, List, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union + +_FILE = Union[None, int, IO[Any]] +_TXT = Union[bytes, Text] +_CMD = Union[_TXT, Sequence[_TXT]] +_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] + +# Same args as Popen.__init__ +def call( + args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., +) -> int: ... +def check_call( + args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., +) -> int: ... + +# Same args as Popen.__init__ except for stdout +def check_output( + args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., +) -> bytes: ... + +PIPE: int +STDOUT: int + +class CalledProcessError(Exception): + returncode: int + # morally: _CMD + cmd: Any + # morally: Optional[bytes] + output: bytes + def __init__(self, returncode: int, cmd: _CMD, output: Optional[bytes] = ...) -> None: ... + +# We use a dummy type variable used to make Popen generic like it is in python 3 +_T = TypeVar("_T", bound=bytes) + +class Popen(Generic[_T]): + stdin: Optional[IO[bytes]] + stdout: Optional[IO[bytes]] + stderr: Optional[IO[bytes]] + pid: int + returncode: int + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: Optional[_TXT] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + ) -> Popen[bytes]: ... + def poll(self) -> Optional[int]: ... + def wait(self) -> int: ... + # morally: -> Tuple[Optional[bytes], Optional[bytes]] + def communicate(self, input: Optional[_TXT] = ...) -> Tuple[bytes, bytes]: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + +def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented + +# Windows-only: STARTUPINFO etc. + +STD_INPUT_HANDLE: Any +STD_OUTPUT_HANDLE: Any +STD_ERROR_HANDLE: Any +SW_HIDE: Any +STARTF_USESTDHANDLES: Any +STARTF_USESHOWWINDOW: Any +CREATE_NEW_CONSOLE: Any +CREATE_NEW_PROCESS_GROUP: Any diff --git a/mypy/typeshed/stdlib/@python2/symbol.pyi b/mypy/typeshed/stdlib/@python2/symbol.pyi new file mode 100644 index 000000000000..a3561fe6b26f --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/symbol.pyi @@ -0,0 +1,89 @@ +from typing import Dict + +single_input: int +file_input: int +eval_input: int +decorator: int +decorators: int +decorated: int +funcdef: int +parameters: int +varargslist: int +fpdef: int +fplist: int +stmt: int +simple_stmt: int +small_stmt: int +expr_stmt: int +augassign: int +print_stmt: int +del_stmt: int +pass_stmt: int +flow_stmt: int +break_stmt: int +continue_stmt: int +return_stmt: int +yield_stmt: int +raise_stmt: int +import_stmt: int +import_name: int +import_from: int +import_as_name: int +dotted_as_name: int +import_as_names: int +dotted_as_names: int +dotted_name: int +global_stmt: int +exec_stmt: int +assert_stmt: int +compound_stmt: int +if_stmt: int +while_stmt: int +for_stmt: int +try_stmt: int +with_stmt: int +with_item: int +except_clause: int +suite: int +testlist_safe: int +old_test: int +old_lambdef: int +test: int +or_test: int +and_test: int +not_test: int +comparison: int +comp_op: int +expr: int +xor_expr: int +and_expr: int +shift_expr: int +arith_expr: int +term: int +factor: int +power: int +atom: int +listmaker: int +testlist_comp: int +lambdef: int +trailer: int +subscriptlist: int +subscript: int +sliceop: int +exprlist: int +testlist: int +dictorsetmaker: int +classdef: int +arglist: int +argument: int +list_iter: int +list_for: int +list_if: int +comp_iter: int +comp_for: int +comp_if: int +testlist1: int +encoding_decl: int +yield_expr: int + +sym_name: Dict[int, str] diff --git a/mypy/typeshed/stdlib/@python2/sys.pyi b/mypy/typeshed/stdlib/@python2/sys.pyi new file mode 100644 index 000000000000..0136f3456c58 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/sys.pyi @@ -0,0 +1,130 @@ +from types import ClassType, FrameType, ModuleType, TracebackType +from typing import IO, Any, BinaryIO, Callable, Dict, List, NoReturn, Optional, Sequence, Text, Tuple, Type, Union, overload + +# The following type alias are stub-only and do not exist during runtime +_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] + +class _flags: + bytes_warning: int + debug: int + division_new: int + division_warning: int + dont_write_bytecode: int + hash_randomization: int + ignore_environment: int + inspect: int + interactive: int + no_site: int + no_user_site: int + optimize: int + py3k_warning: int + tabcheck: int + unicode: int + verbose: int + +class _float_info: + max: float + max_exp: int + max_10_exp: int + min: float + min_exp: int + min_10_exp: int + dig: int + mant_dig: int + epsilon: float + radix: int + rounds: int + +class _version_info(Tuple[int, int, int, str, int]): + major: int + minor: int + micro: int + releaselevel: str + serial: int + +_mercurial: Tuple[str, str, str] +api_version: int +argv: List[str] +builtin_module_names: Tuple[str, ...] +byteorder: str +copyright: str +dont_write_bytecode: bool +exec_prefix: str +executable: str +flags: _flags +float_repr_style: str +hexversion: int +long_info: object +maxint: int +maxsize: int +maxunicode: int +modules: Dict[str, Any] +path: List[str] +platform: str +prefix: str +py3kwarning: bool +__stderr__: IO[str] +__stdin__: IO[str] +__stdout__: IO[str] +stderr: IO[str] +stdin: IO[str] +stdout: IO[str] +subversion: Tuple[str, str, str] +version: str +warnoptions: object +float_info: _float_info +version_info: _version_info +ps1: str +ps2: str +last_type: type +last_value: BaseException +last_traceback: TracebackType +# TODO precise types +meta_path: List[Any] +path_hooks: List[Any] +path_importer_cache: Dict[str, Any] +displayhook: Callable[[object], Any] +excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] +exc_type: Optional[type] +exc_value: Union[BaseException, ClassType] +exc_traceback: TracebackType + +class _WindowsVersionType: + major: Any + minor: Any + build: Any + platform: Any + service_pack: Any + service_pack_major: Any + service_pack_minor: Any + suite_mask: Any + product_type: Any + +def getwindowsversion() -> _WindowsVersionType: ... +def _clear_type_cache() -> None: ... +def _current_frames() -> Dict[int, FrameType]: ... +def _getframe(depth: int = ...) -> FrameType: ... +def call_tracing(fn: Any, args: Any) -> Any: ... +def __displayhook__(value: object) -> None: ... +def __excepthook__(type_: type, value: BaseException, traceback: TracebackType) -> None: ... +def exc_clear() -> None: ... +def exc_info() -> _OptExcInfo: ... + +# sys.exit() accepts an optional argument of anything printable +def exit(arg: Any = ...) -> NoReturn: ... +def getcheckinterval() -> int: ... # deprecated +def getdefaultencoding() -> str: ... +def getdlopenflags() -> int: ... +def getfilesystemencoding() -> str: ... # In practice, never returns None +def getrefcount(arg: Any) -> int: ... +def getrecursionlimit() -> int: ... +def getsizeof(obj: object, default: int = ...) -> int: ... +def getprofile() -> Optional[Any]: ... +def gettrace() -> Optional[Any]: ... +def setcheckinterval(interval: int) -> None: ... # deprecated +def setdlopenflags(n: int) -> None: ... +def setdefaultencoding(encoding: Text) -> None: ... # only exists after reload(sys) +def setprofile(profilefunc: Any) -> None: ... # TODO type +def setrecursionlimit(limit: int) -> None: ... +def settrace(tracefunc: Any) -> None: ... # TODO type diff --git a/mypy/typeshed/stdlib/@python2/tempfile.pyi b/mypy/typeshed/stdlib/@python2/tempfile.pyi new file mode 100644 index 000000000000..687e10784585 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/tempfile.pyi @@ -0,0 +1,102 @@ +from random import Random +from thread import LockType +from typing import IO, Any, AnyStr, Iterable, Iterator, List, Optional, Text, Tuple, Union, overload + +TMP_MAX: int +tempdir: str +template: str +_name_sequence: Optional[_RandomNameSequence] + +class _RandomNameSequence: + characters: str = ... + mutex: LockType + @property + def rng(self) -> Random: ... + def __iter__(self) -> _RandomNameSequence: ... + def next(self) -> str: ... + # from os.path: + def normcase(self, path: AnyStr) -> AnyStr: ... + +class _TemporaryFileWrapper(IO[str]): + delete: bool + file: IO[str] + name: Any + def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> _TemporaryFileWrapper: ... + def __exit__(self, exc, value, tb) -> Optional[bool]: ... + def __getattr__(self, name: unicode) -> Any: ... + def close(self) -> None: ... + def unlink(self, path: unicode) -> 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 fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + 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: Text) -> int: ... + def writelines(self, lines: Iterable[str]) -> None: ... + +# TODO text files + +def TemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ..., +) -> _TemporaryFileWrapper: ... +def NamedTemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ..., + delete: bool = ..., +) -> _TemporaryFileWrapper: ... +def SpooledTemporaryFile( + max_size: int = ..., + mode: Union[bytes, unicode] = ..., + buffering: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ..., +) -> _TemporaryFileWrapper: ... + +class TemporaryDirectory: + name: Any + def __init__( + self, suffix: Union[bytes, unicode] = ..., prefix: Union[bytes, unicode] = ..., dir: Union[bytes, unicode] = ... + ) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> Any: ... # Can be str or unicode + def __exit__(self, type, value, traceback) -> None: ... + +@overload +def mkstemp() -> Tuple[int, str]: ... +@overload +def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ..., text: bool = ...) -> Tuple[int, AnyStr]: ... +@overload +def mkdtemp() -> str: ... +@overload +def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +@overload +def mktemp() -> str: ... +@overload +def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +def gettempdir() -> str: ... +def gettempprefix() -> str: ... +def _candidate_tempdir_list() -> List[str]: ... +def _get_candidate_names() -> Optional[_RandomNameSequence]: ... +def _get_default_tempdir() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/textwrap.pyi b/mypy/typeshed/stdlib/@python2/textwrap.pyi new file mode 100644 index 000000000000..c4147b4bd538 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/textwrap.pyi @@ -0,0 +1,61 @@ +from typing import AnyStr, Dict, List, Pattern + +class TextWrapper(object): + width: int = ... + initial_indent: str = ... + subsequent_indent: str = ... + expand_tabs: bool = ... + replace_whitespace: bool = ... + fix_sentence_endings: bool = ... + drop_whitespace: bool = ... + break_long_words: bool = ... + break_on_hyphens: bool = ... + + # Attributes not present in documentation + sentence_end_re: Pattern[str] = ... + wordsep_re: Pattern[str] = ... + wordsep_simple_re: Pattern[str] = ... + whitespace_trans: str = ... + unicode_whitespace_trans: Dict[int, int] = ... + uspace: int = ... + x: int = ... + def __init__( + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., + ) -> None: ... + def wrap(self, text: AnyStr) -> List[AnyStr]: ... + def fill(self, text: AnyStr) -> AnyStr: ... + +def wrap( + text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., +) -> List[AnyStr]: ... +def fill( + text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., +) -> AnyStr: ... +def dedent(text: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/thread.pyi b/mypy/typeshed/stdlib/@python2/thread.pyi new file mode 100644 index 000000000000..b3ba062a498e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/thread.pyi @@ -0,0 +1,27 @@ +from typing import Any, Callable + +def _count() -> int: ... + +class error(Exception): ... + +class LockType: + def acquire(self, waitflag: int = ...) -> bool: ... + def acquire_lock(self, waitflag: int = ...) -> bool: ... + def release(self) -> None: ... + def release_lock(self) -> None: ... + def locked(self) -> bool: ... + def locked_lock(self) -> bool: ... + def __enter__(self) -> LockType: ... + def __exit__(self, typ: Any, value: Any, traceback: Any) -> None: ... + +class _local(object): ... +class _localdummy(object): ... + +def start_new(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def start_new_thread(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def interrupt_main() -> None: ... +def exit() -> None: ... +def exit_thread() -> Any: ... +def allocate_lock() -> LockType: ... +def get_ident() -> int: ... +def stack_size(size: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/toaiff.pyi b/mypy/typeshed/stdlib/@python2/toaiff.pyi new file mode 100644 index 000000000000..b70e026d6d8e --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/toaiff.pyi @@ -0,0 +1,11 @@ +from pipes import Template +from typing import Dict, List + +table: Dict[str, Template] +t: Template +uncompress: Template + +class error(Exception): ... + +def toaiff(filename: str) -> str: ... +def _toaiff(filename: str, temps: List[str]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/tokenize.pyi new file mode 100644 index 000000000000..86d5937d6bc9 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/tokenize.pyi @@ -0,0 +1,133 @@ +from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple, Union + +__author__: str +__credits__: str + +AMPER: int +AMPEREQUAL: int +AT: int +BACKQUOTE: int +Binnumber: str +Bracket: str +CIRCUMFLEX: int +CIRCUMFLEXEQUAL: int +COLON: int +COMMA: int +COMMENT: int +Comment: str +ContStr: str +DEDENT: int +DOT: int +DOUBLESLASH: int +DOUBLESLASHEQUAL: int +DOUBLESTAR: int +DOUBLESTAREQUAL: int +Decnumber: str +Double: str +Double3: str +ENDMARKER: int +EQEQUAL: int +EQUAL: int +ERRORTOKEN: int +Expfloat: str +Exponent: str +Floatnumber: str +Funny: str +GREATER: int +GREATEREQUAL: int +Hexnumber: str +INDENT: int + +def ISEOF(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISTERMINAL(x: int) -> bool: ... + +Ignore: str +Imagnumber: str +Intnumber: str +LBRACE: int +LEFTSHIFT: int +LEFTSHIFTEQUAL: int +LESS: int +LESSEQUAL: int +LPAR: int +LSQB: int +MINEQUAL: int +MINUS: int +NAME: int +NEWLINE: int +NL: int +NOTEQUAL: int +NT_OFFSET: int +NUMBER: int +N_TOKENS: int +Name: str +Number: str +OP: int +Octnumber: str +Operator: str +PERCENT: int +PERCENTEQUAL: int +PLUS: int +PLUSEQUAL: int +PlainToken: str +Pointfloat: str +PseudoExtras: str +PseudoToken: str +RBRACE: int +RIGHTSHIFT: int +RIGHTSHIFTEQUAL: int +RPAR: int +RSQB: int +SEMI: int +SLASH: int +SLASHEQUAL: int +STAR: int +STAREQUAL: int +STRING: int +Single: str +Single3: str +Special: str +String: str +TILDE: int +Token: str +Triple: str +VBAR: int +VBAREQUAL: int +Whitespace: str +chain: type +double3prog: type +endprogs: Dict[str, Any] +pseudoprog: type +single3prog: type +single_quoted: Dict[str, str] +t: str +tabsize: int +tok_name: Dict[int, str] +tokenprog: type +triple_quoted: Dict[str, str] +x: str + +_Pos = Tuple[int, int] +_TokenType = Tuple[int, str, _Pos, _Pos, str] + +def any(*args, **kwargs) -> str: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... +def group(*args: str) -> str: ... +def maybe(*args: str) -> str: ... +def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... +def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def untokenize(iterable: Iterable[_TokenType]) -> str: ... + +class StopTokenizing(Exception): ... +class TokenError(Exception): ... + +class Untokenizer: + prev_col: int + prev_row: int + tokens: List[str] + def __init__(self) -> None: ... + def add_whitespace(self, _Pos) -> None: ... + def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... + def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/types.pyi b/mypy/typeshed/stdlib/@python2/types.pyi new file mode 100644 index 000000000000..cf57c6329665 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/types.pyi @@ -0,0 +1,195 @@ +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Type, TypeVar, Union, overload + +_T = TypeVar("_T") + +# Note, all classes "defined" here require special handling. + +class NoneType: ... + +TypeType = type +ObjectType = object + +IntType = int +LongType = int # Really long, but can't reference that due to a mypy import cycle +FloatType = float +BooleanType = bool +ComplexType = complex +StringType = str +UnicodeType = unicode +StringTypes: Tuple[Type[StringType], Type[UnicodeType]] +BufferType = buffer +TupleType = tuple +ListType = list +DictType = dict +DictionaryType = dict + +class _Cell: + cell_contents: Any + +class FunctionType: + func_closure: Optional[Tuple[_Cell, ...]] = ... + func_code: CodeType = ... + func_defaults: Optional[Tuple[Any, ...]] = ... + func_dict: Dict[str, Any] = ... + func_doc: Optional[str] = ... + func_globals: Dict[str, Any] = ... + func_name: str = ... + __closure__ = func_closure + __code__ = func_code + __defaults__ = func_defaults + __dict__ = func_dict + __globals__ = func_globals + __name__ = func_name + def __init__( + self, + code: CodeType, + globals: Dict[str, Any], + name: Optional[str] = ..., + argdefs: Optional[Tuple[object, ...]] = ..., + closure: Optional[Tuple[_Cell, ...]] = ..., + ) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Optional[object], type: Optional[type]) -> UnboundMethodType: ... + +LambdaType = FunctionType + +class CodeType: + co_argcount: int + co_cellvars: Tuple[str, ...] + co_code: str + co_consts: Tuple[Any, ...] + co_filename: str + co_firstlineno: int + co_flags: int + co_freevars: Tuple[str, ...] + co_lnotab: str + co_name: str + co_names: Tuple[str, ...] + co_nlocals: int + co_stacksize: int + co_varnames: Tuple[str, ...] + def __init__( + self, + argcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: str, + constants: Tuple[Any, ...], + names: Tuple[str, ...], + varnames: Tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: str, + freevars: Tuple[str, ...] = ..., + cellvars: Tuple[str, ...] = ..., + ) -> None: ... + +class GeneratorType: + gi_code: CodeType + gi_frame: FrameType + gi_running: int + def __iter__(self) -> GeneratorType: ... + def close(self) -> None: ... + def next(self) -> Any: ... + def send(self, __arg: Any) -> Any: ... + @overload + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> Any: ... + @overload + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... + +class ClassType: ... + +class UnboundMethodType: + im_class: type = ... + im_func: FunctionType = ... + im_self: object = ... + __name__: str + __func__ = im_func + __self__ = im_self + def __init__(self, func: Callable[..., Any], obj: object) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class InstanceType(object): ... + +MethodType = UnboundMethodType + +class BuiltinFunctionType: + __self__: Optional[object] + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +BuiltinMethodType = BuiltinFunctionType + +class ModuleType: + __doc__: Optional[str] + __file__: Optional[str] + __name__: str + __package__: Optional[str] + __path__: Optional[Iterable[str]] + __dict__: Dict[str, Any] + def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... + +FileType = file +XRangeType = xrange + +class TracebackType: + tb_frame: FrameType + tb_lasti: int + tb_lineno: int + tb_next: TracebackType + +class FrameType: + f_back: FrameType + f_builtins: Dict[str, Any] + f_code: CodeType + f_exc_type: None + f_exc_value: None + f_exc_traceback: None + f_globals: Dict[str, Any] + f_lasti: int + f_lineno: int + f_locals: Dict[str, Any] + f_restricted: bool + f_trace: Callable[[], None] + def clear(self) -> None: ... + +SliceType = slice + +class EllipsisType: ... + +class DictProxyType: + # TODO is it possible to have non-string keys? + # no __init__ + def copy(self) -> Dict[Any, Any]: ... + def get(self, key: str, default: _T = ...) -> Union[Any, _T]: ... + def has_key(self, key: str) -> bool: ... + def items(self) -> List[Tuple[str, Any]]: ... + def iteritems(self) -> Iterator[Tuple[str, Any]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[Any]: ... + def keys(self) -> List[str]: ... + def values(self) -> List[Any]: ... + def __contains__(self, key: str) -> bool: ... + def __getitem__(self, key: str) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class NotImplementedType: ... + +class GetSetDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + +# Same type on Jython, different on CPython and PyPy, unknown on IronPython. +class MemberDescriptorType: + __name__: str + __objclass__: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/typing.pyi b/mypy/typeshed/stdlib/@python2/typing.pyi new file mode 100644 index 000000000000..e134d17415b0 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/typing.pyi @@ -0,0 +1,495 @@ +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +from abc import ABCMeta, abstractmethod +from types import CodeType, FrameType, TracebackType + +# Definitions of special type checking related constructs. Their definitions +# are not used, so their value does not matter. + +overload = object() +Any = object() + +class TypeVar: + __name__: str + __bound__: Optional[Type[Any]] + __constraints__: Tuple[Type[Any], ...] + __covariant__: bool + __contravariant__: bool + def __init__( + self, + name: str, + *constraints: Type[Any], + bound: Optional[Type[Any]] = ..., + covariant: bool = ..., + contravariant: bool = ..., + ) -> None: ... + +_promote = object() + +class _SpecialForm(object): + def __getitem__(self, typeargs: Any) -> object: ... + +Union: _SpecialForm = ... +Optional: _SpecialForm = ... +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... +Final: _SpecialForm = ... +_F = TypeVar("_F", bound=Callable[..., Any]) + +def final(f: _F) -> _F: ... + +Literal: _SpecialForm = ... +# TypedDict is a (non-subscriptable) special form. +TypedDict: object = ... + +class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# These type variables are used by the container types. +_T = TypeVar("_T") +_S = TypeVar("_S") +_KT = TypeVar("_KT") # Key type. +_VT = TypeVar("_VT") # Value type. +_T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. +_V_co = TypeVar("_V_co", covariant=True) # Any type covariant containers. +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. +_T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. +_TC = TypeVar("_TC", bound=Type[object]) +_C = TypeVar("_C", bound=Callable[..., Any]) + +no_type_check = object() + +def no_type_check_decorator(decorator: _C) -> _C: ... + +# Type aliases and type constructors + +class _Alias: + # Class for defining generic aliases for library types. + def __getitem__(self, typeargs: Any) -> Any: ... + +List = _Alias() +Dict = _Alias() +DefaultDict = _Alias() +Set = _Alias() +FrozenSet = _Alias() +Counter = _Alias() +Deque = _Alias() + +# Predefined type variables. +AnyStr = TypeVar("AnyStr", str, unicode) + +# Abstract base classes. + +def runtime_checkable(cls: _TC) -> _TC: ... +@runtime_checkable +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime_checkable +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime_checkable +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime_checkable +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime_checkable +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime_checkable +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime_checkable +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def next(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def next(self) -> _T_co: ... + @abstractmethod + def send(self, __value: _T_contra) -> _T_co: ... + @overload + @abstractmethod + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> _T_co: ... + @overload + @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... + @abstractmethod + def close(self) -> None: ... + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + +@runtime_checkable +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + +class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + def index(self, x: Any) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + # TODO: argument can be any container? + def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView(object): + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +@runtime_checkable +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__( + self, + __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> Optional[bool]: ... + +class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT_co]: ... + def items(self) -> list[Tuple[_KT, _VT_co]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT_co]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... + def __contains__(self, o: object) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = unicode + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + @abstractmethod + def next(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__( + self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> Optional[bool]: ... + +class BinaryIO(IO[str]): + # TODO readinto + # TODO read1? + # TODO peek? + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[unicode]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> bool: ... + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos: int + endpos: int + lastindex: Optional[int] + string: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. This should not be Pattern[AnyStr] because the type + # of the pattern is independent of the type of the matched string in + # Python 2. Strictly speaking Match should be generic over AnyStr twice: + # once for the type of the pattern and once for the type of the matched + # string. + re: Pattern[Any] + # Can be None if there are no groups or if the last group was unnamed; + # otherwise matches the type of the pattern. + lastgroup: Optional[Any] + def expand(self, template: Union[str, Text]) -> Any: ... + @overload + def group(self, group1: int = ...) -> AnyStr: ... + @overload + def group(self, group1: str) -> AnyStr: ... + @overload + def group(self, group1: int, group2: int, *groups: int) -> Tuple[AnyStr, ...]: ... + @overload + def group(self, group1: str, group2: str, *groups: str) -> Tuple[AnyStr, ...]: ... + def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... + def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... + def start(self, __group: Union[int, str] = ...) -> int: ... + def end(self, __group: Union[int, str] = ...) -> int: ... + def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + +# We need a second TypeVar with the same definition as AnyStr, because +# Pattern is generic over AnyStr (determining the type of its .pattern +# attribute), but at the same time its methods take either bytes or +# Text and return the same type, regardless of the type of the pattern. +_AnyStr2 = TypeVar("_AnyStr2", bytes, Text) + +class Pattern(Generic[AnyStr]): + flags: int + groupindex: Dict[AnyStr, int] + groups: int + pattern: AnyStr + def search(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def match(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... + # Returns either a list of _AnyStr2 or a list of tuples, depending on + # whether there are groups in the pattern. + def findall(self, string: Union[bytes, Text], pos: int = ..., endpos: int = ...) -> List[Any]: ... + def finditer(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... + @overload + def sub(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> _AnyStr2: ... + @overload + def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> _AnyStr2: ... + @overload + def subn(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... + @overload + def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... + +# Functions + +def get_type_hints( + obj: Callable[..., Any], globalns: Optional[Dict[Text, Any]] = ..., localns: Optional[Dict[Text, Any]] = ... +) -> None: ... +@overload +def cast(tp: Type[_T], obj: Any) -> _T: ... +@overload +def cast(tp: str, obj: Any) -> Any: ... +@overload +def cast(tp: object, obj: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(Tuple[Any, ...]): + _fields: Tuple[str, ...] + def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., **kwargs: Any) -> None: ... + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + def _asdict(self) -> Dict[str, Any]: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +class _TypedDict(Mapping[str, object], metaclass=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: ... + 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: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _C) -> _C: ... diff --git a/mypy/typeshed/stdlib/@python2/unittest.pyi b/mypy/typeshed/stdlib/@python2/unittest.pyi new file mode 100644 index 000000000000..57b73a762cfa --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/unittest.pyi @@ -0,0 +1,280 @@ +import datetime +import types +from abc import ABCMeta, abstractmethod +from typing import ( + Any, + Callable, + Dict, + FrozenSet, + Iterable, + Iterator, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Sequence, + Set, + Text, + TextIO, + Tuple, + Type, + TypeVar, + Union, + overload, +) + +_T = TypeVar("_T") +_FT = TypeVar("_FT") + +_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_Regexp = Union[Text, Pattern[Text]] + +_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]] + +class Testable(metaclass=ABCMeta): + @abstractmethod + def run(self, result: TestResult) -> None: ... + @abstractmethod + def debug(self) -> None: ... + @abstractmethod + def countTestCases(self) -> int: ... + +# TODO ABC for test runners? + +class TestResult: + errors: List[Tuple[TestCase, str]] + failures: List[Tuple[TestCase, str]] + skipped: List[Tuple[TestCase, str]] + expectedFailures: List[Tuple[TestCase, str]] + unexpectedSuccesses: List[TestCase] + shouldStop: bool + testsRun: int + buffer: bool + failfast: bool + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: TestCase) -> None: ... + def stopTest(self, test: TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addSuccess(self, test: TestCase) -> None: ... + def addSkip(self, test: TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: TestCase, err: str) -> None: ... + def addUnexpectedSuccess(self, test: TestCase) -> None: ... + +class _AssertRaisesBaseContext: + expected: Any + failureException: Type[BaseException] + obj_name: str + expected_regex: Pattern[str] + +class _AssertRaisesContext(_AssertRaisesBaseContext): + exception: Any + def __enter__(self) -> _AssertRaisesContext: ... + def __exit__(self, exc_type, exc_value, tb) -> bool: ... + +class TestCase(Testable): + failureException: Type[BaseException] + longMessage: bool + maxDiff: Optional[int] + # undocumented + _testMethodName: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: TestResult = ...) -> None: ... + def debug(self) -> None: ... + def assert_(self, expr: Any, msg: object = ...) -> None: ... + def failUnless(self, expr: Any, msg: object = ...) -> None: ... + def assertTrue(self, expr: Any, msg: object = ...) -> None: ... + def assertEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... + def failUnlessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, msg: object = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEqual( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertAlmostEquals( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: object = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEqual( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEquals(self, first: float, second: float, *, msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEquals( + self, first: datetime.datetime, second: datetime.datetime, *, msg: Any = ..., delta: datetime.timedelta = ... + ) -> None: ... + def failIfAlmostEqual( + self, first: float, second: float, places: int = ..., msg: object = ..., delta: float = ... + ) -> None: ... + def assertGreater(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertGreaterEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, msg: object = ...) -> None: ... + def assertSequenceEqual( + self, first: Sequence[Any], second: Sequence[Any], msg: object = ..., seq_type: type = ... + ) -> None: ... + def assertListEqual(self, first: List[Any], second: List[Any], msg: object = ...) -> None: ... + def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], msg: object = ...) -> None: ... + def assertSetEqual( + self, first: Union[Set[Any], FrozenSet[Any]], second: Union[Set[Any], FrozenSet[Any]], msg: object = ... + ) -> None: ... + def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], msg: object = ...) -> None: ... + def assertLess(self, first: Any, second: Any, msg: object = ...) -> None: ... + def assertLessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + @overload + def assertRaisesRegexp( + self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any + ) -> None: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... + def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... + def assertDictContainsSubset(self, expected: Mapping[Any, Any], actual: Mapping[Any, Any], msg: object = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + def failIf(self, expr: Any, msg: object = ...) -> None: ... + def assertFalse(self, expr: Any, msg: object = ...) -> None: ... + def assertIs(self, first: object, second: object, msg: object = ...) -> None: ... + def assertIsNot(self, first: object, second: object, msg: object = ...) -> None: ... + def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... + def assertNotIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], msg: object = ...) -> None: ... + def fail(self, msg: object = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> str: ... # May return None + def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... + def doCleanups(self) -> bool: ... + def skipTest(self, reason: Any) -> None: ... + def _formatMessage(self, msg: Optional[Text], standardMsg: Text) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + +class FunctionTestCase(TestCase): + def __init__( + self, + testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ..., + ) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + +class TestSuite(Testable): + def __init__(self, tests: Iterable[Testable] = ...) -> None: ... + def addTest(self, test: Testable) -> None: ... + def addTests(self, tests: Iterable[Testable]) -> None: ... + def run(self, result: TestResult) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[Testable]: ... + +class TestLoader: + testMethodPrefix: str + sortTestMethodsUsing: Optional[Callable[[str, str], int]] + suiteClass: Callable[[List[TestCase]], TestSuite] + def loadTestsFromTestCase(self, testCaseClass: Type[TestCase]) -> TestSuite: ... + def loadTestsFromModule(self, module: types.ModuleType = ..., use_load_tests: bool = ...) -> TestSuite: ... + def loadTestsFromName(self, name: str = ..., module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: List[str] = ..., module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def discover(self, start_dir: str, pattern: str = ..., top_level_dir: Optional[str] = ...) -> TestSuite: ... + def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + +defaultTestLoader: TestLoader + +class TextTestResult(TestResult): + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + def getDescription(self, test: TestCase) -> str: ... # undocumented + def printErrors(self) -> None: ... # undocumented + def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented + +class TextTestRunner: + def __init__( + self, + stream: Optional[TextIO] = ..., + descriptions: bool = ..., + verbosity: int = ..., + failfast: bool = ..., + buffer: bool = ..., + resultclass: Optional[Type[TestResult]] = ..., + ) -> None: ... + def _makeResult(self) -> TestResult: ... + def run(self, test: Testable) -> TestResult: ... # undocumented + +class SkipTest(Exception): ... + +# TODO precise types +def skipUnless(condition: Any, reason: Union[str, unicode]) -> Any: ... +def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ... +def expectedFailure(func: _FT) -> _FT: ... +def skip(reason: Union[str, unicode]) -> Any: ... + +# not really documented +class TestProgram: + result: TestResult + def runTests(self) -> None: ... # undocumented + +def main( + module: Union[None, Text, types.ModuleType] = ..., + defaultTest: Optional[str] = ..., + argv: Optional[Sequence[str]] = ..., + testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ..., + testLoader: TestLoader = ..., + exit: bool = ..., + verbosity: int = ..., + failfast: Optional[bool] = ..., + catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ..., +) -> TestProgram: ... +def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[Text]) -> TestSuite: ... +def installHandler() -> None: ... +def registerResult(result: TestResult) -> None: ... +def removeResult(result: TestResult) -> bool: ... +@overload +def removeHandler() -> None: ... +@overload +def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... + +# private but occasionally used +util: types.ModuleType diff --git a/mypy/typeshed/stdlib/@python2/urllib.pyi b/mypy/typeshed/stdlib/@python2/urllib.pyi new file mode 100644 index 000000000000..c719c1faa693 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/urllib.pyi @@ -0,0 +1,133 @@ +from typing import IO, Any, AnyStr, List, Mapping, Sequence, Text, Tuple, TypeVar, Union + +def url2pathname(pathname: AnyStr) -> AnyStr: ... +def pathname2url(pathname: AnyStr) -> AnyStr: ... +def urlopen(url: str, data=..., proxies: Mapping[str, str] = ..., context=...) -> IO[Any]: ... +def urlretrieve(url, filename=..., reporthook=..., data=..., context=...): ... +def urlcleanup() -> None: ... + +class ContentTooShortError(IOError): + content: Any + def __init__(self, message, content) -> None: ... + +class URLopener: + version: Any + proxies: Any + key_file: Any + cert_file: Any + context: Any + addheaders: Any + tempcache: Any + ftpcache: Any + def __init__(self, proxies: Mapping[str, str] = ..., context=..., **x509) -> None: ... + def __del__(self): ... + def close(self): ... + def cleanup(self): ... + def addheader(self, *args): ... + type: Any + def open(self, fullurl: str, data=...): ... + def open_unknown(self, fullurl, data=...): ... + def open_unknown_proxy(self, proxy, fullurl, data=...): ... + def retrieve(self, url, filename=..., reporthook=..., data=...): ... + def open_http(self, url, data=...): ... + def http_error(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def open_https(self, url, data=...): ... + def open_file(self, url): ... + def open_local_file(self, url): ... + def open_ftp(self, url): ... + def open_data(self, url, data=...): ... + +class FancyURLopener(URLopener): + auth_cache: Any + tries: Any + maxtries: Any + def __init__(self, *args, **kwargs) -> None: ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def http_error_302(self, url, fp, errcode, errmsg, headers, data=...): ... + def redirect_internal(self, url, fp, errcode, errmsg, headers, data): ... + def http_error_301(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_303(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_307(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_401(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_407(self, url, fp, errcode, errmsg, headers, data=...): ... + def retry_proxy_http_basic_auth(self, url, realm, data=...): ... + def retry_proxy_https_basic_auth(self, url, realm, data=...): ... + def retry_http_basic_auth(self, url, realm, data=...): ... + def retry_https_basic_auth(self, url, realm, data=...): ... + def get_user_passwd(self, host, realm, clear_cache=...): ... + def prompt_user_passwd(self, host, realm): ... + +class ftpwrapper: + user: Any + passwd: Any + host: Any + port: Any + dirs: Any + timeout: Any + refcount: Any + keepalive: Any + def __init__(self, user, passwd, host, port, dirs, timeout=..., persistent=...) -> None: ... + busy: Any + ftp: Any + def init(self): ... + def retrfile(self, file, type): ... + def endtransfer(self): ... + def close(self): ... + def file_close(self): ... + def real_close(self): ... + +_AIUT = TypeVar("_AIUT", bound=addbase) + +class addbase: + fp: Any + def read(self, n: int = ...) -> bytes: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def fileno(self) -> int: ... # Optional[int], but that is rare + def __iter__(self: _AIUT) -> _AIUT: ... + def next(self) -> bytes: ... + def __init__(self, fp) -> None: ... + def close(self) -> None: ... + +class addclosehook(addbase): + closehook: Any + hookargs: Any + def __init__(self, fp, closehook, *hookargs) -> None: ... + def close(self): ... + +class addinfo(addbase): + headers: Any + def __init__(self, fp, headers) -> None: ... + def info(self): ... + +class addinfourl(addbase): + headers: Any + url: Any + code: Any + def __init__(self, fp, headers, url, code=...) -> None: ... + def info(self): ... + def getcode(self): ... + def geturl(self): ... + +def unwrap(url): ... +def splittype(url): ... +def splithost(url): ... +def splituser(host): ... +def splitpasswd(user): ... +def splitport(host): ... +def splitnport(host, defport=...): ... +def splitquery(url): ... +def splittag(url): ... +def splitattr(url): ... +def splitvalue(attr): ... +def unquote(s: AnyStr) -> AnyStr: ... +def unquote_plus(s: AnyStr) -> AnyStr: ... +def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def urlencode(query: Union[Sequence[Tuple[Any, Any]], Mapping[Any, Any]], doseq=...) -> str: ... +def getproxies() -> Mapping[str, str]: ... +def proxy_bypass(host: str) -> Any: ... # Undocumented + +# Names in __all__ with no definition: +# basejoin diff --git a/mypy/typeshed/stdlib/@python2/urllib2.pyi b/mypy/typeshed/stdlib/@python2/urllib2.pyi new file mode 100644 index 000000000000..8c355db46d75 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/urllib2.pyi @@ -0,0 +1,187 @@ +import ssl +from httplib import HTTPConnectionProtocol, HTTPResponse +from typing import Any, AnyStr, Callable, Dict, List, Mapping, Optional, Sequence, Text, Tuple, Type, Union +from urllib import addinfourl + +_string = Union[str, unicode] + +class URLError(IOError): + reason: Union[str, BaseException] + +class HTTPError(URLError, addinfourl): + code: int + headers: Mapping[str, str] + def __init__(self, url, code: int, msg: str, hdrs: Mapping[str, str], fp: addinfourl) -> None: ... + +class Request(object): + host: str + port: str + data: str + headers: Dict[str, str] + unverifiable: bool + type: Optional[str] + origin_req_host = ... + unredirected_hdrs: Dict[str, str] + timeout: Optional[float] # Undocumented, only set after __init__() by OpenerDirector.open() + def __init__( + self, + url: str, + data: Optional[str] = ..., + headers: Dict[str, str] = ..., + origin_req_host: Optional[str] = ..., + unverifiable: bool = ..., + ) -> None: ... + def __getattr__(self, attr): ... + def get_method(self) -> str: ... + def add_data(self, data) -> None: ... + def has_data(self) -> bool: ... + def get_data(self) -> str: ... + def get_full_url(self) -> str: ... + def get_type(self): ... + def get_host(self) -> str: ... + def get_selector(self): ... + def set_proxy(self, host, type) -> None: ... + def has_proxy(self) -> bool: ... + def get_origin_req_host(self) -> str: ... + def is_unverifiable(self) -> bool: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def get_header(self, header_name: str, default: Optional[str] = ...) -> str: ... + def header_items(self): ... + +class OpenerDirector(object): + addheaders: List[Tuple[str, str]] + def add_handler(self, handler: BaseHandler) -> None: ... + def open( + self, fullurl: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ... + ) -> Optional[addinfourl]: ... + def error(self, proto: _string, *args: Any): ... + +# Note that this type is somewhat a lie. The return *can* be None if +# a custom opener has been installed that fails to handle the request. +def urlopen( + url: Union[Request, _string], + data: Optional[_string] = ..., + timeout: Optional[float] = ..., + cafile: Optional[_string] = ..., + capath: Optional[_string] = ..., + cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ..., +) -> addinfourl: ... +def install_opener(opener: OpenerDirector) -> None: ... +def build_opener(*handlers: Union[BaseHandler, Type[BaseHandler]]) -> OpenerDirector: ... + +class BaseHandler: + handler_order: int + parent: OpenerDirector + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def __lt__(self, other: Any) -> bool: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request, response): ... + +class HTTPDefaultErrorHandler(BaseHandler): + def http_error_default(self, req: Request, fp: addinfourl, code: int, msg: str, hdrs: Mapping[str, str]): ... + +class HTTPRedirectHandler(BaseHandler): + max_repeats: int + max_redirections: int + def redirect_request(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str], newurl): ... + def http_error_301(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_302(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_303(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_307(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + inf_msg: str + +class ProxyHandler(BaseHandler): + proxies: Mapping[str, str] + def __init__(self, proxies: Optional[Mapping[str, str]] = ...): ... + def proxy_open(self, req: Request, proxy, type): ... + +class HTTPPasswordMgr: + def __init__(self) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def find_user_password(self, realm: Optional[Text], authuri: Text) -> Tuple[Any, Any]: ... + def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... + def is_suburi(self, base: _string, test: _string) -> bool: ... + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... + +class AbstractBasicAuthHandler: + def __init__(self, password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def http_error_auth_reqed(self, authreq, host, req: Request, headers: Mapping[str, str]): ... + def retry_http_basic_auth(self, host, req: Request, realm): ... + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: str + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: str + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: Mapping[str, str]) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[HTTPResponse]: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: str + handler_order: int + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: str + handler_order: int + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + def __init__(self, debuglevel: int = ...) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, http_class: HTTPConnectionProtocol, req: Request, **http_conn_args: Optional[Any]) -> addinfourl: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> addinfourl: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + def __init__(self, debuglevel: int = ..., context: Optional[ssl.SSLContext] = ...) -> None: ... + def https_open(self, req: Request) -> addinfourl: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class HTTPCookieProcessor(BaseHandler): + def __init__(self, cookiejar: Optional[Any] = ...): ... + def http_request(self, request: Request): ... + def http_response(self, request: Request, response): ... + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request): ... + +class FileHandler(BaseHandler): + def file_open(self, req: Request): ... + def get_names(self): ... + def open_local_file(self, req: Request): ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request): ... + def connect_ftp(self, user, passwd, host, port, dirs, timeout): ... + +class CacheFTPHandler(FTPHandler): + def __init__(self) -> None: ... + def setTimeout(self, t: Optional[float]): ... + def setMaxConns(self, m: int): ... + def check_cache(self): ... + def clear_cache(self): ... + +def parse_http_list(s: AnyStr) -> List[AnyStr]: ... +def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/urlparse.pyi b/mypy/typeshed/stdlib/@python2/urlparse.pyi new file mode 100644 index 000000000000..40691239a87b --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/urlparse.pyi @@ -0,0 +1,61 @@ +from typing import AnyStr, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union, overload + +_String = Union[str, unicode] + +uses_relative: List[str] +uses_netloc: List[str] +uses_params: List[str] +non_hierarchical: List[str] +uses_query: List[str] +uses_fragment: List[str] +scheme_chars: str +MAX_CACHE_SIZE: int + +def clear_cache() -> None: ... + +class ResultMixin(object): + @property + def username(self) -> Optional[str]: ... + @property + def password(self) -> Optional[str]: ... + @property + def hostname(self) -> Optional[str]: ... + @property + def port(self) -> Optional[int]: ... + +class _SplitResult(NamedTuple): + scheme: str + netloc: str + path: str + query: str + fragment: str + +class SplitResult(_SplitResult, ResultMixin): + def geturl(self) -> str: ... + +class _ParseResult(NamedTuple): + scheme: str + netloc: str + path: str + params: str + query: str + fragment: str + +class ParseResult(_ParseResult, ResultMixin): + def geturl(self) -> _String: ... + +def urlparse(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> ParseResult: ... +def urlsplit(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> SplitResult: ... +@overload +def urlunparse(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +@overload +def urlunparse(data: Sequence[AnyStr]) -> AnyStr: ... +@overload +def urlunsplit(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +@overload +def urlunsplit(data: Sequence[AnyStr]) -> AnyStr: ... +def urljoin(base: AnyStr, url: AnyStr, allow_fragments: bool = ...) -> AnyStr: ... +def urldefrag(url: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def unquote(s: AnyStr) -> AnyStr: ... +def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... +def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... diff --git a/mypy/typeshed/stdlib/@python2/user.pyi b/mypy/typeshed/stdlib/@python2/user.pyi new file mode 100644 index 000000000000..9c33922b383d --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/user.pyi @@ -0,0 +1,6 @@ +from typing import Any + +def __getattr__(name) -> Any: ... + +home: str +pythonrc: str diff --git a/mypy/typeshed/stdlib/@python2/whichdb.pyi b/mypy/typeshed/stdlib/@python2/whichdb.pyi new file mode 100644 index 000000000000..67542096d712 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/whichdb.pyi @@ -0,0 +1,3 @@ +from typing import Optional, Text + +def whichdb(filename: Text) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi new file mode 100644 index 000000000000..52e36b61a209 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi @@ -0,0 +1,248 @@ +from datetime import datetime +from gzip import GzipFile +from httplib import HTTPConnection, HTTPResponse, HTTPSConnection +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 + +_Unmarshaller = Any +_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] +# Represents types that can be compared against a DateTime object +_dateTimeComp = Union[unicode, DateTime, datetime] +# A "host description" used by Transport factories +_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] + +def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... + +MAXINT: int +MININT: int +PARSE_ERROR: int +SERVER_ERROR: int +APPLICATION_ERROR: int +SYSTEM_ERROR: int +TRANSPORT_ERROR: int +NOT_WELLFORMED_ERROR: int +UNSUPPORTED_ENCODING: int +INVALID_ENCODING_CHAR: int +INVALID_XMLRPC: int +METHOD_NOT_FOUND: int +INVALID_METHOD_PARAMS: int +INTERNAL_ERROR: int + +class Error(Exception): ... + +class ProtocolError(Error): + url: str + errcode: int + errmsg: str + headers: Any + def __init__(self, url: str, errcode: int, errmsg: str, headers: Any) -> None: ... + +class ResponseError(Error): ... + +class Fault(Error): + faultCode: Any + faultString: str + def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... + +boolean: Type[bool] +Boolean: Type[bool] + +class DateTime: + value: str + def __init__(self, value: Union[str, unicode, datetime, float, int, _timeTuple, struct_time] = ...) -> None: ... + def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... + def __lt__(self, other: _dateTimeComp) -> bool: ... + def __le__(self, other: _dateTimeComp) -> bool: ... + def __gt__(self, other: _dateTimeComp) -> bool: ... + def __ge__(self, other: _dateTimeComp) -> bool: ... + def __eq__(self, other: _dateTimeComp) -> bool: ... # type: ignore + def __ne__(self, other: _dateTimeComp) -> bool: ... # type: ignore + def timetuple(self) -> struct_time: ... + def __cmp__(self, other: _dateTimeComp) -> int: ... + def decode(self, data: Any) -> None: ... + def encode(self, out: IO[str]) -> None: ... + +class Binary: + data: str + def __init__(self, data: Optional[str] = ...) -> None: ... + def __cmp__(self, other: Any) -> int: ... + def decode(self, data: str) -> None: ... + def encode(self, out: IO[str]) -> None: ... + +WRAPPERS: Tuple[Type[Any], ...] + +# Still part of the public API, but see http://bugs.python.org/issue1773632 +FastParser: None +FastUnmarshaller: None +FastMarshaller: None + +# xmlrpclib.py will leave ExpatParser undefined if it can't import expat from +# xml.parsers. Because this is Python 2.7, the import will succeed. +class ExpatParser: + def __init__(self, target: _Unmarshaller) -> None: ... + def feed(self, data: str): ... + def close(self): ... + +# TODO: Add xmllib.XMLParser as base class +class SlowParser: + handle_xml: Callable[[str, bool], None] + unknown_starttag: Callable[[str, Any], None] + handle_data: Callable[[str], None] + handle_cdata: Callable[[str], None] + unknown_endtag: Callable[[str, Callable[[Iterable[str], str], str]], None] + def __init__(self, target: _Unmarshaller) -> None: ... + +class Marshaller: + memo: MutableMapping[int, Any] + data: Optional[str] + encoding: Optional[str] + allow_none: bool + def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... + dispatch: Mapping[type, Callable[[Marshaller, str, Callable[[str], None]], None]] + def dumps( + self, + values: Union[ + Iterable[ + Union[ + None, + int, + bool, + long, + float, + str, + unicode, + List[Any], + Tuple[Any, ...], + Mapping[Any, Any], + datetime, + InstanceType, + ] + ], + Fault, + ], + ) -> str: ... + def dump_nil(self, value: None, write: Callable[[str], None]) -> None: ... + def dump_int(self, value: int, write: Callable[[str], None]) -> None: ... + def dump_bool(self, value: bool, write: Callable[[str], None]) -> None: ... + def dump_long(self, value: long, write: Callable[[str], None]) -> None: ... + def dump_double(self, value: float, write: Callable[[str], None]) -> None: ... + def dump_string( + self, + value: str, + write: Callable[[str], None], + escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., + ) -> None: ... + def dump_unicode( + self, + value: unicode, + write: Callable[[str], None], + escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., + ) -> None: ... + def dump_array(self, value: Iterable[Any], write: Callable[[str], None]) -> None: ... + def dump_struct( + self, + value: Mapping[unicode, Any], + write: Callable[[str], None], + escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ..., + ) -> None: ... + def dump_datetime(self, value: datetime, write: Callable[[str], None]) -> None: ... + def dump_instance(self, value: InstanceType, write: Callable[[str], None]) -> None: ... + +class Unmarshaller: + def append(self, object: Any) -> None: ... + def __init__(self, use_datetime: bool = ...) -> None: ... + def close(self) -> Tuple[Any, ...]: ... + def getmethodname(self) -> Optional[str]: ... + def xml(self, encoding: str, standalone: bool) -> None: ... + def start(self, tag: str, attrs: Any) -> None: ... + def data(self, text: str) -> None: ... + def end(self, tag: str, join: Callable[[Iterable[str], str], str] = ...) -> None: ... + def end_dispatch(self, tag: str, data: str) -> None: ... + dispatch: Mapping[str, Callable[[Unmarshaller, str], None]] + def end_nil(self, data: str): ... + def end_boolean(self, data: str) -> None: ... + def end_int(self, data: str) -> None: ... + def end_double(self, data: str) -> None: ... + def end_string(self, data: str) -> None: ... + def end_array(self, data: str) -> None: ... + def end_struct(self, data: str) -> None: ... + def end_base64(self, data: str) -> None: ... + def end_dateTime(self, data: str) -> None: ... + def end_value(self, data: str) -> None: ... + def end_params(self, data: str) -> None: ... + def end_fault(self, data: str) -> None: ... + def end_methodName(self, data: str) -> None: ... + +class _MultiCallMethod: + def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... + +class MultiCallIterator: + def __init__(self, results: List[Any]) -> None: ... + +class MultiCall: + def __init__(self, server: ServerProxy) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self) -> MultiCallIterator: ... + +def getparser(use_datetime: bool = ...) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... +def dumps( + params: Union[Tuple[Any, ...], Fault], + methodname: Optional[str] = ..., + methodresponse: Optional[bool] = ..., + encoding: Optional[str] = ..., + allow_none: bool = ..., +) -> str: ... +def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], Optional[str]]: ... +def gzip_encode(data: str) -> str: ... +def gzip_decode(data: str, max_decode: int = ...) -> str: ... + +class GzipDecodedResponse(GzipFile): + stringio: StringIO[Any] + def __init__(self, response: HTTPResponse) -> None: ... + def close(self): ... + +class _Method: + def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, *args: Any) -> Any: ... + +class Transport: + user_agent: str + accept_gzip_encoding: bool + encode_threshold: Optional[int] + def __init__(self, use_datetime: bool = ...) -> None: ... + def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + verbose: bool + def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + def getparser(self) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... + def get_host_info(self, host: _hostDesc) -> Tuple[str, Optional[List[Tuple[str, str]]], Optional[Mapping[Any, Any]]]: ... + def make_connection(self, host: _hostDesc) -> HTTPConnection: ... + def close(self) -> None: ... + def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... + def send_host(self, connection: HTTPConnection, host: str) -> None: ... + def send_user_agent(self, connection: HTTPConnection) -> None: ... + def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... + def parse_response(self, response: HTTPResponse) -> Tuple[Any, ...]: ... + +class SafeTransport(Transport): + def __init__(self, use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... + def make_connection(self, host: _hostDesc) -> HTTPSConnection: ... + +class ServerProxy: + def __init__( + self, + uri: str, + transport: Optional[Transport] = ..., + encoding: Optional[str] = ..., + verbose: bool = ..., + allow_none: bool = ..., + use_datetime: bool = ..., + context: Optional[SSLContext] = ..., + ) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, attr: str) -> Optional[Transport]: ... + +Server = ServerProxy From b89c24c756adda524e988e7923b63e05e98907e3 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 17:26:27 +0000 Subject: [PATCH 48/50] Install test requirements before mypyc build, since it includes stubs --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9bfced0ab303..f88b04f44ccd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -93,7 +93,7 @@ install: # means that tox picks up the mypy from the source directories instead of # the version it installed into a venv. This is also *why* we need to do this, # since if we arranged for tox to build with mypyc, pytest wouldn't use it. -- if [[ $TEST_MYPYC == 1 ]]; then pip install -r mypy-requirements.txt; CC=clang MYPYC_OPT_LEVEL=0 python3 setup.py --use-mypyc build_ext --inplace; fi +- if [[ $TEST_MYPYC == 1 ]]; then pip install -r test-requirements.txt; CC=clang MYPYC_OPT_LEVEL=0 python3 setup.py --use-mypyc build_ext --inplace; fi script: - tox --skip-pkg-install -- $EXTRA_ARGS From 21b7882a9bd91a9c443440471fcf6af051be8915 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 18:13:47 +0000 Subject: [PATCH 49/50] Move a dataclass mypyc test case to Python 3.7 specific test file --- mypyc/test-data/run-classes.test | 142 ----------------------------- mypyc/test-data/run-python37.test | 143 ++++++++++++++++++++++++++++++ mypyc/test-data/run-python38.test | 2 + mypyc/test/test_run.py | 2 + 4 files changed, 147 insertions(+), 142 deletions(-) create mode 100644 mypyc/test-data/run-python37.test diff --git a/mypyc/test-data/run-classes.test b/mypyc/test-data/run-classes.test index dcc00630798a..0c794a4bf9fc 100644 --- a/mypyc/test-data/run-classes.test +++ b/mypyc/test-data/run-classes.test @@ -150,148 +150,6 @@ if sys.version_info[:2] > (3, 5): assert TestEnum.b.name == 'b' assert TestEnum.b.value == 2 -[case testRunDataclass] -from dataclasses import dataclass, field -from typing import Set, List, Callable, Any - -@dataclass -class Person1: - age : int - name : str - - def __bool__(self) -> bool: - return self.name == 'robot' - -def testBool(p: Person1) -> bool: - if p: - return True - else: - return False - -@dataclass -class Person1b(Person1): - id: str = '000' - -@dataclass -class Person2: - age : int - name : str = field(default='robot') - -@dataclass(order = True) -class Person3: - age : int = field(default = 6) - friendIDs : List[int] = field(default_factory = list) - - def get_age(self) -> int: - return (self.age) - - def set_age(self, new_age : int) -> None: - self.age = new_age - - def add_friendID(self, fid : int) -> None: - self.friendIDs.append(fid) - - def get_friendIDs(self) -> List[int]: - return self.friendIDs - -def get_next_age(g: Callable[[Any], int]) -> Callable[[Any], int]: - def f(a: Any) -> int: - return g(a) + 1 - return f - -@dataclass -class Person4: - age : int - _name : str = 'Bot' - - @get_next_age - def get_age(self) -> int: - return self.age - - @property - def name(self) -> str: - return self._name - -[file other.py] -from native import Person1, Person1b, Person2, Person3, Person4, testBool -i1 = Person1(age = 5, name = 'robot') -assert i1.age == 5 -assert i1.name == 'robot' -assert testBool(i1) == True -assert testBool(Person1(age = 5, name = 'robo')) == False -i1b = Person1b(age = 5, name = 'robot') -assert i1b.age == 5 -assert i1b.name == 'robot' -assert testBool(i1b) == True -assert testBool(Person1b(age = 5, name = 'robo')) == False -i1c = Person1b(age = 20, name = 'robot', id = 'test') -assert i1c.age == 20 -assert i1c.id == 'test' - -i2 = Person2(age = 5) -assert i2.age == 5 -assert i2.name == 'robot' -i3 = Person2(age = 5, name = 'new_robot') -assert i3.age == 5 -assert i3.name == 'new_robot' -i4 = Person3() -assert i4.age == 6 -assert i4.friendIDs == [] -i5 = Person3(age = 5) -assert i5.age == 5 -assert i5.friendIDs == [] -i6 = Person3(age = 5, friendIDs = [1,2,3]) -assert i6.age == 5 -assert i6.friendIDs == [1,2,3] -assert i6.get_age() == 5 -i6.set_age(10) -assert i6.get_age() == 10 -i6.add_friendID(4) -assert i6.get_friendIDs() == [1,2,3,4] -i7 = Person4(age = 5) -assert i7.get_age() == 6 -i7.age += 3 -assert i7.age == 8 -assert i7.name == 'Bot' -i8 = Person3(age = 1, friendIDs = [1,2]) -i9 = Person3(age = 1, friendIDs = [1,2]) -assert i8 == i9 -i8.age = 2 -assert i8 > i9 - - -[file driver.py] -import sys - -# Dataclasses introduced in 3.7 -version = sys.version_info[:2] -if version[0] < 3 or version[1] < 7: - exit() - -# Run the tests in both interpreted and compiled mode -import other -import other_interpreted - -# Test for an exceptional cases -from testutil import assertRaises -from native import Person1, Person1b, Person3 -from types import BuiltinMethodType - -with assertRaises(TypeError, "missing 1 required positional argument"): - Person1(0) - -with assertRaises(TypeError, "missing 2 required positional arguments"): - Person1b() - -with assertRaises(TypeError, "int object expected; got str"): - Person1('nope', 'test') - -p = Person1(0, 'test') -with assertRaises(TypeError, "int object expected; got str"): - p.age = 'nope' - -assert isinstance(Person3().get_age, BuiltinMethodType) - [case testGetAttribute] class C: x: int diff --git a/mypyc/test-data/run-python37.test b/mypyc/test-data/run-python37.test new file mode 100644 index 000000000000..3660ba13a6c8 --- /dev/null +++ b/mypyc/test-data/run-python37.test @@ -0,0 +1,143 @@ +-- Test cases for Python 3.7 features + +[case testRunDataclass] +from dataclasses import dataclass, field +from typing import Set, List, Callable, Any + +@dataclass +class Person1: + age : int + name : str + + def __bool__(self) -> bool: + return self.name == 'robot' + +def testBool(p: Person1) -> bool: + if p: + return True + else: + return False + +@dataclass +class Person1b(Person1): + id: str = '000' + +@dataclass +class Person2: + age : int + name : str = field(default='robot') + +@dataclass(order = True) +class Person3: + age : int = field(default = 6) + friendIDs : List[int] = field(default_factory = list) + + def get_age(self) -> int: + return (self.age) + + def set_age(self, new_age : int) -> None: + self.age = new_age + + def add_friendID(self, fid : int) -> None: + self.friendIDs.append(fid) + + def get_friendIDs(self) -> List[int]: + return self.friendIDs + +def get_next_age(g: Callable[[Any], int]) -> Callable[[Any], int]: + def f(a: Any) -> int: + return g(a) + 1 + return f + +@dataclass +class Person4: + age : int + _name : str = 'Bot' + + @get_next_age + def get_age(self) -> int: + return self.age + + @property + def name(self) -> str: + return self._name + +[file other.py] +from native import Person1, Person1b, Person2, Person3, Person4, testBool +i1 = Person1(age = 5, name = 'robot') +assert i1.age == 5 +assert i1.name == 'robot' +assert testBool(i1) == True +assert testBool(Person1(age = 5, name = 'robo')) == False +i1b = Person1b(age = 5, name = 'robot') +assert i1b.age == 5 +assert i1b.name == 'robot' +assert testBool(i1b) == True +assert testBool(Person1b(age = 5, name = 'robo')) == False +i1c = Person1b(age = 20, name = 'robot', id = 'test') +assert i1c.age == 20 +assert i1c.id == 'test' + +i2 = Person2(age = 5) +assert i2.age == 5 +assert i2.name == 'robot' +i3 = Person2(age = 5, name = 'new_robot') +assert i3.age == 5 +assert i3.name == 'new_robot' +i4 = Person3() +assert i4.age == 6 +assert i4.friendIDs == [] +i5 = Person3(age = 5) +assert i5.age == 5 +assert i5.friendIDs == [] +i6 = Person3(age = 5, friendIDs = [1,2,3]) +assert i6.age == 5 +assert i6.friendIDs == [1,2,3] +assert i6.get_age() == 5 +i6.set_age(10) +assert i6.get_age() == 10 +i6.add_friendID(4) +assert i6.get_friendIDs() == [1,2,3,4] +i7 = Person4(age = 5) +assert i7.get_age() == 6 +i7.age += 3 +assert i7.age == 8 +assert i7.name == 'Bot' +i8 = Person3(age = 1, friendIDs = [1,2]) +i9 = Person3(age = 1, friendIDs = [1,2]) +assert i8 == i9 +i8.age = 2 +assert i8 > i9 + + +[file driver.py] +import sys + +# Dataclasses introduced in 3.7 +version = sys.version_info[:2] +if version[0] < 3 or version[1] < 7: + exit() + +# Run the tests in both interpreted and compiled mode +import other +import other_interpreted + +# Test for an exceptional cases +from testutil import assertRaises +from native import Person1, Person1b, Person3 +from types import BuiltinMethodType + +with assertRaises(TypeError, "missing 1 required positional argument"): + Person1(0) + +with assertRaises(TypeError, "missing 2 required positional arguments"): + Person1b() + +with assertRaises(TypeError, "int object expected; got str"): + Person1('nope', 'test') + +p = Person1(0, 'test') +with assertRaises(TypeError, "int object expected; got str"): + p.age = 'nope' + +assert isinstance(Person3().get_age, BuiltinMethodType) diff --git a/mypyc/test-data/run-python38.test b/mypyc/test-data/run-python38.test index beb553065f74..9b620ddb8dae 100644 --- a/mypyc/test-data/run-python38.test +++ b/mypyc/test-data/run-python38.test @@ -1,3 +1,5 @@ +-- Test cases for Python 3.8 features + [case testWalrus1] from typing import Optional diff --git a/mypyc/test/test_run.py b/mypyc/test/test_run.py index 938bdeb7c995..d219c6f811e8 100644 --- a/mypyc/test/test_run.py +++ b/mypyc/test/test_run.py @@ -51,6 +51,8 @@ 'run-bench.test', 'run-mypy-sim.test', ] +if sys.version_info >= (3, 7): + files.append('run-python37.test') if sys.version_info >= (3, 8): files.append('run-python38.test') From d13f6a49bd2d97e8c4342708e540374fed9571ae Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 26 Jan 2021 18:29:41 +0000 Subject: [PATCH 50/50] Fix test case on 3.9 --- mypy/test/testsamples.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mypy/test/testsamples.py b/mypy/test/testsamples.py index c132c3e3f676..2bbd791f3b6e 100644 --- a/mypy/test/testsamples.py +++ b/mypy/test/testsamples.py @@ -48,6 +48,9 @@ class SamplesSuite(Suite): def test_samples(self) -> None: for f in find_files(os.path.join('test-data', 'samples'), suffix='.py'): mypy_args = ['--no-strict-optional'] + if f == os.path.join('test-data', 'samples', 'crawl2.py'): + # This test requires 3.5 for async functions + mypy_args.append('--python-version=3.5') run_mypy(mypy_args + [f]) def test_stdlibsamples(self) -> None: