From 3c6615caaf621acf9882329f7a57135df4bed52c Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 9 Mar 2022 13:32:10 +0000 Subject: [PATCH 1/4] Sync typeshed Source commit: https://github.com/python/typeshed/commit/4e87b9058f0908fa895076c0d9643e18be785be6 --- .../stdlib/@python2/BaseHTTPServer.pyi | 10 +- .../stdlib/@python2/CGIHTTPServer.pyi | 3 +- .../typeshed/stdlib/@python2/ConfigParser.pyi | 30 +- mypy/typeshed/stdlib/@python2/Cookie.pyi | 6 +- mypy/typeshed/stdlib/@python2/HTMLParser.pyi | 6 +- mypy/typeshed/stdlib/@python2/Queue.pyi | 5 +- .../typeshed/stdlib/@python2/SocketServer.pyi | 27 +- mypy/typeshed/stdlib/@python2/StringIO.pyi | 4 +- mypy/typeshed/stdlib/@python2/UserDict.pyi | 16 +- mypy/typeshed/stdlib/@python2/UserList.pyi | 8 +- mypy/typeshed/stdlib/@python2/UserString.pyi | 76 +- mypy/typeshed/stdlib/@python2/__builtin__.pyi | 345 ++++---- mypy/typeshed/stdlib/@python2/__future__.pyi | 3 +- mypy/typeshed/stdlib/@python2/_ast.pyi | 96 ++- mypy/typeshed/stdlib/@python2/_codecs.pyi | 78 +- .../typeshed/stdlib/@python2/_collections.pyi | 12 +- mypy/typeshed/stdlib/@python2/_csv.pyi | 10 +- mypy/typeshed/stdlib/@python2/_curses.pyi | 22 +- .../stdlib/@python2/_dummy_threading.pyi | 33 +- mypy/typeshed/stdlib/@python2/_functools.pyi | 6 +- mypy/typeshed/stdlib/@python2/_heapq.pyi | 16 +- mypy/typeshed/stdlib/@python2/_hotshot.pyi | 4 +- mypy/typeshed/stdlib/@python2/_io.pyi | 28 +- mypy/typeshed/stdlib/@python2/_json.pyi | 4 +- mypy/typeshed/stdlib/@python2/_markupbase.pyi | 4 +- mypy/typeshed/stdlib/@python2/_msi.pyi | 3 +- .../typeshed/stdlib/@python2/_osx_support.pyi | 32 +- mypy/typeshed/stdlib/@python2/_random.pyi | 4 +- mypy/typeshed/stdlib/@python2/_socket.pyi | 20 +- mypy/typeshed/stdlib/@python2/_sre.pyi | 22 +- mypy/typeshed/stdlib/@python2/_struct.pyi | 10 +- mypy/typeshed/stdlib/@python2/_symtable.pyi | 8 +- mypy/typeshed/stdlib/@python2/_thread.pyi | 6 +- .../stdlib/@python2/_typeshed/__init__.pyi | 4 +- .../stdlib/@python2/_typeshed/wsgi.pyi | 10 +- mypy/typeshed/stdlib/@python2/_warnings.pyi | 18 +- mypy/typeshed/stdlib/@python2/_weakref.pyi | 4 +- mypy/typeshed/stdlib/@python2/_weakrefset.pyi | 26 +- mypy/typeshed/stdlib/@python2/_winreg.pyi | 13 +- mypy/typeshed/stdlib/@python2/abc.pyi | 6 +- mypy/typeshed/stdlib/@python2/aifc.pyi | 10 +- mypy/typeshed/stdlib/@python2/argparse.pyi | 110 ++- mypy/typeshed/stdlib/@python2/array.pyi | 13 +- mypy/typeshed/stdlib/@python2/asynchat.pyi | 4 +- mypy/typeshed/stdlib/@python2/asyncore.pyi | 19 +- mypy/typeshed/stdlib/@python2/audioop.pyi | 16 +- mypy/typeshed/stdlib/@python2/bdb.pyi | 37 +- mypy/typeshed/stdlib/@python2/binhex.pyi | 4 +- mypy/typeshed/stdlib/@python2/builtins.pyi | 345 ++++---- mypy/typeshed/stdlib/@python2/bz2.pyi | 9 +- mypy/typeshed/stdlib/@python2/cPickle.pyi | 4 +- mypy/typeshed/stdlib/@python2/cProfile.pyi | 16 +- mypy/typeshed/stdlib/@python2/cStringIO.pyi | 6 +- mypy/typeshed/stdlib/@python2/calendar.pyi | 26 +- mypy/typeshed/stdlib/@python2/cgi.pyi | 18 +- mypy/typeshed/stdlib/@python2/cgitb.pyi | 12 +- mypy/typeshed/stdlib/@python2/cmath.pyi | 4 +- mypy/typeshed/stdlib/@python2/cmd.pyi | 22 +- mypy/typeshed/stdlib/@python2/codecs.pyi | 92 +-- mypy/typeshed/stdlib/@python2/collections.pyi | 41 +- mypy/typeshed/stdlib/@python2/colorsys.pyi | 14 +- mypy/typeshed/stdlib/@python2/commands.pyi | 4 +- mypy/typeshed/stdlib/@python2/contextlib.pyi | 10 +- mypy/typeshed/stdlib/@python2/copy.pyi | 4 +- mypy/typeshed/stdlib/@python2/copy_reg.pyi | 6 +- mypy/typeshed/stdlib/@python2/copyreg.pyi | 6 +- mypy/typeshed/stdlib/@python2/csv.pyi | 20 +- .../stdlib/@python2/ctypes/__init__.pyi | 80 +- .../stdlib/@python2/curses/__init__.pyi | 2 +- .../typeshed/stdlib/@python2/curses/ascii.pyi | 4 +- mypy/typeshed/stdlib/@python2/datetime.pyi | 46 +- .../typeshed/stdlib/@python2/dbm/__init__.pyi | 9 +- mypy/typeshed/stdlib/@python2/dbm/dumb.pyi | 7 +- mypy/typeshed/stdlib/@python2/dbm/gnu.pyi | 9 +- mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi | 11 +- mypy/typeshed/stdlib/@python2/decimal.pyi | 32 +- mypy/typeshed/stdlib/@python2/difflib.pyi | 27 +- mypy/typeshed/stdlib/@python2/dircache.pyi | 4 +- mypy/typeshed/stdlib/@python2/dis.pyi | 8 +- .../stdlib/@python2/distutils/ccompiler.pyi | 126 +-- .../stdlib/@python2/distutils/cmd.pyi | 18 +- .../@python2/distutils/command/bdist_msi.pyi | 1 + .../@python2/distutils/command/config.pyi | 8 +- .../distutils/command/install_egg_info.pyi | 6 +- .../@python2/distutils/command/upload.pyi | 4 +- .../stdlib/@python2/distutils/config.pyi | 6 +- .../stdlib/@python2/distutils/core.pyi | 44 +- .../stdlib/@python2/distutils/dep_util.pyi | 6 +- .../stdlib/@python2/distutils/dir_util.pyi | 8 +- .../stdlib/@python2/distutils/dist.pyi | 6 +- .../stdlib/@python2/distutils/extension.pyi | 26 +- .../@python2/distutils/fancy_getopt.pyi | 22 +- .../stdlib/@python2/distutils/file_util.pyi | 4 +- .../stdlib/@python2/distutils/spawn.pyi | 4 +- .../stdlib/@python2/distutils/text_file.pyi | 6 +- .../stdlib/@python2/distutils/util.pyi | 11 +- .../stdlib/@python2/distutils/version.pyi | 20 +- mypy/typeshed/stdlib/@python2/doctest.pyi | 50 +- .../typeshed/stdlib/@python2/dummy_thread.pyi | 4 +- .../@python2/email/mime/application.pyi | 4 +- .../stdlib/@python2/encodings/utf_8.pyi | 4 +- mypy/typeshed/stdlib/@python2/filecmp.pyi | 32 +- mypy/typeshed/stdlib/@python2/fnmatch.pyi | 4 +- mypy/typeshed/stdlib/@python2/formatter.pyi | 16 +- mypy/typeshed/stdlib/@python2/fractions.pyi | 18 +- mypy/typeshed/stdlib/@python2/ftplib.pyi | 25 +- mypy/typeshed/stdlib/@python2/functools.pyi | 8 +- mypy/typeshed/stdlib/@python2/gc.pyi | 14 +- mypy/typeshed/stdlib/@python2/genericpath.pyi | 6 +- mypy/typeshed/stdlib/@python2/getopt.pyi | 7 +- mypy/typeshed/stdlib/@python2/gettext.pyi | 8 +- mypy/typeshed/stdlib/@python2/glob.pyi | 8 +- mypy/typeshed/stdlib/@python2/grp.pyi | 6 +- mypy/typeshed/stdlib/@python2/hashlib.pyi | 8 +- mypy/typeshed/stdlib/@python2/heapq.pyi | 18 +- .../stdlib/@python2/htmlentitydefs.pyi | 8 +- mypy/typeshed/stdlib/@python2/httplib.pyi | 6 +- mypy/typeshed/stdlib/@python2/imaplib.pyi | 37 +- mypy/typeshed/stdlib/@python2/imghdr.pyi | 4 +- mypy/typeshed/stdlib/@python2/imp.pyi | 8 +- mypy/typeshed/stdlib/@python2/inspect.pyi | 42 +- mypy/typeshed/stdlib/@python2/itertools.pyi | 43 +- mypy/typeshed/stdlib/@python2/json.pyi | 26 +- .../stdlib/@python2/lib2to3/pgen2/grammar.pyi | 31 +- .../@python2/lib2to3/pgen2/literals.pyi | 4 +- .../stdlib/@python2/lib2to3/pgen2/parse.pyi | 6 +- .../stdlib/@python2/lib2to3/pgen2/pgen.pyi | 32 +- .../stdlib/@python2/lib2to3/pgen2/token.pyi | 4 +- .../@python2/lib2to3/pgen2/tokenize.pyi | 10 +- .../stdlib/@python2/lib2to3/pytree.pyi | 33 +- mypy/typeshed/stdlib/@python2/linecache.pyi | 8 +- mypy/typeshed/stdlib/@python2/locale.pyi | 12 +- .../stdlib/@python2/logging/__init__.pyi | 76 +- .../stdlib/@python2/logging/config.pyi | 6 +- .../stdlib/@python2/logging/handlers.pyi | 24 +- mypy/typeshed/stdlib/@python2/macpath.pyi | 4 +- mypy/typeshed/stdlib/@python2/mailbox.pyi | 38 +- mypy/typeshed/stdlib/@python2/mailcap.pyi | 10 +- mypy/typeshed/stdlib/@python2/markupbase.pyi | 4 +- mypy/typeshed/stdlib/@python2/math.pyi | 6 +- mypy/typeshed/stdlib/@python2/mimetypes.pyi | 32 +- mypy/typeshed/stdlib/@python2/mmap.pyi | 1 + .../typeshed/stdlib/@python2/modulefinder.pyi | 33 +- .../stdlib/@python2/msilib/__init__.pyi | 39 +- .../stdlib/@python2/msilib/schema.pyi | 5 +- .../stdlib/@python2/msilib/sequence.pyi | 6 +- mypy/typeshed/stdlib/@python2/msilib/text.pyi | 7 +- .../multiprocessing/dummy/__init__.pyi | 4 +- .../multiprocessing/dummy/connection.pyi | 6 +- .../stdlib/@python2/multiprocessing/pool.pyi | 13 +- mypy/typeshed/stdlib/@python2/mutex.pyi | 5 +- mypy/typeshed/stdlib/@python2/netrc.pyi | 8 +- mypy/typeshed/stdlib/@python2/nis.pyi | 6 +- mypy/typeshed/stdlib/@python2/nntplib.pyi | 51 +- mypy/typeshed/stdlib/@python2/ntpath.pyi | 12 +- mypy/typeshed/stdlib/@python2/numbers.pyi | 4 +- mypy/typeshed/stdlib/@python2/opcode.pyi | 20 +- mypy/typeshed/stdlib/@python2/operator.pyi | 30 +- mypy/typeshed/stdlib/@python2/optparse.pyi | 74 +- mypy/typeshed/stdlib/@python2/os/__init__.pyi | 58 +- mypy/typeshed/stdlib/@python2/os/path.pyi | 12 +- mypy/typeshed/stdlib/@python2/os2emxpath.pyi | 12 +- mypy/typeshed/stdlib/@python2/ossaudiodev.pyi | 251 +++--- mypy/typeshed/stdlib/@python2/parser.pyi | 10 +- mypy/typeshed/stdlib/@python2/pdb.pyi | 32 +- mypy/typeshed/stdlib/@python2/pickle.pyi | 12 +- mypy/typeshed/stdlib/@python2/pickletools.pyi | 18 +- mypy/typeshed/stdlib/@python2/pkgutil.pyi | 8 +- mypy/typeshed/stdlib/@python2/platform.pyi | 20 +- mypy/typeshed/stdlib/@python2/plistlib.pyi | 4 +- mypy/typeshed/stdlib/@python2/popen2.pyi | 8 +- mypy/typeshed/stdlib/@python2/poplib.pyi | 6 +- mypy/typeshed/stdlib/@python2/posix.pyi | 38 +- mypy/typeshed/stdlib/@python2/posixpath.pyi | 12 +- mypy/typeshed/stdlib/@python2/pprint.pyi | 4 +- mypy/typeshed/stdlib/@python2/profile.pyi | 16 +- mypy/typeshed/stdlib/@python2/pstats.pyi | 29 +- mypy/typeshed/stdlib/@python2/pty.pyi | 8 +- mypy/typeshed/stdlib/@python2/pwd.pyi | 5 +- mypy/typeshed/stdlib/@python2/py_compile.pyi | 6 +- mypy/typeshed/stdlib/@python2/pyclbr.pyi | 12 +- mypy/typeshed/stdlib/@python2/pydoc.pyi | 47 +- .../stdlib/@python2/pydoc_data/topics.pyi | 4 +- .../stdlib/@python2/pyexpat/__init__.pyi | 14 +- mypy/typeshed/stdlib/@python2/random.pyi | 6 +- mypy/typeshed/stdlib/@python2/re.pyi | 18 +- mypy/typeshed/stdlib/@python2/repr.pyi | 4 +- mypy/typeshed/stdlib/@python2/resource.pyi | 7 +- mypy/typeshed/stdlib/@python2/rlcompleter.pyi | 6 +- mypy/typeshed/stdlib/@python2/sched.pyi | 12 +- mypy/typeshed/stdlib/@python2/select.pyi | 10 +- mypy/typeshed/stdlib/@python2/sets.pyi | 38 +- mypy/typeshed/stdlib/@python2/shelve.pyi | 21 +- mypy/typeshed/stdlib/@python2/shlex.pyi | 9 +- mypy/typeshed/stdlib/@python2/shutil.pyi | 12 +- mypy/typeshed/stdlib/@python2/signal.pyi | 98 +-- mypy/typeshed/stdlib/@python2/site.pyi | 6 +- mypy/typeshed/stdlib/@python2/smtpd.pyi | 12 +- mypy/typeshed/stdlib/@python2/sndhdr.pyi | 4 +- mypy/typeshed/stdlib/@python2/socket.pyi | 33 +- mypy/typeshed/stdlib/@python2/spwd.pyi | 4 +- .../stdlib/@python2/sqlite3/__init__.pyi | 2 +- .../stdlib/@python2/sqlite3/dbapi2.pyi | 17 +- mypy/typeshed/stdlib/@python2/sre_compile.pyi | 4 +- .../stdlib/@python2/sre_constants.pyi | 16 +- mypy/typeshed/stdlib/@python2/sre_parse.pyi | 36 +- mypy/typeshed/stdlib/@python2/ssl.pyi | 30 +- mypy/typeshed/stdlib/@python2/string.pyi | 10 +- mypy/typeshed/stdlib/@python2/stringold.pyi | 8 +- mypy/typeshed/stdlib/@python2/strop.pyi | 6 +- mypy/typeshed/stdlib/@python2/struct.pyi | 10 +- mypy/typeshed/stdlib/@python2/subprocess.pyi | 4 +- mypy/typeshed/stdlib/@python2/sunau.pyi | 4 +- mypy/typeshed/stdlib/@python2/symbol.pyi | 4 +- mypy/typeshed/stdlib/@python2/symtable.pyi | 16 +- mypy/typeshed/stdlib/@python2/sys.pyi | 30 +- mypy/typeshed/stdlib/@python2/sysconfig.pyi | 16 +- mypy/typeshed/stdlib/@python2/tabnanny.pyi | 4 +- mypy/typeshed/stdlib/@python2/tarfile.pyi | 39 +- mypy/typeshed/stdlib/@python2/telnetlib.pyi | 4 +- mypy/typeshed/stdlib/@python2/tempfile.pyi | 13 +- mypy/typeshed/stdlib/@python2/termios.pyi | 7 +- mypy/typeshed/stdlib/@python2/textwrap.pyi | 8 +- mypy/typeshed/stdlib/@python2/this.pyi | 4 +- mypy/typeshed/stdlib/@python2/thread.pyi | 2 + mypy/typeshed/stdlib/@python2/threading.pyi | 33 +- mypy/typeshed/stdlib/@python2/time.pyi | 8 +- mypy/typeshed/stdlib/@python2/timeit.pyi | 6 +- mypy/typeshed/stdlib/@python2/toaiff.pyi | 5 +- mypy/typeshed/stdlib/@python2/token.pyi | 4 +- mypy/typeshed/stdlib/@python2/tokenize.pyi | 22 +- mypy/typeshed/stdlib/@python2/trace.pyi | 16 +- mypy/typeshed/stdlib/@python2/traceback.pyi | 22 +- mypy/typeshed/stdlib/@python2/turtle.pyi | 63 +- mypy/typeshed/stdlib/@python2/types.pyi | 58 +- mypy/typeshed/stdlib/@python2/typing.pyi | 96 ++- .../stdlib/@python2/typing_extensions.pyi | 42 +- mypy/typeshed/stdlib/@python2/unittest.pyi | 73 +- mypy/typeshed/stdlib/@python2/urllib.pyi | 11 +- mypy/typeshed/stdlib/@python2/urllib2.pyi | 22 +- mypy/typeshed/stdlib/@python2/urlparse.pyi | 24 +- mypy/typeshed/stdlib/@python2/uuid.pyi | 4 +- mypy/typeshed/stdlib/@python2/warnings.pyi | 20 +- mypy/typeshed/stdlib/@python2/wave.pyi | 4 +- mypy/typeshed/stdlib/@python2/weakref.pyi | 31 +- mypy/typeshed/stdlib/@python2/webbrowser.pyi | 23 +- .../stdlib/@python2/wsgiref/handlers.pyi | 16 +- .../stdlib/@python2/wsgiref/headers.pyi | 10 +- .../stdlib/@python2/wsgiref/simple_server.pyi | 8 +- mypy/typeshed/stdlib/@python2/xdrlib.pyi | 8 +- .../stdlib/@python2/xml/dom/domreg.pyi | 8 +- .../stdlib/@python2/xml/dom/minicompat.pyi | 10 +- .../stdlib/@python2/xml/dom/minidom.pyi | 9 +- .../stdlib/@python2/xml/etree/ElementPath.pyi | 22 +- .../stdlib/@python2/xml/etree/ElementTree.pyi | 53 +- .../@python2/xml/etree/cElementTree.pyi | 2 +- .../stdlib/@python2/xml/sax/__init__.pyi | 6 +- .../stdlib/@python2/xml/sax/xmlreader.pyi | 4 +- mypy/typeshed/stdlib/@python2/xmlrpclib.pyi | 42 +- mypy/typeshed/stdlib/@python2/zipfile.pyi | 21 +- mypy/typeshed/stdlib/VERSIONS | 13 + mypy/typeshed/stdlib/_ast.pyi | 29 +- mypy/typeshed/stdlib/_bisect.pyi | 66 +- mypy/typeshed/stdlib/_collections_abc.pyi | 9 +- mypy/typeshed/stdlib/_compression.pyi | 8 +- mypy/typeshed/stdlib/_csv.pyi | 15 +- mypy/typeshed/stdlib/_curses.pyi | 8 + mypy/typeshed/stdlib/_decimal.pyi | 2 + mypy/typeshed/stdlib/_dummy_threading.pyi | 67 +- mypy/typeshed/stdlib/_heapq.pyi | 2 + mypy/typeshed/stdlib/_json.pyi | 27 +- mypy/typeshed/stdlib/_msi.pyi | 6 +- mypy/typeshed/stdlib/_operator.pyi | 27 +- mypy/typeshed/stdlib/_osx_support.pyi | 2 +- mypy/typeshed/stdlib/_py_abc.pyi | 12 +- mypy/typeshed/stdlib/_socket.pyi | 17 +- mypy/typeshed/stdlib/_thread.pyi | 8 +- mypy/typeshed/stdlib/_threading_local.pyi | 1 + mypy/typeshed/stdlib/_tkinter.pyi | 94 ++- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 25 +- mypy/typeshed/stdlib/_warnings.pyi | 12 +- mypy/typeshed/stdlib/_weakrefset.pyi | 28 +- mypy/typeshed/stdlib/_winapi.pyi | 1 + mypy/typeshed/stdlib/abc.pyi | 22 +- mypy/typeshed/stdlib/aifc.pyi | 11 +- mypy/typeshed/stdlib/argparse.pyi | 112 ++- mypy/typeshed/stdlib/array.pyi | 24 +- mypy/typeshed/stdlib/ast.pyi | 4 + mypy/typeshed/stdlib/asyncio/__init__.pyi | 134 +--- mypy/typeshed/stdlib/asyncio/base_events.pyi | 88 +- mypy/typeshed/stdlib/asyncio/base_futures.pyi | 12 +- mypy/typeshed/stdlib/asyncio/compat.pyi | 10 +- mypy/typeshed/stdlib/asyncio/coroutines.pyi | 7 + mypy/typeshed/stdlib/asyncio/events.pyi | 183 ++++- mypy/typeshed/stdlib/asyncio/exceptions.pyi | 34 +- .../stdlib/asyncio/format_helpers.pyi | 18 +- mypy/typeshed/stdlib/asyncio/futures.pyi | 41 +- mypy/typeshed/stdlib/asyncio/locks.pyi | 43 +- mypy/typeshed/stdlib/asyncio/mixins.pyi | 7 + .../stdlib/asyncio/proactor_events.pyi | 41 +- mypy/typeshed/stdlib/asyncio/protocols.pyi | 13 +- mypy/typeshed/stdlib/asyncio/queues.pyi | 7 +- mypy/typeshed/stdlib/asyncio/runners.pyi | 14 +- .../stdlib/asyncio/selector_events.pyi | 6 + mypy/typeshed/stdlib/asyncio/sslproto.pyi | 4 + mypy/typeshed/stdlib/asyncio/staggered.pyi | 10 +- mypy/typeshed/stdlib/asyncio/streams.pyi | 67 +- mypy/typeshed/stdlib/asyncio/subprocess.pyi | 5 + mypy/typeshed/stdlib/asyncio/taskgroups.pyi | 17 + mypy/typeshed/stdlib/asyncio/tasks.pyi | 190 +++-- mypy/typeshed/stdlib/asyncio/threads.pyi | 5 +- mypy/typeshed/stdlib/asyncio/transports.pyi | 6 + mypy/typeshed/stdlib/asyncio/trsock.pyi | 75 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 94 ++- .../stdlib/asyncio/windows_events.pyi | 16 +- .../typeshed/stdlib/asyncio/windows_utils.pyi | 40 +- mypy/typeshed/stdlib/asyncore.pyi | 1 + mypy/typeshed/stdlib/base64.pyi | 45 ++ mypy/typeshed/stdlib/bdb.pyi | 13 +- mypy/typeshed/stdlib/binhex.pyi | 9 +- mypy/typeshed/stdlib/builtins.pyi | 316 +++++--- mypy/typeshed/stdlib/bz2.pyi | 7 +- mypy/typeshed/stdlib/cProfile.pyi | 6 +- mypy/typeshed/stdlib/calendar.pyi | 49 +- mypy/typeshed/stdlib/cgi.pyi | 51 +- mypy/typeshed/stdlib/cgitb.pyi | 8 +- mypy/typeshed/stdlib/cmd.pyi | 8 +- mypy/typeshed/stdlib/code.pyi | 2 + mypy/typeshed/stdlib/codecs.pyi | 133 +++- mypy/typeshed/stdlib/codeop.pyi | 2 + mypy/typeshed/stdlib/collections/__init__.pyi | 222 ++++-- mypy/typeshed/stdlib/colorsys.pyi | 2 + mypy/typeshed/stdlib/compileall.pyi | 2 + .../stdlib/concurrent/futures/__init__.pyi | 16 + .../stdlib/concurrent/futures/_base.pyi | 20 +- .../stdlib/concurrent/futures/process.pyi | 4 +- .../stdlib/concurrent/futures/thread.pyi | 2 + mypy/typeshed/stdlib/configparser.pyi | 45 +- mypy/typeshed/stdlib/contextlib.pyi | 123 ++- mypy/typeshed/stdlib/contextvars.pyi | 19 +- mypy/typeshed/stdlib/copy.pyi | 2 + mypy/typeshed/stdlib/copyreg.pyi | 17 +- mypy/typeshed/stdlib/crypt.pyi | 1 + mypy/typeshed/stdlib/csv.pyi | 33 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 76 +- mypy/typeshed/stdlib/curses/__init__.pyi | 4 +- mypy/typeshed/stdlib/curses/panel.pyi | 2 + mypy/typeshed/stdlib/curses/textpad.pyi | 1 + mypy/typeshed/stdlib/dataclasses.pyi | 73 +- mypy/typeshed/stdlib/datetime.pyi | 67 +- mypy/typeshed/stdlib/dbm/__init__.pyi | 8 +- mypy/typeshed/stdlib/dbm/dumb.pyi | 8 +- mypy/typeshed/stdlib/dbm/gnu.pyi | 68 +- mypy/typeshed/stdlib/dbm/ndbm.pyi | 60 +- mypy/typeshed/stdlib/decimal.pyi | 23 +- mypy/typeshed/stdlib/difflib.pyi | 27 +- mypy/typeshed/stdlib/dis.pyi | 49 +- mypy/typeshed/stdlib/distutils/cmd.pyi | 2 +- .../stdlib/distutils/command/__init__.pyi | 40 - .../stdlib/distutils/command/bdist_msi.pyi | 2 + .../distutils/command/bdist_wininst.pyi | 16 + mypy/typeshed/stdlib/distutils/core.pyi | 6 +- mypy/typeshed/stdlib/distutils/dist.pyi | 4 +- mypy/typeshed/stdlib/distutils/extension.pyi | 18 +- mypy/typeshed/stdlib/distutils/util.pyi | 3 +- mypy/typeshed/stdlib/distutils/version.pyi | 30 +- mypy/typeshed/stdlib/doctest.pyi | 43 +- .../stdlib/email/_header_value_parser.pyi | 21 +- mypy/typeshed/stdlib/email/base64mime.pyi | 2 + mypy/typeshed/stdlib/email/charset.pyi | 9 +- mypy/typeshed/stdlib/email/encoders.pyi | 2 + mypy/typeshed/stdlib/email/feedparser.pyi | 2 + mypy/typeshed/stdlib/email/generator.pyi | 24 +- mypy/typeshed/stdlib/email/header.pyi | 8 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 16 +- mypy/typeshed/stdlib/email/iterators.pyi | 7 + mypy/typeshed/stdlib/email/message.pyi | 8 +- .../stdlib/email/mime/application.pyi | 2 + mypy/typeshed/stdlib/email/mime/audio.pyi | 2 + mypy/typeshed/stdlib/email/mime/base.pyi | 2 + mypy/typeshed/stdlib/email/mime/image.pyi | 2 + mypy/typeshed/stdlib/email/mime/message.pyi | 2 + mypy/typeshed/stdlib/email/mime/multipart.pyi | 2 + .../stdlib/email/mime/nonmultipart.pyi | 2 + mypy/typeshed/stdlib/email/mime/text.pyi | 2 + mypy/typeshed/stdlib/email/parser.pyi | 10 +- mypy/typeshed/stdlib/email/policy.pyi | 2 + mypy/typeshed/stdlib/email/quoprimime.pyi | 13 + mypy/typeshed/stdlib/email/utils.pyi | 18 + mypy/typeshed/stdlib/ensurepip/__init__.pyi | 2 + mypy/typeshed/stdlib/enum.pyi | 198 +++-- mypy/typeshed/stdlib/errno.pyi | 1 + mypy/typeshed/stdlib/fcntl.pyi | 132 +-- mypy/typeshed/stdlib/filecmp.pyi | 9 +- mypy/typeshed/stdlib/fileinput.pyi | 21 +- mypy/typeshed/stdlib/fnmatch.pyi | 2 + mypy/typeshed/stdlib/fractions.pyi | 114 +-- mypy/typeshed/stdlib/ftplib.pyi | 19 +- mypy/typeshed/stdlib/functools.pyi | 103 ++- mypy/typeshed/stdlib/gc.pyi | 20 +- mypy/typeshed/stdlib/genericpath.pyi | 14 + mypy/typeshed/stdlib/getopt.pyi | 2 + mypy/typeshed/stdlib/getpass.pyi | 2 + mypy/typeshed/stdlib/gettext.pyi | 85 +- mypy/typeshed/stdlib/glob.pyi | 22 +- mypy/typeshed/stdlib/graphlib.pyi | 10 +- mypy/typeshed/stdlib/grp.pyi | 1 + mypy/typeshed/stdlib/gzip.pyi | 5 + mypy/typeshed/stdlib/hashlib.pyi | 24 +- mypy/typeshed/stdlib/heapq.pyi | 18 +- mypy/typeshed/stdlib/hmac.pyi | 3 +- mypy/typeshed/stdlib/html/__init__.pyi | 2 + mypy/typeshed/stdlib/html/entities.pyi | 2 + mypy/typeshed/stdlib/html/parser.pyi | 2 + mypy/typeshed/stdlib/http/__init__.pyi | 2 + mypy/typeshed/stdlib/http/client.pyi | 31 +- mypy/typeshed/stdlib/http/cookiejar.pyi | 15 +- mypy/typeshed/stdlib/http/cookies.pyi | 16 +- mypy/typeshed/stdlib/http/server.pyi | 6 + mypy/typeshed/stdlib/imaplib.pyi | 20 +- mypy/typeshed/stdlib/imghdr.pyi | 2 + mypy/typeshed/stdlib/imp.pyi | 4 +- mypy/typeshed/stdlib/importlib/__init__.pyi | 2 + mypy/typeshed/stdlib/importlib/abc.pyi | 6 +- mypy/typeshed/stdlib/importlib/machinery.pyi | 15 +- .../stdlib/importlib/metadata/__init__.pyi | 267 +++++-- mypy/typeshed/stdlib/importlib/resources.pyi | 63 +- mypy/typeshed/stdlib/inspect.pyi | 169 +++- mypy/typeshed/stdlib/io.pyi | 70 +- mypy/typeshed/stdlib/ipaddress.pyi | 82 +- mypy/typeshed/stdlib/itertools.pyi | 45 +- mypy/typeshed/stdlib/json/__init__.pyi | 12 +- mypy/typeshed/stdlib/json/decoder.pyi | 2 + mypy/typeshed/stdlib/keyword.pyi | 5 + mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi | 2 + .../typeshed/stdlib/lib2to3/pgen2/grammar.pyi | 7 +- mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi | 2 +- .../stdlib/lib2to3/pgen2/tokenize.pyi | 147 +++- mypy/typeshed/stdlib/lib2to3/pytree.pyi | 12 +- mypy/typeshed/stdlib/linecache.pyi | 6 + mypy/typeshed/stdlib/locale.pyi | 39 + mypy/typeshed/stdlib/logging/__init__.pyi | 64 +- mypy/typeshed/stdlib/logging/handlers.pyi | 8 +- mypy/typeshed/stdlib/lzma.pyi | 95 ++- mypy/typeshed/stdlib/mailbox.pyi | 92 ++- mypy/typeshed/stdlib/mailcap.pyi | 2 + mypy/typeshed/stdlib/math.pyi | 4 + mypy/typeshed/stdlib/mimetypes.pyi | 17 + mypy/typeshed/stdlib/mmap.pyi | 22 +- mypy/typeshed/stdlib/modulefinder.pyi | 2 +- mypy/typeshed/stdlib/msilib/__init__.pyi | 25 +- mypy/typeshed/stdlib/msvcrt.pyi | 11 +- .../stdlib/multiprocessing/__init__.pyi | 82 +- .../stdlib/multiprocessing/connection.pyi | 15 +- .../stdlib/multiprocessing/context.pyi | 53 +- .../stdlib/multiprocessing/dummy/__init__.pyi | 25 +- .../multiprocessing/dummy/connection.pyi | 8 +- .../stdlib/multiprocessing/managers.pyi | 15 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 14 +- .../stdlib/multiprocessing/process.pyi | 6 + .../stdlib/multiprocessing/queues.pyi | 3 + .../stdlib/multiprocessing/reduction.pyi | 84 ++ .../stdlib/multiprocessing/shared_memory.pyi | 52 +- .../stdlib/multiprocessing/sharedctypes.pyi | 24 +- .../typeshed/stdlib/multiprocessing/spawn.pyi | 10 + .../stdlib/multiprocessing/synchronize.pyi | 12 +- mypy/typeshed/stdlib/netrc.pyi | 2 + mypy/typeshed/stdlib/nis.pyi | 1 + mypy/typeshed/stdlib/nntplib.pyi | 52 +- mypy/typeshed/stdlib/ntpath.pyi | 88 +- mypy/typeshed/stdlib/numbers.pyi | 7 +- mypy/typeshed/stdlib/opcode.pyi | 41 +- mypy/typeshed/stdlib/operator.pyi | 116 +++ mypy/typeshed/stdlib/optparse.pyi | 36 +- mypy/typeshed/stdlib/os/__init__.pyi | 125 +-- mypy/typeshed/stdlib/os/path.pyi | 2 + mypy/typeshed/stdlib/ossaudiodev.pyi | 249 +++--- mypy/typeshed/stdlib/parser.pyi | 2 + mypy/typeshed/stdlib/pathlib.pyi | 100 ++- mypy/typeshed/stdlib/pdb.pyi | 9 +- mypy/typeshed/stdlib/pickle.pyi | 173 +++- mypy/typeshed/stdlib/pickletools.pyi | 10 +- mypy/typeshed/stdlib/pipes.pyi | 2 + mypy/typeshed/stdlib/pkgutil.pyi | 17 +- mypy/typeshed/stdlib/plistlib.pyi | 76 +- mypy/typeshed/stdlib/poplib.pyi | 22 +- mypy/typeshed/stdlib/posix.pyi | 4 +- mypy/typeshed/stdlib/posixpath.pyi | 41 + mypy/typeshed/stdlib/pprint.pyi | 10 +- mypy/typeshed/stdlib/profile.pyi | 13 +- mypy/typeshed/stdlib/pstats.pyi | 60 +- mypy/typeshed/stdlib/pwd.pyi | 1 + mypy/typeshed/stdlib/py_compile.pyi | 16 +- mypy/typeshed/stdlib/pyclbr.pyi | 45 +- mypy/typeshed/stdlib/pydoc.pyi | 44 +- mypy/typeshed/stdlib/queue.pyi | 14 +- mypy/typeshed/stdlib/quopri.pyi | 2 + mypy/typeshed/stdlib/random.pyi | 134 +++- mypy/typeshed/stdlib/re.pyi | 143 +++- mypy/typeshed/stdlib/readline.pyi | 17 +- mypy/typeshed/stdlib/reprlib.pyi | 2 + mypy/typeshed/stdlib/resource.pyi | 1 + mypy/typeshed/stdlib/rlcompleter.pyi | 4 + mypy/typeshed/stdlib/runpy.pyi | 2 + mypy/typeshed/stdlib/sched.pyi | 30 +- mypy/typeshed/stdlib/secrets.pyi | 2 + mypy/typeshed/stdlib/select.pyi | 12 +- mypy/typeshed/stdlib/shelve.pyi | 12 +- mypy/typeshed/stdlib/shlex.pyi | 23 +- mypy/typeshed/stdlib/shutil.pyi | 89 ++- mypy/typeshed/stdlib/signal.pyi | 30 +- mypy/typeshed/stdlib/smtpd.pyi | 15 +- mypy/typeshed/stdlib/smtplib.pyi | 38 +- mypy/typeshed/stdlib/sndhdr.pyi | 2 + mypy/typeshed/stdlib/socket.pyi | 12 +- mypy/typeshed/stdlib/socketserver.pyi | 81 +- mypy/typeshed/stdlib/spwd.pyi | 1 + mypy/typeshed/stdlib/sqlite3/__init__.pyi | 2 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 31 +- mypy/typeshed/stdlib/sre_constants.pyi | 3 +- mypy/typeshed/stdlib/sre_parse.pyi | 2 + mypy/typeshed/stdlib/ssl.pyi | 34 +- mypy/typeshed/stdlib/statistics.pyi | 88 +- mypy/typeshed/stdlib/string.pyi | 15 + mypy/typeshed/stdlib/struct.pyi | 2 + mypy/typeshed/stdlib/subprocess.pyi | 127 ++- mypy/typeshed/stdlib/sunau.pyi | 9 +- mypy/typeshed/stdlib/symtable.pyi | 3 + mypy/typeshed/stdlib/sys.pyi | 232 ++++-- mypy/typeshed/stdlib/sysconfig.pyi | 14 + mypy/typeshed/stdlib/tabnanny.pyi | 2 + mypy/typeshed/stdlib/tarfile.pyi | 78 +- mypy/typeshed/stdlib/telnetlib.pyi | 2 + mypy/typeshed/stdlib/tempfile.pyi | 32 +- mypy/typeshed/stdlib/termios.pyi | 1 + mypy/typeshed/stdlib/textwrap.pyi | 2 + mypy/typeshed/stdlib/threading.pyi | 116 ++- mypy/typeshed/stdlib/time.pyi | 17 +- mypy/typeshed/stdlib/timeit.pyi | 7 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 404 +++++++--- mypy/typeshed/stdlib/tkinter/colorchooser.pyi | 4 + mypy/typeshed/stdlib/tkinter/commondialog.pyi | 4 + mypy/typeshed/stdlib/tkinter/dialog.pyi | 4 + mypy/typeshed/stdlib/tkinter/dnd.pyi | 4 + mypy/typeshed/stdlib/tkinter/filedialog.pyi | 20 +- mypy/typeshed/stdlib/tkinter/font.pyi | 4 + mypy/typeshed/stdlib/tkinter/messagebox.pyi | 13 + mypy/typeshed/stdlib/tkinter/scrolledtext.pyi | 2 + mypy/typeshed/stdlib/tkinter/simpledialog.pyi | 8 +- mypy/typeshed/stdlib/tkinter/tix.pyi | 2 +- mypy/typeshed/stdlib/tkinter/ttk.pyi | 123 ++- mypy/typeshed/stdlib/token.pyi | 279 +++++++ mypy/typeshed/stdlib/tokenize.pyi | 307 ++++++- mypy/typeshed/stdlib/tomllib.pyi | 10 + mypy/typeshed/stdlib/trace.pyi | 3 + mypy/typeshed/stdlib/traceback.pyi | 114 ++- mypy/typeshed/stdlib/tracemalloc.pyi | 63 +- mypy/typeshed/stdlib/turtle.pyi | 148 +++- mypy/typeshed/stdlib/types.pyi | 444 ++++++++--- mypy/typeshed/stdlib/typing.pyi | 752 +++++++++++++++--- mypy/typeshed/stdlib/typing_extensions.pyi | 89 ++- mypy/typeshed/stdlib/unicodedata.pyi | 7 +- mypy/typeshed/stdlib/unittest/__init__.pyi | 54 +- mypy/typeshed/stdlib/unittest/_log.pyi | 5 +- mypy/typeshed/stdlib/unittest/async_case.pyi | 15 +- mypy/typeshed/stdlib/unittest/case.pyi | 80 +- mypy/typeshed/stdlib/unittest/loader.pyi | 14 +- mypy/typeshed/stdlib/unittest/main.pyi | 5 +- mypy/typeshed/stdlib/unittest/mock.pyi | 88 +- mypy/typeshed/stdlib/unittest/result.pyi | 4 +- mypy/typeshed/stdlib/unittest/runner.pyi | 8 +- mypy/typeshed/stdlib/unittest/suite.pyi | 1 + mypy/typeshed/stdlib/unittest/util.pyi | 2 +- mypy/typeshed/stdlib/urllib/error.pyi | 4 +- mypy/typeshed/stdlib/urllib/parse.pyi | 45 +- mypy/typeshed/stdlib/urllib/request.pyi | 57 +- mypy/typeshed/stdlib/urllib/response.pyi | 9 +- mypy/typeshed/stdlib/urllib/robotparser.pyi | 6 +- mypy/typeshed/stdlib/uu.pyi | 2 + mypy/typeshed/stdlib/uuid.pyi | 13 +- mypy/typeshed/stdlib/venv/__init__.pyi | 1 + mypy/typeshed/stdlib/warnings.pyi | 29 +- mypy/typeshed/stdlib/wave.pyi | 23 +- mypy/typeshed/stdlib/weakref.pyi | 84 +- mypy/typeshed/stdlib/webbrowser.pyi | 25 +- mypy/typeshed/stdlib/winreg.pyi | 4 +- mypy/typeshed/stdlib/winsound.pyi | 28 +- mypy/typeshed/stdlib/wsgiref/handlers.pyi | 10 +- .../typeshed/stdlib/wsgiref/simple_server.pyi | 8 +- mypy/typeshed/stdlib/wsgiref/util.pyi | 3 + mypy/typeshed/stdlib/wsgiref/validate.pyi | 2 + mypy/typeshed/stdlib/xdrlib.pyi | 2 + mypy/typeshed/stdlib/xml/dom/minicompat.pyi | 8 +- mypy/typeshed/stdlib/xml/dom/minidom.pyi | 11 +- mypy/typeshed/stdlib/xml/dom/pulldom.pyi | 12 +- mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi | 2 + .../stdlib/xml/etree/ElementInclude.pyi | 1 + .../typeshed/stdlib/xml/etree/ElementTree.pyi | 135 +++- .../stdlib/xml/etree/cElementTree.pyi | 2 +- mypy/typeshed/stdlib/xml/sax/__init__.pyi | 10 +- mypy/typeshed/stdlib/xmlrpc/client.pyi | 14 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 9 +- mypy/typeshed/stdlib/xxlimited.pyi | 3 + mypy/typeshed/stdlib/zipapp.pyi | 2 + mypy/typeshed/stdlib/zipfile.pyi | 59 +- mypy/typeshed/stdlib/zipimport.pyi | 4 + mypy/typeshed/stdlib/zlib.pyi | 43 +- mypy/typeshed/stdlib/zoneinfo/__init__.pyi | 11 +- .../stubs/mypy-extensions/mypy_extensions.pyi | 17 +- 609 files changed, 12522 insertions(+), 6100 deletions(-) create mode 100644 mypy/typeshed/stdlib/asyncio/mixins.pyi create mode 100644 mypy/typeshed/stdlib/asyncio/taskgroups.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/reduction.pyi create mode 100644 mypy/typeshed/stdlib/tomllib.pyi diff --git a/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi index 46946aa37c46..9aad705bde6c 100644 --- a/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi +++ b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi @@ -1,14 +1,14 @@ import mimetools import SocketServer -from typing import Any, BinaryIO, Callable, Mapping, Tuple +from typing import Any, BinaryIO, Callable, Mapping 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: ... class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): - client_address: Tuple[str, int] + client_address: tuple[str, int] server: SocketServer.BaseServer close_connection: bool command: str @@ -23,8 +23,8 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): 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: ... + 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: str | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi index 393dcb83217f..cc08bc02d666 100644 --- a/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi +++ b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi @@ -1,6 +1,5 @@ import SimpleHTTPServer -from typing import List class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - cgi_directories: List[str] + 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 index 89167b3e7ec8..ebf2a434e596 100644 --- a/mypy/typeshed/stdlib/@python2/ConfigParser.pyi +++ b/mypy/typeshed/stdlib/@python2/ConfigParser.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsNoArgReadline -from typing import IO, Any, Dict, List, Sequence, Tuple +from typing import IO, Any, Sequence DEFAULTSECT: str MAX_INTERPOLATION_DEPTH: int @@ -9,8 +9,6 @@ class Error(Exception): 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 @@ -42,7 +40,7 @@ class InterpolationDepthError(InterpolationError): class ParsingError(Error): filename: str - errors: List[Tuple[Any, Any]] + errors: list[tuple[Any, Any]] def __init__(self, filename: str) -> None: ... def append(self, lineno: Any, line: Any) -> None: ... @@ -53,26 +51,26 @@ class MissingSectionHeaderError(ParsingError): class RawConfigParser: _dict: Any - _sections: Dict[Any, Any] - _defaults: Dict[Any, 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 __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: str | Sequence[str]) -> List[str]: ... + def options(self, section: str) -> list[str]: ... + def read(self, filenames: 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 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] + _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: ... @@ -84,8 +82,8 @@ class RawConfigParser: class ConfigParser(RawConfigParser): _KEYCRE: Any - def get(self, section: str, option: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> Any: ... - def items(self, section: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> List[Tuple[str, Any]]: ... + def get(self, section: str, option: str, raw: bool = ..., vars: dict[Any, Any] | None = ...) -> Any: ... + def items(self, section: str, raw: bool = ..., vars: dict[Any, Any] | None = ...) -> list[tuple[str, Any]]: ... def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... def _interpolation_replace(self, match: Any) -> str: ... @@ -93,5 +91,5 @@ 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 + 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 index 3d01c3c66152..dcc27a2d349d 100644 --- a/mypy/typeshed/stdlib/@python2/Cookie.pyi +++ b/mypy/typeshed/stdlib/@python2/Cookie.pyi @@ -1,8 +1,8 @@ -from typing import Any, Dict +from typing import Any class CookieError(Exception): ... -class Morsel(Dict[Any, Any]): +class Morsel(dict[Any, Any]): key: Any def __init__(self): ... def __setitem__(self, K, V): ... @@ -14,7 +14,7 @@ class Morsel(Dict[Any, Any]): def js_output(self, attrs: Any | None = ...): ... def OutputString(self, attrs: Any | None = ...): ... -class BaseCookie(Dict[Any, Any]): +class BaseCookie(dict[Any, Any]): def value_decode(self, val): ... def value_encode(self, val): ... def __init__(self, input: Any | None = ...): ... diff --git a/mypy/typeshed/stdlib/@python2/HTMLParser.pyi b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi index ebc2735e9c48..755f0d058b15 100644 --- a/mypy/typeshed/stdlib/@python2/HTMLParser.pyi +++ b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, List, Tuple +from typing import AnyStr from markupbase import ParserBase @@ -10,8 +10,8 @@ class HTMLParser(ParserBase): 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_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): ... diff --git a/mypy/typeshed/stdlib/@python2/Queue.pyi b/mypy/typeshed/stdlib/@python2/Queue.pyi index 24743a80280d..a53380723188 100644 --- a/mypy/typeshed/stdlib/@python2/Queue.pyi +++ b/mypy/typeshed/stdlib/@python2/Queue.pyi @@ -1,4 +1,5 @@ -from typing import Any, Deque, Generic, TypeVar +from collections import deque +from typing import Any, Generic, TypeVar _T = TypeVar("_T") @@ -12,7 +13,7 @@ class Queue(Generic[_T]): not_full: Any all_tasks_done: Any unfinished_tasks: Any - queue: Deque[Any] # undocumented + queue: deque[Any] # undocumented def __init__(self, maxsize: int = ...) -> None: ... def task_done(self) -> None: ... def join(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/SocketServer.pyi b/mypy/typeshed/stdlib/@python2/SocketServer.pyi index e5a19ffd5e68..7c72675e677c 100644 --- a/mypy/typeshed/stdlib/@python2/SocketServer.pyi +++ b/mypy/typeshed/stdlib/@python2/SocketServer.pyi @@ -1,11 +1,11 @@ import sys from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, List, Text, Tuple, Union +from typing import Any, BinaryIO, Callable, ClassVar, Text, Union class BaseServer: address_family: int RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: Tuple[str, int] + server_address: tuple[str, int] socket: SocketType allow_reuse_address: bool request_queue_size: int @@ -17,19 +17,19 @@ class BaseServer: 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 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: ... + def verify_request(self, request: bytes, client_address: tuple[str, int]) -> bool: ... class TCPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... @@ -37,7 +37,7 @@ class TCPServer(BaseServer): class UDPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... @@ -50,6 +50,7 @@ if sys.platform != "win32": RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... + class UnixDatagramServer(BaseServer): def __init__( self, @@ -61,16 +62,16 @@ if sys.platform != "win32": if sys.platform != "win32": class ForkingMixIn: timeout: float | None # undocumented - active_children: List[int] | None # undocumented + active_children: list[int] | None # 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: ... + 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: ... + 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): ... diff --git a/mypy/typeshed/stdlib/@python2/StringIO.pyi b/mypy/typeshed/stdlib/@python2/StringIO.pyi index efa90f8e0330..4aa0cb3fcd5a 100644 --- a/mypy/typeshed/stdlib/@python2/StringIO.pyi +++ b/mypy/typeshed/stdlib/@python2/StringIO.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator class StringIO(IO[AnyStr], Generic[AnyStr]): closed: bool @@ -14,7 +14,7 @@ class StringIO(IO[AnyStr], Generic[AnyStr]): def tell(self) -> int: ... def read(self, n: int = ...) -> AnyStr: ... def readline(self, length: int = ...) -> AnyStr: ... - def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... + def readlines(self, sizehint: int = ...) -> list[AnyStr]: ... def truncate(self, size: int | None = ...) -> int: ... def write(self, s: AnyStr) -> int: ... def writelines(self, iterable: Iterable[AnyStr]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserDict.pyi b/mypy/typeshed/stdlib/@python2/UserDict.pyi index dce7bebafd66..fd21ff0e684b 100644 --- a/mypy/typeshed/stdlib/@python2/UserDict.pyi +++ b/mypy/typeshed/stdlib/@python2/UserDict.pyi @@ -1,11 +1,11 @@ -from typing import Any, Container, Dict, Generic, Iterable, Iterator, List, Mapping, Sized, Tuple, TypeVar, overload +from typing import Any, Container, Generic, Iterable, Iterator, Mapping, Sized, TypeVar, overload _KT = TypeVar("_KT") _VT = TypeVar("_VT") _T = TypeVar("_T") -class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): - data: Dict[_KT, _VT] +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 @@ -21,18 +21,18 @@ class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): def get(self, k: _KT) -> _VT | None: ... @overload def get(self, k: _KT, default: _VT | _T) -> _VT | _T: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + 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 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 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: ... + 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 index be4ebce5a815..36a4bc6a001c 100644 --- a/mypy/typeshed/stdlib/@python2/UserList.pyi +++ b/mypy/typeshed/stdlib/@python2/UserList.pyi @@ -1,10 +1,10 @@ -from typing import Iterable, List, MutableSequence, TypeVar, overload +from _typeshed import Self +from typing import Iterable, MutableSequence, TypeVar, overload _T = TypeVar("_T") -_S = TypeVar("_S") class UserList(MutableSequence[_T]): - data: List[_T] + data: list[_T] def insert(self, index: int, object: _T) -> None: ... @overload def __setitem__(self, i: int, o: _T) -> None: ... @@ -15,5 +15,5 @@ class UserList(MutableSequence[_T]): @overload def __getitem__(self, i: int) -> _T: ... @overload - def __getitem__(self: _S, s: slice) -> _S: ... + def __getitem__(self: Self, s: slice) -> Self: ... def sort(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserString.pyi b/mypy/typeshed/stdlib/@python2/UserString.pyi index f60dbe18f9b1..7598fcaee04d 100644 --- a/mypy/typeshed/stdlib/@python2/UserString.pyi +++ b/mypy/typeshed/stdlib/@python2/UserString.pyi @@ -1,7 +1,5 @@ -from typing import Any, Iterable, List, MutableSequence, Sequence, Text, Tuple, TypeVar, overload - -_UST = TypeVar("_UST", bound=UserString) -_MST = TypeVar("_MST", bound=MutableString) +from _typeshed import Self +from typing import Any, Iterable, MutableSequence, Sequence, Text, overload class UserString(Sequence[UserString]): data: unicode @@ -13,21 +11,21 @@ class UserString(Sequence[UserString]): def __hash__(self) -> int: ... def __len__(self) -> int: ... @overload - def __getitem__(self: _UST, i: int) -> _UST: ... + def __getitem__(self: Self, i: int) -> Self: ... @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 __getitem__(self: Self, s: slice) -> Self: ... + def __add__(self: Self, other: Any) -> Self: ... + def __radd__(self: Self, other: Any) -> Self: ... + def __mul__(self: Self, other: int) -> Self: ... + def __rmul__(self: Self, other: int) -> Self: ... + def __mod__(self: Self, args: Any) -> Self: ... + def capitalize(self: Self) -> Self: ... + def center(self: Self, width: int, *args: Any) -> Self: ... def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... - def decode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def encode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def endswith(self, suffix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... + def decode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def encode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def endswith(self, suffix: Text | tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def expandtabs(self: Self, tabsize: int = ...) -> Self: ... def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def isalpha(self) -> bool: ... @@ -40,35 +38,35 @@ class UserString(Sequence[UserString]): 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: Text | None = ...) -> _UST: ... - def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... + def ljust(self: Self, width: int, *args: Any) -> Self: ... + def lower(self: Self) -> Self: ... + def lstrip(self: Self, chars: Text | None = ...) -> Self: ... + def partition(self, sep: Text) -> tuple[Text, Text, Text]: ... + def replace(self: Self, old: Text, new: Text, maxsplit: int = ...) -> Self: ... 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: Text | None = ...) -> _UST: ... - def split(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def rsplit(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def splitlines(self, keepends: int = ...) -> List[Text]: ... - def startswith(self, prefix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UST, chars: Text | None = ...) -> _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: ... + def rjust(self: Self, width: int, *args: Any) -> Self: ... + def rpartition(self, sep: Text) -> tuple[Text, Text, Text]: ... + def rstrip(self: Self, chars: Text | None = ...) -> Self: ... + def split(self, sep: Text | None = ..., maxsplit: int = ...) -> list[Text]: ... + def rsplit(self, sep: Text | None = ..., maxsplit: int = ...) -> list[Text]: ... + def splitlines(self, keepends: int = ...) -> list[Text]: ... + def startswith(self, prefix: Text | tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def strip(self: Self, chars: Text | None = ...) -> Self: ... + def swapcase(self: Self) -> Self: ... + def title(self: Self) -> Self: ... + def translate(self: Self, *args: Any) -> Self: ... + def upper(self: Self) -> Self: ... + def zfill(self: Self, width: int) -> Self: ... class MutableString(UserString, MutableSequence[MutableString]): @overload - def __getitem__(self: _MST, i: int) -> _MST: ... + def __getitem__(self: Self, i: int) -> Self: ... @overload - def __getitem__(self: _MST, s: slice) -> _MST: ... + def __getitem__(self: Self, s: slice) -> Self: ... def __setitem__(self, index: int | slice, sub: Any) -> None: ... def __delitem__(self, index: int | slice) -> None: ... def immutable(self) -> UserString: ... - def __iadd__(self: _MST, other: Any) -> _MST: ... - def __imul__(self, n: int) -> _MST: ... + def __iadd__(self: Self, other: Any) -> Self: ... + def __imul__(self: Self, n: int) -> Self: ... def insert(self, index: int, value: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index fad8b2b4e7d8..b6ac2b78aca8 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -1,7 +1,7 @@ # 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 _typeshed import ReadableBuffer, Self, SupportsKeysAndGetItem, SupportsWrite from abc import ABCMeta from ast import mod from types import CodeType @@ -13,14 +13,11 @@ from typing import ( ByteString, Callable, Container, - Dict, - FrozenSet, Generic, ItemsView, Iterable, Iterator, KeysView, - List, Mapping, MutableMapping, MutableSequence, @@ -29,15 +26,12 @@ from typing import ( Protocol, Reversible, Sequence, - Set, Sized, SupportsAbs, SupportsComplex, SupportsFloat, SupportsInt, Text, - Tuple, - Type, TypeVar, ValuesView, overload, @@ -60,70 +54,68 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") +_TT = TypeVar("_TT", bound=type) class object: __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] + __dict__: dict[str, Any] __module__: str @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: _T) -> type[_T]: ... @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + 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 __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 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) -> str | Tuple[Any, ...]: ... - def __reduce_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: int) -> 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: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> 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: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class type(object): __base__: type - __bases__: Tuple[type, ...] + __bases__: tuple[type, ...] __basicsize__: int - __dict__: Dict[str, Any] + __dict__: dict[str, Any] __dictoffset__: int __flags__: int __itemsize__: int __module__: str - __mro__: Tuple[type, ...] + __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: ... + 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 __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]: ... + def __subclasses__(self: _TT) -> list[_TT]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. - def mro(self) -> List[type]: ... + def mro(self) -> list[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... def __subclasscheck__(self, subclass: type) -> bool: ... @@ -135,9 +127,9 @@ class super(object): class int: @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | bytearray, base: int) -> Self: ... @property def real(self) -> int: ... @property @@ -155,7 +147,7 @@ class 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 __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: ... @@ -163,7 +155,7 @@ class 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]: ... + def __rdivmod__(self, x: int) -> tuple[int, int]: ... @overload def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... @overload @@ -183,14 +175,13 @@ class int: def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[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: ... @@ -199,8 +190,8 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... + def __new__(cls: type[Self], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> Self: ... + def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod @@ -217,7 +208,7 @@ class 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 __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 @@ -228,9 +219,9 @@ class 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 __rdivmod__(self, x: float) -> tuple[float, float]: ... def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... @@ -240,7 +231,6 @@ 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: ... @@ -249,9 +239,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | _SupportsIndex) -> Self: ... @property def real(self) -> float: ... @property @@ -273,7 +263,6 @@ class complex: 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: ... @@ -293,7 +282,7 @@ class unicode(basestring, Sequence[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: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> 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: ... @@ -313,21 +302,21 @@ class unicode(basestring, Sequence[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 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: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... + def rpartition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[unicode]: ... + def startswith(self, __prefix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... + def translate(self, table: dict[int, Any] | unicode) -> unicode: ... def upper(self) -> unicode: ... def zfill(self, width: int) -> unicode: ... @overload @@ -349,12 +338,10 @@ class unicode(basestring, Sequence[unicode]): # The argument type is incompatible with Sequence def __contains__(self, s: 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]: ... + def __getnewargs__(self) -> tuple[unicode]: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... @@ -366,7 +353,7 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -387,35 +374,35 @@ class str(Sequence[str], basestring): @overload def lstrip(self, __chars: unicode) -> unicode: ... @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def partition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def partition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + 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: int | None = ..., __end: int | None = ...) -> int: ... def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def rpartition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rpartition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rpartition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + 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: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def split(self, sep: str | None = ..., 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: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[str]: ... + def startswith(self, __prefix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -440,10 +427,8 @@ class str(Sequence[str], basestring): 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 __getnewargs__(self) -> tuple[str]: ... def __getslice__(self, start: int, stop: int) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -465,7 +450,7 @@ class bytearray(MutableSequence[int], ByteString): 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: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: str | Iterable[int]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... @@ -482,17 +467,17 @@ class bytearray(MutableSequence[int], ByteString): def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, 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: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... + def startswith(self, __prefix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... @@ -503,8 +488,6 @@ class bytearray(MutableSequence[int], ByteString): 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 @@ -534,9 +517,9 @@ class bytearray(MutableSequence[int], ByteString): class memoryview(Sized, Container[str]): format: str itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None + shape: tuple[int, ...] | None + strides: tuple[int, ...] | None + suboffsets: tuple[int, ...] | None readonly: bool ndim: int def __init__(self, obj: ReadableBuffer) -> None: ... @@ -552,11 +535,11 @@ class memoryview(Sized, Container[str]): @overload def __setitem__(self, i: int, o: int) -> None: ... def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... + def tolist(self) -> list[int]: ... @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, x: bool) -> bool: ... @overload @@ -581,7 +564,7 @@ class bool(int): def __rxor__(self, x: bool) -> bool: ... @overload def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... + def __getnewargs__(self) -> tuple[int]: ... class slice(object): start: Any @@ -592,27 +575,27 @@ class slice(object): @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... + 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 __new__(cls: type[Self], iterable: Iterable[_T_co] = ...) -> Self: ... 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 __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: ... + 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, ...]: ... + 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 __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: ... @@ -638,30 +621,29 @@ class list(MutableSequence[_T], Generic[_T]): 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]: ... + 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: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... + 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 __add__(self, x: list[_T]) -> list[_T]: ... + def __iadd__(self: Self, x: Iterable[_T]) -> Self: ... + 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: ... + 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 @@ -671,76 +653,74 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @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 __init__(self, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def has_key(self, k: _KT) -> bool: ... def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... + 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: ... + 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 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]: ... + def fromkeys(cls, __iterable: Iterable[_T]) -> dict[_T, Any]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... def __len__(self) -> int: ... def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... 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 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(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(self, s: Iterable[_T]) -> set[_T]: ... def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... + 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[_T | _S]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... + def __and__(self, s: AbstractSet[object]) -> set[_T]: ... + def __iand__(self: Self, s: AbstractSet[object]) -> Self: ... + def __or__(self, s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ior__(self: Self, s: AbstractSet[_T]) -> Self: ... @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __sub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... + def __sub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __isub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __isub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... + def __isub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ixor__(self: Self, s: AbstractSet[_T]) -> Self: ... def __le__(self, s: AbstractSet[object]) -> bool: ... def __lt__(self, s: AbstractSet[object]) -> bool: ... def __ge__(self, s: AbstractSet[object]) -> bool: ... @@ -749,31 +729,30 @@ class set(MutableSet[_T], Generic[_T]): 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 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 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[_T_co | _S]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... + def __and__(self, s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> frozenset[_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]): +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]: ... + def __iter__(self: Self) -> Self: ... + def next(self) -> tuple[int, _T]: ... class xrange(Sized, Iterable[int], Reversible[int]): @overload @@ -823,29 +802,29 @@ def cmp(__x: Any, __y: Any) -> int: ... _N1 = TypeVar("_N1", bool, int, float, complex) -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +def coerce(__x: _N1, __y: _N1) -> tuple[_N1, _N1]: ... def compile(source: 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]: ... +def dir(__o: object = ...) -> list[str]: ... _N2 = TypeVar("_N2", int, float) -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def divmod(__x: _N2, __y: _N2) -> tuple[_N2, _N2]: ... def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... + __source: Text | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... ) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... +def execfile(__filename: str, __globals: dict[str, Any] | None = ..., __locals: dict[str, Any] | None = ...) -> 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[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: None, __iterable: tuple[_T | None, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: Callable[[_T], Any], __iterable: tuple[_T, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... +def filter(__function: None, __iterable: Iterable[_T | None]) -> list[_T]: ... @overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> list[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... @@ -863,7 +842,7 @@ def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: .. def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... @overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... +def globals() -> dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... def hex(__number: int | _SupportsIndex) -> str: ... @@ -876,20 +855,20 @@ def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... +def isinstance(__obj: object, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... +def issubclass(__cls: type, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... +def locals() -> dict[str, Any]: ... @overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +def map(__func: None, __iter1: Iterable[_T1]) -> list[_T1]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def map( __func: None, @@ -898,7 +877,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def map( __func: None, @@ -909,15 +888,15 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... @overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +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]: ... +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]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4], _S], @@ -925,7 +904,7 @@ def map( __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], @@ -934,7 +913,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[..., _S], @@ -945,7 +924,7 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[_S]: ... +) -> list[_S]: ... @overload def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... @overload @@ -985,7 +964,7 @@ 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 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: ... @@ -1008,27 +987,27 @@ 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: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... +) -> list[_T]: ... @overload def sum(__iterable: Iterable[_T]) -> _T | int: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... +def vars(__object: Any = ...) -> dict[str, Any]: ... @overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +def zip(__iter1: Iterable[_T1]) -> list[tuple[_T1]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> 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]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def zip( __iter1: Iterable[Any], @@ -1038,7 +1017,7 @@ def zip( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... def __import__( name: Text, globals: Mapping[str, Any] | None = ..., @@ -1066,13 +1045,11 @@ class buffer(Sized): def __mul__(self, x: int) -> str: ... class BaseException(object): - args: Tuple[Any, ...] + 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, ...]: ... + def __getslice__(self, start: int, stop: int) -> tuple[Any, ...]: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1181,7 +1158,7 @@ class file(BinaryIO): 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 readlines(self, hint: int = ...) -> list[str]: ... def write(self, data: str) -> int: ... def writelines(self, data: Iterable[str]) -> None: ... def truncate(self, pos: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/__future__.pyi b/mypy/typeshed/stdlib/@python2/__future__.pyi index 8f5ff06ac080..df05b0d7c2de 100644 --- a/mypy/typeshed/stdlib/@python2/__future__.pyi +++ b/mypy/typeshed/stdlib/@python2/__future__.pyi @@ -1,5 +1,4 @@ import sys -from typing import List class _Feature: def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... @@ -14,4 +13,4 @@ nested_scopes: _Feature print_function: _Feature unicode_literals: _Feature with_statement: _Feature -all_feature_names: List[str] # undocumented +all_feature_names: list[str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/_ast.pyi b/mypy/typeshed/stdlib/@python2/_ast.pyi index 05cbc70c41d2..c81dc09abb57 100644 --- a/mypy/typeshed/stdlib/@python2/_ast.pyi +++ b/mypy/typeshed/stdlib/@python2/_ast.pyi @@ -1,27 +1,25 @@ -import typing - __version__: str PyCF_ONLY_AST: int _identifier = str class AST: - _attributes: typing.Tuple[str, ...] - _fields: typing.Tuple[str, ...] + _attributes: tuple[str, ...] + _fields: tuple[str, ...] def __init__(self, *args, **kwargs) -> None: ... class mod(AST): ... class Module(mod): - body: typing.List[stmt] + body: list[stmt] class Interactive(mod): - body: typing.List[stmt] + body: list[stmt] class Expression(mod): body: expr class Suite(mod): - body: typing.List[stmt] + body: list[stmt] class stmt(AST): lineno: int @@ -30,23 +28,23 @@ class stmt(AST): class FunctionDef(stmt): name: _identifier args: arguments - body: typing.List[stmt] - decorator_list: typing.List[expr] + body: list[stmt] + decorator_list: list[expr] class ClassDef(stmt): name: _identifier - bases: typing.List[expr] - body: typing.List[stmt] - decorator_list: typing.List[expr] + bases: list[expr] + body: list[stmt] + decorator_list: list[expr] class Return(stmt): value: expr | None class Delete(stmt): - targets: typing.List[expr] + targets: list[expr] class Assign(stmt): - targets: typing.List[expr] + targets: list[expr] value: expr class AugAssign(stmt): @@ -56,29 +54,29 @@ class AugAssign(stmt): class Print(stmt): dest: expr | None - values: typing.List[expr] + values: list[expr] nl: bool class For(stmt): target: expr iter: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class While(stmt): test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class If(stmt): test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class With(stmt): context_expr: expr optional_vars: expr | None - body: typing.List[stmt] + body: list[stmt] class Raise(stmt): type: expr | None @@ -86,24 +84,24 @@ class Raise(stmt): tback: expr | None class TryExcept(stmt): - body: typing.List[stmt] - handlers: typing.List[ExceptHandler] - orelse: typing.List[stmt] + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] class TryFinally(stmt): - body: typing.List[stmt] - finalbody: typing.List[stmt] + body: list[stmt] + finalbody: list[stmt] class Assert(stmt): test: expr msg: expr | None class Import(stmt): - names: typing.List[alias] + names: list[alias] class ImportFrom(stmt): module: _identifier | None - names: typing.List[alias] + names: list[alias] level: int | None class Exec(stmt): @@ -112,7 +110,7 @@ class Exec(stmt): locals: expr | None class Global(stmt): - names: typing.List[_identifier] + names: list[_identifier] class Expr(stmt): value: expr @@ -130,7 +128,7 @@ class Slice(slice): step: expr | None class ExtSlice(slice): - dims: typing.List[slice] + dims: list[slice] class Index(slice): value: expr @@ -143,7 +141,7 @@ class expr(AST): class BoolOp(expr): op: boolop - values: typing.List[expr] + values: list[expr] class BinOp(expr): left: expr @@ -164,41 +162,41 @@ class IfExp(expr): orelse: expr class Dict(expr): - keys: typing.List[expr] - values: typing.List[expr] + keys: list[expr] + values: list[expr] class Set(expr): - elts: typing.List[expr] + elts: list[expr] class ListComp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class SetComp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class DictComp(expr): key: expr value: expr - generators: typing.List[comprehension] + generators: list[comprehension] class GeneratorExp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class Yield(expr): value: expr | None class Compare(expr): left: expr - ops: typing.List[cmpop] - comparators: typing.List[expr] + ops: list[cmpop] + comparators: list[expr] class Call(expr): func: expr - args: typing.List[expr] - keywords: typing.List[keyword] + args: list[expr] + keywords: list[keyword] starargs: expr | None kwargs: expr | None @@ -226,11 +224,11 @@ class Name(expr): ctx: expr_context class List(expr): - elts: typing.List[expr] + elts: list[expr] ctx: expr_context class Tuple(expr): - elts: typing.List[expr] + elts: list[expr] ctx: expr_context class expr_context(AST): ... @@ -276,22 +274,22 @@ class NotIn(cmpop): ... class comprehension(AST): target: expr iter: expr - ifs: typing.List[expr] + ifs: list[expr] class excepthandler(AST): ... class ExceptHandler(excepthandler): type: expr | None name: expr | None - body: typing.List[stmt] + body: list[stmt] lineno: int col_offset: int class arguments(AST): - args: typing.List[expr] + args: list[expr] vararg: _identifier | None kwarg: _identifier | None - defaults: typing.List[expr] + defaults: list[expr] class keyword(AST): arg: _identifier diff --git a/mypy/typeshed/stdlib/@python2/_codecs.pyi b/mypy/typeshed/stdlib/@python2/_codecs.pyi index 83601f6621bb..fa6922207c25 100644 --- a/mypy/typeshed/stdlib/@python2/_codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/_codecs.pyi @@ -1,9 +1,9 @@ import codecs import sys -from typing import Any, Callable, Dict, Text, Tuple, Union +from typing import Any, Callable, Text, Union # For convenience: -_Handler = Callable[[Exception], Tuple[Text, int]] +_Handler = Callable[[Exception], tuple[Text, int]] _String = Union[bytes, str] _Errors = Union[str, Text, None] _Decodable = Union[bytes, Text] @@ -13,7 +13,7 @@ _Encodable = Union[bytes, Text] class _EncodingMap(object): def size(self) -> int: ... -_MapT = Union[Dict[int, int], _EncodingMap] +_MapT = Union[dict[int, int], _EncodingMap] def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str | Text, __handler: _Handler) -> None: ... @@ -22,45 +22,45 @@ def lookup_error(__name: str | Text) -> _Handler: ... def decode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... def encode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... def charmap_build(__map: Text) -> _MapT: ... -def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[Text, int]: ... -def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[bytes, int]: ... -def escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> tuple[Text, int]: ... +def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> tuple[Text, int]: ... +def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> tuple[bytes, int]: ... +def escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[str, int]: ... +def escape_encode(__data: bytes, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> tuple[Text, int]: ... +def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> tuple[bytes, int]: ... def utf_16_ex_decode( __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +) -> 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]: ... +) -> 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]: ... + def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... + def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/_collections.pyi b/mypy/typeshed/stdlib/@python2/_collections.pyi index 22ada07d0f24..6f0ee3f8740b 100644 --- a/mypy/typeshed/stdlib/@python2/_collections.pyi +++ b/mypy/typeshed/stdlib/@python2/_collections.pyi @@ -1,16 +1,16 @@ -from typing import Any, Callable, Dict, Generic, Iterator, TypeVar +from _typeshed import Self +from typing import Any, Callable, Generic, Iterator, TypeVar _K = TypeVar("_K") _V = TypeVar("_V") _T = TypeVar("_T") -_T2 = TypeVar("_T2") -class defaultdict(Dict[_K, _V]): +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: ... + def __copy__(self: Self) -> Self: ... + def copy(self: Self) -> Self: ... class deque(Generic[_T]): maxlen: int | None @@ -29,7 +29,7 @@ class deque(Generic[_T]): def __contains__(self, o: Any) -> bool: ... def __copy__(self) -> deque[_T]: ... def __getitem__(self, i: int) -> _T: ... - def __iadd__(self, other: deque[_T2]) -> deque[_T | _T2]: ... + def __iadd__(self: Self, other: deque[_T]) -> Self: ... def __iter__(self) -> Iterator[_T]: ... def __len__(self) -> int: ... def __reversed__(self) -> Iterator[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/_csv.pyi b/mypy/typeshed/stdlib/@python2/_csv.pyi index ebe44bab67d9..e01ccc19cb19 100644 --- a/mypy/typeshed/stdlib/@python2/_csv.pyi +++ b/mypy/typeshed/stdlib/@python2/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Sequence, Text, Type, Union +from typing import Any, Iterable, Iterator, Protocol, Sequence, Text, Union QUOTE_ALL: int QUOTE_MINIMAL: int @@ -18,12 +18,12 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] +_DialectLike = Union[str, Dialect, type[Dialect]] -class _reader(Iterator[List[str]]): +class _reader(Iterator[list[str]]): dialect: Dialect line_num: int - def next(self) -> List[str]: ... + def next(self) -> list[str]: ... class _writer: dialect: Dialect @@ -38,5 +38,5 @@ def reader(csvfile: Iterable[Text], dialect: _DialectLike = ..., **fmtparams: An 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 list_dialects() -> list[str]: ... def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/_curses.pyi b/mypy/typeshed/stdlib/@python2/_curses.pyi index 32c1f761ac9e..4b2941e74753 100644 --- a/mypy/typeshed/stdlib/@python2/_curses.pyi +++ b/mypy/typeshed/stdlib/@python2/_curses.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, BinaryIO, Tuple, Union, overload +from typing import IO, Any, BinaryIO, Union, overload _chtype = Union[str, bytes, int] @@ -263,7 +263,7 @@ 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_content(__color_number: int) -> tuple[int, int, int]: ... # Changed in Python 3.8.8 and 3.9.2 def color_pair(__color_number: int) -> int: ... @@ -278,8 +278,8 @@ 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 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: ... @@ -297,7 +297,7 @@ def killchar() -> bytes: ... def longname() -> bytes: ... def meta(__yes: bool) -> None: ... def mouseinterval(__interval: int) -> None: ... -def mousemask(__newmask: int) -> Tuple[int, int]: ... +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: ... @@ -307,7 +307,7 @@ def noecho() -> None: ... def nonl() -> None: ... def noqiflush() -> None: ... def noraw() -> None: ... -def pair_content(__pair_number: int) -> Tuple[int, int]: ... +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: ... @@ -405,8 +405,8 @@ class _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]: ... + def getbegyx(self) -> tuple[int, int]: ... + def getbkgd(self) -> tuple[int, int]: ... @overload def getch(self) -> int: ... @overload @@ -415,8 +415,8 @@ class _CursesWindow: 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]: ... + def getmaxyx(self) -> tuple[int, int]: ... + def getparyx(self) -> tuple[int, int]: ... @overload def getstr(self) -> _chtype: ... @overload @@ -425,7 +425,7 @@ class _CursesWindow: 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]: ... + def getyx(self) -> tuple[int, int]: ... @overload def hline(self, ch: _chtype, n: int) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi index e45a1b5c4a89..c03c52a7907c 100644 --- a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi @@ -1,19 +1,36 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, Text # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") -__all__: List[str] +__all__ = [ + "activeCount", + "active_count", + "Condition", + "currentThread", + "current_thread", + "enumerate", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Timer", + "setprofile", + "settrace", + "local", + "stack_size", +] def active_count() -> int: ... def activeCount() -> int: ... def current_thread() -> Thread: ... def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... +def enumerate() -> list[Thread]: ... def settrace(func: _TF) -> None: ... def setprofile(func: _PF | None) -> None: ... def stack_size(size: int = ...) -> int: ... @@ -53,7 +70,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -63,7 +80,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -74,7 +91,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -86,7 +103,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def __enter__(self, blocking: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_functools.pyi b/mypy/typeshed/stdlib/@python2/_functools.pyi index e68398238f9b..d695e76994c9 100644 --- a/mypy/typeshed/stdlib/@python2/_functools.pyi +++ b/mypy/typeshed/stdlib/@python2/_functools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, overload +from typing import Any, Callable, Iterable, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") @@ -10,7 +10,7 @@ def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T class partial(object): func: Callable[..., Any] - args: Tuple[Any, ...] - keywords: Dict[str, 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/_heapq.pyi b/mypy/typeshed/stdlib/@python2/_heapq.pyi index 08a8add08e9a..a2a38dc9c3ed 100644 --- a/mypy/typeshed/stdlib/@python2/_heapq.pyi +++ b/mypy/typeshed/stdlib/@python2/_heapq.pyi @@ -1,11 +1,11 @@ -from typing import Any, Callable, Iterable, List, TypeVar +from typing import Any, Callable, Iterable, TypeVar _T = TypeVar("_T") -def heapify(__heap: List[Any]) -> None: ... -def heappop(__heap: List[_T]) -> _T: ... -def heappush(__heap: List[_T], __item: _T) -> None: ... -def heappushpop(__heap: List[_T], __item: _T) -> _T: ... -def heapreplace(__heap: List[_T], __item: _T) -> _T: ... -def nlargest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... -def nsmallest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... +def heapify(__heap: list[Any]) -> None: ... +def heappop(__heap: list[_T]) -> _T: ... +def heappush(__heap: list[_T], __item: _T) -> None: ... +def heappushpop(__heap: list[_T], __item: _T) -> _T: ... +def heapreplace(__heap: list[_T], __item: _T) -> _T: ... +def nlargest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> list[_T]: ... +def nsmallest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> list[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/_hotshot.pyi b/mypy/typeshed/stdlib/@python2/_hotshot.pyi index b048f6fb83d5..aa188a2b4fae 100644 --- a/mypy/typeshed/stdlib/@python2/_hotshot.pyi +++ b/mypy/typeshed/stdlib/@python2/_hotshot.pyi @@ -1,9 +1,9 @@ -from typing import Any, Tuple +from typing import Any def coverage(a: str) -> Any: ... def logreader(a: str) -> LogReaderType: ... def profiler(a: str, *args, **kwargs) -> Any: ... -def resolution() -> Tuple[Any, ...]: ... +def resolution() -> tuple[Any, ...]: ... class LogReaderType(object): def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi index fedbbe137940..3671bbd2177d 100644 --- a/mypy/typeshed/stdlib/@python2/_io.pyi +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from mmap import mmap -from typing import IO, Any, BinaryIO, Iterable, List, Text, TextIO, Tuple, Type, TypeVar, Union +from typing import IO, Any, BinaryIO, Iterable, Text, TextIO, Union _bytearray_like = Union[bytearray, mmap] @@ -11,8 +11,6 @@ class BlockingIOError(IOError): class UnsupportedOperation(ValueError, IOError): ... -_T = TypeVar("_T") - class _IOBase(BinaryIO): @property def closed(self) -> bool: ... @@ -32,13 +30,13 @@ class _IOBase(BinaryIO): def truncate(self, size: int | None = ...) -> int: ... def writable(self) -> bool: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... + def __exit__(self, t: type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... + def __iter__(self: Self) -> Self: ... # 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 readline(self, limit: int | None = ...) -> 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. @@ -79,8 +77,8 @@ class BufferedWriter(_BufferedIOBase): class BytesIO(_BufferedIOBase): def __init__(self, initial_bytes: bytes = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... + 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[]. @@ -106,8 +104,8 @@ class IncrementalNewlineDecoder(object): newlines: 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 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. @@ -140,14 +138,14 @@ class _TextIOBase(TextIO): def write(self, pbuf: unicode) -> int: ... def writelines(self, lines: Iterable[unicode]) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... + def __exit__(self, t: type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... + def __iter__(self: Self) -> Self: ... class StringIO(_TextIOBase): line_buffering: bool def __init__(self, initial_value: unicode | None = ..., newline: unicode | None = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... + 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[]. diff --git a/mypy/typeshed/stdlib/@python2/_json.pyi b/mypy/typeshed/stdlib/@python2/_json.pyi index a9868b3e60fd..57c70e80564e 100644 --- a/mypy/typeshed/stdlib/@python2/_json.pyi +++ b/mypy/typeshed/stdlib/@python2/_json.pyi @@ -1,7 +1,7 @@ -from typing import Any, Tuple +from typing import Any def encode_basestring_ascii(*args, **kwargs) -> str: ... -def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... +def scanstring(a, b, *args, **kwargs) -> tuple[Any, ...]: ... class Encoder(object): ... class Scanner(object): ... diff --git a/mypy/typeshed/stdlib/@python2/_markupbase.pyi b/mypy/typeshed/stdlib/@python2/_markupbase.pyi index d8bc79f34e8c..368d32bd5b4c 100644 --- a/mypy/typeshed/stdlib/@python2/_markupbase.pyi +++ b/mypy/typeshed/stdlib/@python2/_markupbase.pyi @@ -1,8 +1,6 @@ -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 getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_msi.pyi b/mypy/typeshed/stdlib/@python2/_msi.pyi index a1030a66160f..754febe68da9 100644 --- a/mypy/typeshed/stdlib/@python2/_msi.pyi +++ b/mypy/typeshed/stdlib/@python2/_msi.pyi @@ -1,5 +1,4 @@ import sys -from typing import List if sys.platform == "win32": @@ -44,6 +43,6 @@ if sys.platform == "win32": __new__: None # type: ignore __init__: None # type: ignore def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: List[str]) -> None: ... + def FCICreate(cabname: str, files: list[str]) -> None: ... def OpenDatabase(name: str, flags: int) -> _Database: ... def CreateRecord(count: int) -> _Record: ... diff --git a/mypy/typeshed/stdlib/@python2/_osx_support.pyi b/mypy/typeshed/stdlib/@python2/_osx_support.pyi index 1b890d8d8a0a..27a4a019de58 100644 --- a/mypy/typeshed/stdlib/@python2/_osx_support.pyi +++ b/mypy/typeshed/stdlib/@python2/_osx_support.pyi @@ -1,13 +1,13 @@ -from typing import Dict, Iterable, List, Sequence, Tuple, TypeVar +from typing import Iterable, Sequence, TypeVar _T = TypeVar("_T") _K = TypeVar("_K") _V = TypeVar("_V") -__all__: List[str] +__all__ = ["compiler_fixup", "customize_config_vars", "customize_compiler", "get_platform_osx"] -_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented -_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented +_UNIVERSAL_CONFIG_VARS: tuple[str, ...] # undocumented +_COMPILER_CONFIG_VARS: tuple[str, ...] # undocumented _INITPRE: str # undocumented def _find_executable(executable: str, path: str | None = ...) -> str | None: ... # undocumented @@ -17,17 +17,17 @@ def _find_build_tool(toolname: str) -> str: ... # undocumented _SYSTEM_VERSION: str | None # 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 _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 _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[str | _T, str | _K, str | _V]: ... + _config_vars: dict[str, str], osname: _T, release: _K, machine: _V +) -> tuple[str | _T, str | _K, str | _V]: ... diff --git a/mypy/typeshed/stdlib/@python2/_random.pyi b/mypy/typeshed/stdlib/@python2/_random.pyi index 7c2dd61af49f..8bd1afad48cb 100644 --- a/mypy/typeshed/stdlib/@python2/_random.pyi +++ b/mypy/typeshed/stdlib/@python2/_random.pyi @@ -1,7 +1,5 @@ -from typing import Tuple - # Actually Tuple[(int,) * 625] -_State = Tuple[int, ...] +_State = tuple[int, ...] class Random(object): def __init__(self, seed: object = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_socket.pyi b/mypy/typeshed/stdlib/@python2/_socket.pyi index c505384c5226..d081494be68f 100644 --- a/mypy/typeshed/stdlib/@python2/_socket.pyi +++ b/mypy/typeshed/stdlib/@python2/_socket.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Tuple, overload +from typing import IO, Any, overload AF_APPLETALK: int AF_ASH: int @@ -252,29 +252,29 @@ class SocketType(object): 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 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 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 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(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: ... + def sendto(self, data: str, address: tuple[Any, ...]) -> int: ... @overload - def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... + 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: int | str) -> None: ... def settimeout(self, value: float | None) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_sre.pyi b/mypy/typeshed/stdlib/@python2/_sre.pyi index 3bacc097451e..ba61c56344ac 100644 --- a/mypy/typeshed/stdlib/@python2/_sre.pyi +++ b/mypy/typeshed/stdlib/@python2/_sre.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple, overload +from typing import Any, Iterable, Mapping, Sequence, overload CODESIZE: int MAGIC: int @@ -13,11 +13,11 @@ class SRE_Match(object): def group(self) -> str: ... @overload def group(self, group: int = ...) -> str | None: ... - def groupdict(self) -> Dict[int, str | None]: ... - def groups(self) -> Tuple[str | None, ...]: ... - def span(self) -> Tuple[int, int]: ... + def groupdict(self) -> dict[int, str | None]: ... + def groups(self) -> tuple[str | None, ...]: ... + def span(self) -> tuple[int, int]: ... @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented class SRE_Scanner(object): pattern: str @@ -30,19 +30,19 @@ class SRE_Pattern(object): groups: int groupindex: Mapping[str, int] indexgroup: Sequence[int] - def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Tuple[Any, ...] | str]: ... - def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Tuple[Any, ...] | str]: ... + def findall(self, source: str, pos: int = ..., endpos: int = ...) -> list[tuple[Any, ...] | str]: ... + def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[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[str | None]: ... - def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + def split(self, source: str, maxsplit: int = ...) -> list[str | None]: ... + 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], + code: list[int], groups: int = ..., groupindex: Mapping[str, int] = ..., indexgroup: Sequence[int] = ..., diff --git a/mypy/typeshed/stdlib/@python2/_struct.pyi b/mypy/typeshed/stdlib/@python2/_struct.pyi index 316307eaabca..89357ab0bbc8 100644 --- a/mypy/typeshed/stdlib/@python2/_struct.pyi +++ b/mypy/typeshed/stdlib/@python2/_struct.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Tuple +from typing import Any, AnyStr class error(Exception): ... @@ -8,12 +8,12 @@ class Struct(object): 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 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, ...]: ... +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 index 5b2370449c31..ca21f8d5e521 100644 --- a/mypy/typeshed/stdlib/@python2/_symtable.pyi +++ b/mypy/typeshed/stdlib/@python2/_symtable.pyi @@ -1,5 +1,3 @@ -from typing import Dict, List - CELL: int DEF_BOUND: int DEF_FREE: int @@ -25,13 +23,13 @@ USE: int class _symtable_entry(object): ... class symtable(object): - children: List[_symtable_entry] + children: list[_symtable_entry] id: int lineno: int name: str nested: int optimized: int - symbols: Dict[str, int] + symbols: dict[str, int] type: int - varnames: List[str] + varnames: list[str] def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_thread.pyi b/mypy/typeshed/stdlib/@python2/_thread.pyi index 562ece61e042..0470ebd4830f 100644 --- a/mypy/typeshed/stdlib/@python2/_thread.pyi +++ b/mypy/typeshed/stdlib/@python2/_thread.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Any, Callable, Dict, NoReturn, Tuple, Type +from typing import Any, Callable, NoReturn error = RuntimeError @@ -13,10 +13,10 @@ class LockType: def locked(self) -> bool: ... def __enter__(self) -> bool: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> int: ... +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: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi index ca698e29ae8a..0d1dc3866b56 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi @@ -14,7 +14,7 @@ import array import mmap -from typing import Any, Container, Iterable, Protocol, Text, Tuple, TypeVar, Union +from typing import Any, Container, Iterable, Protocol, Text, TypeVar, Union from typing_extensions import Literal, final _KT = TypeVar("_KT") @@ -48,7 +48,7 @@ class SupportsRDivMod(Protocol[_T_contra, _T_co]): class SupportsItems(Protocol[_KT_co, _VT_co]): # We want dictionaries to support this on Python 2. - def items(self) -> Iterable[Tuple[_KT_co, _VT_co]]: ... + def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi index a1f10443a6f0..6dc2b5cc021d 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi @@ -4,28 +4,28 @@ # file. They are provided for type checking purposes. from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Text, Tuple +from typing import Any, Callable, Iterable, Optional, Protocol, Text class StartResponse(Protocol): def __call__( - self, status: str, headers: List[Tuple[str, str]], exc_info: _OptExcInfo | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... ) -> Callable[[bytes], Any]: ... -WSGIEnvironment = Dict[Text, 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 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: ... + def writelines(self, seq: list[str]) -> None: ... class _Readable(Protocol): def read(self, size: int = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/_warnings.pyi b/mypy/typeshed/stdlib/@python2/_warnings.pyi index ccc51fecb8da..8f531c47af55 100644 --- a/mypy/typeshed/stdlib/@python2/_warnings.pyi +++ b/mypy/typeshed/stdlib/@python2/_warnings.pyi @@ -1,23 +1,23 @@ -from typing import Any, Dict, List, Tuple, Type, overload +from typing import Any, overload default_action: str -once_registry: Dict[Any, Any] +once_registry: dict[Any, Any] -filters: List[Tuple[Any, ...]] +filters: list[tuple[Any, ...]] @overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ...) -> None: ... +def warn(message: str, category: type[Warning] | None = ..., stacklevel: int = ...) -> None: ... @overload def warn(message: Warning, category: Any = ..., stacklevel: int = ...) -> None: ... @overload def warn_explicit( message: str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., + module_globals: dict[str, Any] | None = ..., ) -> None: ... @overload def warn_explicit( @@ -26,6 +26,6 @@ def warn_explicit( filename: str, lineno: int, module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., + module_globals: dict[str, Any] | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakref.pyi b/mypy/typeshed/stdlib/@python2/_weakref.pyi index a283d4cb60d3..9a37de3174b6 100644 --- a/mypy/typeshed/stdlib/@python2/_weakref.pyi +++ b/mypy/typeshed/stdlib/@python2/_weakref.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Generic, List, TypeVar, overload +from typing import Any, Callable, Generic, TypeVar, overload _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") @@ -17,7 +17,7 @@ class ReferenceType(Generic[_T]): ref = ReferenceType def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> List[Any]: ... +def getweakrefs(object: Any) -> list[Any]: ... @overload def proxy(object: _C, callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakrefset.pyi b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi index f2cde7d67e52..0d2c7fc42f22 100644 --- a/mypy/typeshed/stdlib/@python2/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi @@ -1,30 +1,30 @@ +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) class WeakSet(MutableSet[_T], Generic[_T]): def __init__(self, data: Iterable[_T] | None = ...) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... + def copy(self: Self) -> Self: ... 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[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __ior__(self: Self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] + def difference(self: Self, other: Iterable[_T]) -> Self: ... + def __sub__(self: Self, other: Iterable[Any]) -> Self: ... + def difference_update(self, other: Iterable[Any]) -> None: ... + def __isub__(self: Self, other: Iterable[Any]) -> Self: ... + def intersection(self: Self, other: Iterable[_T]) -> Self: ... + def __and__(self: Self, other: Iterable[Any]) -> Self: ... + def intersection_update(self, other: Iterable[Any]) -> None: ... + def __iand__(self: Self, other: Iterable[Any]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... @@ -34,8 +34,8 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __eq__(self, other: object) -> bool: ... def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... - def __ixor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def symmetric_difference_update(self, other: Iterable[_T]) -> None: ... + def __ixor__(self: Self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_winreg.pyi b/mypy/typeshed/stdlib/@python2/_winreg.pyi index 5b8ec1130ca1..e432d883e4d5 100644 --- a/mypy/typeshed/stdlib/@python2/_winreg.pyi +++ b/mypy/typeshed/stdlib/@python2/_winreg.pyi @@ -1,6 +1,7 @@ import sys +from _typeshed import Self from types import TracebackType -from typing import Any, Tuple, Type, Union +from typing import Any, Union if sys.platform == "win32": _KeyType = Union[HKEYType, int] @@ -12,15 +13,15 @@ if sys.platform == "win32": 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 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 QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... - def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... + 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( @@ -88,9 +89,9 @@ if sys.platform == "win32": class HKEYType: def __bool__(self) -> bool: ... def __int__(self) -> int: ... - def __enter__(self) -> HKEYType: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def Close(self) -> None: ... def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/abc.pyi b/mypy/typeshed/stdlib/@python2/abc.pyi index ac14246d44a5..49ec775f91e8 100644 --- a/mypy/typeshed/stdlib/@python2/abc.pyi +++ b/mypy/typeshed/stdlib/@python2/abc.pyi @@ -1,6 +1,6 @@ import _weakrefset from _typeshed import SupportsWrite -from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar +from typing import Any, Callable, TypeVar _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) @@ -15,11 +15,11 @@ class ABCMeta(type): _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[str, Any]) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> None: ... def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... def _dump_registry(cls: ABCMeta, file: SupportsWrite[Any] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... + def register(cls: ABCMeta, subclass: type[Any]) -> None: ... # TODO: The real abc.abstractproperty inherits from "property". class abstractproperty(object): diff --git a/mypy/typeshed/stdlib/@python2/aifc.pyi b/mypy/typeshed/stdlib/@python2/aifc.pyi index 42f20b7466a1..b8049e857304 100644 --- a/mypy/typeshed/stdlib/@python2/aifc.pyi +++ b/mypy/typeshed/stdlib/@python2/aifc.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, List, NamedTuple, Text, Tuple, Union, overload +from typing import IO, Any, NamedTuple, Text, Union, overload from typing_extensions import Literal class Error(Exception): ... @@ -12,7 +12,7 @@ class _aifc_params(NamedTuple): compname: bytes _File = Union[Text, IO[bytes]] -_Marker = Tuple[int, int, bytes] +_Marker = tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... @@ -28,7 +28,7 @@ class Aifc_read: def getcomptype(self) -> bytes: ... def getcompname(self) -> bytes: ... def getparams(self) -> _aifc_params: ... - def getmarkers(self) -> List[_Marker] | None: ... + def getmarkers(self) -> list[_Marker] | None: ... def getmark(self, id: int) -> _Marker: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes: ... @@ -50,11 +50,11 @@ class Aifc_write: 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 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) -> List[_Marker] | None: ... + def getmarkers(self) -> list[_Marker] | None: ... def tell(self) -> int: ... def writeframesraw(self, data: Any) -> None: ... # Actual type for data is Buffer Protocol def writeframes(self, data: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/argparse.pyi b/mypy/typeshed/stdlib/@python2/argparse.pyi index 4d77f6582c5f..e82a8c621e40 100644 --- a/mypy/typeshed/stdlib/@python2/argparse.pyi +++ b/mypy/typeshed/stdlib/@python2/argparse.pyi @@ -1,22 +1,4 @@ -from typing import ( - IO, - Any, - Callable, - Dict, - Generator, - Iterable, - List, - NoReturn, - Pattern, - Protocol, - Sequence, - Text, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, Union, overload _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) @@ -39,8 +21,8 @@ class ArgumentError(Exception): # undocumented class _AttributeHolder: - def _get_kwargs(self) -> List[Tuple[str, Any]]: ... - def _get_args(self) -> List[Any]: ... + def _get_kwargs(self) -> list[tuple[str, Any]]: ... + def _get_args(self) -> list[Any]: ... # undocumented class _ActionsContainer: @@ -49,14 +31,14 @@ class _ActionsContainer: argument_default: Any conflict_handler: _Text - _registries: Dict[_Text, Dict[Any, Any]] - _actions: List[Action] - _option_string_actions: Dict[_Text, Action] - _action_groups: List[_ArgumentGroup] - _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] - _defaults: Dict[str, Any] + _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] + _has_negative_number_optionals: list[bool] def __init__(self, description: Text | None, 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: ... @@ -65,7 +47,7 @@ class _ActionsContainer: def add_argument( self, *name_or_flags: Text, - action: Text | Type[Action] = ..., + action: Text | type[Action] = ..., nargs: int | Text = ..., const: Any = ..., default: Any = ..., @@ -73,7 +55,7 @@ class _ActionsContainer: choices: Iterable[_T] = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., dest: Text | None = ..., version: Text = ..., **kwargs: Any, @@ -83,13 +65,13 @@ class _ActionsContainer: def _add_action(self, action: _ActionT) -> _ActionT: ... def _remove_action(self, action: Action) -> None: ... def _add_container_actions(self, container: _ActionsContainer) -> None: ... - def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> Dict[str, Any]: ... - def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... - def _get_handler(self) -> Callable[[Action, Iterable[Tuple[Text, Action]]], Any]: ... + 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: type[Action] | None = ...) -> 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: ... + 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: ... @@ -138,8 +120,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: Text = ..., description: Text | None = ..., prog: Text = ..., - parser_class: Type[ArgumentParser] = ..., - action: Type[Action] = ..., + parser_class: type[ArgumentParser] = ..., + action: type[Action] = ..., option_string: Text = ..., dest: Text | None = ..., help: Text | None = ..., @@ -151,21 +133,21 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def format_help(self) -> str: ... def parse_known_args( self, args: Sequence[Text] | None = ..., namespace: Namespace | None = ... - ) -> Tuple[Namespace, List[str]]: ... - def convert_arg_line_to_args(self, arg_line: Text) -> List[str]: ... + ) -> tuple[Namespace, list[str]]: ... + def convert_arg_line_to_args(self, arg_line: Text) -> list[str]: ... def exit(self, status: int = ..., message: Text | None = ...) -> NoReturn: ... def error(self, message: Text) -> NoReturn: ... # undocumented - def _get_optional_actions(self) -> List[Action]: ... - def _get_positional_actions(self) -> List[Action]: ... - def _parse_known_args(self, arg_strings: List[Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... - def _read_args_from_files(self, arg_strings: List[Text]) -> List[Text]: ... + def _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) -> Tuple[Action | None, Text, Text | None] | None: ... - def _get_option_tuples(self, option_string: Text) -> List[Tuple[Action, Text, Text | None]]: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> list[int]: ... + def _parse_optional(self, arg_string: Text) -> tuple[Action | None, Text, Text | None] | None: ... + def _get_option_tuples(self, option_string: Text) -> list[tuple[Action, Text, Text | None]]: ... def _get_nargs_pattern(self, action: Action) -> _Text: ... - def _get_values(self, action: Action, arg_strings: List[Text]) -> Any: ... + 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: ... @@ -184,7 +166,7 @@ class HelpFormatter: _current_section: Any _whitespace_matcher: Pattern[str] _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class + _Section: type[Any] # Nested class def __init__( self, prog: Text, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ... ) -> None: ... @@ -208,11 +190,11 @@ class HelpFormatter: 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 _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 _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) -> _Text | None: ... def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... @@ -232,7 +214,7 @@ class Action(_AttributeHolder): choices: Iterable[Any] | None required: bool help: _Text | None - metavar: _Text | Tuple[_Text, ...] | None + metavar: _Text | tuple[_Text, ...] | None def __init__( self, option_strings: Sequence[Text], @@ -244,7 +226,7 @@ class Action(_AttributeHolder): choices: Iterable[_T] | None = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... def __call__( self, parser: ArgumentParser, namespace: Namespace, values: Text | Sequence[Any] | None, option_string: Text | None = ... @@ -266,7 +248,7 @@ class FileType: # undocumented class _ArgumentGroup(_ActionsContainer): title: _Text | None - _group_actions: List[Action] + _group_actions: list[Action] def __init__( self, container: _ActionsContainer, title: Text | None = ..., description: Text | None = ..., **kwargs: Any ) -> None: ... @@ -290,7 +272,7 @@ class _StoreConstAction(Action): default: Any = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # undocumented @@ -318,7 +300,7 @@ class _AppendConstAction(Action): default: Any = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # undocumented @@ -342,24 +324,24 @@ class _VersionAction(Action): # undocumented class _SubParsersAction(Action): - _ChoicesPseudoAction: Type[Any] # nested class + _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] + _parser_class: type[ArgumentParser] + _name_parser_map: dict[_Text, ArgumentParser] + choices: dict[_Text, ArgumentParser] + _choices_actions: list[Action] def __init__( self, option_strings: Sequence[Text], prog: Text, - parser_class: Type[ArgumentParser], + parser_class: type[ArgumentParser], dest: Text = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # TODO: Type keyword args properly. def add_parser(self, name: Text, **kwargs: Any) -> ArgumentParser: ... - def _get_subactions(self) -> List[Action]: ... + def _get_subactions(self) -> list[Action]: ... # undocumented class ArgumentTypeError(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/array.pyi b/mypy/typeshed/stdlib/@python2/array.pyi index 39670fe734fc..1ef8c3a7c8c3 100644 --- a/mypy/typeshed/stdlib/@python2/array.pyi +++ b/mypy/typeshed/stdlib/@python2/array.pyi @@ -1,4 +1,5 @@ -from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Text, Tuple, TypeVar, Union, overload +from _typeshed import Self +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, Union, overload from typing_extensions import Literal _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] @@ -20,12 +21,12 @@ class array(MutableSequence[_T], Generic[_T]): @overload def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... def append(self, __v: _T) -> None: ... - def buffer_info(self) -> Tuple[int, int]: ... + def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... def count(self, __v: Any) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... def fromfile(self, __f: BinaryIO, __n: int) -> None: ... - def fromlist(self, __list: List[_T]) -> None: ... + def 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: ... @@ -34,7 +35,7 @@ class array(MutableSequence[_T], Generic[_T]): def remove(self, __v: Any) -> None: ... def reverse(self) -> None: ... def tofile(self, __f: BinaryIO) -> None: ... - def tolist(self) -> List[_T]: ... + def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... def write(self, f: BinaryIO) -> None: ... def fromstring(self, __buffer: bytes) -> None: ... @@ -52,8 +53,8 @@ class array(MutableSequence[_T], Generic[_T]): 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 __iadd__(self: Self, x: array[_T]) -> Self: ... # type: ignore[override] + def __imul__(self: Self, n: int) -> Self: ... def __le__(self, other: array[_T]) -> bool: ... def __lt__(self, other: array[_T]) -> bool: ... def __mul__(self, n: int) -> array[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/asynchat.pyi b/mypy/typeshed/stdlib/@python2/asynchat.pyi index 0f5526d71b1d..e55dbf258a14 100644 --- a/mypy/typeshed/stdlib/@python2/asynchat.pyi +++ b/mypy/typeshed/stdlib/@python2/asynchat.pyi @@ -1,7 +1,7 @@ import asyncore import socket from abc import abstractmethod -from typing import Sequence, Tuple +from typing import Sequence class simple_producer: def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... @@ -34,4 +34,4 @@ class fifo: def is_empty(self) -> bool: ... def first(self) -> bytes: ... def push(self, data: bytes | simple_producer) -> None: ... - def pop(self) -> Tuple[int, bytes]: ... + def pop(self) -> tuple[int, bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/asyncore.pyi b/mypy/typeshed/stdlib/@python2/asyncore.pyi index 95acf9b706d3..1daa1aac87a7 100644 --- a/mypy/typeshed/stdlib/@python2/asyncore.pyi +++ b/mypy/typeshed/stdlib/@python2/asyncore.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import FileDescriptorLike from socket import SocketType -from typing import Any, Dict, Optional, Tuple, overload +from typing import Any, Optional, overload # cyclic dependence with asynchat -_maptype = Dict[int, Any] +_maptype = dict[int, Any] -socket_map: _maptype = ... # undocumented +socket_map: _maptype # undocumented class ExitNow(Exception): ... @@ -40,9 +40,9 @@ class dispatcher: def readable(self) -> bool: ... def writable(self) -> bool: ... def listen(self, num: int) -> None: ... - def bind(self, addr: Tuple[Any, ...] | str) -> None: ... - def connect(self, address: Tuple[Any, ...] | str) -> None: ... - def accept(self) -> Tuple[SocketType, Any] | None: ... + def bind(self, addr: tuple[Any, ...] | str) -> None: ... + def connect(self, address: tuple[Any, ...] | str) -> None: ... + def accept(self) -> tuple[SocketType, Any] | None: ... def send(self, data: bytes) -> int: ... def recv(self, buffer_size: int) -> bytes: ... def close(self) -> None: ... @@ -73,7 +73,7 @@ class dispatcher: @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 = ... @@ -83,7 +83,7 @@ class dispatcher: 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: Tuple[str, int] | str, flags: int = ...) -> int: ... + def sendto(self, data: bytes, address: tuple[str, int] | str, flags: int = ...) -> int: ... def setblocking(self, flag: bool) -> None: ... def settimeout(self, value: float | None) -> None: ... def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... @@ -96,7 +96,7 @@ class dispatcher_with_send(dispatcher): # incompatible signature: # def send(self, data: bytes) -> Optional[int]: ... -def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ... +def compact_traceback() -> tuple[tuple[str, str, str], type, type, str]: ... def close_all(map: _maptype | None = ..., ignore_all: bool = ...) -> None: ... if sys.platform != "win32": @@ -113,6 +113,7 @@ if sys.platform != "win32": 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: _maptype | None = ...) -> None: ... def set_file(self, fd: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/audioop.pyi b/mypy/typeshed/stdlib/@python2/audioop.pyi index 71671afe487e..b08731b85b0b 100644 --- a/mypy/typeshed/stdlib/@python2/audioop.pyi +++ b/mypy/typeshed/stdlib/@python2/audioop.pyi @@ -1,12 +1,10 @@ -from typing import Tuple - -AdpcmState = Tuple[int, int] -RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] +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: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... +def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... def avg(__fragment: bytes, __width: int) -> int: ... def avgpp(__fragment: bytes, __width: int) -> int: ... @@ -14,16 +12,16 @@ 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 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: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... +def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> 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 minmax(__fragment: bytes, __width: int) -> tuple[int, int]: ... def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... def ratecv( __fragment: bytes, @@ -34,7 +32,7 @@ def ratecv( __state: RatecvState | None, __weightA: int = ..., __weightB: int = ..., -) -> Tuple[bytes, RatecvState]: ... +) -> 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: ... diff --git a/mypy/typeshed/stdlib/@python2/bdb.pyi b/mypy/typeshed/stdlib/@python2/bdb.pyi index 5bee9dadb928..ec2fe4956b6c 100644 --- a/mypy/typeshed/stdlib/@python2/bdb.pyi +++ b/mypy/typeshed/stdlib/@python2/bdb.pyi @@ -1,19 +1,21 @@ from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Set, SupportsInt, Tuple, Type, TypeVar +from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar +from typing_extensions import ParamSpec _T = TypeVar("_T") +_P = ParamSpec("_P") _TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] +_ExcInfo = tuple[type[BaseException], BaseException, FrameType] -GENERATOR_AND_COROUTINE_FLAGS: int = ... +GENERATOR_AND_COROUTINE_FLAGS: int class BdbQuit(Exception): ... class Bdb: - skip: Set[str] | None - breaks: Dict[str, List[int]] - fncache: Dict[str, str] + skip: set[str] | None + breaks: dict[str, list[int]] + fncache: dict[str, str] frame_returning: FrameType | None botframe: FrameType | None quitting: bool @@ -53,21 +55,21 @@ class Bdb: 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: FrameType | None, t: TracebackType | None) -> Tuple[List[Tuple[FrameType, int]], int]: ... + 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: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ... def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... - def run(self, cmd: str | CodeType, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runeval(self, expr: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runctx(self, cmd: str | CodeType, globals: Dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... + def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... + def runeval(self, expr: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... + def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... class Breakpoint: next: int = ... - bplist: Dict[Tuple[str, int], List[Breakpoint]] = ... - bpbynumber: List[Breakpoint | None] = ... + bplist: dict[tuple[str, int], list[Breakpoint]] = ... + bpbynumber: list[Breakpoint | None] = ... funcname: str | None func_first_executable_line: int | None @@ -87,8 +89,7 @@ class Breakpoint: def disable(self) -> None: ... def bpprint(self, out: IO[str] | None = ...) -> None: ... def bpformat(self) -> str: ... - def __str__(self) -> str: ... def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... -def effective(file: str, line: int, frame: FrameType) -> Tuple[Breakpoint, bool] | Tuple[None, None]: ... +def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... def set_trace() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/binhex.pyi b/mypy/typeshed/stdlib/@python2/binhex.pyi index 02d094faf923..4e295b8ed903 100644 --- a/mypy/typeshed/stdlib/@python2/binhex.pyi +++ b/mypy/typeshed/stdlib/@python2/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Tuple, Union +from typing import IO, Any, Union class Error(Exception): ... @@ -12,7 +12,7 @@ class FInfo: Creator: str Flags: int -_FileInfoTuple = Tuple[str, FInfo, int, int] +_FileInfoTuple = tuple[str, FInfo, int, int] _FileHandleUnion = Union[str, IO[bytes]] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index fad8b2b4e7d8..b6ac2b78aca8 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -1,7 +1,7 @@ # 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 _typeshed import ReadableBuffer, Self, SupportsKeysAndGetItem, SupportsWrite from abc import ABCMeta from ast import mod from types import CodeType @@ -13,14 +13,11 @@ from typing import ( ByteString, Callable, Container, - Dict, - FrozenSet, Generic, ItemsView, Iterable, Iterator, KeysView, - List, Mapping, MutableMapping, MutableSequence, @@ -29,15 +26,12 @@ from typing import ( Protocol, Reversible, Sequence, - Set, Sized, SupportsAbs, SupportsComplex, SupportsFloat, SupportsInt, Text, - Tuple, - Type, TypeVar, ValuesView, overload, @@ -60,70 +54,68 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") +_TT = TypeVar("_TT", bound=type) class object: __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] + __dict__: dict[str, Any] __module__: str @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: _T) -> type[_T]: ... @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + 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 __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 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) -> str | Tuple[Any, ...]: ... - def __reduce_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: int) -> 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: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> 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: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class type(object): __base__: type - __bases__: Tuple[type, ...] + __bases__: tuple[type, ...] __basicsize__: int - __dict__: Dict[str, Any] + __dict__: dict[str, Any] __dictoffset__: int __flags__: int __itemsize__: int __module__: str - __mro__: Tuple[type, ...] + __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: ... + 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 __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]: ... + def __subclasses__(self: _TT) -> list[_TT]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. - def mro(self) -> List[type]: ... + def mro(self) -> list[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... def __subclasscheck__(self, subclass: type) -> bool: ... @@ -135,9 +127,9 @@ class super(object): class int: @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | bytearray, base: int) -> Self: ... @property def real(self) -> int: ... @property @@ -155,7 +147,7 @@ class 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 __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: ... @@ -163,7 +155,7 @@ class 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]: ... + def __rdivmod__(self, x: int) -> tuple[int, int]: ... @overload def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... @overload @@ -183,14 +175,13 @@ class int: def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[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: ... @@ -199,8 +190,8 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... + def __new__(cls: type[Self], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> Self: ... + def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod @@ -217,7 +208,7 @@ class 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 __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 @@ -228,9 +219,9 @@ class 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 __rdivmod__(self, x: float) -> tuple[float, float]: ... def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... @@ -240,7 +231,6 @@ 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: ... @@ -249,9 +239,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | _SupportsIndex) -> Self: ... @property def real(self) -> float: ... @property @@ -273,7 +263,6 @@ class complex: 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: ... @@ -293,7 +282,7 @@ class unicode(basestring, Sequence[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: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> 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: ... @@ -313,21 +302,21 @@ class unicode(basestring, Sequence[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 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: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... + def rpartition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[unicode]: ... + def startswith(self, __prefix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... + def translate(self, table: dict[int, Any] | unicode) -> unicode: ... def upper(self) -> unicode: ... def zfill(self, width: int) -> unicode: ... @overload @@ -349,12 +338,10 @@ class unicode(basestring, Sequence[unicode]): # The argument type is incompatible with Sequence def __contains__(self, s: 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]: ... + def __getnewargs__(self) -> tuple[unicode]: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... @@ -366,7 +353,7 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -387,35 +374,35 @@ class str(Sequence[str], basestring): @overload def lstrip(self, __chars: unicode) -> unicode: ... @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def partition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def partition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + 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: int | None = ..., __end: int | None = ...) -> int: ... def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def rpartition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rpartition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rpartition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + 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: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def split(self, sep: str | None = ..., 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: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[str]: ... + def startswith(self, __prefix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -440,10 +427,8 @@ class str(Sequence[str], basestring): 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 __getnewargs__(self) -> tuple[str]: ... def __getslice__(self, start: int, stop: int) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -465,7 +450,7 @@ class bytearray(MutableSequence[int], ByteString): 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: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: str | Iterable[int]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... @@ -482,17 +467,17 @@ class bytearray(MutableSequence[int], ByteString): def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, 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: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... + def startswith(self, __prefix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... @@ -503,8 +488,6 @@ class bytearray(MutableSequence[int], ByteString): 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 @@ -534,9 +517,9 @@ class bytearray(MutableSequence[int], ByteString): class memoryview(Sized, Container[str]): format: str itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None + shape: tuple[int, ...] | None + strides: tuple[int, ...] | None + suboffsets: tuple[int, ...] | None readonly: bool ndim: int def __init__(self, obj: ReadableBuffer) -> None: ... @@ -552,11 +535,11 @@ class memoryview(Sized, Container[str]): @overload def __setitem__(self, i: int, o: int) -> None: ... def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... + def tolist(self) -> list[int]: ... @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, x: bool) -> bool: ... @overload @@ -581,7 +564,7 @@ class bool(int): def __rxor__(self, x: bool) -> bool: ... @overload def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... + def __getnewargs__(self) -> tuple[int]: ... class slice(object): start: Any @@ -592,27 +575,27 @@ class slice(object): @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... + 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 __new__(cls: type[Self], iterable: Iterable[_T_co] = ...) -> Self: ... 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 __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: ... + 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, ...]: ... + 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 __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: ... @@ -638,30 +621,29 @@ class list(MutableSequence[_T], Generic[_T]): 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]: ... + 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: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... + 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 __add__(self, x: list[_T]) -> list[_T]: ... + def __iadd__(self: Self, x: Iterable[_T]) -> Self: ... + 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: ... + 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 @@ -671,76 +653,74 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @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 __init__(self, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def has_key(self, k: _KT) -> bool: ... def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... + 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: ... + 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 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]: ... + def fromkeys(cls, __iterable: Iterable[_T]) -> dict[_T, Any]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... def __len__(self) -> int: ... def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... 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 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(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(self, s: Iterable[_T]) -> set[_T]: ... def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... + 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[_T | _S]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... + def __and__(self, s: AbstractSet[object]) -> set[_T]: ... + def __iand__(self: Self, s: AbstractSet[object]) -> Self: ... + def __or__(self, s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ior__(self: Self, s: AbstractSet[_T]) -> Self: ... @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __sub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... + def __sub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __isub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __isub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... + def __isub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ixor__(self: Self, s: AbstractSet[_T]) -> Self: ... def __le__(self, s: AbstractSet[object]) -> bool: ... def __lt__(self, s: AbstractSet[object]) -> bool: ... def __ge__(self, s: AbstractSet[object]) -> bool: ... @@ -749,31 +729,30 @@ class set(MutableSet[_T], Generic[_T]): 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 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 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[_T_co | _S]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... + def __and__(self, s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __or__(self, s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... + def __sub__(self, s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __xor__(self, s: AbstractSet[_S]) -> frozenset[_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]): +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]: ... + def __iter__(self: Self) -> Self: ... + def next(self) -> tuple[int, _T]: ... class xrange(Sized, Iterable[int], Reversible[int]): @overload @@ -823,29 +802,29 @@ def cmp(__x: Any, __y: Any) -> int: ... _N1 = TypeVar("_N1", bool, int, float, complex) -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +def coerce(__x: _N1, __y: _N1) -> tuple[_N1, _N1]: ... def compile(source: 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]: ... +def dir(__o: object = ...) -> list[str]: ... _N2 = TypeVar("_N2", int, float) -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def divmod(__x: _N2, __y: _N2) -> tuple[_N2, _N2]: ... def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... + __source: Text | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... ) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... +def execfile(__filename: str, __globals: dict[str, Any] | None = ..., __locals: dict[str, Any] | None = ...) -> 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[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: None, __iterable: tuple[_T | None, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: Callable[[_T], Any], __iterable: tuple[_T, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... +def filter(__function: None, __iterable: Iterable[_T | None]) -> list[_T]: ... @overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> list[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... @@ -863,7 +842,7 @@ def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: .. def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... @overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... +def globals() -> dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... def hex(__number: int | _SupportsIndex) -> str: ... @@ -876,20 +855,20 @@ def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... +def isinstance(__obj: object, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... +def issubclass(__cls: type, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... +def locals() -> dict[str, Any]: ... @overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +def map(__func: None, __iter1: Iterable[_T1]) -> list[_T1]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def map( __func: None, @@ -898,7 +877,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def map( __func: None, @@ -909,15 +888,15 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... @overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +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]: ... +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]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4], _S], @@ -925,7 +904,7 @@ def map( __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], @@ -934,7 +913,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[..., _S], @@ -945,7 +924,7 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[_S]: ... +) -> list[_S]: ... @overload def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... @overload @@ -985,7 +964,7 @@ 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 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: ... @@ -1008,27 +987,27 @@ 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: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... +) -> list[_T]: ... @overload def sum(__iterable: Iterable[_T]) -> _T | int: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... +def vars(__object: Any = ...) -> dict[str, Any]: ... @overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +def zip(__iter1: Iterable[_T1]) -> list[tuple[_T1]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> 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]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def zip( __iter1: Iterable[Any], @@ -1038,7 +1017,7 @@ def zip( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... def __import__( name: Text, globals: Mapping[str, Any] | None = ..., @@ -1066,13 +1045,11 @@ class buffer(Sized): def __mul__(self, x: int) -> str: ... class BaseException(object): - args: Tuple[Any, ...] + 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, ...]: ... + def __getslice__(self, start: int, stop: int) -> tuple[Any, ...]: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1181,7 +1158,7 @@ class file(BinaryIO): 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 readlines(self, hint: int = ...) -> list[str]: ... def write(self, data: str) -> int: ... def writelines(self, data: Iterable[str]) -> None: ... def truncate(self, pos: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/bz2.pyi b/mypy/typeshed/stdlib/@python2/bz2.pyi index 81ee6f6ce26a..bec8994dbe29 100644 --- a/mypy/typeshed/stdlib/@python2/bz2.pyi +++ b/mypy/typeshed/stdlib/@python2/bz2.pyi @@ -1,22 +1,21 @@ import io -from _typeshed import ReadableBuffer, WriteableBuffer -from typing import IO, Any, Iterable, List, Text, TypeVar, Union +from _typeshed import ReadableBuffer, Self, WriteableBuffer +from typing import IO, Any, Iterable, Text, Union from typing_extensions import SupportsIndex _PathOrFile = Union[Text, IO[bytes]] -_T = TypeVar("_T") def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... class BZ2File(io.BufferedIOBase, IO[bytes]): - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __init__(self, filename: _PathOrFile, mode: str = ..., buffering: Any | None = ..., compresslevel: int = ...) -> None: ... def read(self, size: int | None = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore def readinto(self, b: WriteableBuffer) -> int: ... - def readlines(self, size: SupportsIndex = ...) -> List[bytes]: ... + def readlines(self, size: SupportsIndex = ...) -> list[bytes]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def write(self, data: ReadableBuffer) -> int: ... def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cPickle.pyi b/mypy/typeshed/stdlib/@python2/cPickle.pyi index d8db140cdda1..9169a8df02b0 100644 --- a/mypy/typeshed/stdlib/@python2/cPickle.pyi +++ b/mypy/typeshed/stdlib/@python2/cPickle.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, List +from typing import IO, Any HIGHEST_PROTOCOL: int -compatible_formats: List[str] +compatible_formats: list[str] format_version: str class Pickler: diff --git a/mypy/typeshed/stdlib/@python2/cProfile.pyi b/mypy/typeshed/stdlib/@python2/cProfile.pyi index 1257b0cc92eb..40731e2f3d76 100644 --- a/mypy/typeshed/stdlib/@python2/cProfile.pyi +++ b/mypy/typeshed/stdlib/@python2/cProfile.pyi @@ -1,14 +1,16 @@ +from _typeshed import Self from types import CodeType -from typing import Any, Callable, Dict, Text, Tuple, TypeVar +from typing import Any, Callable, Text, TypeVar +from typing_extensions import ParamSpec def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_P = ParamSpec("_P") +_Label = tuple[str, int, str] class Profile: stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented @@ -21,8 +23,8 @@ class Profile: def dump_stats(self, file: Text) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/cStringIO.pyi b/mypy/typeshed/stdlib/@python2/cStringIO.pyi index 7703e030c332..33a20dd4a739 100644 --- a/mypy/typeshed/stdlib/@python2/cStringIO.pyi +++ b/mypy/typeshed/stdlib/@python2/cStringIO.pyi @@ -1,5 +1,5 @@ from abc import ABCMeta -from typing import IO, Iterable, Iterator, List, overload +from typing import IO, Iterable, Iterator, 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. @@ -12,7 +12,7 @@ class InputType(IO[str], Iterator[str], metaclass=ABCMeta): def isatty(self) -> bool: ... def read(self, size: int = ...) -> str: ... def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... @@ -31,7 +31,7 @@ class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): def isatty(self) -> bool: ... def read(self, size: int = ...) -> str: ... def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/calendar.pyi b/mypy/typeshed/stdlib/@python2/calendar.pyi index ce765210dc1e..f21e6406a5c5 100644 --- a/mypy/typeshed/stdlib/@python2/calendar.pyi +++ b/mypy/typeshed/stdlib/@python2/calendar.pyi @@ -1,21 +1,19 @@ import datetime from time import struct_time -from typing import Any, Iterable, List, Optional, Sequence, Tuple +from typing import Any, Iterable, Optional, Sequence -_LocaleType = Tuple[Optional[str], Optional[str]] +_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]: ... +def monthrange(year: int, month: int) -> tuple[int, int]: ... class Calendar: firstweekday: int @@ -24,14 +22,14 @@ class Calendar: 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 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]]: ... + def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ... + def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ... + def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ... + def yeardatescalendar(self, year: int, width: int = ...) -> list[list[int]]: ... + def yeardays2calendar(self, year: int, width: int = ...) -> list[list[tuple[int, int]]]: ... + def yeardayscalendar(self, year: int, width: int = ...) -> list[list[int]]: ... class TextCalendar(Calendar): def prweek(self, theweek: int, width: int) -> None: ... @@ -46,7 +44,7 @@ class TextCalendar(Calendar): 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 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: ... @@ -85,7 +83,7 @@ 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: Tuple[int, ...] | struct_time) -> int: ... +def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes day_name: Sequence[str] diff --git a/mypy/typeshed/stdlib/@python2/cgi.pyi b/mypy/typeshed/stdlib/@python2/cgi.pyi index 674748242ebb..6c83a9c27e55 100644 --- a/mypy/typeshed/stdlib/@python2/cgi.pyi +++ b/mypy/typeshed/stdlib/@python2/cgi.pyi @@ -1,19 +1,17 @@ from _typeshed import SupportsGetItem, SupportsItemAccess -from builtins import type as _type -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Mapping, Protocol, TypeVar +from builtins import list as List, type as _type # aliases to avoid name clashes with `FieldStorage` attributes +from typing import IO, Any, AnyStr, Iterable, Iterator, Mapping, Protocol from UserDict import UserDict -_T = TypeVar("_T", bound=FieldStorage) - def parse( fp: IO[Any] | None = ..., environ: SupportsItemAccess[str, str] = ..., keep_blank_values: bool = ..., strict_parsing: bool = ..., -) -> dict[str, List[str]]: ... -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 = ...) -> List[tuple[str, str]]: ... -def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, List[bytes]]: ... +) -> dict[str, list[str]]: ... +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 = ...) -> list[tuple[str, str]]: ... +def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, list[bytes]]: ... class _Environ(Protocol): def __getitem__(self, __k: str) -> str: ... @@ -40,7 +38,6 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... class FieldStorage(object): FieldStorageClass: _type | None @@ -74,7 +71,6 @@ class FieldStorage(object): keep_blank_values: int = ..., strict_parsing: int = ..., ) -> None: ... - def __repr__(self) -> str: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... def getvalue(self, key: str, default: Any = ...) -> Any: ... @@ -88,7 +84,7 @@ class FieldStorage(object): # In Python 2 it always returns bytes and ignores the "binary" flag def make_file(self, binary: Any = ...) -> IO[bytes]: ... -class FormContentDict(UserDict[str, List[str]]): +class FormContentDict(UserDict[str, list[str]]): query_string: str def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cgitb.pyi b/mypy/typeshed/stdlib/@python2/cgitb.pyi index daa0233ee69a..aff45db6198c 100644 --- a/mypy/typeshed/stdlib/@python2/cgitb.pyi +++ b/mypy/typeshed/stdlib/@python2/cgitb.pyi @@ -1,16 +1,16 @@ from types import FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, Optional, Text, Tuple, Type +from typing import IO, Any, Callable, Optional, Text -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_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[str | None, Any]: ... # undocumented +def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | None, Any]: ... # undocumented def scanvars( - reader: Callable[[], bytes], frame: FrameType, locals: Dict[str, Any] -) -> List[Tuple[str, str | None, Any]]: ... # undocumented + reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] +) -> list[tuple[str, str | None, Any]]: ... # undocumented def html(einfo: _ExcInfo, context: int = ...) -> str: ... def text(einfo: _ExcInfo, context: int = ...) -> str: ... @@ -18,7 +18,7 @@ class Hook: # undocumented def __init__( self, display: int = ..., logdir: Text | None = ..., context: int = ..., file: IO[str] | None = ..., format: str = ... ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... def handle(self, info: _ExcInfo | None = ...) -> None: ... def handler(info: _ExcInfo | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cmath.pyi b/mypy/typeshed/stdlib/@python2/cmath.pyi index 1e19687b4885..ef54d7f43854 100644 --- a/mypy/typeshed/stdlib/@python2/cmath.pyi +++ b/mypy/typeshed/stdlib/@python2/cmath.pyi @@ -1,4 +1,4 @@ -from typing import SupportsComplex, SupportsFloat, Tuple, Union +from typing import SupportsComplex, SupportsFloat, Union e: float pi: float @@ -18,7 +18,7 @@ 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 polar(__z: _C) -> tuple[float, float]: ... def rect(__r: float, __phi: float) -> complex: ... def sin(__z: _C) -> complex: ... def sinh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/@python2/cmd.pyi b/mypy/typeshed/stdlib/@python2/cmd.pyi index ffccba84ec16..f6d818591a4e 100644 --- a/mypy/typeshed/stdlib/@python2/cmd.pyi +++ b/mypy/typeshed/stdlib/@python2/cmd.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, List, Tuple +from typing import IO, Any, Callable class Cmd: prompt: str @@ -14,7 +14,7 @@ class Cmd: use_rawinput: bool stdin: IO[str] stdout: IO[str] - cmdqueue: List[str] + cmdqueue: list[str] completekey: str def __init__(self, completekey: str = ..., stdin: IO[str] | None = ..., stdout: IO[str] | None = ...) -> None: ... old_completer: Callable[[str, int], str | None] | None @@ -23,17 +23,17 @@ class Cmd: def postcmd(self, stop: bool, line: str) -> bool: ... def preloop(self) -> None: ... def postloop(self) -> None: ... - def parseline(self, line: str) -> Tuple[str | None, str | None, str]: ... + def parseline(self, line: str) -> tuple[str | None, str | None, 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: List[str] | None - def complete(self, text: str, state: int) -> List[str] | None: ... - def get_names(self) -> List[str]: ... + def completedefault(self, *ignored: Any) -> list[str]: ... + def completenames(self, text: str, *ignored: Any) -> list[str]: ... + completion_matches: list[str] | None + def complete(self, text: str, state: int) -> list[str] | None: ... + def get_names(self) -> list[str]: ... # Only the first element of args matters. - def complete_help(self, *args: Any) -> List[str]: ... + def complete_help(self, *args: Any) -> list[str]: ... def do_help(self, arg: str) -> bool | None: ... - def print_topics(self, header: str, cmds: List[str] | None, cmdlen: Any, maxcol: int) -> None: ... - def columnize(self, list: List[str] | None, displaywidth: int = ...) -> None: ... + def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ... + def columnize(self, list: list[str] | None, displaywidth: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/codecs.pyi b/mypy/typeshed/stdlib/@python2/codecs.pyi index a7835106336d..2780d473b781 100644 --- a/mypy/typeshed/stdlib/@python2/codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/codecs.pyi @@ -1,23 +1,7 @@ import types +from _typeshed import Self from abc import abstractmethod -from typing import ( - IO, - Any, - BinaryIO, - Callable, - Generator, - Iterable, - Iterator, - List, - Protocol, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, Union, overload from typing_extensions import Literal # TODO: this only satisfies the most common interface, where @@ -30,10 +14,10 @@ _Decoded = Text _Encoded = bytes class _Encoder(Protocol): - def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode + def __call__(self, input: _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 + 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: ... @@ -83,10 +67,10 @@ def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: . def lookup(__encoding: str) -> CodecInfo: ... def utf_16_be_decode( __data: _Encoded, __errors: str | None = ..., __final: bool = ... -) -> Tuple[_Decoded, int]: ... # undocumented -def utf_16_be_encode(__str: _Decoded, __errors: str | None = ...) -> Tuple[_Encoded, int]: ... # undocumented +) -> tuple[_Decoded, int]: ... # undocumented +def utf_16_be_encode(__str: _Decoded, __errors: str | None = ...) -> tuple[_Encoded, int]: ... # undocumented -class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): +class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property def encode(self) -> _Encoder: ... @property @@ -101,7 +85,7 @@ class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): def incrementaldecoder(self) -> _IncrementalDecoder: ... name: str def __new__( - cls, + cls: type[Self], encode: _Encoder, decode: _Decoder, streamreader: _StreamReader | None = ..., @@ -111,7 +95,7 @@ class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): name: str | None = ..., *, _is_text_encoding: bool | None = ..., - ) -> CodecInfo: ... + ) -> Self: ... def getencoder(encoding: str) -> _Encoder: ... def getdecoder(encoding: str) -> _Decoder: ... @@ -141,19 +125,19 @@ BOM_UTF32_LE: bytes # It is expected that different actions be taken depending on which of the # three subclasses of `UnicodeError` is actually ...ed. However, the Union # is still needed for at least one of the cases. -def register_error(__errors: str, __handler: Callable[[UnicodeError], Tuple[str | bytes, int]]) -> None: ... -def lookup_error(__name: str) -> Callable[[UnicodeError], Tuple[str | bytes, int]]: ... -def strict_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def replace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def ignore_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def backslashreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... +def register_error(__errors: str, __handler: Callable[[UnicodeError], tuple[str | bytes, int]]) -> None: ... +def lookup_error(__name: str) -> Callable[[UnicodeError], tuple[str | bytes, int]]: ... +def strict_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def replace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def ignore_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def backslashreplace_errors(exception: UnicodeError) -> tuple[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]: ... + def encode(self, input: _Decoded, errors: str = ...) -> tuple[_Encoded, int]: ... + def decode(self, input: _Encoded, errors: str = ...) -> tuple[_Decoded, int]: ... class IncrementalEncoder: errors: str @@ -171,8 +155,8 @@ class IncrementalDecoder: @abstractmethod def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... def reset(self) -> None: ... - def getstate(self) -> Tuple[_Encoded, int]: ... - def setstate(self, state: Tuple[_Encoded, int]) -> None: ... + 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): @@ -186,11 +170,9 @@ 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 _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> tuple[_Decoded, int]: ... def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... -_SW = TypeVar("_SW", bound=StreamWriter) - # TODO: it is not possible to specify the requirement that all other # attributes and methods are passed-through from the stream. class StreamWriter(Codec): @@ -199,43 +181,39 @@ class StreamWriter(Codec): def write(self, object: _Decoded) -> None: ... def writelines(self, list: Iterable[_Decoded]) -> None: ... def reset(self) -> None: ... - def __enter__(self: _SW) -> _SW: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_SR = TypeVar("_SR", bound=StreamReader) - class StreamReader(Codec): errors: str def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... def readline(self, size: int | None = ..., keepends: bool = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> List[_Decoded]: ... + def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[_Decoded]: ... def reset(self) -> None: ... - def __enter__(self: _SR) -> _SR: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __iter__(self) -> Iterator[_Decoded]: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_T = TypeVar("_T", bound=StreamReaderWriter) - # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... def read(self, size: int = ...) -> _Decoded: ... def readline(self, size: int | None = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ...) -> List[_Decoded]: ... + def readlines(self, sizehint: int | None = ...) -> list[_Decoded]: ... def next(self) -> Text: ... - def __iter__(self: _T) -> _T: ... + def __iter__(self: Self) -> Self: ... # 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: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> 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__. @@ -249,8 +227,6 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): def __init__( self, @@ -263,15 +239,15 @@ class StreamRecoder(BinaryIO): ) -> None: ... def read(self, size: int = ...) -> bytes: ... def readline(self, size: int | None = ...) -> bytes: ... - def readlines(self, sizehint: int | None = ...) -> List[bytes]: ... + def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... def next(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... + def __iter__(self: Self) -> Self: ... 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: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> 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: ... diff --git a/mypy/typeshed/stdlib/@python2/collections.pyi b/mypy/typeshed/stdlib/@python2/collections.pyi index 5a2f73aed7ce..e7a2e7d1793f 100644 --- a/mypy/typeshed/stdlib/@python2/collections.pyi +++ b/mypy/typeshed/stdlib/@python2/collections.pyi @@ -1,16 +1,15 @@ +from _typeshed import Self 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, @@ -19,8 +18,6 @@ from typing import ( Reversible, Sequence as Sequence, Sized as Sized, - Tuple, - Type, TypeVar, ValuesView as ValuesView, overload, @@ -28,7 +25,6 @@ from typing import ( Set = AbstractSet -_S = TypeVar("_S") _T = TypeVar("_T") _KT = TypeVar("_KT") _VT = TypeVar("_VT") @@ -36,7 +32,7 @@ _VT = TypeVar("_VT") # namedtuple is special-cased in the type checker; the initializer is ignored. def namedtuple( typename: str | unicode, field_names: str | unicode | Iterable[str | unicode], verbose: bool = ..., rename: bool = ... -) -> Type[Tuple[Any, ...]]: ... +) -> type[tuple[Any, ...]]: ... class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ..., maxlen: int = ...) -> None: ... @@ -55,24 +51,23 @@ class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): 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: ... + def __iadd__(self: Self, iterable: Iterable[_T]) -> Self: ... -class Counter(Dict[_T, int], Generic[_T]): +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 copy(self: Self) -> Self: ... def elements(self) -> Iterator[_T]: ... - def most_common(self, n: int | None = ...) -> List[Tuple[_T, int]]: ... + def most_common(self, n: int | None = ...) -> list[tuple[_T, int]]: ... @overload def subtract(self, __mapping: Mapping[_T, int]) -> None: ... @overload @@ -85,24 +80,24 @@ class Counter(Dict[_T, int], Generic[_T]): @overload def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... @overload - def update(self, __m: Iterable[_T] | Iterable[Tuple[_T, int]], **kwargs: int) -> None: ... + def update(self, __m: 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]: ... + def __iadd__(self: Self, other: Counter[_T]) -> Self: ... + def __isub__(self: Self, other: Counter[_T]) -> Self: ... + def __iand__(self: Self, other: Counter[_T]) -> Self: ... + def __ior__(self: Self, other: Counter[_T]) -> Self: ... -class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): - def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... - def copy(self: _S) -> _S: ... +class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> tuple[_KT, _VT]: ... + def copy(self: Self) -> Self: ... def __reversed__(self) -> Iterator[_KT]: ... -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): +class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] @overload def __init__(self, **kwargs: _VT) -> None: ... @@ -115,8 +110,8 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self, default_factory: Callable[[], _VT] | None, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]]) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... def __missing__(self, key: _KT) -> _VT: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/@python2/colorsys.pyi b/mypy/typeshed/stdlib/@python2/colorsys.pyi index 8db2e2c9ab3a..00c5f9d22cb1 100644 --- a/mypy/typeshed/stdlib/@python2/colorsys.pyi +++ b/mypy/typeshed/stdlib/@python2/colorsys.pyi @@ -1,11 +1,9 @@ -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]: ... +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 diff --git a/mypy/typeshed/stdlib/@python2/commands.pyi b/mypy/typeshed/stdlib/@python2/commands.pyi index 970d6ccf2032..2c36033583ec 100644 --- a/mypy/typeshed/stdlib/@python2/commands.pyi +++ b/mypy/typeshed/stdlib/@python2/commands.pyi @@ -1,8 +1,8 @@ -from typing import AnyStr, Text, Tuple, overload +from typing import AnyStr, Text, overload def getstatus(file: Text) -> str: ... def getoutput(cmd: Text) -> str: ... -def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... +def getstatusoutput(cmd: Text) -> tuple[int, str]: ... @overload def mk2arg(head: bytes, x: bytes) -> bytes: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/contextlib.pyi b/mypy/typeshed/stdlib/@python2/contextlib.pyi index 6782fbf1874c..8e68238fc6e2 100644 --- a/mypy/typeshed/stdlib/@python2/contextlib.pyi +++ b/mypy/typeshed/stdlib/@python2/contextlib.pyi @@ -1,18 +1,18 @@ from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, Type, TypeVar +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, TypeVar +from typing_extensions import ParamSpec _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]) +_P = ParamSpec("_P") -_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] class GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... -def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... +def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, ContextManager[_T]]: ... def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... class _SupportsClose(Protocol): diff --git a/mypy/typeshed/stdlib/@python2/copy.pyi b/mypy/typeshed/stdlib/@python2/copy.pyi index c88f92846ddf..a5f9420e3811 100644 --- a/mypy/typeshed/stdlib/@python2/copy.pyi +++ b/mypy/typeshed/stdlib/@python2/copy.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, TypeVar +from typing import Any, TypeVar _T = TypeVar("_T") @@ -6,7 +6,7 @@ _T = TypeVar("_T") PyStringMap: Any # Note: memo and _nil are internal kwargs. -def deepcopy(x: _T, memo: Dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... +def deepcopy(x: _T, memo: dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... def copy(x: _T) -> _T: ... class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/copy_reg.pyi b/mypy/typeshed/stdlib/@python2/copy_reg.pyi index 91b099888bab..5aec88298ab3 100644 --- a/mypy/typeshed/stdlib/@python2/copy_reg.pyi +++ b/mypy/typeshed/stdlib/@python2/copy_reg.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union +from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] -__all__: List[str] +__all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] def pickle( ob_type: _TypeT, diff --git a/mypy/typeshed/stdlib/@python2/copyreg.pyi b/mypy/typeshed/stdlib/@python2/copyreg.pyi index 91b099888bab..5aec88298ab3 100644 --- a/mypy/typeshed/stdlib/@python2/copyreg.pyi +++ b/mypy/typeshed/stdlib/@python2/copyreg.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union +from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] -__all__: List[str] +__all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] def pickle( ob_type: _TypeT, diff --git a/mypy/typeshed/stdlib/@python2/csv.pyi b/mypy/typeshed/stdlib/@python2/csv.pyi index 886de6210ca9..a52db42291af 100644 --- a/mypy/typeshed/stdlib/@python2/csv.pyi +++ b/mypy/typeshed/stdlib/@python2/csv.pyi @@ -16,20 +16,8 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) -from typing import ( - Any, - Dict as _DictReadMapping, - Generic, - Iterable, - Iterator, - List, - Mapping, - Sequence, - Text, - Type, - TypeVar, - overload, -) +from builtins import dict as _DictReadMapping +from typing import Any, Generic, Iterable, Iterator, Mapping, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -96,7 +84,7 @@ class DictWriter(Generic[_T]): def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... class Sniffer(object): - preferred: List[str] + preferred: list[str] def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... + def sniff(self, sample: str, delimiters: str | None = ...) -> type[Dialect]: ... def has_header(self, sample: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi index 8a10ff954e27..9fab35ebd022 100644 --- a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from array import array from typing import ( Any, @@ -7,13 +8,10 @@ from typing import ( Generic, Iterable, Iterator, - List, Mapping, Optional, Sequence, Text, - Tuple, - Type, TypeVar, Union as _UnionT, overload, @@ -23,16 +21,16 @@ _T = TypeVar("_T") _DLLT = TypeVar("_DLLT", bound=CDLL) _CT = TypeVar("_CT", bound=_CData) -RTLD_GLOBAL: int = ... -RTLD_LOCAL: int = ... -DEFAULT_MODE: int = ... +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] = ... + _FuncPtr: type[_FuncPointer] = ... def __init__( self, name: str | None, mode: int = ..., handle: int | None = ..., use_errno: bool = ..., use_last_error: bool = ... ) -> None: ... @@ -46,17 +44,17 @@ if sys.platform == "win32": class PyDLL(CDLL): ... class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... + 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] = ... +cdll: LibraryLoader[CDLL] if sys.platform == "win32": - windll: LibraryLoader[WinDLL] = ... - oledll: LibraryLoader[OleDLL] = ... -pydll: LibraryLoader[PyDLL] = ... -pythonapi: PyDLL = ... + 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 @@ -69,42 +67,42 @@ 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 + 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: Mapping[Any, int] | None = ... @classmethod - def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ... + def from_buffer(cls: type[Self], source: _WritableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ... + def from_buffer_copy(cls: type[Self], source: _ReadOnlyBuffer, offset: int = ...) -> Self: ... @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... + def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + def from_param(cls: type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... 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]] +_ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CData] +_PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[Type[_CData], Callable[[int], Any], None] = ... - argtypes: Sequence[Type[_CData]] = ... + restype: _UnionT[type[_CData], Callable[[int], Any], None] = ... + argtypes: Sequence[type[_CData]] = ... errcheck: _ECT = ... @overload def __init__(self, address: int) -> None: ... @overload def __init__(self, callable: Callable[..., Any]) -> None: ... @overload - def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... + 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): @@ -113,15 +111,15 @@ class _NamedFuncPointer(_FuncPointer): class ArgumentError(Exception): ... def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... +) -> type[_FuncPointer]: ... if sys.platform == "win32": def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... + ) -> type[_FuncPointer]: ... -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... +def PYFUNCTYPE(restype: type[_CData] | None, *argtypes: type[_CData]) -> type[_FuncPointer]: ... class _CArgObject: ... @@ -135,12 +133,12 @@ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] _CVoidConstPLike = _UnionT[_CVoidPLike, bytes] def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def alignment(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _UnionT[_CData, _CArgObject, int], typ: Type[_CastT]) -> _CastT: ... +def cast(obj: _UnionT[_CData, _CArgObject, int], typ: type[_CastT]) -> _CastT: ... def create_string_buffer(init: _UnionT[int, bytes], size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer @@ -160,32 +158,32 @@ if sys.platform == "win32": 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]]: ... +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_: Type[_CT] = ... + _type_: 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]: ... + def __getitem__(self, s: slice) -> list[_CT]: ... @overload def __setitem__(self, i: int, o: _CT) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... def resize(obj: _CData, size: int) -> None: ... -def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... +def set_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 sizeof(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -246,7 +244,7 @@ class _CField: size: int = ... class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ... + _fields_: Sequence[_UnionT[tuple[str, type[_CData]], tuple[str, type[_CData], int]]] = ... _pack_: int = ... _anonymous_: Sequence[str] = ... def __getattr__(self, name: str) -> _CField: ... @@ -263,7 +261,7 @@ class LittleEndianStructure(Structure): ... class Array(Generic[_CT], _CData): _length_: int = ... - _type_: Type[_CT] = ... + _type_: 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. @@ -282,7 +280,7 @@ class Array(Generic[_CT], _CData): @overload def __getitem__(self, i: int) -> Any: ... @overload - def __getitem__(self, s: slice) -> List[Any]: ... + def __getitem__(self, s: slice) -> list[Any]: ... @overload def __setitem__(self, i: int, o: Any) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/curses/__init__.pyi b/mypy/typeshed/stdlib/@python2/curses/__init__.pyi index 73e84fba3763..d5581ce11c22 100644 --- a/mypy/typeshed/stdlib/@python2/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/curses/__init__.pyi @@ -1,4 +1,4 @@ -from _curses import * # noqa: F403 +from _curses import * from _curses import _CursesWindow as _CursesWindow from typing import Any, Callable, TypeVar diff --git a/mypy/typeshed/stdlib/@python2/curses/ascii.pyi b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi index 05efb326687a..66efbe36a7df 100644 --- a/mypy/typeshed/stdlib/@python2/curses/ascii.pyi +++ b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi @@ -1,4 +1,4 @@ -from typing import List, TypeVar +from typing import TypeVar _CharT = TypeVar("_CharT", str, int) @@ -39,7 +39,7 @@ US: int SP: int DEL: int -controlnames: List[int] +controlnames: list[int] def isalnum(c: str | int) -> bool: ... def isalpha(c: str | int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/datetime.pyi b/mypy/typeshed/stdlib/@python2/datetime.pyi index 8b19a3d316f2..6a259cf4d0e4 100644 --- a/mypy/typeshed/stdlib/@python2/datetime.pyi +++ b/mypy/typeshed/stdlib/@python2/datetime.pyi @@ -1,7 +1,6 @@ +from _typeshed import Self from time import struct_time -from typing import AnyStr, ClassVar, SupportsAbs, Tuple, Type, TypeVar, Union, overload - -_S = TypeVar("_S") +from typing import AnyStr, ClassVar, SupportsAbs, Union, overload _Text = Union[str, unicode] @@ -20,13 +19,13 @@ class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls: type[Self], year: int, month: int, day: int) -> Self: ... @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal(cls: type[Self], n: int) -> Self: ... @property def year(self) -> int: ... @property @@ -53,15 +52,20 @@ class date: def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... + def isocalendar(self) -> tuple[int, int, int]: ... class time: min: ClassVar[time] max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ... - ) -> _S: ... + cls: type[Self], + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -95,7 +99,7 @@ class timedelta(SupportsAbs[timedelta]): max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], days: float = ..., seconds: float = ..., microseconds: float = ..., @@ -103,7 +107,7 @@ class timedelta(SupportsAbs[timedelta]): minutes: float = ..., hours: float = ..., weeks: float = ..., - ) -> _S: ... + ) -> Self: ... @property def days(self) -> int: ... @property @@ -139,7 +143,7 @@ class datetime(date): max: ClassVar[datetime] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], year: int, month: int, day: int, @@ -148,7 +152,7 @@ class datetime(date): second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ..., - ) -> _S: ... + ) -> Self: ... @property def year(self) -> int: ... @property @@ -166,21 +170,21 @@ class datetime(date): @property def tzinfo(self) -> _tzinfo | None: ... @classmethod - def fromtimestamp(cls: Type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[Self], t: float, tz: _tzinfo | None = ...) -> Self: ... @classmethod - def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... + def utcfromtimestamp(cls: type[Self], t: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal(cls: type[Self], n: int) -> Self: ... @overload @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... + def now(cls: type[Self], tz: None = ...) -> Self: ... @overload @classmethod def now(cls, tz: _tzinfo) -> datetime: ... @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + def utcnow(cls: type[Self]) -> Self: ... @classmethod def combine(cls, date: _date, time: _time) -> datetime: ... def strftime(self, fmt: _Text) -> str: ... @@ -223,4 +227,4 @@ class datetime(date): def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... + def isocalendar(self) -> tuple[int, int, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi index 95f6d9cf0363..9c867074df06 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Tuple, Type, Union +from typing import Iterator, MutableMapping, Union from typing_extensions import Literal _KeyType = Union[str, bytes] @@ -13,14 +14,14 @@ class _Database(MutableMapping[_KeyType, bytes]): def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... class _error(Exception): ... -error = Tuple[Type[_error], Type[OSError]] +error = tuple[type[_error], type[OSError]] def whichdb(filename: str) -> str: ... def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi index fb5e2da5fa2c..e040f23ce2b0 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Union _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -17,9 +18,9 @@ class _Database(MutableMapping[_KeyType, bytes]): def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi index 0e9339bf81f9..1eecfac66a5f 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from types import TracebackType -from typing import List, Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] @@ -18,15 +19,15 @@ class _gdbm: def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... def __delitem__(self, key: _KeyType) -> None: ... def __len__(self) -> int: ... - def __enter__(self) -> _gdbm: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @overload def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime __new__: None # type: ignore diff --git a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi index 28f4dd8e4e59..12d9f31881c1 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from types import TracebackType -from typing import List, Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] @@ -7,7 +8,7 @@ _ValueType = Union[str, bytes] class error(OSError): ... -library: str = ... +library: str # Actual typename dbm, not exposed by the implementation class _dbm: @@ -17,15 +18,15 @@ class _dbm: def __delitem__(self, key: _KeyType) -> None: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _dbm: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @overload def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime __new__: None # type: ignore diff --git a/mypy/typeshed/stdlib/@python2/decimal.pyi b/mypy/typeshed/stdlib/@python2/decimal.pyi index 915bddadb584..f798d8811c87 100644 --- a/mypy/typeshed/stdlib/@python2/decimal.pyi +++ b/mypy/typeshed/stdlib/@python2/decimal.pyi @@ -1,14 +1,14 @@ +from _typeshed import Self from types import TracebackType -from typing import Any, Container, Dict, List, NamedTuple, Sequence, Text, Tuple, Type, TypeVar, Union +from typing import Any, Container, NamedTuple, Sequence, Text, Union _Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] +_DecimalNew = Union[Decimal, float, Text, tuple[int, Sequence[int], int]] _ComparableNum = Union[Decimal, float] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): sign: int - digits: Tuple[int, ...] + digits: tuple[int, ...] exponent: int ROUND_DOWN: str @@ -41,7 +41,7 @@ def getcontext() -> Context: ... def localcontext(ctx: Context | None = ...) -> _ContextManager: ... class Decimal(object): - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod def from_float(cls, __f: float) -> Decimal: ... def __nonzero__(self) -> bool: ... @@ -54,7 +54,7 @@ class Decimal(object): def to_eng_string(self, context: Context | None = ...) -> str: ... def __abs__(self, round: bool = ..., context: Context | None = ...) -> Decimal: ... def __add__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __divmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... + def __divmod__(self, other: _Decimal, context: Context | None = ...) -> tuple[Decimal, Decimal]: ... def __eq__(self, other: object, context: Context | None = ...) -> bool: ... def __floordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __ge__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... @@ -67,7 +67,7 @@ class Decimal(object): def __pos__(self, context: Context | None = ...) -> Decimal: ... def __pow__(self, other: _Decimal, modulo: _Decimal | None = ..., context: Context | None = ...) -> Decimal: ... def __radd__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rdivmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... + def __rdivmod__(self, other: _Decimal, context: Context | None = ...) -> tuple[Decimal, Decimal]: ... def __rfloordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __rmod__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __rmul__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... @@ -136,7 +136,7 @@ class Decimal(object): def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> Tuple[Type[Decimal], Tuple[str]]: ... + def __reduce__(self) -> tuple[type[Decimal], tuple[str]]: ... def __copy__(self) -> Decimal: ... def __deepcopy__(self, memo: Any) -> Decimal: ... def __format__(self, specifier: str, context: Context | None = ...) -> str: ... @@ -146,9 +146,9 @@ class _ContextManager(object): saved_context: Context def __init__(self, new_context: Context) -> None: ... def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... -_TrapType = Type[DecimalException] +_TrapType = type[DecimalException] class Context(object): prec: int @@ -157,19 +157,19 @@ class Context(object): Emax: int capitals: int _clamp: int - traps: Dict[_TrapType, bool] - flags: Dict[_TrapType, bool] + traps: dict[_TrapType, bool] + flags: dict[_TrapType, bool] def __init__( self, prec: int | None = ..., rounding: str | None = ..., - traps: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., - flags: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., + traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., + flags: None | dict[_TrapType, bool] | Container[_TrapType] = ..., Emin: int | None = ..., Emax: int | None = ..., capitals: int | None = ..., _clamp: int | None = ..., - _ignored_flags: List[_TrapType] | None = ..., + _ignored_flags: list[_TrapType] | None = ..., ) -> None: ... def clear_flags(self) -> None: ... def copy(self) -> Context: ... @@ -192,7 +192,7 @@ class Context(object): 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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/difflib.pyi b/mypy/typeshed/stdlib/@python2/difflib.pyi index 41ffc6a286d1..c4e59f54c66d 100644 --- a/mypy/typeshed/stdlib/@python2/difflib.pyi +++ b/mypy/typeshed/stdlib/@python2/difflib.pyi @@ -1,19 +1,4 @@ -from typing import ( - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - List, - NamedTuple, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, Union, overload _T = TypeVar("_T") @@ -35,9 +20,9 @@ class SequenceMatcher(Generic[_T]): def set_seq1(self, a: Sequence[_T]) -> None: ... def set_seq2(self, b: Sequence[_T]) -> None: ... def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... - def get_matching_blocks(self) -> List[Match]: ... - def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ... - def get_grouped_opcodes(self, n: int = ...) -> Iterable[List[Tuple[str, int, int, int, int]]]: ... + def 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: ... @@ -46,11 +31,11 @@ class SequenceMatcher(Generic[_T]): @overload def get_close_matches( # type: ignore word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... -) -> List[AnyStr]: ... +) -> list[AnyStr]: ... @overload def get_close_matches( word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... -) -> List[Sequence[_T]]: ... +) -> list[Sequence[_T]]: ... class Differ: def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dircache.pyi b/mypy/typeshed/stdlib/@python2/dircache.pyi index 366909d87133..dc1e129648e8 100644 --- a/mypy/typeshed/stdlib/@python2/dircache.pyi +++ b/mypy/typeshed/stdlib/@python2/dircache.pyi @@ -1,7 +1,7 @@ -from typing import List, MutableSequence, Text +from typing import MutableSequence, Text def reset() -> None: ... -def listdir(path: Text) -> List[str]: ... +def listdir(path: Text) -> list[str]: ... opendir = listdir diff --git a/mypy/typeshed/stdlib/@python2/dis.pyi b/mypy/typeshed/stdlib/@python2/dis.pyi index 1d6537667a60..f6be1a8dfa83 100644 --- a/mypy/typeshed/stdlib/@python2/dis.pyi +++ b/mypy/typeshed/stdlib/@python2/dis.pyi @@ -13,17 +13,17 @@ from opcode import ( opmap as opmap, opname as opname, ) -from typing import Any, Callable, Dict, Iterator, List, Tuple, Union +from typing import Any, Callable, Iterator, Union # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) _have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] _have_code_or_string = Union[_have_code, str, bytes] -COMPILER_FLAG_NAMES: Dict[int, str] +COMPILER_FLAG_NAMES: dict[int, str] -def findlabels(code: _have_code) -> List[int]: ... -def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... +def findlabels(code: _have_code) -> list[int]: ... +def findlinestarts(code: _have_code) -> Iterator[tuple[int, int]]: ... def dis(x: _have_code_or_string = ...) -> None: ... def distb(tb: types.TracebackType = ...) -> None: ... def disassemble(co: _have_code, lasti: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi index b0539bf9e5dc..7c7023ed0b65 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi @@ -1,11 +1,11 @@ -from typing import Any, Callable, List, Optional, Tuple, Union +from typing import Any, Callable, Optional, Union -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] +_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]: ... + 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: str | None = ..., platform: str | None = ...) -> str: ... def new_compiler( plat: str | None = ..., compiler: str | None = ..., verbose: int = ..., dry_run: int = ..., force: int = ... @@ -17,34 +17,34 @@ class CCompiler: force: bool verbose: bool output_dir: str | None - macros: List[_Macro] - include_dirs: List[str] - libraries: List[str] - library_dirs: List[str] - runtime_library_dirs: List[str] - objects: List[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 set_include_dirs(self, dirs: list[str]) -> None: ... def add_library(self, libname: str) -> None: ... - def set_libraries(self, libnames: List[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 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 set_runtime_library_dirs(self, dirs: list[str]) -> None: ... def define_macro(self, name: str, value: str | None = ...) -> 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: str | List[str]) -> str | None: ... - def find_library_file(self, dirs: List[str], lib: str, debug: bool = ...) -> str | None: ... + def set_link_objects(self, objects: list[str]) -> None: ... + def detect_language(self, sources: str | list[str]) -> str | None: ... + def find_library_file(self, dirs: list[str], lib: str, debug: bool = ...) -> str | None: ... def has_function( self, funcname: str, - includes: List[str] | None = ..., - include_dirs: List[str] | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., + includes: list[str] | None = ..., + include_dirs: list[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., ) -> bool: ... def library_dir_option(self, dir: str) -> str: ... def library_option(self, lib: str) -> str: ... @@ -52,18 +52,18 @@ class CCompiler: def set_executables(self, **args: str) -> None: ... def compile( self, - sources: List[str], + sources: list[str], output_dir: str | None = ..., macros: _Macro | None = ..., - include_dirs: List[str] | None = ..., + include_dirs: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - depends: List[str] | None = ..., - ) -> List[str]: ... + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., + depends: list[str] | None = ..., + ) -> list[str]: ... def create_static_lib( self, - objects: List[str], + objects: list[str], output_libname: str, output_dir: str | None = ..., debug: bool = ..., @@ -72,59 +72,59 @@ class CCompiler: def link( self, target_desc: str, - objects: List[str], + objects: list[str], output_filename: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... def link_executable( self, - objects: List[str], + objects: list[str], output_progname: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., target_lang: str | None = ..., ) -> None: ... def link_shared_lib( self, - objects: List[str], + objects: list[str], output_libname: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... def link_shared_object( self, - objects: List[str], + objects: list[str], output_filename: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... @@ -132,17 +132,17 @@ class CCompiler: self, source: str, output_file: str | None = ..., - macros: List[_Macro] | None = ..., - include_dirs: List[str] | None = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + macros: list[_Macro] | None = ..., + include_dirs: list[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., ) -> 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 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: str | None = ..., level: int = ...) -> None: ... - def spawn(self, cmd: List[str]) -> None: ... + def execute(self, func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., 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: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi index d4e90bf69970..096414713f7f 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi @@ -1,9 +1,9 @@ from abc import abstractmethod from distutils.dist import Distribution -from typing import Any, Callable, Iterable, List, Text, Tuple +from typing import Any, Callable, Iterable, Text class Command: - sub_commands: List[Tuple[str, Callable[[Command], bool] | None]] + sub_commands: list[tuple[str, Callable[[Command], bool] | None]] def __init__(self, dist: Distribution) -> None: ... @abstractmethod def initialize_options(self) -> None: ... @@ -14,15 +14,15 @@ class Command: def announce(self, msg: Text, level: int = ...) -> None: ... def debug_print(self, msg: Text) -> None: ... def ensure_string(self, option: str, default: str | None = ...) -> None: ... - def ensure_string_list(self, option: str | List[str]) -> None: ... + def ensure_string_list(self, option: 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 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: Command | Text, reinit_subcommands: int = ...) -> Command: ... def run_command(self, command: Text) -> None: ... - def get_sub_commands(self) -> List[str]: ... + def get_sub_commands(self) -> list[str]: ... def warn(self, msg: Text) -> None: ... def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Text | None = ..., level: int = ...) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... @@ -34,7 +34,7 @@ class Command: preserve_times: int = ..., link: str | None = ..., level: Any = ..., - ) -> Tuple[str, bool]: ... # level is not used + ) -> tuple[str, bool]: ... # level is not used def copy_tree( self, infile: str, @@ -43,7 +43,7 @@ class Command: preserve_times: int = ..., preserve_symlinks: int = ..., level: Any = ..., - ) -> List[str]: ... # level is not used + ) -> 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( @@ -57,10 +57,10 @@ class Command: ) -> str: ... def make_file( self, - infiles: str | List[str] | Tuple[str], + infiles: str | list[str] | tuple[str, ...], outfile: str, func: Callable[..., Any], - args: List[Any], + args: list[Any], exec_msg: str | None = ..., skip_msg: str | None = ..., level: Any = ..., diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi index 150229fb01c9..09351d29a673 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi @@ -2,6 +2,7 @@ import sys if sys.platform == "win32": from distutils.cmd import Command + class bdist_msi(Command): def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi index d0fd762e83b2..790a8b485a56 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi @@ -3,14 +3,14 @@ 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, Pattern, Sequence, Tuple +from typing import Pattern, Sequence -LANG_EXT: Dict[str, str] +LANG_EXT: dict[str, str] class config(Command): description: str = ... # Tuple is full name, short name, description - user_options: Sequence[Tuple[str, str | None, str]] = ... + user_options: Sequence[tuple[str, str | None, str]] = ... compiler: str | CCompiler | None = ... cc: str | None = ... include_dirs: Sequence[str] | None = ... @@ -74,7 +74,7 @@ class config(Command): library_dirs: Sequence[str] | None = ..., headers: Sequence[str] | None = ..., include_dirs: Sequence[str] | None = ..., - other_libraries: List[str] = ..., + other_libraries: list[str] = ..., ) -> bool: ... def check_header( self, header: str, include_dirs: Sequence[str] | None = ..., library_dirs: Sequence[str] | None = ..., lang: str = ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi index bf3d0737f244..1bee1ed07e45 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi @@ -1,10 +1,10 @@ from distutils.cmd import Command -from typing import ClassVar, List, Tuple +from typing import ClassVar class install_egg_info(Command): description: ClassVar[str] - user_options: ClassVar[List[Tuple[str, str | None, str]]] + user_options: ClassVar[list[tuple[str, str | None, str]]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... - def get_outputs(self) -> List[str]: ... + def get_outputs(self) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi index 3835d9fd6ec6..005db872b0bf 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi @@ -1,8 +1,8 @@ from distutils.config import PyPIRCCommand -from typing import ClassVar, List, Tuple +from typing import ClassVar class upload(PyPIRCCommand): description: ClassVar[str] - boolean_options: ClassVar[List[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 index bcd626c81d48..5814a82841cc 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/config.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/config.pyi @@ -1,6 +1,6 @@ from abc import abstractmethod from distutils.cmd import Command -from typing import ClassVar, List, Tuple +from typing import ClassVar DEFAULT_PYPIRC: str @@ -9,8 +9,8 @@ class PyPIRCCommand(Command): DEFAULT_REALM: ClassVar[str] repository: None realm: None - user_options: ClassVar[List[Tuple[str, str | None, str]]] - boolean_options: ClassVar[List[str]] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/@python2/distutils/core.pyi b/mypy/typeshed/stdlib/@python2/distutils/core.pyi index 48bd7b5018bc..6564c9a86ded 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/core.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/core.pyi @@ -1,7 +1,7 @@ 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, Tuple, Type +from typing import Any, Mapping def setup( *, @@ -15,34 +15,34 @@ def setup( 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] = ..., + 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] = ..., + script_args: list[str] = ..., options: Mapping[str, Any] = ..., license: str = ..., - keywords: List[str] | str = ..., - platforms: List[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., - data_files: List[Tuple[str, List[str]]] = ..., + keywords: list[str] | str = ..., + platforms: 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]] = ..., + 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] = ..., + libraries: list[str] = ..., + headers: list[str] = ..., ext_package: str = ..., - include_dirs: List[str] = ..., + include_dirs: list[str] = ..., password: str = ..., fullname: str = ..., **attrs: Any, ) -> None: ... -def run_setup(script_name: str, script_args: List[str] | None = ..., stop_after: str = ...) -> Distribution: ... +def run_setup(script_name: str, script_args: list[str] | None = ..., stop_after: str = ...) -> Distribution: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi index 6f779d540e5e..929d6ffd0c81 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi @@ -1,5 +1,3 @@ -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: ... +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 index 4c4a22102558..ffe5ff1cfbd4 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi @@ -1,7 +1,5 @@ -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 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, @@ -11,5 +9,5 @@ def copy_tree( update: int = ..., verbose: int = ..., dry_run: int = ..., -) -> List[str]: ... +) -> 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 index adba8f093569..8e6eeafc15b3 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dist.pyi @@ -1,9 +1,9 @@ from distutils.cmd import Command -from typing import Any, Dict, Iterable, Mapping, Text, Tuple, Type +from typing import Any, Iterable, Mapping, Text class Distribution: - cmdclass: Dict[str, Type[Command]] + cmdclass: dict[str, type[Command]] def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... - def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... + def get_option_dict(self, command: str) -> dict[str, tuple[str, Text]]: ... def parse_config_files(self, filenames: Iterable[Text] | None = ...) -> None: ... def get_command_obj(self, command: str, create: bool = ...) -> Command | None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/extension.pyi b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi index 9335fad86418..cff84ef59b6b 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/extension.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi @@ -1,21 +1,19 @@ -from typing import List, Tuple - class Extension: def __init__( self, name: str, - sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, str | None]] = ..., - 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] = ..., + sources: list[str], + include_dirs: list[str] = ..., + define_macros: list[tuple[str, str | None]] = ..., + 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: str | None = ..., # undocumented - depends: List[str] = ..., + 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 index d0e3309c2d77..02301aed63f4 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi @@ -1,21 +1,21 @@ -from typing import Any, List, Mapping, Optional, Tuple, overload +from typing import Any, Mapping, Optional, overload -_Option = Tuple[str, Optional[str], str] -_GR = Tuple[List[str], OptionDummy] +_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: List[str] | None -) -> List[str] | _GR: ... -def wrap_text(text: str, width: int) -> List[str]: ... + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None +) -> list[str] | _GR: ... +def wrap_text(text: str, width: int) -> list[str]: ... class FancyGetopt: - def __init__(self, option_table: List[_Option] | None = ...) -> None: ... + def __init__(self, option_table: list[_Option] | None = ...) -> None: ... # TODO kinda wrong, `getopt(object=object())` is invalid @overload - def getopt(self, args: List[str] | None = ...) -> _GR: ... + def getopt(self, args: list[str] | None = ...) -> _GR: ... @overload - def getopt(self, args: List[str] | None, object: Any) -> List[str]: ... - def get_option_order(self) -> List[Tuple[str, str]]: ... - def generate_help(self, header: str | None = ...) -> List[str]: ... + def getopt(self, args: list[str] | None, object: Any) -> list[str]: ... + def get_option_order(self) -> list[tuple[str, str]]: ... + def generate_help(self, header: str | None = ...) -> list[str]: ... class OptionDummy: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi index cfe840e71040..a7f24105a678 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi @@ -1,4 +1,4 @@ -from typing import Sequence, Tuple +from typing import Sequence def copy_file( src: str, @@ -9,6 +9,6 @@ def copy_file( link: str | None = ..., verbose: bool = ..., dry_run: bool = ..., -) -> Tuple[str, str]: ... +) -> 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/spawn.pyi b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi index 0fffc5402c62..dda05ad7e85a 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi @@ -1,4 +1,2 @@ -from typing import List - -def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... +def spawn(cmd: list[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... def find_executable(executable: str, path: str | None = ...) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi index 26ba5a6fabb6..364bcf9ff154 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi @@ -1,4 +1,4 @@ -from typing import IO, List, Tuple +from typing import IO class TextFile: def __init__( @@ -15,7 +15,7 @@ class TextFile: ) -> None: ... def open(self, filename: str) -> None: ... def close(self) -> None: ... - def warn(self, msg: str, line: List[int] | Tuple[int, int] | int = ...) -> None: ... + def warn(self, msg: str, line: list[int] | tuple[int, int] | int = ...) -> None: ... def readline(self) -> str | None: ... - def readlines(self) -> List[str]: ... + def readlines(self) -> list[str]: ... def unreadline(self, line: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/util.pyi b/mypy/typeshed/stdlib/@python2/distutils/util.pyi index c0882d1dd1cb..935a695e58db 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/util.pyi @@ -1,17 +1,18 @@ -from typing import Any, Callable, List, Mapping, Tuple +from typing import Any, Callable, Mapping +from typing_extensions import Literal 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 split_quoted(s: str) -> list[str]: ... def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... + func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... ) -> None: ... -def strtobool(val: str) -> bool: ... +def strtobool(val: str) -> Literal[0, 1]: ... def byte_compile( - py_files: List[str], + py_files: list[str], optimize: int = ..., force: bool = ..., prefix: str | None = ..., diff --git a/mypy/typeshed/stdlib/@python2/distutils/version.pyi b/mypy/typeshed/stdlib/@python2/distutils/version.pyi index dd0969b8635f..b3bb9ea4909f 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/version.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/version.pyi @@ -1,14 +1,14 @@ +from _typeshed import Self from abc import abstractmethod -from typing import Pattern, Text, Tuple, TypeVar +from typing import Pattern, Text, TypeVar _T = TypeVar("_T", bound=Version) class Version: - def __repr__(self) -> str: ... @abstractmethod def __init__(self, vstring: Text | None = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: Text) -> _T: ... + def parse(self: Self, vstring: Text) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod @@ -16,18 +16,18 @@ class Version: class StrictVersion(Version): version_re: Pattern[str] - version: Tuple[int, int, int] - prerelease: Tuple[Text, int] | None + version: tuple[int, int, int] + prerelease: tuple[Text, int] | None def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... + def parse(self: Self, vstring: Text) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: Text - version: Tuple[Text | int, ...] + version: tuple[Text | int, ...] def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... + def parse(self: Self, vstring: Text) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/doctest.pyi b/mypy/typeshed/stdlib/@python2/doctest.pyi index 6c3b922244f4..9f95d122eea5 100644 --- a/mypy/typeshed/stdlib/@python2/doctest.pyi +++ b/mypy/typeshed/stdlib/@python2/doctest.pyi @@ -1,12 +1,12 @@ import types import unittest -from typing import Any, Callable, Dict, List, NamedTuple, Tuple, Type +from typing import Any, Callable, NamedTuple class TestResults(NamedTuple): failed: int attempted: int -OPTIONFLAGS_BY_NAME: Dict[str, int] +OPTIONFLAGS_BY_NAME: dict[str, int] def register_optionflag(name: str) -> int: ... @@ -34,7 +34,7 @@ class Example: exc_msg: str | None lineno: int indent: int - options: Dict[int, bool] + options: dict[int, bool] def __init__( self, source: str, @@ -42,21 +42,21 @@ class Example: exc_msg: str | None = ..., lineno: int = ..., indent: int = ..., - options: Dict[int, bool] | None = ..., + options: dict[int, bool] | None = ..., ) -> None: ... def __hash__(self) -> int: ... class DocTest: - examples: List[Example] - globs: Dict[str, Any] + examples: list[Example] + globs: dict[str, Any] name: str filename: str | None lineno: int | None docstring: str | None def __init__( self, - examples: List[Example], - globs: Dict[str, Any], + examples: list[Example], + globs: dict[str, Any], name: str, filename: str | None, lineno: int | None, @@ -66,9 +66,9 @@ class DocTest: def __lt__(self, other: DocTest) -> bool: ... class DocTestParser: - def parse(self, string: str, name: str = ...) -> List[str | Example]: ... - def get_doctest(self, string: str, globs: Dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... - def get_examples(self, string: str, name: str = ...) -> List[Example]: ... + def parse(self, string: str, name: str = ...) -> list[str | Example]: ... + def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... + def get_examples(self, string: str, name: str = ...) -> list[Example]: ... class DocTestFinder: def __init__( @@ -79,12 +79,12 @@ class DocTestFinder: obj: object, name: str | None = ..., module: None | bool | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., - ) -> List[DocTest]: ... + globs: dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., + ) -> list[DocTest]: ... _Out = Callable[[str], Any] -_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] +_ExcInfo = tuple[type[BaseException], BaseException, types.TracebackType] class DocTestRunner: DIVIDER: str @@ -127,11 +127,11 @@ master: DocTestRunner | None def testmod( m: types.ModuleType | None = ..., name: str | None = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., verbose: bool | None = ..., report: bool = ..., optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., raise_on_error: bool = ..., exclude_empty: bool = ..., ) -> TestResults: ... @@ -140,17 +140,17 @@ def testfile( module_relative: bool = ..., name: str | None = ..., package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., verbose: bool | None = ..., report: bool = ..., optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., raise_on_error: bool = ..., parser: DocTestParser = ..., encoding: str | None = ..., ) -> TestResults: ... def run_docstring_examples( - f: object, globs: Dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... + f: object, globs: dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... ) -> None: ... def set_unittest_reportflags(flags: int) -> int: ... @@ -182,8 +182,8 @@ _DocTestSuite = unittest.TestSuite def DocTestSuite( module: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., test_finder: DocTestFinder | None = ..., **options: Any, ) -> _DocTestSuite: ... @@ -196,7 +196,7 @@ def DocFileTest( path: str, module_relative: bool = ..., package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., parser: DocTestParser = ..., encoding: str | None = ..., **options: Any, @@ -204,6 +204,6 @@ def DocFileTest( def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... def script_from_examples(s: str) -> str: ... def testsource(module: None | str | types.ModuleType, name: str) -> str: ... -def debug_src(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... -def debug_script(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... +def debug_src(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... +def debug_script(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... def debug(module: None | str | types.ModuleType, name: str, pm: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dummy_thread.pyi b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi index 0a28b3aaeeb9..1bd324b7eaaf 100644 --- a/mypy/typeshed/stdlib/@python2/dummy_thread.pyi +++ b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Dict, NoReturn, Tuple +from typing import Any, Callable, NoReturn 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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi index 4245e3e0f980..308b296c4d53 100644 --- a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi @@ -1,7 +1,7 @@ from email.mime.nonmultipart import MIMENonMultipart -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEApplication(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi index d38bd58d0e43..349b61432eab 100644 --- a/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi +++ b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi @@ -1,11 +1,11 @@ import codecs -from typing import Text, Tuple +from typing import Text 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]: ... + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> tuple[Text, int]: ... class StreamWriter(codecs.StreamWriter): ... class StreamReader(codecs.StreamReader): ... diff --git a/mypy/typeshed/stdlib/@python2/filecmp.pyi b/mypy/typeshed/stdlib/@python2/filecmp.pyi index 0be5596c2bdb..c50faedf2fa1 100644 --- a/mypy/typeshed/stdlib/@python2/filecmp.pyi +++ b/mypy/typeshed/stdlib/@python2/filecmp.pyi @@ -1,11 +1,11 @@ -from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Sequence, Text, Tuple +from typing import AnyStr, Callable, Generic, Iterable, Sequence, Text -DEFAULT_IGNORES: List[str] +DEFAULT_IGNORES: list[str] def cmp(f1: bytes | Text, f2: bytes | Text, shallow: int | bool = ...) -> bool: ... def cmpfiles( a: AnyStr, b: AnyStr, common: Iterable[AnyStr], shallow: int | bool = ... -) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... +) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... class dircmp(Generic[AnyStr]): def __init__( @@ -16,22 +16,22 @@ class dircmp(Generic[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] + 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]] + methodmap: dict[str, Callable[[], None]] def phase0(self) -> None: ... def phase1(self) -> None: ... def phase2(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/fnmatch.pyi b/mypy/typeshed/stdlib/@python2/fnmatch.pyi index e933b7b2cb62..ead2dd5bf38e 100644 --- a/mypy/typeshed/stdlib/@python2/fnmatch.pyi +++ b/mypy/typeshed/stdlib/@python2/fnmatch.pyi @@ -1,8 +1,8 @@ -from typing import AnyStr, Iterable, List, Union +from typing import AnyStr, Iterable, 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 filter(names: Iterable[AnyStr], pattern: _EitherStr) -> list[AnyStr]: ... def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/formatter.pyi b/mypy/typeshed/stdlib/@python2/formatter.pyi index da165f2d55e3..f5d8348d08a1 100644 --- a/mypy/typeshed/stdlib/@python2/formatter.pyi +++ b/mypy/typeshed/stdlib/@python2/formatter.pyi @@ -1,8 +1,8 @@ -from typing import IO, Any, Iterable, List, Tuple +from typing import IO, Any, Iterable AS_IS: None -_FontType = Tuple[str, bool, bool, bool] -_StylesType = Tuple[Any, ...] +_FontType = tuple[str, bool, bool, bool] +_StylesType = tuple[Any, ...] class NullFormatter: writer: NullWriter | None @@ -28,9 +28,9 @@ class NullFormatter: class AbstractFormatter: writer: NullWriter align: str | None - align_stack: List[str | None] - font_stack: List[_FontType] - margin_stack: List[int] + align_stack: list[str | None] + font_stack: list[_FontType] + margin_stack: list[int] spacing: str | None style_stack: Any nospace: int @@ -68,7 +68,7 @@ class NullWriter: def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> 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: ... @@ -81,7 +81,7 @@ class AbstractWriter(NullWriter): def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> 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: ... diff --git a/mypy/typeshed/stdlib/@python2/fractions.pyi b/mypy/typeshed/stdlib/@python2/fractions.pyi index 872e20ede688..7835e9aa56b6 100644 --- a/mypy/typeshed/stdlib/@python2/fractions.pyi +++ b/mypy/typeshed/stdlib/@python2/fractions.pyi @@ -1,10 +1,10 @@ +from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Tuple, Type, TypeVar, Union, overload +from typing import Union, overload from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") @overload def gcd(a: int, b: int) -> int: ... @@ -18,10 +18,10 @@ def gcd(a: Integral, b: Integral) -> Integral: ... class Fraction(Rational): @overload def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + cls: type[Self], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... + ) -> Self: ... @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls: type[Self], __value: float | Decimal | str, *, _normalize: bool = ...) -> Self: ... @classmethod def from_float(cls, f: float) -> Fraction: ... @classmethod @@ -108,13 +108,13 @@ class Fraction(Rational): @overload def __rmod__(self, other: float) -> float: ... @overload - def __divmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... + def __divmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __divmod__(self, other: float) -> Tuple[float, Fraction]: ... + def __divmod__(self, other: float) -> tuple[float, Fraction]: ... @overload - def __rdivmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... + def __rdivmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __rdivmod__(self, other: float) -> Tuple[float, Fraction]: ... + def __rdivmod__(self, other: float) -> tuple[float, Fraction]: ... @overload def __pow__(self, other: int) -> Fraction: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/ftplib.pyi b/mypy/typeshed/stdlib/@python2/ftplib.pyi index 0931a9d171cd..b8c2bbd40371 100644 --- a/mypy/typeshed/stdlib/@python2/ftplib.pyi +++ b/mypy/typeshed/stdlib/@python2/ftplib.pyi @@ -1,10 +1,9 @@ from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext -from typing import Any, BinaryIO, Callable, List, Text, Tuple, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, Text, Union from typing_extensions import Literal -_T = TypeVar("_T") _IntOrStr = Union[int, Text] MSG_OOB: int @@ -18,7 +17,7 @@ class error_temp(Error): ... class error_perm(Error): ... class error_proto(Error): ... -all_errors: Tuple[Type[Exception], ...] +all_errors: tuple[type[Exception], ...] class FTP: debugging: int @@ -58,10 +57,10 @@ class FTP: 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 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: _IntOrStr | None = ...) -> Tuple[socket, int]: ... + def ntransfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> tuple[socket, int]: ... def transfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> socket: ... def retrbinary( self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: _IntOrStr | None = ... @@ -77,7 +76,7 @@ class FTP: def retrlines(self, cmd: Text, callback: Callable[[str], Any] | None = ...) -> str: ... def storlines(self, cmd: Text, fp: SupportsReadline[bytes], callback: Callable[[bytes], Any] | None = ...) -> str: ... def acct(self, password: Text) -> str: ... - def nlst(self, *args: Text) -> List[str]: ... + def nlst(self, *args: Text) -> list[str]: ... # Technically only the last arg can be a Callable but ... def dir(self, *args: str | Callable[[str], None]) -> None: ... def rename(self, fromname: Text, toname: Text) -> str: ... @@ -101,7 +100,7 @@ class FTP_TLS(FTP): certfile: str | None = ..., context: SSLContext | None = ..., timeout: float = ..., - source_address: Tuple[str, int] | None = ..., + source_address: tuple[str, int] | None = ..., ) -> None: ... ssl_version: int keyfile: str | None @@ -114,14 +113,14 @@ class FTP_TLS(FTP): class Netrc: def __init__(self, filename: Text | None = ...) -> None: ... - def get_hosts(self) -> List[str]: ... - def get_account(self, host: Text) -> Tuple[str | None, str | None, str | None]: ... - def get_macros(self) -> List[str]: ... - def get_macro(self, macro: Text) -> Tuple[str, ...]: ... + def get_hosts(self) -> list[str]: ... + def get_account(self, host: Text) -> tuple[str | None, str | None, str | None]: ... + def get_macros(self) -> list[str]: ... + def get_macro(self, macro: Text) -> tuple[str, ...]: ... def parse150(resp: str) -> int | None: ... # undocumented -def parse227(resp: str) -> Tuple[str, int]: ... # undocumented -def parse229(resp: str, peer: Any) -> Tuple[str, 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"] = ... diff --git a/mypy/typeshed/stdlib/@python2/functools.pyi b/mypy/typeshed/stdlib/@python2/functools.pyi index dd873708fea4..026a74faf6ff 100644 --- a/mypy/typeshed/stdlib/@python2/functools.pyi +++ b/mypy/typeshed/stdlib/@python2/functools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Generic, Iterable, Sequence, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Sequence, TypeVar, overload _AnyCallable = Callable[..., Any] @@ -19,12 +19,12 @@ def update_wrapper( def wraps( wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... ) -> Callable[[_AnyCallable], _AnyCallable]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... +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] + 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/gc.pyi b/mypy/typeshed/stdlib/@python2/gc.pyi index b1fb1acc07d2..0ee05387a5a8 100644 --- a/mypy/typeshed/stdlib/@python2/gc.pyi +++ b/mypy/typeshed/stdlib/@python2/gc.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, Tuple +from typing import Any def enable() -> None: ... def disable() -> None: ... @@ -6,15 +6,15 @@ def isenabled() -> bool: ... def collect(generation: int = ...) -> int: ... def set_debug(flags: int) -> None: ... def get_debug() -> int: ... -def get_objects() -> List[Any]: ... +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 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] +garbage: list[Any] DEBUG_STATS: int DEBUG_COLLECTABLE: int diff --git a/mypy/typeshed/stdlib/@python2/genericpath.pyi b/mypy/typeshed/stdlib/@python2/genericpath.pyi index ba29db4692bb..fecb3b70af42 100644 --- a/mypy/typeshed/stdlib/@python2/genericpath.pyi +++ b/mypy/typeshed/stdlib/@python2/genericpath.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsLessThanT -from typing import List, Sequence, Text, Tuple, Union, overload +from typing import Sequence, Text, Union, overload from typing_extensions import Literal # All overloads can return empty string. Ideally, Literal[""] would be a valid @@ -10,9 +10,9 @@ def commonprefix(m: Sequence[str]) -> str | Literal[""]: ... # type: ignore @overload def commonprefix(m: Sequence[Text]) -> Text: ... # type: ignore @overload -def commonprefix(m: Sequence[List[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[list[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... @overload -def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... def exists(path: Text) -> bool: ... def getsize(filename: Text) -> int: ... def isfile(path: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/getopt.pyi b/mypy/typeshed/stdlib/@python2/getopt.pyi index 370d4d5c1cba..b1e90a6c5a67 100644 --- a/mypy/typeshed/stdlib/@python2/getopt.pyi +++ b/mypy/typeshed/stdlib/@python2/getopt.pyi @@ -1,12 +1,9 @@ -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]]: ... +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/gettext.pyi b/mypy/typeshed/stdlib/@python2/gettext.pyi index a91234f6b2d3..02e306978160 100644 --- a/mypy/typeshed/stdlib/@python2/gettext.pyi +++ b/mypy/typeshed/stdlib/@python2/gettext.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Container, Dict, List, Sequence, Type +from typing import IO, Any, Container, Sequence def bindtextdomain(domain: str, localedir: str = ...) -> str: ... def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... @@ -22,7 +22,7 @@ class NullTranslations(object): def ngettext(self, singular: str, plural: str, n: int) -> str: ... def lngettext(self, singular: str, plural: str, n: int) -> str: ... def ungettext(self, singular: str | unicode, plural: str | unicode, n: int) -> unicode: ... - def info(self) -> Dict[str, str]: ... + def info(self) -> dict[str, str]: ... def charset(self) -> str | None: ... def output_charset(self) -> str | None: ... def set_output_charset(self, charset: str | None) -> None: ... @@ -34,12 +34,12 @@ class GNUTranslations(NullTranslations): def find( domain: str, localedir: str | None = ..., languages: Sequence[str] | None = ..., all: Any = ... -) -> str | List[str] | None: ... +) -> str | list[str] | None: ... def translation( domain: str, localedir: str | None = ..., languages: Sequence[str] | None = ..., - class_: Type[NullTranslations] | None = ..., + class_: type[NullTranslations] | None = ..., fallback: bool = ..., codeset: str | None = ..., ) -> NullTranslations: ... diff --git a/mypy/typeshed/stdlib/@python2/glob.pyi b/mypy/typeshed/stdlib/@python2/glob.pyi index f5a389a0ddfa..2fc01a03a48b 100644 --- a/mypy/typeshed/stdlib/@python2/glob.pyi +++ b/mypy/typeshed/stdlib/@python2/glob.pyi @@ -1,7 +1,7 @@ -from typing import AnyStr, Iterator, List +from typing import AnyStr, Iterator -def glob(pathname: AnyStr) -> List[AnyStr]: ... +def glob(pathname: AnyStr) -> list[AnyStr]: ... def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... -def glob1(dirname: str | unicode, pattern: AnyStr) -> List[AnyStr]: ... -def glob0(dirname: str | unicode, basename: AnyStr) -> List[AnyStr]: ... +def glob1(dirname: str | unicode, pattern: AnyStr) -> list[AnyStr]: ... +def glob0(dirname: str | unicode, basename: AnyStr) -> list[AnyStr]: ... def has_magic(s: str | unicode) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/grp.pyi b/mypy/typeshed/stdlib/@python2/grp.pyi index 6e937ec0f262..1651663eb242 100644 --- a/mypy/typeshed/stdlib/@python2/grp.pyi +++ b/mypy/typeshed/stdlib/@python2/grp.pyi @@ -1,12 +1,12 @@ import sys -from typing import List, NamedTuple +from typing import NamedTuple if sys.platform != "win32": class struct_group(NamedTuple): gr_name: str gr_passwd: str | None gr_gid: int - gr_mem: List[str] - def getgrall() -> List[struct_group]: ... + gr_mem: list[str] + def getgrall() -> list[struct_group]: ... def getgrgid(id: int) -> struct_group: ... def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/typeshed/stdlib/@python2/hashlib.pyi b/mypy/typeshed/stdlib/@python2/hashlib.pyi index 9c53d2b6b30d..8f881aaaf419 100644 --- a/mypy/typeshed/stdlib/@python2/hashlib.pyi +++ b/mypy/typeshed/stdlib/@python2/hashlib.pyi @@ -1,4 +1,4 @@ -from typing import Tuple, Union +from typing import Union _DataType = Union[str, unicode, bytearray, buffer, memoryview] @@ -25,8 +25,8 @@ 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, ...] +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 index 78ce6fd03928..5c393436d3c2 100644 --- a/mypy/typeshed/stdlib/@python2/heapq.pyi +++ b/mypy/typeshed/stdlib/@python2/heapq.pyi @@ -1,15 +1,15 @@ from _typeshed import SupportsLessThan -from typing import Callable, Iterable, List, TypeVar +from typing import Callable, Iterable, 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 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: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def _heapify_max(__x: List[_T]) -> None: ... # undocumented +def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> list[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> 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 index 749b3039dfc3..3fcc4be2d5a0 100644 --- a/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi +++ b/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi @@ -1,5 +1,3 @@ -from typing import Dict - -name2codepoint: Dict[str, int] -codepoint2name: Dict[int, str] -entitydefs: Dict[str, str] +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 index f2163818fae4..b72423fc8ea9 100644 --- a/mypy/typeshed/stdlib/@python2/httplib.pyi +++ b/mypy/typeshed/stdlib/@python2/httplib.pyi @@ -1,9 +1,9 @@ import mimetools -from typing import Any, Dict, Protocol +from typing import Any, Protocol class HTTPMessage(mimetools.Message): def addcontinue(self, key: str, more: str) -> None: ... - dict: Dict[str, str] + dict: dict[str, str] def addheader(self, key: str, value: str) -> None: ... unixfrom: str headers: Any @@ -151,7 +151,7 @@ class LineAndFileWrapper: # Constants -responses: Dict[int, str] +responses: dict[int, str] HTTP_PORT: int HTTPS_PORT: int diff --git a/mypy/typeshed/stdlib/@python2/imaplib.pyi b/mypy/typeshed/stdlib/@python2/imaplib.pyi index c4346851bdac..fc17ca0aaec1 100644 --- a/mypy/typeshed/stdlib/@python2/imaplib.pyi +++ b/mypy/typeshed/stdlib/@python2/imaplib.pyi @@ -1,33 +1,34 @@ import subprocess import time +from builtins import list as List # alias to avoid name clashes with `IMAP4.list` from socket import socket as _socket from ssl import SSLSocket -from typing import IO, Any, Callable, Dict, List, Pattern, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Pattern, Text, 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]] +# E.g. tuple[Literal["OK"], list[bytes]] +_CommandResults = tuple[str, list[Any]] -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] +_AnyResponseData = Union[list[None], list[Union[bytes, tuple[bytes, bytes]]]] class IMAP4: - error: Type[Exception] = ... - abort: Type[Exception] = ... - readonly: Type[Exception] = ... + error: type[Exception] = ... + abort: type[Exception] = ... + readonly: type[Exception] = ... mustquote: Pattern[Text] = ... debug: int = ... state: str = ... literal: Text | None = ... - tagged_commands: Dict[bytes, List[bytes] | None] - untagged_responses: Dict[str, List[bytes | Tuple[bytes, bytes]]] + tagged_commands: dict[bytes, List[bytes] | None] + untagged_responses: dict[str, List[bytes | tuple[bytes, bytes]]] continuation_response: str = ... is_readonly: bool = ... tagnum: int = ... tagpre: str = ... tagre: Pattern[Text] = ... welcome: bytes = ... - capabilities: Tuple[str] = ... + capabilities: tuple[str, ...] = ... PROTOCOL_VERSION: str = ... def __init__(self, host: str = ..., port: int = ...) -> None: ... def open(self, host: str = ..., port: int = ...) -> None: ... @@ -44,7 +45,7 @@ class IMAP4: 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], bytes | None]) -> Tuple[str, str]: ... + def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: ... def capability(self) -> _CommandResults: ... def check(self) -> _CommandResults: ... def close(self) -> _CommandResults: ... @@ -53,24 +54,24 @@ class IMAP4: def delete(self, mailbox: str) -> _CommandResults: ... def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def expunge(self) -> _CommandResults: ... - def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... + def 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 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 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 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: str | None, *criteria: str) -> _CommandResults: ... - def select(self, mailbox: str = ..., readonly: bool = ...) -> Tuple[str, List[bytes | None]]: ... + def select(self, mailbox: str = ..., readonly: bool = ...) -> tuple[str, List[bytes | None]]: ... def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... def setannotation(self, *args: str) -> _CommandResults: ... def setquota(self, root: str, limits: str) -> _CommandResults: ... @@ -126,5 +127,5 @@ class _Authenticator: def Internaldate2tuple(resp: str) -> time.struct_time: ... def Int2AP(num: int) -> str: ... -def ParseFlags(resp: str) -> Tuple[str]: ... +def ParseFlags(resp: str) -> tuple[str, ...]: ... def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/imghdr.pyi b/mypy/typeshed/stdlib/@python2/imghdr.pyi index d60cafa4c78f..dcfc3506fb9a 100644 --- a/mypy/typeshed/stdlib/@python2/imghdr.pyi +++ b/mypy/typeshed/stdlib/@python2/imghdr.pyi @@ -1,4 +1,4 @@ -from typing import Any, BinaryIO, Callable, List, Protocol, Text, Union, overload +from typing import Any, BinaryIO, Callable, Protocol, Text, Union, overload class _ReadableBinary(Protocol): def tell(self) -> int: ... @@ -12,4 +12,4 @@ def what(file: _File, h: None = ...) -> str | None: ... @overload def what(file: Any, h: bytes) -> str | None: ... -tests: List[Callable[[bytes, BinaryIO | None], str | None]] +tests: list[Callable[[bytes, BinaryIO | None], str | None]] diff --git a/mypy/typeshed/stdlib/@python2/imp.pyi b/mypy/typeshed/stdlib/@python2/imp.pyi index 128bd900e996..15d689249563 100644 --- a/mypy/typeshed/stdlib/@python2/imp.pyi +++ b/mypy/typeshed/stdlib/@python2/imp.pyi @@ -1,5 +1,5 @@ import types -from typing import IO, Any, Iterable, List, Tuple +from typing import IO, Any, Iterable C_BUILTIN: int C_EXTENSION: int @@ -13,16 +13,16 @@ PY_SOURCE: int SEARCH_ERROR: int def acquire_lock() -> None: ... -def find_module(name: str, path: Iterable[str] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]] | None: ... +def find_module(name: str, path: Iterable[str] = ...) -> tuple[IO[Any], str, tuple[str, str, int]] | None: ... def get_magic() -> str: ... -def get_suffixes() -> List[Tuple[str, str, int]]: ... +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_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: ... diff --git a/mypy/typeshed/stdlib/@python2/inspect.pyi b/mypy/typeshed/stdlib/@python2/inspect.pyi index c6118ea8aebb..aa0450ce6785 100644 --- a/mypy/typeshed/stdlib/@python2/inspect.pyi +++ b/mypy/typeshed/stdlib/@python2/inspect.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple, Type, Union +from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence, Union # Types and members class EndOfBlock(Exception): ... @@ -11,7 +11,7 @@ class BlockFinder: passline: bool last: int def tokeneater( - self, type: int, token: AnyStr, srow_scol: Tuple[int, int], erow_ecol: Tuple[int, int], line: AnyStr + self, type: int, token: AnyStr, srow_scol: tuple[int, int], erow_ecol: tuple[int, int], line: AnyStr ) -> None: ... CO_GENERATOR: int @@ -29,7 +29,7 @@ class ModuleInfo(NamedTuple): mode: str module_type: int -def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> List[Tuple[str, Any]]: ... +def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> list[tuple[str, Any]]: ... def getmoduleinfo(path: str | unicode) -> ModuleInfo | None: ... def getmodulename(path: AnyStr) -> AnyStr | None: ... def ismodule(object: object) -> bool: ... @@ -50,9 +50,9 @@ 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]] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType) -> str: ... def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... def getdoc(object: object) -> str | None: ... @@ -60,28 +60,28 @@ def getcomments(object: object) -> str | None: ... def getfile(object: _SourceObjectType) -> str: ... def getmodule(object: object) -> ModuleType | None: ... def getsourcefile(object: _SourceObjectType) -> str | None: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: AnyStr) -> AnyStr: ... def indentsize(line: str | unicode) -> int: ... # Classes and functions -def getclasstree(classes: List[type], unique: bool = ...) -> List[Tuple[type, Tuple[type, ...]] | List[Any]]: ... +def getclasstree(classes: list[type], unique: bool = ...) -> list[tuple[type, tuple[type, ...]] | list[Any]]: ... class ArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: str | None keywords: str | None - defaults: Tuple[Any, ...] + defaults: tuple[Any, ...] class ArgInfo(NamedTuple): - args: List[str] + args: list[str] varargs: str | None keywords: str | None - locals: Dict[str, Any] + locals: dict[str, Any] class Arguments(NamedTuple): - args: List[str | List[Any]] + args: list[str | list[Any]] varargs: str | None keywords: str | None @@ -94,8 +94,8 @@ def formatargspec( 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]: ... +def getmro(cls: type) -> tuple[type, ...]: ... +def getcallargs(func, *args, **kwds) -> dict[str, Any]: ... # The interpreter stack @@ -103,18 +103,18 @@ class Traceback(NamedTuple): filename: str lineno: int function: str - code_context: List[str] | None + code_context: list[str] | None index: int | None # type: ignore -_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] +_FrameInfo = tuple[FrameType, str, int, str, Optional[list[str]], Optional[int]] -def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... +def getouterframes(frame: FrameType, context: int = ...) -> list[_FrameInfo]: ... def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... -def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... +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]: ... +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. @@ -126,4 +126,4 @@ class Attribute(NamedTuple): defining_class: type object: _Object -def classify_class_attrs(cls: type) -> List[Attribute]: ... +def classify_class_attrs(cls: type) -> list[Attribute]: ... diff --git a/mypy/typeshed/stdlib/@python2/itertools.pyi b/mypy/typeshed/stdlib/@python2/itertools.pyi index 12996d44628b..6509213e1625 100644 --- a/mypy/typeshed/stdlib/@python2/itertools.pyi +++ b/mypy/typeshed/stdlib/@python2/itertools.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable, Generic, Iterable, Iterator, Sequence, Tuple, TypeVar, overload +from _typeshed import Self +from typing import Any, Callable, Generic, Iterable, Iterator, Sequence, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") @@ -8,14 +9,14 @@ def count(start: int = ..., step: int = ...) -> Iterator[int]: ... # more gener class cycle(Iterator[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T]) -> None: ... def next(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... 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]: ... + def __iter__(self: Self) -> Self: ... @staticmethod def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... @@ -24,9 +25,9 @@ def dropwhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterato def ifilter(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... def ifilterfalse(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... @overload -def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +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]]]: ... +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[tuple[_S, Iterator[_T]]]: ... @overload def islice(iterable: Iterable[_T], stop: int | None) -> Iterator[_T]: ... @overload @@ -88,21 +89,21 @@ def imap( ) -> 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], ...]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> tuple[Iterator[_T], ...]: ... @overload -def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +def izip(iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... @overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> 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]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def izip( iter1: Iterable[_T1], @@ -111,7 +112,7 @@ def izip( iter4: Iterable[_T4], iter5: Iterable[_T5], iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def izip( iter1: Iterable[Any], @@ -122,22 +123,22 @@ def izip( iter6: Iterable[Any], iter7: Iterable[Any], *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... +) -> Iterator[tuple[Any, ...]]: ... def izip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... @overload -def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +def product(iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... @overload -def product(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +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]]: ... +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]]: ... +) -> 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]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def product( iter1: Iterable[_T1], @@ -146,7 +147,7 @@ def product( iter4: Iterable[_T4], iter5: Iterable[_T5], iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def product( iter1: Iterable[Any], @@ -157,9 +158,9 @@ def product( iter6: Iterable[Any], iter7: Iterable[Any], *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... +) -> Iterator[tuple[Any, ...]]: ... @overload -def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... +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 index bfbddb2a6835..fa6fdc49b9a9 100644 --- a/mypy/typeshed/stdlib/@python2/json.pyi +++ b/mypy/typeshed/stdlib/@python2/json.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Dict, List, Text, Tuple, Type +from typing import IO, Any, Callable, Text def dumps( obj: Any, @@ -7,9 +7,9 @@ def dumps( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: int | None = ..., - separators: Tuple[str, str] | None = ..., + separators: tuple[str, str] | None = ..., encoding: str = ..., default: Callable[[Any], Any] | None = ..., sort_keys: bool = ..., @@ -22,9 +22,9 @@ def dump( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: int | None = ..., - separators: Tuple[str, str] | None = ..., + separators: tuple[str, str] | None = ..., encoding: str = ..., default: Callable[[Any], Any] | None = ..., sort_keys: bool = ..., @@ -33,23 +33,23 @@ def dump( def loads( s: Text | bytes, encoding: Any = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., + cls: type[JSONDecoder] | None = ..., + object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., **kwds: Any, ) -> Any: ... def load( fp: SupportsRead[Text | bytes], encoding: str | None = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., + cls: type[JSONDecoder] | None = ..., + object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., **kwds: Any, ) -> Any: ... @@ -65,7 +65,7 @@ class JSONDecoder(object): object_pairs_hook: Callable[..., Any] = ..., ) -> None: ... def decode(self, s: Text | bytes, _w: Any = ...) -> Any: ... - def raw_decode(self, s: Text | bytes, idx: int = ...) -> Tuple[Any, Any]: ... + def raw_decode(self, s: Text | bytes, idx: int = ...) -> tuple[Any, Any]: ... class JSONEncoder(object): item_separator: str @@ -84,7 +84,7 @@ class JSONEncoder(object): allow_nan: bool = ..., sort_keys: bool = ..., indent: int | None = ..., - separators: Tuple[Text | bytes, Text | bytes] = ..., + separators: tuple[Text | bytes, Text | bytes] = ..., encoding: Text | bytes = ..., default: Callable[..., Any] = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi index 6ec97ce849d2..32eed63d42f9 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi @@ -1,26 +1,25 @@ -from _typeshed import StrPath -from typing import Dict, List, Optional, Text, Tuple, TypeVar +from _typeshed import Self, StrPath +from typing import Optional, Text -_P = TypeVar("_P") -_Label = Tuple[int, Optional[Text]] -_DFA = List[List[Tuple[int, int]]] -_DFAS = Tuple[_DFA, Dict[int, int]] +_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] + 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 copy(self: Self) -> Self: ... def report(self) -> None: ... opmap_raw: Text -opmap: Dict[Text, Text] +opmap: dict[Text, Text] diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi index 160d6fd76f76..c7a219b5f9af 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi @@ -1,6 +1,6 @@ -from typing import Dict, Match, Text +from typing import Match, Text -simple_escapes: Dict[Text, Text] +simple_escapes: dict[Text, Text] def escape(m: Match[str]) -> Text: ... def evalString(s: Text) -> Text: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi index eed165db551c..be66a8e21e7e 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi @@ -1,6 +1,6 @@ from lib2to3.pgen2.grammar import _DFAS, Grammar from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, List, Sequence, Set, Text, Tuple +from typing import Any, Sequence, Text _Context = Sequence[Any] @@ -14,9 +14,9 @@ class ParseError(Exception): class Parser: grammar: Grammar convert: _Convert - stack: List[Tuple[_DFAS, int, _RawNode]] + stack: list[tuple[_DFAS, int, _RawNode]] rootnode: _NL | None - used_names: Set[Text] + used_names: set[Text] def __init__(self, grammar: Grammar, convert: _Convert | None = ...) -> None: ... def setup(self, start: int | None = ...) -> None: ... def addtoken(self, type: int, value: Text | None, context: _Context) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi index 67dbbccdd4a6..daddcf0cf113 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from lib2to3.pgen2 import grammar from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Text, Tuple +from typing import IO, Any, Iterable, Iterator, NoReturn, Text class PgenGrammar(grammar.Grammar): ... @@ -9,38 +9,38 @@ class ParserGenerator: filename: StrPath stream: IO[Text] generator: Iterator[_TokenInfo] - first: Dict[Text, Dict[Text, int]] + first: dict[Text, dict[Text, int]] def __init__(self, filename: StrPath, stream: IO[Text] | None = ...) -> None: ... def make_grammar(self) -> PgenGrammar: ... - def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... + 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 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 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: Any | None = ...) -> Text: ... def gettoken(self) -> None: ... def raise_error(self, msg: str, *args: Any) -> NoReturn: ... class NFAState: - arcs: List[Tuple[Text | None, NFAState]] + arcs: list[tuple[Text | None, NFAState]] def __init__(self) -> None: ... def addarc(self, next: NFAState, label: Text | None = ...) -> None: ... class DFAState: - nfaset: Dict[NFAState, Any] + nfaset: dict[NFAState, Any] isfinal: bool - arcs: Dict[Text, DFAState] - def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... + 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 __eq__(self, other: DFAState) -> bool: ... # type: ignore[override] def generate_grammar(filename: StrPath = ...) -> PgenGrammar: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi index 3f4e41d49bd5..967c4df5d721 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi @@ -1,4 +1,4 @@ -from typing import Dict, Text +from typing import Text ENDMARKER: int NAME: int @@ -56,7 +56,7 @@ NL: int ERRORTOKEN: int N_TOKENS: int NT_OFFSET: int -tok_name: Dict[int, Text] +tok_name: dict[int, Text] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi index 477341c1a54e..d93d3f482766 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi @@ -1,9 +1,9 @@ from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, List, Text, Tuple +from typing import Callable, Iterable, Iterator, Text -_Coord = Tuple[int, int] +_Coord = tuple[int, int] _TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] -_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] +_TokenInfo = tuple[int, Text, _Coord, _Coord, Text] class TokenError(Exception): ... class StopTokenizing(Exception): ... @@ -11,13 +11,13 @@ class StopTokenizing(Exception): ... def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... class Untokenizer: - tokens: List[Text] + 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 compat(self, token: tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi index 27c64853329e..130f03dabdb7 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi @@ -1,11 +1,12 @@ +from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Text, TypeVar, Union _P = TypeVar("_P") _NL = Union[Node, Leaf] -_Context = Tuple[Text, int, int] -_Results = Dict[Text, _NL] -_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] +_Context = tuple[Text, int, int] +_Results = dict[Text, _NL] +_RawNode = tuple[int, Text, _Context, Optional[list[_NL]]] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int @@ -16,15 +17,15 @@ class Base: type: int parent: Node | None prefix: Text - children: List[_NL] + children: list[_NL] was_changed: bool was_checked: bool - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... + def clone(self: Self) -> Self: ... def post_order(self) -> Iterator[_NL]: ... def pre_order(self) -> Iterator[_NL]: ... - def replace(self, new: _NL | List[_NL]) -> None: ... + def replace(self, new: _NL | list[_NL]) -> None: ... def get_lineno(self) -> int: ... def changed(self) -> None: ... def remove(self) -> int | None: ... @@ -39,14 +40,14 @@ class Base: def set_prefix(self, prefix: Text) -> None: ... class Node(Base): - fixers_applied: List[Any] + fixers_applied: list[Any] def __init__( self, type: int, - children: List[_NL], + children: list[_NL], context: Any | None = ..., prefix: Text | None = ..., - fixers_applied: List[Any] | None = ..., + fixers_applied: list[Any] | None = ..., ) -> None: ... def set_child(self, i: int, child: _NL) -> None: ... def insert_child(self, i: int, child: _NL) -> None: ... @@ -56,9 +57,9 @@ class Leaf(Base): lineno: int column: int value: Text - fixers_applied: List[Any] + fixers_applied: list[Any] def __init__( - self, type: int, value: Text, context: _Context | None = ..., prefix: Text | None = ..., fixers_applied: List[Any] = ... + self, type: int, value: Text, context: _Context | None = ..., prefix: Text | None = ..., fixers_applied: list[Any] = ... ) -> None: ... def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... @@ -69,8 +70,8 @@ class BasePattern: name: Text | None def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns def match(self, node: _NL, results: _Results | None = ...) -> bool: ... - def match_seq(self, nodes: List[_NL], results: _Results | None = ...) -> bool: ... - def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... + def match_seq(self, nodes: list[_NL], results: _Results | None = ...) -> bool: ... + def generate_matches(self, nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... class LeafPattern(BasePattern): def __init__(self, type: int | None = ..., content: Text | None = ..., name: Text | None = ...) -> None: ... @@ -87,4 +88,4 @@ class WildcardPattern(BasePattern): class NegatedPattern(BasePattern): def __init__(self, content: Text | None = ...) -> None: ... -def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... +def generate_matches(patterns: list[BasePattern], nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... diff --git a/mypy/typeshed/stdlib/@python2/linecache.pyi b/mypy/typeshed/stdlib/@python2/linecache.pyi index 8628a0c58adc..68c907499867 100644 --- a/mypy/typeshed/stdlib/@python2/linecache.pyi +++ b/mypy/typeshed/stdlib/@python2/linecache.pyi @@ -1,9 +1,9 @@ -from typing import Any, Dict, List, Text +from typing import Any, Text -_ModuleGlobals = Dict[str, Any] +_ModuleGlobals = dict[str, Any] def getline(filename: Text, lineno: int, module_globals: _ModuleGlobals | None = ...) -> str: ... def clearcache() -> None: ... -def getlines(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... +def getlines(filename: Text, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... def checkcache(filename: Text | None = ...) -> None: ... -def updatecache(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... +def updatecache(filename: Text, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/locale.pyi b/mypy/typeshed/stdlib/@python2/locale.pyi index 21a7da166e29..c75d865b8746 100644 --- a/mypy/typeshed/stdlib/@python2/locale.pyi +++ b/mypy/typeshed/stdlib/@python2/locale.pyi @@ -1,7 +1,7 @@ # workaround for mypy#2010 from __builtin__ import str as _str from decimal import Decimal -from typing import Any, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple +from typing import Any, Callable, Iterable, Mapping, Sequence CODESET: int D_T_FMT: int @@ -75,9 +75,9 @@ CHAR_MAX: int class Error(Exception): ... def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... -def localeconv() -> Mapping[_str, int | _str | List[int]]: ... +def localeconv() -> Mapping[_str, int | _str | list[int]]: ... def nl_langinfo(__key: int) -> _str: ... -def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[_str | None, _str | None]: ... +def getdefaultlocale(envvars: tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... def getlocale(category: int = ...) -> Sequence[_str]: ... def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... def normalize(localename: _str) -> _str: ... @@ -91,6 +91,6 @@ 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 +locale_alias: dict[_str, _str] # undocumented +locale_encoding_alias: dict[_str, _str] # undocumented +windows_locale: dict[int, _str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi index f981e2400624..9ca64dc966ae 100644 --- a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -2,27 +2,11 @@ import threading from _typeshed import StrPath, SupportsWrite from time import struct_time from types import FrameType, TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Generic, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) +from typing import IO, Any, Callable, Generic, Mapping, MutableMapping, Optional, Sequence, Text, TypeVar, Union, overload -_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type, BaseException, Optional[TracebackType]], tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType] -_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] +_ArgsType = Union[tuple[Any, ...], Mapping[str, Any]] _FilterType = Union[Filter, Callable[[LogRecord], int]] _Level = Union[int, Text] @@ -34,10 +18,10 @@ _srcfile: str | None def currentframe() -> FrameType: ... -_levelNames: Dict[int | str, str | int] # Union[int:str, str:int] +_levelNames: dict[int | str, str | int] # Union[int:str, str:int] class Filterer(object): - filters: List[Filter] + filters: list[Filter] def __init__(self) -> None: ... def addFilter(self, filter: _FilterType) -> None: ... def removeFilter(self, filter: _FilterType) -> None: ... @@ -48,7 +32,7 @@ class Logger(Filterer): level: int parent: Logger | PlaceHolder propagate: bool - handlers: List[Handler] + handlers: list[Handler] disabled: int def __init__(self, name: str, level: _Level = ...) -> None: ... def setLevel(self, level: _Level) -> None: ... @@ -56,35 +40,35 @@ class Logger(Filterer): def getEffectiveLevel(self) -> int: ... def getChild(self, suffix: str) -> Logger: ... def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... warn = warning def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... fatal = critical def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def _log( - self, level: int, msg: Any, args: _ArgsType, exc_info: _ExcInfoType | None = ..., extra: Dict[str, Any] | None = ... + self, level: int, msg: Any, args: _ArgsType, exc_info: _ExcInfoType | None = ..., extra: dict[str, Any] | None = ... ) -> None: ... # undocumented def filter(self, record: LogRecord) -> bool: ... def addHandler(self, hdlr: Handler) -> None: ... def removeHandler(self, hdlr: Handler) -> None: ... - def findCaller(self) -> Tuple[str, int, str]: ... + def findCaller(self) -> tuple[str, int, str]: ... def handle(self, record: LogRecord) -> None: ... def makeRecord( self, @@ -181,27 +165,27 @@ class LoggerAdapter(Generic[_L]): logger: _L extra: Mapping[str, Any] def __init__(self, logger: _L, extra: Mapping[str, Any]) -> None: ... - def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def isEnabledFor(self, level: int) -> bool: ... @@ -210,17 +194,17 @@ def getLogger() -> Logger: ... @overload def getLogger(name: Text | str) -> Logger: ... def getLoggerClass() -> type: ... -def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... warn = warning -def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... def log( - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... fatal = critical diff --git a/mypy/typeshed/stdlib/@python2/logging/config.pyi b/mypy/typeshed/stdlib/@python2/logging/config.pyi index 03707bb98f55..5597347d0961 100644 --- a/mypy/typeshed/stdlib/@python2/logging/config.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/config.pyi @@ -1,10 +1,10 @@ from _typeshed import StrPath from threading import Thread -from typing import IO, Any, Dict +from typing import IO, Any _Path = StrPath -def dictConfig(config: Dict[str, Any]) -> None: ... -def fileConfig(fname: str | IO[str], defaults: Dict[str, str] | None = ..., disable_existing_loggers: bool = ...) -> None: ... +def dictConfig(config: dict[str, Any]) -> None: ... +def fileConfig(fname: str | IO[str], defaults: dict[str, str] | None = ..., disable_existing_loggers: bool = ...) -> None: ... def listen(port: int = ...) -> Thread: ... def stopListening() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi index d18d57e77af4..360e76c66558 100644 --- a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from logging import FileHandler, Handler, LogRecord from socket import SocketKind, SocketType -from typing import Any, ClassVar, Dict, List, Tuple +from typing import Any, ClassVar DEFAULT_TCP_LOGGING_PORT: int DEFAULT_UDP_LOGGING_PORT: int @@ -84,14 +84,14 @@ class SysLogHandler(Handler): LOG_LOCAL5: int LOG_LOCAL6: int LOG_LOCAL7: int - address: Tuple[str, int] | str # undocumented + address: tuple[str, int] | str # undocumented unixsocket: bool # undocumented socktype: SocketKind # 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: Tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... + 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: tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... def encodePriority(self, facility: int | str, priority: int | str) -> int: ... def mapPriority(self, levelName: str) -> str: ... @@ -106,17 +106,17 @@ class SMTPHandler(Handler): # TODO `secure` can also be an empty tuple def __init__( self, - mailhost: str | Tuple[str, int], + mailhost: str | tuple[str, int], fromaddr: str, - toaddrs: List[str], + toaddrs: list[str], subject: str, - credentials: Tuple[str, str] | None = ..., - secure: Tuple[str] | Tuple[str, str] | None = ..., + credentials: tuple[str, str] | None = ..., + secure: tuple[str] | tuple[str, str] | None = ..., ) -> None: ... def getSubject(self, record: LogRecord) -> str: ... class BufferingHandler(Handler): - buffer: List[LogRecord] + buffer: list[LogRecord] def __init__(self, capacity: int) -> None: ... def shouldFlush(self, record: LogRecord) -> bool: ... @@ -126,4 +126,4 @@ class MemoryHandler(BufferingHandler): class HTTPHandler(Handler): def __init__(self, host: str, url: str, method: str = ...) -> None: ... - def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... + def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/macpath.pyi b/mypy/typeshed/stdlib/@python2/macpath.pyi index bcb882e23eef..73d55b15328f 100644 --- a/mypy/typeshed/stdlib/@python2/macpath.pyi +++ b/mypy/typeshed/stdlib/@python2/macpath.pyi @@ -27,7 +27,7 @@ from posixpath import ( splitext as splitext, supports_unicode_filenames as supports_unicode_filenames, ) -from typing import AnyStr, Text, Tuple, overload +from typing import AnyStr, Text, overload altsep: str | None @@ -52,4 +52,4 @@ def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload def join(__p1: Text, *p: Text) -> Text: ... -def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(s: AnyStr) -> tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/mailbox.pyi b/mypy/typeshed/stdlib/@python2/mailbox.pyi index 18a66fa964c4..9c4aa66cdbb7 100644 --- a/mypy/typeshed/stdlib/@python2/mailbox.pyi +++ b/mypy/typeshed/stdlib/@python2/mailbox.pyi @@ -5,17 +5,13 @@ from typing import ( Any, AnyStr, Callable, - Dict, Generic, Iterable, Iterator, - List, Mapping, Protocol, Sequence, Text, - Tuple, - Type, TypeVar, Union, overload, @@ -27,10 +23,10 @@ _MessageT = TypeVar("_MessageT", bound=Message) _MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] class _HasIteritems(Protocol): - def iteritems(self) -> Iterator[Tuple[str, _MessageData]]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... class _HasItems(Protocol): - def items(self) -> Iterator[Tuple[str, _MessageData]]: ... + def items(self) -> Iterator[tuple[str, _MessageData]]: ... linesep: bytes @@ -55,12 +51,12 @@ class Mailbox(Generic[_MessageT]): # 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 keys(self) -> list[str]: ... def itervalues(self) -> Iterator[_MessageT]: ... def __iter__(self) -> Iterator[_MessageT]: ... - def values(self) -> List[_MessageT]: ... - def iteritems(self) -> Iterator[Tuple[str, _MessageT]]: ... - def items(self) -> List[Tuple[str, _MessageT]]: ... + def 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: ... @@ -68,8 +64,8 @@ class Mailbox(Generic[_MessageT]): def pop(self, key: str, default: None = ...) -> _MessageT | None: ... @overload def pop(self, key: str, default: _T = ...) -> _MessageT | _T: ... - def popitem(self) -> Tuple[str, _MessageT]: ... - def update(self, arg: _HasIteritems | _HasItems | Iterable[Tuple[str, _MessageData]] | None = ...) -> None: ... + def popitem(self) -> tuple[str, _MessageT]: ... + def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = ...) -> None: ... def flush(self) -> None: ... def lock(self) -> None: ... def unlock(self) -> None: ... @@ -80,7 +76,7 @@ class Maildir(Mailbox[MaildirMessage]): colon: str def __init__(self, dirname: Text, factory: Callable[[IO[Any]], MaildirMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... + 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: ... @@ -103,18 +99,18 @@ class MMDF(_mboxMMDF[MMDFMessage]): class MH(Mailbox[MHMessage]): def __init__(self, path: Text, factory: Callable[[IO[Any]], MHMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... + def list_folders(self) -> list[str]: ... def get_folder(self, folder: Text) -> MH: ... def add_folder(self, folder: Text) -> MH: ... def remove_folder(self, folder: Text) -> None: ... - def get_sequences(self) -> Dict[str, List[int]]: ... + def get_sequences(self) -> dict[str, list[int]]: ... def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): def __init__(self, path: Text, factory: Callable[[IO[Any]], BabylMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> IO[bytes]: ... - def get_labels(self) -> List[str]: ... + def get_labels(self) -> list[str]: ... class Message(email.message.Message): def __init__(self, message: _MessageData | None = ...) -> None: ... @@ -133,7 +129,7 @@ class MaildirMessage(Message): class _mboxMMDFMessage(Message): def get_from(self) -> str: ... - def set_from(self, from_: str, time_: bool | Tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... + def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... def get_flags(self) -> str: ... def set_flags(self, flags: Iterable[str]) -> None: ... def add_flag(self, flag: str) -> None: ... @@ -142,13 +138,13 @@ class _mboxMMDFMessage(Message): class mboxMessage(_mboxMMDFMessage): ... class MHMessage(Message): - def get_sequences(self) -> List[str]: ... + 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 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: ... @@ -163,13 +159,13 @@ class _ProxyFile(Generic[AnyStr]): def read(self, size: int | None = ...) -> AnyStr: ... def read1(self, size: int | None = ...) -> AnyStr: ... def readline(self, size: int | None = ...) -> AnyStr: ... - def readlines(self, sizehint: int | None = ...) -> List[AnyStr]: ... + def readlines(self, sizehint: int | None = ...) -> 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: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/mailcap.pyi b/mypy/typeshed/stdlib/@python2/mailcap.pyi index b29854f3c744..56218d1370fe 100644 --- a/mypy/typeshed/stdlib/@python2/mailcap.pyi +++ b/mypy/typeshed/stdlib/@python2/mailcap.pyi @@ -1,8 +1,8 @@ -from typing import Dict, List, Mapping, Sequence, Tuple, Union +from typing import Mapping, Sequence, Union -_Cap = Dict[str, Union[str, int]] +_Cap = dict[str, Union[str, int]] def findmatch( - caps: Mapping[str, List[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... -) -> Tuple[str | None, _Cap | None]: ... -def getcaps() -> Dict[str, List[_Cap]]: ... + caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... +) -> tuple[str | None, _Cap | None]: ... +def getcaps() -> dict[str, list[_Cap]]: ... diff --git a/mypy/typeshed/stdlib/@python2/markupbase.pyi b/mypy/typeshed/stdlib/@python2/markupbase.pyi index 727daaacf25e..869c341b66aa 100644 --- a/mypy/typeshed/stdlib/@python2/markupbase.pyi +++ b/mypy/typeshed/stdlib/@python2/markupbase.pyi @@ -1,8 +1,6 @@ -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 getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/math.pyi b/mypy/typeshed/stdlib/@python2/math.pyi index caddcedd864b..643242a73fa9 100644 --- a/mypy/typeshed/stdlib/@python2/math.pyi +++ b/mypy/typeshed/stdlib/@python2/math.pyi @@ -1,4 +1,4 @@ -from typing import Iterable, SupportsFloat, SupportsInt, Tuple +from typing import Iterable, SupportsFloat, SupportsInt e: float pi: float @@ -23,7 +23,7 @@ def fabs(__x: SupportsFloat) -> float: ... def factorial(__x: SupportsInt) -> int: ... def floor(__x: SupportsFloat) -> float: ... def fmod(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def frexp(__x: SupportsFloat) -> Tuple[float, int]: ... +def frexp(__x: SupportsFloat) -> tuple[float, int]: ... def fsum(__seq: Iterable[float]) -> float: ... def gamma(__x: SupportsFloat) -> float: ... def hypot(__x: SupportsFloat, __y: SupportsFloat) -> float: ... @@ -34,7 +34,7 @@ def lgamma(__x: SupportsFloat) -> float: ... def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... def log10(__x: SupportsFloat) -> float: ... def log1p(__x: SupportsFloat) -> float: ... -def modf(__x: SupportsFloat) -> Tuple[float, float]: ... +def modf(__x: SupportsFloat) -> tuple[float, float]: ... def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... def radians(__x: SupportsFloat) -> float: ... def sin(__x: SupportsFloat) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/mimetypes.pyi b/mypy/typeshed/stdlib/@python2/mimetypes.pyi index a9661dab56ad..a7cddca65921 100644 --- a/mypy/typeshed/stdlib/@python2/mimetypes.pyi +++ b/mypy/typeshed/stdlib/@python2/mimetypes.pyi @@ -1,29 +1,29 @@ import sys -from typing import IO, Dict, List, Sequence, Text, Tuple +from typing import IO, Sequence, Text -def guess_type(url: Text, strict: bool = ...) -> Tuple[str | None, str | None]: ... -def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... +def guess_type(url: Text, strict: bool = ...) -> tuple[str | None, str | None]: ... +def guess_all_extensions(type: str, strict: bool = ...) -> list[str]: ... def guess_extension(type: str, strict: bool = ...) -> str | None: ... def init(files: Sequence[str] | None = ...) -> None: ... -def read_mime_types(file: str) -> Dict[str, str] | None: ... +def read_mime_types(file: str) -> dict[str, str] | None: ... 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] +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: ... + 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 = ...) -> str | None: ... - def guess_type(self, url: str, strict: bool = ...) -> Tuple[str | None, str | None]: ... - def guess_all_extensions(self, type: str, strict: bool = ...) -> List[str]: ... + def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... + 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": diff --git a/mypy/typeshed/stdlib/@python2/mmap.pyi b/mypy/typeshed/stdlib/@python2/mmap.pyi index 44369e6c051d..4e08bc28c28a 100644 --- a/mypy/typeshed/stdlib/@python2/mmap.pyi +++ b/mypy/typeshed/stdlib/@python2/mmap.pyi @@ -30,6 +30,7 @@ class mmap(Sequence[bytes]): def __init__( self, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ... ) -> None: ... + def close(self) -> None: ... def flush(self, offset: int = ..., size: int = ...) -> int: ... def move(self, dest: int, src: int, count: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/modulefinder.pyi b/mypy/typeshed/stdlib/@python2/modulefinder.pyi index 76fd014daf6e..458b037723f3 100644 --- a/mypy/typeshed/stdlib/@python2/modulefinder.pyi +++ b/mypy/typeshed/stdlib/@python2/modulefinder.pyi @@ -1,40 +1,39 @@ from types import CodeType -from typing import IO, Any, Container, Dict, Iterable, List, Sequence, Tuple +from typing import IO, Any, Container, Iterable, Sequence LOAD_CONST: int # undocumented IMPORT_NAME: int # undocumented STORE_NAME: int # undocumented STORE_GLOBAL: int # undocumented -STORE_OPS: Tuple[int, int] # undocumented +STORE_OPS: tuple[int, int] # undocumented EXTENDED_ARG: int # undocumented -packagePathMap: Dict[str, List[str]] # undocumented +packagePathMap: dict[str, list[str]] # undocumented def AddPackagePath(packagename: str, path: str) -> None: ... -replacePackageMap: Dict[str, str] # undocumented +replacePackageMap: dict[str, str] # undocumented def ReplacePackage(oldname: str, newname: str) -> None: ... class Module: # undocumented def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... class ModuleFinder: - modules: Dict[str, Module] - path: List[str] # undocumented - badmodules: Dict[str, Dict[str, int]] # undocumented + 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 + replace_paths: Sequence[tuple[str, str]] # undocumented def __init__( self, - path: List[str] | None = ..., + path: list[str] | None = ..., debug: int = ..., excludes: Container[str] = ..., - replace_paths: Sequence[Tuple[str, 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 @@ -42,22 +41,22 @@ class ModuleFinder: def run_script(self, pathname: str) -> None: ... def load_file(self, pathname: str) -> None: ... # undocumented def import_hook( - self, name: str, caller: Module | None = ..., fromlist: List[str] | None = ..., level: int = ... + self, name: str, caller: Module | None = ..., fromlist: list[str] | None = ..., level: int = ... ) -> Module | None: ... # undocumented def determine_parent(self, caller: Module | None, level: int = ...) -> Module | None: ... # undocumented - def find_head_package(self, parent: Module, name: str) -> Tuple[Module, str]: ... # 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) -> Module | None: ... # undocumented - def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented + def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ... # undocumented def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented def add_module(self, fqname: str) -> Module: ... # undocumented def find_module( self, name: str, path: str | None, parent: Module | None = ... - ) -> Tuple[IO[Any] | None, str | None, Tuple[str, str, int]]: ... # undocumented + ) -> tuple[IO[Any] | None, str | None, 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 any_missing(self) -> list[str]: ... # undocumented + def any_missing_maybe(self) -> tuple[list[str], list[str]]: ... # undocumented def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi index fa6757696845..a49f37f0de1d 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi @@ -1,6 +1,6 @@ import sys from types import ModuleType -from typing import Any, Container, Dict, Iterable, List, Sequence, Set, Tuple, Type +from typing import Any, Container, Iterable, Sequence from typing_extensions import Literal if sys.platform == "win32": @@ -21,22 +21,25 @@ if sys.platform == "win32": type_nullable: Literal[0x1000] type_key: Literal[0x2000] knownbits: Literal[0x3FFF] + class Table: name: str - fields: List[Tuple[int, str, int]] + 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, str | None, int]], + seq: Sequence[tuple[str, str | None, int]], action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., + seqno: int | type[_Unspecified] = ..., + cond: str | type[_Unspecified] = ..., ) -> None: ... - def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> 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 @@ -44,17 +47,19 @@ if sys.platform == "win32": 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] + 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 append(self, full: str, file: str, logical: str) -> tuple[int, str]: ... def commit(self, db: _Database) -> None: ... - _directories: Set[str] + _directories: set[str] + class Directory: db: _Database @@ -63,9 +68,9 @@ if sys.platform == "win32": physical: str logical: str component: str | None - short_names: Set[str] - ids: Set[str] - keyfiles: Dict[str, str] + short_names: set[str] + ids: set[str] + keyfiles: dict[str, str] componentflags: int | None absolute: str def __init__( @@ -88,13 +93,14 @@ if sys.platform == "win32": ) -> None: ... def make_short(self, file: str) -> str: ... def add_file(self, file: str, src: str | None = ..., version: str | None = ..., language: str | None = ...) -> str: ... - def glob(self, pattern: str, exclude: Container[str] | None = ...) -> List[str]: ... + def glob(self, pattern: str, exclude: Container[str] | None = ...) -> 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 @@ -111,6 +117,7 @@ if sys.platform == "win32": attributes: int = ..., ) -> None: ... def set_current(self) -> None: ... + class Control: dlg: Dialog @@ -119,12 +126,14 @@ if sys.platform == "win32": def event(self, event: str, argument: str, condition: str = ..., ordering: int | None = ...) -> 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: str | None = ...) -> None: ... + class Dialog: db: _Database diff --git a/mypy/typeshed/stdlib/@python2/msilib/schema.pyi b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi index d59e9767c3de..4ad9a1783fcd 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/schema.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi @@ -1,5 +1,4 @@ import sys -from typing import List, Tuple if sys.platform == "win32": from . import Table @@ -90,6 +89,6 @@ if sys.platform == "win32": Upgrade: Table Verb: Table - tables: List[Table] + tables: list[Table] - _Validation_records: List[Tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] + _Validation_records: list[tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] diff --git a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi index e4f400d33233..87dff754009d 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi @@ -1,9 +1,9 @@ import sys -from typing import List, Optional, Tuple +from typing import Optional if sys.platform == "win32": - _SequenceType = List[Tuple[str, Optional[str], int]] + _SequenceType = list[tuple[str, Optional[str], int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType @@ -11,4 +11,4 @@ if sys.platform == "win32": InstallExecuteSequence: _SequenceType InstallUISequence: _SequenceType - tables: List[str] + tables: list[str] diff --git a/mypy/typeshed/stdlib/@python2/msilib/text.pyi b/mypy/typeshed/stdlib/@python2/msilib/text.pyi index 4ae8ee68184b..879429ecea85 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/text.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/text.pyi @@ -1,9 +1,8 @@ import sys -from typing import List, Tuple if sys.platform == "win32": - ActionText: List[Tuple[str, str, str | None]] - UIText: List[Tuple[str, str | None]] + ActionText: list[tuple[str, str, str | None]] + UIText: list[tuple[str, str | None]] - tables: List[str] + tables: list[str] diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi index 80a1456d1be8..a5381ed3839c 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi @@ -2,7 +2,7 @@ import array import threading import weakref from Queue import Queue -from typing import Any, List +from typing import Any class DummyProcess(threading.Thread): _children: weakref.WeakKeyDictionary[Any, Any] @@ -35,7 +35,7 @@ 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 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 index ae5e05e9ccdd..f01b3f8cd660 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi @@ -1,7 +1,7 @@ from Queue import Queue -from typing import Any, List, Tuple +from typing import Any -families: List[None] +families: list[None] class Connection(object): _in: Any @@ -22,4 +22,4 @@ class Listener(object): def close(self) -> None: ... def Client(address) -> Connection: ... -def Pipe(duplex=...) -> Tuple[Connection, 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 index be9747e89c2f..440b5e83c500 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi @@ -1,6 +1,5 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, TypeVar - -_T = TypeVar("_T", bound=Pool) +from _typeshed import Self +from typing import Any, Callable, Iterable, Iterator class AsyncResult: def get(self, timeout: float | None = ...) -> Any: ... @@ -9,7 +8,7 @@ class AsyncResult: def successful(self) -> bool: ... class IMapIterator(Iterator[Any]): - def __iter__(self) -> Iterator[Any]: ... + def __iter__(self: Self) -> Self: ... def next(self, timeout: float | None = ...) -> Any: ... class IMapUnorderedIterator(IMapIterator): ... @@ -22,15 +21,15 @@ class Pool(object): initargs: Iterable[Any] = ..., maxtasksperchild: int | None = ..., ) -> None: ... - def apply(self, func: Callable[..., Any], args: Iterable[Any] = ..., kwds: Dict[str, Any] = ...) -> Any: ... + 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] = ..., + kwds: dict[str, Any] = ..., callback: Callable[..., None] | None = ..., ) -> AsyncResult: ... - def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> List[Any]: ... + def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> list[Any]: ... def map_async( self, func: Callable[..., Any], diff --git a/mypy/typeshed/stdlib/@python2/mutex.pyi b/mypy/typeshed/stdlib/@python2/mutex.pyi index e0931dc1188a..fd5363de73e5 100644 --- a/mypy/typeshed/stdlib/@python2/mutex.pyi +++ b/mypy/typeshed/stdlib/@python2/mutex.pyi @@ -1,10 +1,11 @@ -from typing import Any, Callable, Deque, TypeVar +from collections import deque +from typing import Any, Callable, TypeVar _T = TypeVar("_T") class mutex: locked: bool - queue: Deque[Any] + queue: deque[Any] def __init__(self) -> None: ... def test(self) -> bool: ... def testandset(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/netrc.pyi b/mypy/typeshed/stdlib/@python2/netrc.pyi index 3033c2f78955..3d92c7b4d43b 100644 --- a/mypy/typeshed/stdlib/@python2/netrc.pyi +++ b/mypy/typeshed/stdlib/@python2/netrc.pyi @@ -1,4 +1,4 @@ -from typing import Dict, List, Optional, Text, Tuple +from typing import Optional, Text class NetrcParseError(Exception): filename: str | None @@ -7,10 +7,10 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: Text | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] +_NetrcTuple = tuple[str, Optional[str], Optional[str]] class netrc: - hosts: Dict[str, _NetrcTuple] - macros: Dict[str, List[str]] + hosts: dict[str, _NetrcTuple] + macros: dict[str, list[str]] def __init__(self, file: Text | None = ...) -> None: ... def authenticators(self, host: str) -> _NetrcTuple | None: ... diff --git a/mypy/typeshed/stdlib/@python2/nis.pyi b/mypy/typeshed/stdlib/@python2/nis.pyi index bc6c2bc07256..10eef2336a83 100644 --- a/mypy/typeshed/stdlib/@python2/nis.pyi +++ b/mypy/typeshed/stdlib/@python2/nis.pyi @@ -1,9 +1,9 @@ import sys -from typing import Dict, List if sys.platform != "win32": - def cat(map: str, domain: str = ...) -> Dict[str, str]: ... + def cat(map: str, domain: str = ...) -> dict[str, str]: ... def get_default_domain() -> str: ... - def maps(domain: str = ...) -> List[str]: ... + def maps(domain: str = ...) -> list[str]: ... def match(key: str, map: str, domain: str = ...) -> str: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/nntplib.pyi b/mypy/typeshed/stdlib/@python2/nntplib.pyi index 56545d3b88b4..602617665ea8 100644 --- a/mypy/typeshed/stdlib/@python2/nntplib.pyi +++ b/mypy/typeshed/stdlib/@python2/nntplib.pyi @@ -1,9 +1,10 @@ import datetime import socket import ssl -from typing import IO, Any, Dict, Iterable, List, NamedTuple, Tuple, TypeVar, Union +from _typeshed import Self +from builtins import list as List # alias to avoid a name clash with a method named `list` in `_NNTPBase` +from typing import IO, Any, Iterable, NamedTuple, Union -_SelfT = TypeVar("_SelfT", bound=_NNTPBase) _File = Union[IO[bytes], bytes, str, None] class NNTPError(Exception): @@ -27,7 +28,7 @@ class GroupInfo(NamedTuple): class ArticleInfo(NamedTuple): number: int message_id: str - lines: List[bytes] + lines: list[bytes] def decode_header(header_str: str) -> str: ... @@ -45,35 +46,35 @@ class _NNTPBase: nntp_implementation: str nntp_version: int def __init__(self, file: IO[bytes], host: str, readermode: bool | None = ..., timeout: float = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getwelcome(self) -> str: ... - def getcapabilities(self) -> Dict[str, List[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: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def list(self, group_pattern: str | None = ..., *, file: _File = ...) -> Tuple[str, List[str]]: ... + def capabilities(self) -> tuple[str, dict[str, List[str]]]: ... + def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, List[str]]: ... + def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, List[str]]: ... + def list(self, group_pattern: str | None = ..., *, 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 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 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: None | str | List[Any] | Tuple[Any, ...], *, file: _File = ... - ) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... - def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... - def xpath(self, id: Any) -> Tuple[str, str]: ... - def date(self) -> Tuple[str, datetime.datetime]: ... + self, message_spec: None | str | List[Any] | tuple[Any, ...], *, file: _File = ... + ) -> tuple[str, List[tuple[int, dict[str, str]]]]: ... + def xgtitle(self, group: str, *, file: _File = ...) -> tuple[str, List[tuple[str, str]]]: ... + def xpath(self, id: Any) -> tuple[str, str]: ... + def date(self) -> tuple[str, datetime.datetime]: ... def post(self, data: bytes | Iterable[bytes]) -> str: ... def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... def quit(self) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/ntpath.pyi b/mypy/typeshed/stdlib/@python2/ntpath.pyi index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/ntpath.pyi +++ b/mypy/typeshed/stdlib/@python2/ntpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +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 splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/numbers.pyi b/mypy/typeshed/stdlib/@python2/numbers.pyi index fb88e076d446..73384a30803c 100644 --- a/mypy/typeshed/stdlib/@python2/numbers.pyi +++ b/mypy/typeshed/stdlib/@python2/numbers.pyi @@ -46,8 +46,8 @@ class Complex(Number): def __rpow__(self, base: Any) -> Any: ... def __abs__(self) -> Real: ... def conjugate(self) -> Any: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... class Real(Complex, SupportsFloat): @abstractmethod diff --git a/mypy/typeshed/stdlib/@python2/opcode.pyi b/mypy/typeshed/stdlib/@python2/opcode.pyi index 893dd7c7df9c..be162da4e496 100644 --- a/mypy/typeshed/stdlib/@python2/opcode.pyi +++ b/mypy/typeshed/stdlib/@python2/opcode.pyi @@ -1,15 +1,15 @@ -from typing import Dict, List, Sequence +from typing import Sequence cmp_op: Sequence[str] -hasconst: List[int] -hasname: List[int] -hasjrel: List[int] -hasjabs: List[int] -haslocal: List[int] -hascompare: List[int] -hasfree: List[int] -opname: List[str] +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] +opmap: dict[str, int] HAVE_ARGUMENT: int EXTENDED_ARG: int diff --git a/mypy/typeshed/stdlib/@python2/operator.pyi b/mypy/typeshed/stdlib/@python2/operator.pyi index 76a8a9b6bee4..cff20b85898b 100644 --- a/mypy/typeshed/stdlib/@python2/operator.pyi +++ b/mypy/typeshed/stdlib/@python2/operator.pyi @@ -1,16 +1,4 @@ -from typing import ( - Any, - Container, - Generic, - Mapping, - MutableMapping, - MutableSequence, - Sequence, - SupportsAbs, - Tuple, - TypeVar, - overload, -) +from typing import Any, Container, Generic, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, TypeVar, overload _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -128,26 +116,26 @@ class attrgetter(Generic[_T_co]): @overload def __new__(cls, attr: str) -> attrgetter[Any]: ... @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[Tuple[Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[Tuple[Any, Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[Tuple[Any, Any, Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... + def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... class itemgetter(Generic[_T_co]): @overload def __new__(cls, item: Any) -> itemgetter[Any]: ... @overload - def __new__(cls, item: Any, __item2: Any) -> itemgetter[Tuple[Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any) -> itemgetter[tuple[Any, Any]]: ... @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[Tuple[Any, Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[tuple[Any, Any, Any]]: ... @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[Tuple[Any, Any, Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[tuple[Any, Any, Any, Any]]: ... @overload - def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... + def __new__(cls, item: Any, *items: Any) -> itemgetter[tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... class methodcaller: diff --git a/mypy/typeshed/stdlib/@python2/optparse.pyi b/mypy/typeshed/stdlib/@python2/optparse.pyi index 08a926e301b3..a99bc0a6fb3b 100644 --- a/mypy/typeshed/stdlib/@python2/optparse.pyi +++ b/mypy/typeshed/stdlib/@python2/optparse.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple, Type, Union, overload +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Union, overload # See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g _Text = Union[str, unicode] -NO_DEFAULT: Tuple[_Text, ...] +NO_DEFAULT: tuple[_Text, ...] SUPPRESS_HELP: _Text SUPPRESS_USAGE: _Text @@ -42,7 +42,7 @@ class HelpFormatter: indent_increment: int level: int max_help_position: int - option_strings: Dict[Option, _Text] + option_strings: dict[Option, _Text] parser: OptionParser short_first: Any width: int @@ -76,25 +76,25 @@ class TitledHelpFormatter(HelpFormatter): def format_usage(self, usage: _Text) -> _Text: ... class Option: - ACTIONS: Tuple[_Text, ...] - ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] - ATTRS: List[_Text] - CHECK_METHODS: List[Callable[..., Any]] | None - 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] + ACTIONS: tuple[_Text, ...] + ALWAYS_TYPED_ACTIONS: tuple[_Text, ...] + ATTRS: list[_Text] + CHECK_METHODS: list[Callable[..., Any]] | None + 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: _Text | None default: Any nargs: int type: Any callback: Callable[..., Any] | None - callback_args: Tuple[Any, ...] | None - callback_kwargs: Dict[_Text, Any] | None + callback_args: tuple[Any, ...] | None + callback_kwargs: dict[_Text, Any] | None help: _Text | None metavar: _Text | None def __init__(self, *opts: _Text | None, **attrs: Any) -> None: ... @@ -104,9 +104,9 @@ class Option: def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... - def _check_opt_strings(self, opts: Iterable[_Text | None]) -> List[_Text]: ... + def _check_opt_strings(self, opts: Iterable[_Text | None]) -> list[_Text]: ... def _check_type(self) -> None: ... - def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... + def _set_attrs(self, attrs: dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: _Text, value: Any) -> Any: ... def convert_value(self, opt: _Text, value: Any) -> Any: ... @@ -118,13 +118,13 @@ class Option: make_option = Option class OptionContainer: - _long_opt: Dict[_Text, Option] - _short_opt: Dict[_Text, Option] + _long_opt: dict[_Text, Option] + _short_opt: dict[_Text, Option] conflict_handler: _Text - defaults: Dict[_Text, Any] + defaults: dict[_Text, Any] description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[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: ... @@ -145,7 +145,7 @@ class OptionContainer: def set_description(self, description: Any) -> None: ... class OptionGroup(OptionContainer): - option_list: List[Option] + option_list: list[Option] parser: OptionParser title: _Text def __init__(self, parser: OptionParser, title: _Text, description: _Text | None = ...) -> None: ... @@ -167,13 +167,13 @@ class OptionParser(OptionContainer): allow_interspersed_args: bool epilog: _Text | None formatter: HelpFormatter - largs: List[_Text] | None - option_groups: List[OptionGroup] - option_list: List[Option] + largs: list[_Text] | None + option_groups: list[OptionGroup] + option_list: list[Option] process_default_values: Any prog: _Text | None - rargs: List[Any] | None - standard_option_list: List[Option] + rargs: list[Any] | None + standard_option_list: list[Option] usage: _Text | None values: Values | None version: _Text @@ -181,7 +181,7 @@ class OptionParser(OptionContainer): self, usage: _Text | None = ..., option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., + option_class: type[Option] = ..., version: _Text | None = ..., conflict_handler: _Text = ..., description: _Text | None = ..., @@ -193,19 +193,19 @@ class OptionParser(OptionContainer): 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 _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: ... + def _process_args(self, largs: list[Any], rargs: list[Any], values: Values) -> None: ... + def _process_long_opt(self, rargs: list[Any], values: Any) -> None: ... + def _process_short_opts(self, rargs: list[Any], values: Any) -> None: ... @overload def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... @overload def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... - def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... + def 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: ... @@ -219,7 +219,7 @@ class OptionParser(OptionContainer): def get_prog_name(self) -> _Text: ... def get_usage(self) -> _Text: ... def get_version(self) -> _Text: ... - def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> Tuple[Values, List[AnyStr]]: ... + def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> tuple[Values, list[AnyStr]]: ... def print_usage(self, file: IO[str] | None = ...) -> None: ... def print_help(self, file: IO[str] | None = ...) -> None: ... def print_version(self, file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/os/__init__.pyi b/mypy/typeshed/stdlib/@python2/os/__init__.pyi index 1955c07020de..2ca9bce243ae 100644 --- a/mypy/typeshed/stdlib/@python2/os/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/os/__init__.pyi @@ -7,17 +7,14 @@ from typing import ( Any, AnyStr, Callable, - Dict, Generic, Iterator, - List, Mapping, MutableMapping, NamedTuple, NoReturn, Sequence, Text, - Tuple, TypeVar, Union, overload, @@ -90,7 +87,7 @@ W_OK: int X_OK: int class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): - def copy(self) -> Dict[AnyStr, 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: ... @@ -100,9 +97,9 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): environ: _Environ[str] if sys.platform != "win32": # Unix only - confstr_names: Dict[str, int] - pathconf_names: Dict[str, int] - sysconf_names: Dict[str, int] + confstr_names: dict[str, int] + pathconf_names: dict[str, int] + sysconf_names: dict[str, int] EX_OK: int EX_USAGE: int @@ -161,12 +158,12 @@ if sys.platform != "win32": def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... - def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + 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 getresuid() -> tuple[int, int, int]: ... + def getresgid() -> tuple[int, int, int]: ... def getuid() -> int: ... def setegid(egid: int) -> None: ... def seteuid(euid: int) -> None: ... @@ -181,7 +178,7 @@ if sys.platform != "win32": def getsid(pid: int) -> int: ... def setsid() -> None: ... def setuid(uid: int) -> None: ... - def uname() -> Tuple[str, str, str, str, str]: ... + def uname() -> tuple[str, str, str, str, str]: ... @overload def getenv(key: Text) -> str | None: ... @@ -198,7 +195,7 @@ def fstat(fd: int) -> Any: ... def fsync(fd: FileDescriptorLike) -> None: ... def lseek(fd: int, pos: int, how: int) -> int: ... def open(file: Text, flags: int, mode: int = ...) -> int: ... -def pipe() -> Tuple[int, int]: ... +def pipe() -> tuple[int, int]: ... def read(fd: int, n: int) -> bytes: ... def write(fd: int, string: bytes | buffer) -> int: ... def access(path: Text, mode: int) -> bool: ... @@ -230,7 +227,7 @@ def symlink(source: Text, link_name: Text) -> None: ... def unlink(path: Text) -> None: ... # TODO: add ns, dir_fd, follow_symlinks argument -def utime(path: Text, times: Tuple[float, float] | None) -> None: ... +def utime(path: Text, times: tuple[float, float] | None) -> None: ... if sys.platform != "win32": # Unix only @@ -238,11 +235,12 @@ if sys.platform != "win32": 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: 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 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: ... @@ -258,7 +256,7 @@ if sys.platform != "win32": def walk( top: AnyStr, topdown: bool = ..., onerror: Callable[[OSError], Any] | None = ..., followlinks: bool = ... -) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... +) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... def abort() -> NoReturn: ... # These are defined as execl(file, *args) but the first *arg is mandatory. @@ -271,7 +269,7 @@ def execlpe(file: Text, __arg0: 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]]] +_ExecVArgs = Union[tuple[Union[bytes, Text], ...], list[bytes], list[Text], list[Union[bytes, Text]]] def execv(path: Text, args: _ExecVArgs) -> NoReturn: ... def execve(path: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... @@ -283,22 +281,22 @@ 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 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? 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 popen2(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any]]: ... +def popen3(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any], IO[Any]]: ... +def popen4(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any]]: ... def spawnl(mode: int, path: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... def spawnle(mode: int, path: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise sig -def spawnv(mode: int, path: Text, args: List[bytes | Text]) -> int: ... -def spawnve(mode: int, path: Text, args: List[bytes | Text], env: Mapping[str, str]) -> int: ... +def spawnv(mode: int, path: Text, args: list[bytes | Text]) -> int: ... +def spawnve(mode: int, path: Text, args: list[bytes | Text], env: Mapping[str, str]) -> int: ... def system(command: Text) -> int: ... -def times() -> Tuple[float, float, float, float, float]: ... -def waitpid(pid: int, options: int) -> Tuple[int, int]: ... +def 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": @@ -308,11 +306,11 @@ else: # Unix only def spawnlp(mode: int, file: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... def spawnlpe(mode: int, file: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: Text, args: List[bytes | Text]) -> int: ... - def spawnvpe(mode: int, file: Text, args: List[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 spawnvp(mode: int, file: Text, args: list[bytes | Text]) -> int: ... + def spawnvpe(mode: int, file: Text, args: list[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: ... @@ -322,7 +320,7 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... def confstr(name: str | int) -> str | None: ... - def getloadavg() -> Tuple[float, float, float]: ... + def getloadavg() -> tuple[float, float, float]: ... def sysconf(name: str | int) -> int: ... def tmpfile() -> IO[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/os/path.pyi b/mypy/typeshed/stdlib/@python2/os/path.pyi index 2ce2f592f0e2..4e484ce8a096 100644 --- a/mypy/typeshed/stdlib/@python2/os/path.pyi +++ b/mypy/typeshed/stdlib/@python2/os/path.pyi @@ -1,6 +1,6 @@ import os import sys -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +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 splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +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 index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi +++ b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +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 splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi index af3e2c210930..d956a89729fd 100644 --- a/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi +++ b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi @@ -1,131 +1,132 @@ -from typing import Any, List, overload +import sys +from typing import Any, 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 +if sys.platform != "win32" and sys.platform != "darwin": + 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] + 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_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: ... + # TODO: oss_mixer_device return type + def openmixer(device: str = ...) -> Any: ... -class OSSAudioError(Exception): ... - -error = OSSAudioError + class OSSAudioError(Exception): ... + error = OSSAudioError diff --git a/mypy/typeshed/stdlib/@python2/parser.pyi b/mypy/typeshed/stdlib/@python2/parser.pyi index ff8bf039ee80..de88bc0ba056 100644 --- a/mypy/typeshed/stdlib/@python2/parser.pyi +++ b/mypy/typeshed/stdlib/@python2/parser.pyi @@ -1,12 +1,12 @@ from types import CodeType -from typing import Any, List, Sequence, Text, Tuple +from typing import Any, Sequence, Text 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 st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... +def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: ... def compilest(st: STType, filename: Text = ...) -> CodeType: ... def isexpr(st: STType) -> bool: ... def issuite(st: STType) -> bool: ... @@ -17,5 +17,5 @@ class STType: def compile(self, filename: Text = ...) -> CodeType: ... def isexpr(self) -> bool: ... def issuite(self) -> bool: ... - def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... - def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... + def tolist(self, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... + def totuple(self, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/pdb.pyi b/mypy/typeshed/stdlib/@python2/pdb.pyi index 6d3a6d5c5903..4600b5818eb3 100644 --- a/mypy/typeshed/stdlib/@python2/pdb.pyi +++ b/mypy/typeshed/stdlib/@python2/pdb.pyi @@ -1,18 +1,20 @@ from bdb import Bdb from cmd import Cmd from types import FrameType, TracebackType -from typing import IO, Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Tuple, TypeVar +from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, TypeVar +from typing_extensions import ParamSpec _T = TypeVar("_T") +_P = ParamSpec("_P") line_prefix: str # undocumented class Restart(Exception): ... -def run(statement: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... -def runeval(expression: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... -def runctx(statement: str, globals: Dict[str, Any], locals: Mapping[str, Any]) -> None: ... -def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... +def run(statement: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... +def runeval(expression: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... +def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... +def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... def set_trace() -> None: ... def post_mortem(t: TracebackType | None = ...) -> None: ... def pm() -> None: ... @@ -20,19 +22,19 @@ def pm() -> None: ... class Pdb(Bdb, Cmd): # Everything here is undocumented, except for __init__ - commands_resuming: ClassVar[List[str]] + commands_resuming: ClassVar[list[str]] - aliases: Dict[str, 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] + rcLines: list[str] + commands: dict[int, list[str]] + commands_doprompt: dict[int, bool] + commands_silent: dict[int, bool] commands_defining: bool commands_bnum: int | None lineno: int | None - stack: List[Tuple[FrameType, int]] + stack: list[tuple[FrameType, int]] curindex: int curframe: FrameType | None curframe_locals: Mapping[str, Any] @@ -47,11 +49,11 @@ class Pdb(Bdb, Cmd): def displayhook(self, obj: object) -> None: ... def handle_command_def(self, line: str) -> bool: ... def defaultFile(self) -> str: ... - def lineinfo(self, identifier: str) -> Tuple[None, None, None] | Tuple[str, str, int]: ... + def lineinfo(self, identifier: str) -> 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 print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... def lookupmodule(self, filename: str) -> str | None: ... def _runscript(self, filename: str) -> None: ... def do_commands(self, arg: str) -> bool | None: ... @@ -157,7 +159,7 @@ class Pdb(Bdb, Cmd): # undocumented -def find_function(funcname: str, filename: str) -> Tuple[str, str, int] | None: ... +def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... def main() -> None: ... def help() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pickle.pyi b/mypy/typeshed/stdlib/@python2/pickle.pyi index 07e32e64b449..bb9b6614f329 100644 --- a/mypy/typeshed/stdlib/@python2/pickle.pyi +++ b/mypy/typeshed/stdlib/@python2/pickle.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, Callable, Iterator, Optional, Tuple, Type, Union +from typing import IO, Any, Callable, Iterator, Optional, Union HIGHEST_PROTOCOL: int -bytes_types: Tuple[Type[Any], ...] # undocumented +bytes_types: tuple[type[Any], ...] # undocumented def dump(obj: Any, file: IO[bytes], protocol: int | None = ...) -> None: ... def dumps(obj: Any, protocol: int | None = ...) -> bytes: ... @@ -14,10 +14,10 @@ class UnpicklingError(PickleError): ... _reducedtype = Union[ str, - Tuple[Callable[..., Any], Tuple[Any, ...]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], + 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: diff --git a/mypy/typeshed/stdlib/@python2/pickletools.pyi b/mypy/typeshed/stdlib/@python2/pickletools.pyi index 14ec0fdff03a..915b700dc8e5 100644 --- a/mypy/typeshed/stdlib/@python2/pickletools.pyi +++ b/mypy/typeshed/stdlib/@python2/pickletools.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Iterator, List, MutableMapping, Text, Tuple, Type +from typing import IO, Any, Callable, Iterator, MutableMapping, Text _Reader = Callable[[IO[bytes]], Any] @@ -77,9 +77,9 @@ long4: ArgumentDescriptor class StackObject(object): name: str - obtype: Type[Any] | Tuple[Type[Any], ...] + obtype: type[Any] | tuple[type[Any], ...] doc: str - def __init__(self, name: str, obtype: Type[Any] | Tuple[Type[Any], ...], doc: str) -> None: ... + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... pyint: StackObject pylong: StackObject @@ -100,8 +100,8 @@ class OpcodeInfo(object): name: str code: str arg: ArgumentDescriptor | None - stack_before: List[StackObject] - stack_after: List[StackObject] + stack_before: list[StackObject] + stack_after: list[StackObject] proto: int doc: str def __init__( @@ -109,15 +109,15 @@ class OpcodeInfo(object): name: str, code: str, arg: ArgumentDescriptor | None, - stack_before: List[StackObject], - stack_after: List[StackObject], + stack_before: list[StackObject], + stack_after: list[StackObject], proto: int, doc: str, ) -> None: ... -opcodes: List[OpcodeInfo] +opcodes: list[OpcodeInfo] -def genops(pickle: bytes | IO[bytes]) -> Iterator[Tuple[OpcodeInfo, Any | None, int | None]]: ... +def genops(pickle: bytes | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ... def optimize(p: bytes | IO[bytes]) -> bytes: ... def dis( pickle: bytes | IO[bytes], out: IO[str] | None = ..., memo: MutableMapping[int, Any] | None = ..., indentlevel: int = ... diff --git a/mypy/typeshed/stdlib/@python2/pkgutil.pyi b/mypy/typeshed/stdlib/@python2/pkgutil.pyi index fd42af916cfe..3b006b376641 100644 --- a/mypy/typeshed/stdlib/@python2/pkgutil.pyi +++ b/mypy/typeshed/stdlib/@python2/pkgutil.pyi @@ -1,19 +1,19 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Iterable, Iterator, List, Tuple, Union +from typing import IO, Any, Callable, Iterable, Iterator, Union Loader = Any MetaPathFinder = Any PathEntryFinder = Any -_ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] +_ModuleInfoLike = tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] -def extend_path(path: List[str], name: str) -> List[str]: ... +def extend_path(path: list[str], name: str) -> list[str]: ... class ImpImporter: def __init__(self, path: str | None = ...) -> 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) -> Loader | None: ... def get_importer(path_item: str) -> PathEntryFinder | None: ... diff --git a/mypy/typeshed/stdlib/@python2/platform.pyi b/mypy/typeshed/stdlib/@python2/platform.pyi index b984a2b2d3d5..7d71ee943da1 100644 --- a/mypy/typeshed/stdlib/@python2/platform.pyi +++ b/mypy/typeshed/stdlib/@python2/platform.pyi @@ -1,4 +1,4 @@ -from typing import Any, Tuple +from typing import Any __copyright__: Any DEV_NULL: Any @@ -19,16 +19,16 @@ class _popen: __del__: Any def popen(cmd, mode=..., bufsize: Any | None = ...): ... -def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... +def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> tuple[str, str, str, str]: ... def mac_ver( - release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ... -) -> Tuple[str, Tuple[str, str, str], str]: ... + 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]]: ... + 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, release, version): ... -def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... -def uname() -> Tuple[str, str, str, str, str, str]: ... +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: ... @@ -37,9 +37,9 @@ def machine() -> str: ... def processor() -> str: ... def python_implementation() -> str: ... def python_version() -> str: ... -def python_version_tuple() -> Tuple[str, str, 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_build() -> tuple[str, str]: ... def python_compiler() -> str: ... def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/plistlib.pyi b/mypy/typeshed/stdlib/@python2/plistlib.pyi index d815e3c35404..02a1cb506d1d 100644 --- a/mypy/typeshed/stdlib/@python2/plistlib.pyi +++ b/mypy/typeshed/stdlib/@python2/plistlib.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Dict as DictT, Mapping, Text, Union +from typing import IO, Any, Mapping, Text, Union _Path = Union[str, Text] @@ -11,7 +11,7 @@ def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, restype: st def readPlistFromString(data: str) -> Any: ... def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... -class Dict(DictT[str, Any]): +class Dict(dict[str, Any]): def __getattr__(self, attr: str) -> Any: ... def __setattr__(self, attr: str, value: Any) -> None: ... def __delattr__(self, attr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/popen2.pyi b/mypy/typeshed/stdlib/@python2/popen2.pyi index 0efee4e6d271..43f6804e0659 100644 --- a/mypy/typeshed/stdlib/@python2/popen2.pyi +++ b/mypy/typeshed/stdlib/@python2/popen2.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, TextIO, Tuple, TypeVar +from typing import Any, Iterable, TextIO, TypeVar _T = TypeVar("_T") @@ -22,6 +22,6 @@ class Popen4(Popen3): 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]: ... +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/poplib.pyi b/mypy/typeshed/stdlib/@python2/poplib.pyi index 7a71f9850dfe..4525cac1e687 100644 --- a/mypy/typeshed/stdlib/@python2/poplib.pyi +++ b/mypy/typeshed/stdlib/@python2/poplib.pyi @@ -1,7 +1,7 @@ import socket -from typing import Any, BinaryIO, List, Pattern, Text, Tuple, overload +from typing import Any, BinaryIO, Pattern, Text, overload -_LongResp = Tuple[bytes, List[bytes], int] +_LongResp = tuple[bytes, list[bytes], int] class error_proto(Exception): ... @@ -22,7 +22,7 @@ class POP3: 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 stat(self) -> tuple[int, int]: ... def list(self, which: Any | None = ...) -> _LongResp: ... def retr(self, which: Any) -> _LongResp: ... def dele(self, which: Any) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/posix.pyi b/mypy/typeshed/stdlib/@python2/posix.pyi index c39ce325289b..7ea9c0015ab0 100644 --- a/mypy/typeshed/stdlib/@python2/posix.pyi +++ b/mypy/typeshed/stdlib/@python2/posix.pyi @@ -1,12 +1,12 @@ from _typeshed import FileDescriptorLike -from typing import IO, AnyStr, Dict, List, Mapping, NamedTuple, Sequence, Tuple, TypeVar +from typing import IO, AnyStr, Mapping, NamedTuple, Sequence, TypeVar error = OSError -confstr_names: Dict[str, int] -environ: Dict[str, str] -pathconf_names: Dict[str, int] -sysconf_names: Dict[str, int] +confstr_names: dict[str, int] +environ: dict[str, str] +pathconf_names: dict[str, int] +sysconf_names: dict[str, int] _T = TypeVar("_T") @@ -112,7 +112,7 @@ 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 forkpty() -> tuple[int, int]: ... def fpathconf(fd: int, name: str) -> None: ... def fstat(fd: int) -> stat_result: ... def fstatvfs(fd: int) -> statvfs_result: ... @@ -123,15 +123,15 @@ def getcwdu() -> unicode: ... def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... -def getgroups() -> List[int]: ... -def getloadavg() -> Tuple[float, float, float]: ... +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 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: ... @@ -140,7 +140,7 @@ 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 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: ... @@ -151,9 +151,9 @@ 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 openpty() -> tuple[int, int]: ... def pathconf(path: unicode, name: str) -> str: ... -def pipe() -> Tuple[int, int]: ... +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: ... @@ -182,20 +182,20 @@ def sysconf(name: 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 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 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: Tuple[int, int] | None) -> None: ... +def utime(path: unicode, times: tuple[int, int] | None) -> None: ... def wait() -> int: ... -_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, 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 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 index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/posixpath.pyi +++ b/mypy/typeshed/stdlib/@python2/posixpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +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 splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pprint.pyi b/mypy/typeshed/stdlib/@python2/pprint.pyi index 407a9afb8e47..e22c4464eb4d 100644 --- a/mypy/typeshed/stdlib/@python2/pprint.pyi +++ b/mypy/typeshed/stdlib/@python2/pprint.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Dict, Tuple +from typing import IO, Any def pformat(object: object, indent: int = ..., width: int = ..., depth: int | None = ...) -> str: ... def pprint( @@ -14,4 +14,4 @@ class PrettyPrinter: 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/@python2/profile.pyi b/mypy/typeshed/stdlib/@python2/profile.pyi index 08e9b906dd0d..d9884038e0e0 100644 --- a/mypy/typeshed/stdlib/@python2/profile.pyi +++ b/mypy/typeshed/stdlib/@python2/profile.pyi @@ -1,13 +1,15 @@ -from typing import Any, Callable, Dict, Text, Tuple, TypeVar +from _typeshed import Self +from typing import Any, Callable, Text, TypeVar +from typing_extensions import ParamSpec def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_P = ParamSpec("_P") +_Label = tuple[str, int, str] class Profile: bias: int @@ -20,7 +22,7 @@ class Profile: def dump_stats(self, file: Text) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/pstats.pyi b/mypy/typeshed/stdlib/@python2/pstats.pyi index cecd1e84e305..e2cf6e437826 100644 --- a/mypy/typeshed/stdlib/@python2/pstats.pyi +++ b/mypy/typeshed/stdlib/@python2/pstats.pyi @@ -1,12 +1,13 @@ +from _typeshed import Self from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Dict, Iterable, List, Text, Tuple, TypeVar, Union, overload +from typing import IO, Any, Iterable, Text, TypeVar, Union, overload _Selector = Union[str, float, int] _T = TypeVar("_T", bound=Stats) class Stats: - sort_arg_dict_default: Dict[str, Tuple[Any, str]] + sort_arg_dict_default: dict[str, tuple[Any, str]] def __init__( self: _T, __arg: None | str | Text | Profile | _cProfile = ..., @@ -16,22 +17,22 @@ class Stats: def init(self, arg: None | str | Text | Profile | _cProfile) -> None: ... def load_stats(self, arg: None | str | Text | Profile | _cProfile) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Text | Profile | _cProfile | _T) -> _T: ... + def add(self: Self, *arg_list: None | str | Text | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: Text) -> None: ... - def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... + def get_sort_arg_defs(self) -> dict[str, tuple[tuple[tuple[int, int], ...], str]]: ... @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self: Self, field: int) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self: Self, *field: str) -> Self: ... + def reverse_order(self: Self) -> Self: ... + def strip_dirs(self: Self) -> Self: ... 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 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: Self, *amount: _Selector) -> Self: ... + def print_callees(self: Self, *amount: _Selector) -> Self: ... + def print_callers(self: Self, *amount: _Selector) -> Self: ... 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_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = ...) -> None: ... def print_title(self) -> None: ... def print_line(self, func: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pty.pyi b/mypy/typeshed/stdlib/@python2/pty.pyi index d9d9fd98e41b..2c90faf18aa3 100644 --- a/mypy/typeshed/stdlib/@python2/pty.pyi +++ b/mypy/typeshed/stdlib/@python2/pty.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable, Iterable, Tuple +from typing import Callable, Iterable if sys.platform != "win32": _Reader = Callable[[int], bytes] @@ -9,8 +9,8 @@ if sys.platform != "win32": STDERR_FILENO: int CHILD: int - def openpty() -> Tuple[int, int]: ... - def master_open() -> Tuple[int, str]: ... + def openpty() -> tuple[int, int]: ... + def master_open() -> tuple[int, str]: ... def slave_open(tty_name: str) -> int: ... - def fork() -> Tuple[int, int]: ... + def fork() -> tuple[int, int]: ... def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pwd.pyi b/mypy/typeshed/stdlib/@python2/pwd.pyi index 583999fd84b7..e64cbf6a1ac3 100644 --- a/mypy/typeshed/stdlib/@python2/pwd.pyi +++ b/mypy/typeshed/stdlib/@python2/pwd.pyi @@ -1,8 +1,7 @@ import sys -from typing import List, Tuple if sys.platform != "win32": - class struct_passwd(Tuple[str, str, int, int, str, str, str]): + class struct_passwd(tuple[str, str, int, int, str, str, str]): pw_name: str pw_passwd: str pw_uid: int @@ -10,6 +9,6 @@ if sys.platform != "win32": pw_gecos: str pw_dir: str pw_shell: str - def getpwall() -> List[struct_passwd]: ... + def getpwall() -> list[struct_passwd]: ... def getpwuid(__uid: int) -> struct_passwd: ... def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/@python2/py_compile.pyi b/mypy/typeshed/stdlib/@python2/py_compile.pyi index 44905b43da33..3c26f451116e 100644 --- a/mypy/typeshed/stdlib/@python2/py_compile.pyi +++ b/mypy/typeshed/stdlib/@python2/py_compile.pyi @@ -1,4 +1,4 @@ -from typing import List, Text, Type, Union +from typing import Text, Union _EitherStr = Union[bytes, Text] @@ -7,7 +7,7 @@ class PyCompileError(Exception): exc_value: BaseException file: str msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... def compile(file: _EitherStr, cfile: _EitherStr | None = ..., dfile: _EitherStr | None = ..., doraise: bool = ...) -> None: ... -def main(args: List[Text] | None = ...) -> int: ... +def main(args: list[Text] | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/pyclbr.pyi b/mypy/typeshed/stdlib/@python2/pyclbr.pyi index 893079901665..317e934694c5 100644 --- a/mypy/typeshed/stdlib/@python2/pyclbr.pyi +++ b/mypy/typeshed/stdlib/@python2/pyclbr.pyi @@ -1,13 +1,13 @@ -from typing import Dict, List, Sequence +from typing import Sequence class Class: module: str name: str - super: List[Class | str] | None - methods: Dict[str, int] + super: list[Class | str] | None + methods: dict[str, int] file: int lineno: int - def __init__(self, module: str, name: str, super: List[Class | str] | None, file: str, lineno: int) -> None: ... + def __init__(self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int) -> None: ... class Function: module: str @@ -16,5 +16,5 @@ class Function: lineno: int def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... -def readmodule(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class]: ... -def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class | Function | List[str]]: ... +def readmodule(module: str, path: Sequence[str] | None = ...) -> dict[str, Class]: ... +def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> dict[str, Class | Function | list[str]]: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc.pyi b/mypy/typeshed/stdlib/@python2/pydoc.pyi index dee0c4710b39..a43b7333c7b0 100644 --- a/mypy/typeshed/stdlib/@python2/pydoc.pyi +++ b/mypy/typeshed/stdlib/@python2/pydoc.pyi @@ -1,35 +1,20 @@ 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, -) +from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Text 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]] +_Exc_Info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] __author__: str __date__: str __version__: str __credits__: str -def pathdirs() -> List[str]: ... +def pathdirs() -> list[str]: ... def getdoc(object: object) -> Text: ... -def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +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: ... @@ -37,14 +22,14 @@ def cram(text: str, maxlen: int) -> str: ... def stripid(text: str) -> str: ... def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... def visiblename(name: str, all: Container[str] | None = ..., obj: object | None = ...) -> bool: ... -def classify_class_attrs(object: object) -> List[Tuple[str, str, type, str]]: ... +def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... def ispackage(path: str) -> bool: ... def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... -def synopsis(filename: str, cache: MutableMapping[str, Tuple[int, str]] = ...) -> str | None: ... +def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = ...) -> str | None: ... class ErrorDuringImport(Exception): filename: str - exc: Type[BaseException] | None + exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... @@ -97,12 +82,12 @@ class HTMLDoc(Doc): ) -> 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 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 modpkglink(self, modpkginfo: tuple[str, str, bool, bool]) -> str: ... def markup( self, text: str, @@ -112,7 +97,7 @@ class HTMLDoc(Doc): methods: Mapping[str, str] = ..., ) -> str: ... def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ... ) -> str: ... def docmodule(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... def docclass( @@ -164,7 +149,7 @@ class TextDoc(Doc): def indent(self, text: str, prefix: str = ...) -> str: ... def section(self, title: str, contents: str) -> str: ... def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ..., prefix: str = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ..., prefix: str = ... ) -> str: ... def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... def docclass(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... @@ -204,16 +189,16 @@ html: HTMLDoc class _OldStyleClass: ... -def resolve(thing: str | object, forceload: bool = ...) -> Tuple[object, str] | None: ... +def resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: ... def render_doc(thing: str | object, title: str = ..., forceload: bool = ..., renderer: Doc | None = ...) -> str: ... def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: SupportsWrite[str] | None = ...) -> None: ... def writedoc(thing: str | object, forceload: bool = ...) -> None: ... def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ... class Helper: - keywords: Dict[str, str | Tuple[str, str]] - symbols: Dict[str, str] - topics: Dict[str, str | Tuple[str, ...]] + keywords: dict[str, str | tuple[str, str]] + symbols: dict[str, str] + topics: dict[str, str | tuple[str, ...]] def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... input: IO[str] output: IO[str] @@ -222,7 +207,7 @@ class Helper: 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 list(self, items: list[str], columns: int = ..., width: int = ...) -> None: ... def listkeywords(self) -> None: ... def listsymbols(self) -> None: ... def listtopics(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi index 1c48f4022fd6..091d34300106 100644 --- a/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi +++ b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi @@ -1,3 +1 @@ -from typing import Dict - -topics: Dict[str, str] +topics: dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi index bd73f850b559..8faaec294316 100644 --- a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi @@ -1,12 +1,12 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Dict, List, Optional, Text, Tuple +from typing import Any, Callable, Optional, Text EXPAT_VERSION: str # undocumented -version_info: Tuple[int, int, int] # undocumented +version_info: tuple[int, int, int] # undocumented native_encoding: str # undocumented -features: List[Tuple[str, int]] # undocumented +features: list[tuple[str, int]] # undocumented class ExpatError(Exception): code: int @@ -19,7 +19,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +_Model = tuple[int, int, Optional[str], tuple[Any, ...]] class XMLParserType(object): def Parse(self, __data: Text | bytes, __isfinal: bool = ...) -> int: ... @@ -48,8 +48,8 @@ class XMLParserType(object): EndDoctypeDeclHandler: Callable[[], Any] | None ElementDeclHandler: Callable[[str, _Model], Any] | None AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None - StartElementHandler: Callable[[str, Dict[str, str]], Any] | Callable[[str, List[str]], Any] | Callable[ - [str, Dict[str, str], List[str]], Any + StartElementHandler: Callable[[str, dict[str, str]], Any] | Callable[[str, list[str]], Any] | Callable[ + [str, dict[str, str], list[str]], Any ] | None EndElementHandler: Callable[[str], Any] | None ProcessingInstructionHandler: Callable[[str, str], Any] | None @@ -71,5 +71,5 @@ def ErrorString(__code: int) -> str: ... # intern is undocumented def ParserCreate( - encoding: Text | None = ..., namespace_separator: Text | None = ..., intern: Dict[str, Any] | None = ... + encoding: Text | None = ..., namespace_separator: Text | None = ..., intern: dict[str, Any] | None = ... ) -> XMLParserType: ... diff --git a/mypy/typeshed/stdlib/@python2/random.pyi b/mypy/typeshed/stdlib/@python2/random.pyi index 6fb5d602067c..df279a03c24a 100644 --- a/mypy/typeshed/stdlib/@python2/random.pyi +++ b/mypy/typeshed/stdlib/@python2/random.pyi @@ -1,5 +1,5 @@ import _random -from typing import Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, overload +from typing import Any, Callable, Iterator, MutableSequence, Protocol, Sequence, TypeVar, overload _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -22,7 +22,7 @@ class Random(_random.Random): 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 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: ... @@ -52,7 +52,7 @@ 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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/re.pyi b/mypy/typeshed/stdlib/@python2/re.pyi index fbe021ce67be..ba555968ad4b 100644 --- a/mypy/typeshed/stdlib/@python2/re.pyi +++ b/mypy/typeshed/stdlib/@python2/re.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Callable, Iterator, List, Match, Pattern, Tuple, overload +from typing import Any, AnyStr, Callable, Iterator, Match, Pattern, overload # ----- re variables and constants ----- DEBUG: int @@ -32,13 +32,13 @@ def match(pattern: str | unicode, string: AnyStr, flags: int = ...) -> Match[Any @overload def match(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... @overload -def split(pattern: str | unicode, string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +def split(pattern: str | unicode, string: AnyStr, maxsplit: int = ..., flags: int = ...) -> list[AnyStr]: ... @overload -def split(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +def split(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> list[AnyStr]: ... @overload -def findall(pattern: str | unicode, string: AnyStr, flags: int = ...) -> List[Any]: ... +def findall(pattern: str | unicode, string: AnyStr, flags: int = ...) -> list[Any]: ... @overload -def findall(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... +def findall(pattern: 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 @@ -65,15 +65,15 @@ def sub( flags: int = ..., ) -> AnyStr: ... @overload -def subn(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> Tuple[AnyStr, int]: ... +def subn(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> tuple[AnyStr, int]: ... @overload def subn( pattern: str | unicode, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... @overload def subn( pattern: Pattern[str] | Pattern[unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... @overload def subn( pattern: Pattern[str] | Pattern[unicode], @@ -81,7 +81,7 @@ def subn( string: AnyStr, count: int = ..., flags: int = ..., -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... def escape(string: AnyStr) -> AnyStr: ... def purge() -> None: ... def template(pattern: AnyStr | Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/repr.pyi b/mypy/typeshed/stdlib/@python2/repr.pyi index bdb8822ac77d..6b6f5ea9325e 100644 --- a/mypy/typeshed/stdlib/@python2/repr.pyi +++ b/mypy/typeshed/stdlib/@python2/repr.pyi @@ -1,4 +1,4 @@ -from typing import Any, List +from typing import Any class Repr: maxarray: int @@ -27,7 +27,7 @@ class Repr: def repr_str(self, x, level: complex) -> str: ... def repr_tuple(self, x, level: complex) -> str: ... -def _possibly_sorted(x) -> List[Any]: ... +def _possibly_sorted(x) -> list[Any]: ... aRepr: Repr diff --git a/mypy/typeshed/stdlib/@python2/resource.pyi b/mypy/typeshed/stdlib/@python2/resource.pyi index 476438d53674..8deec4f67f51 100644 --- a/mypy/typeshed/stdlib/@python2/resource.pyi +++ b/mypy/typeshed/stdlib/@python2/resource.pyi @@ -1,11 +1,11 @@ import sys -from typing import NamedTuple, Tuple +from typing import NamedTuple if sys.platform != "win32": class error(Exception): ... RLIM_INFINITY: int - def getrlimit(resource: int) -> Tuple[int, int]: ... - def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... + 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 @@ -18,6 +18,7 @@ if sys.platform != "win32": RLIMIT_MEMLOCK: int RLIMIT_VMEM: int RLIMIT_AS: int + class _RUsage(NamedTuple): ru_utime: float ru_stime: float diff --git a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi index a61c61eb24f2..e075e241b794 100644 --- a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi @@ -1,7 +1,9 @@ -from typing import Any, Dict, Union +from typing import Any, Union _Text = Union[str, unicode] class Completer: - def __init__(self, namespace: Dict[str, Any] | None = ...) -> None: ... + def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... def complete(self, text: _Text, state: int) -> str | None: ... + def attr_matches(self, text: _Text) -> list[str]: ... + def global_matches(self, text: _Text) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/sched.pyi b/mypy/typeshed/stdlib/@python2/sched.pyi index f718dd7a57bd..9247a95da974 100644 --- a/mypy/typeshed/stdlib/@python2/sched.pyi +++ b/mypy/typeshed/stdlib/@python2/sched.pyi @@ -1,18 +1,18 @@ -from typing import Any, Callable, Dict, List, NamedTuple, Text, Tuple +from typing import Any, Callable, NamedTuple, Text class Event(NamedTuple): time: float priority: Any action: Callable[..., Any] - argument: Tuple[Any, ...] - kwargs: Dict[Text, Any] + argument: tuple[Any, ...] + kwargs: dict[Text, Any] class scheduler: def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... - def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def 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]: ... + def queue(self) -> list[Event]: ... diff --git a/mypy/typeshed/stdlib/@python2/select.pyi b/mypy/typeshed/stdlib/@python2/select.pyi index b960fd4e24b5..cd799d75b5b1 100644 --- a/mypy/typeshed/stdlib/@python2/select.pyi +++ b/mypy/typeshed/stdlib/@python2/select.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Iterable, List, Tuple +from typing import Any, Iterable if sys.platform != "win32": PIPE_BUF: int @@ -21,11 +21,11 @@ class poll: 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: float | None = ...) -> List[Tuple[int, int]]: ... + def poll(self, timeout: float | None = ...) -> list[tuple[int, int]]: ... def select( __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: float | None = ... -) -> Tuple[List[Any], List[Any], List[Any]]: ... +) -> tuple[list[Any], list[Any], list[Any]]: ... class error(Exception): ... @@ -54,7 +54,7 @@ if sys.platform != "linux" and sys.platform != "win32": def close(self) -> None: ... def control( self, __changelist: Iterable[kevent] | None, __maxevents: int, __timeout: float | None = ... - ) -> List[kevent]: ... + ) -> list[kevent]: ... def fileno(self) -> int: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... @@ -106,7 +106,7 @@ if sys.platform == "linux": 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: float | None = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ... + def poll(self, timeout: float | None = ..., maxevents: int = ...) -> list[tuple[int, int]]: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... EPOLLERR: int diff --git a/mypy/typeshed/stdlib/@python2/sets.pyi b/mypy/typeshed/stdlib/@python2/sets.pyi index d2b94ea44bbc..7cafbaf8a7c7 100644 --- a/mypy/typeshed/stdlib/@python2/sets.pyi +++ b/mypy/typeshed/stdlib/@python2/sets.pyi @@ -1,29 +1,27 @@ +from _typeshed import Self from typing import Any, Hashable, Iterable, Iterator, MutableMapping, 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 __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def copy(self: Self) -> Self: ... + def __copy__(self: Self) -> Self: ... + def __deepcopy__(self: Self, memo: MutableMapping[int, BaseSet[_T]]) -> Self: ... + def __or__(self: Self, other: BaseSet[_T]) -> Self: ... + def union(self: Self, other: _Setlike[_T]) -> Self: ... + def __and__(self: Self, other: BaseSet[_T]) -> Self: ... + def intersection(self: Self, other: _Setlike[Any]) -> Self: ... + def __xor__(self: Self, other: BaseSet[_T]) -> Self: ... + def symmetric_difference(self: Self, other: _Setlike[_T]) -> Self: ... + def __sub__(self: Self, other: BaseSet[_T]) -> Self: ... + def difference(self: Self, other: _Setlike[Any]) -> Self: ... def __contains__(self, element: Any) -> bool: ... def issubset(self, other: BaseSet[_T]) -> bool: ... def issuperset(self, other: BaseSet[_T]) -> bool: ... @@ -38,13 +36,13 @@ class ImmutableSet(BaseSet[_T], Hashable): class Set(BaseSet[_T]): def __init__(self, iterable: _Setlike[_T] | None = ...) -> None: ... - def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __ior__(self: Self, other: BaseSet[_T]) -> Self: ... def union_update(self, other: _Setlike[_T]) -> None: ... - def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __iand__(self: Self, other: BaseSet[_T]) -> Self: ... def intersection_update(self, other: _Setlike[Any]) -> None: ... - def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __ixor__(self: Self, other: BaseSet[_T]) -> Self: ... def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... - def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __isub__(self: Self, other: BaseSet[_T]) -> Self: ... def difference_update(self, other: _Setlike[Any]) -> None: ... def update(self, iterable: _Setlike[_T]) -> None: ... def clear(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shelve.pyi b/mypy/typeshed/stdlib/@python2/shelve.pyi index d9b1a00e58df..011159792e60 100644 --- a/mypy/typeshed/stdlib/@python2/shelve.pyi +++ b/mypy/typeshed/stdlib/@python2/shelve.pyi @@ -1,12 +1,13 @@ import collections -from typing import Any, Dict, Iterator, List, Tuple +from _typeshed import Self +from typing import Any, Iterator class Shelf(collections.MutableMapping[Any, Any]): def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... + self, dict: dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... ) -> None: ... def __iter__(self) -> Iterator[str]: ... - def keys(self) -> List[Any]: ... + def keys(self) -> list[Any]: ... def __len__(self) -> int: ... def has_key(self, key: Any) -> bool: ... def __contains__(self, key: Any) -> bool: ... @@ -14,7 +15,7 @@ class Shelf(collections.MutableMapping[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 __enter__(self: Self) -> Self: ... def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... def close(self) -> None: ... def __del__(self) -> None: ... @@ -22,13 +23,13 @@ class Shelf(collections.MutableMapping[Any, Any]): class BsdDbShelf(Shelf): def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... + self, dict: dict[Any, Any], protocol: int | None = ..., 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]: ... + 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: int | None = ..., writeback: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shlex.pyi b/mypy/typeshed/stdlib/@python2/shlex.pyi index 89c28fc9be7f..6c4557a98036 100644 --- a/mypy/typeshed/stdlib/@python2/shlex.pyi +++ b/mypy/typeshed/stdlib/@python2/shlex.pyi @@ -1,12 +1,11 @@ -from typing import IO, Any, List, Text, TypeVar +from _typeshed import Self +from typing import IO, Any, Text -def split(s: str | None, comments: bool = ..., posix: bool = ...) -> List[str]: ... - -_SLT = TypeVar("_SLT", bound=shlex) +def split(s: str | None, comments: bool = ..., posix: bool = ...) -> list[str]: ... class shlex: def __init__(self, instream: IO[Any] | Text = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def __iter__(self: Self) -> Self: ... def next(self) -> str: ... def get_token(self) -> str | None: ... def push_token(self, _str: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shutil.pyi b/mypy/typeshed/stdlib/@python2/shutil.pyi index 4805c8e4cdb7..f92cf1c9f1a0 100644 --- a/mypy/typeshed/stdlib/@python2/shutil.pyi +++ b/mypy/typeshed/stdlib/@python2/shutil.pyi @@ -1,9 +1,9 @@ from _typeshed import SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, List, Sequence, Set, Text, Tuple, Type, TypeVar, Union +from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar, Union _AnyStr = TypeVar("_AnyStr", str, unicode) _AnyPath = TypeVar("_AnyPath", str, unicode) -_PathReturn = Type[None] +_PathReturn = type[None] class Error(EnvironmentError): ... class SpecialFileError(EnvironmentError): ... @@ -15,9 +15,9 @@ def copymode(src: Text, dst: Text) -> None: ... def copystat(src: Text, dst: Text) -> None: ... def copy(src: Text, dst: Text) -> _PathReturn: ... def copy2(src: Text, dst: Text) -> _PathReturn: ... -def ignore_patterns(*patterns: Text) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... +def ignore_patterns(*patterns: Text) -> Callable[[Any, list[_AnyStr]], set[_AnyStr]]: ... def copytree( - src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: None | Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]] = ... + src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: None | Callable[[AnyStr, list[AnyStr]], Iterable[AnyStr]] = ... ) -> _PathReturn: ... def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Callable[[Any, _AnyPath, Any], Any] | None = ...) -> None: ... @@ -35,11 +35,11 @@ def make_archive( group: str | None = ..., logger: Any | None = ..., ) -> _AnyStr: ... -def get_archive_formats() -> List[Tuple[str, str]]: ... +def get_archive_formats() -> list[tuple[str, str]]: ... def register_archive_format( name: str, function: Callable[..., Any], - extra_args: Sequence[Tuple[str, Any] | List[Any]] | None = ..., + extra_args: Sequence[tuple[str, Any] | list[Any]] | None = ..., description: str = ..., ) -> None: ... def unregister_archive_format(name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/signal.pyi b/mypy/typeshed/stdlib/@python2/signal.pyi index 16a8f2d1cb8b..7f86f03e638a 100644 --- a/mypy/typeshed/stdlib/@python2/signal.pyi +++ b/mypy/typeshed/stdlib/@python2/signal.pyi @@ -1,57 +1,57 @@ from types import FrameType -from typing import Callable, Tuple, Union +from typing import Callable, Union -SIG_DFL: int = ... -SIG_IGN: int = ... +SIG_DFL: int +SIG_IGN: int -ITIMER_REAL: int = ... -ITIMER_VIRTUAL: int = ... -ITIMER_PROF: int = ... +ITIMER_REAL: int +ITIMER_VIRTUAL: int +ITIMER_PROF: int -NSIG: 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 = ... +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 = ... +CTRL_C_EVENT: int +CTRL_BREAK_EVENT: int class ItimerError(IOError): ... @@ -60,8 +60,8 @@ _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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/site.pyi b/mypy/typeshed/stdlib/@python2/site.pyi index c77c9397f612..fc331c113163 100644 --- a/mypy/typeshed/stdlib/@python2/site.pyi +++ b/mypy/typeshed/stdlib/@python2/site.pyi @@ -1,12 +1,12 @@ -from typing import Iterable, List +from typing import Iterable -PREFIXES: List[str] +PREFIXES: list[str] ENABLE_USER_SITE: bool | None USER_SITE: str | None USER_BASE: str | None def main() -> None: ... def addsitedir(sitedir: str, known_paths: Iterable[str] | None = ...) -> None: ... -def getsitepackages(prefixes: Iterable[str] | None = ...) -> List[str]: ... +def getsitepackages(prefixes: Iterable[str] | None = ...) -> list[str]: ... def getuserbase() -> str: ... def getusersitepackages() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/smtpd.pyi b/mypy/typeshed/stdlib/@python2/smtpd.pyi index 1c17b82d8ab5..6778611a56d9 100644 --- a/mypy/typeshed/stdlib/@python2/smtpd.pyi +++ b/mypy/typeshed/stdlib/@python2/smtpd.pyi @@ -1,9 +1,9 @@ import asynchat import asyncore import socket -from typing import Any, List, Text, Tuple, Type +from typing import Any, Text -_Address = Tuple[str, int] # (host, port) +_Address = tuple[str, int] # (host, port) class SMTPChannel(asynchat.async_chat): COMMAND: int @@ -22,24 +22,24 @@ class SMTPChannel(asynchat.async_chat): def smtp_DATA(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] + channel_class: type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool def __init__(self, localaddr: _Address, remoteaddr: _Address, data_size_limit: int = ...) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message( - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str, **kwargs: Any + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str, **kwargs: Any ) -> str | None: ... class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str ) -> str | None: ... class MailmanProxy(PureProxy): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str ) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/sndhdr.pyi b/mypy/typeshed/stdlib/@python2/sndhdr.pyi index 189529fd21d6..0213a5d0cbb3 100644 --- a/mypy/typeshed/stdlib/@python2/sndhdr.pyi +++ b/mypy/typeshed/stdlib/@python2/sndhdr.pyi @@ -1,6 +1,6 @@ -from typing import Text, Tuple, Union +from typing import Text, Union -_SndHeaders = Tuple[str, int, int, int, Union[int, str]] +_SndHeaders = tuple[str, int, int, int, Union[int, str]] def what(filename: Text) -> _SndHeaders | None: ... def whathdr(filename: Text) -> _SndHeaders | None: ... diff --git a/mypy/typeshed/stdlib/@python2/socket.pyi b/mypy/typeshed/stdlib/@python2/socket.pyi index 2bf719dd9faa..0981ce28a786 100644 --- a/mypy/typeshed/stdlib/@python2/socket.pyi +++ b/mypy/typeshed/stdlib/@python2/socket.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, BinaryIO, Iterable, List, Text, Tuple, TypeVar, Union, overload +from typing import Any, BinaryIO, Iterable, Text, Union, overload # ----- Constants ----- # Some socket families are listed in the "Socket families" section of the docs, @@ -373,14 +373,13 @@ class timeout(error): # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] +_Address = Union[tuple[Any, ...], str] _RetAddress = Any # TODO Most methods allow bytes as address objects _WriteBuffer = Union[bytearray, memoryview] -_CMSG = Tuple[int, int, bytes] -_SelfT = TypeVar("_SelfT", bound=socket) +_CMSG = tuple[int, int, bytes] class socket: family: int @@ -388,7 +387,7 @@ class socket: proto: int def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... # --- methods --- - def accept(self) -> Tuple[socket, _RetAddress]: ... + def accept(self) -> tuple[socket, _RetAddress]: ... def bind(self, address: _Address | bytes) -> None: ... def close(self) -> None: ... def connect(self, address: _Address | bytes) -> None: ... @@ -404,13 +403,14 @@ class socket: def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... def gettimeout(self) -> float | None: ... if sys.platform == "win32": - def ioctl(self, control: int, option: int | Tuple[int, int, int]) -> None: ... + def ioctl(self, control: int, option: int | tuple[int, int, int]) -> None: ... + def listen(self, __backlog: int) -> None: ... # Note that the makefile's documented windows-specific behavior is not represented def makefile(self, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... + def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def send(self, data: bytes, flags: int = ...) -> int: ... def sendall(self, data: bytes, flags: int = ...) -> None: ... # return type: None on success @@ -423,14 +423,15 @@ class socket: def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... if sys.platform == "win32": def share(self, process_id: int) -> bytes: ... + def shutdown(self, how: int) -> None: ... # ----- Functions ----- def create_connection( - address: Tuple[str | None, int], + address: tuple[str | None, int], timeout: float | None = ..., - source_address: Tuple[bytearray | bytes | Text, int] | None = ..., + source_address: tuple[bytearray | bytes | Text, int] | None = ..., ) -> socket: ... def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... @@ -442,22 +443,22 @@ def getaddrinfo( socktype: int = ..., proto: int = ..., flags: int = ..., -) -> List[Tuple[AddressFamily, SocketKind, int, str, Tuple[Any, ...]]]: ... +) -> 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 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: Tuple[str, int] | Tuple[str, int, int, int], flags: int) -> Tuple[str, str]: ... +def gethostbyaddr(ip_address: str) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int) -> tuple[str, str]: ... def getprotobyname(protocolname: str) -> int: ... def getservbyname(servicename: str, protocolname: str = ...) -> int: ... def getservbyport(port: int, protocolname: str = ...) -> str: ... if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... else: - def socketpair(family: int | None = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + def socketpair(family: int | None = ..., 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 diff --git a/mypy/typeshed/stdlib/@python2/spwd.pyi b/mypy/typeshed/stdlib/@python2/spwd.pyi index 95122ce43d1e..b21242fc49e4 100644 --- a/mypy/typeshed/stdlib/@python2/spwd.pyi +++ b/mypy/typeshed/stdlib/@python2/spwd.pyi @@ -1,5 +1,5 @@ import sys -from typing import List, NamedTuple +from typing import NamedTuple if sys.platform != "win32": class struct_spwd(NamedTuple): @@ -12,5 +12,5 @@ if sys.platform != "win32": sp_inact: int sp_expire: int sp_flag: int - def getspall() -> List[struct_spwd]: ... + def getspall() -> list[struct_spwd]: ... def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi index d5d20d67b58e..d747be90fd0a 100644 --- a/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/sqlite3/__init__.pyi @@ -1 +1 @@ -from sqlite3.dbapi2 import * # noqa: F403 +from sqlite3.dbapi2 import * diff --git a/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi index 023a0506f4aa..90740bcf90a1 100644 --- a/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, List, Protocol, Text, Tuple, Type, TypeVar +from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, Text, TypeVar _T = TypeVar("_T") @@ -14,8 +15,8 @@ def DateFromTicks(ticks: float) -> Date: ... def TimeFromTicks(ticks: float) -> Time: ... def TimestampFromTicks(ticks: float) -> Timestamp: ... -version_info: Tuple[int, int, int] -sqlite_version_info: Tuple[int, int, int] +version_info: tuple[int, int, int] +sqlite_version_info: tuple[int, int, int] Binary = buffer # The remaining definitions are imported from _sqlite3. @@ -67,12 +68,12 @@ def connect( detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., ) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... +def register_adapter(__type: type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... class Cache(object): @@ -126,7 +127,7 @@ class Connection(object): def enable_load_extension(self, enabled: bool) -> None: ... def load_extension(self, path: str) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __enter__(self) -> Connection: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, t: type | None, exc: BaseException | None, tb: Any | None) -> None: ... class Cursor(Iterator[Any]): @@ -144,8 +145,8 @@ class Cursor(Iterator[Any]): 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: bytes | Text) -> Cursor: ... - def fetchall(self) -> List[Any]: ... - def fetchmany(self, size: int | None = ...) -> List[Any]: ... + def fetchall(self) -> list[Any]: ... + def fetchmany(self, size: int | None = ...) -> list[Any]: ... def fetchone(self) -> Any: ... def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sre_compile.pyi b/mypy/typeshed/stdlib/@python2/sre_compile.pyi index efc3e568a07c..30b4d2cb628c 100644 --- a/mypy/typeshed/stdlib/@python2/sre_compile.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_compile.pyi @@ -12,10 +12,10 @@ from sre_constants import ( SRE_INFO_PREFIX as SRE_INFO_PREFIX, ) from sre_parse import SubPattern -from typing import Any, List, Pattern, Tuple, Type +from typing import Any, Pattern MAXCODE: int -STRING_TYPES: Tuple[Type[str], Type[unicode]] +STRING_TYPES: tuple[type[str], type[unicode]] _IsStringType = int def isstring(obj: Any) -> _IsStringType: ... diff --git a/mypy/typeshed/stdlib/@python2/sre_constants.pyi b/mypy/typeshed/stdlib/@python2/sre_constants.pyi index bc15754d6fa1..09280512a7f4 100644 --- a/mypy/typeshed/stdlib/@python2/sre_constants.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_constants.pyi @@ -1,4 +1,4 @@ -from typing import Dict, List, TypeVar +from typing import TypeVar MAGIC: int MAXREPEAT: int @@ -72,14 +72,14 @@ CATEGORY_UNI_NOT_LINEBREAK: str _T = TypeVar("_T") -def makedict(list: List[_T]) -> Dict[_T, int]: ... +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] +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 diff --git a/mypy/typeshed/stdlib/@python2/sre_parse.pyi b/mypy/typeshed/stdlib/@python2/sre_parse.pyi index 35f6d4d32ae2..c4307bb9bb53 100644 --- a/mypy/typeshed/stdlib/@python2/sre_parse.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_parse.pyi @@ -1,38 +1,38 @@ -from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union +from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, 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, Tuple[str, str] | Tuple[str, List[Tuple[str, str]]]] -FLAGS: Dict[str, int] +DIGITS: set[Any] +OCTDIGITS: set[Any] +HEXDIGITS: set[Any] +WHITESPACE: set[Any] +ESCAPES: dict[str, tuple[str, int]] +CATEGORIES: dict[str, tuple[str, str] | tuple[str, list[tuple[str, str]]]] +FLAGS: dict[str, int] class Pattern: flags: int - open: List[int] + open: list[int] groups: int - groupdict: Dict[str, 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]] +_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] + data: list[_CodeType] width: int | None - def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... + def __init__(self, pattern, data: list[_CodeType] = ...) -> None: ... def dump(self, level: int = ...) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: int | slice) -> None: ... @@ -48,7 +48,7 @@ class Tokenizer: def __init__(self, string: str) -> None: ... def match(self, char: str, skip: int = ...) -> int: ... def get(self) -> str | None: ... - def tell(self) -> Tuple[int, str | None]: ... + def tell(self) -> tuple[int, str | None]: ... def seek(self, index: int) -> None: ... def isident(char: str) -> bool: ... @@ -56,7 +56,7 @@ 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]]] +_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/ssl.pyi b/mypy/typeshed/stdlib/@python2/ssl.pyi index aabecaaba87a..4eccf5875d55 100644 --- a/mypy/typeshed/stdlib/@python2/ssl.pyi +++ b/mypy/typeshed/stdlib/@python2/ssl.pyi @@ -1,14 +1,14 @@ import socket import sys -from _typeshed import StrPath -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Tuple, Union, overload +from _typeshed import Self, StrPath +from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Text, Union, overload from typing_extensions import Literal -_PCTRTT = Tuple[Tuple[str, str], ...] -_PCTRTTT = Tuple[_PCTRTT, ...] -_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] +_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]]] +_EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] _PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] _SC1ArgT = SSLSocket @@ -60,7 +60,7 @@ 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: str | None = ...) -> str: ... +def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... @@ -110,10 +110,10 @@ HAS_ALPN: bool HAS_ECDH: bool HAS_SNI: bool HAS_NPN: bool -CHANNEL_BINDING_TYPES: List[str] +CHANNEL_BINDING_TYPES: list[str] OPENSSL_VERSION: str -OPENSSL_VERSION_INFO: Tuple[int, int, int, int, int] +OPENSSL_VERSION_INFO: tuple[int, int, int, int, int] OPENSSL_VERSION_NUMBER: int ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int @@ -200,12 +200,12 @@ class SSLSocket(socket.socket): def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... - def cipher(self) -> Tuple[str, str, int] | None: ... + def cipher(self) -> tuple[str, str, int] | None: ... def compression(self) -> str | None: ... def get_channel_binding(self, cb_type: str = ...) -> bytes | None: ... def selected_alpn_protocol(self) -> str | None: ... def selected_npn_protocol(self) -> str | None: ... - def accept(self) -> Tuple[SSLSocket, socket._RetAddress]: ... + def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... def pending(self) -> int: ... @@ -213,19 +213,19 @@ class SSLSocket(socket.socket): class SSLContext: check_hostname: bool options: int - def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> SSLContext: ... + def __new__(cls: type[Self], protocol: int, *args: Any, **kwargs: Any) -> Self: ... @property def protocol(self) -> int: ... verify_flags: int verify_mode: int def __init__(self, protocol: int) -> None: ... - def cert_store_stats(self) -> Dict[str, int]: ... + def cert_store_stats(self) -> dict[str, int]: ... def load_cert_chain(self, certfile: StrPath, keyfile: StrPath | None = ..., password: _PasswordType | None = ...) -> None: ... def load_default_certs(self, purpose: Purpose = ...) -> None: ... def load_verify_locations( self, cafile: StrPath | None = ..., capath: StrPath | None = ..., cadata: Text | bytes | None = ... ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> List[_PeerCertRetDictType] | List[bytes]: ... + def get_ca_certs(self, binary_form: bool = ...) -> 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: ... @@ -241,7 +241,7 @@ class SSLContext: suppress_ragged_eofs: bool = ..., server_hostname: str | None = ..., ) -> SSLSocket: ... - def session_stats(self) -> Dict[str, int]: ... + def session_stats(self) -> dict[str, int]: ... # TODO below documented in cpython but not in docs.python.org # taken from python 3.4 diff --git a/mypy/typeshed/stdlib/@python2/string.pyi b/mypy/typeshed/stdlib/@python2/string.pyi index fe028dab39bd..79fce4f893c7 100644 --- a/mypy/typeshed/stdlib/@python2/string.pyi +++ b/mypy/typeshed/stdlib/@python2/string.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Iterable, List, Mapping, Sequence, Text, Tuple, overload +from typing import Any, AnyStr, Iterable, Mapping, Sequence, Text, overload ascii_letters: str ascii_lowercase: str @@ -27,9 +27,9 @@ 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 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: ... @@ -60,7 +60,7 @@ class Template: 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 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: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... def check_unused_args(self, used_args: Sequence[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/stringold.pyi b/mypy/typeshed/stdlib/@python2/stringold.pyi index d221547f1c07..80402b0069e3 100644 --- a/mypy/typeshed/stdlib/@python2/stringold.pyi +++ b/mypy/typeshed/stdlib/@python2/stringold.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, Iterable, List +from typing import AnyStr, Iterable whitespace: str lowercase: str @@ -8,7 +8,7 @@ digits: str hexdigits: str octdigits: str _idmap: str -_idmapL: List[str] | None +_idmapL: list[str] | None index_error = ValueError atoi_error = ValueError atof_error = ValueError @@ -20,8 +20,8 @@ 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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/strop.pyi b/mypy/typeshed/stdlib/@python2/strop.pyi index 81035eaabe79..9321bbe5bf5e 100644 --- a/mypy/typeshed/stdlib/@python2/strop.pyi +++ b/mypy/typeshed/stdlib/@python2/strop.pyi @@ -1,4 +1,4 @@ -from typing import List, Sequence +from typing import Sequence lowercase: str uppercase: str @@ -19,8 +19,8 @@ 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 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: ... diff --git a/mypy/typeshed/stdlib/@python2/struct.pyi b/mypy/typeshed/stdlib/@python2/struct.pyi index bf27d12783da..7129fbc4cfb6 100644 --- a/mypy/typeshed/stdlib/@python2/struct.pyi +++ b/mypy/typeshed/stdlib/@python2/struct.pyi @@ -1,6 +1,6 @@ from array import array from mmap import mmap -from typing import Any, Text, Tuple, Union +from typing import Any, Text, Union class error(Exception): ... @@ -10,8 +10,8 @@ _WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] def pack(fmt: _FmtType, *v: Any) -> bytes: ... def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... -def unpack(__format: _FmtType, __buffer: _BufferType) -> Tuple[Any, ...]: ... -def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... +def unpack(__format: _FmtType, __buffer: _BufferType) -> tuple[Any, ...]: ... +def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> tuple[Any, ...]: ... def calcsize(__format: _FmtType) -> int: ... class Struct: @@ -20,5 +20,5 @@ class Struct: 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, ...]: ... + def unpack(self, __buffer: _BufferType) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: _BufferType, offset: int = ...) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/subprocess.pyi b/mypy/typeshed/stdlib/@python2/subprocess.pyi index 8c101272322a..d2149c81aaaf 100644 --- a/mypy/typeshed/stdlib/@python2/subprocess.pyi +++ b/mypy/typeshed/stdlib/@python2/subprocess.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union +from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, TypeVar, Union _FILE = Union[None, int, IO[Any]] _TXT = Union[bytes, Text] @@ -96,7 +96,7 @@ class Popen(Generic[_T]): def poll(self) -> int | None: ... def wait(self) -> int: ... # morally: -> Tuple[Optional[bytes], Optional[bytes]] - def communicate(self, input: _TXT | None = ...) -> Tuple[bytes, bytes]: ... + def communicate(self, input: _TXT | None = ...) -> tuple[bytes, bytes]: ... def send_signal(self, signal: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sunau.pyi b/mypy/typeshed/stdlib/@python2/sunau.pyi index 3ee4b9651346..6d5caee7b199 100644 --- a/mypy/typeshed/stdlib/@python2/sunau.pyi +++ b/mypy/typeshed/stdlib/@python2/sunau.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, NoReturn, Text, Tuple, Union +from typing import IO, Any, NoReturn, Text, Union _File = Union[Text, IO[bytes]] @@ -19,7 +19,7 @@ AUDIO_FILE_ENCODING_ADPCM_G723_5: int AUDIO_FILE_ENCODING_ALAW_8: int AUDIO_UNKNOWN_SIZE: int -_sunau_params = Tuple[int, int, int, int, str, str] +_sunau_params = tuple[int, int, int, int, str, str] class Au_read: def __init__(self, f: _File) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/symbol.pyi b/mypy/typeshed/stdlib/@python2/symbol.pyi index a3561fe6b26f..052e3f1f8f42 100644 --- a/mypy/typeshed/stdlib/@python2/symbol.pyi +++ b/mypy/typeshed/stdlib/@python2/symbol.pyi @@ -1,5 +1,3 @@ -from typing import Dict - single_input: int file_input: int eval_input: int @@ -86,4 +84,4 @@ testlist1: int encoding_decl: int yield_expr: int -sym_name: Dict[int, str] +sym_name: dict[int, str] diff --git a/mypy/typeshed/stdlib/@python2/symtable.pyi b/mypy/typeshed/stdlib/@python2/symtable.pyi index bd3f25c7cb63..c0b701cc1df5 100644 --- a/mypy/typeshed/stdlib/@python2/symtable.pyi +++ b/mypy/typeshed/stdlib/@python2/symtable.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, Sequence, Text, Tuple +from typing import Any, Sequence, Text def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... @@ -15,17 +15,17 @@ class SymbolTable(object): 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]: ... + 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, ...]: ... + 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, ...]: ... + def get_methods(self) -> tuple[str, ...]: ... class Symbol(object): def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sys.pyi b/mypy/typeshed/stdlib/@python2/sys.pyi index d4858ec251fa..409b776cdcb0 100644 --- a/mypy/typeshed/stdlib/@python2/sys.pyi +++ b/mypy/typeshed/stdlib/@python2/sys.pyi @@ -1,9 +1,9 @@ from types import ClassType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, NoReturn, Text, Tuple, Type, Union +from typing import IO, Any, Callable, NoReturn, Text, Union # 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]] +_ExcInfo = tuple[type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, tuple[None, None, None]] class _flags: bytes_warning: int @@ -36,17 +36,17 @@ class _float_info: radix: int rounds: int -class _version_info(Tuple[int, int, int, str, 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] +_mercurial: tuple[str, str, str] api_version: int -argv: List[str] -builtin_module_names: Tuple[str, ...] +argv: list[str] +builtin_module_names: tuple[str, ...] byteorder: str copyright: str dont_write_bytecode: bool @@ -59,8 +59,8 @@ long_info: object maxint: int maxsize: int maxunicode: int -modules: Dict[str, Any] -path: List[str] +modules: dict[str, Any] +path: list[str] platform: str prefix: str py3kwarning: bool @@ -70,7 +70,7 @@ __stdout__: IO[str] stderr: IO[str] stdin: IO[str] stdout: IO[str] -subversion: Tuple[str, str, str] +subversion: tuple[str, str, str] version: str warnoptions: object float_info: _float_info @@ -81,11 +81,11 @@ 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] +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] +excepthook: Callable[[type[BaseException], BaseException, TracebackType], Any] exc_type: type | None exc_value: BaseException | ClassType exc_traceback: TracebackType @@ -103,7 +103,7 @@ class _WindowsVersionType: def getwindowsversion() -> _WindowsVersionType: ... def _clear_type_cache() -> None: ... -def _current_frames() -> Dict[int, FrameType]: ... +def _current_frames() -> dict[int, FrameType]: ... def _getframe(depth: int = ...) -> FrameType: ... def call_tracing(fn: Any, args: Any) -> Any: ... def __displayhook__(value: object) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sysconfig.pyi b/mypy/typeshed/stdlib/@python2/sysconfig.pyi index 2bef9e467bc9..17077144f6e9 100644 --- a/mypy/typeshed/stdlib/@python2/sysconfig.pyi +++ b/mypy/typeshed/stdlib/@python2/sysconfig.pyi @@ -1,17 +1,17 @@ -from typing import IO, Any, Dict, List, Tuple, overload +from typing import IO, Any, overload def get_config_var(name: str) -> str | None: ... @overload -def get_config_vars() -> Dict[str, Any]: ... +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: Dict[str, Any] | None = ..., expand: bool = ...) -> str: ... -def get_paths(scheme: str = ..., vars: Dict[str, Any] | None = ..., expand: bool = ...) -> Dict[str, str]: ... +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: dict[str, Any] | None = ..., expand: bool = ...) -> str: ... +def get_paths(scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... def is_python_build(check_home: bool = ...) -> bool: ... -def parse_config_h(fp: IO[Any], vars: Dict[str, Any] | None = ...) -> Dict[str, Any]: ... +def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = ...) -> dict[str, Any]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/tabnanny.pyi b/mypy/typeshed/stdlib/@python2/tabnanny.pyi index 95873761ee75..cf6eefc2e15f 100644 --- a/mypy/typeshed/stdlib/@python2/tabnanny.pyi +++ b/mypy/typeshed/stdlib/@python2/tabnanny.pyi @@ -1,4 +1,4 @@ -from typing import Iterable, Text, Tuple +from typing import Iterable, Text verbose: int filename_only: int @@ -10,4 +10,4 @@ class NannyNag(Exception): def get_line(self) -> str: ... def check(file: Text) -> None: ... -def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... +def process_tokens(tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/tarfile.pyi b/mypy/typeshed/stdlib/@python2/tarfile.pyi index c08c96b6f0d5..571bb19632a8 100644 --- a/mypy/typeshed/stdlib/@python2/tarfile.pyi +++ b/mypy/typeshed/stdlib/@python2/tarfile.pyi @@ -1,6 +1,7 @@ import io +from _typeshed import Self from types import TracebackType -from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Text, Tuple, Type +from typing import IO, Callable, Iterable, Iterator, Mapping, Text # tar constants NUL: bytes @@ -38,11 +39,11 @@ 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] +SUPPORTED_TYPES: tuple[bytes, ...] +REGULAR_TYPES: tuple[bytes, ...] +GNU_TYPES: tuple[bytes, ...] +PAX_FIELDS: tuple[str, ...] +PAX_NUMBER_FIELDS: dict[str, type] ENCODING: str @@ -56,7 +57,7 @@ def open( bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -76,12 +77,12 @@ class TarFile(Iterable[TarInfo]): mode: str fileobj: IO[bytes] | None format: int | None - tarinfo: Type[TarInfo] + tarinfo: type[TarInfo] dereference: bool | None ignore_zeros: bool | None encoding: str | None errors: str - fileobject: Type[ExFileObject] + fileobject: type[ExFileObject] pax_headers: Mapping[str, str] | None debug: int | None errorlevel: int | None @@ -93,7 +94,7 @@ class TarFile(Iterable[TarInfo]): mode: str = ..., fileobj: IO[bytes] | None = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -103,9 +104,9 @@ class TarFile(Iterable[TarInfo]): errorlevel: int | None = ..., copybufsize: int | None = ..., # undocumented ) -> None: ... - def __enter__(self) -> TarFile: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def __iter__(self) -> Iterator[TarInfo]: ... @classmethod @@ -117,7 +118,7 @@ class TarFile(Iterable[TarInfo]): bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -135,7 +136,7 @@ class TarFile(Iterable[TarInfo]): *, compresslevel: int = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -152,7 +153,7 @@ class TarFile(Iterable[TarInfo]): compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -169,7 +170,7 @@ class TarFile(Iterable[TarInfo]): compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -186,7 +187,7 @@ class TarFile(Iterable[TarInfo]): preset: int | None = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -195,8 +196,8 @@ class TarFile(Iterable[TarInfo]): errorlevel: int | None = ..., ) -> TarFile: ... def getmember(self, name: str) -> TarInfo: ... - def getmembers(self) -> List[TarInfo]: ... - def getnames(self) -> List[str]: ... + def getmembers(self) -> list[TarInfo]: ... + def getnames(self) -> list[str]: ... def list(self, verbose: bool = ...) -> None: ... def next(self) -> TarInfo | None: ... def extractall(self, path: Text = ..., members: Iterable[TarInfo] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/telnetlib.pyi b/mypy/typeshed/stdlib/@python2/telnetlib.pyi index dfb01f26398e..5cd47e28a95c 100644 --- a/mypy/typeshed/stdlib/@python2/telnetlib.pyi +++ b/mypy/typeshed/stdlib/@python2/telnetlib.pyi @@ -1,5 +1,5 @@ import socket -from typing import Any, Callable, Match, Pattern, Sequence, Tuple +from typing import Any, Callable, Match, Pattern, Sequence DEBUGLEVEL: int TELNET_PORT: int @@ -108,4 +108,4 @@ class Telnet: def listener(self) -> None: ... def expect( self, list: Sequence[Pattern[bytes] | bytes], timeout: float | None = ... - ) -> Tuple[int, Match[bytes] | None, bytes]: ... + ) -> tuple[int, Match[bytes] | None, bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/tempfile.pyi b/mypy/typeshed/stdlib/@python2/tempfile.pyi index c5f67d243ac8..3d94bdefeb74 100644 --- a/mypy/typeshed/stdlib/@python2/tempfile.pyi +++ b/mypy/typeshed/stdlib/@python2/tempfile.pyi @@ -1,6 +1,7 @@ +from _typeshed import Self from random import Random from thread import LockType -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Text, Tuple, overload +from typing import IO, Any, AnyStr, Iterable, Iterator, Text, overload TMP_MAX: int tempdir: str @@ -23,7 +24,7 @@ class _TemporaryFileWrapper(IO[str]): name: Any def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... def __del__(self) -> None: ... - def __enter__(self) -> _TemporaryFileWrapper: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, exc, value, tb) -> bool | None: ... def __getattr__(self, name: unicode) -> Any: ... def close(self) -> None: ... @@ -39,7 +40,7 @@ class _TemporaryFileWrapper(IO[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 readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def seekable(self) -> bool: ... def tell(self) -> int: ... @@ -82,9 +83,9 @@ class TemporaryDirectory: def __exit__(self, type, value, traceback) -> None: ... @overload -def mkstemp() -> Tuple[int, str]: ... +def mkstemp() -> tuple[int, str]: ... @overload -def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ..., text: bool = ...) -> Tuple[int, AnyStr]: ... +def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ..., text: bool = ...) -> tuple[int, AnyStr]: ... @overload def mkdtemp() -> str: ... @overload @@ -95,6 +96,6 @@ def mktemp() -> str: ... def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ...) -> AnyStr: ... def gettempdir() -> str: ... def gettempprefix() -> str: ... -def _candidate_tempdir_list() -> List[str]: ... +def _candidate_tempdir_list() -> list[str]: ... def _get_candidate_names() -> _RandomNameSequence | None: ... def _get_default_tempdir() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/termios.pyi b/mypy/typeshed/stdlib/@python2/termios.pyi index cee6b85f9ba5..6ef2f6818827 100644 --- a/mypy/typeshed/stdlib/@python2/termios.pyi +++ b/mypy/typeshed/stdlib/@python2/termios.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, List, Union +from typing import Any, Union if sys.platform != "win32": - _Attr = List[Union[int, List[Union[bytes, int]]]] + _Attr = list[Union[int, list[Union[bytes, int]]]] # TODO constants not really documented B0: int @@ -237,10 +237,11 @@ if sys.platform != "win32": VWERASE: int XCASE: int XTABS: int - def tcgetattr(__fd: FileDescriptorLike) -> List[Any]: ... + def tcgetattr(__fd: FileDescriptorLike) -> list[Any]: ... def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... def tcdrain(__fd: FileDescriptorLike) -> None: ... def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/textwrap.pyi b/mypy/typeshed/stdlib/@python2/textwrap.pyi index c4147b4bd538..cb9c034cc4ba 100644 --- a/mypy/typeshed/stdlib/@python2/textwrap.pyi +++ b/mypy/typeshed/stdlib/@python2/textwrap.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, Dict, List, Pattern +from typing import AnyStr, Pattern class TextWrapper(object): width: int = ... @@ -16,7 +16,7 @@ class TextWrapper(object): wordsep_re: Pattern[str] = ... wordsep_simple_re: Pattern[str] = ... whitespace_trans: str = ... - unicode_whitespace_trans: Dict[int, int] = ... + unicode_whitespace_trans: dict[int, int] = ... uspace: int = ... x: int = ... def __init__( @@ -31,7 +31,7 @@ class TextWrapper(object): drop_whitespace: bool = ..., break_on_hyphens: bool = ..., ) -> None: ... - def wrap(self, text: AnyStr) -> List[AnyStr]: ... + def wrap(self, text: AnyStr) -> list[AnyStr]: ... def fill(self, text: AnyStr) -> AnyStr: ... def wrap( @@ -45,7 +45,7 @@ def wrap( break_long_words: bool = ..., drop_whitespace: bool = ..., break_on_hyphens: bool = ..., -) -> List[AnyStr]: ... +) -> list[AnyStr]: ... def fill( text: AnyStr, width: int = ..., diff --git a/mypy/typeshed/stdlib/@python2/this.pyi b/mypy/typeshed/stdlib/@python2/this.pyi index 0687a6675cca..8de996b04aec 100644 --- a/mypy/typeshed/stdlib/@python2/this.pyi +++ b/mypy/typeshed/stdlib/@python2/this.pyi @@ -1,4 +1,2 @@ -from typing import Dict - s: str -d: Dict[str, str] +d: dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/thread.pyi b/mypy/typeshed/stdlib/@python2/thread.pyi index b3ba062a498e..9823dddcbfd7 100644 --- a/mypy/typeshed/stdlib/@python2/thread.pyi +++ b/mypy/typeshed/stdlib/@python2/thread.pyi @@ -1,9 +1,11 @@ from typing import Any, Callable +from typing_extensions import final def _count() -> int: ... class error(Exception): ... +@final class LockType: def acquire(self, waitflag: int = ...) -> bool: ... def acquire_lock(self, waitflag: int = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/threading.pyi b/mypy/typeshed/stdlib/@python2/threading.pyi index e45a1b5c4a89..611552dc92ab 100644 --- a/mypy/typeshed/stdlib/@python2/threading.pyi +++ b/mypy/typeshed/stdlib/@python2/threading.pyi @@ -1,19 +1,36 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, Text, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") -__all__: List[str] +__all__ = [ + "activeCount", + "active_count", + "Condition", + "currentThread", + "current_thread", + "enumerate", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Timer", + "setprofile", + "settrace", + "local", + "stack_size", +] def active_count() -> int: ... def activeCount() -> int: ... def current_thread() -> Thread: ... def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... +def enumerate() -> list[Thread]: ... def settrace(func: _TF) -> None: ... def setprofile(func: _PF | None) -> None: ... def stack_size(size: int = ...) -> int: ... @@ -53,7 +70,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -63,7 +80,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -74,7 +91,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -86,7 +103,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def __enter__(self, blocking: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/time.pyi b/mypy/typeshed/stdlib/@python2/time.pyi index 48ae9da9c65e..93cdafa7cafa 100644 --- a/mypy/typeshed/stdlib/@python2/time.pyi +++ b/mypy/typeshed/stdlib/@python2/time.pyi @@ -1,13 +1,14 @@ import sys -from typing import Any, NamedTuple, Tuple +from typing import Any, NamedTuple +from typing_extensions import final -_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_TimeTuple = tuple[int, int, int, int, int, int, int, int, int] accept2dyear: bool altzone: int daylight: int timezone: int -tzname: Tuple[str, str] +tzname: tuple[str, str] class _struct_time(NamedTuple): tm_year: int @@ -26,6 +27,7 @@ class _struct_time(NamedTuple): @property def n_unnamed_fields(self) -> int: ... +@final class struct_time(_struct_time): def __init__(self, o: _TimeTuple, _arg: Any = ...) -> None: ... def __new__(cls, o: _TimeTuple, _arg: Any = ...) -> struct_time: ... diff --git a/mypy/typeshed/stdlib/@python2/timeit.pyi b/mypy/typeshed/stdlib/@python2/timeit.pyi index ecb528725a9c..3a7f6e0e0841 100644 --- a/mypy/typeshed/stdlib/@python2/timeit.pyi +++ b/mypy/typeshed/stdlib/@python2/timeit.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, List, Sequence, Text, Union +from typing import IO, Any, Callable, Sequence, Text, Union _str = Union[str, Text] _Timer = Callable[[], float] @@ -10,10 +10,10 @@ class Timer: def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... def print_exc(self, file: IO[str] | None = ...) -> None: ... def timeit(self, number: int = ...) -> float: ... - def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... + def repeat(self, repeat: int = ..., number: int = ...) -> list[float]: ... def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... -def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> List[float]: ... +def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> list[float]: ... _timerFunc = Callable[[], float] diff --git a/mypy/typeshed/stdlib/@python2/toaiff.pyi b/mypy/typeshed/stdlib/@python2/toaiff.pyi index b70e026d6d8e..d4b86f9bb756 100644 --- a/mypy/typeshed/stdlib/@python2/toaiff.pyi +++ b/mypy/typeshed/stdlib/@python2/toaiff.pyi @@ -1,11 +1,10 @@ from pipes import Template -from typing import Dict, List -table: Dict[str, Template] +table: dict[str, Template] t: Template uncompress: Template class error(Exception): ... def toaiff(filename: str) -> str: ... -def _toaiff(filename: str, temps: List[str]) -> str: ... +def _toaiff(filename: str, temps: list[str]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/token.pyi b/mypy/typeshed/stdlib/@python2/token.pyi index 4ba710470624..d88aba8678a0 100644 --- a/mypy/typeshed/stdlib/@python2/token.pyi +++ b/mypy/typeshed/stdlib/@python2/token.pyi @@ -1,5 +1,3 @@ -from typing import Dict - ENDMARKER: int NAME: int NUMBER: int @@ -55,7 +53,7 @@ OP: int ERRORTOKEN: int N_TOKENS: int NT_OFFSET: int -tok_name: Dict[int, str] +tok_name: dict[int, str] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/tokenize.pyi index 98ec01a6cb75..f045f76cc39e 100644 --- a/mypy/typeshed/stdlib/@python2/tokenize.pyi +++ b/mypy/typeshed/stdlib/@python2/tokenize.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple +from typing import Any, Callable, Generator, Iterable, Iterator __author__: str __credits__: str @@ -97,27 +97,27 @@ VBAREQUAL: int Whitespace: str chain: type double3prog: type -endprogs: Dict[str, Any] +endprogs: dict[str, Any] pseudoprog: type single3prog: type -single_quoted: Dict[str, str] +single_quoted: dict[str, str] t: str tabsize: int -tok_name: Dict[int, str] +tok_name: dict[int, str] tokenprog: type -triple_quoted: Dict[str, str] +triple_quoted: dict[str, str] x: str -_Pos = Tuple[int, int] -_TokenType = Tuple[int, str, _Pos, _Pos, 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 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): ... @@ -126,8 +126,8 @@ class TokenError(Exception): ... class Untokenizer: prev_col: int prev_row: int - tokens: List[str] + 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 compat(self, token: tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/trace.pyi b/mypy/typeshed/stdlib/@python2/trace.pyi index 62f228673a55..aa35754cfdfc 100644 --- a/mypy/typeshed/stdlib/@python2/trace.pyi +++ b/mypy/typeshed/stdlib/@python2/trace.pyi @@ -1,25 +1,27 @@ import types from _typeshed import StrPath -from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, TypeVar +from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar +from typing_extensions import ParamSpec _T = TypeVar("_T") +_P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] +_fileModuleFunction = tuple[str, Optional[str], str] class CoverageResults: def __init__( self, - counts: Dict[Tuple[str, int], int] | None = ..., - calledfuncs: Dict[_fileModuleFunction, int] | None = ..., + counts: dict[tuple[str, int], int] | None = ..., + calledfuncs: dict[_fileModuleFunction, int] | None = ..., infile: StrPath | None = ..., - callers: Dict[Tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., + callers: dict[tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., outfile: StrPath | None = ..., ) -> None: ... # undocumented def update(self, other: CoverageResults) -> None: ... def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: StrPath | None = ...) -> None: ... def write_results_file( self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = ... - ) -> Tuple[int, int]: ... + ) -> tuple[int, int]: ... class Trace: def __init__( @@ -38,7 +40,7 @@ class Trace: def runctx( self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ... ) -> None: ... - def runfunc(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/traceback.pyi b/mypy/typeshed/stdlib/@python2/traceback.pyi index 2152ab255942..94c75e5ef6b1 100644 --- a/mypy/typeshed/stdlib/@python2/traceback.pyi +++ b/mypy/typeshed/stdlib/@python2/traceback.pyi @@ -1,11 +1,11 @@ from types import FrameType, TracebackType -from typing import IO, List, Optional, Tuple, Type +from typing import IO, Optional -_PT = Tuple[str, int, str, Optional[str]] +_PT = tuple[str, int, str, Optional[str]] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_exception( - etype: Type[BaseException] | None, + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., @@ -14,14 +14,14 @@ def print_exception( def print_exc(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_last(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> List[_PT]: ... -def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[_PT]: ... -def format_list(extracted_list: List[_PT]) -> List[str]: ... -def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> List[str]: ... +def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> list[_PT]: ... +def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> list[_PT]: ... +def format_list(extracted_list: list[_PT]) -> list[str]: ... +def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... def format_exception( - etype: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ... -) -> List[str]: ... + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ... +) -> list[str]: ... def format_exc(limit: int | None = ...) -> str: ... -def format_tb(tb: TracebackType | None, limit: int | None = ...) -> List[str]: ... -def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[str]: ... +def format_tb(tb: TracebackType | None, limit: int | None = ...) -> list[str]: ... +def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> list[str]: ... def tb_lineno(tb: TracebackType) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/turtle.pyi b/mypy/typeshed/stdlib/@python2/turtle.pyi index 659dfd31b161..cb52479864a2 100644 --- a/mypy/typeshed/stdlib/@python2/turtle.pyi +++ b/mypy/typeshed/stdlib/@python2/turtle.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable, Dict, List, Sequence, Text, Tuple, TypeVar, Union, overload +from _typeshed import Self +from typing import Any, Callable, Sequence, Text, Union, overload # TODO: Replace these aliases once we have Python 2 stubs for the Tkinter module. Canvas = Any @@ -8,18 +9,18 @@ PhotoImage = Any # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[Text, Tuple[float, float, float]] +_Color = Union[Text, tuple[float, float, float]] _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = Dict[str, Any] +_PenState = dict[str, Any] _Speed = Union[str, float] -_PolygonCoords = Sequence[Tuple[float, float]] +_PolygonCoords = Sequence[tuple[float, float]] # TODO: Type this more accurately # Vec2D is actually a custom subclass of 'tuple'. -Vec2D = Tuple[float, float] +Vec2D = tuple[float, float] class TurtleScreenBase(object): cv: Canvas = ... @@ -50,7 +51,7 @@ class TurtleScreen(TurtleScreenBase): @overload def colormode(self, cmode: float) -> None: ... def reset(self) -> None: ... - def turtles(self) -> List[Turtle]: ... + def turtles(self) -> list[Turtle]: ... @overload def bgcolor(self) -> _AnyColor: ... @overload @@ -69,7 +70,7 @@ class TurtleScreen(TurtleScreenBase): def window_width(self) -> int: ... def window_height(self) -> int: ... def getcanvas(self) -> Canvas: ... - def getshapes(self) -> List[str]: ... + def getshapes(self) -> list[str]: ... def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... def onkey(self, fun: Callable[[], Any], key: str) -> None: ... def listen(self, xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... @@ -79,7 +80,7 @@ class TurtleScreen(TurtleScreenBase): @overload def bgpic(self, picname: str) -> None: ... @overload - def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... + 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: _Color | None = ...) -> None: ... @@ -89,7 +90,7 @@ class TurtleScreen(TurtleScreenBase): addshape = register_shape class TNavigator(object): - START_ORIENTATION: Dict[str, Vec2D] = ... + START_ORIENTATION: dict[str, Vec2D] = ... DEFAULT_MODE: str = ... DEFAULT_ANGLEOFFSET: int = ... DEFAULT_ANGLEORIENT: int = ... @@ -105,18 +106,18 @@ class TNavigator(object): def xcor(self) -> float: ... def ycor(self) -> float: ... @overload - def goto(self, x: Tuple[float, float], y: None = ...) -> None: ... + 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: TNavigator | Tuple[float, float], y: None = ...) -> float: ... + def distance(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def distance(self, x: float, y: float) -> float: ... @overload - def towards(self, x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... + def towards(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def towards(self, x: float, y: float) -> float: ... def heading(self) -> float: ... @@ -162,7 +163,7 @@ class TPen(object): @overload def fillcolor(self, r: float, g: float, b: float) -> None: ... @overload - def color(self) -> Tuple[_AnyColor, _AnyColor]: ... + def color(self) -> tuple[_AnyColor, _AnyColor]: ... @overload def color(self, color: _Color) -> None: ... @overload @@ -187,7 +188,7 @@ class TPen(object): pensize: int = ..., speed: int = ..., resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., + stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., ) -> None: ... @@ -199,8 +200,6 @@ class TPen(object): st = showturtle ht = hideturtle -_T = TypeVar("_T") - class RawTurtle(TPen, TNavigator): def __init__( self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... @@ -209,14 +208,14 @@ class RawTurtle(TPen, TNavigator): def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self: Self) -> Self: ... @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 + def shapesize(self) -> tuple[float, float, float]: ... # type: ignore @overload def shapesize( self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... @@ -231,18 +230,18 @@ class RawTurtle(TPen, TNavigator): # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp(self) -> Any: ... - def clearstamp(self, stampid: int | Tuple[int, ...]) -> None: ... + def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ... def clearstamps(self, n: int | None = ...) -> None: ... def filling(self) -> bool: ... def begin_fill(self) -> None: ... def end_fill(self) -> None: ... def dot(self, size: int | None = ..., *color: _Color) -> None: ... - def write(self, arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> 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) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self: Self) -> Self: ... getpen = getturtle def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... @@ -297,7 +296,7 @@ def colormode(cmode: None = ...) -> float: ... @overload def colormode(cmode: float) -> None: ... def reset() -> None: ... -def turtles() -> List[Turtle]: ... +def turtles() -> list[Turtle]: ... @overload def bgcolor() -> _AnyColor: ... @overload @@ -316,7 +315,7 @@ def update() -> None: ... def window_width() -> int: ... def window_height() -> int: ... def getcanvas() -> Canvas: ... -def getshapes() -> List[str]: ... +def getshapes() -> list[str]: ... def onclick(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... def onkey(fun: Callable[[], Any], key: str) -> None: ... def listen(xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... @@ -326,7 +325,7 @@ def bgpic(picname: None = ...) -> str: ... @overload def bgpic(picname: str) -> None: ... @overload -def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... +def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ... @overload def screensize(canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... @@ -354,18 +353,18 @@ def pos() -> Vec2D: ... def xcor() -> float: ... def ycor() -> float: ... @overload -def goto(x: Tuple[float, float], y: None = ...) -> None: ... +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: TNavigator | Tuple[float, float], y: None = ...) -> float: ... +def distance(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def distance(x: float, y: float) -> float: ... @overload -def towards(x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... +def towards(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def towards(x: float, y: float) -> float: ... def heading() -> float: ... @@ -411,7 +410,7 @@ def fillcolor(color: _Color) -> None: ... @overload def fillcolor(r: float, g: float, b: float) -> None: ... @overload -def color() -> Tuple[_AnyColor, _AnyColor]: ... +def color() -> tuple[_AnyColor, _AnyColor]: ... @overload def color(color: _Color) -> None: ... @overload @@ -436,7 +435,7 @@ def pen( pensize: int = ..., speed: int = ..., resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., + stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., ) -> None: ... @@ -460,7 +459,7 @@ def shape(name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapesize() -> Tuple[float, float, float]: ... # type: ignore +def shapesize() -> tuple[float, float, float]: ... # type: ignore @overload def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... def settiltangle(angle: float) -> None: ... @@ -474,13 +473,13 @@ def tilt(angle: float) -> None: ... # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp() -> Any: ... -def clearstamp(stampid: int | Tuple[int, ...]) -> None: ... +def clearstamp(stampid: int | tuple[int, ...]) -> None: ... def clearstamps(n: int | None = ...) -> None: ... def filling() -> bool: ... def begin_fill() -> None: ... def end_fill() -> None: ... def dot(size: int | None = ..., *color: _Color) -> None: ... -def write(arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> 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() -> _PolygonCoords | None: ... diff --git a/mypy/typeshed/stdlib/@python2/types.pyi b/mypy/typeshed/stdlib/@python2/types.pyi index 0feee4530586..d2194296aa17 100644 --- a/mypy/typeshed/stdlib/@python2/types.pyi +++ b/mypy/typeshed/stdlib/@python2/types.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Iterable, Iterator, TypeVar, overload _T = TypeVar("_T") @@ -16,7 +16,7 @@ BooleanType = bool ComplexType = complex StringType = str UnicodeType = unicode -StringTypes: Tuple[Type[StringType], Type[UnicodeType]] +StringTypes: tuple[type[StringType], type[UnicodeType]] BufferType = buffer TupleType = tuple ListType = list @@ -27,12 +27,12 @@ class _Cell: cell_contents: Any class FunctionType: - func_closure: Tuple[_Cell, ...] | None = ... + func_closure: tuple[_Cell, ...] | None = ... func_code: CodeType = ... - func_defaults: Tuple[Any, ...] | None = ... - func_dict: Dict[str, Any] = ... + func_defaults: tuple[Any, ...] | None = ... + func_dict: dict[str, Any] = ... func_doc: str | None = ... - func_globals: Dict[str, Any] = ... + func_globals: dict[str, Any] = ... func_name: str = ... __closure__ = func_closure __code__ = func_code @@ -43,10 +43,10 @@ class FunctionType: def __init__( self, code: CodeType, - globals: Dict[str, Any], + globals: dict[str, Any], name: str | None = ..., - argdefs: Tuple[object, ...] | None = ..., - closure: Tuple[_Cell, ...] | None = ..., + argdefs: tuple[object, ...] | None = ..., + closure: tuple[_Cell, ...] | None = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: object | None, type: type | None) -> UnboundMethodType: ... @@ -55,19 +55,19 @@ LambdaType = FunctionType class CodeType: co_argcount: int - co_cellvars: Tuple[str, ...] + co_cellvars: tuple[str, ...] co_code: str - co_consts: Tuple[Any, ...] + co_consts: tuple[Any, ...] co_filename: str co_firstlineno: int co_flags: int - co_freevars: Tuple[str, ...] + co_freevars: tuple[str, ...] co_lnotab: str co_name: str - co_names: Tuple[str, ...] + co_names: tuple[str, ...] co_nlocals: int co_stacksize: int - co_varnames: Tuple[str, ...] + co_varnames: tuple[str, ...] def __init__( self, argcount: int, @@ -75,15 +75,15 @@ class CodeType: stacksize: int, flags: int, codestring: str, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[Any, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, firstlineno: int, lnotab: str, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., ) -> None: ... class GeneratorType: @@ -95,7 +95,7 @@ class GeneratorType: def next(self) -> Any: ... def send(self, __arg: Any) -> Any: ... @overload - def throw(self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ...) -> Any: ... + def throw(self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ...) -> Any: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Any: ... @@ -127,7 +127,7 @@ class ModuleType: __name__: str __package__: str | None __path__: Iterable[str] | None - __dict__: Dict[str, Any] + __dict__: dict[str, Any] def __init__(self, name: str, doc: str | None = ...) -> None: ... FileType = file @@ -141,15 +141,15 @@ class TracebackType: class FrameType: f_back: FrameType - f_builtins: Dict[str, Any] + 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_globals: dict[str, Any] f_lasti: int f_lineno: int | None - f_locals: Dict[str, Any] + f_locals: dict[str, Any] f_restricted: bool f_trace: Callable[[], None] def clear(self) -> None: ... @@ -161,15 +161,15 @@ class EllipsisType: ... class DictProxyType: # TODO is it possible to have non-string keys? # no __init__ - def copy(self) -> Dict[Any, Any]: ... + def copy(self) -> dict[Any, Any]: ... def get(self, key: str, default: _T = ...) -> Any | _T: ... def has_key(self, key: str) -> bool: ... - def items(self) -> List[Tuple[str, Any]]: ... - def iteritems(self) -> Iterator[Tuple[str, Any]]: ... + 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 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]: ... diff --git a/mypy/typeshed/stdlib/@python2/typing.pyi b/mypy/typeshed/stdlib/@python2/typing.pyi index a1b02e81990c..affa82c825a2 100644 --- a/mypy/typeshed/stdlib/@python2/typing.pyi +++ b/mypy/typeshed/stdlib/@python2/typing.pyi @@ -1,4 +1,5 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +from _typeshed import Self from abc import ABCMeta, abstractmethod from types import CodeType, FrameType, TracebackType @@ -9,36 +10,44 @@ Any = object() class TypeVar: __name__: str - __bound__: Type[Any] | None - __constraints__: Tuple[Type[Any], ...] + __bound__: type[Any] | None + __constraints__: tuple[type[Any], ...] __covariant__: bool __contravariant__: bool def __init__( - self, name: str, *constraints: Type[Any], bound: Type[Any] | None = ..., covariant: bool = ..., contravariant: bool = ... + self, name: str, *constraints: type[Any], bound: type[Any] | None = ..., covariant: bool = ..., contravariant: bool = ... ) -> None: ... _promote = object() +# N.B. Keep this definition in sync with typing_extensions._SpecialForm class _SpecialForm(object): def __getitem__(self, typeargs: Any) -> object: ... -Union: _SpecialForm = ... -Optional: _SpecialForm = ... -Tuple: _SpecialForm = ... +# Unlike the vast majority module-level objects in stub files, +# these `_SpecialForm` objects in typing need the default value `= ...`, +# due to the fact that they are used elswhere in the same file. +# Otherwise, flake8 erroneously flags them as undefined. +# `_SpecialForm` objects in typing.py that are not used elswhere in the same file +# do not need the default value assignment. Generic: _SpecialForm = ... Protocol: _SpecialForm = ... Callable: _SpecialForm = ... -Type: _SpecialForm = ... -ClassVar: _SpecialForm = ... -Final: _SpecialForm = ... +Union: _SpecialForm = ... + +Optional: _SpecialForm +Tuple: _SpecialForm +Type: _SpecialForm +ClassVar: _SpecialForm +Final: _SpecialForm _F = TypeVar("_F", bound=Callable[..., Any]) def final(f: _F) -> _F: ... def overload(f: _F) -> _F: ... -Literal: _SpecialForm = ... +Literal: _SpecialForm # TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... +TypedDict: object class GenericMeta(type): ... @@ -49,7 +58,6 @@ 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. @@ -57,7 +65,7 @@ _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]) +_TC = TypeVar("_TC", bound=type[object]) def no_type_check(f: _F) -> _F: ... def no_type_check_decorator(decorator: _F) -> _F: ... @@ -77,7 +85,7 @@ Counter = _Alias() Deque = _Alias() # Predefined type variables. -AnyStr = TypeVar("AnyStr", str, unicode) +AnyStr = TypeVar("AnyStr", str, unicode) # noqa: Y001 # Abstract base classes. @@ -139,7 +147,7 @@ class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): @overload @abstractmethod def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> _T_co: ... @overload @abstractmethod @@ -202,7 +210,7 @@ class MutableSequence(Sequence[_T], Generic[_T]): def reverse(self) -> None: ... def pop(self, index: int = ...) -> _T: ... def remove(self, object: _T) -> None: ... - def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + def __iadd__(self: Self, x: Iterable[_T]) -> Self: ... class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): @abstractmethod @@ -231,18 +239,18 @@ class MutableSet(AbstractSet[_T], Generic[_T]): def clear(self) -> None: ... def pop(self) -> _T: ... def remove(self, element: _T) -> None: ... - def __ior__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ior__(self: Self, s: AbstractSet[_T]) -> Self: ... + def __iand__(self: Self, s: AbstractSet[Any]) -> Self: ... + def __ixor__(self: Self, s: AbstractSet[_T]) -> Self: ... + def __isub__(self: Self, s: AbstractSet[Any]) -> Self: ... class MappingView(object): def __len__(self) -> int: ... -class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): +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]]: ... + 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: ... @@ -258,7 +266,7 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): class ContextManager(Protocol[_T_co]): def __enter__(self) -> _T_co: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None ) -> bool | None: ... class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): @@ -273,10 +281,10 @@ class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): def get(self, k: _KT, default: _VT_co | _T) -> _VT_co | _T: ... def keys(self) -> list[_KT]: ... def values(self) -> list[_VT_co]: ... - def items(self) -> list[Tuple[_KT, _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 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 @@ -292,18 +300,18 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): def pop(self, k: _KT) -> _VT: ... @overload def pop(self, k: _KT, default: _VT | _T = ...) -> _VT | _T: ... - def popitem(self) -> Tuple[_KT, _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: ... + def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... Text = unicode -TYPE_CHECKING = True +TYPE_CHECKING: bool class IO(Iterator[AnyStr], Generic[AnyStr]): # TODO detach @@ -354,7 +362,7 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, t: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, t: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... class BinaryIO(IO[str]): @@ -403,16 +411,16 @@ class Match(Generic[AnyStr]): @overload def group(self, group1: str) -> AnyStr: ... @overload - def group(self, group1: int, group2: int, *groups: int) -> Tuple[AnyStr, ...]: ... + 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 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: int | str = ...) -> int: ... def end(self, __group: int | str = ...) -> int: ... - def span(self, __group: int | str = ...) -> Tuple[int, int]: ... + def span(self, __group: int | str = ...) -> tuple[int, int]: ... @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + 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 @@ -437,9 +445,9 @@ class Pattern(Generic[AnyStr]): @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]: ... + 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]: ... + def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> tuple[_AnyStr2, int]: ... # Functions @@ -447,7 +455,7 @@ def get_type_hints( obj: Callable[..., Any], globalns: Dict[Text, Any] | None = ..., localns: Dict[Text, Any] | None = ... ) -> None: ... @overload -def cast(tp: Type[_T], obj: Any) -> _T: ... +def cast(tp: type[_T], obj: Any) -> _T: ... @overload def cast(tp: str, obj: Any) -> Any: ... @overload @@ -456,17 +464,17 @@ 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: ... +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 _make(cls: type[Self], iterable: Iterable[Any]) -> Self: ... def _asdict(self) -> Dict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + def _replace(self: Self, **kwargs: Any) -> Self: ... # 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: ... + def copy(self: Self) -> Self: ... # 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: ... @@ -479,7 +487,7 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def viewvalues(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... -def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... +def NewType(name: str, tp: type[_T]) -> type[_T]: ... # This itself is only available during type checking def type_check_only(func_or_cls: _F) -> _F: ... diff --git a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi index d946cc278d32..53957910576c 100644 --- a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi @@ -1,5 +1,6 @@ import abc -from typing import ( +from _typeshed import Self +from typing import ( # noqa Y022 TYPE_CHECKING as TYPE_CHECKING, Any, Callable, @@ -8,44 +9,41 @@ from typing import ( Counter as Counter, DefaultDict as DefaultDict, Deque as Deque, - Dict, ItemsView, KeysView, Mapping, NewType as NewType, NoReturn as NoReturn, + Protocol as Protocol, Text as Text, - Tuple, Type as Type, TypeVar, ValuesView, _Alias, overload as overload, + runtime_checkable as runtime_checkable, ) _T = TypeVar("_T") _F = TypeVar("_F", bound=Callable[..., Any]) -_TC = TypeVar("_TC", bound=Type[object]) +# unfortunately we have to duplicate this class definition from typing.pyi or we break pytype class _SpecialForm: - def __getitem__(self, typeargs: Any) -> Any: ... - -def runtime_checkable(cls: _TC) -> _TC: ... + def __getitem__(self, typeargs: Any) -> object: ... # This alias for above is kept here for backwards compatibility. runtime = runtime_checkable -Protocol: _SpecialForm = ... -Final: _SpecialForm = ... +Final: _SpecialForm def final(f: _F) -> _F: ... -Literal: _SpecialForm = ... +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: ... + def copy(self: Self) -> Self: ... # 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: ... @@ -59,19 +57,19 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def __delitem__(self, k: NoReturn) -> None: ... # TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... +TypedDict: object OrderedDict = _Alias() def get_type_hints( obj: Callable[..., Any], - globalns: Dict[str, Any] | None = ..., - localns: Dict[str, Any] | None = ..., + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., include_extras: bool = ..., -) -> Dict[str, Any]: ... +) -> dict[str, Any]: ... -Annotated: _SpecialForm = ... -_AnnotatedAlias: Any = ... # undocumented +Annotated: _SpecialForm +_AnnotatedAlias: Any # undocumented @runtime_checkable class SupportsIndex(Protocol, metaclass=abc.ABCMeta): @@ -89,17 +87,17 @@ class ParamSpecKwargs: class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: type[Any] | None __covariant__: bool __contravariant__: bool def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, name: str, *, bound: None | type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... ) -> None: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... -Concatenate: _SpecialForm = ... -TypeAlias: _SpecialForm = ... -TypeGuard: _SpecialForm = ... +Concatenate: _SpecialForm +TypeAlias: _SpecialForm +TypeGuard: _SpecialForm diff --git a/mypy/typeshed/stdlib/@python2/unittest.pyi b/mypy/typeshed/stdlib/@python2/unittest.pyi index 65a5a7878de6..9db413d996bb 100644 --- a/mypy/typeshed/stdlib/@python2/unittest.pyi +++ b/mypy/typeshed/stdlib/@python2/unittest.pyi @@ -1,35 +1,18 @@ import datetime import types +from _typeshed import Self from abc import ABCMeta, abstractmethod -from typing import ( - Any, - Callable, - Dict, - FrozenSet, - Iterable, - Iterator, - List, - Mapping, - NoReturn, - Pattern, - Sequence, - Set, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, Iterable, Iterator, Mapping, NoReturn, Pattern, Sequence, Text, TextIO, TypeVar, Union, overload +from typing_extensions import ParamSpec _T = TypeVar("_T") _FT = TypeVar("_FT") +_P = ParamSpec("_P") -_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_ExceptionType = Union[type[BaseException], tuple[type[BaseException], ...]] _Regexp = Union[Text, Pattern[Text]] -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, types.TracebackType], tuple[None, None, None]] class Testable(metaclass=ABCMeta): @abstractmethod @@ -42,11 +25,11 @@ class Testable(metaclass=ABCMeta): # 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] + 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 @@ -66,17 +49,17 @@ class TestResult: class _AssertRaisesBaseContext: expected: Any - failureException: Type[BaseException] + failureException: type[BaseException] obj_name: str expected_regex: Pattern[str] class _AssertRaisesContext(_AssertRaisesBaseContext): exception: Any - def __enter__(self) -> _AssertRaisesContext: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, exc_type, exc_value, tb) -> bool: ... class TestCase(Testable): - failureException: Type[BaseException] + failureException: type[BaseException] longMessage: bool maxDiff: int | None # undocumented @@ -141,10 +124,10 @@ class TestCase(Testable): 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: Set[Any] | FrozenSet[Any], second: Set[Any] | FrozenSet[Any], msg: object = ...) -> None: ... - def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], msg: object = ...) -> 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: set[Any] | frozenset[Any], second: 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 @@ -174,8 +157,8 @@ class TestCase(Testable): 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: type | Tuple[type, ...], msg: object = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: object = ...) -> None: ... def fail(self, msg: object = ...) -> NoReturn: ... def countTestCases(self) -> int: ... def defaultTestResult(self) -> TestResult: ... @@ -210,13 +193,13 @@ class TestSuite(Testable): class TestLoader: testMethodPrefix: str sortTestMethodsUsing: Callable[[str, str], int] | None - suiteClass: Callable[[List[TestCase]], TestSuite] - def loadTestsFromTestCase(self, testCaseClass: Type[TestCase]) -> TestSuite: ... + 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: types.ModuleType | None = ...) -> TestSuite: ... - def loadTestsFromNames(self, names: List[str] = ..., module: types.ModuleType | None = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: list[str] = ..., module: types.ModuleType | None = ...) -> TestSuite: ... def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + def getTestCaseNames(self, testCaseClass: type[TestCase] = ...) -> list[str]: ... defaultTestLoader: TestLoader @@ -224,7 +207,7 @@ 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 + def printErrorList(self, flavour: str, errors: list[tuple[TestCase, str]]) -> None: ... # undocumented class TextTestRunner: def __init__( @@ -234,7 +217,7 @@ class TextTestRunner: verbosity: int = ..., failfast: bool = ..., buffer: bool = ..., - resultclass: Type[TestResult] | None = ..., + resultclass: type[TestResult] | None = ..., ) -> None: ... def _makeResult(self) -> TestResult: ... def run(self, test: Testable) -> TestResult: ... # undocumented @@ -256,7 +239,7 @@ def main( module: None | Text | types.ModuleType = ..., defaultTest: str | None = ..., argv: Sequence[str] | None = ..., - testRunner: Type[TextTestRunner] | TextTestRunner | None = ..., + testRunner: type[TextTestRunner] | TextTestRunner | None = ..., testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., @@ -271,7 +254,7 @@ def removeResult(result: TestResult) -> bool: ... @overload def removeHandler() -> None: ... @overload -def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... +def removeHandler(function: Callable[_P, _T]) -> Callable[_P, _T]: ... # private but occasionally used util: types.ModuleType diff --git a/mypy/typeshed/stdlib/@python2/urllib.pyi b/mypy/typeshed/stdlib/@python2/urllib.pyi index f6bb555b9581..56a75af74bb3 100644 --- a/mypy/typeshed/stdlib/@python2/urllib.pyi +++ b/mypy/typeshed/stdlib/@python2/urllib.pyi @@ -1,4 +1,5 @@ -from typing import IO, Any, AnyStr, List, Mapping, Sequence, Text, Tuple, TypeVar +from _typeshed import Self +from typing import IO, Any, AnyStr, Mapping, Sequence, Text def url2pathname(pathname: AnyStr) -> AnyStr: ... def pathname2url(pathname: AnyStr) -> AnyStr: ... @@ -77,15 +78,13 @@ class ftpwrapper: 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 readlines(self, hint: int = ...) -> list[bytes]: ... def fileno(self) -> int: ... # Optional[int], but that is rare - def __iter__(self: _AIUT) -> _AIUT: ... + def __iter__(self: Self) -> Self: ... def next(self) -> bytes: ... def __init__(self, fp) -> None: ... def close(self) -> None: ... @@ -125,7 +124,7 @@ 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: Sequence[Tuple[Any, Any]] | Mapping[Any, Any], doseq=...) -> str: ... +def urlencode(query: Sequence[tuple[Any, Any]] | Mapping[Any, Any], doseq=...) -> str: ... def getproxies() -> Mapping[str, str]: ... def proxy_bypass(host: str) -> Any: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/urllib2.pyi b/mypy/typeshed/stdlib/@python2/urllib2.pyi index bf6157b8428b..990384ebdcd1 100644 --- a/mypy/typeshed/stdlib/@python2/urllib2.pyi +++ b/mypy/typeshed/stdlib/@python2/urllib2.pyi @@ -1,6 +1,6 @@ import ssl from httplib import HTTPConnectionProtocol, HTTPResponse -from typing import Any, AnyStr, Callable, Dict, List, Mapping, Sequence, Text, Tuple, Type, Union +from typing import Any, AnyStr, Callable, Mapping, Sequence, Text, Union from urllib import addinfourl _string = Union[str, unicode] @@ -17,17 +17,17 @@ class Request(object): host: str port: str data: str - headers: Dict[str, str] + headers: dict[str, str] unverifiable: bool type: str | None origin_req_host = ... - unredirected_hdrs: Dict[str, str] + unredirected_hdrs: dict[str, str] timeout: float | None # Undocumented, only set after __init__() by OpenerDirector.open() def __init__( self, url: str, data: str | None = ..., - headers: Dict[str, str] = ..., + headers: dict[str, str] = ..., origin_req_host: str | None = ..., unverifiable: bool = ..., ) -> None: ... @@ -51,7 +51,7 @@ class Request(object): def header_items(self): ... class OpenerDirector(object): - addheaders: List[Tuple[str, str]] + addheaders: list[tuple[str, str]] def add_handler(self, handler: BaseHandler) -> None: ... def open(self, fullurl: Request | _string, data: _string | None = ..., timeout: float | None = ...) -> addinfourl | None: ... def error(self, proto: _string, *args: Any): ... @@ -68,7 +68,7 @@ def urlopen( context: ssl.SSLContext | None = ..., ) -> addinfourl: ... def install_opener(opener: OpenerDirector) -> None: ... -def build_opener(*handlers: BaseHandler | Type[BaseHandler]) -> OpenerDirector: ... +def build_opener(*handlers: BaseHandler | type[BaseHandler]) -> OpenerDirector: ... class BaseHandler: handler_order: int @@ -101,8 +101,8 @@ class ProxyHandler(BaseHandler): class HTTPPasswordMgr: def __init__(self) -> None: ... def add_password(self, realm: Text | None, uri: Text | Sequence[Text], user: Text, passwd: Text) -> None: ... - def find_user_password(self, realm: Text | None, authuri: Text) -> Tuple[Any, Any]: ... - def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... + def find_user_password(self, realm: Text | None, 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): ... @@ -129,7 +129,7 @@ class AbstractDigestAuthHandler: def retry_http_digest_auth(self, req: Request, auth: str) -> HTTPResponse | None: ... 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_algorithm_impls(self, algorithm: str) -> tuple[Callable[[str], str], Callable[[str, str], str]]: ... def get_entity_digest(self, data: bytes | None, chal: Mapping[str, str]) -> str | None: ... class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): @@ -181,5 +181,5 @@ class CacheFTPHandler(FTPHandler): 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]: ... +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 index 6668c743373a..625928a74135 100644 --- a/mypy/typeshed/stdlib/@python2/urlparse.pyi +++ b/mypy/typeshed/stdlib/@python2/urlparse.pyi @@ -1,13 +1,13 @@ -from typing import AnyStr, Dict, List, NamedTuple, Sequence, Tuple, Union, overload +from typing import AnyStr, NamedTuple, Sequence, 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] +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 @@ -47,15 +47,15 @@ class ParseResult(_ParseResult, ResultMixin): 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: ... +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: ... +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 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]]: ... +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/uuid.pyi b/mypy/typeshed/stdlib/@python2/uuid.pyi index 2c8a9fb1c097..8ba2d7e5aa24 100644 --- a/mypy/typeshed/stdlib/@python2/uuid.pyi +++ b/mypy/typeshed/stdlib/@python2/uuid.pyi @@ -1,9 +1,9 @@ -from typing import Any, Text, Tuple +from typing import 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] +_FieldsType = tuple[int, int, int, int, int, int] class UUID: def __init__( diff --git a/mypy/typeshed/stdlib/@python2/warnings.pyi b/mypy/typeshed/stdlib/@python2/warnings.pyi index 0d187bf70c33..2e872a4fb28e 100644 --- a/mypy/typeshed/stdlib/@python2/warnings.pyi +++ b/mypy/typeshed/stdlib/@python2/warnings.pyi @@ -1,23 +1,23 @@ from _warnings import warn as warn, warn_explicit as warn_explicit from types import ModuleType, TracebackType -from typing import List, TextIO, Type, overload +from typing import TextIO, overload from typing_extensions import Literal def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... + message: Warning | str, category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... ) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... +def formatwarning(message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... def filterwarnings( - action: str, message: str = ..., category: Type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ... + 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 simplefilter(action: str, category: type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... def resetwarnings() -> None: ... class _OptionError(Exception): ... class WarningMessage: message: Warning | str - category: Type[Warning] + category: type[Warning] filename: str lineno: int file: TextIO | None @@ -25,7 +25,7 @@ class WarningMessage: def __init__( self, message: Warning | str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., @@ -39,13 +39,13 @@ class catch_warnings: def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... @overload def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... - def __enter__(self) -> List[WarningMessage] | None: ... + def __enter__(self) -> list[WarningMessage] | None: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... class _catch_warnings_without_records(catch_warnings): def __enter__(self) -> None: ... class _catch_warnings_with_records(catch_warnings): - def __enter__(self) -> List[WarningMessage]: ... + def __enter__(self) -> list[WarningMessage]: ... diff --git a/mypy/typeshed/stdlib/@python2/wave.pyi b/mypy/typeshed/stdlib/@python2/wave.pyi index 0e9fe612cd24..ceae301145d8 100644 --- a/mypy/typeshed/stdlib/@python2/wave.pyi +++ b/mypy/typeshed/stdlib/@python2/wave.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, BinaryIO, NoReturn, Text, Tuple, Union +from typing import IO, Any, BinaryIO, NoReturn, Text, Union _File = Union[Text, IO[bytes]] @@ -6,7 +6,7 @@ class Error(Exception): ... WAVE_FORMAT_PCM: int -_wave_params = Tuple[int, int, int, int, str, str] +_wave_params = tuple[int, int, int, int, str, str] class Wave_read: def __init__(self, f: _File) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/weakref.pyi b/mypy/typeshed/stdlib/@python2/weakref.pyi index 6467f3a7517f..8c65ab21a568 100644 --- a/mypy/typeshed/stdlib/@python2/weakref.pyi +++ b/mypy/typeshed/stdlib/@python2/weakref.pyi @@ -1,5 +1,5 @@ from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, List, Mapping, MutableMapping, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar, overload from _weakref import ( CallableProxyType as CallableProxyType, @@ -12,18 +12,17 @@ from _weakref import ( ) from exceptions import ReferenceError as ReferenceError -_S = TypeVar("_S") _T = TypeVar("_T") _KT = TypeVar("_KT") _VT = TypeVar("_VT") -ProxyTypes: Tuple[Type[Any], ...] +ProxyTypes: tuple[type[Any], ...] class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __other: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self, __other: 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: ... @@ -31,16 +30,15 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + def 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 iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... - def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... + def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT @@ -52,7 +50,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self, dict: None = ...) -> None: ... @overload - def __init__(self, dict: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]]) -> None: ... + def __init__(self, dict: 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: ... @@ -60,13 +58,12 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + def 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 iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... - def keyrefs(self) -> List[ref[_KT]]: ... + def keyrefs(self) -> list[ref[_KT]]: ... diff --git a/mypy/typeshed/stdlib/@python2/webbrowser.pyi b/mypy/typeshed/stdlib/@python2/webbrowser.pyi index f634bc11ca7d..33600fe3255d 100644 --- a/mypy/typeshed/stdlib/@python2/webbrowser.pyi +++ b/mypy/typeshed/stdlib/@python2/webbrowser.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable, List, Sequence, Text +from typing import Callable, Sequence, Text class Error(Exception): ... @@ -12,7 +12,7 @@ def open_new(url: Text) -> bool: ... def open_new_tab(url: Text) -> bool: ... class BaseBrowser: - args: List[str] + args: list[str] name: str basename: str def __init__(self, name: Text = ...) -> None: ... @@ -21,7 +21,7 @@ class BaseBrowser: def open_new_tab(self, url: Text) -> bool: ... class GenericBrowser(BaseBrowser): - args: List[str] + args: list[str] name: str basename: str def __init__(self, name: Text | Sequence[Text]) -> None: ... @@ -31,45 +31,45 @@ class BackgroundBrowser(GenericBrowser): def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... class UnixBrowser(BaseBrowser): - raise_opts: List[str] | None + raise_opts: list[str] | None background: bool redirect_stdout: bool - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... class Mozilla(UnixBrowser): - remote_args: List[str] + remote_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] + 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_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str background: bool class Opera(UnixBrowser): - remote_args: 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_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str @@ -91,6 +91,7 @@ if sys.platform == "darwin": name: str def __init__(self, name: Text) -> None: ... def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + class MacOSXOSAScript(BaseBrowser): def __init__(self, name: Text) -> None: ... def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi index d7e35ba8aff6..4dd63ac75035 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi @@ -1,17 +1,17 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, List, MutableMapping, Optional, Text, Tuple, Type +from typing import IO, Callable, MutableMapping, Optional, Text from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_exc_info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def format_date_time(timestamp: float | None) -> str: ... # undocumented class BaseHandler: - wsgi_version: Tuple[int, int] # undocumented + wsgi_version: tuple[int, int] # undocumented wsgi_multithread: bool wsgi_multiprocess: bool wsgi_run_once: bool @@ -22,12 +22,12 @@ class BaseHandler: os_environ: MutableMapping[str, str] - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented traceback_limit: int | None error_status: str - error_headers: List[Tuple[Text, Text]] + error_headers: list[tuple[Text, Text]] error_body: bytes def run(self, application: WSGIApplication) -> None: ... def setup_environ(self) -> None: ... @@ -36,7 +36,7 @@ class BaseHandler: def set_content_length(self) -> None: ... def cleanup_headers(self) -> None: ... def start_response( - self, status: Text, headers: List[Tuple[Text, Text]], exc_info: _exc_info | None = ... + self, status: Text, headers: list[tuple[Text, Text]], exc_info: _exc_info | None = ... ) -> Callable[[bytes], None]: ... def send_preamble(self) -> None: ... def write(self, data: bytes) -> None: ... @@ -48,7 +48,7 @@ class BaseHandler: 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]: ... + def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... @abstractmethod def _write(self, data: bytes) -> None: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi index 08061fee7664..5c939a342510 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi @@ -1,6 +1,6 @@ -from typing import List, Pattern, Tuple, overload +from typing import Pattern, overload -_HeaderList = List[Tuple[str, str]] +_HeaderList = list[tuple[str, str]] tspecials: Pattern[str] # undocumented @@ -12,13 +12,13 @@ class Headers: def __getitem__(self, name: str) -> str | None: ... def has_key(self, name: str) -> bool: ... def __contains__(self, name: str) -> bool: ... - def get_all(self, name: str) -> List[str]: ... + def get_all(self, name: str) -> list[str]: ... @overload def get(self, name: str, default: str) -> str: ... @overload def get(self, name: str, default: str | None = ...) -> str | None: ... - def keys(self) -> List[str]: ... - def values(self) -> List[str]: ... + def keys(self) -> list[str]: ... + def values(self) -> list[str]: ... def items(self) -> _HeaderList: ... def setdefault(self, name: str, value: str) -> str: ... def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi index a74a26fed935..6faba328f935 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi @@ -1,5 +1,5 @@ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer -from typing import List, Type, TypeVar, overload +from typing import TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment @@ -25,13 +25,13 @@ class WSGIRequestHandler(BaseHTTPRequestHandler): def get_stderr(self) -> ErrorStream: ... def handle(self) -> None: ... -def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... +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: ... +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] = ... + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... ) -> _S: ... diff --git a/mypy/typeshed/stdlib/@python2/xdrlib.pyi b/mypy/typeshed/stdlib/@python2/xdrlib.pyi index 378504c37227..f59843f8ee9d 100644 --- a/mypy/typeshed/stdlib/@python2/xdrlib.pyi +++ b/mypy/typeshed/stdlib/@python2/xdrlib.pyi @@ -1,4 +1,4 @@ -from typing import Callable, List, Sequence, TypeVar +from typing import Callable, Sequence, TypeVar _T = TypeVar("_T") @@ -50,6 +50,6 @@ class Unpacker: 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]: ... + def unpack_list(self, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_array(self, unpack_item: Callable[[], _T]) -> list[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi index 2496b3884ea1..b9e2dd9eb263 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi @@ -1,8 +1,8 @@ from _typeshed.xml import DOMImplementation -from typing import Callable, Dict, Iterable, Tuple +from typing import Callable, Iterable -well_known_implementations: Dict[str, str] -registered: Dict[str, Callable[[], DOMImplementation]] +well_known_implementations: dict[str, str] +registered: dict[str, Callable[[], DOMImplementation]] def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... -def getDOMImplementation(name: str | None = ..., features: str | Iterable[Tuple[str, str | None]] = ...) -> DOMImplementation: ... +def getDOMImplementation(name: str | None = ..., features: str | Iterable[tuple[str, str | None]] = ...) -> DOMImplementation: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi index e9b0395ab50d..254f8a0c1657 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi @@ -1,17 +1,17 @@ -from typing import Any, Iterable, List, Tuple, Type, TypeVar +from typing import Any, Iterable, TypeVar _T = TypeVar("_T") -StringTypes: Tuple[Type[str]] +StringTypes: tuple[type[str]] -class NodeList(List[_T]): +class NodeList(list[_T]): length: int def item(self, index: int) -> _T | None: ... -class EmptyNodeList(Tuple[Any, ...]): +class EmptyNodeList(tuple[Any, ...]): length: int def item(self, index: int) -> None: ... def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi index ed46ac4561ec..b09d1a503b44 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi @@ -1,10 +1,9 @@ import xml.dom -from typing import IO, Any, Text as _Text, TypeVar +from _typeshed import Self +from typing import IO, Any, Text as _Text from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader -_T = TypeVar("_T") - def parse(file: str | IO[Any], parser: XMLReader | None = ..., bufsize: int | None = ...): ... def parseString(string: bytes | _Text, parser: XMLReader | None = ...): ... def getDOMImplementation(features=...): ... @@ -32,7 +31,7 @@ class Node(xml.dom.Node): def setUserData(self, key, data, handler): ... childNodes: Any def unlink(self) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, et, ev, tb) -> None: ... class DocumentFragment(Node): @@ -72,7 +71,7 @@ class NamedNodeMap: def values(self): ... def get(self, name, value: Any | None = ...): ... def __len__(self) -> int: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __ge__(self, other: Any) -> bool: ... def __gt__(self, other: Any) -> bool: ... def __le__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi index 02fe84567543..5a2dd69c1bee 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi @@ -1,14 +1,14 @@ -from typing import Callable, Dict, Generator, List, Pattern, Tuple, TypeVar +from typing import Callable, Generator, Pattern, TypeVar from xml.etree.ElementTree import Element xpath_tokenizer_re: Pattern[str] -_token = Tuple[str, str] +_token = tuple[str, str] _next = Callable[[], _token] -_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] +_callback = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]] -def xpath_tokenizer(pattern: str, namespaces: Dict[str, str] | None = ...) -> Generator[_token, None, None]: ... -def get_parent_map(context: _SelectorContext) -> Dict[Element, Element]: ... +def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = ...) -> 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: ... @@ -16,16 +16,16 @@ 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]] +ops: dict[str, Callable[[_next, _token], _callback]] class _SelectorContext: - parent_map: Dict[Element, Element] | None + parent_map: dict[Element, Element] | None root: Element def __init__(self, root: Element) -> None: ... _T = TypeVar("_T") -def iterfind(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Generator[Element, None, None]: ... -def find(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Element | None: ... -def findall(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> List[Element]: ... -def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: Dict[str, str] | None = ...) -> _T | str: ... +def iterfind(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... +def find(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... +def findall(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> list[Element]: ... +def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: dict[str, str] | None = ...) -> _T | str: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi index a7a0a1c65f46..a6cbae35d04f 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi @@ -3,17 +3,14 @@ from typing import ( IO, Any, Callable, - Dict, Generator, ItemsView, Iterable, Iterator, KeysView, - List, MutableSequence, Sequence, Text, - Tuple, TypeVar, Union, overload, @@ -23,7 +20,7 @@ VERSION: str class ParseError(SyntaxError): code: int - position: Tuple[int, int] + position: tuple[int, int] def iselement(element: object) -> bool: ... @@ -53,31 +50,31 @@ _file_or_filename = Union[Text, FileDescriptor, IO[Any]] class Element(MutableSequence[Element]): tag: _str_result_type - attrib: Dict[_str_result_type, _str_result_type] + attrib: dict[_str_result_type, _str_result_type] text: _str_result_type | None tail: _str_result_type | None def __init__( self, tag: _str_argument_type | Callable[..., Element], - attrib: Dict[_str_argument_type, _str_argument_type] = ..., + attrib: dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type, ) -> None: ... def append(self, __subelement: Element) -> None: ... def clear(self) -> None: ... def extend(self, __elements: Iterable[Element]) -> None: ... def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Element | None: ... def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... + ) -> list[Element]: ... @overload def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: None = ..., namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _str_result_type | None: ... @overload def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: _T, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _T | _str_result_type: ... @overload def get(self, key: _str_argument_type, default: None = ...) -> _str_result_type | None: ... @@ -87,11 +84,11 @@ class Element(MutableSequence[Element]): def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Generator[Element, None, None]: ... def itertext(self) -> Generator[_str_result_type, None, None]: ... def keys(self) -> KeysView[_str_result_type]: ... - def makeelement(self, __tag: _str_argument_type, __attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... + def makeelement(self, __tag: _str_argument_type, __attrib: dict[_str_argument_type, _str_argument_type]) -> Element: ... def remove(self, __subelement: Element) -> None: ... def set(self, __key: _str_argument_type, __value: _str_argument_type) -> None: ... def __delitem__(self, i: int | slice) -> None: ... @@ -104,13 +101,13 @@ class Element(MutableSequence[Element]): def __setitem__(self, i: int, o: Element) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... - def getchildren(self) -> List[Element]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... + def getchildren(self) -> list[Element]: ... + def getiterator(self, tag: _str_argument_type | None = ...) -> list[Element]: ... def SubElement( parent: Element, tag: _str_argument_type, - attrib: Dict[_str_argument_type, _str_argument_type] = ..., + attrib: dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type, ) -> Element: ... def Comment(text: _str_argument_type | None = ...) -> Element: ... @@ -127,23 +124,23 @@ class ElementTree: def getroot(self) -> Element: ... def parse(self, source: _file_or_filename, parser: XMLParser | None = ...) -> Element: ... def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... + def getiterator(self, tag: _str_argument_type | None = ...) -> list[Element]: ... def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Element | None: ... @overload def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: None = ..., namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _str_result_type | None: ... @overload def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: _T, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _T | _str_result_type: ... def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... + ) -> list[Element]: ... def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Generator[Element, None, None]: ... def write( self, @@ -157,14 +154,14 @@ class ElementTree: def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... def tostring(element: Element, encoding: str | None = ..., method: str | None = ...) -> bytes: ... -def tostringlist(element: Element, encoding: str | None = ..., method: str | None = ...) -> List[bytes]: ... +def tostringlist(element: Element, encoding: str | None = ..., method: str | None = ...) -> list[bytes]: ... def dump(elem: Element) -> None: ... def parse(source: _file_or_filename, parser: XMLParser | None = ...) -> ElementTree: ... def iterparse( source: _file_or_filename, events: Sequence[str] | None = ..., parser: XMLParser | None = ... -) -> Iterator[Tuple[str, Any]]: ... +) -> Iterator[tuple[str, Any]]: ... def XML(text: _parser_input_type, parser: XMLParser | None = ...) -> Element: ... -def XMLID(text: _parser_input_type, parser: XMLParser | None = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... +def XMLID(text: _parser_input_type, parser: XMLParser | None = ...) -> tuple[Element, dict[_str_result_type, Element]]: ... # This is aliased to XML in the source. fromstring = XML @@ -180,13 +177,13 @@ def fromstringlist(sequence: Sequence[_parser_input_type], parser: XMLParser | N # 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] +_ElementFactory = Callable[[Any, dict[Any, Any]], Element] class TreeBuilder: def __init__(self, element_factory: _ElementFactory | None = ...) -> 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 start(self, __tag: _parser_input_type, __attrs: dict[_parser_input_type, _parser_input_type]) -> Element: ... def end(self, __tag: _parser_input_type) -> Element: ... class XMLParser: diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi index c41e2bee0eb1..02272d803c18 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/cElementTree.pyi @@ -1 +1 @@ -from xml.etree.ElementTree import * # noqa: F403 +from xml.etree.ElementTree import * diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi index 0c6da9a87d13..7a35805f9f16 100644 --- a/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, List, NoReturn, Text +from typing import IO, Any, NoReturn, Text from xml.sax.handler import ContentHandler, ErrorHandler from xml.sax.xmlreader import Locator, XMLReader @@ -19,9 +19,9 @@ class SAXNotRecognizedException(SAXException): ... class SAXNotSupportedException(SAXException): ... class SAXReaderNotAvailable(SAXNotSupportedException): ... -default_parser_list: List[str] +default_parser_list: list[str] -def make_parser(parser_list: List[str] = ...) -> XMLReader: ... +def make_parser(parser_list: list[str] = ...) -> XMLReader: ... def parse(source: str | IO[str] | IO[bytes], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... def parseString(string: bytes | Text, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi index 8afc566b16a1..684e9cef1f42 100644 --- a/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi @@ -1,4 +1,4 @@ -from typing import Mapping, Tuple +from typing import Mapping class XMLReader: def __init__(self) -> None: ... @@ -64,7 +64,7 @@ class AttributesImpl: def values(self): ... class AttributesNSImpl(AttributesImpl): - def __init__(self, attrs: Mapping[Tuple[str, str], str], qnames: Mapping[Tuple[str, str], str]) -> None: ... + 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): ... diff --git a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi index 5a7d0fc34f0e..0defb96bffb8 100644 --- a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi +++ b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi @@ -5,14 +5,14 @@ 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, Tuple, Type, Union +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, MutableMapping, Union _Unmarshaller = Any -_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_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]]] +_hostDesc = Union[str, tuple[str, Mapping[Any, Any]]] def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... @@ -47,13 +47,13 @@ class Fault(Error): faultString: str def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... -boolean: Type[bool] -Boolean: Type[bool] +boolean: type[bool] +Boolean: type[bool] class DateTime: value: str def __init__(self, value: str | unicode | datetime | float | int | _timeTuple | struct_time = ...) -> None: ... - def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... + 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: ... @@ -72,7 +72,7 @@ class Binary: def decode(self, data: str) -> None: ... def encode(self, out: IO[str]) -> None: ... -WRAPPERS: Tuple[Type[Any], ...] +WRAPPERS: tuple[type[Any], ...] # Still part of the public API, but see http://bugs.python.org/issue1773632 FastParser: None @@ -112,8 +112,8 @@ class Marshaller: | float | str | unicode - | List[Any] - | Tuple[Any, ...] + | list[Any] + | tuple[Any, ...] | Mapping[Any, Any] | datetime | InstanceType @@ -150,7 +150,7 @@ class Marshaller: class Unmarshaller: def append(self, object: Any) -> None: ... def __init__(self, use_datetime: bool = ...) -> None: ... - def close(self) -> Tuple[Any, ...]: ... + def close(self) -> tuple[Any, ...]: ... def getmethodname(self) -> str | None: ... def xml(self, encoding: str, standalone: bool) -> None: ... def start(self, tag: str, attrs: Any) -> None: ... @@ -173,25 +173,25 @@ class Unmarshaller: def end_methodName(self, data: str) -> None: ... class _MultiCallMethod: - def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... + def __init__(self, call_list: list[tuple[str, tuple[Any, ...]]], name: str) -> None: ... class MultiCallIterator: - def __init__(self, results: List[Any]) -> None: ... + 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[ExpatParser | SlowParser, Unmarshaller]: ... +def getparser(use_datetime: bool = ...) -> tuple[ExpatParser | SlowParser, Unmarshaller]: ... def dumps( - params: Tuple[Any, ...] | Fault, + params: tuple[Any, ...] | Fault, methodname: str | None = ..., methodresponse: bool | None = ..., encoding: str | None = ..., allow_none: bool = ..., ) -> str: ... -def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], str | None]: ... +def loads(data: str, use_datetime: bool = ...) -> tuple[tuple[Any, ...], str | None]: ... def gzip_encode(data: str) -> str: ... def gzip_decode(data: str, max_decode: int = ...) -> str: ... @@ -201,7 +201,7 @@ class GzipDecodedResponse(GzipFile): def close(self): ... class _Method: - def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... + def __init__(self, send: Callable[[str, tuple[Any, ...]], Any], name: str) -> None: ... def __getattr__(self, name: str) -> _Method: ... def __call__(self, *args: Any) -> Any: ... @@ -210,18 +210,18 @@ class Transport: accept_gzip_encoding: bool encode_threshold: int | None def __init__(self, use_datetime: bool = ...) -> None: ... - def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + 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[ExpatParser | SlowParser, Unmarshaller]: ... - def get_host_info(self, host: _hostDesc) -> Tuple[str, List[Tuple[str, str]] | None, Mapping[Any, Any] | None]: ... + def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> tuple[Any, ...]: ... + def getparser(self) -> tuple[ExpatParser | SlowParser, Unmarshaller]: ... + def get_host_info(self, host: _hostDesc) -> tuple[str, list[tuple[str, str]] | None, Mapping[Any, Any] | None]: ... 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, ...]: ... + def parse_response(self, response: HTTPResponse) -> tuple[Any, ...]: ... class SafeTransport(Transport): def __init__(self, use_datetime: bool = ..., context: SSLContext | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/zipfile.pyi b/mypy/typeshed/stdlib/@python2/zipfile.pyi index 5a0879492a88..0f376d2d93b8 100644 --- a/mypy/typeshed/stdlib/@python2/zipfile.pyi +++ b/mypy/typeshed/stdlib/@python2/zipfile.pyi @@ -1,10 +1,10 @@ import io -from _typeshed import StrPath +from _typeshed import Self, StrPath from types import TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Pattern, Protocol, Sequence, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text, Union _SZI = Union[Text, ZipInfo] -_DT = Tuple[int, int, int, int, int, int] +_DT = tuple[int, int, int, int, int, int] class BadZipfile(Exception): ... @@ -18,7 +18,7 @@ class ZipExtFile(io.BufferedIOBase): PATTERN: Pattern[str] = ... - newlines: List[bytes] | None + newlines: list[bytes] | None mode: str name: str def __init__( @@ -31,7 +31,6 @@ class ZipExtFile(io.BufferedIOBase): ) -> None: ... def read(self, n: int | None = ...) -> bytes: ... def readline(self, limit: int = ...) -> bytes: ... # type: ignore - def __repr__(self) -> str: ... def peek(self, n: int = ...) -> bytes: ... def read1(self, n: int | None) -> bytes: ... # type: ignore @@ -42,19 +41,19 @@ class ZipFile: filename: Text | None debug: int comment: bytes - filelist: List[ZipInfo] + filelist: list[ZipInfo] fp: IO[bytes] | None - NameToInfo: Dict[Text, ZipInfo] + NameToInfo: dict[Text, ZipInfo] start_dir: int # undocumented def __init__(self, file: StrPath | IO[bytes], mode: Text = ..., compression: int = ..., allowZip64: bool = ...) -> None: ... - def __enter__(self) -> ZipFile: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def close(self) -> None: ... def getinfo(self, name: Text) -> ZipInfo: ... - def infolist(self) -> List[ZipInfo]: ... - def namelist(self) -> List[Text]: ... + def infolist(self) -> list[ZipInfo]: ... + def namelist(self) -> list[Text]: ... def open(self, name: _SZI, mode: Text = ..., pwd: bytes | None = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... def extract(self, member: _SZI, path: StrPath | None = ..., pwd: bytes | None = ...) -> str: ... def extractall(self, path: StrPath | None = ..., members: Iterable[Text] | None = ..., pwd: bytes | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index e82161d97cb6..d3ba459dd9e3 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -62,6 +62,15 @@ array: 2.7- ast: 2.7- asynchat: 2.7- asyncio: 3.4- +asyncio.mixins: 3.10- +asyncio.compat: 3.4-3.6 +asyncio.exceptions: 3.8- +asyncio.format_helpers: 3.7- +asyncio.runners: 3.7- +asyncio.staggered: 3.8- +asyncio.taskgroups: 3.11- +asyncio.threads: 3.9- +asyncio.trsock: 3.8- asyncore: 2.7- atexit: 2.7- audioop: 2.7- @@ -104,6 +113,7 @@ difflib: 2.7- dis: 2.7- distutils: 2.7- distutils.command.bdist_msi: 2.7-3.10 +distutils.command.bdist_wininst: 2.7-3.9 doctest: 2.7- dummy_threading: 2.7-3.8 email: 2.7- @@ -164,6 +174,7 @@ modulefinder: 2.7- msilib: 2.7- msvcrt: 2.7- multiprocessing: 2.7- +multiprocessing.shared_memory: 3.8- netrc: 2.7- nis: 2.7- nntplib: 2.7- @@ -251,6 +262,7 @@ timeit: 2.7- tkinter: 3.0- token: 2.7- tokenize: 2.7- +tomllib: 3.11- trace: 2.7- traceback: 2.7- tracemalloc: 3.4- @@ -262,6 +274,7 @@ typing_extensions: 2.7- unicodedata: 2.7- unittest: 2.7- unittest._log: 3.9- +unittest.async_case: 3.8- urllib: 2.7- uu: 2.7- uuid: 2.7- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 08725cfc0b77..eea49588cb95 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,18 +1,17 @@ import sys -import typing from typing import Any, ClassVar from typing_extensions import Literal -PyCF_ONLY_AST: int +PyCF_ONLY_AST: Literal[1024] if sys.version_info >= (3, 8): - PyCF_TYPE_COMMENTS: int - PyCF_ALLOW_TOP_LEVEL_AWAIT: int + PyCF_TYPE_COMMENTS: Literal[4096] + PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] _identifier = str class AST: - _attributes: ClassVar[typing.Tuple[str, ...]] - _fields: ClassVar[typing.Tuple[str, ...]] + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] def __init__(self, *args: Any, **kwargs: Any) -> None: ... # TODO: Not all nodes have all of the following attributes lineno: int @@ -26,8 +25,10 @@ class mod(AST): ... if sys.version_info >= (3, 8): class type_ignore(AST): ... + class TypeIgnore(type_ignore): tag: str + class FunctionType(mod): argtypes: list[expr] returns: expr @@ -229,12 +230,16 @@ class JoinedStr(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 class Constant(expr): @@ -268,6 +273,7 @@ class Slice(_SliceT): if sys.version_info < (3, 9): class ExtSlice(slice): dims: list[slice] + class Index(slice): value: expr @@ -298,6 +304,7 @@ if sys.version_info < (3, 9): class AugLoad(expr_context): ... class AugStore(expr_context): ... class Param(expr_context): ... + class Suite(mod): body: list[stmt] @@ -381,32 +388,42 @@ if sys.version_info >= (3, 10): class Match(stmt): subject: expr cases: list[match_case] + class pattern(AST): ... # Without the alias, Pyright complains variables named pattern are recursively defined _pattern = pattern + class match_case(AST): pattern: _pattern guard: expr | None body: list[stmt] + class MatchValue(pattern): value: expr + class MatchSingleton(pattern): value: Literal[True, False, None] + class MatchSequence(pattern): patterns: list[pattern] + class MatchStar(pattern): name: _identifier | None + class MatchMapping(pattern): keys: list[expr] patterns: list[pattern] rest: _identifier | None + class MatchClass(pattern): cls: expr patterns: list[pattern] kwd_attrs: list[_identifier] kwd_patterns: list[pattern] + class MatchAs(pattern): pattern: _pattern | None name: _identifier | None + class MatchOr(pattern): patterns: list[pattern] diff --git a/mypy/typeshed/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi index 1f67dadd89a0..5608094ccbd6 100644 --- a/mypy/typeshed/stdlib/_bisect.pyi +++ b/mypy/typeshed/stdlib/_bisect.pyi @@ -1,35 +1,73 @@ import sys -from _typeshed import SupportsRichComparison -from typing import Callable, MutableSequence, Sequence, TypeVar +from _typeshed import SupportsRichComparisonT +from typing import Callable, MutableSequence, Sequence, TypeVar, overload _T = TypeVar("_T") if sys.version_info >= (3, 10): + @overload def bisect_left( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... + a: Sequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ..., *, key: None = ... ) -> int: ... + @overload + def bisect_left( + a: Sequence[_T], + x: SupportsRichComparisonT, + lo: int = ..., + hi: int | None = ..., + *, + key: Callable[[_T], SupportsRichComparisonT] = ..., + ) -> int: ... + @overload def bisect_right( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... + a: Sequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ..., *, key: None = ... ) -> int: ... + @overload + def bisect_right( + a: Sequence[_T], + x: SupportsRichComparisonT, + lo: int = ..., + hi: int | None = ..., + *, + key: Callable[[_T], SupportsRichComparisonT] = ..., + ) -> int: ... + @overload def insort_left( - a: MutableSequence[_T], - x: _T, + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ..., *, - key: Callable[[_T], SupportsRichComparison] | None = ..., + key: None = ..., + ) -> None: ... + @overload + def insort_left( + a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparisonT] = ... ) -> None: ... + @overload def insort_right( - a: MutableSequence[_T], - x: _T, + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ..., *, - key: Callable[[_T], SupportsRichComparison] | None = ..., + key: None = ..., + ) -> None: ... + @overload + def insort_right( + a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparisonT] = ... ) -> None: ... else: - def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... - def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> int: ... - def insort_left(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... - def insort_right(a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ...) -> None: ... + def bisect_left( + a: Sequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ... + ) -> int: ... + def bisect_right( + a: Sequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ... + ) -> int: ... + def insort_left( + a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ... + ) -> None: ... + def insort_right( + a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = ..., hi: int | None = ... + ) -> None: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 223b5fb8d62e..bd8d35641b37 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -65,14 +65,17 @@ _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. @final class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final class dict_items(ItemsView[_KT_co, _VT_co], Generic[_KT_co, _VT_co]): # undocumented if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index 31940e3eb15b..e71f7d14bd2b 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -1,8 +1,8 @@ from _typeshed import WriteableBuffer -from io import BufferedIOBase, RawIOBase -from typing import Any, Callable, Protocol, Type +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Callable, Protocol -BUFFER_SIZE: Any +BUFFER_SIZE = DEFAULT_BUFFER_SIZE class _Reader(Protocol): def read(self, __n: int) -> bytes: ... @@ -16,7 +16,7 @@ class DecompressReader(RawIOBase): self, fp: _Reader, decomp_factory: Callable[..., object], - trailing_error: Type[Exception] | tuple[Type[Exception], ...] = ..., + trailing_error: type[Exception] | tuple[type[Exception], ...] = ..., **decomp_args: Any, ) -> None: ... def readable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 54e9099bbdcd..161a89778de8 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,9 +1,12 @@ -from typing import Any, Iterable, Iterator, Protocol, Type, Union +from typing import Any, Iterable, Iterator, Protocol, Union +from typing_extensions import Literal -QUOTE_ALL: int -QUOTE_MINIMAL: int -QUOTE_NONE: int -QUOTE_NONNUMERIC: int +__version__: str + +QUOTE_ALL: Literal[1] +QUOTE_MINIMAL: Literal[0] +QUOTE_NONE: Literal[3] +QUOTE_NONNUMERIC: Literal[2] class Error(Exception): ... @@ -18,7 +21,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] +_DialectLike = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): dialect: Dialect diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 9f23eeb1c6dc..7022097628fc 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import SupportsRead from typing import IO, Any, NamedTuple, Union, overload +from typing_extensions import final if sys.platform != "win32": _chtype = Union[str, bytes, int] @@ -280,6 +281,7 @@ if sys.platform != "win32": def color_pair(pair_number: int) -> int: ... else: def color_pair(__color_number: int) -> int: ... + def curs_set(__visibility: int) -> int: ... def def_prog_mode() -> None: ... def def_shell_mode() -> None: ... @@ -294,6 +296,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 9): def get_escdelay() -> int: ... def get_tabsize() -> int: ... + def getmouse() -> tuple[int, int, int, int, int]: ... def getsyx() -> tuple[int, int]: ... def getwin(__file: SupportsRead[bytes]) -> _CursesWindow: ... @@ -301,6 +304,7 @@ if sys.platform != "win32": def has_colors() -> bool: ... if sys.version_info >= (3, 10): def has_extended_color_support() -> bool: ... + def has_ic() -> bool: ... def has_il() -> bool: ... def has_key(__key: int) -> bool: ... @@ -339,6 +343,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 9): def set_escdelay(__ms: int) -> None: ... def set_tabsize(__size: int) -> None: ... + def setsyx(__y: int, __x: int) -> None: ... def setupterm(term: str | None = ..., fd: int = ...) -> None: ... def start_color() -> None: ... @@ -367,7 +372,10 @@ if sys.platform != "win32": def update_lines_cols() -> None: ... def use_default_colors() -> None: ... def use_env(__flag: bool) -> None: ... + class error(Exception): ... + + @final class _CursesWindow: encoding: str @overload diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index e58805855b13..de49a787283d 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -1 +1,3 @@ from decimal import * + +__libmpdec_version__: str diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index 075ea4637f73..f63bec448f90 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -8,7 +8,56 @@ _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") -__all__: list[str] +if sys.version_info >= (3, 8): + __all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", + "excepthook", + "ExceptHookArgs", + ] +else: + __all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", + ] def active_count() -> int: ... def current_thread() -> Thread: ... @@ -16,10 +65,6 @@ def currentThread() -> Thread: ... def get_ident() -> int: ... def enumerate() -> list[Thread]: ... 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: _PF | None) -> None: ... def stack_size(size: int = ...) -> int: ... @@ -55,9 +100,11 @@ class Thread: if sys.version_info >= (3, 8): @property def native_id(self) -> int | None: ... # 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: ... @@ -67,7 +114,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -77,7 +124,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -88,7 +135,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -101,7 +148,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi index 87e0fe0fa777..90dc28deb71f 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -2,6 +2,8 @@ from typing import Any, TypeVar _T = TypeVar("_T") +__about__: str + def heapify(__heap: list[Any]) -> None: ... def heappop(__heap: list[_T]) -> _T: ... def heappush(__heap: list[_T], __item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi index 7395288afdbc..962fa9ec257a 100644 --- a/mypy/typeshed/stdlib/_json.pyi +++ b/mypy/typeshed/stdlib/_json.pyi @@ -1,14 +1,24 @@ from typing import Any, Callable +from typing_extensions import final +@final class make_encoder: - sort_keys: Any - skipkeys: Any - key_separator: Any - indent: Any - markers: Any - default: Any - encoder: Any - item_separator: Any + @property + def sort_keys(self) -> bool: ... + @property + def skipkeys(self) -> bool: ... + @property + def key_separator(self) -> str: ... + @property + def indent(self) -> int | None: ... + @property + def markers(self) -> dict[int, Any] | None: ... + @property + def default(self) -> Callable[[Any], Any]: ... + @property + def encoder(self) -> Callable[[str], str]: ... + @property + def item_separator(self) -> str: ... def __init__( self, markers: dict[int, Any] | None, @@ -23,6 +33,7 @@ class make_encoder: ) -> None: ... def __call__(self, obj: object, _current_indent_level: int) -> Any: ... +@final class make_scanner: object_hook: Any object_pairs_hook: Any diff --git a/mypy/typeshed/stdlib/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi index b7e852f38ae9..ffe53c819e53 100644 --- a/mypy/typeshed/stdlib/_msi.pyi +++ b/mypy/typeshed/stdlib/_msi.pyi @@ -43,6 +43,6 @@ if sys.platform == "win32": __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: list[str]) -> None: ... - def OpenDatabase(name: str, flags: int) -> _Database: ... - def CreateRecord(count: int) -> _Record: ... + def FCICreate(__cabname: str, __files: list[str]) -> None: ... + def OpenDatabase(__path: str, __persist: int) -> _Database: ... + def CreateRecord(__count: int) -> _Record: ... diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 77a88d4fa141..375d8e4ddfbf 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,5 +1,4 @@ import sys -from _typeshed import SupportsAnyComparison from typing import ( Any, AnyStr, @@ -25,6 +24,24 @@ _K = TypeVar("_K") _V = TypeVar("_V") _P = ParamSpec("_P") +# The following protocols return "Any" instead of bool, since the comparison +# operators can be overloaded to return an arbitrary object. For example, +# the numpy.array comparison dunders return another numpy.array. + +class _SupportsDunderLT(Protocol): + def __lt__(self, __other: Any) -> Any: ... + +class _SupportsDunderGT(Protocol): + def __gt__(self, __other: Any) -> Any: ... + +class _SupportsDunderLE(Protocol): + def __le__(self, __other: Any) -> Any: ... + +class _SupportsDunderGE(Protocol): + def __ge__(self, __other: Any) -> Any: ... + +_SupportsComparison = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT + class _SupportsInversion(Protocol[_T_co]): def __invert__(self) -> _T_co: ... @@ -35,12 +52,12 @@ class _SupportsPos(Protocol[_T_co]): def __pos__(self) -> _T_co: ... # All four comparison functions must have the same signature, or we get false-positive errors -def lt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def le(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def lt(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... +def le(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... def eq(__a: object, __b: object) -> Any: ... def ne(__a: object, __b: object) -> Any: ... -def ge(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... -def gt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def ge(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... +def gt(__a: _SupportsComparison, __b: _SupportsComparison) -> Any: ... def not_(__a: object) -> bool: ... def truth(__a: object) -> bool: ... def is_(__a: object, __b: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi index ffb25d5a2c0e..cb43fa93bb80 100644 --- a/mypy/typeshed/stdlib/_osx_support.pyi +++ b/mypy/typeshed/stdlib/_osx_support.pyi @@ -5,7 +5,7 @@ _T = TypeVar("_T") _K = TypeVar("_K") _V = TypeVar("_V") -__all__: list[str] +__all__ = ["compiler_fixup", "customize_config_vars", "customize_compiler", "get_platform_osx"] _UNIVERSAL_CONFIG_VARS: tuple[str, ...] # undocumented _COMPILER_CONFIG_VARS: tuple[str, ...] # undocumented diff --git a/mypy/typeshed/stdlib/_py_abc.pyi b/mypy/typeshed/stdlib/_py_abc.pyi index 697a7f17111a..ddf04364a238 100644 --- a/mypy/typeshed/stdlib/_py_abc.pyi +++ b/mypy/typeshed/stdlib/_py_abc.pyi @@ -1,10 +1,12 @@ -from typing import Any, Type, TypeVar +from _typeshed import Self +from typing import Any, NewType, TypeVar _T = TypeVar("_T") -# TODO: Change the return into a NewType bound to int after pytype/#597 -def get_cache_token() -> object: ... +_CacheToken = NewType("_CacheToken", int) + +def get_cache_token() -> _CacheToken: ... 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]: ... + def __new__(__mcls: type[Self], __name: str, __bases: tuple[type[Any], ...], __namespace: dict[str, Any]) -> Self: ... + def register(cls, subclass: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index d7d7f73ea37d..1395d69dab41 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -356,6 +356,9 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): J1939_FILTER_MAX: int +if sys.platform == "linux" and sys.version_info >= (3, 10): + IPPROTO_MPTCP: int + if sys.platform == "linux": AF_PACKET: int PF_PACKET: int @@ -524,9 +527,12 @@ else: # ----- Classes ----- class socket: - family: int - type: int - proto: int + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... @property def timeout(self) -> float | None: ... def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | None = ...) -> None: ... @@ -544,9 +550,11 @@ class socket: def getsockopt(self, __level: int, __optname: int, __buflen: int) -> bytes: ... if sys.version_info >= (3, 7): def getblocking(self) -> bool: ... + def gettimeout(self) -> float | None: ... if sys.platform == "win32": def ioctl(self, __control: int, __option: int | tuple[int, int, int] | bool) -> None: ... + def listen(self, __backlog: int = ...) -> None: ... def recv(self, __bufsize: int, __flags: int = ...) -> bytes: ... def recvfrom(self, __bufsize: int, __flags: int = ...) -> tuple[bytes, _RetAddress]: ... @@ -555,6 +563,7 @@ class socket: def recvmsg_into( self, __buffers: Iterable[WriteableBuffer], __ancbufsize: int = ..., __flags: int = ... ) -> tuple[int, list[_CMSG], int, Any]: ... + def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def send(self, __data: ReadableBuffer, __flags: int = ...) -> int: ... @@ -575,6 +584,7 @@ class socket: def sendmsg_afalg( self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... ) -> int: ... + def setblocking(self, __flag: bool) -> None: ... def settimeout(self, __value: float | None) -> None: ... @overload @@ -583,6 +593,7 @@ class socket: 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: ... SocketType = socket diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 03318a0b2d41..744799f1f66f 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import structseq from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn, Optional, Type +from typing import Any, Callable, NoReturn, Optional from typing_extensions import final error = RuntimeError @@ -18,7 +18,7 @@ class LockType: def locked(self) -> bool: ... def __enter__(self) -> bool: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... @@ -34,10 +34,10 @@ if sys.version_info >= (3, 8): def get_native_id() -> int: ... # only available on some platforms @final class _ExceptHookArgs( - structseq[Any], tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]] + structseq[Any], tuple[type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]] ): @property - def exc_type(self) -> Type[BaseException]: ... + def exc_type(self) -> type[BaseException]: ... @property def exc_value(self) -> BaseException | None: ... @property diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index 9e1e3f48d286..2ad77a177c37 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -1,6 +1,7 @@ from typing import Any from weakref import ReferenceType +__all__ = ["local"] localdict = dict[Any, Any] class _localimpl: diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index b6c8ccd1c380..6dfe070dafac 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -17,8 +17,15 @@ from typing_extensions import Literal, final # (, ) @final class Tcl_Obj: - string: str # str(tclobj) returns this + string: str | bytes typename: str + __hash__: None # type: ignore[assignment] + def __eq__(self, __other): ... + def __ge__(self, __other): ... + def __gt__(self, __other): ... + def __le__(self, __other): ... + def __lt__(self, __other): ... + def __ne__(self, __other): ... class TclError(Exception): ... @@ -42,39 +49,42 @@ class TclError(Exception): ... @final class TkappType: # Please keep in sync with tkinter.Tk + def adderrorinfo(self, __msg): ... def call(self, __command: Any, *args: Any) -> Any: ... + def createcommand(self, __name, __func): ... + if sys.platform != "win32": + def createfilehandler(self, __file, __mask, __func): ... + def deletefilehandler(self, __file): ... + + def createtimerhandler(self, __milliseconds, __func): ... + def deletecommand(self, __name): ... + def dooneevent(self, __flags: int = ...): ... 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 + def evalfile(self, __fileName): ... + def exprboolean(self, __s): ... + def exprdouble(self, __s): ... + def exprlong(self, __s): ... + def exprstring(self, __s): ... + def getboolean(self, __arg): ... + def getdouble(self, __arg): ... + def getint(self, __arg): ... + def getvar(self, *args, **kwargs): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self): ... + def loadtk(self) -> None: ... + def mainloop(self, __threshold: int = ...): ... + def quit(self): ... + def record(self, __script): ... + def setvar(self, *ags, **kwargs): ... if sys.version_info < (3, 11): - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + def split(self, __arg): ... + + def splitlist(self, __arg): ... + def unsetvar(self, *args, **kwargs): ... + def wantobjects(self, *args, **kwargs): ... + def willdispatch(self): ... # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS ALL_EVENTS: Literal[-3] @@ -91,9 +101,19 @@ WRITABLE: Literal[4] TCL_VERSION: str TK_VERSION: str -# TODO: figure out what these are (with e.g. help()) and get rid of Any -TkttType: Any -_flatten: Any -create: Any -getbusywaitinterval: Any -setbusywaitinterval: Any +@final +class TkttType: + def deletetimerhandler(self): ... + +def create( + __screenName: str | None = ..., + __baseName: str | None = ..., + __className: str = ..., + __interactive: bool = ..., + __wantobjects: bool = ..., + __wantTk: bool = ..., + __sync: bool = ..., + __use: str | None = ..., +): ... +def getbusywaitinterval(): ... +def setbusywaitinterval(__new_val): ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index a7f8c5147103..103af47c7524 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -7,8 +7,8 @@ import ctypes import mmap import sys from os import PathLike -from typing import AbstractSet, Any, Awaitable, ClassVar, Container, Generic, Iterable, Protocol, Type, TypeVar, Union -from typing_extensions import Literal, final +from typing import AbstractSet, Any, Container, Generic, Iterable, Protocol, TypeVar, Union +from typing_extensions import Final, Literal, final _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -33,27 +33,26 @@ class SupportsNext(Protocol[_T_co]): # stable class SupportsAnext(Protocol[_T_co]): - def __anext__(self) -> Awaitable[_T_co]: ... + async def __anext__(self) -> _T_co: ... # Comparison protocols class SupportsDunderLT(Protocol): - def __lt__(self, __other: Any) -> Any: ... + def __lt__(self, __other: Any) -> bool: ... class SupportsDunderGT(Protocol): - def __gt__(self, __other: Any) -> Any: ... + def __gt__(self, __other: Any) -> bool: ... class SupportsDunderLE(Protocol): - def __le__(self, __other: Any) -> Any: ... + def __le__(self, __other: Any) -> bool: ... class SupportsDunderGE(Protocol): - def __ge__(self, __other: Any) -> Any: ... + def __ge__(self, __other: Any) -> bool: ... class SupportsAllComparisons(SupportsDunderLT, SupportsDunderGT, SupportsDunderLE, SupportsDunderGE, Protocol): ... SupportsRichComparison = Union[SupportsDunderLT, SupportsDunderGT] SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 -SupportsAnyComparison = Union[SupportsDunderLE, SupportsDunderGE, SupportsDunderGT, SupportsDunderLT] class SupportsDivMod(Protocol[_T_contra, _T_co]): def __divmod__(self, __other: _T_contra) -> _T_co: ... @@ -181,7 +180,7 @@ class SupportsNoArgReadline(Protocol[_T_co]): # stable class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> Any: ... + def write(self, __s: _T_contra) -> object: ... ReadOnlyBuffer = bytes # stable # Anything that implements the read-write buffer interface. @@ -206,13 +205,13 @@ else: # See discussion at #6546 & #6560 # `structseq` classes are unsubclassable, so are all decorated with `@final`. class structseq(Generic[_T_co]): - n_fields: ClassVar[int] - n_unnamed_fields: ClassVar[int] - n_sequence_fields: ClassVar[int] + n_fields: Final[int] + n_unnamed_fields: Final[int] + n_sequence_fields: Final[int] # The first parameter will generally only take an iterable of a specific length. # E.g. `os.uname_result` takes any iterable of length exactly 5. # # The second parameter will accept a dict of any kind without raising an exception, # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 - def __new__(cls: Type[_T], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _T: ... + def __new__(cls: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ... diff --git a/mypy/typeshed/stdlib/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi index e5b180b14fea..2eb9ae478a5d 100644 --- a/mypy/typeshed/stdlib/_warnings.pyi +++ b/mypy/typeshed/stdlib/_warnings.pyi @@ -1,21 +1,21 @@ -from typing import Any, Type, overload +from typing import Any, overload _defaultaction: str _onceregistry: dict[Any, Any] -filters: list[tuple[str, str | None, Type[Warning], str | None, int]] +filters: list[tuple[str, str | None, type[Warning], str | None, int]] @overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... +def warn(message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... @overload def warn(message: Warning, category: Any = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... @overload def warn_explicit( message: str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., module_globals: dict[str, Any] | None = ..., source: Any | None = ..., ) -> None: ... @@ -26,7 +26,7 @@ def warn_explicit( filename: str, lineno: int, module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., module_globals: dict[str, Any] | None = ..., source: Any | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 1f0132f4c240..b0c22a5ecc13 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,34 +1,36 @@ import sys +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ["WeakSet"] + _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) class WeakSet(MutableSet[_T], Generic[_T]): def __init__(self, data: Iterable[_T] | None = ...) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... + def copy(self: Self) -> Self: ... 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[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __ior__(self: Self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] + def difference(self: Self, other: Iterable[_T]) -> Self: ... + def __sub__(self: Self, other: Iterable[Any]) -> Self: ... + def difference_update(self, other: Iterable[Any]) -> None: ... + def __isub__(self: Self, other: Iterable[Any]) -> Self: ... + def intersection(self: Self, other: Iterable[_T]) -> Self: ... + def __and__(self: Self, other: Iterable[Any]) -> Self: ... + def intersection_update(self, other: Iterable[Any]) -> None: ... + def __iand__(self: Self, other: Iterable[Any]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... @@ -38,8 +40,8 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __eq__(self, other: object) -> bool: ... def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... - def __ixor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def symmetric_difference_update(self, other: Iterable[_T]) -> None: ... + def __ixor__(self: Self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index eba236597840..1e8c51477083 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -160,6 +160,7 @@ if sys.platform == "win32": 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: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index 3c53692e1b36..58985067b125 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -1,8 +1,11 @@ import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Type, TypeVar +from collections.abc import Callable +from typing import Any, Generic, TypeVar +from typing_extensions import Literal _T = TypeVar("_T") +_R_co = TypeVar("_R_co", covariant=True) _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) # These definitions have special processing in mypy @@ -12,19 +15,24 @@ class ABCMeta(type): def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... + def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... -class abstractproperty(property): ... +class abstractclassmethod(classmethod[_R_co], Generic[_R_co]): + __isabstractmethod__: Literal[True] + def __init__(self: abstractclassmethod[_R_co], callable: Callable[..., _R_co]) -> None: ... -# These two are deprecated and not supported by mypy -def abstractstaticmethod(callable: _FuncT) -> _FuncT: ... -def abstractclassmethod(callable: _FuncT) -> _FuncT: ... +class abstractstaticmethod(staticmethod[_R_co], Generic[_R_co]): + __isabstractmethod__: Literal[True] + def __init__(self, callable: Callable[..., _R_co]) -> None: ... + +class abstractproperty(property): + __isabstractmethod__: Literal[True] class ABC(metaclass=ABCMeta): ... def get_cache_token() -> object: ... if sys.version_info >= (3, 10): - def update_abstractmethods(cls: Type[_T]) -> Type[_T]: ... + def update_abstractmethods(cls: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index e19bf2478bf3..8fc188980312 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,9 +1,14 @@ import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, NamedTuple, Type, Union, overload +from typing import IO, Any, NamedTuple, Union, overload from typing_extensions import Literal +if sys.version_info >= (3, 9): + __all__ = ["Error", "open"] +else: + __all__ = ["Error", "open", "openfp"] + class Error(Exception): ... class _aifc_params(NamedTuple): @@ -21,7 +26,7 @@ class Aifc_read: def __init__(self, f: _File) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def getfp(self) -> IO[bytes]: ... @@ -45,7 +50,7 @@ class Aifc_write: def __del__(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def initfp(self, file: IO[bytes]) -> None: ... def aiff(self) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 51933dc66668..ad54660cc45d 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -1,17 +1,76 @@ import sys -from typing import IO, Any, Callable, Generator, Generic, Iterable, NoReturn, Pattern, Protocol, Sequence, Type, TypeVar, overload +from typing import ( + IO, + Any, + Callable, + Generator, + Generic, + Iterable, + NewType, + NoReturn, + Pattern, + Protocol, + Sequence, + TypeVar, + overload, +) +from typing_extensions import Literal + +if sys.version_info >= (3, 9): + __all__ = [ + "ArgumentParser", + "ArgumentError", + "ArgumentTypeError", + "BooleanOptionalAction", + "FileType", + "HelpFormatter", + "ArgumentDefaultsHelpFormatter", + "RawDescriptionHelpFormatter", + "RawTextHelpFormatter", + "MetavarTypeHelpFormatter", + "Namespace", + "Action", + "ONE_OR_MORE", + "OPTIONAL", + "PARSER", + "REMAINDER", + "SUPPRESS", + "ZERO_OR_MORE", + ] +else: + __all__ = [ + "ArgumentParser", + "ArgumentError", + "ArgumentTypeError", + "FileType", + "HelpFormatter", + "ArgumentDefaultsHelpFormatter", + "RawDescriptionHelpFormatter", + "RawTextHelpFormatter", + "MetavarTypeHelpFormatter", + "Namespace", + "Action", + "ONE_OR_MORE", + "OPTIONAL", + "PARSER", + "REMAINDER", + "SUPPRESS", + "ZERO_OR_MORE", + ] _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser) _N = TypeVar("_N") -ONE_OR_MORE: str -OPTIONAL: str -PARSER: str -REMAINDER: str -SUPPRESS: str -ZERO_OR_MORE: str +ONE_OR_MORE: Literal["+"] +OPTIONAL: Literal["?"] +PARSER: Literal["A..."] +REMAINDER: Literal["..."] +_SUPPRESS_T = NewType("_SUPPRESS_T", str) +SUPPRESS: _SUPPRESS_T | str # not using Literal because argparse sometimes compares SUPPRESS with is +# the | str is there so that foo = argparse.SUPPRESS; foo = "test" checks out in mypy +ZERO_OR_MORE: Literal["*"] _UNRECOGNIZED_ARGS_ATTR: str # undocumented class ArgumentError(Exception): @@ -47,8 +106,11 @@ class _ActionsContainer: def add_argument( self, *name_or_flags: str, - action: str | Type[Action] = ..., - nargs: int | str = ..., + action: Literal[ + "store", "store_const", "store_true", "store_false", "append", "append_const", "count", "help", "version", "extend" + ] + | type[Action] = ..., + nargs: int | Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="] | _SUPPRESS_T = ..., const: Any = ..., default: Any = ..., type: Callable[[str], _T] | FileType = ..., @@ -67,7 +129,7 @@ class _ActionsContainer: def _add_container_actions(self, container: _ActionsContainer) -> None: ... def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ... def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... + def _pop_action_class(self, kwargs: Any, default: type[Action] | None = ...) -> type[Action]: ... def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ... @@ -143,7 +205,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - action: Type[Action] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., required: bool = ..., @@ -157,8 +219,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., + parser_class: type[_ArgumentParserT] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., required: bool = ..., @@ -173,7 +235,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - action: Type[Action] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., help: str | None = ..., @@ -186,13 +248,14 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., + parser_class: type[_ArgumentParserT] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., help: str | None = ..., metavar: str | None = ..., ) -> _SubParsersAction[_ArgumentParserT]: ... + def print_usage(self, file: IO[str] | None = ...) -> None: ... def print_help(self, file: IO[str] | None = ...) -> None: ... def format_usage(self) -> str: ... @@ -237,7 +300,7 @@ class HelpFormatter: _current_section: Any _whitespace_matcher: Pattern[str] _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class + _Section: type[Any] # Nested class def __init__(self, prog: str, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ...) -> None: ... def _indent(self) -> None: ... def _dedent(self) -> None: ... @@ -292,7 +355,7 @@ class Action(_AttributeHolder): nargs: int | str | None = ..., const: _T | None = ..., default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., + type: Callable[[str], _T] | FileType | None = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., @@ -311,7 +374,7 @@ if sys.version_info >= (3, 9): option_strings: Sequence[str], dest: str, default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., + type: Callable[[str], _T] | FileType | None = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., @@ -321,8 +384,9 @@ if sys.version_info >= (3, 9): class Namespace(_AttributeHolder): def __init__(self, **kwargs: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... def __contains__(self, key: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... class FileType: # undocumented @@ -410,9 +474,9 @@ class _VersionAction(Action): # undocumented class _SubParsersAction(Action, Generic[_ArgumentParserT]): - _ChoicesPseudoAction: Type[Any] # nested class + _ChoicesPseudoAction: type[Any] # nested class _prog_prefix: str - _parser_class: Type[_ArgumentParserT] + _parser_class: type[_ArgumentParserT] _name_parser_map: dict[str, _ArgumentParserT] choices: dict[str, _ArgumentParserT] _choices_actions: list[Action] @@ -421,7 +485,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): self, option_strings: Sequence[str], prog: str, - parser_class: Type[_ArgumentParserT], + parser_class: type[_ArgumentParserT], dest: str = ..., required: bool = ..., help: str | None = ..., @@ -432,7 +496,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): self, option_strings: Sequence[str], prog: str, - parser_class: Type[_ArgumentParserT], + parser_class: type[_ArgumentParserT], dest: str = ..., help: str | None = ..., metavar: str | tuple[str, ...] | None = ..., diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index f49eb2c916c2..a13052707178 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload from typing_extensions import Literal, SupportsIndex @@ -12,8 +13,10 @@ _T = TypeVar("_T", int, float, str) typecodes: str class array(MutableSequence[_T], Generic[_T]): - typecode: _TypeCode - itemsize: int + @property + def typecode(self) -> _TypeCode: ... + @property + def itemsize(self) -> int: ... @overload def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... @overload @@ -25,7 +28,7 @@ class array(MutableSequence[_T], Generic[_T]): def append(self, __v: _T) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... - def count(self, __v: Any) -> int: ... + def count(self, __v: _T) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... def frombytes(self, __buffer: bytes) -> None: ... def fromfile(self, __f: BinaryIO, __n: int) -> None: ... @@ -34,10 +37,11 @@ class array(MutableSequence[_T], Generic[_T]): if sys.version_info >= (3, 10): def index(self, __v: _T, __start: int = ..., __stop: int = ...) -> int: ... else: - def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence + def index(self, __v: _T) -> int: ... # type: ignore[override] + def insert(self, __i: int, __v: _T) -> None: ... def pop(self, __i: int = ...) -> _T: ... - def remove(self, __v: Any) -> None: ... + def remove(self, __v: _T) -> None: ... def reverse(self) -> None: ... def tobytes(self) -> bytes: ... def tofile(self, __f: BinaryIO) -> None: ... @@ -46,12 +50,14 @@ class array(MutableSequence[_T], Generic[_T]): if sys.version_info < (3, 9): def fromstring(self, __buffer: bytes) -> None: ... def tostring(self) -> bytes: ... + + def __contains__(self, __key: object) -> bool: ... def __len__(self) -> int: ... @overload def __getitem__(self, __i: SupportsIndex) -> _T: ... @overload def __getitem__(self, __s: slice) -> array[_T]: ... - @overload # type: ignore # Overrides MutableSequence + @overload # type: ignore[override] def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... @overload def __setitem__(self, __s: slice, __o: array[_T]) -> None: ... @@ -59,11 +65,13 @@ class array(MutableSequence[_T], Generic[_T]): 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 __iadd__(self: Self, __x: array[_T]) -> Self: ... # type: ignore[override] + def __imul__(self: Self, __n: int) -> Self: ... def __le__(self, __other: array[_T]) -> bool: ... def __lt__(self, __other: array[_T]) -> bool: ... def __mul__(self, __n: int) -> array[_T]: ... def __rmul__(self, __n: int) -> array[_T]: ... + def __copy__(self) -> array[_T]: ... + def __deepcopy__(self, __unused: Any) -> array[_T]: ... ArrayType = array diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 8494a3a99126..5a86d6888b2f 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -15,14 +15,17 @@ from typing_extensions import Literal if sys.version_info >= (3, 8): 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): ... @@ -88,6 +91,7 @@ class NodeVisitor: 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: ... diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index f2f7c6b0d165..2f4823b22b24 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -1,125 +1,31 @@ import sys -from typing import Type -from .base_events import BaseEventLoop as BaseEventLoop -from .coroutines import 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_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, - get_event_loop_policy as get_event_loop_policy, - new_event_loop as new_event_loop, - set_child_watcher as set_child_watcher, - set_event_loop as set_event_loop, - set_event_loop_policy as set_event_loop_policy, -) -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, -) -from .protocols import ( - BaseProtocol as BaseProtocol, - DatagramProtocol as DatagramProtocol, - Protocol as Protocol, - SubprocessProtocol as SubprocessProtocol, -) -from .queues import ( - LifoQueue as LifoQueue, - PriorityQueue as PriorityQueue, - Queue as Queue, - QueueEmpty as QueueEmpty, - QueueFull as QueueFull, -) -from .streams import ( - StreamReader as StreamReader, - StreamReaderProtocol as StreamReaderProtocol, - StreamWriter as StreamWriter, - open_connection as open_connection, - start_server as start_server, -) -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, - Task as Task, - 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, -) -from .transports import ( - BaseTransport as BaseTransport, - DatagramTransport as DatagramTransport, - ReadTransport as ReadTransport, - SubprocessTransport as SubprocessTransport, - Transport as Transport, - WriteTransport as WriteTransport, -) +# As at runtime, this depends on all submodules defining __all__ accurately. +from .base_events import * +from .coroutines import * +from .events import * +from .futures import * +from .locks import * +from .protocols import * +from .queues import * +from .streams import * +from .subprocess import * +from .tasks import * +from .transports import * -if sys.version_info < (3, 11): - from .coroutines import coroutine as coroutine - -if sys.version_info >= (3, 9): - from .threads import to_thread as to_thread - -if sys.version_info >= (3, 8): - from .exceptions import ( - CancelledError as CancelledError, - IncompleteReadError as IncompleteReadError, - InvalidStateError as InvalidStateError, - LimitOverrunError as LimitOverrunError, - TimeoutError as TimeoutError, - ) -else: - 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 .runners import * if sys.version_info >= (3, 8): - from .exceptions import SendfileNotAvailableError as SendfileNotAvailableError -elif sys.version_info >= (3, 7): - from .events import SendfileNotAvailableError as SendfileNotAvailableError + from .exceptions import * -if sys.version_info >= (3, 7): - from .events import get_running_loop as get_running_loop - from .protocols import BufferedProtocol as BufferedProtocol - from .runners import run as run - from .tasks import ( - _enter_task as _enter_task, - _leave_task as _leave_task, - _register_task as _register_task, - _unregister_task as _unregister_task, - all_tasks as all_tasks, - create_task as create_task, - current_task as current_task, - ) +if sys.version_info >= (3, 9): + from .threads import * -DefaultEventLoopPolicy: Type[AbstractEventLoopPolicy] +if sys.version_info >= (3, 11): + from .taskgroups import * if sys.platform == "win32": from .windows_events import * else: - 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 + from .unix_events import * diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 674baf49ba05..1d52942bf6c5 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -1,26 +1,29 @@ import ssl import sys from _typeshed import FileDescriptorLike -from abc import ABCMeta 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 asyncio.transports import BaseTransport, ReadTransport, SubprocessTransport, WriteTransport from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 7): from contextvars import Context + __all__ = ("BaseEventLoop",) +else: + __all__ = ["BaseEventLoop"] + _T = TypeVar("_T") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _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): if sys.version_info >= (3, 7): @@ -33,6 +36,10 @@ class Server(AbstractServer): backlog: int, ssl_handshake_timeout: float | None, ) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + def is_serving(self) -> bool: ... + async def start_serving(self) -> None: ... + async def serve_forever(self) -> None: ... else: def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... if sys.version_info >= (3, 8): @@ -43,8 +50,10 @@ class Server(AbstractServer): def sockets(self) -> list[socket]: ... else: sockets: list[socket] | None + def close(self) -> None: ... + async def wait_closed(self) -> None: ... -class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): +class BaseEventLoop(AbstractEventLoop): def run_forever(self) -> None: ... # Can't use a union, see mypy issue # 1873. @overload @@ -69,14 +78,16 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): 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: Awaitable[_T] | Generator[Any, None, _T], *, name: object = ...) -> Task[_T]: ... + def create_task(self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], *, name: object = ...) -> Task[_T]: ... else: - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T]) -> Task[_T]: ... + def create_task(self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T]) -> Task[_T]: ... + def set_task_factory(self, factory: Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None) -> None: ... def get_task_factory(self) -> Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None: ... # Methods for interacting with threads @@ -84,6 +95,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any, context: Context | None = ...) -> Handle: ... else: def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + 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. @@ -95,7 +107,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -109,11 +121,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -127,12 +139,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... elif sys.version_info >= (3, 7): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -144,11 +156,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -160,12 +172,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): local_addr: None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... else: @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -176,11 +188,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): sock: None = ..., local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -191,7 +203,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): sock: socket, local_addr: None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... if sys.version_info >= (3, 7): async def sock_sendfile( self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... @@ -232,12 +244,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ) -> Server: ... async def connect_accepted_socket( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], sock: socket, *, ssl: _SSLContext = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def sendfile( self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... ) -> int: ... @@ -283,12 +295,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): reuse_port: bool | None = ..., ) -> Server: ... async def connect_accepted_socket( - self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ... - ) -> _TransProtPair: ... + self, protocol_factory: Callable[[], _ProtocolT], sock: socket, *, ssl: _SSLContext = ... + ) -> tuple[BaseTransport, _ProtocolT]: ... if sys.version_info >= (3, 11): - async def create_datagram_endpoint( + async def create_datagram_endpoint( # type: ignore[override] self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], local_addr: tuple[str, int] | None = ..., remote_addr: tuple[str, int] | None = ..., *, @@ -298,11 +310,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): reuse_port: bool | None = ..., allow_broadcast: bool | None = ..., sock: socket | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... else: async def create_datagram_endpoint( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], local_addr: tuple[str, int] | None = ..., remote_addr: tuple[str, int] | None = ..., *, @@ -313,13 +325,17 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): reuse_port: bool | None = ..., allow_broadcast: bool | None = ..., sock: socket | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... # 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 connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, stdin: int | IO[Any] | None = ..., @@ -332,10 +348,10 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, stdin: int | IO[Any] | None = ..., @@ -347,11 +363,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): encoding: None = ..., errors: None = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... - def remove_reader(self, fd: FileDescriptorLike) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... - def remove_writer(self, fd: FileDescriptorLike) -> None: ... + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... # 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: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_futures.pyi b/mypy/typeshed/stdlib/asyncio/base_futures.pyi index 72ba6163e9d3..1b7fe4671ca8 100644 --- a/mypy/typeshed/stdlib/asyncio/base_futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_futures.pyi @@ -7,12 +7,20 @@ if sys.version_info >= (3, 7): from . import futures +if sys.version_info >= (3, 7): + __all__ = () +else: + __all__: list[str] = [] + +# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py +# but it leads to circular import error in pytype tool. +# That's why the import order is reversed. +from .futures import isfuture as isfuture + _PENDING: Literal["PENDING"] # undocumented _CANCELLED: Literal["CANCELLED"] # undocumented _FINISHED: Literal["FINISHED"] # undocumented -def isfuture(obj: object) -> bool: ... - if sys.version_info >= (3, 7): def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/compat.pyi b/mypy/typeshed/stdlib/asyncio/compat.pyi index 1beeea9d6c3f..f6f1bbca7faf 100644 --- a/mypy/typeshed/stdlib/asyncio/compat.pyi +++ b/mypy/typeshed/stdlib/asyncio/compat.pyi @@ -1,7 +1,5 @@ -import sys +PY34: bool +PY35: bool +PY352: bool -if sys.version_info < (3, 7): - PY34: bool - PY35: bool - PY352: bool - def flatten_list_bytes(list_of_data: list[bytes]) -> bytes: ... +def flatten_list_bytes(list_of_data: list[bytes]) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index 6c2d8179d1f1..6d4d507c6a4c 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -4,6 +4,13 @@ from collections.abc import Coroutine from typing import Any from typing_extensions import TypeGuard +if sys.version_info >= (3, 11): + __all__ = ("iscoroutinefunction", "iscoroutine") +elif sys.version_info >= (3, 7): + __all__ = ("coroutine", "iscoroutinefunction", "iscoroutine") +else: + __all__ = ["coroutine", "iscoroutinefunction", "iscoroutine"] + if sys.version_info < (3, 11): from collections.abc import Callable from typing import TypeVar diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 81b30b7e0065..37079dc091e5 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -3,28 +3,85 @@ import sys from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, Union, overload from typing_extensions import Literal from .base_events import Server from .futures import Future from .protocols import BaseProtocol from .tasks import Task -from .transports import BaseTransport +from .transports import BaseTransport, ReadTransport, SubprocessTransport, WriteTransport from .unix_events import AbstractChildWatcher if sys.version_info >= (3, 7): from contextvars import Context +if sys.version_info >= (3, 8): + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) + +elif sys.version_info >= (3, 7): + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "SendfileNotAvailableError", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) + +else: + __all__ = [ + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "_get_running_loop", + ] + _T = TypeVar("_T") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _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 + _cancelled: bool _args: Sequence[Any] if sys.version_info >= (3, 7): def __init__( @@ -32,7 +89,7 @@ class Handle: ) -> 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): @@ -50,22 +107,36 @@ class TimerHandle(Handle): ) -> 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: ... + def __lt__(self, other: TimerHandle) -> bool: ... + def __le__(self, other: TimerHandle) -> bool: ... + def __gt__(self, other: TimerHandle) -> bool: ... + def __ge__(self, other: TimerHandle) -> bool: ... + def __eq__(self, other: object) -> bool: ... + class AbstractServer: + @abstractmethod def close(self) -> None: ... if sys.version_info >= (3, 7): async def __aenter__(self: Self) -> Self: ... async def __aexit__(self, *exc: Any) -> None: ... + @abstractmethod def get_loop(self) -> AbstractEventLoop: ... + @abstractmethod def is_serving(self) -> bool: ... + @abstractmethod async def start_serving(self) -> None: ... + @abstractmethod async def serve_forever(self) -> None: ... + + @abstractmethod async def wait_closed(self) -> None: ... -class AbstractEventLoop(metaclass=ABCMeta): +class AbstractEventLoop: slow_callback_duration: float @abstractmethod def run_forever(self) -> None: ... @@ -87,12 +158,25 @@ class AbstractEventLoop(metaclass=ABCMeta): @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: ... + if sys.version_info >= (3, 9): # "context" added in 3.9.10/3.10.2 + @abstractmethod + def call_soon(self, callback: Callable[..., Any], *args: Any, context: Context | None = ...) -> Handle: ... + @abstractmethod + def call_later( + self, delay: float, callback: Callable[..., Any], *args: Any, context: Context | None = ... + ) -> TimerHandle: ... + @abstractmethod + def call_at( + self, when: float, callback: Callable[..., Any], *args: Any, context: Context | None = ... + ) -> TimerHandle: ... + else: + @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 @@ -101,17 +185,25 @@ class AbstractEventLoop(metaclass=ABCMeta): # Tasks methods if sys.version_info >= (3, 8): @abstractmethod - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T], *, name: str | None = ...) -> Task[_T]: ... + def create_task( + self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], *, name: str | None = ... + ) -> Task[_T]: ... else: @abstractmethod - def create_task(self, coro: Awaitable[_T] | Generator[Any, None, _T]) -> Task[_T]: ... + def create_task(self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T]) -> Task[_T]: ... + @abstractmethod def set_task_factory(self, factory: Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None) -> None: ... @abstractmethod def get_task_factory(self) -> Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]] | None: ... # Methods for interacting with threads - @abstractmethod - def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + if sys.version_info >= (3, 9): # "context" added in 3.9.10/3.10.2 + @abstractmethod + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any, context: Context | None = ...) -> Handle: ... + else: + @abstractmethod + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + @abstractmethod def run_in_executor(self, executor: Any, func: Callable[..., _T], *args: Any) -> Future[_T]: ... @abstractmethod @@ -128,7 +220,7 @@ class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -142,12 +234,12 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -161,13 +253,13 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... elif sys.version_info >= (3, 7): @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -179,12 +271,12 @@ class AbstractEventLoop(metaclass=ABCMeta): local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -196,13 +288,13 @@ class AbstractEventLoop(metaclass=ABCMeta): local_addr: None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... else: @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -213,12 +305,12 @@ class AbstractEventLoop(metaclass=ABCMeta): sock: None = ..., local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -229,7 +321,7 @@ class AbstractEventLoop(metaclass=ABCMeta): sock: socket, local_addr: None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... if sys.version_info >= (3, 7): @abstractmethod async def sock_sendfile( @@ -273,14 +365,14 @@ class AbstractEventLoop(metaclass=ABCMeta): ) -> Server: ... async def create_unix_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], path: str | None = ..., *, ssl: _SSLContext = ..., sock: socket | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def create_unix_server( self, protocol_factory: _ProtocolFactory, @@ -342,13 +434,13 @@ class AbstractEventLoop(metaclass=ABCMeta): ) -> Server: ... async def create_unix_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], path: str, *, ssl: _SSLContext = ..., sock: socket | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def create_unix_server( self, protocol_factory: _ProtocolFactory, @@ -358,10 +450,11 @@ class AbstractEventLoop(metaclass=ABCMeta): backlog: int = ..., ssl: _SSLContext = ..., ) -> Server: ... + @abstractmethod async def create_datagram_endpoint( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], local_addr: tuple[str, int] | None = ..., remote_addr: tuple[str, int] | None = ..., *, @@ -372,16 +465,20 @@ class AbstractEventLoop(metaclass=ABCMeta): reuse_port: bool | None = ..., allow_broadcast: bool | None = ..., sock: socket | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... # Pipes and subprocesses. @abstractmethod - async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... @abstractmethod - async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... @abstractmethod async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, stdin: int | IO[Any] | None = ..., @@ -394,11 +491,11 @@ class AbstractEventLoop(metaclass=ABCMeta): errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... @abstractmethod async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, stdin: int | IO[Any] | None = ..., @@ -410,15 +507,15 @@ class AbstractEventLoop(metaclass=ABCMeta): encoding: None = ..., errors: None = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[SubprocessTransport, _ProtocolT]: ... @abstractmethod def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... @abstractmethod - def remove_reader(self, fd: FileDescriptorLike) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... @abstractmethod def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... @abstractmethod - def remove_writer(self, fd: FileDescriptorLike) -> None: ... + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... # Completion based I/O methods returning Futures prior to 3.7 if sys.version_info >= (3, 7): @abstractmethod @@ -463,7 +560,7 @@ class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod async def shutdown_default_executor(self) -> None: ... -class AbstractEventLoopPolicy(metaclass=ABCMeta): +class AbstractEventLoopPolicy: @abstractmethod def get_event_loop(self) -> AbstractEventLoop: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/asyncio/exceptions.pyi b/mypy/typeshed/stdlib/asyncio/exceptions.pyi index 5b99966329ac..a1bc2c16ab1f 100644 --- a/mypy/typeshed/stdlib/asyncio/exceptions.pyi +++ b/mypy/typeshed/stdlib/asyncio/exceptions.pyi @@ -1,14 +1,22 @@ -import sys +__all__ = ( + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", +) -if sys.version_info >= (3, 8): - class CancelledError(BaseException): ... - class TimeoutError(Exception): ... - class InvalidStateError(Exception): ... - class SendfileNotAvailableError(RuntimeError): ... - class IncompleteReadError(EOFError): - expected: int | None - partial: bytes - def __init__(self, partial: bytes, expected: int | None) -> None: ... - class LimitOverrunError(Exception): - consumed: int - def __init__(self, message: str, consumed: int) -> None: ... +class CancelledError(BaseException): ... +class TimeoutError(Exception): ... +class InvalidStateError(Exception): ... +class SendfileNotAvailableError(RuntimeError): ... + +class IncompleteReadError(EOFError): + expected: int | None + partial: bytes + def __init__(self, partial: bytes, expected: int | None) -> None: ... + +class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index be80efe266b1..bf4412264ced 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -1,5 +1,4 @@ import functools -import sys import traceback from types import FrameType, FunctionType from typing import Any, Iterable, Union, overload @@ -9,12 +8,11 @@ class _HasWrapper: _FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] -if sys.version_info >= (3, 7): - @overload - def _get_function_source(func: _FuncType) -> tuple[str, int]: ... - @overload - def _get_function_source(func: object) -> tuple[str, int] | None: ... - 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: FrameType | None = ..., limit: int | None = ...) -> traceback.StackSummary: ... +@overload +def _get_function_source(func: _FuncType) -> tuple[str, int]: ... +@overload +def _get_function_source(func: object) -> tuple[str, int] | None: ... +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: FrameType | None = ..., limit: int | None = ...) -> traceback.StackSummary: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 9788123f427e..2b0b93a09638 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -1,11 +1,14 @@ import sys +from _typeshed import Self from concurrent.futures._base import Error, Future as _ConcurrentFuture from typing import Any, Awaitable, Callable, Generator, Iterable, TypeVar +from typing_extensions import Literal, TypeGuard from .events import AbstractEventLoop if sys.version_info < (3, 8): from concurrent.futures import CancelledError as CancelledError, TimeoutError as TimeoutError + class InvalidStateError(Error): ... if sys.version_info >= (3, 7): @@ -14,8 +17,19 @@ if sys.version_info >= (3, 7): if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 8): + __all__ = ("Future", "wrap_future", "isfuture") +elif sys.version_info >= (3, 7): + __all__ = ("CancelledError", "TimeoutError", "InvalidStateError", "Future", "wrap_future", "isfuture") +else: + __all__ = ["CancelledError", "TimeoutError", "InvalidStateError", "Future", "wrap_future", "isfuture"] + _T = TypeVar("_T") -_S = TypeVar("_S") + +# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py +# but it leads to circular import error in pytype tool. +# That's why the import order is reversed. +def isfuture(obj: object) -> TypeGuard[Future[Any]]: ... if sys.version_info < (3, 7): class _TracebackLogger: @@ -26,33 +40,36 @@ if sys.version_info < (3, 7): 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 + @property + def _exception(self) -> BaseException: ... + _blocking: bool + @property + def _log_traceback(self) -> bool: ... + @_log_traceback.setter + def _log_traceback(self, val: Literal[False]) -> None: ... + _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` def __init__(self, *, loop: AbstractEventLoop | None = ...) -> 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: Context | None = ...) -> None: ... + def _callbacks(self: Self) -> list[tuple[Callable[[Self], Any], Context]]: ... + def add_done_callback(self: Self, __fn: Callable[[Self], Any], *, context: Context | None = ...) -> None: ... else: @property - def _callbacks(self: _S) -> list[Callable[[_S], Any]]: ... - def add_done_callback(self: _S, __fn: Callable[[_S], Any]) -> None: ... + def _callbacks(self: Self) -> list[Callable[[Self], Any]]: ... + def add_done_callback(self: Self, __fn: Callable[[Self], Any]) -> None: ... if sys.version_info >= (3, 9): def cancel(self, msg: Any | None = ...) -> bool: ... else: def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... def done(self) -> bool: ... def result(self) -> _T: ... def exception(self) -> BaseException | None: ... - def remove_done_callback(self: _S, __fn: Callable[[_S], Any]) -> int: ... + def remove_done_callback(self: Self, __fn: Callable[[Self], Any]) -> int: ... def set_result(self, __result: _T) -> None: ... def set_exception(self, __exception: type | BaseException) -> None: ... def __iter__(self) -> Generator[Any, None, _T]: ... diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 7c4f40d9e4ca..d0edcbdcaeda 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,42 +1,47 @@ import sys from collections import deque from types import TracebackType -from typing import Any, Awaitable, Callable, Generator, Type, TypeVar +from typing import Any, Callable, Generator, TypeVar +from typing_extensions import Literal from .events import AbstractEventLoop from .futures import Future +if sys.version_info >= (3, 7): + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore") +else: + __all__ = ["Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore"] + _T = TypeVar("_T") if sys.version_info >= (3, 9): class _ContextManagerMixin: - def __init__(self, lock: Lock | Semaphore) -> None: ... - def __aenter__(self) -> Awaitable[None]: ... - def __aexit__( - self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> Awaitable[None]: ... + async def __aenter__(self) -> None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... else: class _ContextManager: def __init__(self, lock: Lock | Semaphore) -> None: ... - def __enter__(self) -> object: ... + def __enter__(self) -> None: ... def __exit__(self, *args: Any) -> None: ... + class _ContextManagerMixin: - def __init__(self, lock: Lock | Semaphore) -> None: ... # Apparently this exists to *prohibit* use as a context manager. - def __enter__(self) -> object: ... - def __exit__(self, *args: Any) -> None: ... + # def __enter__(self) -> NoReturn: ... see: https://github.com/python/typing/issues/1043 + # 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: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> Awaitable[None]: ... + async def __aenter__(self) -> None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... class Lock(_ContextManagerMixin): def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... class Event: @@ -44,14 +49,14 @@ class Event: def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... - async def wait(self) -> bool: ... + async def wait(self) -> Literal[True]: ... class Condition(_ContextManagerMixin): def __init__(self, lock: Lock | None = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... - async def wait(self) -> bool: ... + async def wait(self) -> Literal[True]: ... async def wait_for(self, predicate: Callable[[], _T]) -> _T: ... def notify(self, n: int = ...) -> None: ... def notify_all(self) -> None: ... @@ -61,7 +66,7 @@ class Semaphore(_ContextManagerMixin): _waiters: deque[Future[Any]] def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... def locked(self) -> bool: ... - async def acquire(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... def _wake_up_next(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/mixins.pyi b/mypy/typeshed/stdlib/asyncio/mixins.pyi new file mode 100644 index 000000000000..4c11865c8968 --- /dev/null +++ b/mypy/typeshed/stdlib/asyncio/mixins.pyi @@ -0,0 +1,7 @@ +import threading +from typing import NoReturn + +_global_lock: threading.Lock + +class _LoopBoundMixin: + def __init__(self, *, loop: NoReturn = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 1e9cff1b1dd6..4ffb40160420 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,14 +1,19 @@ import sys from socket import socket -from typing import Any, Mapping, Protocol, Type +from typing import Any, Mapping, Protocol from typing_extensions import Literal from . import base_events, constants, events, futures, streams, transports +if sys.version_info >= (3, 7): + __all__ = ("BaseProactorEventLoop",) +else: + __all__ = ["BaseProactorEventLoop"] + if sys.version_info >= (3, 8): class _WarnCallbackProtocol(Protocol): def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... + self, message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... ) -> None: ... class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): @@ -21,23 +26,35 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr extra: Mapping[Any, Any] | None = ..., server: events.AbstractServer | None = ..., ) -> None: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 8): def __del__(self, _warn: _WarnCallbackProtocol = ...) -> None: ... else: 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: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., - ) -> None: ... + if sys.version_info >= (3, 10): + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = ..., + extra: Mapping[Any, Any] | None = ..., + server: events.AbstractServer | None = ..., + buffer_size: int = ..., + ) -> None: ... + else: + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = ..., + extra: Mapping[Any, Any] | None = ..., + server: events.AbstractServer | None = ..., + ) -> None: ... class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): def __init__( diff --git a/mypy/typeshed/stdlib/asyncio/protocols.pyi b/mypy/typeshed/stdlib/asyncio/protocols.pyi index 754f02c8bb4b..7b5169702dba 100644 --- a/mypy/typeshed/stdlib/asyncio/protocols.pyi +++ b/mypy/typeshed/stdlib/asyncio/protocols.pyi @@ -1,5 +1,11 @@ import sys from asyncio import transports +from typing import Any + +if sys.version_info >= (3, 7): + __all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol") +else: + __all__ = ["BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol"] class BaseProtocol: def connection_made(self, transport: transports.BaseTransport) -> None: ... @@ -15,10 +21,15 @@ if sys.version_info >= (3, 7): class BufferedProtocol(BaseProtocol): def get_buffer(self, sizehint: int) -> bytearray: ... def buffer_updated(self, nbytes: int) -> None: ... + def eof_received(self) -> bool | None: ... class DatagramProtocol(BaseProtocol): def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override] - def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: ... + # addr can be a tuple[int, int] for some unusual protocols like socket.AF_NETLINK. + # Use tuple[str | Any, int] to not cause typechecking issues on most usual cases. + # This could be improved by using tuple[AnyOf[str, int], int] if the AnyOf feature is accepted. + # See https://github.com/python/typing/issues/566 + def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None: ... def error_received(self, exc: Exception) -> None: ... class SubprocessProtocol(BaseProtocol): diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index aff4af727b08..93ea9d9fc6fe 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -5,6 +5,11 @@ from typing import Any, Generic, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 7): + __all__ = ("Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty") +else: + __all__ = ["Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty"] + class QueueEmpty(Exception): ... class QueueFull(Exception): ... @@ -15,8 +20,6 @@ class Queue(Generic[_T]): 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 diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 3f0f42eef48b..7e799dd22fd8 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -1,10 +1,10 @@ import sys +from typing import Awaitable, TypeVar -if sys.version_info >= (3, 7): - from typing import Awaitable, TypeVar +__all__ = ("run",) +_T = TypeVar("_T") +if sys.version_info >= (3, 8): + def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... - _T = TypeVar("_T") - if sys.version_info >= (3, 8): - def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... - else: - def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... +else: + def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/selector_events.pyi b/mypy/typeshed/stdlib/asyncio/selector_events.pyi index bcbcd2fbe4b8..698bfef351a1 100644 --- a/mypy/typeshed/stdlib/asyncio/selector_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/selector_events.pyi @@ -1,6 +1,12 @@ import selectors +import sys from . import base_events +if sys.version_info >= (3, 7): + __all__ = ("BaseSelectorEventLoop",) +else: + __all__ = ["BaseSelectorEventLoop"] + class BaseSelectorEventLoop(base_events.BaseEventLoop): def __init__(self, selector: selectors.BaseSelector | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 082e96dc0233..4ecd7a11dd56 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -57,6 +57,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): 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: int | None = ..., low: int | None = ...) -> None: ... @@ -64,6 +65,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): 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: ... @@ -114,6 +116,7 @@ class SSLProtocol(protocols.Protocol): ) -> None: ... if sys.version_info >= (3, 7): def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... + def _wakeup_waiter(self, exc: BaseException | None = ...) -> None: ... def connection_made(self, transport: transports.BaseTransport) -> None: ... def connection_lost(self, exc: BaseException | None) -> None: ... @@ -127,6 +130,7 @@ class SSLProtocol(protocols.Protocol): def _start_handshake(self) -> None: ... if sys.version_info >= (3, 7): def _check_handshake_timeout(self) -> None: ... + def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ... def _process_write_backlog(self) -> None: ... def _fatal_error(self, exc: BaseException, message: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/staggered.pyi b/mypy/typeshed/stdlib/asyncio/staggered.pyi index 1d76d382555d..fc4bfad76984 100644 --- a/mypy/typeshed/stdlib/asyncio/staggered.pyi +++ b/mypy/typeshed/stdlib/asyncio/staggered.pyi @@ -1,9 +1,9 @@ -import sys from typing import Any, Awaitable, Callable, Iterable from . import events -if sys.version_info >= (3, 8): - async def staggered_race( - coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = ... - ) -> tuple[Any, int | None, list[Exception | None]]: ... +__all__ = ("staggered_race",) + +async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = ... +) -> tuple[Any, int | None, list[Exception | None]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 6dae893e3b97..2b0993ee03d7 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,10 +1,69 @@ import sys -from _typeshed import StrPath +from _typeshed import Self, StrPath from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional from . import events, protocols, transports from .base_events import Server +if sys.platform == "win32": + if sys.version_info >= (3, 8): + __all__ = ("StreamReader", "StreamWriter", "StreamReaderProtocol", "open_connection", "start_server") + elif sys.version_info >= (3, 7): + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "IncompleteReadError", + "LimitOverrunError", + ) + else: + __all__ = [ + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "IncompleteReadError", + "LimitOverrunError", + ] +else: + if sys.version_info >= (3, 8): + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "open_unix_connection", + "start_unix_server", + ) + elif sys.version_info >= (3, 7): + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "IncompleteReadError", + "LimitOverrunError", + "open_unix_connection", + "start_unix_server", + ) + else: + __all__ = [ + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "IncompleteReadError", + "LimitOverrunError", + "open_unix_connection", + "start_unix_server", + ] + _ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] if sys.version_info < (3, 8): @@ -12,6 +71,7 @@ if sys.version_info < (3, 8): expected: int | None partial: bytes def __init__(self, partial: bytes, expected: int | None) -> None: ... + class LimitOverrunError(Exception): consumed: int def __init__(self, message: str, consumed: int) -> None: ... @@ -114,10 +174,11 @@ class StreamWriter: 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: +class StreamReader(AsyncIterator[bytes]): def __init__(self, limit: int = ..., loop: events.AbstractEventLoop | None = ...) -> None: ... def exception(self) -> Exception: ... def set_exception(self, exc: Exception) -> None: ... @@ -129,5 +190,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]: ... + def __aiter__(self: Self) -> Self: ... async def __anext__(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index d835c12af3d8..f2725a8992ae 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -5,6 +5,11 @@ from asyncio import events, protocols, streams, transports from typing import IO, Any, Callable, Union from typing_extensions import Literal +if sys.version_info >= (3, 7): + __all__ = ("create_subprocess_exec", "create_subprocess_shell") +else: + __all__ = ["create_subprocess_exec", "create_subprocess_shell"] + if sys.version_info >= (3, 8): _ExecArg = StrOrBytesPath else: diff --git a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi new file mode 100644 index 000000000000..ef04614c3c15 --- /dev/null +++ b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi @@ -0,0 +1,17 @@ +# This only exists in 3.11+. See VERSIONS. + +from _typeshed import Self +from types import TracebackType +from typing import Any, Coroutine, Generator, TypeVar + +from .tasks import Task + +__all__ = ["TaskGroup"] + +_T = TypeVar("_T") + +class TaskGroup: + def __init__(self) -> None: ... + async def __aenter__(self: Self) -> Self: ... + async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def create_task(self, coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ...) -> Task[_T]: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 71f9741cb33b..140fc106bf42 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -2,7 +2,7 @@ import concurrent.futures import sys from collections.abc import Awaitable, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Generic, Optional, TextIO, TypeVar, Union, overload +from typing import Any, Coroutine, Generic, Optional, TextIO, TypeVar, Union, overload from typing_extensions import Literal from .events import AbstractEventLoop @@ -11,6 +11,44 @@ from .futures import Future if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 7): + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) +else: + __all__ = [ + "Task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + ] + _T = TypeVar("_T") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") @@ -47,79 +85,79 @@ def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | No # typing PR #1550 for discussion. if sys.version_info >= (3, 10): @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: Literal[False] = ...) -> Future[tuple[_T1]]: ... + def gather(__coro_or_future1: _FutureT[_T1], *, return_exceptions: Literal[False] = ...) -> Future[tuple[_T1]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: Literal[False] = ... + __coro_or_future1: _FutureT[_T1], __coro_or_future2: _FutureT[_T2], *, 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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, 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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, 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], + __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], *, 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], + __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], return_exceptions: bool = ..., ) -> Future[list[Any]]: ... @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: bool = ...) -> Future[tuple[_T1 | BaseException]]: ... + def gather(__coro_or_future1: _FutureT[_T1], *, return_exceptions: bool = ...) -> Future[tuple[_T1 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: bool = ... + __coro_or_future1: _FutureT[_T1], __coro_or_future2: _FutureT[_T2], *, return_exceptions: bool = ... ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _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], + __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], *, return_exceptions: bool = ..., ) -> Future[ @@ -129,96 +167,96 @@ if sys.version_info >= (3, 10): else: @overload def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ... + __coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ... ) -> Future[tuple[_T1]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], *, loop: AbstractEventLoop | None = ..., 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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, loop: AbstractEventLoop | None = ..., 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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, loop: AbstractEventLoop | None = ..., 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], + __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: AbstractEventLoop | None = ..., 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], + __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: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[list[Any]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ... + __coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ... ) -> Future[tuple[_T1 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _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], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _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], + __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: AbstractEventLoop | None = ..., return_exceptions: bool = ..., @@ -265,17 +303,20 @@ class Task(Future[_T], Generic[_T]): def __init__( self, coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, loop: AbstractEventLoop = ... ) -> None: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 8): def get_coro(self) -> Generator[_TaskYieldType, None, _T] | Awaitable[_T]: ... def get_name(self) -> str: ... def set_name(self, __value: object) -> None: ... + def get_stack(self, *, limit: int | None = ...) -> list[FrameType]: ... def print_stack(self, *, limit: int | None = ..., file: TextIO | None = ...) -> None: ... if sys.version_info >= (3, 9): def cancel(self, msg: Any | None = ...) -> bool: ... else: def cancel(self) -> bool: ... + if sys.version_info >= (3, 11): + def cancelling(self) -> int: ... + def uncancel(self) -> int: ... if sys.version_info < (3, 9): @classmethod def current_task(cls, loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... @@ -289,9 +330,10 @@ class Task(Future[_T], Generic[_T]): if sys.version_info >= (3, 7): def all_tasks(loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... if sys.version_info >= (3, 8): - def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, name: str | None = ...) -> Task[_T]: ... + def create_task(coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ...) -> Task[_T]: ... else: - def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T]) -> Task[_T]: ... + def create_task(coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T]) -> Task[_T]: ... + def current_task(loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index c13c0c6d1194..ac3a5c56b222 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -1,9 +1,8 @@ -import sys from typing import Callable, TypeVar from typing_extensions import ParamSpec +__all__ = ("to_thread",) _P = ParamSpec("_P") _R = TypeVar("_R") -if sys.version_info >= (3, 9): - async def to_thread(__func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... +async def to_thread(__func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index acca0e4c28b4..c24ded49cfb8 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -4,6 +4,11 @@ from asyncio.protocols import BaseProtocol from socket import _Address from typing import Any, Mapping +if sys.version_info >= (3, 7): + __all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") +else: + __all__ = ["BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport"] + class BaseTransport: def __init__(self, extra: Mapping[Any, Any] | None = ...) -> None: ... def get_extra_info(self, name: Any, default: Any = ...) -> Any: ... @@ -15,6 +20,7 @@ class BaseTransport: class ReadTransport(BaseTransport): if sys.version_info >= (3, 7): def is_reading(self) -> bool: ... + def pause_reading(self) -> None: ... def resume_reading(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 55147f4fddd5..5bbdadf8c269 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -1,39 +1,44 @@ import socket import sys +from builtins import type as Type # alias to avoid name clashes with property named "type" from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, Type, Union, overload +from typing import Any, BinaryIO, Iterable, NoReturn, Union, overload -if sys.version_info >= (3, 8): - # These are based in socket, maybe move them out into _typeshed.pyi or such - _Address = Union[tuple[Any, ...], 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: 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? +# These are based in socket, maybe move them out into _typeshed.pyi or such +_Address = Union[tuple[Any, ...], 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: 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 settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, flag: bool) -> None: ... + if sys.version_info < (3, 11): def accept(self) -> tuple[socket.socket, _RetAddress]: ... def connect(self, address: _Address | bytes) -> None: ... def connect_ex(self, address: _Address | bytes) -> int: ... @@ -42,6 +47,7 @@ if sys.version_info >= (3, 8): def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... else: def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... + def listen(self, __backlog: int = ...) -> None: ... def makefile(self) -> BinaryIO: ... def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... @@ -55,6 +61,7 @@ if sys.version_info >= (3, 8): 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: ... @@ -69,6 +76,7 @@ if sys.version_info >= (3, 8): 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( @@ -77,9 +85,6 @@ if sys.version_info >= (3, 8): 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: float | None) -> None: ... - def gettimeout(self) -> float | None: ... - def setblocking(self, flag: bool) -> None: ... def __enter__(self) -> socket.socket: ... def __exit__( self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index de3b320a4e24..b8c569b10cd4 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -1,8 +1,10 @@ import sys import types from _typeshed import Self +from abc import ABCMeta, abstractmethod from socket import socket -from typing import Any, Callable, Type +from typing import Any, Callable +from typing_extensions import Literal from .base_events import Server from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext @@ -12,22 +14,71 @@ from .selector_events import BaseSelectorEventLoop # but other parts of typeshed need this defintion. # So, it is special cased. class AbstractChildWatcher: + @abstractmethod def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod def close(self) -> None: ... + @abstractmethod def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + @abstractmethod + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... if sys.version_info >= (3, 8): + @abstractmethod def is_active(self) -> bool: ... if sys.platform != "win32": - class BaseChildWatcher(AbstractChildWatcher): + if sys.version_info >= (3, 9): + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "PidfdChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + ) + elif sys.version_info >= (3, 8): + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + ) + elif sys.version_info >= (3, 7): + __all__ = ("SelectorEventLoop", "AbstractChildWatcher", "SafeChildWatcher", "FastChildWatcher", "DefaultEventLoopPolicy") + else: + __all__ = ["SelectorEventLoop", "AbstractChildWatcher", "SafeChildWatcher", "FastChildWatcher", "DefaultEventLoopPolicy"] + + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): def __init__(self) -> None: ... + def close(self) -> None: ... + if sys.version_info >= (3, 8): + def is_active(self) -> bool: ... + + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + class SafeChildWatcher(BaseChildWatcher): def __enter__(self: Self) -> Self: ... + def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... + def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + class FastChildWatcher(BaseChildWatcher): def __enter__(self: Self) -> Self: ... + def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... + def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + class _UnixSelectorEventLoop(BaseSelectorEventLoop): if sys.version_info < (3, 7): async def create_unix_server( @@ -39,6 +90,7 @@ if sys.platform != "win32": backlog: int = ..., ssl: _SSLContext = ..., ) -> Server: ... + class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): def get_child_watcher(self) -> AbstractChildWatcher: ... def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... @@ -49,12 +101,46 @@ if sys.platform != "win32": if sys.version_info >= (3, 8): from typing import Protocol + class _Warn(Protocol): def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... + self, message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... ) -> None: ... + class MultiLoopChildWatcher(AbstractChildWatcher): + def __init__(self) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + 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: AbstractEventLoop | None) -> None: ... + class ThreadedChildWatcher(AbstractChildWatcher): + def __init__(self) -> None: ... + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... def __del__(self, _warn: _Warn = ...) -> None: ... + 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: AbstractEventLoop | None) -> None: ... + + if sys.version_info >= (3, 9): + class PidfdChildWatcher(AbstractChildWatcher): + def __init__(self) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index d86b6af91a29..1e4d286386c8 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -1,7 +1,7 @@ import socket import sys from _typeshed import WriteableBuffer -from typing import IO, Any, Callable, ClassVar, NoReturn, Type +from typing import IO, Any, Callable, ClassVar, NoReturn from typing_extensions import Literal from . import events, futures, proactor_events, selector_events, streams, windows_utils @@ -25,12 +25,15 @@ if sys.platform == "win32": ERROR_CONNECTION_ABORTED: Literal[1236] 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: IocpProactor | None = ...) -> None: ... async def create_pipe_connection( @@ -39,20 +42,22 @@ if sys.platform == "win32": 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: int | None = ...) -> 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: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... + def send(self, conn: socket.socket, buf: WriteableBuffer, 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: int | None = ...) -> bool: ... @@ -61,17 +66,18 @@ if sys.platform == "win32": if sys.version_info >= (3, 7): class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[SelectorEventLoop]] + _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]] + _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]] + _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/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index c387fc40f211..35a44be509af 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -2,28 +2,62 @@ import subprocess import sys from _typeshed import Self from types import TracebackType -from typing import Callable, Protocol, Type +from typing import Any, AnyStr, Callable, Protocol from typing_extensions import Literal if sys.platform == "win32": + if sys.version_info >= (3, 7): + __all__ = ("pipe", "Popen", "PIPE", "PipeHandle") + else: + __all__ = ["socketpair", "pipe", "Popen", "PIPE", "PipeHandle"] + import socket + + socketpair = socket.socketpair + class _WarnFunction(Protocol): def __call__( - self, message: str, category: Type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ... + self, message: str, category: type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ... ) -> None: ... BUFSIZE: Literal[8192] PIPE = subprocess.PIPE STDOUT = subprocess.STDOUT 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: Self) -> Self: ... def __exit__(self, t: type | None, v: BaseException | None, tb: TracebackType | None) -> None: ... @property def handle(self) -> int: ... def fileno(self) -> int: ... def close(self, *, CloseHandle: Callable[[int], None] = ...) -> None: ... + + class Popen(subprocess.Popen[AnyStr]): + stdin: PipeHandle | None # type: ignore[assignment] + stdout: PipeHandle | None # type: ignore[assignment] + stderr: PipeHandle | None # type: ignore[assignment] + # For simplicity we omit the full overloaded __new__ signature of + # subprocess.Popen. The arguments are mostly the same, but + # subprocess.Popen takes other positional-or-keyword arguments before + # stdin. + def __new__( + cls: type[Self], + args: subprocess._CMD, + stdin: subprocess._FILE | None = ..., + stdout: subprocess._FILE | None = ..., + stderr: subprocess._FILE | None = ..., + **kwds: Any, + ) -> Self: ... + def __init__( + self, + args: subprocess._CMD, + stdin: subprocess._FILE | None = ..., + stdout: subprocess._FILE | None = ..., + stderr: subprocess._FILE | None = ..., + **kwds: Any, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 123da2677a7e..8f77e0e45c44 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -85,6 +85,7 @@ if sys.platform != "win32": 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: _maptype | None = ...) -> None: ... def set_file(self, fd: int) -> None: ... diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index 8610eea17b52..70fe64292328 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -1,6 +1,51 @@ import sys from typing import IO +if sys.version_info >= (3, 10): + __all__ = [ + "encode", + "decode", + "encodebytes", + "decodebytes", + "b64encode", + "b64decode", + "b32encode", + "b32decode", + "b32hexencode", + "b32hexdecode", + "b16encode", + "b16decode", + "b85encode", + "b85decode", + "a85encode", + "a85decode", + "standard_b64encode", + "standard_b64decode", + "urlsafe_b64encode", + "urlsafe_b64decode", + ] +else: + __all__ = [ + "encode", + "decode", + "encodebytes", + "decodebytes", + "b64encode", + "b64decode", + "b32encode", + "b32decode", + "b16encode", + "b16decode", + "b85encode", + "b85decode", + "a85encode", + "a85decode", + "standard_b64encode", + "standard_b64decode", + "urlsafe_b64encode", + "urlsafe_b64decode", + ] + def b64encode(s: bytes, altchars: bytes | None = ...) -> bytes: ... def b64decode(s: str | bytes, altchars: bytes | None = ..., validate: bool = ...) -> bytes: ... def standard_b64encode(s: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 3f6b6d3d8b7b..8f61433e0cb8 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,11 +1,15 @@ from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, Type, TypeVar +from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar +from typing_extensions import Literal, ParamSpec + +__all__ = ["BdbQuit", "Bdb", "Breakpoint"] _T = TypeVar("_T") +_P = ParamSpec("_P") _TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = tuple[Type[BaseException], BaseException, FrameType] +_ExcInfo = tuple[type[BaseException], BaseException, FrameType] -GENERATOR_AND_COROUTINE_FLAGS: int +GENERATOR_AND_COROUTINE_FLAGS: Literal[672] class BdbQuit(Exception): ... @@ -61,7 +65,7 @@ class Bdb: def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... def runeval(self, expr: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... class Breakpoint: @@ -87,7 +91,6 @@ class Breakpoint: def disable(self) -> None: ... def bpprint(self, out: IO[str] | None = ...) -> None: ... def bpformat(self) -> str: ... - def __str__(self) -> str: ... def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index 4e295b8ed903..e531ccd508bf 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,10 +1,13 @@ from typing import IO, Any, Union +from typing_extensions import Literal + +__all__ = ["binhex", "hexbin", "Error"] class Error(Exception): ... -REASONABLY_LARGE: int -LINELEN: int -RUNCHAR: bytes +REASONABLY_LARGE: Literal[32768] +LINELEN: Literal[64] +RUNCHAR: Literal[b"\x90"] class FInfo: def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 5547afc217f6..9ce6959a1abf 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -22,6 +22,7 @@ from _typeshed import ( SupportsTrunc, SupportsWrite, ) +from collections.abc import Callable from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from types import CodeType, TracebackType, _Cell from typing import ( @@ -30,7 +31,6 @@ from typing import ( Any, BinaryIO, ByteString, - Callable, Generic, Iterable, Iterator, @@ -49,7 +49,6 @@ from typing import ( SupportsFloat, SupportsInt, SupportsRound, - Type, TypeVar, Union, overload, @@ -62,6 +61,7 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) +_R_co = TypeVar("_R_co", covariant=True) _KT = TypeVar("_KT") _VT = TypeVar("_VT") _S = TypeVar("_S") @@ -70,9 +70,6 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") -_R = TypeVar("_R") # Return-type TypeVar _SupportsNextT = TypeVar("_SupportsNextT", bound=SupportsNext[Any], covariant=True) _SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant=True) @@ -85,25 +82,26 @@ class _SupportsAiter(Protocol[_T_co]): class object: __doc__: str | None __dict__: dict[str, Any] - __slots__: str | Iterable[str] __module__: str __annotations__: dict[str, Any] @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: Self) -> type[Self]: ... # Ignore errors about type mismatch between property getter and setter @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # type: ignore # noqa: F811 + def __class__(self, __type: type[object]) -> None: ... # type: ignore # noqa: F811 def __init__(self) -> None: ... - def __new__(cls: Type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... + # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers. + # Overriding them in subclasses has different semantics, even if the override has an identical signature. def __setattr__(self, __name: str, __value: Any) -> None: ... + def __delattr__(self, __name: str) -> None: ... def __eq__(self, __o: object) -> bool: ... def __ne__(self, __o: object) -> bool: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... + def __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 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: ... # return type of pickle methods is rather hard to express in the current type system # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ @@ -112,46 +110,58 @@ class object: def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ... else: def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ... + def __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... -class staticmethod(Generic[_R]): # Special, only valid as a decorator. - __func__: Callable[..., _R] - __isabstractmethod__: bool - def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... +class staticmethod(Generic[_R_co]): + @property + def __func__(self) -> Callable[..., _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self: staticmethod[_R_co], __f: Callable[..., _R_co]) -> None: ... + def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R_co]: ... if sys.version_info >= (3, 10): __name__: str __qualname__: str - __wrapped__: Callable[..., _R] - def __call__(self, *args: Any, **kwargs: Any) -> _R: ... + __wrapped__: Callable[..., _R_co] + def __call__(self, *args: Any, **kwargs: Any) -> _R_co: ... -class classmethod(Generic[_R]): # Special, only valid as a decorator. - __func__: Callable[..., _R] - __isabstractmethod__: bool - def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... +class classmethod(Generic[_R_co]): + @property + def __func__(self) -> Callable[..., _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self: classmethod[_R_co], __f: Callable[..., _R_co]) -> None: ... + def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R_co]: ... if sys.version_info >= (3, 10): __name__: str __qualname__: str - __wrapped__: Callable[..., _R] + __wrapped__: Callable[..., _R_co] class type: - __base__: type + @property + def __base__(self) -> type: ... __bases__: tuple[type, ...] - __basicsize__: int - __dict__: dict[str, Any] - __dictoffset__: int - __flags__: int - __itemsize__: int + @property + def __basicsize__(self) -> int: ... + @property + def __dict__(self) -> types.MappingProxyType[str, Any]: ... # type: ignore[override] + @property + def __dictoffset__(self) -> int: ... + @property + def __flags__(self) -> int: ... + @property + def __itemsize__(self) -> int: ... __module__: str - __mro__: tuple[type, ...] + @property + def __mro__(self) -> tuple[type, ...]: ... __name__: str __qualname__: str - __text_signature__: str | None - __weakrefoffset__: int + @property + def __text_signature__(self) -> str | None: ... + @property + def __weakrefoffset__(self) -> int: ... @overload def __init__(self, __o: object) -> None: ... @overload @@ -159,9 +169,9 @@ class type: @overload def __new__(cls, __o: object) -> type: ... @overload - def __new__(cls: Type[_TT], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> _TT: ... + def __new__(cls: type[Self], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> Self: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> list[_TT]: ... + def __subclasses__(self: Self) -> list[Self]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: ... @@ -186,11 +196,12 @@ _NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -1 class int: @overload - def __new__(cls: Type[_T], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], __x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... + @property def real(self) -> int: ... @property @@ -203,11 +214,16 @@ class int: def bit_length(self) -> int: ... if sys.version_info >= (3, 10): def bit_count(self) -> int: ... + def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... @classmethod def from_bytes( - cls, bytes: Iterable[SupportsIndex] | SupportsBytes, byteorder: Literal["little", "big"], *, signed: bool = ... - ) -> int: ... # TODO buffer object argument + cls: type[Self], + bytes: Iterable[SupportsIndex] | SupportsBytes, # TODO buffer object argument + byteorder: Literal["little", "big"], + *, + signed: bool = ..., + ) -> Self: ... def __add__(self, __x: int) -> int: ... def __sub__(self, __x: int) -> int: ... def __mul__(self, __x: int) -> int: ... @@ -227,6 +243,8 @@ class int: @overload def __pow__(self, __x: int, __modulo: int) -> int: ... @overload + def __pow__(self, __x: Literal[0], __modulo: None = ...) -> Literal[1]: ... + @overload def __pow__(self, __x: _PositiveInteger, __modulo: None = ...) -> int: ... @overload def __pow__(self, __x: _NegativeInteger, __modulo: None = ...) -> float: ... @@ -259,7 +277,6 @@ class int: 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: ... @@ -268,12 +285,12 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> _T: ... + def __new__(cls: type[Self], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod - def fromhex(cls, __s: str) -> float: ... + def fromhex(cls: type[Self], __s: str) -> Self: ... @property def real(self) -> float: ... @property @@ -299,12 +316,14 @@ class 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: ... + # Returns complex if the argument is negative. + def __rpow__(self, __x: float, __mod: None = ...) -> Any: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... if sys.version_info >= (3, 9): def __ceil__(self) -> int: ... def __floor__(self) -> int: ... + @overload def __round__(self, __ndigits: None = ...) -> int: ... @overload @@ -317,7 +336,6 @@ 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: ... @@ -326,9 +344,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | SupportsIndex | complex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | SupportsIndex | complex) -> Self: ... @property def real(self) -> float: ... @property @@ -337,7 +355,7 @@ class 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 __pow__(self, __x: complex, __mod: None = ...) -> complex: ... def __truediv__(self, __x: complex) -> complex: ... def __radd__(self, __x: complex) -> complex: ... def __rsub__(self, __x: complex) -> complex: ... @@ -348,7 +366,6 @@ class complex: def __ne__(self, __x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... def __bool__(self) -> bool: ... @@ -360,9 +377,9 @@ class _FormatMapMapping(Protocol): class str(Sequence[str]): @overload - def __new__(cls: Type[_T], object: object = ...) -> _T: ... + def __new__(cls: type[Self], object: object = ...) -> Self: ... @overload - def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... + def __new__(cls: type[Self], object: bytes, encoding: str = ..., errors: str = ...) -> Self: ... def capitalize(self) -> str: ... def casefold(self) -> str: ... def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... @@ -375,6 +392,7 @@ class str(Sequence[str]): def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... else: def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... @@ -383,6 +401,7 @@ class str(Sequence[str]): def isalpha(self) -> bool: ... if sys.version_info >= (3, 7): def isascii(self) -> bool: ... + def isdecimal(self) -> bool: ... def isdigit(self) -> bool: ... def isidentifier(self) -> bool: ... @@ -401,6 +420,7 @@ class str(Sequence[str]): if sys.version_info >= (3, 9): def removeprefix(self, __prefix: str) -> str: ... def removesuffix(self, __suffix: str) -> str: ... + def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rjust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... @@ -439,22 +459,20 @@ class str(Sequence[str]): def __mod__(self, __x: Any) -> str: ... def __mul__(self, __n: SupportsIndex) -> str: ... def __ne__(self, __x: object) -> bool: ... - def __repr__(self) -> str: ... - def __rmul__(self, n: SupportsIndex) -> str: ... - def __str__(self) -> str: ... + def __rmul__(self, __n: SupportsIndex) -> str: ... def __getnewargs__(self) -> tuple[str]: ... class bytes(ByteString): @overload - def __new__(cls: Type[_T], __ints: Iterable[SupportsIndex]) -> _T: ... + def __new__(cls: type[Self], __ints: Iterable[SupportsIndex]) -> Self: ... @overload - def __new__(cls: Type[_T], __string: str, encoding: str, errors: str = ...) -> _T: ... + def __new__(cls: type[Self], __string: str, encoding: str, errors: str = ...) -> Self: ... @overload - def __new__(cls: Type[_T], __length: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __length: SupportsIndex) -> Self: ... @overload - def __new__(cls: Type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... @overload - def __new__(cls: Type[_T], __o: SupportsBytes) -> _T: ... + def __new__(cls: type[Self], __o: SupportsBytes) -> Self: ... def capitalize(self) -> bytes: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( @@ -468,6 +486,7 @@ class bytes(ByteString): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytes: ... else: def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -475,6 +494,7 @@ class bytes(ByteString): def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... else: def hex(self) -> str: ... + def index( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -482,6 +502,7 @@ class bytes(ByteString): 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: ... @@ -496,6 +517,7 @@ class bytes(ByteString): if sys.version_info >= (3, 9): def removeprefix(self, __prefix: bytes) -> bytes: ... def removesuffix(self, __suffix: bytes) -> bytes: ... + def rfind( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -518,13 +540,11 @@ class bytes(ByteString): def upper(self) -> bytes: ... def zfill(self, __width: SupportsIndex) -> bytes: ... @classmethod - def fromhex(cls: Type[_T], __s: str) -> _T: ... + def fromhex(cls: type[Self], __s: str) -> Self: ... @staticmethod def maketrans(__frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __hash__(self) -> int: ... @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @@ -570,6 +590,7 @@ class bytearray(MutableSequence[int], ByteString): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytearray: ... else: def expandtabs(self, tabsize: int = ...) -> bytearray: ... + def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... def find( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... @@ -578,6 +599,7 @@ class bytearray(MutableSequence[int], ByteString): def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... else: def hex(self) -> str: ... + def index( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -586,6 +608,7 @@ class bytearray(MutableSequence[int], ByteString): 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: ... @@ -596,9 +619,12 @@ class bytearray(MutableSequence[int], ByteString): def lower(self) -> bytearray: ... def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... def partition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def pop(self, __index: int = ...) -> int: ... + def remove(self, __value: int) -> None: ... 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: SupportsIndex = ...) -> bytearray: ... def rfind( self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... @@ -622,28 +648,26 @@ class bytearray(MutableSequence[int], ByteString): def upper(self) -> bytearray: ... def zfill(self, __width: SupportsIndex) -> bytearray: ... @classmethod - def fromhex(cls, __string: str) -> bytearray: ... + def fromhex(cls: type[Self], __string: str) -> Self: ... @staticmethod def maketrans(__frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... __hash__: None # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @overload def __getitem__(self, __s: slice) -> bytearray: ... @overload - def __setitem__(self, __i: SupportsIndex, x: SupportsIndex) -> None: ... + def __setitem__(self, __i: SupportsIndex, __x: SupportsIndex) -> None: ... @overload def __setitem__(self, __s: slice, __x: Iterable[SupportsIndex] | bytes) -> None: ... def __delitem__(self, __i: SupportsIndex | slice) -> None: ... def __add__(self, __s: bytes) -> bytearray: ... - def __iadd__(self, __s: Iterable[int]) -> bytearray: ... + def __iadd__(self: Self, __s: Iterable[int]) -> Self: ... def __mul__(self, __n: SupportsIndex) -> bytearray: ... def __rmul__(self, __n: SupportsIndex) -> bytearray: ... - def __imul__(self, __n: SupportsIndex) -> bytearray: ... + def __imul__(self: Self, __n: SupportsIndex) -> Self: ... def __mod__(self, __value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] @@ -653,26 +677,38 @@ class bytearray(MutableSequence[int], ByteString): def __le__(self, __x: bytes) -> bool: ... def __gt__(self, __x: bytes) -> bool: ... def __ge__(self, __x: bytes) -> bool: ... + def __alloc__(self) -> int: ... @final class memoryview(Sized, Sequence[int]): - format: str - itemsize: int - shape: tuple[int, ...] | None - strides: tuple[int, ...] | None - suboffsets: tuple[int, ...] | None - readonly: bool - ndim: int - - obj: bytes | bytearray - c_contiguous: bool - f_contiguous: bool - contiguous: bool - nbytes: int + @property + def format(self) -> str: ... + @property + def itemsize(self) -> int: ... + @property + def shape(self) -> tuple[int, ...] | None: ... + @property + def strides(self) -> tuple[int, ...] | None: ... + @property + def suboffsets(self) -> tuple[int, ...] | None: ... + @property + def readonly(self) -> bool: ... + @property + def ndim(self) -> int: ... + @property + def obj(self) -> bytes | bytearray: ... + @property + def c_contiguous(self) -> bool: ... + @property + def f_contiguous(self) -> bool: ... + @property + def contiguous(self) -> bool: ... + @property + def nbytes(self) -> int: ... def __init__(self, obj: ReadableBuffer) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None ) -> None: ... def cast(self, format: str, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... @overload @@ -690,9 +726,11 @@ class memoryview(Sized, Sequence[int]): def tobytes(self, order: Literal["C", "F", "A"] | None = ...) -> bytes: ... else: def tobytes(self) -> bytes: ... + def tolist(self) -> list[int]: ... if sys.version_info >= (3, 8): def toreadonly(self) -> memoryview: ... + def release(self) -> None: ... if sys.version_info >= (3, 8): def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... @@ -701,7 +739,9 @@ class memoryview(Sized, Sequence[int]): @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... + # The following overloads could be represented more elegantly with a TypeVar("_B", bool, int), + # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). @overload def __and__(self, __x: bool) -> bool: ... @overload @@ -730,9 +770,12 @@ class bool(int): @final class slice: - start: Any - step: Any - stop: Any + @property + def start(self) -> Any: ... + @property + def step(self) -> Any: ... + @property + def stop(self) -> Any: ... @overload def __init__(self, __stop: Any) -> None: ... @overload @@ -741,7 +784,7 @@ class slice: def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], __iterable: Iterable[_T_co] = ...) -> _T: ... + def __new__(cls: type[Self], __iterable: Iterable[_T_co] = ...) -> Self: ... def __len__(self) -> int: ... def __contains__(self, __x: object) -> bool: ... @overload @@ -768,15 +811,21 @@ class tuple(Sequence[_T_co], Generic[_T_co]): @final class function: # Make sure this class definition stays roughly in line with `types.FunctionType` - __closure__: tuple[_Cell, ...] | None + @property + def __closure__(self) -> tuple[_Cell, ...] | None: ... __code__: CodeType __defaults__: tuple[Any, ...] | None __dict__: dict[str, Any] - __globals__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... __name__: str __qualname__: str __annotations__: dict[str, Any] __kwdefaults__: dict[str, Any] + if sys.version_info >= (3, 10): + @property + def __builtins__(self) -> dict[str, Any]: ... + __module__: str # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. def __get__(self, obj: object | None, type: type | None = ...) -> Any: ... @@ -802,7 +851,6 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> _T: ... @@ -814,10 +862,10 @@ class list(MutableSequence[_T], Generic[_T]): def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... def __delitem__(self, __i: SupportsIndex | slice) -> None: ... def __add__(self, __x: list[_T]) -> list[_T]: ... - def __iadd__(self: _S, __x: Iterable[_T]) -> _S: ... + def __iadd__(self: Self, __x: Iterable[_T]) -> Self: ... def __mul__(self, __n: SupportsIndex) -> list[_T]: ... def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... - def __imul__(self: _S, __n: SupportsIndex) -> _S: ... + def __imul__(self: Self, __n: SupportsIndex) -> Self: ... def __contains__(self, __o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... def __gt__(self, __x: list[_T]) -> bool: ... @@ -841,13 +889,13 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... def keys(self) -> dict_keys[_KT, _VT]: ... def values(self) -> dict_values[_KT, _VT]: ... def items(self) -> dict_items[_KT, _VT]: ... # Signature of `dict.fromkeys` should be kept identical to `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` - # TODO: the true signature of `dict.fromkeys` is not expressable in the current type system. + # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload @@ -855,20 +903,32 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @classmethod @overload def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... + # Positional-only in dict, but not in MutableMapping + @overload + def get(self, __key: _KT) -> _VT | None: ... + @overload + def get(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... + @overload + def pop(self, __key: _KT) -> _VT: ... + @overload + def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... def __len__(self) -> int: ... def __getitem__(self, __k: _KT) -> _VT: ... - def __setitem__(self, __k: _KT, v: _VT) -> None: ... + 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[assignment] if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... - def __ior__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... # type: ignore[misc] + # dict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ... class set(MutableSet[_T], Generic[_T]): def __init__(self, __iterable: Iterable[_T] = ...) -> None: ... @@ -890,15 +950,14 @@ class set(MutableSet[_T], Generic[_T]): 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 __iand__(self: Self, __s: AbstractSet[object]) -> Self: ... def __or__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __ior__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ior__(self: Self, __s: AbstractSet[_T]) -> Self: ... # type: ignore[override,misc] def __sub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... - def __isub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... + def __isub__(self: Self, __s: AbstractSet[object]) -> Self: ... def __xor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... - def __ixor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ixor__(self: Self, __s: AbstractSet[_T]) -> Self: ... # type: ignore[override,misc] def __le__(self, __s: AbstractSet[object]) -> bool: ... def __lt__(self, __s: AbstractSet[object]) -> bool: ... def __ge__(self, __s: AbstractSet[object]) -> bool: ... @@ -920,7 +979,6 @@ class frozenset(AbstractSet[_T_co], Generic[_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[_T_co | _S]: ... def __sub__(self, __s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... @@ -934,16 +992,19 @@ 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]]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @final class range(Sequence[int]): - start: int - stop: int - step: int + @property + def start(self) -> int: ... + @property + def stop(self) -> int: ... + @property + def step(self) -> int: ... @overload def __init__(self, __stop: SupportsIndex) -> None: ... @overload @@ -957,13 +1018,13 @@ class range(Sequence[int]): def __getitem__(self, __i: SupportsIndex) -> int: ... @overload def __getitem__(self, __s: slice) -> range: ... - def __repr__(self) -> str: ... def __reversed__(self) -> Iterator[int]: ... class property: fget: Callable[[Any], Any] | None fset: Callable[[Any, Any], None] | None fdel: Callable[[Any], None] | None + __isabstractmethod__: bool def __init__( self, fget: Callable[[Any], Any] | None = ..., @@ -1060,8 +1121,10 @@ class filter(Iterator[_T], Generic[_T]): @overload def __init__(self, __function: None, __iterable: Iterable[_T | None]) -> None: ... @overload + def __init__(self, __function: Callable[[_S], TypeGuard[_T]], __iterable: Iterable[_S]) -> None: ... + @overload def __init__(self, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @@ -1152,7 +1215,7 @@ class map(Iterator[_S], Generic[_S]): __iter6: Iterable[Any], *iterables: Iterable[Any], ) -> None: ... - def __iter__(self) -> Iterator[_S]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _S: ... @overload @@ -1258,7 +1321,7 @@ def open( def open( file: _OpenFile, mode: OpenBinaryMode, - buffering: int, + buffering: int = ..., encoding: None = ..., errors: None = ..., newline: None = ..., @@ -1316,6 +1379,8 @@ if sys.version_info >= (3, 8): @overload def pow(base: int, exp: int, mod: int) -> int: ... @overload + def pow(base: int, exp: Literal[0], mod: None = ...) -> Literal[1]: ... # type: ignore[misc] + @overload def pow(base: int, exp: _PositiveInteger, mod: None = ...) -> int: ... # type: ignore[misc] @overload def pow(base: int, exp: _NegativeInteger, mod: None = ...) -> float: ... # type: ignore[misc] @@ -1349,6 +1414,8 @@ else: @overload def pow(__base: int, __exp: int, __mod: int) -> int: ... @overload + def pow(__base: int, __exp: Literal[0], __mod: None = ...) -> Literal[1]: ... # type: ignore[misc] + @overload def pow(__base: int, __exp: _PositiveInteger, __mod: None = ...) -> int: ... # type: ignore[misc] @overload def pow(__base: int, __exp: _NegativeInteger, __mod: None = ...) -> float: ... # type: ignore[misc] @@ -1378,8 +1445,9 @@ class reversed(Iterator[_T], Generic[_T]): def __init__(self, __sequence: Reversible[_T]) -> None: ... @overload def __init__(self, __sequence: SupportsLenAndGetItem[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... + def __length_hint__(self) -> int: ... def repr(__obj: object) -> str: ... @overload @@ -1489,7 +1557,8 @@ class zip(Iterator[_T_co], Generic[_T_co]): __iter6: Iterable[Any], *iterables: Iterable[Any], ) -> zip[tuple[Any, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T_co: ... # Signature of `builtins.__import__` should be kept identical to `importlib.__import__` @@ -1501,6 +1570,7 @@ def __import__( fromlist: Sequence[str] = ..., level: int = ..., ) -> types.ModuleType: ... +def __build_class__(__func: Callable[[], _Cell | Any], __name: str, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... # Actually the type of Ellipsis is , but since it's # not exposed anywhere under that name, we make it private here. @@ -1518,9 +1588,7 @@ class BaseException: if sys.version_info >= (3, 11): __note__: str | None def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... - def with_traceback(self: _TBE, __tb: TracebackType | None) -> _TBE: ... + def with_traceback(self: Self, __tb: TracebackType | None) -> Self: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1663,17 +1731,19 @@ if sys.version_info >= (3, 10): class EncodingWarning(Warning): ... if sys.version_info >= (3, 11): - _SplitCondition = type[BaseException] | tuple[type[BaseException, ...]] | Callable[[BaseException], bool] + _SplitCondition = Union[type[BaseException], tuple[type[BaseException], ...], Callable[[BaseException], bool]] + class BaseExceptionGroup(BaseException): - def __new__(cls, __message: str, __exceptions: Sequence[BaseException]) -> BaseExceptionGroup | ExceptionGroup: ... + def __new__(cls: type[Self], __message: str, __exceptions: Sequence[BaseException]) -> Self: ... @property def message(self) -> str: ... @property - def exceptions(self) -> Sequence[BaseException]: ... + def exceptions(self) -> tuple[BaseException, ...]: ... def subgroup(self: Self, __condition: _SplitCondition) -> Self | None: ... def split(self: Self, __condition: _SplitCondition) -> tuple[Self | None, Self | None]: ... def derive(self: Self, __excs: Sequence[BaseException]) -> Self: ... + class ExceptionGroup(BaseExceptionGroup, Exception): - def __new__(cls, __message: str, exceptions: Sequence[Exception]) -> ExceptionGroup: ... + def __new__(cls: type[Self], __message: str, __exceptions: Sequence[Exception]) -> Self: ... @property - def exceptions(self) -> Sequence[Exception]: ... + def exceptions(self) -> tuple[Exception, ...]: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 6aeaa3da4c60..f1467acadd10 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -2,9 +2,11 @@ import _compression import sys from _compression import BaseStream from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import IO, Any, Iterable, Protocol, TextIO, TypeVar, overload +from typing import IO, Any, Iterable, Protocol, TextIO, overload from typing_extensions import Literal, SupportsIndex, final +__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] + # The following attributes and methods are optional: # def fileno(self) -> int: ... # def close(self) -> object: ... @@ -16,8 +18,6 @@ class _WritableFileobj(Protocol): # def fileno(self) -> int: ... # def close(self) -> object: ... -_T = TypeVar("_T") - def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... @@ -118,6 +118,7 @@ class BZ2File(BaseStream, IO[bytes]): buffering: Any | None = ..., compresslevel: int = ..., ) -> None: ... + def read(self, size: int | None = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index e79524aa793e..edaa67109952 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -2,6 +2,9 @@ import sys from _typeshed import Self, StrOrBytesPath from types import CodeType from typing import Any, Callable, TypeVar +from typing_extensions import ParamSpec + +__all__ = ["run", "runctx", "Profile"] def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( @@ -9,6 +12,7 @@ def runctx( ) -> None: ... _T = TypeVar("_T") +_P = ParamSpec("_P") _Label = tuple[str, int, str] class Profile: @@ -24,7 +28,7 @@ class Profile: def snapshot_stats(self) -> None: ... def run(self: Self, cmd: str) -> Self: ... def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... - def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... if sys.version_info >= (3, 8): def __enter__(self: Self) -> Self: ... def __exit__(self, *exc_info: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index aa37928b87b1..17b59b9bc2c9 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -2,16 +2,42 @@ import datetime import sys from time import struct_time from typing import Any, Iterable, Optional, Sequence +from typing_extensions import Literal + +__all__ = [ + "IllegalMonthError", + "IllegalWeekdayError", + "setfirstweekday", + "firstweekday", + "isleap", + "leapdays", + "weekday", + "monthrange", + "monthcalendar", + "prmonth", + "month", + "prcal", + "calendar", + "timegm", + "month_name", + "month_abbr", + "day_name", + "day_abbr", + "Calendar", + "TextCalendar", + "HTMLCalendar", + "LocaleTextCalendar", + "LocaleHTMLCalendar", + "weekheader", +] _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: ... @@ -79,7 +105,7 @@ class HTMLCalendar(Calendar): class different_locale: def __init__(self, locale: _LocaleType) -> None: ... - def __enter__(self) -> _LocaleType: ... + def __enter__(self) -> None: ... def __exit__(self, *args: Any) -> None: ... class LocaleTextCalendar(TextCalendar): @@ -105,13 +131,12 @@ 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: Literal[0] +TUESDAY: Literal[1] +WEDNESDAY: Literal[2] +THURSDAY: Literal[3] +FRIDAY: Literal[4] +SATURDAY: Literal[5] +SUNDAY: Literal[6] -MONDAY: int -TUESDAY: int -WEDNESDAY: int -THURSDAY: int -FRIDAY: int -SATURDAY: int -SUNDAY: int +EPOCH: Literal[1970] diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index c2c3ac261010..1c11beec0c35 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,10 +1,43 @@ import sys -from _typeshed import SupportsGetItem, SupportsItemAccess +from _typeshed import Self, SupportsGetItem, SupportsItemAccess from builtins import type as _type from collections.abc import Iterable, Iterator, Mapping -from typing import IO, Any, Protocol, TypeVar +from types import TracebackType +from typing import IO, Any, Protocol -_T = TypeVar("_T", bound=FieldStorage) +if sys.version_info >= (3, 8): + __all__ = [ + "MiniFieldStorage", + "FieldStorage", + "parse", + "parse_multipart", + "parse_header", + "test", + "print_exception", + "print_environ", + "print_form", + "print_directory", + "print_arguments", + "print_environ_usage", + ] +else: + __all__ = [ + "MiniFieldStorage", + "FieldStorage", + "parse", + "parse_qs", + "parse_qsl", + "parse_multipart", + "parse_header", + "test", + "print_exception", + "print_environ", + "print_form", + "print_directory", + "print_arguments", + "print_environ_usage", + "escape", + ] def parse( fp: IO[Any] | None = ..., @@ -53,7 +86,6 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... _list = list @@ -94,9 +126,8 @@ class FieldStorage: max_num_fields: int | None = ..., separator: str = ..., ) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... 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: ... @@ -108,3 +139,11 @@ class FieldStorage: def __bool__(self) -> bool: ... # In Python 3 it returns bytes or str IO depending on an internal flag def make_file(self) -> IO[Any]: ... + +def print_exception( + type: type[BaseException] | None = ..., + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = ..., +) -> None: ... +def print_arguments() -> None: ... diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index a8f3912aa04c..fb9d69161d5b 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,8 +1,10 @@ from _typeshed import StrOrBytesPath from types import FrameType, TracebackType -from typing import IO, Any, Callable, Optional, Type +from typing import IO, Any, Callable, Optional -_ExcInfo = tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_ExcInfo = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +__UNDEF__: object # undocumented sentinel def reset() -> str: ... # undocumented def small(text: str) -> str: ... # undocumented @@ -24,7 +26,7 @@ class Hook: # undocumented file: IO[str] | None = ..., format: str = ..., ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... def handle(self, info: _ExcInfo | None = ...) -> None: ... def handler(info: _ExcInfo | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi index f6d818591a4e..d1166db0f507 100644 --- a/mypy/typeshed/stdlib/cmd.pyi +++ b/mypy/typeshed/stdlib/cmd.pyi @@ -1,4 +1,10 @@ from typing import IO, Any, Callable +from typing_extensions import Literal + +__all__ = ["Cmd"] + +PROMPT: Literal["(Cmd) "] +IDENTCHARS: str # Too big to be `Literal` class Cmd: prompt: str @@ -26,7 +32,7 @@ class Cmd: def parseline(self, line: str) -> tuple[str | None, str | None, str]: ... def onecmd(self, line: str) -> bool: ... def emptyline(self) -> bool: ... - def default(self, line: str) -> bool: ... + def default(self, line: str) -> None: ... def completedefault(self, *ignored: Any) -> list[str]: ... def completenames(self, text: str, *ignored: Any) -> list[str]: ... completion_matches: list[str] | None diff --git a/mypy/typeshed/stdlib/code.pyi b/mypy/typeshed/stdlib/code.pyi index ed00eaf96a5c..185c15853b82 100644 --- a/mypy/typeshed/stdlib/code.pyi +++ b/mypy/typeshed/stdlib/code.pyi @@ -2,6 +2,8 @@ from codeop import CommandCompiler from types import CodeType from typing import Any, Callable, Mapping +__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] + class InteractiveInterpreter: locals: Mapping[str, Any] # undocumented compile: CommandCompiler # undocumented diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index e08672e51428..8fa93961d9d0 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -2,13 +2,60 @@ import sys import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, Type, TypeVar, overload +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, overload from typing_extensions import Literal -BOM32_BE: bytes -BOM32_LE: bytes -BOM64_BE: bytes -BOM64_LE: bytes +__all__ = [ + "register", + "lookup", + "open", + "EncodedFile", + "BOM", + "BOM_BE", + "BOM_LE", + "BOM32_BE", + "BOM32_LE", + "BOM64_BE", + "BOM64_LE", + "BOM_UTF8", + "BOM_UTF16", + "BOM_UTF16_LE", + "BOM_UTF16_BE", + "BOM_UTF32", + "BOM_UTF32_LE", + "BOM_UTF32_BE", + "CodecInfo", + "Codec", + "IncrementalEncoder", + "IncrementalDecoder", + "StreamReader", + "StreamWriter", + "StreamReaderWriter", + "StreamRecoder", + "getencoder", + "getdecoder", + "getincrementalencoder", + "getincrementaldecoder", + "getreader", + "getwriter", + "encode", + "decode", + "iterencode", + "iterdecode", + "strict_errors", + "ignore_errors", + "replace_errors", + "xmlcharrefreplace_errors", + "backslashreplace_errors", + "namereplace_errors", + "register_error", + "lookup_error", +] + +BOM32_BE: Literal[b"\xfe\xff"] +BOM32_LE: Literal[b"\xff\xfe"] +BOM64_BE: Literal[b"\x00\x00\xfe\xff"] +BOM64_LE: Literal[b"\xff\xfe\x00\x00"] # TODO: this only satisfies the most common interface, where # bytes is the raw form and str is the cooked form. @@ -35,8 +82,8 @@ 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[ +# https://docs.python.org/3/library/codecs.html#binary-transforms +_BytesToBytesEncoding = Literal[ "base64", "base_64", "base64_codec", @@ -54,17 +101,23 @@ _BytesToBytesEncodingT = Literal[ "zlib", "zlib_codec", ] +# https://docs.python.org/3/library/codecs.html#text-transforms +_StrToStrEncoding = Literal["rot13", "rot_13"] @overload -def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... +def encode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... @overload -def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore[misc] +def encode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... # type: ignore[misc] @overload def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... @overload -def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore[misc] +def decode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... # type: ignore[misc] +@overload +def decode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... + +# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str @overload -def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... +def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = ...) -> bytes: ... @overload def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ... def lookup(__encoding: str) -> CodecInfo: ... @@ -86,7 +139,7 @@ class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): def incrementaldecoder(self) -> _IncrementalDecoder: ... name: str def __new__( - cls, + cls: type[Self], encode: _Encoder, decode: _Decoder, streamreader: _StreamReader | None = ..., @@ -96,7 +149,7 @@ class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): name: str | None = ..., *, _is_text_encoding: bool | None = ..., - ) -> CodecInfo: ... + ) -> Self: ... def getencoder(encoding: str) -> _Encoder: ... def getdecoder(encoding: str) -> _Decoder: ... @@ -115,16 +168,16 @@ def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> G if sys.version_info >= (3, 10): def unregister(__search_function: Callable[[str], CodecInfo | 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 +BOM: Literal[b"\xff\xfe", b"\xfe\xff"] # depends on `sys.byteorder` +BOM_BE: Literal[b"\xfe\xff"] +BOM_LE: Literal[b"\xff\xfe"] +BOM_UTF8: Literal[b"\xef\xbb\xbf"] +BOM_UTF16: Literal[b"\xff\xfe", b"\xfe\xff"] # depends on `sys.byteorder` +BOM_UTF16_BE: Literal[b"\xfe\xff"] +BOM_UTF16_LE: Literal[b"\xff\xfe"] +BOM_UTF32: Literal[b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff"] # depends on `sys.byteorder` +BOM_UTF32_BE: Literal[b"\x00\x00\xfe\xff"] +BOM_UTF32_LE: Literal[b"\xff\xfe\x00\x00"] # It is expected that different actions be taken depending on which of the # three subclasses of `UnicodeError` is actually ...ed. However, the Union @@ -136,6 +189,7 @@ def replace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... def ignore_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... def xmlcharrefreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... def backslashreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def namereplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... class Codec: # These are sort of @abstractmethod but sort of not. @@ -186,10 +240,10 @@ class StreamWriter(Codec): def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -class StreamReader(Codec): +class StreamReader(Codec, Iterator[str]): errors: str def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> str: ... @@ -197,12 +251,11 @@ class StreamReader(Codec): def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[str]: ... def reset(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... - def __iter__(self) -> Iterator[str]: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __iter__(self: Self) -> Self: ... + def __next__(self) -> str: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_T = TypeVar("_T", bound=StreamReaderWriter) - # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): @@ -211,15 +264,13 @@ class StreamReaderWriter(TextIO): def readline(self, size: int | None = ...) -> str: ... def readlines(self, sizehint: int | None = ...) -> list[str]: ... def __next__(self) -> str: ... - def __iter__(self: _T) -> _T: ... - # This actually returns None, but that's incompatible with the supertype - def write(self, data: str) -> int: ... + def __iter__(self: Self) -> Self: ... + def write(self, data: str) -> None: ... # type: ignore[override] def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... - # Same as write() - def seek(self, offset: int, whence: int = ...) -> int: ... + def seek(self, offset: int, whence: int = ...) -> None: ... # type: ignore[override] def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> 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__. @@ -233,8 +284,6 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): def __init__( self, @@ -249,16 +298,16 @@ class StreamRecoder(BinaryIO): def readline(self, size: int | None = ...) -> bytes: ... def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... def __next__(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... - def write(self, data: bytes) -> int: ... - def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None + def __iter__(self: Self) -> Self: ... + def write(self, data: bytes) -> None: ... # type: ignore[override] + def writelines(self, list: Iterable[bytes]) -> None: ... def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def seek(self, offset: int, whence: int = ...) -> None: ... # type: ignore[override] # 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: ... diff --git a/mypy/typeshed/stdlib/codeop.pyi b/mypy/typeshed/stdlib/codeop.pyi index 8ed5710c9891..1c00e13fd501 100644 --- a/mypy/typeshed/stdlib/codeop.pyi +++ b/mypy/typeshed/stdlib/codeop.pyi @@ -1,5 +1,7 @@ from types import CodeType +__all__ = ["compile_command", "Compile", "CommandCompiler"] + def compile_command(source: str, filename: str = ..., symbol: str = ...) -> CodeType | None: ... class Compile: diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index adcdf29fa690..e534c13c026b 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,7 +1,7 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import Self, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT -from typing import Any, Generic, NoReturn, Type, TypeVar, overload +from typing import Any, Generic, NoReturn, TypeVar, overload from typing_extensions import SupportsIndex, final if sys.version_info >= (3, 9): @@ -12,8 +12,12 @@ if sys.version_info >= (3, 10): else: from _collections_abc import * +__all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] + _S = TypeVar("_S") _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -28,12 +32,12 @@ if sys.version_info >= (3, 7): rename: bool = ..., module: str | None = ..., defaults: Iterable[Any] | None = ..., - ) -> Type[tuple[Any, ...]]: ... + ) -> type[tuple[Any, ...]]: ... else: def namedtuple( typename: str, field_names: str | Iterable[str], *, verbose: bool = ..., rename: bool = ..., module: str | None = ... - ) -> Type[tuple[Any, ...]]: ... + ) -> type[tuple[Any, ...]]: ... class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): data: dict[_KT, _VT] @@ -55,8 +59,11 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __contains__(self, key: object) -> bool: ... def copy(self: Self) -> Self: ... + if sys.version_info >= (3, 7): + def __copy__(self: Self) -> Self: ... + # `UserDict.fromkeys` has the same semantics as `dict.fromkeys`, so should be kept in line with `dict.fromkeys`. - # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressable in the current type system. + # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload @@ -64,6 +71,14 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... + if sys.version_info >= (3, 9): + def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + # UserDict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class UserList(MutableSequence[_T]): data: list[_T] @@ -72,6 +87,7 @@ class UserList(MutableSequence[_T]): def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ... def __ge__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __contains__(self, item: object) -> bool: ... def __len__(self) -> int: ... @overload @@ -79,19 +95,24 @@ class UserList(MutableSequence[_T]): @overload def __getitem__(self: Self, i: slice) -> Self: ... @overload - def __setitem__(self, i: SupportsIndex, o: _T) -> None: ... + def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... @overload - def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... + def __setitem__(self, i: slice, item: Iterable[_T]) -> None: ... def __delitem__(self, i: SupportsIndex | 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 __add__(self: Self, other: Iterable[_T]) -> Self: ... + def __radd__(self: Self, other: Iterable[_T]) -> Self: ... + def __iadd__(self: Self, other: Iterable[_T]) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __rmul__(self: Self, n: int) -> Self: ... + def __imul__(self: Self, n: int) -> Self: ... 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 copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... + if sys.version_info >= (3, 7): + def __copy__(self: Self) -> Self: ... + def count(self, item: _T) -> int: ... # All arguments are passed to `list.index` at runtime, so the signature should be kept in line with `list.index`. def index(self, item: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... @@ -102,9 +123,7 @@ class UserList(MutableSequence[_T]): def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... def extend(self, other: Iterable[_T]) -> None: ... -_UserStringT = TypeVar("_UserStringT", bound=UserString) - -class UserString(Sequence[str]): +class UserString(Sequence[UserString]): data: str def __init__(self, seq: object) -> None: ... def __int__(self) -> int: ... @@ -115,25 +134,33 @@ class UserString(Sequence[str]): def __le__(self, string: str | UserString) -> bool: ... def __gt__(self, string: str | UserString) -> bool: ... def __ge__(self, string: str | UserString) -> bool: ... + def __eq__(self, string: object) -> 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: SupportsIndex | slice) -> _UserStringT: ... # type: ignore[override] - def __iter__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] - def __reversed__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] - 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 __getitem__(self: Self, index: SupportsIndex | slice) -> Self: ... + def __iter__(self: Self) -> Iterator[Self]: ... + def __reversed__(self: Self) -> Iterator[Self]: ... + def __add__(self: Self, other: object) -> Self: ... + def __radd__(self: Self, other: object) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __rmul__(self: Self, n: int) -> Self: ... + def __mod__(self: Self, args: Any) -> Self: ... + if sys.version_info >= (3, 8): + def __rmod__(self: Self, template: object) -> Self: ... + else: + def __rmod__(self: Self, format: Any) -> Self: ... + + def capitalize(self: Self) -> Self: ... + def casefold(self: Self) -> Self: ... + def center(self: Self, width: int, *args: Any) -> Self: ... def count(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... if sys.version_info >= (3, 8): def encode(self: UserString, encoding: str | None = ..., errors: str | None = ...) -> bytes: ... else: - def encode(self: _UserStringT, encoding: str | None = ..., errors: str | None = ...) -> _UserStringT: ... + def encode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def endswith(self, suffix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... + def expandtabs(self: Self, tabsize: int = ...) -> Self: ... def find(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... def format_map(self, mapping: Mapping[str, Any]) -> str: ... @@ -151,10 +178,11 @@ class UserString(Sequence[str]): def isupper(self) -> bool: ... if sys.version_info >= (3, 7): def isascii(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: str | None = ...) -> _UserStringT: ... + def ljust(self: Self, width: int, *args: Any) -> Self: ... + def lower(self: Self) -> Self: ... + def lstrip(self: Self, chars: str | None = ...) -> Self: ... @staticmethod @overload def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... @@ -163,24 +191,25 @@ class UserString(Sequence[str]): def maketrans(x: str, y: str, z: str = ...) -> dict[int, int | None]: ... def partition(self, sep: str) -> tuple[str, str, str]: ... if sys.version_info >= (3, 9): - def removeprefix(self: _UserStringT, __prefix: str | UserString) -> _UserStringT: ... - def removesuffix(self: _UserStringT, __suffix: str | UserString) -> _UserStringT: ... - def replace(self: _UserStringT, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> _UserStringT: ... + def removeprefix(self: Self, __prefix: str | UserString) -> Self: ... + def removesuffix(self: Self, __suffix: str | UserString) -> Self: ... + + def replace(self: Self, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> Self: ... def rfind(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def rjust(self: Self, width: int, *args: Any) -> Self: ... def rpartition(self, sep: str) -> tuple[str, str, str]: ... - def rstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... + def rstrip(self: Self, chars: str | None = ...) -> Self: ... def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def splitlines(self, keepends: bool = ...) -> list[str]: ... def startswith(self, prefix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UserStringT, chars: str | None = ...) -> _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: ... + def strip(self: Self, chars: str | None = ...) -> Self: ... + def swapcase(self: Self) -> Self: ... + def title(self: Self) -> Self: ... + def translate(self: Self, *args: Any) -> Self: ... + def upper(self: Self) -> Self: ... + def zfill(self: Self, width: int) -> Self: ... class deque(MutableSequence[_T], Generic[_T]): @property @@ -188,7 +217,7 @@ class deque(MutableSequence[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... def append(self, __x: _T) -> None: ... def appendleft(self, __x: _T) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def count(self, __x: _T) -> int: ... def extend(self, __iterable: Iterable[_T]) -> None: ... def extendleft(self, __iterable: Iterable[_T]) -> None: ... @@ -198,25 +227,30 @@ class deque(MutableSequence[_T], Generic[_T]): def popleft(self) -> _T: ... def remove(self, __value: _T) -> None: ... def rotate(self, __n: int = ...) -> None: ... - def __copy__(self: _S) -> _S: ... + def __copy__(self: Self) -> Self: ... def __len__(self) -> int: ... - def __str__(self) -> str: ... # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores def __getitem__(self, __index: SupportsIndex) -> _T: ... # type: ignore[override] def __setitem__(self, __i: SupportsIndex, __x: _T) -> None: ... # type: ignore[override] def __delitem__(self, __i: SupportsIndex) -> None: ... # type: ignore[override] def __contains__(self, __o: object) -> bool: ... - def __reduce__(self: Self) -> tuple[Type[Self], tuple[()], None, Iterator[_T]]: ... - def __iadd__(self: _S, __iterable: Iterable[_T]) -> _S: ... - def __add__(self: _S, __other: _S) -> _S: ... - def __mul__(self: _S, __other: int) -> _S: ... - def __imul__(self: _S, __other: int) -> _S: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... + def __iadd__(self: Self, __iterable: Iterable[_T]) -> Self: ... + def __add__(self: Self, __other: Self) -> Self: ... + def __mul__(self: Self, __other: int) -> Self: ... + def __imul__(self: Self, __other: int) -> Self: ... + def __lt__(self, __other: deque[_T]) -> bool: ... + def __le__(self, __other: deque[_T]) -> bool: ... + def __gt__(self, __other: deque[_T]) -> bool: ... + def __ge__(self, __other: deque[_T]) -> bool: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class Counter(dict[_T, int], Generic[_T]): @overload - def __init__(self, __iterable: None = ..., **kwargs: int) -> None: ... + def __init__(self: Counter[_T], __iterable: None = ...) -> None: ... + @overload + def __init__(self: Counter[str], __iterable: None = ..., **kwargs: int) -> None: ... @overload def __init__(self, __mapping: SupportsKeysAndGetItem[_T, int]) -> None: ... @overload @@ -232,29 +266,41 @@ class Counter(dict[_T, int], Generic[_T]): 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. + # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload + # (source code does an `isinstance(other, Mapping)` check) + # + # The second overload is also deliberately different to dict.update() + # (if it were `Iterable[_T] | Iterable[tuple[_T, int]]`, + # the tuples would be added as keys, breaking type safety) + @overload # type: ignore[override] + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... @overload - def update(self, __m: SupportsKeysAndGetItem[_T, int], **kwargs: int) -> None: ... - @overload - def update(self, __m: Iterable[_T] | Iterable[tuple[_T, int]], **kwargs: int) -> None: ... + def update(self, __m: Iterable[_T], **kwargs: int) -> None: ... @overload def update(self, __m: None = ..., **kwargs: int) -> None: ... - def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __missing__(self, key: _T) -> int: ... + def __delitem__(self, elem: object) -> None: ... + if sys.version_info >= (3, 10): + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + + def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: ... def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore[override] + def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] 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]: ... # type: ignore[override] + # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc. + def __iadd__(self: Self, other: Counter[_T]) -> Self: ... # type: ignore[misc] + def __isub__(self: Self, other: Counter[_T]) -> Self: ... + def __iand__(self: Self, other: Counter[_T]) -> Self: ... + def __ior__(self: Self, other: Counter[_T]) -> Self: ... # type: ignore[override,misc] if sys.version_info >= (3, 10): def total(self) -> int: ... + def __le__(self, other: Counter[Any]) -> bool: ... + def __lt__(self, other: Counter[Any]) -> bool: ... + def __ge__(self, other: Counter[Any]) -> bool: ... + def __gt__(self, other: Counter[Any]) -> bool: ... @final class _OrderedDictKeysView(dict_keys[_KT_co, _VT_co], Reversible[_KT_co]): # type: ignore[misc] @@ -276,39 +322,52 @@ class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): def keys(self) -> _OrderedDictKeysView[_KT, _VT]: ... def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... def values(self) -> _OrderedDictValuesView[_KT, _VT]: ... - # `fromkeys` is actually inherited from `dict` at runtime, so the signature should be kept in line with `dict.fromkeys`. - # Ideally we would not redefine it here, but the true signature of `dict.fromkeys` is not expressable in the current type system. + # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences. + # Like dict.fromkeys, its true signature is not expressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> OrderedDict[_T, Any | None]: ... + def fromkeys(cls, iterable: Iterable[_T], value: None = ...) -> OrderedDict[_T, Any | None]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> OrderedDict[_T, _S]: ... + def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ... + # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: OrderedDict[_KT, _T | None], key: _KT) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] | None @overload - def __init__(self, **kwargs: _VT) -> None: ... + def __init__(self: defaultdict[_KT, _VT]) -> None: ... + @overload + def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... @overload def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ... @overload - def __init__(self, __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... + def __init__(self: defaultdict[str, _VT], __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... @overload def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... @overload def __init__( - self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT + self: defaultdict[str, _VT], + __default_factory: Callable[[], _VT] | None, + __map: SupportsKeysAndGetItem[str, _VT], + **kwargs: _VT, ) -> None: ... @overload def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... @overload def __init__( - self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT + self: defaultdict[str, _VT], + __default_factory: Callable[[], _VT] | None, + __iterable: Iterable[tuple[str, _VT]], + **kwargs: _VT, ) -> None: ... def __missing__(self, __key: _KT) -> _VT: ... - def __copy__(self: _S) -> _S: ... - def copy(self: _S) -> _S: ... + def __copy__(self: Self) -> Self: ... + def copy(self: Self) -> Self: ... class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] @@ -316,18 +375,21 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def new_child(self: Self, m: MutableMapping[_KT, _VT] | None = ...) -> Self: ... @property def parents(self: Self) -> Self: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... + def __contains__(self, key: object) -> bool: ... def __missing__(self, key: _KT) -> _VT: ... # undocumented + def __bool__(self) -> bool: ... def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... def copy(self: Self) -> Self: ... + __copy__ = copy # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, so the signature should be kept in line with `dict.fromkeys`. @classmethod @overload @@ -335,3 +397,11 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @classmethod @overload def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> ChainMap[_T, _S]: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... diff --git a/mypy/typeshed/stdlib/colorsys.pyi b/mypy/typeshed/stdlib/colorsys.pyi index 00c5f9d22cb1..443ee828ebfe 100644 --- a/mypy/typeshed/stdlib/colorsys.pyi +++ b/mypy/typeshed/stdlib/colorsys.pyi @@ -1,3 +1,5 @@ +__all__ = ["rgb_to_yiq", "yiq_to_rgb", "rgb_to_hls", "hls_to_rgb", "rgb_to_hsv", "hsv_to_rgb"] + 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]: ... diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index 64b4dc2bc5f7..7101fd05f717 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -5,6 +5,8 @@ from typing import Any, Protocol if sys.version_info >= (3, 7): from py_compile import PycInvalidationMode +__all__ = ["compile_dir", "compile_file", "compile_path"] + class _SupportsSearch(Protocol): def search(self, string: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi index f3b54e54228c..dbf8ea3df857 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi @@ -1,5 +1,21 @@ import sys +if sys.version_info >= (3, 7): + __all__ = ( + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + ) + from ._base import ( ALL_COMPLETED as ALL_COMPLETED, FIRST_COMPLETED as FIRST_COMPLETED, diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index b55351aacc6f..cf822fc557a2 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -5,7 +5,7 @@ from abc import abstractmethod from collections.abc import Container, Iterable, Iterator, Sequence from logging import Logger from typing import Any, Callable, Generic, Protocol, TypeVar, overload -from typing_extensions import Literal, SupportsIndex +from typing_extensions import Literal, ParamSpec, SupportsIndex if sys.version_info >= (3, 9): from types import GenericAlias @@ -33,8 +33,8 @@ if sys.version_info >= (3, 7): class BrokenExecutor(RuntimeError): ... _T = TypeVar("_T") - _T_co = TypeVar("_T_co", covariant=True) +_P = ParamSpec("_P") # Copied over Collection implementation as it does not exist in Python 2 and <3.6. # Also to solve pytype issues with _Collection. @@ -60,9 +60,10 @@ class Future(Generic[_T]): class Executor: if sys.version_info >= (3, 9): - def submit(self, __fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def submit(self, __fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... else: - def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def submit(self, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... + def map( self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = ..., chunksize: int = ... ) -> Iterator[_T]: ... @@ -70,6 +71,7 @@ class Executor: def shutdown(self, wait: bool = ..., *, cancel_futures: bool = ...) -> None: ... else: def shutdown(self, wait: bool = ...) -> None: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool | None: ... @@ -77,14 +79,16 @@ def as_completed(fs: Iterable[Future[_T]], timeout: float | None = ...) -> Itera # 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]] + @property + def done(self) -> set[Future[_T]]: ... + @property + def not_done(self) -> 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: SupportsIndex) -> set[Future[_T]]: ... + def __getitem__(self, __i: SupportsIndex) -> set[Future[_T]]: ... @overload - def __getitem__(self, s: slice) -> DoneAndNotDoneFutures[_T]: ... + def __getitem__(self, __s: slice) -> DoneAndNotDoneFutures[_T]: ... def wait(fs: Iterable[Future[_T]], timeout: float | None = ..., return_when: str = ...) -> DoneAndNotDoneFutures[_T]: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 6435901a8f13..0c6c403949ad 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -31,7 +31,6 @@ _MAX_WINDOWS_WORKERS: int class _RemoteTraceback(Exception): tb: str def __init__(self, tb: TracebackType) -> None: ... - def __str__(self) -> str: ... class _ExceptionWithTraceback: exc: BaseException @@ -82,6 +81,7 @@ if sys.version_info >= (3, 7): def __init__( self, max_size: int | None = ..., *, ctx: BaseContext, pending_work_items: dict[int, _WorkItem[Any]] ) -> None: ... + def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: ... @@ -131,6 +131,7 @@ def _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> A if sys.version_info >= (3, 7): from ._base import BrokenExecutor + class BrokenProcessPool(BrokenExecutor): ... else: @@ -164,4 +165,5 @@ class ProcessPoolExecutor(Executor): def __init__(self, max_workers: int | None = ...) -> None: ... if sys.version_info >= (3, 9): def _start_executor_manager_thread(self) -> None: ... + def _adjust_process_count(self) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index f27c43c3403c..46ca681c54fc 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -41,6 +41,7 @@ else: if sys.version_info >= (3, 7): from ._base import BrokenExecutor + class BrokenThreadPool(BrokenExecutor): ... class ThreadPoolExecutor(Executor): @@ -67,6 +68,7 @@ class ThreadPoolExecutor(Executor): ) -> None: ... else: def __init__(self, max_workers: int | None = ..., thread_name_prefix: str = ...) -> None: ... + def _adjust_thread_count(self) -> None: ... if sys.version_info >= (3, 7): def _initializer_failed(self) -> None: ... diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index dc81cb78577a..6b043263775c 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -1,9 +1,33 @@ import sys from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, ClassVar, Optional, Pattern, Type, TypeVar, overload +from typing import Any, ClassVar, Optional, Pattern, TypeVar, overload from typing_extensions import Literal +__all__ = [ + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "SafeConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", +] + # Internal type aliases _section = Mapping[str, str] _parser = MutableMapping[str, _section] @@ -16,8 +40,8 @@ if sys.version_info >= (3, 7): else: _Path = StrPath -DEFAULTSECT: str -MAX_INTERPOLATION_DEPTH: int +DEFAULTSECT: Literal["DEFAULT"] +MAX_INTERPOLATION_DEPTH: Literal[10] class Interpolation: def before_get(self, parser: _parser, section: str, option: str, value: str, defaults: _section) -> str: ... @@ -47,7 +71,7 @@ class RawConfigParser(_parser): def __init__( self, defaults: Mapping[str, str | None] | None = ..., - dict_type: Type[Mapping[str, str]] = ..., + dict_type: type[Mapping[str, str]] = ..., allow_no_value: Literal[True] = ..., *, delimiters: Sequence[str] = ..., @@ -63,7 +87,7 @@ class RawConfigParser(_parser): def __init__( self, defaults: _section | None = ..., - dict_type: Type[Mapping[str, str]] = ..., + dict_type: type[Mapping[str, str]] = ..., allow_no_value: bool = ..., *, delimiters: Sequence[str] = ..., @@ -76,10 +100,11 @@ class RawConfigParser(_parser): 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 __getitem__(self, key: str) -> SectionProxy: ... + def __setitem__(self, key: str, value: _section) -> None: ... + def __delitem__(self, key: str) -> None: ... def __iter__(self) -> Iterator[str]: ... + def __contains__(self, key: object) -> bool: ... def defaults(self) -> _section: ... def sections(self) -> list[str]: ... def add_section(self, section: str) -> None: ... @@ -138,8 +163,8 @@ class RawConfigParser(_parser): class ConfigParser(RawConfigParser): ... -if sys.version_info < (3, 11): - class SafeConfigParser(ConfigParser): ... +if sys.version_info < (3, 12): + class SafeConfigParser(ConfigParser): ... # deprecated alias class SectionProxy(MutableMapping[str, str]): def __init__(self, parser: RawConfigParser, name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index b536c36678a2..c2731dea7807 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import ( +from typing import ( # noqa Y027 IO, Any, AsyncGenerator, @@ -14,15 +14,74 @@ from typing import ( Iterator, Optional, Protocol, - Type, TypeVar, overload, ) from typing_extensions import ParamSpec +if sys.version_info >= (3, 11): + __all__ = [ + "asynccontextmanager", + "contextmanager", + "closing", + "nullcontext", + "AbstractContextManager", + "AbstractAsyncContextManager", + "AsyncExitStack", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + "aclosing", + "chdir", + ] +elif sys.version_info >= (3, 10): + __all__ = [ + "asynccontextmanager", + "contextmanager", + "closing", + "nullcontext", + "AbstractContextManager", + "AbstractAsyncContextManager", + "AsyncExitStack", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + "aclosing", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "asynccontextmanager", + "contextmanager", + "closing", + "nullcontext", + "AbstractContextManager", + "AbstractAsyncContextManager", + "AsyncExitStack", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + ] +else: + __all__ = [ + "contextmanager", + "closing", + "AbstractContextManager", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + ] + AbstractContextManager = ContextManager if sys.version_info >= (3, 7): - from typing import AsyncContextManager + from typing import AsyncContextManager # noqa Y022 AbstractAsyncContextManager = AsyncContextManager @@ -32,7 +91,7 @@ _T_io = TypeVar("_T_io", bound=Optional[IO[str]]) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] +_ExitFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], Optional[bool]] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) class ContextDecorator: @@ -47,13 +106,18 @@ class _GeneratorContextManager(AbstractContextManager[_T_co], ContextDecorator, func: Callable[..., Generator[_T_co, Any, Any]] args: tuple[Any, ...] kwds: dict[str, Any] + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... if sys.version_info >= (3, 10): _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + class AsyncContextDecorator: def __call__(self, func: _AF) -> _AF: ... + class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], AsyncContextDecorator, Generic[_T_co]): # __init__ and these attributes are actually defined in the base class _GeneratorContextManagerBase, # which is more trouble than it's worth to include in the stub (see #6676) @@ -62,6 +126,9 @@ if sys.version_info >= (3, 10): func: Callable[..., AsyncGenerator[_T_co, Any]] args: tuple[Any, ...] kwds: dict[str, Any] + async def __aexit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... elif sys.version_info >= (3, 7): class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], Generic[_T_co]): @@ -70,6 +137,9 @@ elif sys.version_info >= (3, 7): func: Callable[..., AsyncGenerator[_T_co, Any]] args: tuple[Any, ...] kwds: dict[str, Any] + async def __aexit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... if sys.version_info >= (3, 7): def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... @@ -81,56 +151,64 @@ _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) class closing(AbstractContextManager[_SupportsCloseT]): def __init__(self, thing: _SupportsCloseT) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... if sys.version_info >= (3, 10): class _SupportsAclose(Protocol): - def aclose(self) -> Awaitable[object]: ... + async def aclose(self) -> object: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) + class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... + async def __aexit__(self, *exc_info: object) -> None: ... class suppress(AbstractContextManager[None]): - def __init__(self, *exceptions: Type[BaseException]) -> None: ... + def __init__(self, *exceptions: type[BaseException]) -> None: ... def __exit__( - self, exctype: Type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None ) -> bool: ... -class redirect_stdout(AbstractContextManager[_T_io]): +class _RedirectStream(AbstractContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... + def __exit__( + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + ) -> None: ... -class redirect_stderr(AbstractContextManager[_T_io]): - def __init__(self, new_target: _T_io) -> None: ... +class redirect_stdout(_RedirectStream[_T_io]): ... +class redirect_stderr(_RedirectStream[_T_io]): ... class ExitStack(AbstractContextManager[ExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_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[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... def pop_all(self: Self) -> Self: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None ) -> bool: ... if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] - _CallbackCoroFunc = Callable[..., Awaitable[Any]] + _ExitCoroFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) + class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... - def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> Awaitable[_T]: ... + async def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> _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[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... + def push_async_callback( + self, __callback: Callable[_P, Awaitable[_T]], *args: _P.args, **kwds: _P.kwargs + ) -> Callable[_P, Awaitable[_T]]: ... def pop_all(self: Self) -> Self: ... - def aclose(self) -> Awaitable[None]: ... - def __aenter__(self: Self) -> Awaitable[Self]: ... - def __aexit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> Awaitable[bool]: ... + async def aclose(self) -> None: ... + async def __aenter__(self: Self) -> Self: ... + async def __aexit__( + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + ) -> bool: ... if sys.version_info >= (3, 10): class nullcontext(AbstractContextManager[_T], AbstractAsyncContextManager[_T]): @@ -156,6 +234,7 @@ elif sys.version_info >= (3, 7): if sys.version_info >= (3, 11): _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=int | StrOrBytesPath) + class chdir(AbstractContextManager[None], Generic[_T_fd_or_any_path]): path: _T_fd_or_any_path def __init__(self, path: _T_fd_or_any_path) -> None: ... diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index e97f62188dcb..6b5661dd69eb 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -1,12 +1,17 @@ import sys from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, overload +from typing_extensions import ParamSpec, final if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ("Context", "ContextVar", "Token", "copy_context") + _T = TypeVar("_T") _D = TypeVar("_D") +_P = ParamSpec("_P") +@final class ContextVar(Generic[_T]): def __init__(self, name: str, *, default: _T = ...) -> None: ... @property @@ -15,11 +20,12 @@ class ContextVar(Generic[_T]): def get(self) -> _T: ... @overload def get(self, default: _D | _T) -> _D | _T: ... - def set(self, value: _T) -> Token[_T]: ... - def reset(self, token: Token[_T]) -> None: ... + 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: ... +@final class Token(Generic[_T]): @property def var(self) -> ContextVar[_T]: ... @@ -33,14 +39,15 @@ def copy_context() -> Context: ... # It doesn't make sense to make this generic, because for most Contexts each ContextVar will have # a different value. +@final class Context(Mapping[ContextVar[Any], Any]): def __init__(self) -> None: ... @overload - def get(self, __key: ContextVar[Any]) -> Any | None: ... + def get(self, __key: ContextVar[_T]) -> _T | None: ... @overload - def get(self, __key: ContextVar[Any], __default: Any | None) -> Any: ... - def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... + def get(self, __key: ContextVar[_T], __default: _D) -> _T | _D: ... + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... def copy(self) -> Context: ... - def __getitem__(self, key: ContextVar[Any]) -> Any: ... + def __getitem__(self, __key: ContextVar[_T]) -> _T: ... def __iter__(self) -> Iterator[ContextVar[Any]]: ... def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/copy.pyi b/mypy/typeshed/stdlib/copy.pyi index a5f9420e3811..b53f418b3930 100644 --- a/mypy/typeshed/stdlib/copy.pyi +++ b/mypy/typeshed/stdlib/copy.pyi @@ -1,5 +1,7 @@ from typing import Any, TypeVar +__all__ = ["Error", "copy", "deepcopy"] + _T = TypeVar("_T") # None in CPython but non-None in Jython diff --git a/mypy/typeshed/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index 6097670833c0..8ac3e87ef3fe 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,18 +1,19 @@ from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union -_TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] +_T = TypeVar("_T") +_Reduce = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Optional[Any]]] -__all__: list[str] +__all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] def pickle( - ob_type: _TypeT, - pickle_function: Callable[[_TypeT], str | _Reduce[_TypeT]], - constructor_ob: Callable[[_Reduce[_TypeT]], _TypeT] | None = ..., + ob_type: type[_T], + pickle_function: Callable[[_T], str | _Reduce[_T]], + constructor_ob: Callable[[_Reduce[_T]], _T] | None = ..., ) -> None: ... -def constructor(object: Callable[[_Reduce[_TypeT]], _TypeT]) -> None: ... +def constructor(object: Callable[[_Reduce[_T]], _T]) -> 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: ... -dispatch_table: dict[type, Callable[[type], str | _Reduce[type]]] # undocumented +_DispatchTableType = dict[type, Callable[[Any], str | _Reduce[Any]]] # imported by multiprocessing.reduction +dispatch_table: _DispatchTableType # undocumented diff --git a/mypy/typeshed/stdlib/crypt.pyi b/mypy/typeshed/stdlib/crypt.pyi index a8342859e770..5083f1eebeed 100644 --- a/mypy/typeshed/stdlib/crypt.pyi +++ b/mypy/typeshed/stdlib/crypt.pyi @@ -15,4 +15,5 @@ if sys.platform != "win32": def mksalt(method: _Method | None = ..., *, rounds: int | None = ...) -> str: ... else: def mksalt(method: _Method | None = ...) -> str: ... + def crypt(word: str, salt: str | _Method | None = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 63999be059f6..dcb3f19bebe1 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -6,6 +6,7 @@ from _csv import ( QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, Dialect as Dialect, Error as Error, + __version__ as __version__, _DialectLike, _reader, _writer, @@ -17,14 +18,39 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) +from _typeshed import Self from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence -from typing import Any, Generic, Type, TypeVar, overload +from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 8): from builtins import dict as _DictReadMapping else: from collections import OrderedDict as _DictReadMapping +__all__ = [ + "QUOTE_MINIMAL", + "QUOTE_ALL", + "QUOTE_NONNUMERIC", + "QUOTE_NONE", + "Error", + "Dialect", + "__doc__", + "excel", + "excel_tab", + "field_size_limit", + "reader", + "writer", + "register_dialect", + "get_dialect", + "list_dialects", + "Sniffer", + "unregister_dialect", + "__version__", + "DictReader", + "DictWriter", + "unix_dialect", +] + _T = TypeVar("_T") class excel(Dialect): @@ -75,7 +101,7 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): *args: Any, **kwds: Any, ) -> None: ... - def __iter__(self) -> DictReader[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _DictReadMapping[_T, str]: ... class DictWriter(Generic[_T]): @@ -97,11 +123,12 @@ class DictWriter(Generic[_T]): def writeheader(self) -> Any: ... else: def writeheader(self) -> None: ... + def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... class Sniffer: preferred: list[str] def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... + def sniff(self, sample: str, delimiters: str | None = ...) -> type[Dialect]: ... def has_header(self, sample: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 7f2eba011d0f..d4caa7a88d76 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import ReadableBuffer, WriteableBuffer +from _typeshed import ReadableBuffer, Self, WriteableBuffer from abc import abstractmethod from typing import ( Any, @@ -11,7 +11,6 @@ from typing import ( Mapping, Optional, Sequence, - Type, TypeVar, Union as _UnionT, overload, @@ -33,7 +32,7 @@ class CDLL: _func_restype_: ClassVar[_CData] _name: str _handle: int - _FuncPtr: Type[_FuncPointer] + _FuncPtr: type[_FuncPointer] if sys.version_info >= (3, 8): def __init__( self, @@ -48,8 +47,9 @@ class CDLL: def __init__( self, name: str | None, mode: int = ..., handle: int | None = ..., use_errno: bool = ..., use_last_error: bool = ... ) -> None: ... + def __getattr__(self, name: str) -> _NamedFuncPointer: ... - def __getitem__(self, name: str) -> _NamedFuncPointer: ... + def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ... if sys.platform == "win32": class OleDLL(CDLL): ... @@ -58,7 +58,7 @@ if sys.platform == "win32": class PyDLL(CDLL): ... class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... + 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: ... @@ -76,33 +76,33 @@ 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[misc] - def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore[misc] + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] class _CData(metaclass=_CDataMeta): _b_base: int _b_needsfree_: bool _objects: Mapping[Any, int] | None @classmethod - def from_buffer(cls: Type[_CT], source: WriteableBuffer, offset: int = ...) -> _CT: ... + def from_buffer(cls: type[Self], source: WriteableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_buffer_copy(cls: Type[_CT], source: ReadableBuffer, offset: int = ...) -> _CT: ... + def from_buffer_copy(cls: type[Self], source: ReadableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... + def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _CT | _CArgObject: ... + def from_param(cls: type[Self], obj: Any) -> Self | _CArgObject: ... @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, tuple[_CData, ...]], _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: Type[_CData] | Callable[[int], Any] | None - argtypes: Sequence[Type[_CData]] + restype: type[_CData] | Callable[[int], Any] | None + argtypes: Sequence[type[_CData]] errcheck: _ECT @overload def __init__(self, address: int) -> None: ... @@ -120,15 +120,15 @@ class _NamedFuncPointer(_FuncPointer): class ArgumentError(Exception): ... def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... +) -> type[_FuncPointer]: ... if sys.platform == "win32": def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... + ) -> type[_FuncPointer]: ... -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... +def PYFUNCTYPE(restype: type[_CData] | None, *argtypes: type[_CData]) -> type[_FuncPointer]: ... class _CArgObject: ... @@ -142,12 +142,12 @@ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] _CVoidConstPLike = _UnionT[_CVoidPLike, bytes] def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _CData | Type[_CData]) -> int: ... +def alignment(obj_or_type: _CData | type[_CData]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _CData | _CArgObject | int, typ: Type[_CastT]) -> _CastT: ... +def cast(obj: _CData | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... def create_string_buffer(init: int | bytes, size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer @@ -165,25 +165,25 @@ 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]]: ... +def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> int: ... +def memset(dst: _CVoidPLike, c: int, count: int) -> int: ... +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_: Type[_CT] + _type_: type[_CT] contents: _CT def __init__(self, arg: _CT = ...) -> None: ... @overload - def __getitem__(self, i: int) -> _CT: ... + def __getitem__(self, __i: int) -> _CT: ... @overload - def __getitem__(self, s: slice) -> list[_CT]: ... + def __getitem__(self, __s: slice) -> list[_CT]: ... @overload - def __setitem__(self, i: int, o: _CT) -> None: ... + def __setitem__(self, __i: int, __o: _CT) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... + def __setitem__(self, __s: slice, __o: Iterable[_CT]) -> None: ... def resize(obj: _CData, size: int) -> None: ... def set_errno(value: int) -> int: ... @@ -191,7 +191,7 @@ def set_errno(value: int) -> int: ... if sys.platform == "win32": def set_last_error(value: int) -> int: ... -def sizeof(obj_or_type: _CData | Type[_CData]) -> int: ... +def sizeof(obj_or_type: _CData | type[_CData]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -252,7 +252,7 @@ class _CField: size: int class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[tuple[str, Type[_CData]] | tuple[str, Type[_CData], int]] + _fields_: Sequence[tuple[str, type[_CData]] | tuple[str, type[_CData], int]] _pack_: int _anonymous_: Sequence[str] def __getattr__(self, name: str) -> _CField: ... @@ -275,9 +275,9 @@ class Array(Generic[_CT], _CData): def _length_(self, value: int) -> None: ... @property @abstractmethod - def _type_(self) -> Type[_CT]: ... + def _type_(self) -> type[_CT]: ... @_type_.setter - def _type_(self, value: Type[_CT]) -> None: ... + def _type_(self, value: type[_CT]) -> None: ... raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. @@ -294,13 +294,13 @@ class Array(Generic[_CT], _CData): # the array element type would belong are annotated with Any instead. def __init__(self, *args: Any) -> None: ... @overload - def __getitem__(self, i: int) -> Any: ... + def __getitem__(self, __i: int) -> Any: ... @overload - def __getitem__(self, s: slice) -> list[Any]: ... + def __getitem__(self, __s: slice) -> list[Any]: ... @overload - def __setitem__(self, i: int, o: Any) -> None: ... + def __setitem__(self, __i: int, __o: Any) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ... + 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. diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index aef2d9b95ed5..ee74c13b6b50 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -2,7 +2,7 @@ import sys from typing import Any, Callable, TypeVar if sys.platform != "win32": - from _curses import * # noqa: F403 + from _curses import * from _curses import _CursesWindow as _CursesWindow _T = TypeVar("_T") @@ -14,4 +14,6 @@ if sys.platform != "win32": # available after calling `curses.start_color()` COLORS: int COLOR_PAIRS: int + # TODO: wait for `Concatenate` support + # def wrapper(__func: Callable[Concatenate[_CursesWindow, _P], _T], *arg: _P.args, **kwds: _P.kwargs) -> _T: ... def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/curses/panel.pyi b/mypy/typeshed/stdlib/curses/panel.pyi index ed13a6e050e9..30803791f039 100644 --- a/mypy/typeshed/stdlib/curses/panel.pyi +++ b/mypy/typeshed/stdlib/curses/panel.pyi @@ -4,6 +4,7 @@ if sys.platform != "win32": from _curses import _CursesWindow version: str + class _Curses_Panel: # type is (note the space in the class name) def above(self) -> _Curses_Panel: ... def below(self) -> _Curses_Panel: ... @@ -17,6 +18,7 @@ if sys.platform != "win32": 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: ... diff --git a/mypy/typeshed/stdlib/curses/textpad.pyi b/mypy/typeshed/stdlib/curses/textpad.pyi index eb6879603853..b8a9c843f402 100644 --- a/mypy/typeshed/stdlib/curses/textpad.pyi +++ b/mypy/typeshed/stdlib/curses/textpad.pyi @@ -4,6 +4,7 @@ from typing import Callable if sys.platform != "win32": from _curses import _CursesWindow 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: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 885facb9c0db..f8e4044932ed 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -1,6 +1,9 @@ +import enum import sys import types -from typing import Any, Callable, Generic, Iterable, Mapping, Protocol, Type, TypeVar, overload +from builtins import type as Type # alias to avoid name clashes with fields named "type" +from typing import Any, Callable, Generic, Iterable, Mapping, Protocol, TypeVar, overload +from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias @@ -8,9 +11,47 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -class _MISSING_TYPE: ... +if sys.version_info >= (3, 10): + __all__ = [ + "dataclass", + "field", + "Field", + "FrozenInstanceError", + "InitVar", + "KW_ONLY", + "MISSING", + "fields", + "asdict", + "astuple", + "make_dataclass", + "replace", + "is_dataclass", + ] +else: + __all__ = [ + "dataclass", + "field", + "Field", + "FrozenInstanceError", + "InitVar", + "MISSING", + "fields", + "asdict", + "astuple", + "make_dataclass", + "replace", + "is_dataclass", + ] -MISSING: _MISSING_TYPE +# define _MISSING_TYPE as an enum within the type stubs, +# even though that is not really its type at runtime +# this allows us to use Literal[_MISSING_TYPE.MISSING] +# for background, see: +# https://github.com/python/typeshed/pull/5900#issuecomment-895513797 +class _MISSING_TYPE(enum.Enum): + MISSING = enum.auto() + +MISSING = _MISSING_TYPE.MISSING if sys.version_info >= (3, 10): class KW_ONLY: ... @@ -26,9 +67,9 @@ def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... if sys.version_info >= (3, 10): @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... + def dataclass(__cls: type[_T]) -> type[_T]: ... @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... @overload def dataclass( *, @@ -41,28 +82,28 @@ if sys.version_info >= (3, 10): match_args: bool = ..., kw_only: bool = ..., slots: bool = ..., - ) -> Callable[[Type[_T]], Type[_T]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... elif sys.version_info >= (3, 8): # cls argument is now positional-only @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... + def dataclass(__cls: type[_T]) -> type[_T]: ... @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + 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]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... else: @overload - def dataclass(_cls: Type[_T]) -> Type[_T]: ... + def dataclass(_cls: type[_T]) -> type[_T]: ... @overload - def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + 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]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... # See https://github.com/python/mypy/issues/10750 class _DefaultFactory(Protocol[_T_co]): @@ -71,15 +112,15 @@ class _DefaultFactory(Protocol[_T_co]): class Field(Generic[_T]): name: str type: Type[_T] - default: _T - default_factory: _DefaultFactory[_T] + default: _T | Literal[_MISSING_TYPE.MISSING] + default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING] repr: bool hash: bool | None init: bool compare: bool metadata: types.MappingProxyType[Any, Any] if sys.version_info >= (3, 10): - kw_only: bool + kw_only: bool | Literal[_MISSING_TYPE.MISSING] def __init__( self, default: _T, @@ -102,6 +143,8 @@ class Field(Generic[_T]): compare: bool, metadata: Mapping[Any, Any], ) -> None: ... + + def __set_name__(self, owner: Type[Any], name: str) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index e0ce085c2967..df33fb88f37e 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,13 +1,16 @@ import sys +from _typeshed import Self from time import struct_time -from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, Type, TypeVar, overload -from typing_extensions import final +from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload +from typing_extensions import Literal, final + +if sys.version_info >= (3, 9): + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") -_S = TypeVar("_S") _D = TypeVar("_D", bound=date) -MINYEAR: int -MAXYEAR: int +MINYEAR: Literal[1] +MAXYEAR: Literal[9999] class tzinfo: def tzname(self, __dt: datetime | None) -> str | None: ... @@ -36,19 +39,20 @@ class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls: type[Self], year: int, month: int, day: int) -> Self: ... @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], __n: int) -> _S: ... + def fromordinal(cls: type[Self], __n: int) -> Self: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... + def fromisocalendar(cls: type[Self], year: int, week: int, day: int) -> Self: ... + @property def year(self) -> int: ... @property @@ -67,10 +71,10 @@ class date: 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: ... + def __add__(self: Self, __other: timedelta) -> Self: ... + def __radd__(self: Self, __other: timedelta) -> Self: ... @overload - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self, __other: datetime) -> NoReturn: ... @overload @@ -85,6 +89,7 @@ class date: def __sub__(self, __other: datetime) -> NoReturn: ... @overload def __sub__(self, __other: date) -> timedelta: ... + def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -98,7 +103,7 @@ class time: max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], hour: int = ..., minute: int = ..., second: int = ..., @@ -106,7 +111,7 @@ class time: tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -127,7 +132,8 @@ class time: def isoformat(self, timespec: str = ...) -> str: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __time_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __time_string: str) -> Self: ... + def strftime(self, __format: str) -> str: ... def __format__(self, __fmt: str) -> str: ... def utcoffset(self) -> timedelta | None: ... @@ -152,7 +158,7 @@ class timedelta(SupportsAbs[timedelta]): max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], days: float = ..., seconds: float = ..., microseconds: float = ..., @@ -160,7 +166,7 @@ class timedelta(SupportsAbs[timedelta]): minutes: float = ..., hours: float = ..., weeks: float = ..., - ) -> _S: ... + ) -> Self: ... @property def days(self) -> int: ... @property @@ -199,7 +205,7 @@ class datetime(date): max: ClassVar[datetime] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], year: int, month: int, day: int, @@ -210,7 +216,7 @@ class datetime(date): tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -227,26 +233,28 @@ class datetime(date): # but it is named "timestamp" in the C implementation and "t" in the Python implementation, # so it is only truly *safe* to pass it as a positional argument. @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float, tz: _tzinfo | None = ...) -> Self: ... @classmethod - def utcfromtimestamp(cls: Type[_S], __t: float) -> _S: ... + def utcfromtimestamp(cls: type[Self], __t: float) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def now(cls: Type[_S], tz: _tzinfo | None = ...) -> _S: ... + def now(cls: type[Self], tz: _tzinfo | None = ...) -> Self: ... else: @overload @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... + def now(cls: type[Self], tz: None = ...) -> Self: ... @overload @classmethod def now(cls, tz: _tzinfo) -> datetime: ... + @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + def utcnow(cls: type[Self]) -> Self: ... @classmethod def combine(cls, date: _date, time: _time, tzinfo: _tzinfo | None = ...) -> datetime: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... + def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... @@ -266,9 +274,10 @@ class datetime(date): fold: int = ..., ) -> datetime: ... if sys.version_info >= (3, 8): - def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... + def astimezone(self: Self, tz: _tzinfo | None = ...) -> Self: ... else: def astimezone(self, tz: _tzinfo | None = ...) -> datetime: ... + def ctime(self) -> str: ... def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod @@ -282,7 +291,7 @@ class datetime(date): def __gt__(self, __other: datetime) -> bool: ... # type: ignore[override] if sys.version_info >= (3, 8): @overload # type: ignore[override] - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self: _D, __other: _D) -> timedelta: ... else: diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 5ecacd91b4ed..630a0d16c1c7 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,8 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Union from typing_extensions import Literal +__all__ = ["open", "whichdb", "error"] + _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] _TFlags = Literal[ @@ -82,12 +84,12 @@ class _Database(MutableMapping[_KeyType, bytes]): def __del__(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... class _error(Exception): ... -error: tuple[Type[_error], Type[OSError]] +error: tuple[type[_error], type[OSError]] def whichdb(filename: str) -> str: ... def open(file: str, flag: _TFlags = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index 0a941b070754..c877ef8593d8 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,6 +1,8 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Union + +__all__ = ["error", "open"] _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -13,14 +15,14 @@ class _Database(MutableMapping[_KeyType, bytes]): 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 __setitem__(self, key: _KeyType, val: _ValueType) -> None: ... def __delitem__(self, key: _KeyType) -> None: ... def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> 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 702f62d11b75..b0e657d6ae4b 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -1,39 +1,39 @@ +import sys from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType = Union[str, bytes] + _ValueType = Union[str, bytes] -open_flags: str + open_flags: str -class error(OSError): ... - -# Actual typename gdbm, not exposed by the implementation -class _gdbm: - def firstkey(self) -> bytes | None: ... - def nextkey(self, key: _KeyType) -> bytes | None: ... - 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 __contains__(self, key: _KeyType) -> bool: ... - def __len__(self) -> int: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> list[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore[assignment] - __init__: None # type: ignore[assignment] - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... + class error(OSError): ... + # Actual typename gdbm, not exposed by the implementation + class _gdbm: + def firstkey(self) -> bytes | None: ... + def nextkey(self, key: _KeyType) -> bytes | None: ... + 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 __contains__(self, key: _KeyType) -> bool: ... + def __len__(self) -> int: ... + def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @overload + def get(self, k: _KeyType) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index 7b04c5385dbe..336720c79f37 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -1,35 +1,35 @@ +import sys from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload -_T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType = Union[str, bytes] + _ValueType = Union[str, bytes] -class error(OSError): ... + class error(OSError): ... + library: str -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: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... - @overload - def get(self, k: _KeyType) -> bytes | None: ... - @overload - def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> list[bytes]: ... - def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... - # Don't exist at runtime - __new__: None # type: ignore[assignment] - __init__: None # type: ignore[assignment] - -def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... + # 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: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @overload + def get(self, k: _KeyType) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index 07f9ca1bfdf0..dfd0670e474e 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -1,12 +1,14 @@ import numbers import sys +from _typeshed import Self from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, Type, TypeVar, Union, overload +from typing import Any, Container, NamedTuple, Sequence, Union, overload _Decimal = Union[Decimal, int] _DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] _ComparableNum = Union[Decimal, float, numbers.Rational] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) + +__libmpdec_version__: str class DecimalTuple(NamedTuple): sign: int @@ -50,9 +52,9 @@ def getcontext() -> Context: ... def localcontext(ctx: Context | None = ...) -> _ContextManager: ... class Decimal: - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod - def from_float(cls, __f: float) -> Decimal: ... + def from_float(cls: type[Self], __f: float) -> Self: ... def __bool__(self) -> bool: ... def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __hash__(self) -> int: ... @@ -80,7 +82,6 @@ class Decimal: def __rmul__(self, __other: _Decimal) -> Decimal: ... def __rsub__(self, __other: _Decimal) -> Decimal: ... def __rtruediv__(self, __other: _Decimal) -> Decimal: ... - def __str__(self) -> str: ... def __sub__(self, __other: _Decimal) -> Decimal: ... def __truediv__(self, __other: _Decimal) -> Decimal: ... def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... @@ -146,9 +147,9 @@ class Decimal: def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> tuple[Type[Decimal], tuple[str]]: ... - def __copy__(self) -> Decimal: ... - def __deepcopy__(self, __memo: Any) -> Decimal: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[str]]: ... + def __copy__(self: Self) -> Self: ... + def __deepcopy__(self: Self, __memo: Any) -> Self: ... def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... class _ContextManager: @@ -156,9 +157,9 @@ class _ContextManager: saved_context: Context def __init__(self, new_context: Context) -> None: ... def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... -_TrapType = Type[DecimalException] +_TrapType = type[DecimalException] class Context: prec: int @@ -184,7 +185,7 @@ class Context: # __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 __reduce__(self: Self) -> tuple[type[Self], tuple[Any, ...]]: ... def clear_flags(self) -> None: ... def clear_traps(self) -> None: ... def copy(self) -> Context: ... diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index d259e77dfe8c..a572430155e9 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,11 +1,25 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = [ + "get_close_matches", + "ndiff", + "restore", + "SequenceMatcher", + "Differ", + "IS_CHARACTER_JUNK", + "IS_LINE_JUNK", + "context_diff", + "unified_diff", + "diff_bytes", + "HtmlDiff", + "Match", +] + _T = TypeVar("_T") -_JunkCallback = Union[Callable[[str], bool], Callable[[str], bool]] class Match(NamedTuple): a: int @@ -23,6 +37,7 @@ class SequenceMatcher(Generic[_T]): def find_longest_match(self, alo: int = ..., ahi: int | None = ..., blo: int = ..., bhi: int | None = ...) -> 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]]]: ... @@ -41,7 +56,7 @@ def get_close_matches( ) -> list[Sequence[_T]]: ... class Differ: - def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... + def __init__(self, linejunk: Callable[[str], bool] | None = ..., charjunk: Callable[[str], bool] | None = ...) -> None: ... def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ... def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: ... # pat is undocumented @@ -67,7 +82,7 @@ def context_diff( lineterm: str = ..., ) -> Iterator[str]: ... def ndiff( - a: Sequence[str], b: Sequence[str], linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ... + a: Sequence[str], b: Sequence[str], linejunk: Callable[[str], bool] | None = ..., charjunk: Callable[[str], bool] | None = ... ) -> Iterator[str]: ... class HtmlDiff: @@ -75,8 +90,8 @@ class HtmlDiff: self, tabsize: int = ..., wrapcolumn: int | None = ..., - linejunk: _JunkCallback | None = ..., - charjunk: _JunkCallback | None = ..., + linejunk: Callable[[str], bool] | None = ..., + charjunk: Callable[[str], bool] | None = ..., ) -> None: ... def make_file( self, diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index ac0632d25c9c..dcb82cb7aefc 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -1,23 +1,37 @@ import sys import types -from opcode import ( - EXTENDED_ARG as EXTENDED_ARG, - HAVE_ARGUMENT as HAVE_ARGUMENT, - cmp_op as cmp_op, - hascompare as hascompare, - hasconst as hasconst, - hasfree as hasfree, - hasjabs as hasjabs, - hasjrel as hasjrel, - haslocal as haslocal, - hasname as hasname, - hasnargs as hasnargs, - opmap as opmap, - opname as opname, - stack_effect as stack_effect, -) +from _typeshed import Self +from opcode import * # `dis` re-exports it as a part of public API from typing import IO, Any, Callable, Iterator, NamedTuple, Union +__all__ = [ + "code_info", + "dis", + "disassemble", + "distb", + "disco", + "findlinestarts", + "findlabels", + "show_code", + "get_instructions", + "Instruction", + "Bytecode", + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "hasnargs", + "stack_effect", +] + # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) _HaveCodeType = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] @@ -38,11 +52,10 @@ class Bytecode: first_line: int def __init__(self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ...) -> 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: ... + def from_traceback(cls: type[Self], tb: types.TracebackType) -> Self: ... COMPILER_FLAG_NAMES: dict[int, str] diff --git a/mypy/typeshed/stdlib/distutils/cmd.pyi b/mypy/typeshed/stdlib/distutils/cmd.pyi index 875e851bed39..96a048c93f41 100644 --- a/mypy/typeshed/stdlib/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/distutils/cmd.pyi @@ -57,7 +57,7 @@ class Command: ) -> str: ... def make_file( self, - infiles: str | list[str] | tuple[str], + infiles: str | list[str] | tuple[str, ...], outfile: str, func: Callable[..., Any], args: list[Any], diff --git a/mypy/typeshed/stdlib/distutils/command/__init__.pyi b/mypy/typeshed/stdlib/distutils/command/__init__.pyi index a4b9b1c2bd1b..e69de29bb2d1 100644 --- a/mypy/typeshed/stdlib/distutils/command/__init__.pyi +++ b/mypy/typeshed/stdlib/distutils/command/__init__.pyi @@ -1,40 +0,0 @@ -from . import ( - bdist_dumb as bdist_dumb, - bdist_rpm as bdist_rpm, - build as build, - build_clib as build_clib, - build_ext as build_ext, - build_py as build_py, - build_scripts as build_scripts, - check as check, - clean as clean, - install as install, - install_data as install_data, - install_headers as install_headers, - install_lib as install_lib, - register as register, - sdist as sdist, - upload as upload, -) - -__all__ = [ - "build", - "build_py", - "build_ext", - "build_clib", - "build_scripts", - "clean", - "install", - "install_lib", - "install_headers", - "install_scripts", - "install_data", - "sdist", - "register", - "bdist", - "bdist_dumb", - "bdist_rpm", - "bdist_wininst", - "check", - "upload", -] diff --git a/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi index e4f64ff6a59e..66202e841d3c 100644 --- a/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi +++ b/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi @@ -5,6 +5,7 @@ from ..cmd import Command if sys.platform == "win32": from msilib import Dialog + class PyDialog(Dialog): def __init__(self, *args, **kw) -> None: ... def title(self, title) -> None: ... @@ -12,6 +13,7 @@ if sys.platform == "win32": def cancel(self, title, next, name: str = ..., active: int = ...): ... def next(self, title, next, name: str = ..., active: int = ...): ... def xbutton(self, name, title, next, xpos): ... + class bdist_msi(Command): description: str user_options: Any diff --git a/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi index e69de29bb2d1..1091fb278493 100644 --- a/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi +++ b/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi @@ -0,0 +1,16 @@ +from _typeshed import StrOrBytesPath +from distutils.cmd import Command +from typing import Any, ClassVar + +class bdist_wininst(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[Any, ...]]] + boolean_options: ClassVar[list[str]] + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_inidata(self) -> str: ... + def create_exe(self, arcname: StrOrBytesPath, fullname: str, bitmap: StrOrBytesPath | None = ...) -> None: ... + def get_installer_filename(self, fullname: str) -> str: ... + def get_exe_bytes(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi index fc4cd81c4752..6564c9a86ded 100644 --- a/mypy/typeshed/stdlib/distutils/core.pyi +++ b/mypy/typeshed/stdlib/distutils/core.pyi @@ -1,7 +1,7 @@ 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, Mapping, Type +from typing import Any, Mapping def setup( *, @@ -20,14 +20,14 @@ def setup( scripts: list[str] = ..., ext_modules: list[Extension] = ..., classifiers: list[str] = ..., - distclass: Type[Distribution] = ..., + distclass: type[Distribution] = ..., script_name: str = ..., script_args: list[str] = ..., options: Mapping[str, Any] = ..., license: str = ..., keywords: list[str] | str = ..., platforms: list[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., + cmdclass: Mapping[str, type[Command]] = ..., data_files: list[tuple[str, list[str]]] = ..., package_dir: Mapping[str, str] = ..., obsoletes: list[str] = ..., diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index 5bb04b049995..c5b3afe7cc3b 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -1,6 +1,6 @@ from _typeshed import StrOrBytesPath, SupportsWrite from distutils.cmd import Command -from typing import IO, Any, Iterable, Mapping, Type +from typing import IO, Any, Iterable, Mapping class DistributionMetadata: def __init__(self, path: int | StrOrBytesPath | None = ...) -> None: ... @@ -50,7 +50,7 @@ class DistributionMetadata: def set_obsoletes(self, value: Iterable[str]) -> None: ... class Distribution: - cmdclass: dict[str, Type[Command]] + cmdclass: dict[str, type[Command]] metadata: DistributionMetadata def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... diff --git a/mypy/typeshed/stdlib/distutils/extension.pyi b/mypy/typeshed/stdlib/distutils/extension.pyi index 655ea1e9e347..5639f44a6d03 100644 --- a/mypy/typeshed/stdlib/distutils/extension.pyi +++ b/mypy/typeshed/stdlib/distutils/extension.pyi @@ -1,4 +1,20 @@ class Extension: + name: str + sources: list[str] + include_dirs: list[str] + define_macros: list[tuple[str, str | None]] + 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: list[str] + depends: list[str] + language: str | None + optional: bool | None def __init__( self, name: str, @@ -13,7 +29,7 @@ class Extension: extra_compile_args: list[str] | None = ..., extra_link_args: list[str] | None = ..., export_symbols: list[str] | None = ..., - swig_opts: str | None = ..., # undocumented + swig_opts: list[str] | None = ..., depends: list[str] | None = ..., language: str | None = ..., optional: bool | None = ..., diff --git a/mypy/typeshed/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi index 03ee0185cac4..22d982e6949d 100644 --- a/mypy/typeshed/stdlib/distutils/util.pyi +++ b/mypy/typeshed/stdlib/distutils/util.pyi @@ -1,6 +1,7 @@ from _typeshed import StrPath from collections.abc import Callable, Container, Iterable, Mapping from typing import Any +from typing_extensions import Literal def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... @@ -11,7 +12,7 @@ def split_quoted(s: str) -> list[str]: ... def execute( func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... ) -> None: ... -def strtobool(val: str) -> bool: ... +def strtobool(val: str) -> Literal[0, 1]: ... def byte_compile( py_files: list[str], optimize: int = ..., diff --git a/mypy/typeshed/stdlib/distutils/version.pyi b/mypy/typeshed/stdlib/distutils/version.pyi index 1908cdeda97a..210aa5cf718b 100644 --- a/mypy/typeshed/stdlib/distutils/version.pyi +++ b/mypy/typeshed/stdlib/distutils/version.pyi @@ -1,38 +1,36 @@ +from _typeshed import Self from abc import abstractmethod -from typing import Pattern, TypeVar - -_T = TypeVar("_T", bound=Version) +from typing import Pattern class Version: - def __repr__(self) -> str: ... def __eq__(self, other: object) -> bool: ... - def __lt__(self: _T, other: _T | str) -> bool: ... - def __le__(self: _T, other: _T | str) -> bool: ... - def __gt__(self: _T, other: _T | str) -> bool: ... - def __ge__(self: _T, other: _T | str) -> bool: ... + def __lt__(self: Self, other: Self | str) -> bool: ... + def __le__(self: Self, other: Self | str) -> bool: ... + def __gt__(self: Self, other: Self | str) -> bool: ... + def __ge__(self: Self, other: Self | str) -> bool: ... @abstractmethod def __init__(self, vstring: str | None = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: str) -> _T: ... + def parse(self: Self, vstring: str) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self: Self, other: Self | str) -> bool: ... class StrictVersion(Version): version_re: Pattern[str] version: tuple[int, int, int] prerelease: tuple[str, int] | None def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def parse(self: Self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 + def _cmp(self: Self, other: Self | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: str version: tuple[str | int, ...] def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def parse(self: Self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 + def _cmp(self: Self, other: Self | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 611137740ac4..651e1b298aaf 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -1,6 +1,42 @@ import types import unittest -from typing import Any, Callable, NamedTuple, Type +from typing import Any, Callable, NamedTuple + +__all__ = [ + "register_optionflag", + "DONT_ACCEPT_TRUE_FOR_1", + "DONT_ACCEPT_BLANKLINE", + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "SKIP", + "IGNORE_EXCEPTION_DETAIL", + "COMPARISON_FLAGS", + "REPORT_UDIFF", + "REPORT_CDIFF", + "REPORT_NDIFF", + "REPORT_ONLY_FIRST_FAILURE", + "REPORTING_FLAGS", + "FAIL_FAST", + "Example", + "DocTest", + "DocTestParser", + "DocTestFinder", + "DocTestRunner", + "OutputChecker", + "DocTestFailure", + "UnexpectedException", + "DebugRunner", + "testmod", + "testfile", + "run_docstring_examples", + "DocTestSuite", + "DocFileSuite", + "set_unittest_reportflags", + "script_from_examples", + "testsource", + "debug_src", + "debug", +] class TestResults(NamedTuple): failed: int @@ -47,6 +83,7 @@ class Example: options: dict[int, bool] | None = ..., ) -> None: ... def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... class DocTest: examples: list[Example] @@ -66,6 +103,7 @@ class DocTest: ) -> None: ... def __hash__(self) -> int: ... def __lt__(self, other: DocTest) -> bool: ... + def __eq__(self, other: object) -> bool: ... class DocTestParser: def parse(self, string: str, name: str = ...) -> list[str | Example]: ... @@ -86,7 +124,7 @@ class DocTestFinder: ) -> list[DocTest]: ... _Out = Callable[[str], Any] -_ExcInfo = tuple[Type[BaseException], BaseException, types.TracebackType] +_ExcInfo = tuple[type[BaseException], BaseException, types.TracebackType] class DocTestRunner: DIVIDER: str @@ -172,6 +210,7 @@ class DocTestCase(unittest.TestCase): def debug(self) -> None: ... def id(self) -> str: ... def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... def shortDescription(self) -> str: ... class SkipDocTestCase(DocTestCase): diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index ddb9d9e45913..18d5f1b9ac22 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -1,11 +1,10 @@ import sys +from _typeshed import Self from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, Pattern, Type, TypeVar, Union +from typing import Any, Iterable, Iterator, Pattern, Union from typing_extensions import Final -_T = TypeVar("_T") - WSP: Final[set[str]] CFWS_LEADER: Final[set[str]] SPECIALS: Final[set[str]] @@ -182,10 +181,14 @@ class InvalidMailbox(TokenList): token_type: str @property def display_name(self) -> None: ... - local_part: None - domain: None - route: None - addr_spec: None + @property + def local_part(self) -> None: ... + @property + def domain(self) -> None: ... + @property + def route(self) -> None: ... + @property + def addr_spec(self) -> None: ... class Domain(TokenList): token_type: str @@ -313,8 +316,10 @@ if sys.version_info >= (3, 8): token_type: str as_ew_allowed: bool def fold(self, policy: Policy) -> str: ... + class MessageID(MsgID): token_type: str + class InvalidMessageID(MessageID): token_type: str @@ -327,7 +332,7 @@ class Terminal(str): syntactic_break: bool token_type: str defects: list[MessageDefect] - def __new__(cls: Type[_T], value: str, token_type: str) -> _T: ... + def __new__(cls: type[Self], value: str, token_type: str) -> Self: ... def pprint(self) -> None: ... @property def all_defects(self) -> list[MessageDefect]: ... diff --git a/mypy/typeshed/stdlib/email/base64mime.pyi b/mypy/typeshed/stdlib/email/base64mime.pyi index a8030a978923..e55658046f55 100644 --- a/mypy/typeshed/stdlib/email/base64mime.pyi +++ b/mypy/typeshed/stdlib/email/base64mime.pyi @@ -1,3 +1,5 @@ +__all__ = ["body_decode", "body_encode", "decode", "decodestring", "header_encode", "header_length"] + def header_length(bytearray: str | bytes) -> int: ... def header_encode(header_bytes: str | bytes, charset: str = ...) -> str: ... def body_encode(s: bytes, maxlinelen: int = ..., eol: str = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index 4bf5d11690eb..fd3de9ceace2 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -1,4 +1,6 @@ -from typing import Any, Iterator +from typing import Iterator + +__all__ = ["Charset", "add_alias", "add_charset", "add_codec"] QP: int # undocumented BASE64: int # undocumented @@ -17,9 +19,8 @@ class Charset: 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 __eq__(self, other: object) -> bool: ... + def __ne__(self, __other: object) -> bool: ... def add_charset( charset: str, header_enc: int | None = ..., body_enc: int | None = ..., output_charset: str | None = ... diff --git a/mypy/typeshed/stdlib/email/encoders.pyi b/mypy/typeshed/stdlib/email/encoders.pyi index e05225e895c4..55223bdc0762 100644 --- a/mypy/typeshed/stdlib/email/encoders.pyi +++ b/mypy/typeshed/stdlib/email/encoders.pyi @@ -1,5 +1,7 @@ from email.message import Message +__all__ = ["encode_7or8bit", "encode_base64", "encode_noop", "encode_quopri"] + def encode_base64(msg: Message) -> None: ... def encode_quopri(msg: Message) -> None: ... def encode_7or8bit(msg: Message) -> None: ... diff --git a/mypy/typeshed/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi index ffcf4f0a7c6e..fd27a7242649 100644 --- a/mypy/typeshed/stdlib/email/feedparser.pyi +++ b/mypy/typeshed/stdlib/email/feedparser.pyi @@ -2,6 +2,8 @@ from email.message import Message from email.policy import Policy from typing import Callable, Generic, TypeVar, overload +__all__ = ["FeedParser", "BytesFeedParser"] + _M = TypeVar("_M", bound=Message) class FeedParser(Generic[_M]): diff --git a/mypy/typeshed/stdlib/email/generator.pyi b/mypy/typeshed/stdlib/email/generator.pyi index 1a810558a0da..5a6b6374dd4b 100644 --- a/mypy/typeshed/stdlib/email/generator.pyi +++ b/mypy/typeshed/stdlib/email/generator.pyi @@ -1,27 +1,39 @@ +from _typeshed import SupportsWrite from email.message import Message from email.policy import Policy -from typing import BinaryIO, TextIO + +__all__ = ["Generator", "DecodedGenerator", "BytesGenerator"] class Generator: - def clone(self, fp: TextIO) -> Generator: ... + def clone(self, fp: SupportsWrite[str]) -> Generator: ... def write(self, s: str) -> None: ... def __init__( - self, outfp: TextIO, mangle_from_: bool | None = ..., maxheaderlen: int | None = ..., *, policy: Policy | None = ... + self, + outfp: SupportsWrite[str], + mangle_from_: bool | None = ..., + maxheaderlen: int | None = ..., + *, + policy: Policy | None = ..., ) -> None: ... def flatten(self, msg: Message, unixfrom: bool = ..., linesep: str | None = ...) -> None: ... class BytesGenerator: - def clone(self, fp: BinaryIO) -> BytesGenerator: ... + def clone(self, fp: SupportsWrite[bytes]) -> BytesGenerator: ... def write(self, s: str) -> None: ... def __init__( - self, outfp: BinaryIO, mangle_from_: bool | None = ..., maxheaderlen: int | None = ..., *, policy: Policy | None = ... + self, + outfp: SupportsWrite[bytes], + mangle_from_: bool | None = ..., + maxheaderlen: int | None = ..., + *, + policy: Policy | None = ..., ) -> None: ... def flatten(self, msg: Message, unixfrom: bool = ..., linesep: str | None = ...) -> None: ... class DecodedGenerator(Generator): def __init__( self, - outfp: TextIO, + outfp: SupportsWrite[str], mangle_from_: bool | None = ..., maxheaderlen: int | None = ..., fmt: str | None = ..., diff --git a/mypy/typeshed/stdlib/email/header.pyi b/mypy/typeshed/stdlib/email/header.pyi index 4bebd50c45e4..bd851bcf8679 100644 --- a/mypy/typeshed/stdlib/email/header.pyi +++ b/mypy/typeshed/stdlib/email/header.pyi @@ -1,5 +1,6 @@ from email.charset import Charset -from typing import Any + +__all__ = ["Header", "decode_header", "make_header"] class Header: def __init__( @@ -13,9 +14,8 @@ class Header: ) -> None: ... def append(self, s: bytes | str, charset: Charset | str | None = ..., errors: str = ...) -> None: ... def encode(self, splitchars: str = ..., maxlinelen: int | None = ..., linesep: str = ...) -> str: ... - def __str__(self) -> str: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, __other: object) -> bool: ... def decode_header(header: Header | str) -> list[tuple[bytes, str | None]]: ... def make_header( diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index abf10ed4a4fd..7f1d86b985a1 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -1,5 +1,6 @@ import sys import types +from _typeshed import Self from collections.abc import Iterable, Mapping from datetime import datetime as _datetime from email._header_value_parser import ( @@ -13,7 +14,7 @@ from email._header_value_parser import ( ) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, ClassVar, Type +from typing import Any, ClassVar from typing_extensions import Literal class BaseHeader(str): @@ -23,7 +24,7 @@ class BaseHeader(str): def name(self) -> str: ... @property def defects(self) -> tuple[MessageDefect, ...]: ... - def __new__(cls, name: str, value: Any) -> BaseHeader: ... + def __new__(cls: type[Self], name: str, value: Any) -> Self: ... def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... def fold(self, *, policy: Policy) -> str: ... @@ -132,6 +133,7 @@ class ContentTransferEncodingHeader: if sys.version_info >= (3, 8): from email._header_value_parser import MessageID + class MessageIDHeader: max_count: ClassVar[Literal[1]] @classmethod @@ -141,10 +143,10 @@ if sys.version_info >= (3, 8): class HeaderRegistry: def __init__( - self, base_class: Type[BaseHeader] = ..., default_class: Type[BaseHeader] = ..., use_default_map: bool = ... + self, base_class: type[BaseHeader] = ..., default_class: type[BaseHeader] = ..., use_default_map: bool = ... ) -> None: ... - def map_to_type(self, name: str, cls: Type[BaseHeader]) -> None: ... - def __getitem__(self, name: str) -> Type[BaseHeader]: ... + def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ... + def __getitem__(self, name: str) -> type[BaseHeader]: ... def __call__(self, name: str, value: Any) -> BaseHeader: ... class Address: @@ -159,7 +161,7 @@ class Address: def __init__( self, display_name: str = ..., username: str | None = ..., domain: str | None = ..., addr_spec: str | None = ... ) -> None: ... - def __str__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... class Group: @property @@ -167,4 +169,4 @@ class Group: @property def addresses(self) -> tuple[Address, ...]: ... def __init__(self, display_name: str | None = ..., addresses: Iterable[Address] | None = ...) -> None: ... - def __str__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/iterators.pyi b/mypy/typeshed/stdlib/email/iterators.pyi index 9081a3e3ba73..ad5517712d25 100644 --- a/mypy/typeshed/stdlib/email/iterators.pyi +++ b/mypy/typeshed/stdlib/email/iterators.pyi @@ -1,5 +1,12 @@ +from _typeshed import SupportsWrite from email.message import Message from typing import Iterator +__all__ = ["body_line_iterator", "typed_subpart_iterator", "walk"] + def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ... def typed_subpart_iterator(msg: Message, maintype: str = ..., subtype: str | None = ...) -> Iterator[str]: ... +def walk(self: Message) -> Iterator[Message]: ... + +# We include the seemingly private function because it is documented in the stdlib documentation. +def _structure(msg: Message, fp: SupportsWrite[str] | None = ..., level: int = ..., include_default: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 7d5eb4500d8f..d6857328a4ee 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -2,7 +2,11 @@ from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Generator, Iterator, Optional, Sequence, TypeVar, Union + +# using a type alias ("_HeaderType = Any") breaks mypy, who knows why +from typing import Any, Any as _HeaderType, Generator, Iterator, Optional, Sequence, TypeVar, Union + +__all__ = ["Message", "EmailMessage"] _T = TypeVar("_T") @@ -10,14 +14,12 @@ _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: policy: Policy # undocumented preamble: str | None epilogue: str | None defects: list[MessageDefect] - def __str__(self) -> str: ... def is_multipart(self) -> bool: ... def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> str | None: ... diff --git a/mypy/typeshed/stdlib/email/mime/application.pyi b/mypy/typeshed/stdlib/email/mime/application.pyi index d176cd613e27..978324c03863 100644 --- a/mypy/typeshed/stdlib/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/email/mime/application.pyi @@ -2,6 +2,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Union +__all__ = ["MIMEApplication"] + _ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEApplication(MIMENonMultipart): diff --git a/mypy/typeshed/stdlib/email/mime/audio.pyi b/mypy/typeshed/stdlib/email/mime/audio.pyi index 38657c932e2f..aa7b9ceb2dea 100644 --- a/mypy/typeshed/stdlib/email/mime/audio.pyi +++ b/mypy/typeshed/stdlib/email/mime/audio.pyi @@ -2,6 +2,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Union +__all__ = ["MIMEAudio"] + _ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEAudio(MIMENonMultipart): diff --git a/mypy/typeshed/stdlib/email/mime/base.pyi b/mypy/typeshed/stdlib/email/mime/base.pyi index cb655607b032..faa561fcb3a1 100644 --- a/mypy/typeshed/stdlib/email/mime/base.pyi +++ b/mypy/typeshed/stdlib/email/mime/base.pyi @@ -2,6 +2,8 @@ import email.message from email.policy import Policy from typing import Optional, Union +__all__ = ["MIMEBase"] + _ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEBase(email.message.Message): diff --git a/mypy/typeshed/stdlib/email/mime/image.pyi b/mypy/typeshed/stdlib/email/mime/image.pyi index 0325d9e594da..4e767e6aa6d8 100644 --- a/mypy/typeshed/stdlib/email/mime/image.pyi +++ b/mypy/typeshed/stdlib/email/mime/image.pyi @@ -2,6 +2,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy from typing import Callable, Optional, Union +__all__ = ["MIMEImage"] + _ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEImage(MIMENonMultipart): diff --git a/mypy/typeshed/stdlib/email/mime/message.pyi b/mypy/typeshed/stdlib/email/mime/message.pyi index 8878741e8db3..9e7cd04b6e77 100644 --- a/mypy/typeshed/stdlib/email/mime/message.pyi +++ b/mypy/typeshed/stdlib/email/mime/message.pyi @@ -2,5 +2,7 @@ from email.message import Message from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy +__all__ = ["MIMEMessage"] + class MIMEMessage(MIMENonMultipart): def __init__(self, _msg: Message, _subtype: str = ..., *, policy: Policy | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/multipart.pyi b/mypy/typeshed/stdlib/email/mime/multipart.pyi index 6c316c055329..3b70d5875661 100644 --- a/mypy/typeshed/stdlib/email/mime/multipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/multipart.pyi @@ -3,6 +3,8 @@ from email.mime.base import MIMEBase from email.policy import Policy from typing import Optional, Sequence, Union +__all__ = ["MIMEMultipart"] + _ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEMultipart(MIMEBase): diff --git a/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi b/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi index 4addff18861a..5497d89b1072 100644 --- a/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/nonmultipart.pyi @@ -1,3 +1,5 @@ from email.mime.base import MIMEBase +__all__ = ["MIMENonMultipart"] + class MIMENonMultipart(MIMEBase): ... diff --git a/mypy/typeshed/stdlib/email/mime/text.pyi b/mypy/typeshed/stdlib/email/mime/text.pyi index afcafa66ee60..9672c3b717b2 100644 --- a/mypy/typeshed/stdlib/email/mime/text.pyi +++ b/mypy/typeshed/stdlib/email/mime/text.pyi @@ -1,5 +1,7 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy +__all__ = ["MIMEText"] + class MIMEText(MIMENonMultipart): def __init__(self, _text: str, _subtype: str = ..., _charset: str | None = ..., *, policy: Policy | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index 574c927eeaf5..bbc5d0124b3a 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,10 +1,14 @@ import email.feedparser from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO +from typing import BinaryIO, Callable, TextIO, TypeVar -FeedParser = email.feedparser.FeedParser -BytesFeedParser = email.feedparser.BytesFeedParser +__all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] + +_M = TypeVar("_M", bound=Message) + +FeedParser = email.feedparser.FeedParser[_M] +BytesFeedParser = email.feedparser.BytesFeedParser[_M] class Parser: def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 15991c7e084b..d4ebb1fd5e37 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -5,6 +5,8 @@ from email.header import Header from email.message import Message from typing import Any, Callable +__all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] + class Policy(metaclass=ABCMeta): max_line_length: int | None linesep: str diff --git a/mypy/typeshed/stdlib/email/quoprimime.pyi b/mypy/typeshed/stdlib/email/quoprimime.pyi index 41c4bd8cca9e..c5d324d17e13 100644 --- a/mypy/typeshed/stdlib/email/quoprimime.pyi +++ b/mypy/typeshed/stdlib/email/quoprimime.pyi @@ -1,3 +1,16 @@ +__all__ = [ + "body_decode", + "body_encode", + "body_length", + "decode", + "decodestring", + "header_decode", + "header_encode", + "header_length", + "quote", + "unquote", +] + def header_check(octet: int) -> bool: ... def body_check(octet: int) -> bool: ... def header_length(bytearray: bytes) -> int: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 728a5a53f230..2b7f1bab3ce0 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -3,6 +3,24 @@ import sys from email.charset import Charset from typing import Optional, Union, overload +__all__ = [ + "collapse_rfc2231_value", + "decode_params", + "decode_rfc2231", + "encode_rfc2231", + "formataddr", + "formatdate", + "format_datetime", + "getaddresses", + "make_msgid", + "mktime_tz", + "parseaddr", + "parsedate", + "parsedate_tz", + "parsedate_to_datetime", + "unquote", +] + _ParamType = Union[str, tuple[Optional[str], Optional[str], str]] _PDTZ = tuple[int, int, int, int, int, int, int, int, int, Optional[int]] diff --git a/mypy/typeshed/stdlib/ensurepip/__init__.pyi b/mypy/typeshed/stdlib/ensurepip/__init__.pyi index 749fedc04424..e2686b8d5437 100644 --- a/mypy/typeshed/stdlib/ensurepip/__init__.pyi +++ b/mypy/typeshed/stdlib/ensurepip/__init__.pyi @@ -1,3 +1,5 @@ +__all__ = ["version", "bootstrap"] + def version() -> str: ... def bootstrap( *, diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index a80a022ad6f5..077a2f423e49 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -1,12 +1,45 @@ import sys import types +from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping -from typing import Any, Type, TypeVar, Union, overload +from typing import Any, TypeVar, Union, overload +from typing_extensions import Literal -_T = TypeVar("_T") -_S = TypeVar("_S", bound=Type[Enum]) +if sys.version_info >= (3, 11): + __all__ = [ + "EnumType", + "EnumMeta", + "Enum", + "IntEnum", + "StrEnum", + "Flag", + "IntFlag", + "ReprEnum", + "auto", + "unique", + "property", + "verify", + "FlagBoundary", + "STRICT", + "CONFORM", + "EJECT", + "KEEP", + "global_flag_repr", + "global_enum_repr", + "global_str", + "global_enum", + "EnumCheck", + "CONTINUOUS", + "NAMED_FLAGS", + "UNIQUE", + ] +else: + __all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] + +_EnumMemberT = TypeVar("_EnumMemberT") +_EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) # The following all work: # >>> from enum import Enum @@ -23,6 +56,7 @@ _EnumNames = Union[str, Iterable[str], Iterable[Iterable[Union[str, Any]]], Mapp class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... + def __setitem__(self, key: str, value: Any) -> None: ... # Note: EnumMeta actually subclasses type directly, not ABCMeta. # This is a temporary workaround to allow multiple creation of enums with builtins @@ -32,7 +66,7 @@ class _EnumDict(dict[str, Any]): class EnumMeta(ABCMeta): if sys.version_info >= (3, 11): def __new__( - metacls: Type[_T], + metacls: type[Self], # type: ignore cls: str, bases: tuple[type, ...], classdict: _EnumDict, @@ -40,22 +74,31 @@ class EnumMeta(ABCMeta): boundary: FlagBoundary | None = ..., _simple: bool = ..., **kwds: Any, - ) -> _T: ... + ) -> Self: ... elif sys.version_info >= (3, 9): - def __new__(metacls: Type[_T], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> _T: ... # type: ignore + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> Self: ... # type: ignore + else: + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> Self: ... # type: ignore + + if sys.version_info >= (3, 9): + @classmethod + def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] else: - def __new__(metacls: Type[_T], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> _T: ... # type: ignore - def __iter__(self: Type[_T]) -> Iterator[_T]: ... - def __reversed__(self: Type[_T]) -> Iterator[_T]: ... - def __contains__(self: Type[Any], member: object) -> bool: ... - def __getitem__(self: Type[_T], name: str) -> _T: ... + @classmethod + def __prepare__(metacls, cls: str, bases: tuple[type, ...]) -> _EnumDict: ... # type: ignore[override] + + def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + def __contains__(self: type[Any], obj: object) -> bool: ... + def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: ... @_builtins_property - def __members__(self: Type[_T]) -> types.MappingProxyType[str, _T]: ... + def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ... def __len__(self) -> int: ... + def __bool__(self) -> Literal[True]: ... if sys.version_info >= (3, 11): # Simple value lookup @overload # type: ignore[override] - def __call__(cls: Type[_T], value: Any, names: None = ...) -> _T: ... + def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... # Functional Enum API @overload def __call__( @@ -68,10 +111,10 @@ class EnumMeta(ABCMeta): type: type | None = ..., start: int = ..., boundary: FlagBoundary | None = ..., - ) -> Type[Enum]: ... + ) -> type[Enum]: ... else: @overload # type: ignore[override] - def __call__(cls: Type[_T], value: Any, names: None = ...) -> _T: ... + def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... @overload def __call__( cls, @@ -82,7 +125,7 @@ class EnumMeta(ABCMeta): qualname: str | None = ..., type: type | None = ..., start: int = ..., - ) -> Type[Enum]: ... + ) -> type[Enum]: ... _member_names_: list[str] # undocumented _member_map_: dict[str, Enum] # undocumented _value2member_map_: dict[Any, Enum] # undocumented @@ -91,17 +134,19 @@ if sys.version_info >= (3, 11): # In 3.11 `EnumMeta` metaclass is renamed to `EnumType`, but old name also exists. EnumType = EnumMeta + class property(types.DynamicClassAttribute): + def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ... + name: str + clsname: str + _magic_enum_attr = property +else: + _magic_enum_attr = types.DynamicClassAttribute + class Enum(metaclass=EnumMeta): - if sys.version_info >= (3, 11): - @property - def name(self) -> str: ... - @property - def value(self) -> Any: ... - else: - @types.DynamicClassAttribute - def name(self) -> str: ... - @types.DynamicClassAttribute - def value(self) -> Any: ... + @_magic_enum_attr + def name(self) -> str: ... + @_magic_enum_attr + def value(self) -> Any: ... _name_: str _value_: Any if sys.version_info >= (3, 7): @@ -112,76 +157,77 @@ class Enum(metaclass=EnumMeta): 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 __new__(cls: type[Self], value: Any) -> Self: ... 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): +if sys.version_info >= (3, 11): + class ReprEnum(Enum): ... + _IntEnumBase = ReprEnum +else: + _IntEnumBase = Enum + +class IntEnum(int, _IntEnumBase): _value_: int - if sys.version_info >= (3, 11): - @property - def value(self) -> int: ... - else: - @types.DynamicClassAttribute - def value(self) -> int: ... - def __new__(cls: Type[_T], value: int | _T) -> _T: ... + @_magic_enum_attr + def value(self) -> int: ... + def __new__(cls: type[Self], value: int) -> Self: ... -def unique(enumeration: _S) -> _S: ... +def unique(enumeration: _EnumerationT) -> _EnumerationT: ... _auto_null: Any # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() class auto(IntFlag): _value_: Any - if sys.version_info >= (3, 11): - @property - def value(self) -> Any: ... - else: - @types.DynamicClassAttribute - def value(self) -> Any: ... - def __new__(cls: Type[_T]) -> _T: ... + @_magic_enum_attr + def value(self) -> Any: ... + def __new__(cls: type[Self]) -> Self: ... class Flag(Enum): _name_: str | None # type: ignore[assignment] _value_: int - if sys.version_info >= (3, 11): - @property - def name(self) -> str | None: ... # type: ignore[override] - @property - def value(self) -> int: ... - else: - @types.DynamicClassAttribute - def name(self) -> str | None: ... # type: ignore[override] - @types.DynamicClassAttribute - def value(self) -> int: ... - def __contains__(self: _T, other: _T) -> bool: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... + @_magic_enum_attr + def name(self) -> str | None: ... # type: ignore[override] + @_magic_enum_attr + def value(self) -> int: ... + def __contains__(self: Self, other: Self) -> bool: ... 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: ... + def __or__(self: Self, other: Self) -> Self: ... + def __and__(self: Self, other: Self) -> Self: ... + def __xor__(self: Self, other: Self) -> Self: ... + def __invert__(self: Self) -> Self: ... class IntFlag(int, Flag): - def __new__(cls: Type[_T], value: int | _T) -> _T: ... - def __or__(self: _T, other: int | _T) -> _T: ... - def __and__(self: _T, other: int | _T) -> _T: ... - def __xor__(self: _T, other: int | _T) -> _T: ... - def __ror__(self: _T, n: int | _T) -> _T: ... - def __rand__(self: _T, n: int | _T) -> _T: ... - def __rxor__(self: _T, n: int | _T) -> _T: ... + def __new__(cls: type[Self], value: int) -> Self: ... + def __or__(self: Self, other: int) -> Self: ... + def __and__(self: Self, other: int) -> Self: ... + def __xor__(self: Self, other: int) -> Self: ... + def __ror__(self: Self, other: int) -> Self: ... + def __rand__(self: Self, other: int) -> Self: ... + def __rxor__(self: Self, other: int) -> Self: ... if sys.version_info >= (3, 11): - class StrEnum(str, Enum): - def __new__(cls: Type[_T], value: str | _T) -> _T: ... + class StrEnum(str, ReprEnum): + def __new__(cls: type[Self], value: str) -> Self: ... _value_: str - @property + @_magic_enum_attr def value(self) -> str: ... + + class EnumCheck(StrEnum): + CONTINUOUS: str + NAMED_FLAGS: str + UNIQUE: str + CONTINUOUS = EnumCheck.CONTINUOUS + NAMED_FLAGS = EnumCheck.NAMED_FLAGS + UNIQUE = EnumCheck.UNIQUE + + class verify: + def __init__(self, *checks: EnumCheck) -> None: ... + def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ... + class FlagBoundary(StrEnum): STRICT: str CONFORM: str @@ -191,10 +237,8 @@ if sys.version_info >= (3, 11): CONFORM = FlagBoundary.CONFORM EJECT = FlagBoundary.EJECT KEEP = FlagBoundary.KEEP - class property(types.DynamicClassAttribute): - def __set_name__(self, ownerclass: Type[Enum], name: str) -> None: ... - name: str - clsname: str - def global_enum(cls: _S) -> _S: ... + + def global_str(self: Enum) -> str: ... + def global_enum(cls: _EnumerationT, update_str: bool = ...) -> _EnumerationT: ... def global_enum_repr(self: Enum) -> str: ... def global_flag_repr(self: Flag) -> str: ... diff --git a/mypy/typeshed/stdlib/errno.pyi b/mypy/typeshed/stdlib/errno.pyi index b053604fc33a..5180b5940eae 100644 --- a/mypy/typeshed/stdlib/errno.pyi +++ b/mypy/typeshed/stdlib/errno.pyi @@ -36,6 +36,7 @@ EMLINK: int EPIPE: int EDOM: int ERANGE: int +EDEADLK: int EDEADLCK: int ENAMETOOLONG: int ENOLCK: int diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 47766357c83f..69863bf580fa 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -6,80 +6,100 @@ from typing_extensions import Literal if sys.platform != "win32": 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 - 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 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 + if sys.platform == "darwin": + F_FULLFSYNC: int + F_NOCACHE: int + if sys.version_info >= (3, 9): + F_GETPATH: int + if sys.platform == "linux": + F_SETLKW64: int + F_SETSIG: int + F_SHLCK: int + F_SETLK64: int + F_SETLEASE: int + F_GETSIG: int + F_NOTIFY: int + F_EXLCK: int + F_GETLEASE: int + F_GETLK64: int + if sys.version_info >= (3, 8): + F_ADD_SEALS: int + F_GET_SEALS: int + F_SEAL_GROW: int + F_SEAL_SEAL: int + F_SEAL_SHRINK: int + F_SEAL_WRITE: int + if sys.version_info >= (3, 9): + F_OFD_GETLK: int + F_OFD_SETLK: int + F_OFD_SETLKW: int + if sys.version_info >= (3, 10): + F_GETPIPE_SZ: int + F_SETPIPE_SZ: int + + DN_ACCESS: int + DN_ATTRIB: int + DN_CREATE: int + DN_DELETE: int + DN_MODIFY: int + DN_MULTISHOT: int + DN_RENAME: 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 + if sys.platform == "linux": + LOCK_MAND: int + LOCK_READ: int + LOCK_RW: int + LOCK_WRITE: int + + # These are highly problematic, they might be present or not, depends on the specific OS. + if sys.platform == "linux": + 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 @overload def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... @overload diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 1c3d0a142a33..7c606af40791 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -2,15 +2,22 @@ import sys from _typeshed import StrOrBytesPath from os import PathLike from typing import Any, AnyStr, Callable, Generic, Iterable, Sequence +from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] + DEFAULT_IGNORES: list[str] +BUFSIZE: Literal[8192] def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: int | bool = ...) -> bool: ... def cmpfiles( - a: AnyStr | PathLike[AnyStr], b: AnyStr | PathLike[AnyStr], common: Iterable[AnyStr], shallow: int | bool = ... + a: AnyStr | PathLike[AnyStr], + b: AnyStr | PathLike[AnyStr], + common: Iterable[AnyStr | PathLike[AnyStr]], + shallow: int | bool = ..., ) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... class dircmp(Generic[AnyStr]): diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 576822059560..787f75b8950a 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -2,6 +2,21 @@ import sys from _typeshed import Self, StrOrBytesPath from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator +__all__ = [ + "input", + "close", + "nextfile", + "filename", + "lineno", + "filelineno", + "fileno", + "isfirstline", + "isstdin", + "FileInput", + "hook_compressed", + "hook_encoded", +] + if sys.version_info >= (3, 9): from types import GenericAlias @@ -46,7 +61,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Iterable[AnyStr], Generic[AnyStr]): +class FileInput(Iterator[AnyStr], Generic[AnyStr]): if sys.version_info >= (3, 10): def __init__( self, @@ -79,14 +94,16 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): mode: str = ..., openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., ) -> None: ... + def __del__(self) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> AnyStr: ... if sys.version_info < (3, 11): def __getitem__(self, i: int) -> AnyStr: ... + def nextfile(self) -> None: ... def readline(self) -> AnyStr: ... def filename(self) -> str: ... diff --git a/mypy/typeshed/stdlib/fnmatch.pyi b/mypy/typeshed/stdlib/fnmatch.pyi index 1cbcf00729ed..8351fce59ebb 100644 --- a/mypy/typeshed/stdlib/fnmatch.pyi +++ b/mypy/typeshed/stdlib/fnmatch.pyi @@ -1,5 +1,7 @@ from typing import AnyStr, Iterable +__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"] + def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ... def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... def filter(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 8de5ae20971c..ecbfb07e1dfd 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -1,13 +1,16 @@ import sys +from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Type, TypeVar, Union, overload +from typing import Any, Union, overload from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") -if sys.version_info < (3, 9): +if sys.version_info >= (3, 9): + __all__ = ["Fraction"] +else: + __all__ = ["Fraction", "gcd"] @overload def gcd(a: int, b: int) -> int: ... @overload @@ -20,103 +23,104 @@ if sys.version_info < (3, 9): class Fraction(Rational): @overload def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + cls: type[Self], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... + ) -> Self: ... @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls: type[Self], __value: float | Decimal | str, *, _normalize: bool = ...) -> Self: ... @classmethod - def from_float(cls, f: float) -> Fraction: ... + def from_float(cls: type[Self], f: float) -> Self: ... @classmethod - def from_decimal(cls, dec: Decimal) -> Fraction: ... + def from_decimal(cls: type[Self], dec: Decimal) -> Self: ... 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: ... @overload - def __add__(self, other: int | Fraction) -> Fraction: ... + def __add__(self, b: int | Fraction) -> Fraction: ... @overload - def __add__(self, other: float) -> float: ... + def __add__(self, b: float) -> float: ... @overload - def __add__(self, other: complex) -> complex: ... + def __add__(self, b: complex) -> complex: ... @overload - def __radd__(self, other: int | Fraction) -> Fraction: ... + def __radd__(self, a: int | Fraction) -> Fraction: ... @overload - def __radd__(self, other: float) -> float: ... + def __radd__(self, a: float) -> float: ... @overload - def __radd__(self, other: complex) -> complex: ... + def __radd__(self, a: complex) -> complex: ... @overload - def __sub__(self, other: int | Fraction) -> Fraction: ... + def __sub__(self, b: int | Fraction) -> Fraction: ... @overload - def __sub__(self, other: float) -> float: ... + def __sub__(self, b: float) -> float: ... @overload - def __sub__(self, other: complex) -> complex: ... + def __sub__(self, b: complex) -> complex: ... @overload - def __rsub__(self, other: int | Fraction) -> Fraction: ... + def __rsub__(self, a: int | Fraction) -> Fraction: ... @overload - def __rsub__(self, other: float) -> float: ... + def __rsub__(self, a: float) -> float: ... @overload - def __rsub__(self, other: complex) -> complex: ... + def __rsub__(self, a: complex) -> complex: ... @overload - def __mul__(self, other: int | Fraction) -> Fraction: ... + def __mul__(self, b: int | Fraction) -> Fraction: ... @overload - def __mul__(self, other: float) -> float: ... + def __mul__(self, b: float) -> float: ... @overload - def __mul__(self, other: complex) -> complex: ... + def __mul__(self, b: complex) -> complex: ... @overload - def __rmul__(self, other: int | Fraction) -> Fraction: ... + def __rmul__(self, a: int | Fraction) -> Fraction: ... @overload - def __rmul__(self, other: float) -> float: ... + def __rmul__(self, a: float) -> float: ... @overload - def __rmul__(self, other: complex) -> complex: ... + def __rmul__(self, a: complex) -> complex: ... @overload - def __truediv__(self, other: int | Fraction) -> Fraction: ... + def __truediv__(self, b: int | Fraction) -> Fraction: ... @overload - def __truediv__(self, other: float) -> float: ... + def __truediv__(self, b: float) -> float: ... @overload - def __truediv__(self, other: complex) -> complex: ... + def __truediv__(self, b: complex) -> complex: ... @overload - def __rtruediv__(self, other: int | Fraction) -> Fraction: ... + def __rtruediv__(self, a: int | Fraction) -> Fraction: ... @overload - def __rtruediv__(self, other: float) -> float: ... + def __rtruediv__(self, a: float) -> float: ... @overload - def __rtruediv__(self, other: complex) -> complex: ... + def __rtruediv__(self, a: complex) -> complex: ... @overload - def __floordiv__(self, other: int | Fraction) -> int: ... + def __floordiv__(self, b: int | Fraction) -> int: ... @overload - def __floordiv__(self, other: float) -> float: ... + def __floordiv__(self, b: float) -> float: ... @overload - def __rfloordiv__(self, other: int | Fraction) -> int: ... + def __rfloordiv__(self, a: int | Fraction) -> int: ... @overload - def __rfloordiv__(self, other: float) -> float: ... + def __rfloordiv__(self, a: float) -> float: ... @overload - def __mod__(self, other: int | Fraction) -> Fraction: ... + def __mod__(self, b: int | Fraction) -> Fraction: ... @overload - def __mod__(self, other: float) -> float: ... + def __mod__(self, b: float) -> float: ... @overload - def __rmod__(self, other: int | Fraction) -> Fraction: ... + def __rmod__(self, a: int | Fraction) -> Fraction: ... @overload - def __rmod__(self, other: float) -> float: ... + def __rmod__(self, a: float) -> float: ... @overload - def __divmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... + def __divmod__(self, b: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __divmod__(self, other: float) -> tuple[float, Fraction]: ... + def __divmod__(self, b: float) -> tuple[float, Fraction]: ... @overload - def __rdivmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... + def __rdivmod__(self, a: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __rdivmod__(self, other: float) -> tuple[float, Fraction]: ... + def __rdivmod__(self, a: float) -> tuple[float, Fraction]: ... @overload - def __pow__(self, other: int) -> Fraction: ... + def __pow__(self, b: int) -> Fraction: ... @overload - def __pow__(self, other: float | Fraction) -> float: ... + def __pow__(self, b: float | Fraction) -> float: ... @overload - def __pow__(self, other: complex) -> complex: ... + def __pow__(self, b: complex) -> complex: ... @overload - def __rpow__(self, other: int | float | Fraction) -> float: ... + def __rpow__(self, a: int | float | Fraction) -> float: ... @overload - def __rpow__(self, other: complex) -> complex: ... + def __rpow__(self, a: complex) -> complex: ... def __pos__(self) -> Fraction: ... def __neg__(self) -> Fraction: ... def __abs__(self) -> Fraction: ... @@ -128,12 +132,14 @@ class Fraction(Rational): @overload def __round__(self, ndigits: int) -> Fraction: ... def __hash__(self) -> int: ... - def __eq__(self, other: object) -> bool: ... - def __lt__(self, other: _ComparableNum) -> bool: ... - def __gt__(self, other: _ComparableNum) -> bool: ... - def __le__(self, other: _ComparableNum) -> bool: ... - def __ge__(self, other: _ComparableNum) -> bool: ... + def __eq__(self, b: object) -> bool: ... + def __lt__(self, b: _ComparableNum) -> bool: ... + def __gt__(self, b: _ComparableNum) -> bool: ... + def __le__(self, b: _ComparableNum) -> bool: ... + def __ge__(self, b: _ComparableNum) -> bool: ... def __bool__(self) -> bool: ... + def __copy__(self: Self) -> Self: ... + def __deepcopy__(self: Self, memo: Any) -> Self: ... if sys.version_info >= (3, 11): def __int__(self) -> int: ... # Not actually defined within fractions.py, but provides more useful diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index f84199c168e9..4a5dad0dd14f 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -3,14 +3,16 @@ from _typeshed import Self, SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Callable, Iterable, Iterator, TextIO, Type +from typing import Any, Callable, Iterable, Iterator, TextIO from typing_extensions import Literal -MSG_OOB: int -FTP_PORT: int -MAXLINE: int -CRLF: str -B_CRLF: bytes +__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors", "FTP_TLS"] + +MSG_OOB: Literal[1] +FTP_PORT: Literal[21] +MAXLINE: Literal[8192] +CRLF: Literal["\r\n"] +B_CRLF: Literal[b"\r\n"] class Error(Exception): ... class error_reply(Error): ... @@ -18,7 +20,7 @@ class error_temp(Error): ... class error_perm(Error): ... class error_proto(Error): ... -all_errors: tuple[Type[Exception], ...] +all_errors: tuple[type[Exception], ...] class FTP: debugging: int @@ -35,7 +37,7 @@ class FTP: encoding: str def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... source_address: tuple[str, int] | None if sys.version_info >= (3, 9): @@ -60,6 +62,7 @@ class FTP: timeout: float = ..., source_address: tuple[str, int] | None = ..., ) -> None: ... + def connect( self, host: str = ..., port: int = ..., timeout: float = ..., source_address: tuple[str, int] | None = ... ) -> str: ... diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 990fed20d80d..741a53ed82a2 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,12 +1,59 @@ import sys import types -from _typeshed import SupportsAllComparisons, SupportsItems -from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, Type, TypeVar, overload -from typing_extensions import final +from _typeshed import Self, SupportsAllComparisons, SupportsItems +from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, TypeVar, overload +from typing_extensions import Literal, final if sys.version_info >= (3, 9): from types import GenericAlias + __all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cache", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", + "singledispatchmethod", + "cached_property", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", + "singledispatchmethod", + "cached_property", + ] +else: + __all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", + ] + _AnyCallable = Callable[..., Any] _T = TypeVar("_T") @@ -29,6 +76,8 @@ class _lru_cache_wrapper(Generic[_T]): def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... def cache_info(self) -> _CacheInfo: ... def cache_clear(self) -> None: ... + def __copy__(self) -> _lru_cache_wrapper[_T]: ... + def __deepcopy__(self, __memo: Any) -> _lru_cache_wrapper[_T]: ... if sys.version_info >= (3, 8): @overload @@ -39,20 +88,25 @@ if sys.version_info >= (3, 8): else: def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... -WRAPPER_ASSIGNMENTS: Sequence[str] -WRAPPER_UPDATES: Sequence[str] +WRAPPER_ASSIGNMENTS: tuple[ + Literal["__module__"], Literal["__name__"], Literal["__qualname__"], Literal["__doc__"], Literal["__annotations__"], +] +WRAPPER_UPDATES: tuple[Literal["__dict__"]] 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 total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... class partial(Generic[_T]): - func: Callable[..., _T] - args: tuple[Any, ...] - keywords: dict[str, Any] - def __new__(cls: Type[_S], __func: Callable[..., _T], *args: Any, **kwargs: Any) -> _S: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + @property + def func(self) -> Callable[..., _T]: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def keywords(self) -> dict[str, Any]: ... + def __new__(cls: type[Self], __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ... + def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -67,7 +121,11 @@ class partialmethod(Generic[_T]): 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]: ... + if sys.version_info >= (3, 8): + def __get__(self, obj: Any, cls: type[Any] | None = ...) -> Callable[..., _T]: ... + else: + def __get__(self, obj: Any, cls: type[Any] | None) -> Callable[..., _T]: ... + @property def __isabstractmethod__(self) -> bool: ... if sys.version_info >= (3, 9): @@ -79,16 +137,16 @@ class _SingleDispatchCallable(Generic[_T]): # @fun.register(complex) # def _(arg, verbose=False): ... @overload - def register(self, cls: Type[Any], func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: type[Any], func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... # @fun.register # def _(arg: int, verbose=False): @overload def register(self, cls: Callable[..., _T], func: None = ...) -> Callable[..., _T]: ... # fun.register(int, lambda x: x) @overload - def register(self, cls: Type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... def _clear_cache(self) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... @@ -97,22 +155,25 @@ if sys.version_info >= (3, 8): dispatcher: _SingleDispatchCallable[_T] func: Callable[..., _T] def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... @overload - def register(self, cls: Type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... @overload def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... @overload - def register(self, cls: Type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... + def __get__(self, obj: _S, cls: type[_S] | None = ...) -> Callable[..., _T]: ... + class cached_property(Generic[_T]): func: Callable[[Any], _T] attrname: str | None def __init__(self, func: Callable[[Any], _T]) -> None: ... @overload - def __get__(self, instance: None, owner: Type[Any] | None = ...) -> cached_property[_T]: ... + def __get__(self, instance: None, owner: type[Any] | None = ...) -> cached_property[_T]: ... @overload - def __get__(self, instance: object, owner: Type[Any] | None = ...) -> _T: ... - def __set_name__(self, owner: Type[Any], name: str) -> None: ... + def __get__(self, instance: object, owner: type[Any] | None = ...) -> _T: ... + def __set_name__(self, owner: type[Any], name: str) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 39d2776783ef..7c15e0f5b0a2 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,12 +1,16 @@ import sys -from typing import Any - -DEBUG_COLLECTABLE: int -DEBUG_LEAK: int -DEBUG_SAVEALL: int -DEBUG_STATS: int -DEBUG_UNCOLLECTABLE: int -callbacks: list[Any] +from typing import Any, Callable +from typing_extensions import Literal + +DEBUG_COLLECTABLE: Literal[2] +DEBUG_LEAK: Literal[38] +DEBUG_SAVEALL: Literal[32] +DEBUG_STATS: Literal[1] +DEBUG_UNCOLLECTABLE: Literal[4] + +_CallbackType = Callable[[Literal["start", "stop"], dict[str, int]], object] + +callbacks: list[_CallbackType] garbage: list[Any] def collect(generation: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index f9518750d3f1..3abedda262ea 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -3,6 +3,20 @@ from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRichComparison from typing import Sequence, overload from typing_extensions import Literal +__all__ = [ + "commonprefix", + "exists", + "getatime", + "getctime", + "getmtime", + "getsize", + "isdir", + "isfile", + "samefile", + "sameopenfile", + "samestat", +] + # All overloads can return empty string. Ideally, Literal[""] would be a valid # Iterable[T], so that list[T] | Literal[""] could be used as a return # type. But because this only works when T is str, we need Sequence[T] instead. diff --git a/mypy/typeshed/stdlib/getopt.pyi b/mypy/typeshed/stdlib/getopt.pyi index 6ae226f52972..42ddb1cb7020 100644 --- a/mypy/typeshed/stdlib/getopt.pyi +++ b/mypy/typeshed/stdlib/getopt.pyi @@ -1,3 +1,5 @@ +__all__ = ["GetoptError", "error", "getopt", "gnu_getopt"] + 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/getpass.pyi b/mypy/typeshed/stdlib/getpass.pyi index 27f4c6a9b635..153db2f4cb9e 100644 --- a/mypy/typeshed/stdlib/getpass.pyi +++ b/mypy/typeshed/stdlib/getpass.pyi @@ -1,5 +1,7 @@ from typing import TextIO +__all__ = ["getpass", "getuser", "GetPassWarning"] + def getpass(prompt: str = ..., stream: TextIO | None = ...) -> str: ... def getuser() -> str: ... diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index 21be9fb1ff29..1f3ef67ab0f3 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -1,8 +1,72 @@ import sys from _typeshed import StrPath -from typing import IO, Any, Container, Iterable, Sequence, Type, TypeVar, overload +from typing import IO, Any, Container, Iterable, Sequence, TypeVar, overload from typing_extensions import Literal +if sys.version_info >= (3, 11): + __all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "bindtextdomain", + "find", + "translation", + "install", + "textdomain", + "dgettext", + "dngettext", + "gettext", + "ngettext", + "pgettext", + "dpgettext", + "npgettext", + "dnpgettext", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "find", + "translation", + "install", + "textdomain", + "bindtextdomain", + "bind_textdomain_codeset", + "dgettext", + "dngettext", + "gettext", + "lgettext", + "ldgettext", + "ldngettext", + "lngettext", + "ngettext", + "pgettext", + "dpgettext", + "npgettext", + "dnpgettext", + ] +else: + __all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "find", + "translation", + "install", + "textdomain", + "bindtextdomain", + "bind_textdomain_codeset", + "dgettext", + "dngettext", + "gettext", + "lgettext", + "ldgettext", + "ldngettext", + "lngettext", + "ngettext", + ] + class NullTranslations: def __init__(self, fp: IO[str] | None = ...) -> None: ... def _parse(self, fp: IO[str]) -> None: ... @@ -14,11 +78,13 @@ class NullTranslations: 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: ... if sys.version_info < (3, 11): def output_charset(self) -> Any: ... def set_output_charset(self, charset: str) -> None: ... + def install(self, names: Container[str] | None = ...) -> None: ... class GNUTranslations(NullTranslations): @@ -27,6 +93,15 @@ class GNUTranslations(NullTranslations): CONTEXT: str VERSIONS: Sequence[int] +@overload # ignores incompatible overloads +def find( # type: ignore[misc] + domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: Literal[False] = ... +) -> str | None: ... +@overload +def find( + domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: Literal[True] = ... +) -> list[str]: ... +@overload def find(domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: bool = ...) -> Any: ... _T = TypeVar("_T") @@ -45,7 +120,7 @@ if sys.version_info >= (3, 11): domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: Type[_T] = ..., + class_: type[_T] = ..., fallback: Literal[False] = ..., ) -> _T: ... @overload @@ -53,7 +128,7 @@ if sys.version_info >= (3, 11): domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: Type[Any] = ..., + class_: type[Any] = ..., fallback: Literal[True] = ..., ) -> Any: ... def install(domain: str, localedir: StrPath | None = ..., names: Container[str] | None = ...) -> None: ... @@ -73,7 +148,7 @@ else: domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: Type[_T] = ..., + class_: type[_T] = ..., fallback: Literal[False] = ..., codeset: str | None = ..., ) -> _T: ... @@ -82,7 +157,7 @@ else: domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: Type[Any] = ..., + class_: type[Any] = ..., fallback: Literal[True] = ..., codeset: str | None = ..., ) -> Any: ... diff --git a/mypy/typeshed/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi index c1cd176f500c..ced0ceceb205 100644 --- a/mypy/typeshed/stdlib/glob.pyi +++ b/mypy/typeshed/stdlib/glob.pyi @@ -2,10 +2,30 @@ import sys from _typeshed import StrOrBytesPath from typing import AnyStr, Iterator +__all__ = ["escape", "glob", "iglob"] + def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 11): + def glob( + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = ..., + dir_fd: int | None = ..., + recursive: bool = ..., + include_hidden: bool = ..., + ) -> list[AnyStr]: ... + def iglob( + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = ..., + dir_fd: int | None = ..., + recursive: bool = ..., + include_hidden: bool = ..., + ) -> Iterator[AnyStr]: ... + +elif sys.version_info >= (3, 10): def glob( pathname: AnyStr, *, root_dir: StrOrBytesPath | None = ..., dir_fd: int | None = ..., recursive: bool = ... ) -> list[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index 96d64cbce18c..cae2a07e95c6 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -1,8 +1,14 @@ +import sys from _typeshed import SupportsItems -from typing import Generic, Iterable, TypeVar +from typing import Any, Generic, Iterable, TypeVar + +__all__ = ["TopologicalSorter", "CycleError"] _T = TypeVar("_T") +if sys.version_info >= (3, 11): + from types import GenericAlias + class TopologicalSorter(Generic[_T]): def __init__(self, graph: SupportsItems[_T, Iterable[_T]] | None = ...) -> None: ... def add(self, node: _T, *predecessors: _T) -> None: ... @@ -12,5 +18,7 @@ class TopologicalSorter(Generic[_T]): def done(self, *nodes: _T) -> None: ... def get_ready(self) -> tuple[_T, ...]: ... def static_order(self) -> Iterable[_T]: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class CycleError(ValueError): ... diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index b416269921d6..732c36b3dda7 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -14,6 +14,7 @@ if sys.platform != "win32": def gr_gid(self) -> int: ... @property def gr_mem(self) -> list[str]: ... + def getgrall() -> list[struct_group]: ... def getgrgid(id: int) -> struct_group: ... def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index 070ceac48282..7347949ae865 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -6,6 +6,11 @@ from io import FileIO from typing import Any, Protocol, TextIO, overload from typing_extensions import Literal +if sys.version_info >= (3, 8): + __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] +else: + __all__ = ["GzipFile", "open", "compress", "decompress"] + _ReadBinaryMode = Literal["r", "rb"] _WriteBinaryMode = Literal["a", "ab", "w", "wb", "x", "xb"] _OpenTextMode = Literal["rt", "at", "wt", "xt"] diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index fad3c5aad457..4332153d281c 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -1,6 +1,28 @@ import sys from _typeshed import ReadableBuffer, Self from typing import AbstractSet +from typing_extensions import final + +__all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "pbkdf2_hmac", +) class _Hash: @property @@ -76,7 +98,7 @@ def scrypt( maxmem: int = ..., dklen: int = ..., ) -> bytes: ... - +@final class _BlakeHash(_Hash): MAX_DIGEST_SIZE: int MAX_KEY_SIZE: int diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index fd3c2db8ad66..a7a787d44e62 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,14 +1,14 @@ +from _heapq import * from _typeshed import SupportsRichComparison from typing import Any, Callable, Iterable, TypeVar -_T = TypeVar("_T") +__all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] -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[Any]) -> None: ... -def heapreplace(__heap: list[_T], __item: _T) -> _T: ... -def merge(*iterables: Iterable[_T], key: Callable[[_T], Any] | None = ..., reverse: bool = ...) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... +_S = TypeVar("_S") + +__about__: str + +def merge(*iterables: Iterable[_S], key: Callable[[_S], Any] | None = ..., reverse: bool = ...) -> Iterable[_S]: ... +def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = ...) -> list[_S]: ... +def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = ...) -> list[_S]: ... def _heapify_max(__x: list[Any]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 88c88631f99a..fbb0397ac40b 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -26,7 +26,8 @@ else: class HMAC: digest_size: int block_size: int - name: str + @property + def name(self) -> str: ... def __init__(self, key: bytes, msg: ReadableBuffer | None = ..., digestmod: _DigestMod = ...) -> None: ... def update(self, msg: ReadableBuffer) -> None: ... def digest(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/html/__init__.pyi b/mypy/typeshed/stdlib/html/__init__.pyi index af2a80021656..109c5f4b50fb 100644 --- a/mypy/typeshed/stdlib/html/__init__.pyi +++ b/mypy/typeshed/stdlib/html/__init__.pyi @@ -1,4 +1,6 @@ from typing import AnyStr +__all__ = ["escape", "unescape"] + def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... def unescape(s: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/html/entities.pyi b/mypy/typeshed/stdlib/html/entities.pyi index 1743fccf32b9..be83fd1135be 100644 --- a/mypy/typeshed/stdlib/html/entities.pyi +++ b/mypy/typeshed/stdlib/html/entities.pyi @@ -1,3 +1,5 @@ +__all__ = ["html5", "name2codepoint", "codepoint2name", "entitydefs"] + name2codepoint: dict[str, int] html5: dict[str, str] codepoint2name: dict[int, str] diff --git a/mypy/typeshed/stdlib/html/parser.pyi b/mypy/typeshed/stdlib/html/parser.pyi index 60e0de51d3b8..1731a345920b 100644 --- a/mypy/typeshed/stdlib/html/parser.pyi +++ b/mypy/typeshed/stdlib/html/parser.pyi @@ -1,6 +1,8 @@ from _markupbase import ParserBase from typing import Pattern +__all__ = ["HTMLParser"] + class HTMLParser(ParserBase): def __init__(self, *, convert_charrefs: bool = ...) -> None: ... def feed(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi index 93895549cb2a..822cc0932939 100644 --- a/mypy/typeshed/stdlib/http/__init__.pyi +++ b/mypy/typeshed/stdlib/http/__init__.pyi @@ -2,6 +2,8 @@ import sys from enum import IntEnum from typing_extensions import Literal +__all__ = ["HTTPStatus"] + class HTTPStatus(IntEnum): @property def phrase(self) -> str: ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 1558f6ff46e8..93f132d678f9 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -5,7 +5,29 @@ import sys import types from _typeshed import Self, WriteableBuffer from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, Type, TypeVar, Union, overload +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, Union, overload + +__all__ = [ + "HTTPResponse", + "HTTPConnection", + "HTTPException", + "NotConnected", + "UnknownProtocol", + "UnknownTransferEncoding", + "UnimplementedFileMode", + "IncompleteRead", + "InvalidURL", + "ImproperConnectionState", + "CannotSendRequest", + "CannotSendHeader", + "ResponseNotReady", + "BadStatusLine", + "LineTooLong", + "RemoteDisconnected", + "error", + "responses", + "HTTPSConnection", +] _DataType = Union[bytes, IO[Any], Iterable[bytes], str] _T = TypeVar("_T") @@ -78,7 +100,7 @@ class HTTPMessage(email.message.Message): def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... -class HTTPResponse(io.BufferedIOBase, BinaryIO): +class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes msg: HTTPMessage headers: HTTPMessage version: int @@ -107,7 +129,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def __iter__(self) -> Iterator[bytes]: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> bool | None: ... def info(self) -> email.message.Message: ... def geturl(self) -> str: ... @@ -135,7 +157,7 @@ class HTTPConnection: auto_open: int # undocumented debuglevel: int default_port: int # undocumented - response_class: Type[HTTPResponse] # undocumented + response_class: type[HTTPResponse] # undocumented timeout: float | None host: str port: int @@ -153,6 +175,7 @@ class HTTPConnection: def __init__( self, host: str, port: int | None = ..., timeout: float | None = ..., source_address: tuple[str, int] | None = ... ) -> None: ... + def request( self, method: str, url: str, body: _DataType | None = ..., headers: Mapping[str, str] = ..., *, encode_chunked: bool = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 6bfa7f385e69..4fb1c38c6ab8 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -4,6 +4,17 @@ from http.client import HTTPResponse from typing import ClassVar, Iterable, Iterator, Pattern, Sequence, TypeVar, overload from urllib.request import Request +__all__ = [ + "Cookie", + "CookieJar", + "CookiePolicy", + "DefaultCookiePolicy", + "FileCookieJar", + "LWPCookieJar", + "LoadError", + "MozillaCookieJar", +] + _T = TypeVar("_T") class LoadError(OSError): ... @@ -27,8 +38,6 @@ class CookieJar(Iterable[Cookie]): def clear_expired_cookies(self) -> None: ... # undocumented def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... class FileCookieJar(CookieJar): filename: str @@ -37,6 +46,7 @@ class FileCookieJar(CookieJar): def __init__(self, filename: StrPath | None = ..., delayload: bool = ..., policy: CookiePolicy | None = ...) -> None: ... else: def __init__(self, filename: str | None = ..., delayload: bool = ..., policy: CookiePolicy | None = ...) -> None: ... + def save(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... def load(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... def revert(self, filename: str | None = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... @@ -102,6 +112,7 @@ class DefaultCookiePolicy(CookiePolicy): 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: ... diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index 211fd37662d4..5e01e603781d 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -4,6 +4,8 @@ from typing import Any, Generic, Iterable, Mapping, TypeVar, Union, overload if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ["CookieError", "BaseCookie", "SimpleCookie"] + _DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] _T = TypeVar("_T") @@ -19,14 +21,18 @@ def _unquote(str: str) -> str: ... class CookieError(Exception): ... class Morsel(dict[str, Any], Generic[_T]): - value: str - coded_value: _T - key: str + @property + def value(self) -> str: ... + @property + def coded_value(self) -> _T: ... + @property + def key(self) -> str: ... def __init__(self) -> None: ... 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 setdefault(self, key: str, val: str | None = ...) -> str: ... # The dict update can also get a keywords argument so this is incompatible @overload # type: ignore[override] @@ -35,8 +41,11 @@ class Morsel(dict[str, Any], Generic[_T]): def update(self, values: Iterable[tuple[str, str]]) -> None: ... def isReservedKey(self, K: str) -> bool: ... def output(self, attrs: list[str] | None = ..., header: str = ...) -> str: ... + __str__ = output def js_output(self, attrs: list[str] | None = ...) -> str: ... def OutputString(self, attrs: list[str] | None = ...) -> str: ... + def __eq__(self, morsel: object) -> bool: ... + def __setitem__(self, K: str, V: Any) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -45,6 +54,7 @@ class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): def value_decode(self, val: str) -> _T: ... def value_encode(self, val: _T) -> str: ... def output(self, attrs: list[str] | None = ..., header: str = ..., sep: str = ...) -> str: ... + __str__ = output def js_output(self, attrs: list[str] | None = ...) -> str: ... def load(self, rawdata: _DataType) -> None: ... def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ... diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index e3d0a8c318f4..53159b65ec14 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -5,6 +5,11 @@ import sys from _typeshed import StrPath, SupportsRead, SupportsWrite from typing import Any, AnyStr, BinaryIO, ClassVar, Mapping, Sequence +if sys.version_info >= (3, 7): + __all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler"] +else: + __all__ = ["HTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler"] + class HTTPServer(socketserver.TCPServer): server_name: str server_port: int @@ -60,6 +65,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): ) -> 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: ... def send_head(self) -> io.BytesIO | BinaryIO | None: ... # undocumented diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index 1b2774d8fde0..e85e7d4ad90a 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -5,9 +5,11 @@ from _typeshed import Self from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, Pattern, Type, Union +from typing import IO, Any, Callable, Pattern, Union from typing_extensions import Literal +__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] + # TODO: Commands should use their actual return types, not this type alias. # E.g. Tuple[Literal["OK"], List[bytes]] _CommandResults = tuple[str, list[Any]] @@ -17,9 +19,9 @@ _AnyResponseData = Union[list[None], list[Union[bytes, tuple[bytes, bytes]]]] _list = list # conflicts with a method named "list" class IMAP4: - error: Type[Exception] - abort: Type[Exception] - readonly: Type[Exception] + error: type[Exception] + abort: type[Exception] + readonly: type[Exception] mustquote: Pattern[str] debug: int state: str @@ -32,7 +34,7 @@ class IMAP4: tagpre: str tagre: Pattern[str] welcome: bytes - capabilities: tuple[str] + capabilities: tuple[str, ...] PROTOCOL_VERSION: str if sys.version_info >= (3, 9): def __init__(self, host: str = ..., port: int = ..., timeout: float | None = ...) -> None: ... @@ -40,6 +42,7 @@ class IMAP4: 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 @@ -63,7 +66,7 @@ class IMAP4: def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def enable(self, capability: str) -> _CommandResults: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def expunge(self) -> _CommandResults: ... def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ... def getacl(self, mailbox: str) -> _CommandResults: ... @@ -96,6 +99,7 @@ class IMAP4: 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: ... @@ -130,6 +134,7 @@ class IMAP4_SSL(IMAP4): def open(self, host: str = ..., port: int | None = ..., timeout: float | None = ...) -> None: ... else: def open(self, host: str = ..., port: int | None = ...) -> None: ... + def read(self, size: int) -> bytes: ... def readline(self) -> bytes: ... def send(self, data: bytes) -> None: ... @@ -151,6 +156,7 @@ class IMAP4_stream(IMAP4): def open(self, host: str | None = ..., port: int | None = ..., timeout: float | None = ...) -> None: ... else: def open(self, host: str | None = ..., port: int | None = ...) -> None: ... + def read(self, size: int) -> bytes: ... def readline(self) -> bytes: ... def send(self, data: bytes) -> None: ... @@ -165,5 +171,5 @@ class _Authenticator: def Internaldate2tuple(resp: str) -> time.struct_time: ... def Int2AP(num: int) -> str: ... -def ParseFlags(resp: str) -> tuple[str]: ... +def ParseFlags(resp: str) -> tuple[str, ...]: ... def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... diff --git a/mypy/typeshed/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi index 4515cf2269b0..af046e899326 100644 --- a/mypy/typeshed/stdlib/imghdr.pyi +++ b/mypy/typeshed/stdlib/imghdr.pyi @@ -1,6 +1,8 @@ from _typeshed import StrPath from typing import Any, BinaryIO, Callable, Protocol, overload +__all__ = ["what"] + class _ReadableBinary(Protocol): def tell(self) -> int: ... def read(self, size: int) -> bytes: ... diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index 88f2e789329b..ec09d18de32c 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -1,7 +1,7 @@ import types from _typeshed import StrPath from os import PathLike -from typing import IO, Any, Protocol, TypeVar +from typing import IO, Any, Protocol from _imp import ( acquire_lock as acquire_lock, @@ -15,8 +15,6 @@ from _imp import ( release_lock as release_lock, ) -_T = TypeVar("_T") - SEARCH_ERROR: int PY_SOURCE: int PY_COMPILED: int diff --git a/mypy/typeshed/stdlib/importlib/__init__.pyi b/mypy/typeshed/stdlib/importlib/__init__.pyi index 1b91cc55f2df..0e99786775b0 100644 --- a/mypy/typeshed/stdlib/importlib/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/__init__.pyi @@ -2,6 +2,8 @@ from importlib.abc import Loader from types import ModuleType from typing import Mapping, Sequence +__all__ = ["__import__", "import_module", "invalidate_caches", "reload"] + # Signature of `builtins.__import__` should be kept identical to `importlib.__import__` def __import__( name: str, diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 9bb370dfd7e8..16f514a74eb5 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -91,6 +91,7 @@ if sys.version_info >= (3, 7): else: @abstractmethod def is_resource(self, name: str) -> bool: ... + @abstractmethod def contents(self) -> Iterator[str]: ... @@ -157,7 +158,7 @@ if sys.version_info >= (3, 9): @overload @abstractmethod def open( - self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... + self, mode: OpenBinaryMode, buffering: int = ..., encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: ... # Fallback if mode is not specified @overload @@ -168,11 +169,12 @@ if sys.version_info >= (3, 9): @property def name(self) -> str: ... @abstractmethod - def __truediv__(self, key: StrPath) -> Traversable: ... + def __truediv__(self, child: StrPath) -> Traversable: ... @abstractmethod def read_bytes(self) -> bytes: ... @abstractmethod def read_text(self, encoding: str | None = ...) -> str: ... + class TraversableResources(ResourceReader): @abstractmethod def files(self) -> Traversable: ... diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index b73f9c527583..7efe287f7205 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -22,8 +22,10 @@ class ModuleSpec: submodule_search_locations: list[str] | None loader_state: Any cached: str | None - parent: str | None + @property + def parent(self) -> str | None: ... has_location: bool + def __eq__(self, other: object) -> bool: ... class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @@ -82,6 +84,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): else: @classmethod def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod def exec_module(module: types.ModuleType) -> None: ... @@ -106,6 +109,7 @@ class PathFinder: elif sys.version_info >= (3, 8): @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + @classmethod def find_spec( cls, fullname: str, path: Sequence[bytes | str] | None = ..., target: types.ModuleType | None = ... @@ -123,16 +127,16 @@ 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[type[importlib.abc.Loader], list[str]]) -> None: ... @classmethod def path_hook( - cls, *loader_details: tuple[importlib.abc.Loader, list[str]] + cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... -class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): +class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): # type: ignore # argument disparities def set_data(self, path: importlib.abc._Path, data: bytes, *, _mode: int = ...) -> None: ... -class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... +class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... # type: ignore # argument disparities class ExtensionFileLoader(importlib.abc.ExecutionLoader): def __init__(self, name: str, path: importlib.abc._Path) -> None: ... @@ -142,3 +146,4 @@ class ExtensionFileLoader(importlib.abc.ExecutionLoader): def exec_module(self, module: types.ModuleType) -> None: ... def is_package(self, fullname: str) -> bool: ... def get_code(self, fullname: str) -> None: ... + def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index a9e223149b52..52c5547a6128 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -1,7 +1,7 @@ import abc import pathlib import sys -from _typeshed import StrPath +from _typeshed import Self, StrPath from collections.abc import Mapping from email.message import Message from importlib.abc import MetaPathFinder @@ -9,98 +9,207 @@ from os import PathLike from pathlib import Path from typing import Any, ClassVar, Iterable, NamedTuple, Pattern, overload +if sys.version_info >= (3, 10): + __all__ = [ + "Distribution", + "DistributionFinder", + "PackageMetadata", + "PackageNotFoundError", + "distribution", + "distributions", + "entry_points", + "files", + "metadata", + "packages_distributions", + "requires", + "version", + ] +else: + __all__ = [ + "Distribution", + "DistributionFinder", + "PackageNotFoundError", + "distribution", + "distributions", + "entry_points", + "files", + "metadata", + "requires", + "version", + ] + if sys.version_info >= (3, 10): from importlib.metadata._meta import PackageMetadata as PackageMetadata def packages_distributions() -> Mapping[str, list[str]]: ... -if sys.version_info >= (3, 8): - class PackageNotFoundError(ModuleNotFoundError): ... - class _EntryPointBase(NamedTuple): - name: str - value: str - group: str - class EntryPoint(_EntryPointBase): - pattern: ClassVar[Pattern[str]] - def load(self) -> Any: ... # Callable[[], Any] or an importable module +class PackageNotFoundError(ModuleNotFoundError): + @property + def name(self) -> str: ... # type: ignore[override] + +class _EntryPointBase(NamedTuple): + name: str + value: str + group: str + +class EntryPoint(_EntryPointBase): + pattern: ClassVar[Pattern[str]] + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> list[str]: ... + if sys.version_info >= (3, 9): + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + if sys.version_info >= (3, 10): + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented + +if sys.version_info >= (3, 10): + class EntryPoints(list[EntryPoint]): # use as list is deprecated since 3.10 + # int argument is deprecated since 3.10 + def __getitem__(self, name: int | str) -> EntryPoint: ... # type: ignore[override] + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + @property + def names(self) -> set[str]: ... @property - def extras(self) -> list[str]: ... - if sys.version_info >= (3, 9): - @property - def module(self) -> str: ... - @property - def attr(self) -> str: ... - if sys.version_info >= (3, 10): - dist: ClassVar[Distribution | None] - def matches(self, **params: Any) -> bool: ... # undocumented - class PackagePath(pathlib.PurePosixPath): - def read_text(self, encoding: str = ...) -> str: ... - def read_binary(self) -> bytes: ... - def locate(self) -> PathLike[str]: ... - # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: - hash: FileHash | None - size: int | None - dist: Distribution - class FileHash: - mode: str - value: str - def __init__(self, spec: str) -> None: ... - class Distribution: - @abc.abstractmethod - def read_text(self, filename: str) -> str | None: ... - @abc.abstractmethod - def locate_file(self, path: StrPath) -> PathLike[str]: ... + def groups(self) -> set[str]: ... + + class SelectableGroups(dict[str, EntryPoints]): # use as dict is deprecated since 3.10 @classmethod - def from_name(cls, name: str) -> Distribution: ... + def load(cls: type[Self], eps: Iterable[EntryPoint]) -> Self: ... + @property + def groups(self) -> set[str]: ... + @property + def names(self) -> set[str]: ... @overload - @classmethod - def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + def select(self: Self) -> Self: ... # type: ignore[misc] @overload - @classmethod - def discover( - cls, *, context: None = ..., name: str | None = ..., path: list[str] = ..., **kwargs: Any - ) -> Iterable[Distribution]: ... - @staticmethod - def at(path: StrPath) -> PathDistribution: ... + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + +class PackagePath(pathlib.PurePosixPath): + def read_text(self, encoding: str = ...) -> str: ... + def read_binary(self) -> bytes: ... + def locate(self) -> PathLike[str]: ... + # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: + hash: FileHash | None + size: int | None + dist: Distribution + +class FileHash: + mode: str + value: str + def __init__(self, spec: str) -> None: ... + +class Distribution: + @abc.abstractmethod + def read_text(self, filename: str) -> str | None: ... + @abc.abstractmethod + def locate_file(self, path: StrPath) -> 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: str | None = ..., path: list[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + @staticmethod + def at(path: StrPath) -> PathDistribution: ... + + if sys.version_info >= (3, 10): @property - def metadata(self) -> Message: ... + def metadata(self) -> PackageMetadata: ... @property - def version(self) -> str: ... + def entry_points(self) -> EntryPoints: ... + else: + @property + def metadata(self) -> Message: ... @property def entry_points(self) -> list[EntryPoint]: ... + + @property + def version(self) -> str: ... + @property + def files(self) -> list[PackagePath] | None: ... + @property + def requires(self) -> list[str] | None: ... + if sys.version_info >= (3, 10): @property - def files(self) -> list[PackagePath] | None: ... + def name(self) -> str: ... + +class DistributionFinder(MetaPathFinder): + class Context: + name: str | None + def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... @property - def requires(self) -> list[str] | None: ... - if sys.version_info >= (3, 10): - @property - def name(self) -> str: ... - class DistributionFinder(MetaPathFinder): - class Context: - name: str | None - def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... - @property - def path(self) -> list[str]: ... - @abc.abstractmethod - def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... - class MetadataPathFinder(DistributionFinder): - @classmethod - def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - if sys.version_info >= (3, 10): - # Yes, this is an instance method that has argumend named "cls" - def invalidate_caches(cls) -> None: ... # type: ignore - class PathDistribution(Distribution): - def __init__(self, path: Path) -> None: ... - def read_text(self, filename: StrPath) -> str: ... - def locate_file(self, path: StrPath) -> PathLike[str]: ... - def distribution(distribution_name: str) -> Distribution: ... + def path(self) -> list[str]: ... + + @abc.abstractmethod + def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... + +class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + if sys.version_info >= (3, 10): + # Yes, this is an instance method that has argumend named "cls" + def invalidate_caches(cls) -> None: ... # type: ignore + +class PathDistribution(Distribution): + def __init__(self, path: Path) -> None: ... + def read_text(self, filename: StrPath) -> str: ... + def locate_file(self, path: StrPath) -> PathLike[str]: ... + +def distribution(distribution_name: str) -> Distribution: ... +@overload +def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... +@overload +def distributions( + *, context: None = ..., name: str | None = ..., path: list[str] = ..., **kwargs: Any +) -> Iterable[Distribution]: ... + +if sys.version_info >= (3, 10): + def metadata(distribution_name: str) -> PackageMetadata: ... @overload - def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + def entry_points() -> SelectableGroups: ... # type: ignore[misc] @overload - def distributions( - *, context: None = ..., name: str | None = ..., path: list[str] = ..., **kwargs: Any - ) -> Iterable[Distribution]: ... + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +else: def metadata(distribution_name: str) -> Message: ... - def version(distribution_name: str) -> str: ... - def entry_points() -> dict[str, tuple[EntryPoint, ...]]: ... - def files(distribution_name: str) -> list[PackagePath] | None: ... - def requires(distribution_name: str) -> list[str] | None: ... + def entry_points() -> dict[str, list[EntryPoint]]: ... + +def version(distribution_name: str) -> str: ... +def files(distribution_name: str) -> list[PackagePath] | None: ... +def requires(distribution_name: str) -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index b484d7126b21..cee3259332ff 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -1,23 +1,52 @@ +import os import sys -from typing import Any +from contextlib import AbstractContextManager +from pathlib import Path +from types import ModuleType +from typing import Any, BinaryIO, Iterator, TextIO, Union -# This is a >=3.7 module, so we conditionally include its source. -if sys.version_info >= (3, 7): - import os - from contextlib import AbstractContextManager - from pathlib import Path - from types import ModuleType - from typing import BinaryIO, Iterator, TextIO, Union +if sys.version_info >= (3, 10): + __all__ = [ + "Package", + "Resource", + "ResourceReader", + "as_file", + "contents", + "files", + "is_resource", + "open_binary", + "open_text", + "path", + "read_binary", + "read_text", + ] +elif sys.version_info >= (3, 9): + __all__ = [ + "Package", + "Resource", + "as_file", + "contents", + "files", + "is_resource", + "open_binary", + "open_text", + "path", + "read_binary", + "read_text", + ] +else: + __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] + +Package = Union[str, ModuleType] +Resource = Union[str, os.PathLike[Any]] - Package = Union[str, ModuleType] - Resource = Union[str, os.PathLike[Any]] - 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) -> AbstractContextManager[Path]: ... - def is_resource(package: Package, name: str) -> bool: ... - def contents(package: Package) -> Iterator[str]: ... +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) -> AbstractContextManager[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 diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index a96e30865a59..f87cd0e55acb 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -21,10 +21,120 @@ from types import ( ) if sys.version_info >= (3, 7): - from types import ClassMethodDescriptorType, WrapperDescriptorType, MemberDescriptorType, MethodDescriptorType - -from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, Type, TypeVar, Union -from typing_extensions import Literal, TypeGuard + from types import ( + ClassMethodDescriptorType, + WrapperDescriptorType, + MemberDescriptorType, + MethodDescriptorType, + MethodWrapperType, + ) + +from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar, Union +from typing_extensions import Literal, ParamSpec, TypeGuard + +if sys.version_info >= (3, 11): + __all__ = [ + "ArgInfo", + "Arguments", + "Attribute", + "BlockFinder", + "BoundArguments", + "CORO_CLOSED", + "CORO_CREATED", + "CORO_RUNNING", + "CORO_SUSPENDED", + "CO_ASYNC_GENERATOR", + "CO_COROUTINE", + "CO_GENERATOR", + "CO_ITERABLE_COROUTINE", + "CO_NESTED", + "CO_NEWLOCALS", + "CO_NOFREE", + "CO_OPTIMIZED", + "CO_VARARGS", + "CO_VARKEYWORDS", + "ClassFoundException", + "ClosureVars", + "EndOfBlock", + "FrameInfo", + "FullArgSpec", + "GEN_CLOSED", + "GEN_CREATED", + "GEN_RUNNING", + "GEN_SUSPENDED", + "Parameter", + "Signature", + "TPFLAGS_IS_ABSTRACT", + "Traceback", + "classify_class_attrs", + "cleandoc", + "currentframe", + "findsource", + "formatannotation", + "formatannotationrelativeto", + "formatargvalues", + "get_annotations", + "getabsfile", + "getargs", + "getargvalues", + "getattr_static", + "getblock", + "getcallargs", + "getclasstree", + "getclosurevars", + "getcomments", + "getcoroutinelocals", + "getcoroutinestate", + "getdoc", + "getfile", + "getframeinfo", + "getfullargspec", + "getgeneratorlocals", + "getgeneratorstate", + "getinnerframes", + "getlineno", + "getmembers", + "getmembers_static", + "getmodule", + "getmodulename", + "getmro", + "getouterframes", + "getsource", + "getsourcefile", + "getsourcelines", + "indentsize", + "isabstract", + "isasyncgen", + "isasyncgenfunction", + "isawaitable", + "isbuiltin", + "isclass", + "iscode", + "iscoroutine", + "iscoroutinefunction", + "isdatadescriptor", + "isframe", + "isfunction", + "isgenerator", + "isgeneratorfunction", + "isgetsetdescriptor", + "ismemberdescriptor", + "ismethod", + "ismethoddescriptor", + "ismethodwrapper", + "ismodule", + "isroutine", + "istraceback", + "signature", + "stack", + "trace", + "unwrap", + "walktree", + ] + +_P = ParamSpec("_P") +_T_cont = TypeVar("_T_cont", contravariant=True) +_V_cont = TypeVar("_V_cont", contravariant=True) # # Types and members @@ -55,10 +165,17 @@ TPFLAGS_IS_ABSTRACT: Literal[1048576] modulesbyfile: dict[str, Any] -def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> list[tuple[str, Any]]: ... +_GetMembersPredicate = Callable[[Any], bool] +_GetMembersReturn = list[tuple[str, Any]] + +def getmembers(object: object, predicate: _GetMembersPredicate | None = ...) -> _GetMembersReturn: ... + +if sys.version_info >= (3, 11): + def getmembers_static(object: object, predicate: _GetMembersPredicate | None = ...) -> _GetMembersReturn: ... + def getmodulename(path: str) -> str | None: ... def ismodule(object: object) -> TypeGuard[ModuleType]: ... -def isclass(object: object) -> TypeGuard[Type[Any]]: ... +def isclass(object: object) -> TypeGuard[type[Any]]: ... def ismethod(object: object) -> TypeGuard[MethodType]: ... def isfunction(object: object) -> TypeGuard[FunctionType]: ... @@ -80,9 +197,6 @@ if sys.version_info >= (3, 8): else: def isasyncgenfunction(object: object) -> bool: ... -_T_cont = TypeVar("_T_cont", contravariant=True) -_V_cont = TypeVar("_V_cont", contravariant=True) - class _SupportsSet(Protocol[_T_cont, _V_cont]): def __set__(self, __instance: _T_cont, __value: _V_cont) -> None: ... @@ -95,6 +209,9 @@ def isframe(object: object) -> TypeGuard[FrameType]: ... def iscode(object: object) -> TypeGuard[CodeType]: ... def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... +if sys.version_info >= (3, 11): + def ismethodwrapper(object: object) -> TypeGuard[MethodWrapperType]: ... + if sys.version_info >= (3, 7): def isroutine( object: object, @@ -125,7 +242,7 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... @@ -166,32 +283,33 @@ class Signature: empty = _empty @property def parameters(self) -> types.MappingProxyType[str, Parameter]: ... - # TODO: can we be more specific here? @property def return_annotation(self) -> Any: ... def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def replace( - self: Self, *, parameters: Sequence[Parameter] | Type[_void] | None = ..., return_annotation: Any = ... + self: Self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ... ) -> Self: ... if sys.version_info >= (3, 10): @classmethod def from_callable( - cls, + cls: type[Self], obj: Callable[..., Any], *, follow_wrapped: bool = ..., globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ..., eval_str: bool = ..., - ) -> Signature: ... + ) -> Self: ... else: @classmethod - def from_callable(cls, obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... + def from_callable(cls: type[Self], obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Self: ... + + def __eq__(self, other: object) -> bool: ... if sys.version_info >= (3, 10): def get_annotations( - obj: Callable[..., Any] | Type[Any] | ModuleType, + obj: Callable[..., Any] | type[Any] | ModuleType, *, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ..., @@ -230,19 +348,24 @@ class Parameter: def replace( self: Self, *, - name: str | Type[_void] = ..., - kind: _ParameterKind | Type[_void] = ..., + name: str | type[_void] = ..., + kind: _ParameterKind | type[_void] = ..., default: Any = ..., annotation: Any = ..., ) -> Self: ... + def __eq__(self, other: object) -> bool: ... class BoundArguments: arguments: OrderedDict[str, Any] - args: tuple[Any, ...] - kwargs: dict[str, Any] - signature: Signature + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> dict[str, Any]: ... + @property + def signature(self) -> Signature: ... def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... def apply_defaults(self) -> None: ... + def __eq__(self, other: object) -> bool: ... # # Classes and functions @@ -252,7 +375,7 @@ class BoundArguments: # seem to be supporting this at the moment: # _ClassTreeItem = list[_ClassTreeItem] | Tuple[type, Tuple[type, ...]] def getclasstree(classes: list[type], unique: bool = ...) -> list[Any]: ... -def walktree(classes: list[type], children: dict[Type[Any], list[type]], parent: Type[Any] | None) -> list[Any]: ... +def walktree(classes: list[type], children: dict[type[Any], list[type]], parent: type[Any] | None) -> list[Any]: ... class Arguments(NamedTuple): args: list[str] @@ -318,7 +441,7 @@ def formatargvalues( formatvalue: Callable[[Any], str] | None = ..., ) -> str: ... def getmro(cls: type) -> tuple[type, ...]: ... -def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> dict[str, Any]: ... +def getcallargs(__func: Callable[_P, Any], *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index 50452917c6f3..c32691edb686 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -4,13 +4,58 @@ import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO, Type +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO +from typing_extensions import Literal -DEFAULT_BUFFER_SIZE: int - -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int +if sys.version_info >= (3, 8): + __all__ = [ + "BlockingIOError", + "open", + "open_code", + "IOBase", + "RawIOBase", + "FileIO", + "BytesIO", + "StringIO", + "BufferedIOBase", + "BufferedReader", + "BufferedWriter", + "BufferedRWPair", + "BufferedRandom", + "TextIOBase", + "TextIOWrapper", + "UnsupportedOperation", + "SEEK_SET", + "SEEK_CUR", + "SEEK_END", + ] +else: + __all__ = [ + "BlockingIOError", + "open", + "IOBase", + "RawIOBase", + "FileIO", + "BytesIO", + "StringIO", + "BufferedIOBase", + "BufferedReader", + "BufferedWriter", + "BufferedRWPair", + "BufferedRandom", + "TextIOBase", + "TextIOWrapper", + "UnsupportedOperation", + "SEEK_SET", + "SEEK_CUR", + "SEEK_END", + ] + +DEFAULT_BUFFER_SIZE: Literal[8192] + +SEEK_SET: Literal[0] +SEEK_CUR: Literal[1] +SEEK_END: Literal[2] open = builtins.open @@ -26,7 +71,7 @@ class IOBase: def __next__(self) -> bytes: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def close(self) -> None: ... def fileno(self) -> int: ... @@ -63,7 +108,7 @@ class BufferedIOBase(IOBase): def read(self, __size: int | None = ...) -> bytes: ... def read1(self, __size: int = ...) -> bytes: ... -class FileIO(RawIOBase, BinaryIO): +class FileIO(RawIOBase, BinaryIO): # type: ignore # argument disparities between the base classes mode: str name: StrOrBytesPath | int # type: ignore[assignment] def __init__( @@ -75,7 +120,7 @@ class FileIO(RawIOBase, BinaryIO): def read(self, __size: int = ...) -> bytes: ... def __enter__(self: Self) -> Self: ... -class BytesIO(BufferedIOBase, BinaryIO): +class BytesIO(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between the base classes 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 @@ -89,7 +134,7 @@ class BytesIO(BufferedIOBase, BinaryIO): else: def read1(self, __size: int | None) -> bytes: ... # type: ignore[override] -class BufferedReader(BufferedIOBase, BinaryIO): +class BufferedReader(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def peek(self, __size: int = ...) -> bytes: ... @@ -98,7 +143,7 @@ class BufferedReader(BufferedIOBase, BinaryIO): else: def read1(self, __size: int) -> bytes: ... # type: ignore[override] -class BufferedWriter(BufferedIOBase, BinaryIO): +class BufferedWriter(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def write(self, __buffer: ReadableBuffer) -> int: ... @@ -130,7 +175,7 @@ class TextIOBase(IOBase): def read(self, __size: int | None = ...) -> str: ... def tell(self) -> int: ... -class TextIOWrapper(TextIOBase, TextIO): +class TextIOWrapper(TextIOBase, TextIO): # type: ignore # argument disparities between base classes def __init__( self, buffer: IO[bytes], @@ -180,3 +225,4 @@ class IncrementalNewlineDecoder(codecs.IncrementalDecoder): def decode(self, input: bytes | str, final: bool = ...) -> str: ... @property def newlines(self) -> str | tuple[str, ...] | None: ... + def setstate(self, __state: tuple[bytes, int]) -> None: ... diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index 1cfd9a7c9378..d777cef74597 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,25 +1,23 @@ import sys +from _typeshed import Self from typing import Any, Container, Generic, Iterable, Iterator, SupportsInt, TypeVar, overload +from typing_extensions import Literal # Undocumented length constants -IPV4LENGTH: int -IPV6LENGTH: int +IPV4LENGTH: Literal[32] +IPV6LENGTH: Literal[128] _A = TypeVar("_A", IPv4Address, IPv6Address) _N = TypeVar("_N", IPv4Network, IPv6Network) -_T = TypeVar("_T") -def ip_address(address: object) -> IPv4Address | IPv6Address: ... -def ip_network(address: object, strict: bool = ...) -> IPv4Network | IPv6Network: ... -def ip_interface(address: object) -> IPv4Interface | IPv6Interface: ... +_RawIPAddress = int | str | bytes | IPv4Address | IPv6Address +_RawNetworkPart = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface + +def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: ... +def ip_network(address: _RawIPAddress | _RawNetworkPart, strict: bool = ...) -> IPv4Network | IPv6Network: ... +def ip_interface(address: _RawIPAddress | _RawNetworkPart) -> 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) -> str: ... @property @@ -31,10 +29,22 @@ class _IPAddressBase: class _BaseAddress(_IPAddressBase, SupportsInt): def __init__(self, address: object) -> None: ... - def __add__(self: _T, other: int) -> _T: ... + def __add__(self: Self, other: int) -> Self: ... def __hash__(self) -> int: ... def __int__(self) -> int: ... - def __sub__(self: _T, other: int) -> _T: ... + def __sub__(self: Self, other: int) -> Self: ... + def __format__(self, fmt: str) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self: Self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self: Self, other: Self) -> bool: ... + def __gt__(self: Self, other: Self) -> bool: ... + def __le__(self: Self, other: Self) -> bool: ... + else: + def __ge__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + @property def is_global(self) -> bool: ... @property @@ -61,10 +71,21 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): 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]: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self: Self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self: Self, other: Self) -> bool: ... + def __gt__(self: Self, other: Self) -> bool: ... + def __le__(self: Self, other: Self) -> bool: ... + else: + def __ge__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self: Self, other: Self, NotImplemented: Any = ...) -> bool: ... + + def address_exclude(self: Self, other: Self) -> Iterator[Self]: ... @property def broadcast_address(self) -> _A: ... - def compare_networks(self: _T, other: _T) -> int: ... + def compare_networks(self: Self, other: Self) -> int: ... def hosts(self) -> Iterator[_A]: ... @property def is_global(self) -> bool: ... @@ -88,10 +109,11 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): @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: int | None = ...) -> Iterator[_T]: ... - def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> _T: ... + def subnet_of(self: Self, other: Self) -> bool: ... + def supernet_of(self: Self, other: Self) -> bool: ... + + def subnets(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[Self]: ... + def supernet(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Self: ... @property def with_hostmask(self) -> str: ... @property @@ -114,11 +136,23 @@ class _BaseInterface(_BaseAddress, Generic[_A, _N]): @property def with_prefixlen(self) -> str: ... -class IPv4Address(_BaseAddress): ... -class IPv4Network(_BaseNetwork[IPv4Address]): ... +class _BaseV4: + @property + def version(self) -> Literal[4]: ... + @property + def max_prefixlen(self) -> Literal[32]: ... + +class IPv4Address(_BaseV4, _BaseAddress): ... +class IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]): ... class IPv4Interface(IPv4Address, _BaseInterface[IPv4Address, IPv4Network]): ... -class IPv6Address(_BaseAddress): +class _BaseV6: + @property + def version(self) -> Literal[6]: ... + @property + def max_prefixlen(self) -> Literal[128]: ... + +class IPv6Address(_BaseV6, _BaseAddress): @property def ipv4_mapped(self) -> IPv4Address | None: ... @property @@ -131,7 +165,7 @@ class IPv6Address(_BaseAddress): @property def scope_id(self) -> str | None: ... -class IPv6Network(_BaseNetwork[IPv6Address]): +class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): @property def is_site_local(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index a5a7f4f1b62f..35765712202a 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import _T_co +from _typeshed import Self, _T_co from typing import ( Any, Callable, @@ -9,7 +9,6 @@ from typing import ( SupportsComplex, SupportsFloat, SupportsInt, - Type, TypeVar, Union, overload, @@ -36,12 +35,12 @@ class count(Iterator[_N], Generic[_N]): @overload def __new__(cls, *, step: _N) -> count[_N]: ... def __next__(self) -> _N: ... - def __iter__(self) -> Iterator[_N]: ... + def __iter__(self: Self) -> Self: ... class cycle(Iterator[_T], Generic[_T]): def __init__(self, __iterable: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... class repeat(Iterator[_T], Generic[_T]): @overload @@ -49,7 +48,8 @@ class repeat(Iterator[_T], Generic[_T]): @overload def __init__(self, object: _T, times: int) -> None: ... def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... + def __length_hint__(self) -> int: ... class accumulate(Iterator[_T], Generic[_T]): if sys.version_info >= (3, 8): @@ -59,32 +59,33 @@ class accumulate(Iterator[_T], Generic[_T]): def __init__(self, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> None: ... else: def __init__(self, iterable: Iterable[_T], func: Callable[[_T, _T], _T] | None = ...) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... @classmethod - # We use Type and not Type[_S] to not lose the type inference from __iterable - def from_iterable(cls: Type[Any], __iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + # We use type[Any] and not type[_S] to not lose the type inference from __iterable + def from_iterable(cls: type[Any], __iterable: Iterable[Iterable[_S]]) -> chain[_S]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class compress(Iterator[_T], Generic[_T]): def __init__(self, data: Iterable[_T], selectors: Iterable[Any]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class dropwhile(Iterator[_T], Generic[_T]): def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class filterfalse(Iterator[_T], Generic[_T]): def __init__(self, __predicate: Predicate[_T] | None, __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... _T1 = TypeVar("_T1") @@ -95,7 +96,7 @@ class groupby(Iterator[tuple[_T, Iterator[_S]]], Generic[_T, _S]): def __new__(cls, iterable: Iterable[_T1], key: None = ...) -> groupby[_T1, _T1]: ... @overload def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... - def __iter__(self) -> Iterator[tuple[_T, Iterator[_S]]]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> tuple[_T, Iterator[_S]]: ... class islice(Iterator[_T], Generic[_T]): @@ -103,24 +104,24 @@ class islice(Iterator[_T], Generic[_T]): def __init__(self, __iterable: Iterable[_T], __stop: int | None) -> None: ... @overload def __init__(self, __iterable: Iterable[_T], __start: int | None, __stop: int | None, __step: int | None = ...) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class starmap(Iterator[_T], Generic[_T]): def __init__(self, __function: Callable[..., _T], __iterable: Iterable[Iterable[Any]]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class takewhile(Iterator[_T], Generic[_T]): def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... def tee(__iterable: Iterable[_T], __n: int = ...) -> tuple[Iterator[_T], ...]: ... class zip_longest(Iterator[Any]): def __init__(self, *p: Iterable[Any], fillvalue: Any = ...) -> None: ... - def __iter__(self) -> Iterator[Any]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> Any: ... _T3 = TypeVar("_T3") @@ -174,12 +175,12 @@ class product(Iterator[_T_co], Generic[_T_co]): def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[tuple[_T1, ...]]: ... @overload def __new__(cls, *iterables: Iterable[Any], repeat: int = ...) -> product[tuple[Any, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T_co: ... class permutations(Iterator[tuple[_T, ...]], Generic[_T]): def __init__(self, iterable: Iterable[_T], r: int | None = ...) -> None: ... - def __iter__(self) -> Iterator[tuple[_T, ...]]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> tuple[_T, ...]: ... class combinations(Iterator[_T_co], Generic[_T_co]): @@ -193,16 +194,16 @@ class combinations(Iterator[_T_co], Generic[_T_co]): def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ... @overload def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T_co: ... class combinations_with_replacement(Iterator[tuple[_T, ...]], Generic[_T]): def __init__(self, iterable: Iterable[_T], r: int) -> None: ... - def __iter__(self) -> Iterator[tuple[_T, ...]]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> tuple[_T, ...]: ... if sys.version_info >= (3, 10): class pairwise(Iterator[_T_co], Generic[_T_co]): def __new__(cls, __iterable: Iterable[_T]) -> pairwise[tuple[_T, _T]]: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 3e26d1b14f82..8e1a36756398 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,9 +1,11 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Type +from typing import IO, Any, Callable from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder +__all__ = ["dump", "dumps", "load", "loads", "JSONDecoder", "JSONDecodeError", "JSONEncoder"] + def dumps( obj: Any, *, @@ -11,7 +13,7 @@ def dumps( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: None | int | str = ..., separators: tuple[str, str] | None = ..., default: Callable[[Any], Any] | None = ..., @@ -26,7 +28,7 @@ def dump( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: None | int | str = ..., separators: tuple[str, str] | None = ..., default: Callable[[Any], Any] | None = ..., @@ -36,7 +38,7 @@ def dump( def loads( s: str | bytes, *, - cls: Type[JSONDecoder] | None = ..., + cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., @@ -47,7 +49,7 @@ def loads( def load( fp: SupportsRead[str | bytes], *, - cls: Type[JSONDecoder] | None = ..., + cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., diff --git a/mypy/typeshed/stdlib/json/decoder.pyi b/mypy/typeshed/stdlib/json/decoder.pyi index adf09bb4bb7d..866836758545 100644 --- a/mypy/typeshed/stdlib/json/decoder.pyi +++ b/mypy/typeshed/stdlib/json/decoder.pyi @@ -1,5 +1,7 @@ from typing import Any, Callable +__all__ = ["JSONDecoder", "JSONDecodeError"] + class JSONDecodeError(ValueError): msg: str doc: str diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index ac052feeba58..e9a9877d57da 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,6 +1,11 @@ import sys from typing import Sequence +if sys.version_info >= (3, 9): + __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] +else: + __all__ = ["iskeyword", "kwlist"] + def iskeyword(s: str) -> bool: ... kwlist: Sequence[str] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi index a8159dccf037..4ecba031942c 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -4,6 +4,8 @@ from lib2to3.pytree import _NL, _Convert from logging import Logger from typing import IO, Any, Iterable +__all__ = ["Driver", "load_grammar"] + class Driver: grammar: Grammar logger: Logger diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index 77cc6aec3d67..3c3b90c52f7c 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,7 +1,6 @@ -from _typeshed import StrPath -from typing import Optional, TypeVar +from _typeshed import Self, StrPath +from typing import Optional -_P = TypeVar("_P") _Label = tuple[int, Optional[str]] _DFA = list[list[tuple[int, int]]] _DFAS = tuple[_DFA, dict[int, int]] @@ -19,7 +18,7 @@ class Grammar: def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... + def copy(self: Self) -> Self: ... def report(self) -> None: ... opmap_raw: str diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 11680157d199..2628e1223fb4 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -41,6 +41,6 @@ class DFAState: def __init__(self, nfaset: dict[NFAState, Any], final: NFAState) -> None: ... def addarc(self, next: DFAState, label: str) -> None: ... def unifystate(self, old: DFAState, new: DFAState) -> None: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: DFAState) -> bool: ... # type: ignore[override] def generate_grammar(filename: StrPath = ...) -> PgenGrammar: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index 3679caee9314..c1b5a91df9e6 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,6 +1,151 @@ -from lib2to3.pgen2.token import * # noqa +import sys +from lib2to3.pgen2.token import * from typing import Callable, Iterable, Iterator +if sys.version_info >= (3, 8): + __all__ = [ + "AMPER", + "AMPEREQUAL", + "ASYNC", + "AT", + "ATEQUAL", + "AWAIT", + "BACKQUOTE", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COLONEQUAL", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", + "tokenize", + "generate_tokens", + "untokenize", + ] +else: + __all__ = [ + "AMPER", + "AMPEREQUAL", + "ASYNC", + "AT", + "ATEQUAL", + "AWAIT", + "BACKQUOTE", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", + "tokenize", + "generate_tokens", + "untokenize", + ] + _Coord = tuple[int, int] _TokenEater = Callable[[int, str, _Coord, _Coord, str], None] _TokenInfo = tuple[int, str, _Coord, _Coord, str] diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 2ed9a2788d84..b0e61c3a38ac 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,7 +1,7 @@ +from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Union -_P = TypeVar("_P") _NL = Union[Node, Leaf] _Context = tuple[str, int, int] _Results = dict[str, _NL] @@ -19,9 +19,9 @@ class Base: 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 __eq__(self, other: object) -> bool: ... + def _eq(self: Self, other: Self) -> bool: ... + def clone(self: Self) -> Self: ... def post_order(self) -> Iterator[_NL]: ... def pre_order(self) -> Iterator[_NL]: ... def replace(self, new: _NL | list[_NL]) -> None: ... @@ -49,6 +49,7 @@ class Node(Base): 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: ... + def __unicode__(self) -> str: ... class Leaf(Base): lineno: int @@ -58,6 +59,7 @@ class Leaf(Base): def __init__( self, type: int, value: str, context: _Context | None = ..., prefix: str | None = ..., fixers_applied: list[Any] = ... ) -> None: ... + def __unicode__(self) -> str: ... def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index e53d3efea5b2..6b3761f4a0c9 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,5 +1,11 @@ +import sys from typing import Any, Protocol +if sys.version_info >= (3, 9): + __all__ = ["getline", "clearcache", "checkcache", "lazycache"] +else: + __all__ = ["getline", "clearcache", "checkcache"] + _ModuleGlobals = dict[str, Any] _ModuleMetadata = tuple[int, float, list[str], str] diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index f3942102716a..899bf0000a2c 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -1,4 +1,32 @@ import sys +from _typeshed import StrPath + +__all__ = [ + "getlocale", + "getdefaultlocale", + "getpreferredencoding", + "Error", + "setlocale", + "resetlocale", + "localeconv", + "strcoll", + "strxfrm", + "str", + "atof", + "atoi", + "format", + "format_string", + "currency", + "normalize", + "LC_CTYPE", + "LC_COLLATE", + "LC_MESSAGES", + "LC_TIME", + "LC_MONETARY", + "LC_NUMERIC", + "LC_ALL", + "CHAR_MAX", +] # This module defines a function "str()", which is why "str" can't be used # as a type annotation or type alias. @@ -103,6 +131,17 @@ def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... def str(val: float) -> _str: ... +# native gettext functions +# https://docs.python.org/3/library/locale.html#access-to-message-catalogs +# https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Modules/_localemodule.c#L626 +if sys.platform == "linux" or sys.platform == "darwin": + def gettext(__msg: _str) -> _str: ... + def dgettext(__domain: _str | None, __msg: _str) -> _str: ... + def dcgettext(__domain: _str | None, __msg: _str, __category: int) -> _str: ... + def textdomain(__domain: _str | None) -> _str: ... + def bindtextdomain(__domain: _str, __dir: StrPath | None) -> _str: ... + def bind_textdomain_codeset(__domain: _str, __codeset: _str | None) -> _str | None: ... + locale_alias: dict[_str, _str] # undocumented locale_encoding_alias: dict[_str, _str] # undocumented windows_locale: dict[int, _str] # undocumented diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 442e79a9c6f3..c860938c31ea 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -6,10 +6,55 @@ from io import TextIOWrapper from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, Type, TypeVar, Union, overload +from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, TypeVar, Union, overload from typing_extensions import Literal -_SysExcInfoType = Union[tuple[Type[BaseException], BaseException, Optional[TracebackType]], tuple[None, None, None]] +__all__ = [ + "BASIC_FORMAT", + "BufferingFormatter", + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "FileHandler", + "Filter", + "Formatter", + "Handler", + "INFO", + "LogRecord", + "Logger", + "LoggerAdapter", + "NOTSET", + "NullHandler", + "StreamHandler", + "WARN", + "WARNING", + "addLevelName", + "basicConfig", + "captureWarnings", + "critical", + "debug", + "disable", + "error", + "exception", + "fatal", + "getLevelName", + "getLogger", + "getLoggerClass", + "info", + "log", + "makeLogRecord", + "setLoggerClass", + "shutdown", + "warn", + "warning", + "getLogRecordFactory", + "setLogRecordFactory", + "lastResort", + "raiseExceptions", +] + +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, Optional[TracebackType]], tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] _ArgsType = Union[tuple[object, ...], Mapping[str, object]] _FilterType = Union[Filter, Callable[[LogRecord], int]] @@ -39,11 +84,11 @@ class Manager: # undocumented disable: int emittedNoHandlerWarning: bool loggerDict: dict[str, Logger | PlaceHolder] - loggerClass: Type[Logger] | None + loggerClass: type[Logger] | None logRecordFactory: Callable[..., LogRecord] | None def __init__(self, rootnode: RootLogger) -> None: ... def getLogger(self, name: str) -> Logger: ... - def setLoggerClass(self, klass: Type[Logger]) -> None: ... + def setLoggerClass(self, klass: type[Logger]) -> None: ... def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ... class Logger(Filterer): @@ -227,6 +272,7 @@ class Logger(Filterer): def findCaller(self, stack_info: bool = ..., stacklevel: int = ...) -> tuple[str, int, str, str | None]: ... else: def findCaller(self, stack_info: bool = ...) -> tuple[str, int, str, str | None]: ... + def handle(self, record: LogRecord) -> None: ... def makeRecord( self, @@ -301,6 +347,7 @@ class Formatter: ) -> None: ... else: def __init__(self, fmt: str | None = ..., datefmt: str | None = ..., style: _FormatStyle = ...) -> None: ... + def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: str | None = ...) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... @@ -372,6 +419,7 @@ class LoggerAdapter(Generic[_L]): else: extra: Mapping[str, object] def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ... + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... if sys.version_info >= (3, 8): def debug( @@ -529,6 +577,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = ..., **kwargs: object, ) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... def getEffectiveLevel(self) -> int: ... def setLevel(self, level: _Level) -> None: ... @@ -546,7 +595,7 @@ class LoggerAdapter(Generic[_L]): def name(self) -> str: ... # undocumented def getLogger(name: str | None = ...) -> Logger: ... -def getLoggerClass() -> Type[Logger]: ... +def getLoggerClass() -> type[Logger]: ... def getLogRecordFactory() -> Callable[..., LogRecord]: ... if sys.version_info >= (3, 8): @@ -703,7 +752,7 @@ else: ) -> None: ... def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented -def setLoggerClass(klass: Type[Logger]) -> None: ... +def setLoggerClass(klass: type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... @@ -733,6 +782,7 @@ class FileHandler(StreamHandler[TextIOWrapper]): ) -> None: ... else: def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... + def _open(self) -> TextIOWrapper: ... # undocumented class NullHandler(Handler): ... @@ -760,9 +810,11 @@ class PercentStyle: # undocumented def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = ...) -> None: ... else: def __init__(self, fmt: str) -> None: ... + def usesTime(self) -> bool: ... if sys.version_info >= (3, 8): def validate(self) -> None: ... + def format(self, record: Any) -> str: ... class StrFormatStyle(PercentStyle): # undocumented diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 50d6d0583556..06cddd94fc69 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -29,6 +29,7 @@ class WatchedFileHandler(FileHandler): ) -> None: ... else: def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... + def _statstream(self) -> None: ... # undocumented def reopenIfNeeded(self) -> None: ... @@ -41,6 +42,7 @@ class BaseRotatingHandler(FileHandler): ) -> None: ... else: def __init__(self, filename: StrPath, mode: str, encoding: str | None = ..., delay: bool = ...) -> None: ... + def rotation_filename(self, default_name: str) -> str: ... def rotate(self, source: str, dest: str) -> None: ... @@ -68,6 +70,7 @@ class RotatingFileHandler(BaseRotatingHandler): encoding: str | None = ..., delay: bool = ..., ) -> None: ... + def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented @@ -106,6 +109,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): utc: bool = ..., atTime: datetime.datetime | None = ..., ) -> None: ... + def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented def computeRollover(self, currentTime: int) -> int: ... # undocumented @@ -250,11 +254,12 @@ class QueueHandler(Handler): else: queue: Queue[Any] # undocumented def __init__(self, queue: Queue[Any]) -> None: ... + def prepare(self, record: LogRecord) -> Any: ... def enqueue(self, record: LogRecord) -> None: ... class QueueListener: - handlers: tuple[Handler] # undocumented + handlers: tuple[Handler, ...] # undocumented respect_handler_level: bool # undocumented if sys.version_info >= (3, 7): queue: SimpleQueue[Any] | Queue[Any] # undocumented @@ -264,6 +269,7 @@ class QueueListener: else: queue: Queue[Any] # undocumented def __init__(self, queue: Queue[Any], *handlers: Handler, respect_handler_level: bool = ...) -> 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 e4bd977d7eab..c469c218abcb 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -3,6 +3,45 @@ from _typeshed import ReadableBuffer, Self, StrOrBytesPath from typing import IO, Any, Mapping, Sequence, TextIO, Union, overload from typing_extensions import Literal, final +__all__ = [ + "CHECK_NONE", + "CHECK_CRC32", + "CHECK_CRC64", + "CHECK_SHA256", + "CHECK_ID_MAX", + "CHECK_UNKNOWN", + "FILTER_LZMA1", + "FILTER_LZMA2", + "FILTER_DELTA", + "FILTER_X86", + "FILTER_IA64", + "FILTER_ARM", + "FILTER_ARMTHUMB", + "FILTER_POWERPC", + "FILTER_SPARC", + "FORMAT_AUTO", + "FORMAT_XZ", + "FORMAT_ALONE", + "FORMAT_RAW", + "MF_HC3", + "MF_HC4", + "MF_BT2", + "MF_BT3", + "MF_BT4", + "MODE_FAST", + "MODE_NORMAL", + "PRESET_DEFAULT", + "PRESET_EXTREME", + "LZMACompressor", + "LZMADecompressor", + "LZMAFile", + "LZMAError", + "open", + "compress", + "decompress", + "is_check_supported", +] + _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] _OpenTextWritingMode = Literal["wt", "xt", "at"] @@ -10,34 +49,34 @@ _PathOrFile = Union[StrOrBytesPath, IO[bytes]] _FilterChain = Sequence[Mapping[str, Any]] -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 +FORMAT_AUTO: Literal[0] +FORMAT_XZ: Literal[1] +FORMAT_ALONE: Literal[2] +FORMAT_RAW: Literal[3] +CHECK_NONE: Literal[0] +CHECK_CRC32: Literal[1] +CHECK_CRC64: Literal[4] +CHECK_SHA256: Literal[10] +CHECK_ID_MAX: Literal[15] +CHECK_UNKNOWN: Literal[16] +FILTER_LZMA1: int # v big number +FILTER_LZMA2: Literal[33] +FILTER_DELTA: Literal[3] +FILTER_X86: Literal[4] +FILTER_IA64: Literal[6] +FILTER_ARM: Literal[7] +FILTER_ARMTHUMB: Literal[8] +FILTER_SPARC: Literal[9] +FILTER_POWERPC: Literal[5] +MF_HC3: Literal[3] +MF_HC4: Literal[4] +MF_BT2: Literal[18] +MF_BT3: Literal[19] +MF_BT4: Literal[20] +MODE_FAST: Literal[1] +MODE_NORMAL: Literal[2] +PRESET_DEFAULT: Literal[6] +PRESET_EXTREME: int # v big number # from _lzma.c @final diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index ffd9c3005cec..3fafd8891840 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -1,28 +1,34 @@ import email.message import sys from _typeshed import Self, StrOrBytesPath +from abc import ABCMeta, abstractmethod from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = [ + "Mailbox", + "Maildir", + "mbox", + "MH", + "Babyl", + "MMDF", + "Message", + "MaildirMessage", + "mboxMessage", + "MHMessage", + "BabylMessage", + "MMDFMessage", + "Error", + "NoSuchMailboxError", + "NotEmptyError", + "ExternalClashError", + "FormatError", +] + _T = TypeVar("_T") _MessageT = TypeVar("_MessageT", bound=Message) _MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] @@ -42,21 +48,28 @@ class Mailbox(Generic[_MessageT]): def __init__( self, path: StrOrBytesPath, factory: Callable[[IO[Any]], _MessageT] | None = ..., create: bool = ... ) -> None: ... + @abstractmethod def add(self, message: _MessageData) -> str: ... + @abstractmethod def remove(self, key: str) -> None: ... def __delitem__(self, key: str) -> None: ... def discard(self, key: str) -> None: ... + @abstractmethod def __setitem__(self, key: str, message: _MessageData) -> None: ... @overload def get(self, key: str, default: None = ...) -> _MessageT | None: ... @overload def get(self, key: str, default: _T) -> _MessageT | _T: ... def __getitem__(self, key: str) -> _MessageT: ... + @abstractmethod def get_message(self, key: str) -> _MessageT: ... def get_string(self, key: str) -> str: ... + @abstractmethod 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 + @abstractmethod def get_file(self, key: str) -> Any: ... + @abstractmethod def iterkeys(self) -> Iterator[str]: ... def keys(self) -> list[str]: ... def itervalues(self) -> Iterator[_MessageT]: ... @@ -64,7 +77,9 @@ class Mailbox(Generic[_MessageT]): def values(self) -> list[_MessageT]: ... def iteritems(self) -> Iterator[tuple[str, _MessageT]]: ... def items(self) -> list[tuple[str, _MessageT]]: ... + @abstractmethod def __contains__(self, key: str) -> bool: ... + @abstractmethod def __len__(self) -> int: ... def clear(self) -> None: ... @overload @@ -73,9 +88,13 @@ class Mailbox(Generic[_MessageT]): def pop(self, key: str, default: _T = ...) -> _MessageT | _T: ... def popitem(self) -> tuple[str, _MessageT]: ... def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = ...) -> None: ... + @abstractmethod def flush(self) -> None: ... + @abstractmethod def lock(self) -> None: ... + @abstractmethod def unlock(self) -> None: ... + @abstractmethod def close(self) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -86,7 +105,19 @@ class Maildir(Mailbox[MaildirMessage]): def __init__( self, dirname: StrOrBytesPath, factory: Callable[[IO[Any]], MaildirMessage] | None = ..., create: bool = ... ) -> None: ... + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def get_message(self, key: str) -> MaildirMessage: ... + def get_bytes(self, key: str) -> bytes: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... def list_folders(self) -> list[str]: ... def get_folder(self, folder: str) -> Maildir: ... def add_folder(self, folder: str) -> Maildir: ... @@ -94,9 +125,20 @@ class Maildir(Mailbox[MaildirMessage]): def clean(self) -> None: ... def next(self) -> str | None: ... -class _singlefileMailbox(Mailbox[_MessageT]): ... +class _singlefileMailbox(Mailbox[_MessageT], metaclass=ABCMeta): + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... class _mboxMMDF(_singlefileMailbox[_MessageT]): + def get_message(self, key: str) -> _MessageT: ... def get_file(self, key: str, from_: bool = ...) -> _PartialFile[bytes]: ... def get_bytes(self, key: str, from_: bool = ...) -> bytes: ... def get_string(self, key: str, from_: bool = ...) -> str: ... @@ -115,7 +157,19 @@ class MH(Mailbox[MHMessage]): def __init__( self, path: StrOrBytesPath, factory: Callable[[IO[Any]], MHMessage] | None = ..., create: bool = ... ) -> None: ... + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def get_message(self, key: str) -> MHMessage: ... + def get_bytes(self, key: str) -> bytes: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... def list_folders(self) -> list[str]: ... def get_folder(self, folder: StrOrBytesPath) -> MH: ... def add_folder(self, folder: StrOrBytesPath) -> MH: ... @@ -128,6 +182,8 @@ class Babyl(_singlefileMailbox[BabylMessage]): def __init__( self, path: StrOrBytesPath, factory: Callable[[IO[Any]], BabylMessage] | None = ..., create: bool = ... ) -> None: ... + def get_message(self, key: str) -> BabylMessage: ... + def get_bytes(self, key: str) -> bytes: ... def get_file(self, key: str) -> IO[bytes]: ... def get_labels(self) -> list[str]: ... @@ -184,7 +240,7 @@ class _ProxyFile(Generic[AnyStr]): def seek(self, offset: int, whence: int = ...) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index 56218d1370fe..7bf2ebd1bdfe 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -2,6 +2,8 @@ from typing import Mapping, Sequence, Union _Cap = dict[str, Union[str, int]] +__all__ = ["getcaps", "findmatch"] + def findmatch( caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... ) -> tuple[str | None, _Cap | None]: ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index d5e6f99dfa68..2218f68174d1 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -41,6 +41,10 @@ if sys.version_info >= (3, 8): def erf(__x: _SupportsFloatOrIndex) -> float: ... def erfc(__x: _SupportsFloatOrIndex) -> float: ... def exp(__x: _SupportsFloatOrIndex) -> float: ... + +if sys.version_info >= (3, 11): + def exp2(__x: _SupportsFloatOrIndex) -> float: ... + def expm1(__x: _SupportsFloatOrIndex) -> float: ... def fabs(__x: _SupportsFloatOrIndex) -> float: ... diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index 8f51c1580eec..e51b7cdf37bd 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -2,6 +2,22 @@ import sys from _typeshed import StrPath from typing import IO, Sequence +__all__ = [ + "knownfiles", + "inited", + "MimeTypes", + "guess_type", + "guess_all_extensions", + "guess_extension", + "add_type", + "init", + "read_mime_types", + "suffix_map", + "encodings_map", + "types_map", + "common_types", +] + if sys.version_info >= (3, 8): def guess_type(url: StrPath, strict: bool = ...) -> tuple[str | None, str | None]: ... @@ -32,6 +48,7 @@ class MimeTypes: def guess_type(self, url: StrPath, strict: bool = ...) -> tuple[str | None, str | None]: ... else: def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... + 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: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index b79ab92f0c87..744888172479 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,6 +1,5 @@ import sys -from _typeshed import ReadableBuffer -from contextlib import AbstractContextManager +from _typeshed import ReadableBuffer, Self from typing import Iterable, Iterator, NoReturn, Sized, overload ACCESS_DEFAULT: int @@ -13,6 +12,8 @@ ALLOCATIONGRANULARITY: int if sys.platform == "linux": MAP_DENYWRITE: int MAP_EXECUTABLE: int + if sys.version_info >= (3, 10): + MAP_POPULATE: int if sys.platform != "win32": MAP_ANON: int @@ -25,18 +26,20 @@ if sys.platform != "win32": PAGESIZE: int -class mmap(AbstractContextManager[mmap], Iterable[int], Sized): +class mmap(Iterable[int], Sized): if sys.platform == "win32": def __init__(self, fileno: int, length: int, tagname: str | None = ..., 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) -> int: ... def readline(self) -> bytes: ... @@ -49,22 +52,25 @@ class mmap(AbstractContextManager[mmap], Iterable[int], 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: int | None = ...) -> bytes: ... def write(self, bytes: ReadableBuffer) -> int: ... @overload - def __getitem__(self, index: int) -> int: ... + def __getitem__(self, __index: int) -> int: ... @overload - def __getitem__(self, index: slice) -> bytes: ... - def __delitem__(self, index: int | slice) -> NoReturn: ... + def __getitem__(self, __index: slice) -> bytes: ... + def __delitem__(self, __index: int | slice) -> NoReturn: ... @overload - def __setitem__(self, index: int, object: int) -> None: ... + def __setitem__(self, __index: int, __object: int) -> None: ... @overload - def __setitem__(self, index: slice, object: ReadableBuffer) -> None: ... + def __setitem__(self, __index: slice, __object: ReadableBuffer) -> 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[int]: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, *args: object) -> None: ... if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_NORMAL: int diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index 3e7694ccffc9..9efe032cfd29 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -19,7 +19,6 @@ def ReplacePackage(oldname: str, newname: str) -> None: ... class Module: # undocumented def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... class ModuleFinder: @@ -47,6 +46,7 @@ class ModuleFinder: 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 diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index b5866492a097..c512489be34d 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,10 +1,16 @@ import sys from types import ModuleType -from typing import Any, Container, Iterable, Sequence, Type +from typing import Any, Container, Iterable, Sequence from typing_extensions import Literal if sys.platform == "win32": - from _msi import _Database + from _msi import ( + CreateRecord as CreateRecord, + FCICreate as FCICreate, + OpenDatabase as OpenDatabase, + UuidCreate as UuidCreate, + _Database, + ) AMD64: bool if sys.version_info < (3, 7): @@ -22,6 +28,7 @@ if sys.platform == "win32": type_nullable: Literal[0x1000] type_key: Literal[0x2000] knownbits: Literal[0x3FFF] + class Table: name: str @@ -30,12 +37,14 @@ if sys.platform == "win32": 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, str | None, int]], action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., + seqno: int | type[_Unspecified] = ..., + cond: 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: ... @@ -45,6 +54,7 @@ if sys.platform == "win32": def add_tables(db: _Database, module: ModuleType) -> None: ... def make_id(str: str) -> str: ... def gen_uuid() -> str: ... + class CAB: name: str @@ -56,6 +66,7 @@ if sys.platform == "win32": 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 @@ -91,11 +102,12 @@ if sys.platform == "win32": def add_file(self, file: str, src: str | None = ..., version: str | None = ..., language: str | None = ...) -> str: ... def glob(self, pattern: str, exclude: Container[str] | None = ...) -> 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 @@ -112,6 +124,7 @@ if sys.platform == "win32": attributes: int = ..., ) -> None: ... def set_current(self) -> None: ... + class Control: dlg: Dialog @@ -120,12 +133,14 @@ if sys.platform == "win32": def event(self, event: str, argument: str, condition: str = ..., ordering: int | None = ...) -> 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: str | None = ...) -> None: ... + class Dialog: db: _Database diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index 0441ed8acd24..35841c62f67a 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -1,12 +1,13 @@ import sys +from typing_extensions import Literal # 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 + LK_UNLCK: Literal[0] + LK_LOCK: Literal[1] + LK_NBLCK: Literal[2] + LK_RLCK: Literal[3] + LK_NBRLCK: Literal[4] def locking(__fd: int, __mode: int, __nbytes: int) -> None: ... def setmode(__fd: int, __mode: int) -> int: ... def open_osfhandle(__handle: int, __flags: int) -> int: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 000fed79f3e4..3f489ca43dba 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable, Iterable from logging import Logger -from multiprocessing import connection, context, pool, synchronize +from multiprocessing import connection, context, pool, reduction as reducer, synchronize from multiprocessing.context import ( AuthenticationError as AuthenticationError, BaseContext, @@ -29,6 +29,86 @@ if sys.version_info >= (3, 8): if sys.platform != "win32": from multiprocessing.context import ForkContext, ForkServerContext +if sys.version_info >= (3, 8): + __all__ = [ + "Array", + "AuthenticationError", + "Barrier", + "BoundedSemaphore", + "BufferTooShort", + "Condition", + "Event", + "JoinableQueue", + "Lock", + "Manager", + "Pipe", + "Pool", + "Process", + "ProcessError", + "Queue", + "RLock", + "RawArray", + "RawValue", + "Semaphore", + "SimpleQueue", + "TimeoutError", + "Value", + "active_children", + "allow_connection_pickling", + "cpu_count", + "current_process", + "freeze_support", + "get_all_start_methods", + "get_context", + "get_logger", + "get_start_method", + "parent_process", + "log_to_stderr", + "reducer", + "set_executable", + "set_forkserver_preload", + "set_start_method", + ] +else: + __all__ = [ + "Array", + "AuthenticationError", + "Barrier", + "BoundedSemaphore", + "BufferTooShort", + "Condition", + "Event", + "JoinableQueue", + "Lock", + "Manager", + "Pipe", + "Pool", + "Process", + "ProcessError", + "Queue", + "RLock", + "RawArray", + "RawValue", + "Semaphore", + "SimpleQueue", + "TimeoutError", + "Value", + "active_children", + "allow_connection_pickling", + "cpu_count", + "current_process", + "freeze_support", + "get_all_start_methods", + "get_context", + "get_logger", + "get_start_method", + "log_to_stderr", + "reducer", + "set_executable", + "set_forkserver_preload", + "set_start_method", + ] + # The following type aliases can be used to annotate the return values of # the corresponding functions. They are not defined at runtime. # diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 56db4594edc0..5db6fa4cda7e 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -2,19 +2,16 @@ import socket import sys import types from _typeshed import Self -from typing import Any, Iterable, Type, Union +from typing import Any, Iterable, Union +from typing_extensions import SupportsIndex -if sys.version_info >= (3, 8): - from typing import SupportsIndex +__all__ = ["Client", "Listener", "Pipe", "wait"] # 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: ... + def __init__(self, handle: SupportsIndex, readable: bool = ..., writable: bool = ...) -> None: ... @property def closed(self) -> bool: ... # undocumented @property @@ -31,7 +28,7 @@ class _ConnectionBase: def poll(self, timeout: float | None = ...) -> bool: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... class Connection(_ConnectionBase): ... @@ -51,7 +48,7 @@ class Listener: def last_accepted(self) -> _Address | None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 83e1b7884efc..db8e6216b6ad 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -8,9 +8,14 @@ from multiprocessing import queues, synchronize from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, Type, TypeVar, Union, overload +from typing import Any, ClassVar, TypeVar, Union, overload from typing_extensions import Literal +if sys.version_info >= (3, 8): + __all__ = () +else: + __all__: list[str] = [] + _LockLike = Union[synchronize.Lock, synchronize.RLock] _CT = TypeVar("_CT", bound=_CData) @@ -20,11 +25,11 @@ class TimeoutError(ProcessError): ... class AuthenticationError(ProcessError): ... class BaseContext: - Process: Type[BaseProcess] - ProcessError: Type[Exception] - BufferTooShort: Type[Exception] - TimeoutError: Type[Exception] - AuthenticationError: Type[Exception] + 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). @@ -33,6 +38,7 @@ class BaseContext: if sys.version_info >= (3, 8): @staticmethod def parent_process() -> BaseProcess | None: ... + @staticmethod def active_children() -> list[BaseProcess]: ... def cpu_count(self) -> int: ... @@ -60,26 +66,26 @@ class BaseContext: maxtasksperchild: int | None = ..., ) -> _Pool: ... @overload - def RawValue(self, typecode_or_type: Type[_CT], *args: Any) -> _CT: ... + def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... @overload - def RawArray(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... + def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[_CT]: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[_CT]: ... @overload def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[Any]: ... @overload - def Value(self, typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ...) -> Any: ... + def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = ...) -> Any: ... @overload - def Array(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... + def Array(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... @overload def Array( - self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike + self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike ) -> SynchronizedArray[_CT]: ... @overload def Array( @@ -87,7 +93,7 @@ class BaseContext: ) -> SynchronizedArray[Any]: ... @overload def Array( - self, typecode_or_type: str | Type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ... + self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ... ) -> Any: ... def freeze_support(self) -> None: ... def get_logger(self) -> Logger: ... @@ -113,6 +119,7 @@ class BaseContext: 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: str | None, force: bool = ...) -> None: ... @property @@ -127,11 +134,13 @@ class Process(BaseProcess): def _Popen(process_obj: BaseProcess) -> DefaultContext: ... class DefaultContext(BaseContext): - Process: Type[multiprocessing.Process] + Process: type[multiprocessing.Process] def __init__(self, context: BaseContext) -> None: ... def set_start_method(self, method: str | None, force: bool = ...) -> None: ... def get_start_method(self, allow_none: bool = ...) -> str: ... def get_all_start_methods(self) -> list[str]: ... + if sys.version_info < (3, 8): + __all__: ClassVar[list[str]] _default_context: DefaultContext @@ -140,32 +149,38 @@ if sys.platform != "win32": _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] + Process: type[ForkProcess] + class SpawnContext(BaseContext): _name: str - Process: Type[SpawnProcess] + Process: type[SpawnProcess] + class ForkServerContext(BaseContext): _name: str - Process: Type[ForkServerProcess] + 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] + Process: type[SpawnProcess] def _force_start_method(method: str) -> None: ... def get_spawning_popen() -> Any | None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi index b4d1c8404d8d..48f42999866a 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi @@ -3,6 +3,28 @@ import threading import weakref from queue import Queue as Queue from typing import Any, Callable, Iterable, Mapping, Sequence +from typing_extensions import Literal + +from .connection import Pipe as Pipe + +__all__ = [ + "Process", + "current_process", + "active_children", + "freeze_support", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Condition", + "Event", + "Barrier", + "Queue", + "Manager", + "Pipe", + "Pool", + "JoinableQueue", +] JoinableQueue = Queue Barrier = threading.Barrier @@ -18,7 +40,8 @@ class DummyProcess(threading.Thread): _parent: threading.Thread _pid: None _start_called: int - exitcode: int | None + @property + def exitcode(self) -> Literal[0] | None: ... def __init__( self, group: Any = ..., diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi index 9500a38364f0..c61617cd91d4 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi @@ -1,7 +1,9 @@ from _typeshed import Self from queue import Queue from types import TracebackType -from typing import Any, Type, Union +from typing import Any, Union + +__all__ = ["Client", "Listener", "Pipe"] families: list[None] @@ -16,7 +18,7 @@ class Connection: send_bytes: Any def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def __init__(self, _in: Any, _out: Any) -> None: ... def close(self) -> None: ... @@ -28,7 +30,7 @@ class Listener: def address(self) -> Queue[Any] | None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def __init__(self, address: _Address | None = ..., family: int | None = ..., backlog: int = ...) -> None: ... def accept(self) -> Connection: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 79310614efc1..fef3e1e21eb2 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -1,7 +1,8 @@ import queue import sys import threading -from contextlib import AbstractContextManager +from _typeshed import Self +from types import TracebackType from typing import Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar from .connection import Connection @@ -10,8 +11,12 @@ from .context import BaseContext if sys.version_info >= (3, 8): from .shared_memory import _SLT, ShareableList, SharedMemory + __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] + _SharedMemory = SharedMemory _ShareableList = ShareableList +else: + __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token"] if sys.version_info >= (3, 9): from types import GenericAlias @@ -32,7 +37,6 @@ class Token: address: tuple[str | bytes, int] id: str | bytes | int | None def __init__(self, typeid: bytes | str | None, address: tuple[str | bytes, int], id: str | bytes | int | None) -> None: ... - def __repr__(self) -> str: ... def __getstate__(self) -> tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]: ... def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ... @@ -70,7 +74,7 @@ class Server: def serve_forever(self) -> None: ... def accept_connection(self, c: Connection, name: str) -> None: ... -class BaseManager(AbstractContextManager[BaseManager]): +class BaseManager: def __init__( self, address: Any | None = ..., authkey: bytes | None = ..., serializer: str = ..., ctx: BaseContext | None = ... ) -> None: ... @@ -91,12 +95,14 @@ class BaseManager(AbstractContextManager[BaseManager]): method_to_typeid: Mapping[str, str] | None = ..., create_method: bool = ..., ) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, exc_type: type[BaseException], exc_val: BaseException, exc_tb: TracebackType) -> None: ... # Conflicts with method names _dict = dict _list = list -class SyncManager(BaseManager, AbstractContextManager[SyncManager]): +class SyncManager(BaseManager): def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... def Condition(self, lock: Any = ...) -> threading.Condition: ... def Event(self) -> threading.Event: ... @@ -114,6 +120,7 @@ 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: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 518e4b7364d7..5e38e0161834 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import Self -from contextlib import AbstractContextManager +from types import TracebackType from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, TypeVar from typing_extensions import Literal @@ -9,7 +9,6 @@ if sys.version_info >= (3, 9): __all__ = ["Pool", "ThreadPool"] -_PT = TypeVar("_PT", bound=Pool) _S = TypeVar("_S") _T = TypeVar("_T") @@ -25,6 +24,7 @@ class ApplyResult(Generic[_T]): callback: Callable[[_T], None] | None, error_callback: Callable[[BaseException], None] | None, ) -> None: ... + def get(self, timeout: float | None = ...) -> _T: ... def wait(self, timeout: float | None = ...) -> None: ... def ready(self) -> bool: ... @@ -60,13 +60,14 @@ class IMapIterator(Iterator[_T]): def __init__(self, pool: Pool) -> None: ... else: def __init__(self, cache: dict[int, IMapIterator[Any]]) -> None: ... - def __iter__(self: _S) -> _S: ... + + def __iter__(self: Self) -> Self: ... def next(self, timeout: float | None = ...) -> _T: ... def __next__(self, timeout: float | None = ...) -> _T: ... class IMapUnorderedIterator(IMapIterator[_T]): ... -class Pool(AbstractContextManager[Pool]): +class Pool: def __init__( self, processes: int | None = ..., @@ -110,8 +111,11 @@ class Pool(AbstractContextManager[Pool]): def terminate(self) -> None: ... def join(self) -> None: ... def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... -class ThreadPool(Pool, AbstractContextManager[ThreadPool]): +class ThreadPool(Pool): def __init__( self, processes: int | None = ..., initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi index 4746c78b1b4d..f4464c08c9bd 100644 --- a/mypy/typeshed/stdlib/multiprocessing/process.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/process.pyi @@ -1,6 +1,11 @@ import sys from typing import Any, Callable, Mapping +if sys.version_info >= (3, 8): + __all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] +else: + __all__ = ["BaseProcess", "current_process", "active_children"] + class BaseProcess: name: str daemon: bool @@ -22,6 +27,7 @@ class BaseProcess: if sys.version_info >= (3, 7): def kill(self) -> None: ... def close(self) -> None: ... + def join(self, timeout: float | None = ...) -> None: ... def is_alive(self) -> bool: ... @property diff --git a/mypy/typeshed/stdlib/multiprocessing/queues.pyi b/mypy/typeshed/stdlib/multiprocessing/queues.pyi index 1c9d76917292..1d31fa694c45 100644 --- a/mypy/typeshed/stdlib/multiprocessing/queues.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/queues.pyi @@ -5,6 +5,8 @@ from typing import Any, Generic, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ["Queue", "SimpleQueue", "JoinableQueue"] + _T = TypeVar("_T") class Queue(queue.Queue[_T]): @@ -30,6 +32,7 @@ class SimpleQueue(Generic[_T]): def __init__(self, *, ctx: Any = ...) -> None: ... if sys.version_info >= (3, 9): def close(self) -> None: ... + def empty(self) -> bool: ... def get(self) -> _T: ... def put(self, item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi new file mode 100644 index 000000000000..9e7387da64a5 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi @@ -0,0 +1,84 @@ +import pickle +import sys +from abc import ABCMeta +from copyreg import _DispatchTableType +from typing import Any +from typing_extensions import Literal + +if sys.platform == "win32": + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupHandle", "duplicate", "steal_handle"] +else: + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupFd", "sendfds", "recvfds"] + +class ForkingPickler(pickle.Pickler): + dispatch_table: _DispatchTableType + def __init__(self, *args) -> None: ... + @classmethod + def register(cls, type, reduce) -> None: ... + @classmethod + def dumps(cls, obj, protocol: Any | None = ...): ... + loads = pickle.loads + +register = ForkingPickler.register + +def dump(obj, file, protocol: Any | None = ...) -> None: ... + +if sys.platform == "win32": + if sys.version_info >= (3, 8): + def duplicate(handle, target_process: Any | None = ..., inheritable: bool = ..., *, source_process: Any | None = ...): ... + else: + def duplicate(handle, target_process: Any | None = ..., inheritable: bool = ...): ... + + def steal_handle(source_pid, handle): ... + def send_handle(conn, handle, destination_pid) -> None: ... + def recv_handle(conn): ... + + class DupHandle: + def __init__(self, handle, access, pid: Any | None = ...) -> None: ... + def detach(self): ... + +else: + if sys.platform == "darwin": + ACKNOWLEDGE: Literal[True] + else: + ACKNOWLEDGE: Literal[False] + + def recvfds(sock, size): ... + def send_handle(conn, handle, destination_pid) -> None: ... + def recv_handle(conn) -> None: ... + def sendfds(sock, fds) -> None: ... + def DupFd(fd): ... + +# These aliases are to work around pyright complaints. +# Pyright doesn't like it when a class object is defined as an alias +# of a global object with the same name. +_ForkingPickler = ForkingPickler +_register = register +_dump = dump +_send_handle = send_handle +_recv_handle = recv_handle + +if sys.platform == "win32": + _steal_handle = steal_handle + _duplicate = duplicate + _DupHandle = DupHandle +else: + _sendfds = sendfds + _recvfds = recvfds + _DupFd = DupFd + +class AbstractReducer(metaclass=ABCMeta): + ForkingPickler = _ForkingPickler + register = _register + dump = _dump + send_handle = _send_handle + recv_handle = _recv_handle + if sys.platform == "win32": + steal_handle = _steal_handle + duplicate = _duplicate + DupHandle = _DupHandle + else: + sendfds = _sendfds + recvfds = _recvfds + DupFd = _DupFd + def __init__(self, *args) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index 1b51da38bc43..a4c4fd071c5f 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,33 +1,35 @@ import sys +from _typeshed import Self from typing import Any, Generic, Iterable, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias -_S = TypeVar("_S") +__all__ = ["SharedMemory", "ShareableList"] + _SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) -if sys.version_info >= (3, 8): - class SharedMemory: - def __init__(self, name: str | None = ..., 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: Iterable[_SLT] | None = ..., *, name: str | None = ...) -> 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: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... +class SharedMemory: + def __init__(self, name: str | None = ..., 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: Iterable[_SLT] | None = ..., *, name: str | None = ...) -> None: ... + def __getitem__(self, position: int) -> _SLT: ... + def __setitem__(self, position: int, value: _SLT) -> None: ... + def __reduce__(self: Self) -> tuple[Self, tuple[_SLT, ...]]: ... + def __len__(self) -> int: ... + @property + 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 index bd9d8f089875..50d5a3d71973 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -3,25 +3,27 @@ from collections.abc import Callable, Iterable, Sequence from ctypes import _CData, _SimpleCData, c_char from multiprocessing.context import BaseContext from multiprocessing.synchronize import _LockLike -from typing import Any, Generic, Protocol, Type, TypeVar, overload +from typing import Any, Generic, Protocol, TypeVar, overload from typing_extensions import Literal +__all__ = ["RawValue", "RawArray", "Value", "Array", "copy", "synchronized"] + _T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) @overload -def RawValue(typecode_or_type: Type[_CT], *args: Any) -> _CT: ... +def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(typecode_or_type: str, *args: Any) -> Any: ... @overload -def RawArray(typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... +def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload -def Value(typecode_or_type: Type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = ...) -> _CT: ... +def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = ...) -> _CT: ... @overload def Value( - typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... + typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... ) -> SynchronizedBase[_CT]: ... @overload def Value( @@ -29,15 +31,15 @@ def Value( ) -> SynchronizedBase[Any]: ... @overload def Value( - typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ..., ctx: BaseContext | None = ... + typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = ..., ctx: BaseContext | None = ... ) -> Any: ... @overload def Array( - typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = ... + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = ... ) -> _CT: ... @overload def Array( - typecode_or_type: Type[_CT], + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike, @@ -53,7 +55,7 @@ def Array( ) -> SynchronizedArray[Any]: ... @overload def Array( - typecode_or_type: str | Type[_CData], + typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ..., @@ -76,7 +78,7 @@ class SynchronizedBase(Generic[_CT]): acquire: _AcquireFunc release: Callable[[], None] def __init__(self, obj: Any, lock: _LockLike | None = ..., ctx: Any | None = ...) -> None: ... - def __reduce__(self) -> tuple[Callable[..., Any], tuple[Any, _LockLike]]: ... + def __reduce__(self) -> tuple[Callable[[Any, _LockLike], SynchronizedBase[Any]], tuple[Any, _LockLike]]: ... def get_obj(self) -> _CT: ... def get_lock(self) -> _LockLike: ... def __enter__(self) -> bool: ... @@ -88,7 +90,7 @@ class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): class SynchronizedArray(SynchronizedBase[ctypes.Array[_CT]], Generic[_CT]): def __len__(self) -> int: ... def __getitem__(self, i: int) -> _CT: ... - def __setitem__(self, i: int, o: _CT) -> None: ... + def __setitem__(self, i: int, value: _CT) -> None: ... def __getslice__(self, start: int, stop: int) -> list[_CT]: ... def __setslice__(self, start: int, stop: int, values: Iterable[_CT]) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi index 34c7322e0d46..4f981ea467c4 100644 --- a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi @@ -1,6 +1,16 @@ from types import ModuleType from typing import Any, Mapping, Sequence +__all__ = [ + "_main", + "freeze_support", + "set_executable", + "get_executable", + "get_preparation_data", + "get_command_line", + "import_main_path", +] + WINEXE: bool WINSERVICE: bool diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index c32c9aafe9a4..cb576abcc815 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -2,8 +2,11 @@ import sys import threading from contextlib import AbstractContextManager from multiprocessing.context import BaseContext +from types import TracebackType from typing import Any, Callable, Union +__all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] + _LockLike = Union[Lock, RLock] class Barrier(threading.Barrier): @@ -20,13 +23,17 @@ class Condition(AbstractContextManager[bool]): def notify(self, n: int = ...) -> None: ... else: def notify(self) -> None: ... + def notify_all(self) -> None: ... def wait(self, timeout: float | None = ...) -> bool: ... def wait_for(self, predicate: Callable[[], bool], timeout: float | None = ...) -> bool: ... def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... + def __exit__( + self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + ) -> None: ... -class Event(AbstractContextManager[bool]): +class Event: def __init__(self, lock: _LockLike | None = ..., *, ctx: BaseContext) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... @@ -46,3 +53,6 @@ class Semaphore(SemLock): class SemLock(AbstractContextManager[bool]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... + def __exit__( + self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + ) -> None: ... diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 7c1c2068aff6..b1c3f5ec5024 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,6 +1,8 @@ from _typeshed import StrOrBytesPath from typing import Optional +__all__ = ["netrc", "NetrcParseError"] + class NetrcParseError(Exception): filename: str | None lineno: int | None diff --git a/mypy/typeshed/stdlib/nis.pyi b/mypy/typeshed/stdlib/nis.pyi index b762ae46241c..10eef2336a83 100644 --- a/mypy/typeshed/stdlib/nis.pyi +++ b/mypy/typeshed/stdlib/nis.pyi @@ -5,4 +5,5 @@ if sys.platform != "win32": 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 f0a0fb42da5c..77cab1e154e8 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -4,6 +4,19 @@ import ssl import sys from _typeshed import Self from typing import IO, Any, Iterable, NamedTuple, Union +from typing_extensions import Literal + +__all__ = [ + "NNTP", + "NNTPError", + "NNTPReplyError", + "NNTPTemporaryError", + "NNTPPermanentError", + "NNTPProtocolError", + "NNTPDataError", + "decode_header", + "NNTP_SSL", +] _File = Union[IO[bytes], bytes, str, None] @@ -16,8 +29,8 @@ class NNTPPermanentError(NNTPError): ... class NNTPProtocolError(NNTPError): ... class NNTPDataError(NNTPError): ... -NNTP_PORT: int -NNTP_SSL_PORT: int +NNTP_PORT: Literal[119] +NNTP_SSL_PORT: Literal[563] class GroupInfo(NamedTuple): group: str @@ -34,11 +47,13 @@ def decode_header(header_str: str) -> str: ... _list = list # conflicts with a method named "list" -class _NNTPBase: +class NNTP: encoding: str errors: str host: str + port: int + sock: socket.socket file: IO[bytes] debugging: int welcome: str @@ -47,7 +62,16 @@ class _NNTPBase: authenticated: bool nntp_implementation: str nntp_version: int - def __init__(self, file: IO[bytes], host: str, readermode: bool | None = ..., timeout: float = ...) -> None: ... + def __init__( + self, + host: str, + port: int = ..., + user: str | None = ..., + password: str | None = ..., + readermode: bool | None = ..., + usenetrc: bool = ..., + timeout: float = ..., + ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getwelcome(self) -> str: ... @@ -77,6 +101,7 @@ class _NNTPBase: 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: bytes | Iterable[bytes]) -> str: ... def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... @@ -84,22 +109,9 @@ class _NNTPBase: def login(self, user: str | None = ..., password: str | None = ..., usenetrc: bool = ...) -> None: ... def starttls(self, context: ssl.SSLContext | None = ...) -> None: ... -class NNTP(_NNTPBase): - port: int - sock: socket.socket - def __init__( - self, - host: str, - port: int = ..., - user: str | None = ..., - password: str | None = ..., - readermode: bool | None = ..., - usenetrc: bool = ..., - timeout: float = ..., - ) -> None: ... - -class NNTP_SSL(_NNTPBase): - sock: socket.socket +class NNTP_SSL(NNTP): + ssl_context: ssl.SSLContext | None + sock: ssl.SSLSocket def __init__( self, host: str, diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index f691356cb702..ffe5cc1e5a2d 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -44,10 +44,94 @@ from posixpath import ( ) from typing import AnyStr, overload -altsep: str -if sys.version_info < (3, 7) and sys.platform == "win32": +if sys.version_info >= (3, 7) or sys.platform != "win32": + __all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "samefile", + "sameopenfile", + "samestat", + "commonpath", + ] +else: + __all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "splitunc", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "samefile", + "sameopenfile", + "samestat", + "commonpath", + ] + def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated +altsep: str + # First parameter is not actually pos-only, # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in posixpath.join() diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index eaf53d25347a..d94ae7faf890 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -4,6 +4,8 @@ from abc import ABCMeta, abstractmethod from typing import Any, SupportsFloat, overload +__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] + class Number(metaclass=ABCMeta): @abstractmethod def __hash__(self) -> int: ... @@ -40,9 +42,12 @@ class Complex(Number): def __pow__(self, exponent: Any) -> Any: ... @abstractmethod def __rpow__(self, base: Any) -> Any: ... + @abstractmethod def __abs__(self) -> Real: ... + @abstractmethod def conjugate(self) -> Any: ... - def __eq__(self, other: Any) -> bool: ... + @abstractmethod + def __eq__(self, other: object) -> bool: ... class Real(Complex, SupportsFloat): @abstractmethod diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index 982ddee43a63..402dbb74cf58 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -1,7 +1,40 @@ import sys -from typing import Sequence +from typing_extensions import Literal -cmp_op: Sequence[str] +__all__ = [ + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "hasnargs", + "stack_effect", +] + +if sys.version_info >= (3, 9): + cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] +else: + cmp_op: tuple[ + Literal["<"], + Literal["<="], + Literal["=="], + Literal["!="], + Literal[">"], + Literal[">="], + Literal["in"], + Literal["not in"], + Literal["is"], + Literal["is not"], + Literal["exception match"], + Literal["BAD"], + ] hasconst: list[int] hasname: list[int] hasjrel: list[int] @@ -12,8 +45,8 @@ hasfree: list[int] opname: list[str] opmap: dict[str, int] -HAVE_ARGUMENT: int -EXTENDED_ARG: int +HAVE_ARGUMENT: Literal[90] +EXTENDED_ARG: Literal[144] if sys.version_info >= (3, 8): def stack_effect(__opcode: int, __oparg: int | None = ..., *, jump: bool | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index 180bd161c045..603e15ebc7be 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -2,6 +2,122 @@ import sys from _operator import * +if sys.version_info >= (3, 11): + __all__ = [ + "abs", + "add", + "and_", + "attrgetter", + "call", + "concat", + "contains", + "countOf", + "delitem", + "eq", + "floordiv", + "ge", + "getitem", + "gt", + "iadd", + "iand", + "iconcat", + "ifloordiv", + "ilshift", + "imatmul", + "imod", + "imul", + "index", + "indexOf", + "inv", + "invert", + "ior", + "ipow", + "irshift", + "is_", + "is_not", + "isub", + "itemgetter", + "itruediv", + "ixor", + "le", + "length_hint", + "lshift", + "lt", + "matmul", + "methodcaller", + "mod", + "mul", + "ne", + "neg", + "not_", + "or_", + "pos", + "pow", + "rshift", + "setitem", + "sub", + "truediv", + "truth", + "xor", + ] +else: + __all__ = [ + "abs", + "add", + "and_", + "attrgetter", + "concat", + "contains", + "countOf", + "delitem", + "eq", + "floordiv", + "ge", + "getitem", + "gt", + "iadd", + "iand", + "iconcat", + "ifloordiv", + "ilshift", + "imatmul", + "imod", + "imul", + "index", + "indexOf", + "inv", + "invert", + "ior", + "ipow", + "irshift", + "is_", + "is_not", + "isub", + "itemgetter", + "itruediv", + "ixor", + "le", + "length_hint", + "lshift", + "lt", + "matmul", + "methodcaller", + "mod", + "mul", + "ne", + "neg", + "not_", + "or_", + "pos", + "pow", + "rshift", + "setitem", + "sub", + "truediv", + "truth", + "xor", + ] + __lt__ = lt __le__ = le __eq__ = eq diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 416bc5446cc5..7aedf583e556 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,11 +1,32 @@ -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Type, overload +from abc import abstractmethod +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, overload + +__all__ = [ + "Option", + "make_option", + "SUPPRESS_HELP", + "SUPPRESS_USAGE", + "Values", + "OptionContainer", + "OptionGroup", + "OptionParser", + "HelpFormatter", + "IndentedHelpFormatter", + "TitledHelpFormatter", + "OptParseError", + "OptionError", + "OptionConflictError", + "OptionValueError", + "BadOptionError", + "check_choice", +] NO_DEFAULT: tuple[str, ...] SUPPRESS_HELP: str SUPPRESS_USAGE: str def check_builtin(option: Option, opt: Any, value: str) -> Any: ... -def check_choice(option: Option, opt: Any, value: str) -> Any: ... +def check_choice(option: Option, opt: Any, value: str) -> str: ... class OptParseError(Exception): msg: str @@ -47,9 +68,11 @@ class HelpFormatter: def expand_default(self, option: Option) -> str: ... def format_description(self, description: str) -> str: ... def format_epilog(self, epilog: str) -> str: ... + @abstractmethod def format_heading(self, heading: Any) -> str: ... def format_option(self, option: Option) -> str: ... def format_option_strings(self, option: Option) -> str: ... + @abstractmethod def format_usage(self, usage: Any) -> str: ... def indent(self) -> None: ... def set_long_opt_delimiter(self, delim: str) -> None: ... @@ -119,8 +142,8 @@ class OptionContainer: conflict_handler: str defaults: dict[str, Any] description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... + 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: ... @@ -157,7 +180,8 @@ class Values: def read_file(self, filename: str, mode: str = ...) -> None: ... def read_module(self, modname: str, mode: str = ...) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + def __eq__(self, other: object) -> bool: ... class OptionParser(OptionContainer): allow_interspersed_args: bool @@ -177,7 +201,7 @@ class OptionParser(OptionContainer): self, usage: str | None = ..., option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., + option_class: type[Option] = ..., version: str | None = ..., conflict_handler: str = ..., description: str | None = ..., diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 5308416adff4..615dff880689 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1,5 +1,6 @@ import sys from _typeshed import ( + BytesPath, FileDescriptorLike, OpenBinaryMode, OpenBinaryModeReading, @@ -11,6 +12,7 @@ from _typeshed import ( StrPath, structseq, ) +from abc import abstractmethod from builtins import OSError from contextlib import AbstractContextManager from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper @@ -45,6 +47,8 @@ if sys.version_info >= (3, 9): path = _path _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) # ----- os variables ----- @@ -237,6 +241,7 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): putenv: Callable[[AnyStr, AnyStr], None], unsetenv: Callable[[AnyStr, AnyStr], None], ) -> None: ... + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... # type: ignore[override] def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... @@ -244,6 +249,16 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __len__(self) -> int: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + # We use @overload instead of a Union for reasons similar to those given for + # overloading MutableMapping.update in stdlib/typing.pyi + # The type: ignore is needed due to incompatible __or__/__ior__ signatures + @overload # type: ignore[misc] + def __ior__(self: Self, other: Mapping[AnyStr, AnyStr]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... environ: _Environ[str] if sys.platform != "win32": @@ -352,21 +367,20 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo if sys.platform == "darwin": @property def st_flags(self) -> int: ... # user defined flags for file - # Atributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. + # Attributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327 @runtime_checkable class PathLike(Protocol[_AnyStr_co]): + @abstractmethod def __fspath__(self) -> _AnyStr_co: ... @overload -def listdir(path: str | None = ...) -> list[str]: ... +def listdir(path: StrPath | None = ...) -> list[str]: ... @overload -def listdir(path: bytes) -> list[bytes]: ... +def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... -@overload -def listdir(path: PathLike[str]) -> list[str]: ... _FdOrAnyPath = Union[int, StrOrBytesPath] @@ -375,8 +389,10 @@ class DirEntry(Generic[AnyStr]): # This is what the scandir iterator yields # The constructor is hidden - name: AnyStr - path: AnyStr + @property + def name(self) -> AnyStr: ... + @property + def path(self) -> AnyStr: ... def inode(self) -> int: ... def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... @@ -387,54 +403,35 @@ class DirEntry(Generic[AnyStr]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 7): - @final - class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): - @property - def f_bsize(self) -> int: ... - @property - def f_frsize(self) -> int: ... - @property - def f_blocks(self) -> int: ... - @property - def f_bfree(self) -> int: ... - @property - def f_bavail(self) -> int: ... - @property - def f_files(self) -> int: ... - @property - def f_ffree(self) -> int: ... - @property - def f_favail(self) -> int: ... - @property - def f_flag(self) -> int: ... - @property - def f_namemax(self) -> int: ... - @property - def f_fsid(self) -> int: ... - + _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int, int] else: - @final - class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int]): - @property - def f_bsize(self) -> int: ... - @property - def f_frsize(self) -> int: ... - @property - def f_blocks(self) -> int: ... - @property - def f_bfree(self) -> int: ... - @property - def f_bavail(self) -> int: ... - @property - def f_files(self) -> int: ... - @property - def f_ffree(self) -> int: ... - @property - def f_favail(self) -> int: ... - @property - def f_flag(self) -> int: ... + _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int] + +@final +class statvfs_result(structseq[int], _StatVfsTuple): + @property + def f_bsize(self) -> int: ... + @property + def f_frsize(self) -> int: ... + @property + def f_blocks(self) -> int: ... + @property + def f_bfree(self) -> int: ... + @property + def f_bavail(self) -> int: ... + @property + def f_files(self) -> int: ... + @property + def f_ffree(self) -> int: ... + @property + def f_favail(self) -> int: ... + @property + def f_flag(self) -> int: ... + @property + def f_namemax(self) -> int: ... + if sys.version_info >= (3, 7): @property - def f_namemax(self) -> int: ... + def f_fsid(self) -> int: ... # ----- os function stubs ----- def fsencode(filename: StrOrBytesPath) -> bytes: ... @@ -479,6 +476,7 @@ if sys.platform != "win32": 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: ... @@ -490,6 +488,7 @@ if sys.platform != "win32": 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: ... @@ -573,7 +572,7 @@ def fdopen( def fdopen( fd: int, mode: OpenBinaryMode, - buffering: int, + buffering: int = ..., encoding: None = ..., errors: None = ..., newline: None = ..., @@ -626,6 +625,7 @@ if sys.platform != "win32": 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: ... if sys.platform != "darwin": @@ -664,6 +664,10 @@ 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": + def get_handle_inheritable(__handle: int) -> bool: ... + def set_handle_inheritable(__handle: int, __inheritable: bool) -> None: ... + if sys.platform != "win32": # Unix only def tcgetpgrp(__fd: int) -> int: ... @@ -726,6 +730,7 @@ def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_ScandirIterator[AnyStr]]): def __next__(self) -> DirEntry[AnyStr]: ... + def __exit__(self, *args: object) -> None: ... def close(self) -> None: ... if sys.version_info >= (3, 7): @@ -910,7 +915,9 @@ else: def si_status(self) -> int: ... @property def si_code(self) -> int: ... + 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: ... @@ -955,9 +962,10 @@ else: if sys.platform != "win32": @final class sched_param(structseq[int], tuple[int]): - def __new__(cls, sched_priority: int) -> sched_param: ... + def __new__(cls: type[Self], sched_priority: int) -> Self: ... @property def sched_priority(self) -> int: ... + 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_yield() -> None: ... # some flavors of Unix @@ -999,6 +1007,7 @@ if sys.version_info >= (3, 8): def close(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... + def add_dll_directory(path: str) -> _AddedDllDirectory: ... if sys.platform == "linux": MFD_CLOEXEC: int @@ -1019,6 +1028,12 @@ if sys.version_info >= (3, 8): MFD_HUGE_2GB: int MFD_HUGE_16GB: int def memfd_create(name: str, flags: int = ...) -> int: ... + def copy_file_range( + src: int, dst: int, count: int, offset_src: int | None = ..., offset_dst: int | None = ... + ) -> int: ... if sys.version_info >= (3, 9): def waitstatus_to_exitcode(status: int) -> int: ... + + if sys.platform == "linux": + def pidfd_open(pid: int, flags: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/os/path.pyi b/mypy/typeshed/stdlib/os/path.pyi index 4533738983f7..dc688a9f877f 100644 --- a/mypy/typeshed/stdlib/os/path.pyi +++ b/mypy/typeshed/stdlib/os/path.pyi @@ -2,5 +2,7 @@ import sys if sys.platform == "win32": from ntpath import * + from ntpath import __all__ as __all__ else: from posixpath import * + from posixpath import __all__ as __all__ diff --git a/mypy/typeshed/stdlib/ossaudiodev.pyi b/mypy/typeshed/stdlib/ossaudiodev.pyi index f221c95b8036..d956a89729fd 100644 --- a/mypy/typeshed/stdlib/ossaudiodev.pyi +++ b/mypy/typeshed/stdlib/ossaudiodev.pyi @@ -1,131 +1,132 @@ +import sys from typing import Any, 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 +if sys.platform != "win32" and sys.platform != "darwin": + 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] + 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_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: ... + # TODO: oss_mixer_device return type + def openmixer(device: str = ...) -> Any: ... -class OSSAudioError(Exception): ... - -error = OSSAudioError + class OSSAudioError(Exception): ... + error = OSSAudioError diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index ab819a71a15f..95e770b57256 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,6 +1,7 @@ from _typeshed import StrOrBytesPath from types import CodeType from typing import Any, Sequence +from typing_extensions import final def expr(source: str) -> STType: ... def suite(source: str) -> STType: ... @@ -14,6 +15,7 @@ def issuite(st: STType) -> bool: ... class ParserError(Exception): ... +@final class STType: def compile(self, filename: StrOrBytesPath = ...) -> CodeType: ... def isexpr(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index b541345c06d4..45917ce59f8f 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -11,31 +11,41 @@ from _typeshed import ( from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result from types import TracebackType -from typing import IO, Any, BinaryIO, Generator, Sequence, Type, TypeVar, overload +from typing import IO, Any, BinaryIO, Generator, Sequence, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias -_P = TypeVar("_P", bound=PurePath) +__all__ = ["PurePath", "PurePosixPath", "PureWindowsPath", "Path", "PosixPath", "WindowsPath"] class PurePath(PathLike[str]): - parts: tuple[str, ...] - drive: str - root: str - anchor: str - name: str - suffix: str - suffixes: list[str] - stem: str - def __new__(cls: Type[_P], *args: StrPath) -> _P: ... + @property + def parts(self) -> tuple[str, ...]: ... + @property + def drive(self) -> str: ... + @property + def root(self) -> str: ... + @property + def anchor(self) -> str: ... + @property + def name(self) -> str: ... + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + def __new__(cls: type[Self], *args: StrPath) -> Self: ... def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __fspath__(self) -> str: ... def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... def __gt__(self, other: PurePath) -> bool: ... def __ge__(self, other: PurePath) -> bool: ... - def __truediv__(self: _P, key: StrPath) -> _P: ... - def __rtruediv__(self: _P, key: StrPath) -> _P: ... + def __truediv__(self: Self, key: StrPath) -> Self: ... + def __rtruediv__(self: Self, key: StrPath) -> Self: ... def __bytes__(self) -> bytes: ... def as_posix(self) -> str: ... def as_uri(self) -> str: ... @@ -43,50 +53,48 @@ class PurePath(PathLike[str]): def is_reserved(self) -> bool: ... if sys.version_info >= (3, 9): def is_relative_to(self, *other: StrPath) -> bool: ... + def match(self, path_pattern: str) -> bool: ... - def relative_to(self: _P, *other: StrPath) -> _P: ... - def with_name(self: _P, name: str) -> _P: ... + def relative_to(self: Self, *other: StrPath) -> Self: ... + def with_name(self: Self, name: str) -> Self: ... if sys.version_info >= (3, 9): - def with_stem(self: _P, stem: str) -> _P: ... - def with_suffix(self: _P, suffix: str) -> _P: ... - def joinpath(self: _P, *other: StrPath) -> _P: ... + def with_stem(self: Self, stem: str) -> Self: ... + + def with_suffix(self: Self, suffix: str) -> Self: ... + def joinpath(self: Self, *other: StrPath) -> Self: ... @property - def parents(self: _P) -> Sequence[_P]: ... + def parents(self: Self) -> Sequence[Self]: ... @property - def parent(self: _P) -> _P: ... - if sys.version_info >= (3, 9): + def parent(self: Self) -> Self: ... + if sys.version_info >= (3, 9) and sys.version_info < (3, 11): def __class_getitem__(cls, type: Any) -> GenericAlias: ... class PurePosixPath(PurePath): ... class PureWindowsPath(PurePath): ... class Path(PurePath): - def __new__(cls: Type[_P], *args: StrPath, **kwargs: Any) -> _P: ... + def __new__(cls: type[Self], *args: StrPath, **kwargs: Any) -> Self: ... def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... @classmethod - def cwd(cls: Type[_P]) -> _P: ... + def cwd(cls: type[Self]) -> Self: ... if sys.version_info >= (3, 10): def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... def chmod(self, mode: int, *, follow_symlinks: bool = ...) -> None: ... else: def stat(self) -> stat_result: ... def chmod(self, mode: int) -> None: ... + def exists(self) -> bool: ... - def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... - def group(self) -> str: ... + def glob(self: Self, pattern: str) -> Generator[Self, None, None]: ... 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: _P) -> Generator[_P, None, None]: ... + def iterdir(self: Self) -> Generator[Self, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... @@ -138,37 +146,47 @@ class Path(PurePath): # Buffering cannot be determined: fall back to BinaryIO @overload def open( - self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... + 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: str | None = ..., errors: str | None = ..., newline: str | None = ... ) -> IO[Any]: ... - def owner(self) -> str: ... + if sys.platform != "win32": + # These methods do "exist" on Windows, but they always raise NotImplementedError, + # so it's safer to pretend they don't exist + def owner(self) -> str: ... + def group(self) -> str: ... + if sys.version_info >= (3, 7): + def is_mount(self) -> bool: ... + if sys.version_info >= (3, 9): - def readlink(self: _P) -> _P: ... + def readlink(self: Self) -> Self: ... if sys.version_info >= (3, 8): - def rename(self: _P, target: str | PurePath) -> _P: ... - def replace(self: _P, target: str | PurePath) -> _P: ... + def rename(self: Self, target: str | PurePath) -> Self: ... + def replace(self: Self, target: str | PurePath) -> Self: ... else: def rename(self, target: str | PurePath) -> None: ... def replace(self, target: str | PurePath) -> None: ... - def resolve(self: _P, strict: bool = ...) -> _P: ... - def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... + + def resolve(self: Self, strict: bool = ...) -> Self: ... + def rglob(self: Self, pattern: str) -> Generator[Self, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: str | Path, target_is_directory: bool = ...) -> None: ... if sys.version_info >= (3, 10): def hardlink_to(self, target: str | Path) -> 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: ... + @classmethod - def home(cls: Type[_P]) -> _P: ... - def absolute(self: _P) -> _P: ... - def expanduser(self: _P) -> _P: ... + def home(cls: type[Self]) -> Self: ... + def absolute(self: Self) -> Self: ... + def expanduser(self: Self) -> Self: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... def samefile(self, other_path: str | bytes | int | Path) -> bool: ... diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index 83bd32d76450..c1cba5e8d23b 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -1,12 +1,17 @@ import signal import sys +from _typeshed import Self from bdb import Bdb from cmd import Cmd from inspect import _SourceObjectType from types import CodeType, FrameType, TracebackType from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, Sequence, TypeVar +from typing_extensions import ParamSpec + +__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] _T = TypeVar("_T") +_P = ParamSpec("_P") line_prefix: str # undocumented @@ -15,7 +20,7 @@ class Restart(Exception): ... def run(statement: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... def runeval(expression: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... -def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... +def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... if sys.version_info >= (3, 7): def set_trace(*, header: str | None = ...) -> None: ... @@ -171,4 +176,4 @@ def getsourcelines(obj: _SourceObjectType) -> tuple[list[str], int]: ... def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): - def __repr__(self) -> _rstr: ... + def __repr__(self: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index 46c349137459..d48d3ead75c5 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,11 +1,178 @@ import sys -from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Type, Union +from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Union from typing_extensions import final +if sys.version_info >= (3, 8): + __all__ = [ + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "dump", + "dumps", + "load", + "loads", + "PickleBuffer", + "ADDITEMS", + "APPEND", + "APPENDS", + "BINBYTES", + "BINBYTES8", + "BINFLOAT", + "BINGET", + "BININT", + "BININT1", + "BININT2", + "BINPERSID", + "BINPUT", + "BINSTRING", + "BINUNICODE", + "BINUNICODE8", + "BUILD", + "BYTEARRAY8", + "DEFAULT_PROTOCOL", + "DICT", + "DUP", + "EMPTY_DICT", + "EMPTY_LIST", + "EMPTY_SET", + "EMPTY_TUPLE", + "EXT1", + "EXT2", + "EXT4", + "FALSE", + "FLOAT", + "FRAME", + "FROZENSET", + "GET", + "GLOBAL", + "HIGHEST_PROTOCOL", + "INST", + "INT", + "LIST", + "LONG", + "LONG1", + "LONG4", + "LONG_BINGET", + "LONG_BINPUT", + "MARK", + "MEMOIZE", + "NEWFALSE", + "NEWOBJ", + "NEWOBJ_EX", + "NEWTRUE", + "NEXT_BUFFER", + "NONE", + "OBJ", + "PERSID", + "POP", + "POP_MARK", + "PROTO", + "PUT", + "READONLY_BUFFER", + "REDUCE", + "SETITEM", + "SETITEMS", + "SHORT_BINBYTES", + "SHORT_BINSTRING", + "SHORT_BINUNICODE", + "STACK_GLOBAL", + "STOP", + "STRING", + "TRUE", + "TUPLE", + "TUPLE1", + "TUPLE2", + "TUPLE3", + "UNICODE", + ] +else: + __all__ = [ + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "dump", + "dumps", + "load", + "loads", + "ADDITEMS", + "APPEND", + "APPENDS", + "BINBYTES", + "BINBYTES8", + "BINFLOAT", + "BINGET", + "BININT", + "BININT1", + "BININT2", + "BINPERSID", + "BINPUT", + "BINSTRING", + "BINUNICODE", + "BINUNICODE8", + "BUILD", + "DEFAULT_PROTOCOL", + "DICT", + "DUP", + "EMPTY_DICT", + "EMPTY_LIST", + "EMPTY_SET", + "EMPTY_TUPLE", + "EXT1", + "EXT2", + "EXT4", + "FALSE", + "FLOAT", + "FRAME", + "FROZENSET", + "GET", + "GLOBAL", + "HIGHEST_PROTOCOL", + "INST", + "INT", + "LIST", + "LONG", + "LONG1", + "LONG4", + "LONG_BINGET", + "LONG_BINPUT", + "MARK", + "MEMOIZE", + "NEWFALSE", + "NEWOBJ", + "NEWOBJ_EX", + "NEWTRUE", + "NONE", + "OBJ", + "PERSID", + "POP", + "POP_MARK", + "PROTO", + "PUT", + "REDUCE", + "SETITEM", + "SETITEMS", + "SHORT_BINBYTES", + "SHORT_BINSTRING", + "SHORT_BINUNICODE", + "STACK_GLOBAL", + "STOP", + "STRING", + "TRUE", + "TUPLE", + "TUPLE1", + "TUPLE2", + "TUPLE3", + "UNICODE", + ] + HIGHEST_PROTOCOL: int DEFAULT_PROTOCOL: int -bytes_types: tuple[Type[Any], ...] # undocumented +bytes_types: tuple[type[Any], ...] # undocumented class _ReadableFileobj(Protocol): def read(self, __n: int) -> bytes: ... @@ -82,6 +249,7 @@ class Pickler: def reducer_override(self, obj: Any) -> Any: ... else: def __init__(self, file: _WritableFileobj, protocol: int | None = ..., *, fix_imports: bool = ...) -> None: ... + def dump(self, __obj: Any) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... @@ -103,6 +271,7 @@ class Unpickler: def __init__( self, file: _ReadableFileobj, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ... ) -> None: ... + def load(self) -> Any: ... def find_class(self, __module_name: str, __global_name: str) -> Any: ... def persistent_load(self, pid: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index 04a695f5f103..7b79ddcff347 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,7 +1,9 @@ -from typing import IO, Any, Callable, Iterator, MutableMapping, Type +from typing import IO, Any, Callable, Iterator, MutableMapping + +__all__ = ["dis", "genops", "optimize"] _Reader = Callable[[IO[bytes]], Any] -bytes_types: tuple[Type[Any], ...] +bytes_types: tuple[type[Any], ...] UP_TO_NEWLINE: int TAKEN_FROM_ARGUMENT1: int @@ -108,9 +110,9 @@ long4: ArgumentDescriptor class StackObject: name: str - obtype: Type[Any] | tuple[Type[Any], ...] + obtype: type[Any] | tuple[type[Any], ...] doc: str - def __init__(self, name: str, obtype: Type[Any] | tuple[Type[Any], ...], doc: str) -> None: ... + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... pyint: StackObject pylong: StackObject diff --git a/mypy/typeshed/stdlib/pipes.pyi b/mypy/typeshed/stdlib/pipes.pyi index fb9d7e4e1d16..d6bbd7eafac3 100644 --- a/mypy/typeshed/stdlib/pipes.pyi +++ b/mypy/typeshed/stdlib/pipes.pyi @@ -1,5 +1,7 @@ import os +__all__ = ["Template"] + class Template: def __init__(self) -> None: ... def reset(self) -> None: ... diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index e0f392fd91d8..607c6b371507 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -3,6 +3,21 @@ from _typeshed import SupportsRead from importlib.abc import Loader, MetaPathFinder, PathEntryFinder from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple +__all__ = [ + "get_importer", + "iter_importers", + "get_loader", + "find_loader", + "walk_packages", + "iter_modules", + "get_data", + "ImpImporter", + "ImpLoader", + "read_code", + "extend_path", + "ModuleInfo", +] + class ModuleInfo(NamedTuple): module_finder: MetaPathFinder | PathEntryFinder name: str @@ -18,7 +33,7 @@ class ImpLoader: def find_loader(fullname: str) -> Loader | None: ... def get_importer(path_item: str) -> PathEntryFinder | None: ... -def get_loader(module_or_name: str) -> Loader: ... +def get_loader(module_or_name: str) -> Loader | None: ... def iter_importers(fullname: str = ...) -> Iterator[MetaPathFinder | PathEntryFinder]: ... def iter_modules(path: Iterable[str] | None = ..., prefix: str = ...) -> Iterator[ModuleInfo]: ... def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 7abe9dd2942b..67d1611de828 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -1,7 +1,59 @@ import sys +from _typeshed import Self from datetime import datetime from enum import Enum -from typing import IO, Any, Mapping, MutableMapping, Type +from typing import IO, Any, Mapping, MutableMapping + +if sys.version_info >= (3, 9): + __all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] +elif sys.version_info >= (3, 8): + __all__ = [ + "readPlist", + "writePlist", + "readPlistFromBytes", + "writePlistToBytes", + "Data", + "InvalidFileException", + "FMT_XML", + "FMT_BINARY", + "load", + "dump", + "loads", + "dumps", + "UID", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "readPlist", + "writePlist", + "readPlistFromBytes", + "writePlistToBytes", + "Data", + "InvalidFileException", + "FMT_XML", + "FMT_BINARY", + "load", + "dump", + "loads", + "dumps", + ] +else: + __all__ = [ + "readPlist", + "writePlist", + "readPlistFromBytes", + "writePlistToBytes", + "Plist", + "Data", + "Dict", + "InvalidFileException", + "FMT_XML", + "FMT_BINARY", + "load", + "dump", + "loads", + "dumps", + ] class PlistFormat(Enum): FMT_XML: int @@ -11,8 +63,8 @@ FMT_XML = PlistFormat.FMT_XML FMT_BINARY = PlistFormat.FMT_BINARY if sys.version_info >= (3, 9): - def load(fp: IO[bytes], *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... - def loads(value: bytes, *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... + def load(fp: IO[bytes], *, fmt: PlistFormat | None = ..., dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... + def loads(value: bytes, *, fmt: PlistFormat | None = ..., dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... else: def load( @@ -20,14 +72,14 @@ else: *, fmt: PlistFormat | None = ..., use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + dict_type: type[MutableMapping[str, Any]] = ..., ) -> Any: ... def loads( value: bytes, *, fmt: PlistFormat | None = ..., use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + dict_type: type[MutableMapping[str, Any]] = ..., ) -> Any: ... def dump( @@ -53,11 +105,20 @@ if sys.version_info < (3, 9): def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... if sys.version_info < (3, 7): - class Dict(dict[str, Any]): + class _InternalDict(dict[str, Any]): def __getattr__(self, attr: str) -> Any: ... def __setattr__(self, attr: str, value: Any) -> None: ... def __delattr__(self, attr: str) -> None: ... + class Dict(_InternalDict): # deprecated + def __init__(self, **kwargs: Any) -> None: ... + + class Plist(_InternalDict): # deprecated + def __init__(self, **kwargs: Any) -> None: ... + @classmethod + def fromFile(cls: type[Self], pathOrFile: str | IO[bytes]) -> Self: ... + def write(self, pathOrFile: str | IO[bytes]) -> None: ... + if sys.version_info < (3, 9): class Data: data: bytes @@ -68,8 +129,9 @@ if sys.version_info >= (3, 8): data: int def __init__(self, data: int) -> None: ... def __index__(self) -> int: ... - def __reduce__(self) -> Any: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[int]]: ... def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... class InvalidFileException(ValueError): def __init__(self, message: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index 028af412847b..111e5c4ca76a 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -1,16 +1,24 @@ import socket import ssl -from typing import Any, BinaryIO, Pattern, overload +import sys +from typing import Any, BinaryIO, NoReturn, Pattern, overload +from typing_extensions import Literal + +if sys.version_info >= (3, 10): + __all__ = ["POP3", "error_proto", "POP3_SSL"] +else: + __all__ = ["POP3", "error_proto"] _LongResp = tuple[bytes, list[bytes], int] class error_proto(Exception): ... -POP3_PORT: int -POP3_SSL_PORT: int -CR: bytes -LF: bytes -CRLF: bytes +POP3_PORT: Literal[110] +POP3_SSL_PORT: Literal[995] +CR: Literal[b"\r"] +LF: Literal[b"\n"] +CRLF: Literal[b"\r\n"] +HAVE_SSL: bool _list = list # conflicts with a method named "list" @@ -57,4 +65,4 @@ class POP3_SSL(POP3): context: ssl.SSLContext | None = ..., ) -> None: ... # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored - def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> bytes: ... + def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> NoReturn: ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 9f658039bcf2..5dba5b36e3d2 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -273,7 +273,8 @@ if sys.platform != "win32": from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode if sys.platform == "linux": - from os import P_PIDFD as P_PIDFD + from os import P_PIDFD as P_PIDFD, pidfd_open as pidfd_open + if sys.version_info >= (3, 8): from os import ( POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, @@ -302,6 +303,7 @@ if sys.platform != "win32": MFD_HUGE_MASK as MFD_HUGE_MASK, MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, MFD_HUGETLB as MFD_HUGETLB, + copy_file_range as copy_file_range, memfd_create as memfd_create, ) if sys.version_info >= (3, 7): diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 58cadb4de03c..c72ba8a99bdd 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -16,6 +16,47 @@ from genericpath import ( from os import PathLike from typing import AnyStr, Sequence, overload +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "samefile", + "sameopenfile", + "samestat", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "commonpath", +] + supports_unicode_filenames: bool # aliases (also in os) curdir: str diff --git a/mypy/typeshed/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi index 9e343feb49bc..0addc8f538b2 100644 --- a/mypy/typeshed/stdlib/pprint.pyi +++ b/mypy/typeshed/stdlib/pprint.pyi @@ -1,5 +1,10 @@ import sys -from typing import IO, Any +from typing import IO + +if sys.version_info >= (3, 8): + __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] +else: + __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter"] if sys.version_info >= (3, 10): def pformat( @@ -126,8 +131,9 @@ class PrettyPrinter: *, compact: bool = ..., ) -> 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, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index 7581c0122c9c..982bcabad401 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -1,13 +1,16 @@ -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from typing import Any, Callable, TypeVar +from typing_extensions import ParamSpec + +__all__ = ["run", "runctx", "Profile"] def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") +_P = ParamSpec("_P") _Label = tuple[str, int, str] class Profile: @@ -21,7 +24,7 @@ class Profile: def dump_stats(self, file: StrOrBytesPath) -> 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 run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... + def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 6e008c823ff2..c4fe28477fb5 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -1,14 +1,22 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, TypeVar, Union, overload +from typing import IO, Any, Iterable, Union, overload +from typing_extensions import Literal + +if sys.version_info >= (3, 9): + __all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] +elif sys.version_info >= (3, 7): + __all__ = ["Stats", "SortKey"] +else: + __all__ = ["Stats"] _Selector = Union[str, float, int] -_T = TypeVar("_T", bound=Stats) if sys.version_info >= (3, 7): from enum import Enum + class SortKey(str, Enum): CALLS: str CUMULATIVE: str @@ -20,32 +28,54 @@ if sys.version_info >= (3, 7): STDNAME: str TIME: str +if sys.version_info >= (3, 9): + from dataclasses import dataclass + + @dataclass(unsafe_hash=True) + class FunctionProfile: + ncalls: int + tottime: float + percall_tottime: float + cumtime: float + percall_cumtime: float + file_name: str + line_number: int + @dataclass(unsafe_hash=True) + class StatsProfile: + total_tt: float + func_profiles: dict[str, FunctionProfile] + +_SortArgDict = dict[str, tuple[tuple[tuple[int, int], ...], str]] + class Stats: - sort_arg_dict_default: dict[str, tuple[Any, str]] + sort_arg_dict_default: _SortArgDict def __init__( - self: _T, + self: Self, __arg: None | str | Profile | _cProfile = ..., - *args: None | str | Profile | _cProfile | _T, + *args: None | str | Profile | _cProfile | Self, stream: IO[Any] | None = ..., ) -> None: ... def init(self, arg: None | str | Profile | _cProfile) -> None: ... def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Profile | _cProfile | _T) -> _T: ... + def add(self: Self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... - def get_sort_arg_defs(self) -> dict[str, tuple[tuple[tuple[int, int], ...], str]]: ... + def get_sort_arg_defs(self) -> _SortArgDict: ... @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self: Self, field: Literal[-1, 0, 1, 2]) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self: Self, *field: str) -> Self: ... + def reverse_order(self: Self) -> Self: ... + def strip_dirs(self: Self) -> Self: ... def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... + if sys.version_info >= (3, 9): + def get_stats_profile(self) -> StatsProfile: ... + 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_stats(self: Self, *amount: _Selector) -> Self: ... + def print_callees(self: Self, *amount: _Selector) -> Self: ... + def print_callers(self: Self, *amount: _Selector) -> Self: ... 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: ... diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 08a9facf642e..84f6dc5ccf91 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -20,6 +20,7 @@ if sys.platform != "win32": def pw_dir(self) -> str: ... @property def pw_shell(self) -> str: ... + def getpwall() -> list[struct_passwd]: ... def getpwuid(__uid: int) -> struct_passwd: ... def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 1df818509d0e..c544a7941981 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -1,15 +1,21 @@ import sys -from typing import AnyStr, Type +from typing import AnyStr + +if sys.version_info >= (3, 7): + __all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"] +else: + __all__ = ["compile", "main", "PyCompileError"] class PyCompileError(Exception): exc_type_name: str exc_value: BaseException file: str msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... if sys.version_info >= (3, 7): import enum + class PycInvalidationMode(enum.Enum): TIMESTAMP: int CHECKED_HASH: int @@ -42,4 +48,8 @@ else: file: AnyStr, cfile: AnyStr | None = ..., dfile: AnyStr | None = ..., doraise: bool = ..., optimize: int = ... ) -> AnyStr | None: ... -def main(args: list[str] | None = ...) -> int: ... +if sys.version_info >= (3, 10): + def main() -> None: ... + +else: + def main(args: list[str] | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/pyclbr.pyi b/mypy/typeshed/stdlib/pyclbr.pyi index 10d106b4f511..3033833a8162 100644 --- a/mypy/typeshed/stdlib/pyclbr.pyi +++ b/mypy/typeshed/stdlib/pyclbr.pyi @@ -1,5 +1,7 @@ import sys -from typing import Sequence +from collections.abc import Sequence + +__all__ = ["readmodule", "readmodule_ex", "Class", "Function"] class Class: module: str @@ -9,7 +11,26 @@ class Class: file: int lineno: int + if sys.version_info >= (3, 10): + end_lineno: int | None + if sys.version_info >= (3, 7): + parent: Class | None + children: dict[str, Class | Function] + + if sys.version_info >= (3, 10): + def __init__( + self, + module: str, + name: str, + super_: list[Class | str] | None, + file: str, + lineno: int, + parent: Class | None = ..., + *, + end_lineno: int | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): def __init__( self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int, parent: Class | None = ... ) -> None: ... @@ -22,8 +43,28 @@ class Function: file: int lineno: int + if sys.version_info >= (3, 10): + end_lineno: int | None + is_async: bool + if sys.version_info >= (3, 7): - def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | None = ...) -> None: ... + parent: Function | Class | None + children: dict[str, Class | Function] + + if sys.version_info >= (3, 10): + def __init__( + self, + module: str, + name: str, + file: str, + lineno: int, + parent: Function | Class | None = ..., + is_async: bool = ..., + *, + end_lineno: int | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): + def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | Class | None = ...) -> None: ... else: def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index a1d4359d28fc..b4fa66c60155 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,10 +1,15 @@ from _typeshed import SupportsWrite +from abc import abstractmethod from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Type +from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, TypeVar + +__all__ = ["help"] # the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_Exc_Info = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] + +_T = TypeVar("_T") __author__: str __date__: str @@ -28,7 +33,7 @@ def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = ...) - class ErrorDuringImport(Exception): filename: str - exc: Type[BaseException] | None + exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... @@ -40,11 +45,17 @@ class Doc: PYTHONDOCS: str def document(self, object: object, name: str | None = ..., *args: Any) -> str: ... def fail(self, object: object, name: str | None = ..., *args: Any) -> NoReturn: ... + @abstractmethod def docmodule(self, object: object, name: str | None = ..., *args: Any) -> str: ... + @abstractmethod def docclass(self, object: object, name: str | None = ..., *args: Any) -> str: ... + @abstractmethod def docroutine(self, object: object, name: str | None = ..., *args: Any) -> str: ... + @abstractmethod def docother(self, object: object, name: str | None = ..., *args: Any) -> str: ... + @abstractmethod def docproperty(self, object: object, name: str | None = ..., *args: Any) -> str: ... + @abstractmethod def docdata(self, object: object, name: str | None = ..., *args: Any) -> str: ... def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... @@ -64,8 +75,9 @@ class HTMLRepr(Repr): def repr_unicode(self, x: AnyStr, level: complex) -> str: ... class HTMLDoc(Doc): - repr: Callable[[object], str] - escape: Callable[[str], str] + _repr_instance: HTMLRepr = ... + repr = _repr_instance.repr + escape = _repr_instance.escape def page(self, title: str, contents: str) -> str: ... def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... def section( @@ -81,7 +93,7 @@ class HTMLDoc(Doc): ) -> 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 multicolumn(self, list: list[_T], format: Callable[[_T], 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: ... @@ -138,7 +150,8 @@ class TextRepr(Repr): def repr_instance(self, x: object, level: complex) -> str: ... class TextDoc(Doc): - repr: Callable[[object], str] + _repr_instance: TextRepr = ... + repr = _repr_instance.repr def bold(self, text: str) -> str: ... def indent(self, text: str, prefix: str = ...) -> str: ... def section(self, title: str, contents: str) -> str: ... @@ -189,8 +202,10 @@ class Helper: symbols: dict[str, str] topics: dict[str, str | tuple[str, ...]] def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... - input: IO[str] - output: IO[str] + @property + def input(self) -> IO[str]: ... + @property + def output(self) -> IO[str]: ... def __call__(self, request: str | Helper | object = ...) -> None: ... def interact(self) -> None: ... def getline(self, prompt: str) -> str: ... @@ -206,21 +221,12 @@ class Helper: 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[[str | None, str, str], None], - key: Any | None = ..., + key: str | None = ..., completer: Callable[[], None] | None = ..., onerror: Callable[[str], None] | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/queue.pyi b/mypy/typeshed/stdlib/queue.pyi index 9671155b7eb6..532d5d98344d 100644 --- a/mypy/typeshed/stdlib/queue.pyi +++ b/mypy/typeshed/stdlib/queue.pyi @@ -5,6 +5,11 @@ from typing import Any, Generic, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 7): + __all__ = ["Empty", "Full", "Queue", "PriorityQueue", "LifoQueue", "SimpleQueue"] +else: + __all__ = ["Empty", "Full", "Queue", "PriorityQueue", "LifoQueue"] + _T = TypeVar("_T") class Empty(Exception): ... @@ -18,6 +23,8 @@ class Queue(Generic[_T]): not_full: Condition # undocumented all_tasks_done: Condition # undocumented unfinished_tasks: int # undocumented + # Despite the fact that `queue` has `deque` type, + # we treat it as `Any` to allow different implementations in subtypes. queue: Any # undocumented def __init__(self, maxsize: int = ...) -> None: ... def _init(self, maxsize: int) -> None: ... @@ -36,8 +43,11 @@ class Queue(Generic[_T]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... -class PriorityQueue(Queue[_T]): ... -class LifoQueue(Queue[_T]): ... +class PriorityQueue(Queue[_T]): + queue: list[_T] + +class LifoQueue(Queue[_T]): + queue: list[_T] if sys.version_info >= (3, 7): class SimpleQueue(Generic[_T]): diff --git a/mypy/typeshed/stdlib/quopri.pyi b/mypy/typeshed/stdlib/quopri.pyi index c2ffabe7d531..b8dc0787fd1a 100644 --- a/mypy/typeshed/stdlib/quopri.pyi +++ b/mypy/typeshed/stdlib/quopri.pyi @@ -1,5 +1,7 @@ from typing import BinaryIO +__all__ = ["encode", "decode", "encodestring", "decodestring"] + 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: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index ffa866ef9aa0..16aa31a0f742 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -5,12 +5,73 @@ from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set a from fractions import Fraction from typing import Any, ClassVar, NoReturn, TypeVar +if sys.version_info >= (3, 9): + __all__ = [ + "Random", + "SystemRandom", + "betavariate", + "choice", + "choices", + "expovariate", + "gammavariate", + "gauss", + "getrandbits", + "getstate", + "lognormvariate", + "normalvariate", + "paretovariate", + "randbytes", + "randint", + "random", + "randrange", + "sample", + "seed", + "setstate", + "shuffle", + "triangular", + "uniform", + "vonmisesvariate", + "weibullvariate", + ] +else: + __all__ = [ + "Random", + "seed", + "random", + "uniform", + "randint", + "choice", + "sample", + "randrange", + "shuffle", + "normalvariate", + "lognormvariate", + "expovariate", + "vonmisesvariate", + "gammavariate", + "triangular", + "gauss", + "betavariate", + "paretovariate", + "weibullvariate", + "getstate", + "setstate", + "getrandbits", + "choices", + "SystemRandom", + ] + _T = TypeVar("_T") class Random(_random.Random): VERSION: ClassVar[int] def __init__(self, x: Any = ...) -> None: ... - def seed(self, a: Any = ..., version: int = ...) -> None: ... + # Using other `seed` types is deprecated since 3.9 and removed in 3.11 + if sys.version_info >= (3, 9): + def seed(self, a: int | float | str | bytes | bytearray | None = ..., version: int = ...) -> None: ... # type: ignore[override] + else: + 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: ... @@ -18,6 +79,7 @@ class Random(_random.Random): def randint(self, a: int, b: int) -> int: ... if sys.version_info >= (3, 9): def randbytes(self, n: int) -> bytes: ... + def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ... def choices( self, @@ -34,15 +96,21 @@ class Random(_random.Random): ) -> list[_T]: ... else: def sample(self, population: 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: float | None = ...) -> 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: ... + if sys.version_info >= (3, 11): + def gauss(self, mu: float = ..., sigma: float = ...) -> float: ... + def normalvariate(self, mu: float = ..., sigma: float = ...) -> float: ... + else: + def gauss(self, mu: float, sigma: float) -> float: ... + def normalvariate(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: ... @@ -54,41 +122,29 @@ class SystemRandom(Random): def setstate(self, *args: Any, **kwds: Any) -> NoReturn: ... # ----- 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: 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: SupportsLenAndGetItem[_T]) -> _T: ... -def choices( - population: SupportsLenAndGetItem[_T], - weights: Sequence[float] | None = ..., - *, - cum_weights: Sequence[float] | None = ..., - k: int = ..., -) -> list[_T]: ... -def shuffle(x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... +_inst: Random = ... +seed = _inst.seed +random = _inst.random +uniform = _inst.uniform +triangular = _inst.triangular +randint = _inst.randint +choice = _inst.choice +randrange = _inst.randrange +sample = _inst.sample +shuffle = _inst.shuffle +choices = _inst.choices +normalvariate = _inst.normalvariate +lognormvariate = _inst.lognormvariate +expovariate = _inst.expovariate +vonmisesvariate = _inst.vonmisesvariate +gammavariate = _inst.gammavariate +gauss = _inst.gauss +betavariate = _inst.betavariate +paretovariate = _inst.paretovariate +weibullvariate = _inst.weibullvariate +getstate = _inst.getstate +setstate = _inst.setstate +getrandbits = _inst.getrandbits if sys.version_info >= (3, 9): - def sample(population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... - -else: - def sample(population: 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: float | None = ...) -> 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: ... + randbytes = _inst.randbytes diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 01a60d170c50..b9c41e1caa16 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,4 +1,5 @@ import enum +import sre_compile import sys from sre_constants import error as error from typing import Any, AnyStr, Callable, Iterator, Union, overload @@ -9,24 +10,123 @@ if sys.version_info >= (3, 7): else: from typing import Match, Pattern +if sys.version_info >= (3, 11): + __all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "template", + "escape", + "error", + "Pattern", + "Match", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", + "RegexFlag", + "NOFLAG", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "template", + "escape", + "error", + "Pattern", + "Match", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", + ] +else: + __all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "template", + "escape", + "error", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", + ] + 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 = sre_compile.SRE_FLAG_ASCII + ASCII = A + DEBUG = sre_compile.SRE_FLAG_DEBUG + I = sre_compile.SRE_FLAG_IGNORECASE + IGNORECASE = I + L = sre_compile.SRE_FLAG_LOCALE + LOCALE = L + M = sre_compile.SRE_FLAG_MULTILINE + MULTILINE = M + S = sre_compile.SRE_FLAG_DOTALL + DOTALL = S + X = sre_compile.SRE_FLAG_VERBOSE + VERBOSE = X + U = sre_compile.SRE_FLAG_UNICODE + UNICODE = U + T = sre_compile.SRE_FLAG_TEMPLATE + TEMPLATE = T + if sys.version_info >= (3, 11): + NOFLAG: int A = RegexFlag.A ASCII = RegexFlag.ASCII @@ -45,12 +145,19 @@ U = RegexFlag.U UNICODE = RegexFlag.UNICODE T = RegexFlag.T TEMPLATE = RegexFlag.TEMPLATE +if sys.version_info >= (3, 11): + NOFLAG = RegexFlag.NOFLAG _FlagsType = Union[int, RegexFlag] if sys.version_info < (3, 7): # undocumented _pattern_type: type +# Type-wise these overloads are unnecessary, they could also be modeled using +# unions in the parameter types. However mypy has a bug regarding TypeVar +# constraints (https://github.com/python/mypy/issues/11880), +# which limits us here because AnyStr is a constrained TypeVar. + @overload def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... @overload @@ -63,8 +170,6 @@ def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... @overload def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... - -# New in Python 3.4 @overload def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... @overload diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index fd3a4b1dcc65..df08a3cc25ff 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,10 +1,11 @@ import sys from _typeshed import StrOrBytesPath -from typing import Callable, Optional, Sequence +from typing import Callable, Sequence if sys.platform != "win32": - _CompleterT = Optional[Callable[[str, int], Optional[str]]] - _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + _Completer = Callable[[str, int], str | None] + _CompDisp = Callable[[str, Sequence[str], int], None] + def parse_and_bind(__string: str) -> None: ... def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... def get_line_buffer() -> str: ... @@ -22,13 +23,13 @@ if sys.platform != "win32": def replace_history_item(__pos: int, __line: str) -> None: ... def add_history(__string: str) -> None: ... def set_auto_history(__enabled: bool) -> None: ... - def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... - def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... - def set_completer(__function: _CompleterT = ...) -> None: ... - def get_completer() -> _CompleterT: ... + def set_startup_hook(__function: Callable[[], object] | None = ...) -> None: ... + def set_pre_input_hook(__function: Callable[[], object] | None = ...) -> None: ... + def set_completer(__function: _Completer | None = ...) -> None: ... + def get_completer() -> _Completer | None: ... 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: ... + def set_completion_display_matches_hook(__function: _CompDisp | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 2095c0af6983..2d114a7c4f26 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -2,6 +2,8 @@ from array import array from collections import deque from typing import Any, Callable +__all__ = ["Repr", "repr", "recursive_repr"] + _ReprFunc = Callable[[Any], str] def recursive_repr(fillvalue: str = ...) -> Callable[[_ReprFunc], _ReprFunc]: ... diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 19a6f470b775..427f4995ecfd 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -61,6 +61,7 @@ if sys.platform != "win32": def ru_nvcsw(self) -> int: ... @property def ru_nivcsw(self) -> int: ... + def getpagesize() -> int: ... def getrlimit(__resource: int) -> tuple[int, int]: ... def getrusage(__who: int) -> struct_rusage: ... diff --git a/mypy/typeshed/stdlib/rlcompleter.pyi b/mypy/typeshed/stdlib/rlcompleter.pyi index f971c424213d..1840b7cfced7 100644 --- a/mypy/typeshed/stdlib/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/rlcompleter.pyi @@ -1,5 +1,9 @@ from typing import Any +__all__ = ["Completer"] + class Completer: def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... def complete(self, text: str, state: int) -> str | None: ... + def attr_matches(self, text: str) -> list[str]: ... + def global_matches(self, text: str) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi index 371fa9d07cf8..05e0ec65dc49 100644 --- a/mypy/typeshed/stdlib/runpy.pyi +++ b/mypy/typeshed/stdlib/runpy.pyi @@ -2,6 +2,8 @@ from _typeshed import Self from types import ModuleType from typing import Any +__all__ = ["run_module", "run_path"] + class _TempModule: mod_name: str module: ModuleType diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index 71aacc5c2610..dff781b0c176 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -1,14 +1,30 @@ +import sys from typing import Any, Callable, NamedTuple -class Event(NamedTuple): - time: float - priority: Any - action: Callable[..., Any] - argument: tuple[Any, ...] - kwargs: dict[str, Any] +__all__ = ["scheduler"] + +if sys.version_info >= (3, 10): + class Event(NamedTuple): + time: float + priority: Any + sequence: int + action: Callable[..., Any] + argument: tuple[Any, ...] + kwargs: dict[str, Any] + +else: + class Event(NamedTuple): + time: float + priority: Any + action: Callable[..., Any] + argument: tuple[Any, ...] + kwargs: dict[str, Any] class scheduler: - def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ... + timefunc: Callable[[], float] + delayfunc: Callable[[float], object] + + def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], object] = ...) -> None: ... def enterabs( self, time: float, diff --git a/mypy/typeshed/stdlib/secrets.pyi b/mypy/typeshed/stdlib/secrets.pyi index f57eef8492d7..99b7c14ebafc 100644 --- a/mypy/typeshed/stdlib/secrets.pyi +++ b/mypy/typeshed/stdlib/secrets.pyi @@ -3,6 +3,8 @@ from hmac import compare_digest as compare_digest from random import SystemRandom as SystemRandom from typing import TypeVar +__all__ = ["choice", "randbelow", "randbits", "SystemRandom", "token_bytes", "token_hex", "token_urlsafe", "compare_digest"] + _T = TypeVar("_T") def randbelow(exclusive_upper_bound: int) -> int: ... diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index e57504b5b447..d4a3656e110e 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import FileDescriptorLike, Self from types import TracebackType -from typing import Any, Iterable, Type +from typing import Any, Iterable +from typing_extensions import final if sys.platform != "win32": PIPE_BUF: int @@ -33,6 +34,7 @@ error = OSError if sys.platform != "linux" and sys.platform != "win32": # BSD only + @final class kevent: data: Any fflags: int @@ -50,6 +52,7 @@ if sys.platform != "linux" and sys.platform != "win32": udata: Any = ..., ) -> None: ... # BSD only + @final class kqueue: closed: bool def __init__(self) -> None: ... @@ -100,14 +103,15 @@ if sys.platform != "linux" and sys.platform != "win32": KQ_NOTE_WRITE: int if sys.platform == "linux": + @final class epoll: def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( self, - exc_type: Type[BaseException] | None = ..., - exc_val: BaseException | None = ..., - exc_tb: TracebackType | None = ..., + __exc_type: type[BaseException] | None = ..., + __exc_val: BaseException | None = ..., + __exc_tb: TracebackType | None = ..., ) -> None: ... def close(self) -> None: ... closed: bool diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index 90b2aafa4f03..2a211ab34208 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,7 +1,10 @@ from _typeshed import Self from collections.abc import Iterator, MutableMapping +from dbm import _TFlags from types import TracebackType -from typing import Type, TypeVar, overload +from typing import TypeVar, overload + +__all__ = ["Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] _T = TypeVar("_T") _VT = TypeVar("_VT") @@ -19,9 +22,10 @@ class Shelf(MutableMapping[str, _VT]): def __getitem__(self, key: str) -> _VT: ... def __setitem__(self, key: str, value: _VT) -> None: ... def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: str) -> bool: ... # type: ignore[override] def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def close(self) -> None: ... def sync(self) -> None: ... @@ -34,6 +38,6 @@ class BsdDbShelf(Shelf[_VT]): def last(self) -> tuple[str, _VT]: ... class DbfilenameShelf(Shelf[_VT]): - def __init__(self, filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> None: ... + def __init__(self, filename: str, flag: _TFlags = ..., protocol: int | None = ..., writeback: bool = ...) -> None: ... -def open(filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> Shelf[object]: ... +def open(filename: str, flag: _TFlags = ..., protocol: int | None = ..., writeback: bool = ...) -> Shelf[object]: ... diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index dfe554b0a773..6385011575a4 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,5 +1,11 @@ import sys -from typing import Any, Iterable, TextIO, TypeVar +from _typeshed import Self +from typing import Iterable, TextIO + +if sys.version_info >= (3, 8): + __all__ = ["shlex", "split", "quote", "join"] +else: + __all__ = ["shlex", "split", "quote"] def split(s: str, comments: bool = ..., posix: bool = ...) -> list[str]: ... @@ -8,8 +14,6 @@ if sys.version_info >= (3, 8): def quote(s: str) -> str: ... -_SLT = TypeVar("_SLT", bound=shlex) - class shlex(Iterable[str]): commenters: str wordchars: str @@ -18,14 +22,18 @@ class shlex(Iterable[str]): quotes: str escapedquotes: str whitespace_split: bool - infile: str + infile: str | None instream: TextIO source: str debug: int lineno: int token: str eof: str - punctuation_chars: str + if sys.version_info >= (3, 7): + @property + def punctuation_chars(self) -> str: ... + else: + punctuation_chars: str def __init__( self, instream: str | TextIO | None = ..., @@ -37,9 +45,8 @@ class shlex(Iterable[str]): def push_token(self, tok: str) -> None: ... def read_token(self) -> str: ... def sourcehook(self, newfile: str) -> tuple[str, TextIO]: ... - # TODO argument types - def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... + def push_source(self, newstream: str | TextIO, newfile: str | None = ...) -> None: ... def pop_source(self) -> None: ... def error_leader(self, infile: str | None = ..., lineno: int | None = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index f4c492caccaf..030f16cd99b7 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,9 +1,39 @@ import os import sys -from _typeshed import StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload -_PathT = TypeVar("_PathT", str, os.PathLike[str]) +__all__ = [ + "copyfileobj", + "copyfile", + "copymode", + "copystat", + "copy", + "copy2", + "copytree", + "move", + "rmtree", + "Error", + "SpecialFileError", + "ExecError", + "make_archive", + "get_archive_formats", + "register_archive_format", + "unregister_archive_format", + "get_unpack_formats", + "register_unpack_format", + "unregister_unpack_format", + "unpack_archive", + "ignore_patterns", + "chown", + "which", + "get_terminal_size", + "SameFileError", + "disk_usage", +] + +_StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) +_StrPathT = TypeVar("_StrPathT", bound=StrPath) # Return value of some functions that may either return a path-like object that was passed in or # a string _PathReturn = Any @@ -16,11 +46,17 @@ class ReadError(OSError): ... class RegistryError(Exception): ... def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... -def copyfile(src: StrPath, dst: _PathT, *, follow_symlinks: bool = ...) -> _PathT: ... -def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... -def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... +def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = ...) -> _StrOrBytesPathT: ... +def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... +def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... +@overload def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload +def copy(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload +def copy2(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... if sys.version_info >= (3, 8): @@ -44,10 +80,13 @@ else: ignore_dangling_symlinks: bool = ..., ) -> _PathReturn: ... -def rmtree(path: bytes | StrPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... +def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... _CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] +# N.B. shutil.move appears to take bytes arguments, however, +# this does not work when dst is (or is within) an existing directory. +# (#6832) if sys.version_info >= (3, 9): def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... @@ -61,16 +100,27 @@ class _ntuple_diskusage(NamedTuple): free: int def disk_usage(path: int | StrOrBytesPath) -> _ntuple_diskusage: ... -def chown(path: StrPath, user: str | int | None = ..., group: str | int | None = ...) -> None: ... + +# While chown can be imported on Windows, it doesn't actually work; +# see https://bugs.python.org/issue33140. We keep it here because it's +# in __all__. +@overload +def chown(path: StrOrBytesPath, user: str | int, group: None = ...) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: None = ..., *, group: str | int) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: None, group: str | int) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: str | int, group: str | int) -> None: ... if sys.version_info >= (3, 8): @overload - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + def which(cmd: _StrPathT, mode: int = ..., path: StrPath | None = ...) -> str | _StrPathT | None: ... @overload def which(cmd: bytes, mode: int = ..., path: StrPath | None = ...) -> bytes | None: ... else: - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + def which(cmd: _StrPathT, mode: int = ..., path: StrPath | None = ...) -> str | _StrPathT | None: ... def make_archive( base_name: str, @@ -84,11 +134,13 @@ def make_archive( logger: Any | None = ..., ) -> str: ... def get_archive_formats() -> list[tuple[str, str]]: ... +@overload def register_archive_format( - name: str, - function: Callable[..., Any], - extra_args: Sequence[tuple[str, Any] | list[Any]] | None = ..., - description: str = ..., + name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = ... +) -> None: ... +@overload +def register_archive_format( + name: str, function: Callable[[str, str], object], extra_args: None = ..., description: str = ... ) -> None: ... def unregister_archive_format(name: str) -> None: ... @@ -99,8 +151,17 @@ else: # See http://bugs.python.org/issue30218 def unpack_archive(filename: str, extract_dir: StrPath | None = ..., format: str | None = ...) -> None: ... +@overload +def register_unpack_format( + name: str, + extensions: list[str], + function: Callable[..., object], + extra_args: Sequence[tuple[str, Any]], + description: str = ..., +) -> None: ... +@overload def register_unpack_format( - name: str, extensions: list[str], function: Any, extra_args: Sequence[tuple[str, Any]] | None = ..., description: str = ... + name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = ..., description: str = ... ) -> None: ... def unregister_unpack_format(name: str) -> None: ... def get_unpack_formats() -> list[tuple[str, list[str], str]]: ... diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 777391662aa3..50f1e0ff0cf1 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -63,9 +63,15 @@ SIG_IGN: Handlers _SIGNUM = Union[int, Signals] _HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] -def default_int_handler(signum: int, frame: FrameType | None) -> None: ... -def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... -def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... +def default_int_handler(__signalnum: int, __frame: FrameType | None) -> None: ... + +if sys.version_info >= (3, 10): # arguments changed in 3.10.2 + def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... + def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... + +else: + def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... + def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... SIGABRT: Signals SIGEMT: Signals @@ -105,10 +111,12 @@ else: SIGWINCH: Signals SIGXCPU: Signals SIGXFSZ: Signals + class ItimerError(IOError): ... ITIMER_PROF: int ITIMER_REAL: int ITIMER_VIRTUAL: int + class Sigmasks(IntEnum): SIG_BLOCK: int SIG_UNBLOCK: int @@ -120,11 +128,18 @@ else: def getitimer(__which: int) -> tuple[float, float]: ... def pause() -> None: ... def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... - def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... + if sys.version_info >= (3, 10): # arguments changed in 3.10.2 + def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... + else: + def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... + def setitimer(__which: int, __seconds: float, __interval: float = ...) -> tuple[float, float]: ... def siginterrupt(__signalnum: int, __flag: bool) -> None: ... def sigpending() -> Any: ... - def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... + if sys.version_info >= (3, 10): # argument changed in 3.10.2 + def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... + else: + def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... if sys.platform != "darwin": SIGCLD: Signals SIGPOLL: Signals @@ -147,6 +162,7 @@ else: def si_status(self) -> int: ... @property def si_band(self) -> int: ... + def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... @@ -160,3 +176,7 @@ if sys.version_info >= (3, 7): else: def set_wakeup_fd(fd: int) -> int: ... + +if sys.version_info >= (3, 9): + if sys.platform == "linux": + def pidfd_send_signal(__pidfd: int, __sig: int, __siginfo: None = ..., __flags: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index e5401552caae..037f62a8d6e1 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -1,8 +1,14 @@ import asynchat import asyncore import socket +import sys from collections import defaultdict -from typing import Any, Type +from typing import Any + +if sys.version_info >= (3, 11): + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy"] +else: + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", "MailmanProxy"] _Address = tuple[str, int] # (host, port) @@ -56,7 +62,7 @@ class SMTPChannel(asynchat.async_chat): def smtp_EXPN(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] + channel_class: type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool @@ -79,5 +85,6 @@ class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] -class MailmanProxy(PureProxy): - def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] +if sys.version_info < (3, 11): + class MailmanProxy(PureProxy): + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 0a57f1f5d2de..5bf95d2eec8c 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -4,7 +4,41 @@ from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Pattern, Protocol, Sequence, Type, Union, overload +from typing import Any, Pattern, Protocol, Sequence, Union, overload + +if sys.version_info >= (3, 7): + __all__ = [ + "SMTPException", + "SMTPNotSupportedError", + "SMTPServerDisconnected", + "SMTPResponseException", + "SMTPSenderRefused", + "SMTPRecipientsRefused", + "SMTPDataError", + "SMTPConnectError", + "SMTPHeloError", + "SMTPAuthenticationError", + "quoteaddr", + "quotedata", + "SMTP", + "SMTP_SSL", + ] +else: + __all__ = [ + "SMTPException", + "SMTPServerDisconnected", + "SMTPResponseException", + "SMTPSenderRefused", + "SMTPRecipientsRefused", + "SMTPDataError", + "SMTPConnectError", + "SMTPHeloError", + "SMTPAuthenticationError", + "quoteaddr", + "quotedata", + "SMTP", + "SMTP_SSL", + ] _Reply = tuple[int, bytes] _SendErrs = dict[str, _Reply] @@ -79,7 +113,7 @@ class SMTP: ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... def connect(self, host: str = ..., port: int = ..., source_address: _SourceAddress | None = ...) -> _Reply: ... diff --git a/mypy/typeshed/stdlib/sndhdr.pyi b/mypy/typeshed/stdlib/sndhdr.pyi index 84d6441a83b1..f4d487607fbb 100644 --- a/mypy/typeshed/stdlib/sndhdr.pyi +++ b/mypy/typeshed/stdlib/sndhdr.pyi @@ -1,6 +1,8 @@ from _typeshed import StrOrBytesPath from typing import NamedTuple +__all__ = ["what", "whathdr"] + class SndHeaders(NamedTuple): filetype: str framerate: int diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 430fef4ff344..461ea41406c8 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -3,7 +3,7 @@ from _typeshed import ReadableBuffer, Self, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag from io import RawIOBase -from typing import Any, BinaryIO, TextIO, TypeVar, overload +from typing import Any, BinaryIO, TextIO, overload from typing_extensions import Literal # Ideally, we'd just do "from _socket import *". Unfortunately, socket @@ -12,8 +12,6 @@ from typing_extensions import Literal import _socket from _socket import ( _FD, - CMSG_LEN as CMSG_LEN, - CMSG_SPACE as CMSG_SPACE, EAI_ADDRFAMILY as EAI_ADDRFAMILY, EAI_AGAIN as EAI_AGAIN, EAI_BADFLAGS as EAI_BADFLAGS, @@ -213,7 +211,7 @@ from _socket import ( if sys.version_info >= (3, 7): from _socket import close as close if sys.platform != "win32": - from _socket import sethostname as sethostname + from _socket import CMSG_LEN as CMSG_LEN, CMSG_SPACE as CMSG_SPACE, sethostname as sethostname if sys.platform != "win32" or sys.version_info >= (3, 8): from _socket import if_indextoname as if_indextoname, if_nameindex as if_nameindex, if_nametoindex as if_nametoindex if sys.platform == "linux": @@ -366,6 +364,8 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): SO_J1939_PROMISC as SO_J1939_PROMISC, SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, ) +if sys.platform == "linux" and sys.version_info >= (3, 10): + from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP if sys.platform == "win32": from _socket import ( RCVALL_IPLEVEL as RCVALL_IPLEVEL, @@ -378,8 +378,6 @@ if sys.platform == "win32": SIO_RCVALL as SIO_RCVALL, ) -_T = TypeVar("_T") - # Re-exported from errno EBADF: int EAGAIN: int @@ -544,7 +542,7 @@ class socket(_socket.socket): ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: object) -> None: ... - def dup(self: _T) -> _T: ... # noqa: F811 + def dup(self: Self) -> Self: ... # noqa: F811 def accept(self) -> tuple[socket, _RetAddress]: ... # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index c663e73bef50..9bdd8ccfe31f 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -2,22 +2,60 @@ import sys import types from _typeshed import Self from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, ClassVar, Union + +if sys.platform == "win32": + __all__ = [ + "BaseServer", + "TCPServer", + "UDPServer", + "ThreadingUDPServer", + "ThreadingTCPServer", + "BaseRequestHandler", + "StreamRequestHandler", + "DatagramRequestHandler", + "ThreadingMixIn", + ] +else: + __all__ = [ + "BaseServer", + "TCPServer", + "UDPServer", + "ThreadingUDPServer", + "ThreadingTCPServer", + "BaseRequestHandler", + "StreamRequestHandler", + "DatagramRequestHandler", + "ThreadingMixIn", + "ForkingUDPServer", + "ForkingTCPServer", + "ForkingMixIn", + "UnixStreamServer", + "UnixDatagramServer", + "ThreadingUnixStreamServer", + "ThreadingUnixDatagramServer", + ] -_T = TypeVar("_T") _RequestType = Union[_socket, tuple[bytes, _socket]] _AddressType = Union[tuple[str, int], str] +# This can possibly be generic at some point: class BaseServer: address_family: int - RequestHandlerClass: Callable[..., BaseRequestHandler] server_address: tuple[str, int] socket: _socket allow_reuse_address: bool request_queue_size: int socket_type: int timeout: float | None - def __init__(self, server_address: Any, RequestHandlerClass: Callable[..., BaseRequestHandler]) -> None: ... + def __init__( + self: Self, server_address: Any, RequestHandlerClass: Callable[[Any, Any, Self], BaseRequestHandler] + ) -> None: ... + # It is not actually a `@property`, but we need a `Self` type: + @property + def RequestHandlerClass(self: Self) -> Callable[[Any, Any, Self], BaseRequestHandler]: ... + @RequestHandlerClass.setter + def RequestHandlerClass(self: Self, val: Callable[[Any, Any, Self], BaseRequestHandler]) -> None: ... def fileno(self) -> int: ... def handle_request(self) -> None: ... def serve_forever(self, poll_interval: float = ...) -> None: ... @@ -33,56 +71,41 @@ class BaseServer: def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def service_actions(self) -> None: ... def shutdown_request(self, request: _RequestType) -> None: ... # undocumented def close_request(self, request: _RequestType) -> None: ... # undocumented class TCPServer(BaseServer): + allow_reuse_port: bool + request_queue_size: int def __init__( - self, + self: Self, server_address: tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], + RequestHandlerClass: Callable[[Any, Any, Self], BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... def get_request(self) -> tuple[_socket, Any]: ... - def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... - def shutdown_request(self, request: _RequestType) -> None: ... # undocumented - def close_request(self, request: _RequestType) -> None: ... # undocumented class UDPServer(BaseServer): max_packet_size: ClassVar[int] - def __init__( - self, - server_address: tuple[str, int], - RequestHandlerClass: Callable[..., BaseRequestHandler], - bind_and_activate: bool = ..., - ) -> None: ... def get_request(self) -> tuple[tuple[bytes, _socket], Any]: ... - def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... - def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... - def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... - def shutdown_request(self, request: _RequestType) -> None: ... # undocumented - def close_request(self, request: _RequestType) -> None: ... # undocumented if sys.platform != "win32": class UnixStreamServer(BaseServer): def __init__( - self, + self: Self, server_address: str | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], + RequestHandlerClass: Callable[[Any, Any, Self], BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... + class UnixDatagramServer(BaseServer): def __init__( - self, + self: Self, server_address: str | bytes, - RequestHandlerClass: Callable[..., BaseRequestHandler], + RequestHandlerClass: Callable[[Any, Any, Self], BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 7a62d62523f5..82d9b8dbfffc 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -24,5 +24,6 @@ if sys.platform != "win32": def sp_expire(self) -> int: ... @property def sp_flag(self) -> int: ... + def getspall() -> list[struct_spwd]: ... def getspnam(__arg: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index d5d20d67b58e..d747be90fd0a 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -1 +1 @@ -from sqlite3.dbapi2 import * # noqa: F403 +from sqlite3.dbapi2 import * diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index ea9098940d4b..456c94362a8e 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self, StrOrBytesPath from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, Type, TypeVar +from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, TypeVar +from typing_extensions import Literal, final _T = TypeVar("_T") @@ -94,7 +95,7 @@ if sys.version_info >= (3, 7): detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., uri: bool = ..., ) -> Connection: ... @@ -106,14 +107,14 @@ else: detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., uri: bool = ..., ) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... +def register_adapter(__type: type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... if sys.version_info < (3, 8): @@ -151,6 +152,7 @@ class Connection: def create_function(self, name: str, narg: int, func: Any, *, deterministic: bool = ...) -> None: ... else: def create_function(self, name: str, num_params: int, func: Any) -> None: ... + def cursor(self, cursorClass: type | None = ...) -> Cursor: ... def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... # TODO: please check in executemany() if seq_of_parameters type is possible like this @@ -178,9 +180,10 @@ class Connection: name: str = ..., sleep: float = ..., ) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: type | None, exc: BaseException | None, tb: Any | None) -> None: ... + def __exit__(self, __type: type | None, __value: BaseException | None, __traceback: Any | None) -> Literal[False]: ... class Cursor(Iterator[Any]): arraysize: Any @@ -202,7 +205,7 @@ class Cursor(Iterator[Any]): def fetchone(self) -> Any: ... def setinputsizes(self, __sizes: object) -> None: ... # does nothing def setoutputsize(self, __size: object, __column: object = ...) -> None: ... # does nothing - def __iter__(self) -> Cursor: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> Any: ... class DataError(DatabaseError): ... @@ -221,6 +224,7 @@ class OperationalError(DatabaseError): ... OptimizedUnicode = str +@final class PrepareProtocol: def __init__(self, *args: Any, **kwargs: Any) -> None: ... @@ -229,18 +233,19 @@ class ProgrammingError(DatabaseError): ... class Row: def __init__(self, *args: Any, **kwargs: Any) -> None: ... def keys(self): ... - def __eq__(self, other): ... - def __ge__(self, other): ... - def __getitem__(self, index): ... - def __gt__(self, other): ... + 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 __le__(self, __other): ... def __len__(self): ... - def __lt__(self, other): ... - def __ne__(self, other): ... + def __lt__(self, __other): ... + def __ne__(self, __other): ... if sys.version_info < (3, 8): + @final class Statement: def __init__(self, *args, **kwargs): ... diff --git a/mypy/typeshed/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi index df7e1a28007b..00644994fe3e 100644 --- a/mypy/typeshed/stdlib/sre_constants.pyi +++ b/mypy/typeshed/stdlib/sre_constants.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any MAXGROUPS: int @@ -15,7 +16,7 @@ class error(Exception): class _NamedIntConstant(int): name: Any - def __new__(cls, value: int, name: str) -> _NamedIntConstant: ... + def __new__(cls: type[Self], value: int, name: str) -> Self: ... MAXREPEAT: _NamedIntConstant OPCODES: list[_NamedIntConstant] diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index c4de55bcbf7e..56d551180f5f 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -54,6 +54,7 @@ class SubPattern: else: pattern: Pattern def __init__(self, pattern: Pattern, data: list[_CodeType] | None = ...) -> None: ... + def dump(self, level: int = ...) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: int | slice) -> None: ... @@ -77,6 +78,7 @@ class Tokenizer: def getuntil(self, terminator: str, name: str) -> str: ... else: def getuntil(self, terminator: str) -> str: ... + @property def pos(self) -> int: ... def tell(self) -> int: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index cdb727285647..83932e5790c4 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -2,8 +2,8 @@ import enum import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Type, Union, overload -from typing_extensions import Literal, TypedDict +from typing import Any, Callable, Iterable, NamedTuple, Optional, Union, overload +from typing_extensions import Literal, TypedDict, final _PCTRTT = tuple[tuple[str, str], ...] _PCTRTTT = tuple[_PCTRTT, ...] @@ -294,9 +294,9 @@ class _ASN1Object(NamedTuple): longname: str oid: str @classmethod - def fromnid(cls: Type[Self], nid: int) -> Self: ... + def fromnid(cls: type[Self], nid: int) -> Self: ... @classmethod - def fromname(cls: Type[Self], name: str) -> Self: ... + def fromname(cls: type[Self], name: str) -> Self: ... class Purpose(_ASN1Object, enum.Enum): SERVER_AUTH: _ASN1Object @@ -307,7 +307,8 @@ class SSLSocket(socket.socket): server_side: bool server_hostname: str | None session: SSLSession | None - session_reused: bool | None + @property + def session_reused(self) -> bool | None: ... if sys.version_info >= (3, 7): def __init__(self, *args: Any, **kwargs: Any) -> None: ... else: @@ -332,6 +333,7 @@ class SSLSocket(socket.socket): _context: SSLContext | None = ..., _session: Any | None = ..., ) -> None: ... + def connect(self, addr: socket._Address | bytes) -> None: ... def connect_ex(self, addr: socket._Address | bytes) -> int: ... def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... @@ -391,12 +393,15 @@ class SSLContext: maximum_version: TLSVersion minimum_version: TLSVersion sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None - sslobject_class: ClassVar[Type[SSLObject]] - sslsocket_class: ClassVar[Type[SSLSocket]] + # The following two attributes have class-level defaults. + # However, the docs explicitly state that it's OK to override these attributes on instances, + # so making these ClassVars wouldn't be appropriate + sslobject_class: type[SSLObject] + sslsocket_class: type[SSLSocket] if sys.version_info >= (3, 8): keylog_filename: str post_handshake_auth: bool - def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> SSLContext: ... + def __new__(cls: type[Self], protocol: int = ..., *args: Any, **kwargs: Any) -> Self: ... def __init__(self, protocol: int = ...) -> None: ... def cert_store_stats(self) -> dict[str, int]: ... def load_cert_chain( @@ -416,6 +421,7 @@ class SSLContext: def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... else: def set_servername_callback(self, __method: _SrvnmeCbType | None) -> None: ... + def load_dh_params(self, __path: str) -> None: ... def set_ecdh_curve(self, __name: str) -> None: ... def wrap_socket( @@ -439,14 +445,18 @@ class SSLContext: class SSLObject: context: SSLContext - server_side: bool - server_hostname: str | None + @property + def server_side(self) -> bool: ... + @property + def server_hostname(self) -> str | None: ... session: SSLSession | None - session_reused: bool + @property + def session_reused(self) -> bool: ... if sys.version_info >= (3, 7): def __init__(self, *args: Any, **kwargs: Any) -> None: ... else: def __init__(self, sslobj: Any, owner: SSLSocket | SSLObject | None = ..., session: Any | None = ...) -> None: ... + def read(self, len: int = ..., buffer: bytearray | None = ...) -> bytes: ... def write(self, data: bytes) -> int: ... @overload @@ -468,6 +478,7 @@ class SSLObject: if sys.version_info >= (3, 8): def verify_client_post_handshake(self) -> None: ... +@final class MemoryBIO: pending: int eof: bool @@ -475,6 +486,7 @@ class MemoryBIO: def write(self, __buf: bytes) -> int: ... def write_eof(self) -> None: ... +@final class SSLSession: id: bytes time: int diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 908d6adaf45d..879ea3c74ec7 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -1,10 +1,69 @@ import sys -from _typeshed import SupportsRichComparisonT +from _typeshed import Self, SupportsRichComparisonT from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, Type, TypeVar, Union +from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar, Union +from typing_extensions import Literal + +if sys.version_info >= (3, 10): + __all__ = [ + "NormalDist", + "StatisticsError", + "correlation", + "covariance", + "fmean", + "geometric_mean", + "harmonic_mean", + "linear_regression", + "mean", + "median", + "median_grouped", + "median_high", + "median_low", + "mode", + "multimode", + "pstdev", + "pvariance", + "quantiles", + "stdev", + "variance", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "NormalDist", + "StatisticsError", + "fmean", + "geometric_mean", + "harmonic_mean", + "mean", + "median", + "median_grouped", + "median_high", + "median_low", + "mode", + "multimode", + "pstdev", + "pvariance", + "quantiles", + "stdev", + "variance", + ] +else: + __all__ = [ + "StatisticsError", + "pstdev", + "pvariance", + "stdev", + "variance", + "median", + "median_low", + "median_high", + "median_grouped", + "mean", + "mode", + "harmonic_mean", + ] -_T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types _Number = Union[float, Decimal, Fraction] _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) @@ -14,8 +73,13 @@ _HashableT = TypeVar("_HashableT", bound=Hashable) class StatisticsError(ValueError): ... -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 11): + def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = ...) -> float: ... + +elif sys.version_info >= (3, 8): def fmean(data: Iterable[SupportsFloat]) -> float: ... + +if sys.version_info >= (3, 8): def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... def mean(data: Iterable[_NumberT]) -> _NumberT: ... @@ -39,7 +103,9 @@ def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = ...) -> _NumberT: ... def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = ...) -> _NumberT: ... if sys.version_info >= (3, 8): - def quantiles(data: Iterable[_NumberT], *, n: int = ..., method: str = ...) -> list[_NumberT]: ... + def quantiles( + data: Iterable[_NumberT], *, n: int = ..., method: Literal["inclusive", "exclusive"] = ... + ) -> list[_NumberT]: ... def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = ...) -> _NumberT: ... def variance(data: Iterable[_NumberT], xbar: _NumberT | None = ...) -> _NumberT: ... @@ -58,7 +124,7 @@ if sys.version_info >= (3, 8): @property def variance(self) -> float: ... @classmethod - def from_samples(cls: Type[_T], data: Iterable[SupportsFloat]) -> _T: ... + def from_samples(cls: type[Self], data: Iterable[SupportsFloat]) -> Self: ... def samples(self, n: int, *, seed: Any | None = ...) -> list[float]: ... def pdf(self, x: float) -> float: ... def cdf(self, x: float) -> float: ... @@ -67,6 +133,8 @@ if sys.version_info >= (3, 8): def quantiles(self, n: int = ...) -> list[float]: ... if sys.version_info >= (3, 9): def zscore(self, x: float) -> float: ... + + def __eq__(self, x2: object) -> bool: ... def __add__(self, x2: float | NormalDist) -> NormalDist: ... def __sub__(self, x2: float | NormalDist) -> NormalDist: ... def __mul__(self, x2: float) -> NormalDist: ... @@ -81,7 +149,15 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 10): def correlation(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... def covariance(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... + class LinearRegression(NamedTuple): slope: float intercept: float + +if sys.version_info >= (3, 11): + def linear_regression( + __regressor: Sequence[_Number], __dependent_variable: Sequence[_Number], *, proportional: bool = ... + ) -> LinearRegression: ... + +elif sys.version_info >= (3, 10): def linear_regression(__regressor: Sequence[_Number], __dependent_variable: Sequence[_Number]) -> LinearRegression: ... diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 374d59959ac9..535f38545132 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -7,6 +7,21 @@ if sys.version_info >= (3, 8): else: from typing import Pattern +__all__ = [ + "ascii_letters", + "ascii_lowercase", + "ascii_uppercase", + "capwords", + "digits", + "hexdigits", + "octdigits", + "printable", + "punctuation", + "whitespace", + "Formatter", + "Template", +] + ascii_letters: str ascii_lowercase: str ascii_uppercase: str diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index 47af62973259..1f6c45a23c0a 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -2,6 +2,8 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Iterator +__all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpack", "Struct", "error"] + class error(Exception): ... def pack(fmt: str | bytes, *v: Any) -> bytes: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index fce517745ee6..a0e446d19c8e 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,12 +1,93 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, Type, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias +if sys.platform == "win32": + if sys.version_info >= (3, 7): + __all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", + "CREATE_NEW_CONSOLE", + "CREATE_NEW_PROCESS_GROUP", + "STD_INPUT_HANDLE", + "STD_OUTPUT_HANDLE", + "STD_ERROR_HANDLE", + "SW_HIDE", + "STARTF_USESTDHANDLES", + "STARTF_USESHOWWINDOW", + "STARTUPINFO", + "ABOVE_NORMAL_PRIORITY_CLASS", + "BELOW_NORMAL_PRIORITY_CLASS", + "HIGH_PRIORITY_CLASS", + "IDLE_PRIORITY_CLASS", + "NORMAL_PRIORITY_CLASS", + "REALTIME_PRIORITY_CLASS", + "CREATE_NO_WINDOW", + "DETACHED_PROCESS", + "CREATE_DEFAULT_ERROR_MODE", + "CREATE_BREAKAWAY_FROM_JOB", + ] + else: + __all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", + "CREATE_NEW_CONSOLE", + "CREATE_NEW_PROCESS_GROUP", + "STD_INPUT_HANDLE", + "STD_OUTPUT_HANDLE", + "STD_ERROR_HANDLE", + "SW_HIDE", + "STARTF_USESTDHANDLES", + "STARTF_USESHOWWINDOW", + "STARTUPINFO", + ] +else: + __all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", + ] + # 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 @@ -991,6 +1072,7 @@ class Popen(Generic[AnyStr]): encoding: str | None = ..., errors: str | None = ..., ) -> Popen[Any]: ... + def poll(self) -> int | None: ... if sys.version_info >= (3, 7): def wait(self, timeout: float | None = ...) -> int: ... @@ -1008,7 +1090,7 @@ class Popen(Generic[AnyStr]): def kill(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -1043,22 +1125,27 @@ 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 - SW_HIDE: int - STARTF_USESTDHANDLES: int - STARTF_USESHOWWINDOW: int - CREATE_NEW_CONSOLE: int - CREATE_NEW_PROCESS_GROUP: int + from _winapi import ( + CREATE_NEW_CONSOLE as CREATE_NEW_CONSOLE, + CREATE_NEW_PROCESS_GROUP as CREATE_NEW_PROCESS_GROUP, + STARTF_USESHOWWINDOW as STARTF_USESHOWWINDOW, + STARTF_USESTDHANDLES as STARTF_USESTDHANDLES, + STD_ERROR_HANDLE as STD_ERROR_HANDLE, + STD_INPUT_HANDLE as STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE as STD_OUTPUT_HANDLE, + SW_HIDE as SW_HIDE, + ) + 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 + from _winapi import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + CREATE_BREAKAWAY_FROM_JOB as CREATE_BREAKAWAY_FROM_JOB, + CREATE_DEFAULT_ERROR_MODE as CREATE_DEFAULT_ERROR_MODE, + CREATE_NO_WINDOW as CREATE_NO_WINDOW, + DETACHED_PROCESS as DETACHED_PROCESS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + ) diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 8393136aa795..f96dbaaf7be8 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self -from typing import IO, Any, NamedTuple, NoReturn, Union +from typing import IO, Any, NamedTuple, NoReturn, Union, overload +from typing_extensions import Literal _File = Union[str, IO[bytes]] @@ -72,7 +73,11 @@ class Au_write: 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 +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Au_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Au_write: ... +@overload def open(f: _File, mode: str | None = ...) -> Any: ... if sys.version_info < (3, 9): diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index bc25a4c4639b..91e95270901e 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,6 +1,8 @@ import sys from typing import Any, Sequence +__all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"] + def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... class SymbolTable: @@ -37,6 +39,7 @@ class Symbol: def is_nonlocal(self) -> bool: ... else: def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... + def get_name(self) -> str: ... def is_referenced(self) -> bool: ... def is_parameter(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index cb1545711d69..89b636cd08af 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -5,13 +5,26 @@ from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import Any, AsyncGenerator, Callable, NoReturn, Optional, Protocol, Sequence, TextIO, Type, TypeVar, Union, overload +from typing import ( + Any, + AsyncGenerator, + Callable, + Coroutine, + NoReturn, + Optional, + Protocol, + Sequence, + TextIO, + TypeVar, + Union, + overload, +) from typing_extensions import Literal, final _T = TypeVar("_T") # The following type alias are stub-only and do not exist during runtime -_ExcInfo = tuple[Type[BaseException], BaseException, TracebackType] +_ExcInfo = tuple[type[BaseException], BaseException, TracebackType] _OptExcInfo = Union[_ExcInfo, tuple[None, None, None]] # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` @@ -31,12 +44,12 @@ if sys.platform == "win32": dllhandle: int dont_write_bytecode: bool displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType | None], Any] +excepthook: Callable[[type[BaseException], BaseException, TracebackType | None], Any] exec_prefix: str executable: str -float_repr_style: str +float_repr_style: Literal["short", "legacy"] hexversion: int -last_type: Type[BaseException] | None +last_type: type[BaseException] | None last_value: BaseException | None last_traceback: TracebackType | None maxsize: int @@ -46,7 +59,7 @@ modules: dict[str, ModuleType] if sys.version_info >= (3, 10): orig_argv: list[str] path: list[str] -path_hooks: list[Any] # TODO precise type; function, path to finder +path_hooks: list[Callable[[str], PathEntryFinder]] path_importer_cache: dict[str, PathEntryFinder | None] platform: str if sys.version_info >= (3, 9): @@ -74,49 +87,105 @@ if sys.platform == "win32": winver: str _xoptions: dict[Any, Any] +# Type alias used as a mixin for structseq classes that cannot be instantiated at runtime +# This can't be represented in the type system, so we just use `structseq[Any]` +_uninstantiable_structseq = structseq[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, 10): + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int, int] +elif sys.version_info >= (3, 7): + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int] +else: + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int] + +@final +class _flags(_uninstantiable_structseq, _FlagTuple): + @property + def debug(self) -> int: ... + @property + def inspect(self) -> int: ... + @property + def interactive(self) -> int: ... + @property + def optimize(self) -> int: ... + @property + def dont_write_bytecode(self) -> int: ... + @property + def no_user_site(self) -> int: ... + @property + def no_site(self) -> int: ... + @property + def ignore_environment(self) -> int: ... + @property + def verbose(self) -> int: ... + @property + def bytes_warning(self) -> int: ... + @property + def quiet(self) -> int: ... + @property + def hash_randomization(self) -> int: ... + @property + def isolated(self) -> int: ... if sys.version_info >= (3, 7): - dev_mode: int - utf8_mode: int + @property + def dev_mode(self) -> bool: ... + @property + def utf8_mode(self) -> int: ... + if sys.version_info >= (3, 10): + @property + def warn_default_encoding(self) -> int: ... # undocumented 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 +@final +class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): + @property + def max(self) -> float: ... # DBL_MAX + @property + def max_exp(self) -> int: ... # DBL_MAX_EXP + @property + def max_10_exp(self) -> int: ... # DBL_MAX_10_EXP + @property + def min(self) -> float: ... # DBL_MIN + @property + def min_exp(self) -> int: ... # DBL_MIN_EXP + @property + def min_10_exp(self) -> int: ... # DBL_MIN_10_EXP + @property + def dig(self) -> int: ... # DBL_DIG + @property + def mant_dig(self) -> int: ... # DBL_MANT_DIG + @property + def epsilon(self) -> float: ... # DBL_EPSILON + @property + def radix(self) -> int: ... # FLT_RADIX + @property + def rounds(self) -> int: ... # FLT_ROUNDS hash_info: _hash_info -class _hash_info: - width: int - modulus: int - inf: int - nan: int - imag: int +@final +class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): + @property + def width(self) -> int: ... + @property + def modulus(self) -> int: ... + @property + def inf(self) -> int: ... + @property + def nan(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def algorithm(self) -> str: ... + @property + def hash_bits(self) -> int: ... + @property + def seed_bits(self) -> int: ... + @property + def cutoff(self) -> int: ... # undocumented implementation: _implementation @@ -125,16 +194,22 @@ class _implementation: version: _version_info hexversion: int cache_tag: str - _multiarch: str + # Define __getattr__, as the documentation states: + # > sys.implementation may contain additional attributes specific to the Python implementation. + # > These non-standard attributes must start with an underscore, and are not described here. + def __getattr__(self, name: str) -> Any: ... int_info: _int_info -class _int_info: - bits_per_digit: int - sizeof_digit: int +@final +class _int_info(structseq[int], tuple[int, int]): + @property + def bits_per_digit(self) -> int: ... + @property + def sizeof_digit(self) -> int: ... @final -class _version_info(structseq[Any | int], tuple[int, int, int, str, int]): +class _version_info(_uninstantiable_structseq, tuple[int, int, int, str, int]): @property def major(self) -> int: ... @property @@ -153,8 +228,8 @@ def _clear_type_cache() -> None: ... 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) -> None: ... +def __displayhook__(__value: object) -> None: ... +def __excepthook__(__exctype: type[BaseException], __value: BaseException, __traceback: TracebackType | None) -> None: ... def exc_info() -> _OptExcInfo: ... # sys.exit() accepts an optional argument of anything printable @@ -185,19 +260,31 @@ _TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, def gettrace() -> _TraceFunc | None: ... def settrace(tracefunc: _TraceFunc | None) -> 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": + # A tuple of length 5, even though it has more than 5 attributes. + @final + class _WinVersion(_uninstantiable_structseq, tuple[int, int, int, int, str]): + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def build(self) -> int: ... + @property + def platform(self) -> int: ... + @property + def service_pack(self) -> str: ... + @property + def service_pack_minor(self) -> int: ... + @property + def service_pack_major(self) -> int: ... + @property + def suite_mask(self) -> int: ... + @property + def product_type(self) -> int: ... + @property + def platform_version(self) -> tuple[int, int, int]: ... + def getwindowsversion() -> _WinVersion: ... def intern(__string: str) -> str: ... @@ -218,27 +305,44 @@ if sys.version_info < (3, 9): def getcheckinterval() -> int: ... # deprecated def setcheckinterval(__n: int) -> None: ... # deprecated +if sys.version_info < (3, 9): + # An 11-tuple or None + def callstats() -> tuple[int, int, int, int, int, int, int, int, int, int, int] | None: ... + if sys.version_info >= (3, 8): - # not exported by sys + # Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. class UnraisableHookArgs: - exc_type: Type[BaseException] + exc_type: type[BaseException] exc_value: BaseException | None exc_traceback: TracebackType | None err_msg: str | None object: _object | None unraisablehook: Callable[[UnraisableHookArgs], Any] + def __unraisablehook__(__unraisable: UnraisableHookArgs) -> Any: ... def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... _AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] -class _asyncgen_hooks(tuple[_AsyncgenHook, _AsyncgenHook]): - firstiter: _AsyncgenHook - finalizer: _AsyncgenHook +@final +class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): + @property + def firstiter(self) -> _AsyncgenHook: ... + @property + def finalizer(self) -> _AsyncgenHook: ... def get_asyncgen_hooks() -> _asyncgen_hooks: ... def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... +if sys.version_info >= (3, 6): + if sys.platform == "win32": + def _enablelegacywindowsfsencoding() -> None: ... + if sys.version_info >= (3, 7): def get_coroutine_origin_tracking_depth() -> int: ... def set_coroutine_origin_tracking_depth(depth: int) -> None: ... + +if sys.version_info < (3, 8): + _CoroWrapper = Callable[[Coroutine[Any, Any, Any]], Any] + def set_coroutine_wrapper(__wrapper: _CoroWrapper) -> None: ... + def get_coroutine_wrapper() -> _CoroWrapper: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index 17077144f6e9..13c40b927f4e 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -1,5 +1,19 @@ from typing import IO, Any, overload +__all__ = [ + "get_config_h_filename", + "get_config_var", + "get_config_vars", + "get_makefile_filename", + "get_path", + "get_path_names", + "get_paths", + "get_platform", + "get_python_version", + "get_scheme_names", + "parse_config_h", +] + def get_config_var(name: str) -> str | None: ... @overload def get_config_vars() -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/tabnanny.pyi b/mypy/typeshed/stdlib/tabnanny.pyi index 4c7be83b0511..020100031c14 100644 --- a/mypy/typeshed/stdlib/tabnanny.pyi +++ b/mypy/typeshed/stdlib/tabnanny.pyi @@ -1,6 +1,8 @@ from _typeshed import StrOrBytesPath from typing import Iterable +__all__ = ["check", "NannyNag", "process_tokens"] + verbose: int filename_only: int diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 4931a6f0e679..2837c46e1d21 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -2,13 +2,30 @@ import bz2 import io import sys from _typeshed import Self, StrOrBytesPath, StrPath +from builtins import type as Type # alias to avoid name clashes with fields named "type" from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Protocol, Type, TypeVar, overload +from typing import IO, Protocol, overload from typing_extensions import Literal -_TF = TypeVar("_TF", bound=TarFile) +__all__ = [ + "TarFile", + "TarInfo", + "is_tarfile", + "TarError", + "ReadError", + "CompressionError", + "StreamError", + "ExtractError", + "HeaderError", + "ENCODING", + "USTAR_FORMAT", + "GNU_FORMAT", + "PAX_FORMAT", + "DEFAULT_FORMAT", + "open", +] class _Fileobj(Protocol): def read(self, __size: int) -> bytes: ... @@ -78,7 +95,7 @@ def open( bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -100,12 +117,12 @@ class TarFile: mode: Literal["r", "a", "w", "x"] fileobj: _Fileobj | None format: int | None - tarinfo: Type[TarInfo] + tarinfo: type[TarInfo] dereference: bool | None ignore_zeros: bool | None encoding: str | None errors: str - fileobject: Type[ExFileObject] + fileobject: type[ExFileObject] pax_headers: Mapping[str, str] | None debug: int | None errorlevel: int | None @@ -116,7 +133,7 @@ class TarFile: mode: Literal["r", "a", "w", "x"] = ..., fileobj: _Fileobj | None = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -128,19 +145,19 @@ class TarFile: ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def __iter__(self) -> Iterator[TarInfo]: ... @classmethod def open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None = ..., mode: str = ..., fileobj: IO[bytes] | None = ..., # depends on mode bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -148,113 +165,113 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def taropen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "a", "w", "x"] = ..., fileobj: _Fileobj | None = ..., *, compresslevel: int = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _GzipReadableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _GzipWritableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _Bz2WritableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _Bz2ReadableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def xzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "w", "x"] = ..., fileobj: IO[bytes] | None = ..., preset: int | None = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> _list[TarInfo]: ... def getnames(self) -> _list[str]: ... @@ -298,6 +315,7 @@ class TarFile: *, filter: Callable[[TarInfo], TarInfo | None] | None = ..., ) -> None: ... + def addfile(self, tarinfo: TarInfo, fileobj: IO[bytes] | None = ...) -> None: ... def gettarinfo(self, name: str | None = ..., arcname: str | None = ..., fileobj: IO[bytes] | None = ...) -> TarInfo: ... def close(self) -> None: ... @@ -340,9 +358,9 @@ class TarInfo: pax_headers: Mapping[str, str] def __init__(self, name: str = ...) -> None: ... @classmethod - def frombuf(cls, buf: bytes, encoding: str, errors: str) -> TarInfo: ... + def frombuf(cls: Type[Self], buf: bytes, encoding: str, errors: str) -> Self: ... @classmethod - def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + def fromtarfile(cls: Type[Self], tarfile: TarFile) -> Self: ... @property def linkpath(self) -> str: ... @linkpath.setter diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index cf00856d9332..f522d206550d 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -2,6 +2,8 @@ import socket from _typeshed import Self from typing import Any, Callable, Match, Pattern, Sequence +__all__ = ["Telnet"] + DEBUGLEVEL: int TELNET_PORT: int diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 4aec26175a48..3821c002c542 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -2,12 +2,28 @@ import os import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Type, Union, overload +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = [ + "NamedTemporaryFile", + "TemporaryFile", + "SpooledTemporaryFile", + "TemporaryDirectory", + "mkstemp", + "mkdtemp", + "mktemp", + "TMP_MAX", + "gettempprefix", + "tempdir", + "gettempdir", + "gettempprefixb", + "gettempdirb", +] + # global variables TMP_MAX: int tempdir: str | None @@ -169,7 +185,7 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): delete: bool def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: ... # These methods don't exist directly on this object, but @@ -290,11 +306,10 @@ class SpooledTemporaryFile(IO[AnyStr]): prefix: str | None = ..., dir: str | None = ..., ) -> None: ... + def rollover(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... # 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. @@ -307,7 +322,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def readlines(self, hint: int = ...) -> list[AnyStr]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... - def truncate(self, size: int | None = ...) -> int: ... + def truncate(self, size: int | None = ...) -> None: ... # type: ignore[override] def write(self, s: AnyStr) -> int: ... def writelines(self, iterable: Iterable[AnyStr]) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... @@ -343,11 +358,10 @@ class TemporaryDirectory(Generic[AnyStr]): def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... @overload def __init__(self, suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> None: ... + def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index 7142df15715d..6ef2f6818827 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -243,4 +243,5 @@ if sys.platform != "win32": def tcdrain(__fd: FileDescriptorLike) -> None: ... def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/textwrap.pyi b/mypy/typeshed/stdlib/textwrap.pyi index 3b8fd5c0349a..aeb1d87141be 100644 --- a/mypy/typeshed/stdlib/textwrap.pyi +++ b/mypy/typeshed/stdlib/textwrap.pyi @@ -1,5 +1,7 @@ from typing import Callable, Pattern +__all__ = ["TextWrapper", "wrap", "fill", "dedent", "indent", "shorten"] + class TextWrapper: width: int initial_indent: str diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index 3e91221baed2..d6a64d0aefb5 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -8,7 +8,88 @@ _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") -__all__: list[str] +if sys.version_info >= (3, 10): + __all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", + "excepthook", + "ExceptHookArgs", + "gettrace", + "getprofile", + "get_native_id", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", + "excepthook", + "ExceptHookArgs", + "get_native_id", + ] +else: + __all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", + ] + +_profile_hook: _PF | None def active_count() -> int: ... def activeCount() -> int: ... # deprecated alias for active_count() @@ -35,13 +116,14 @@ TIMEOUT_MAX: float class ThreadError(Exception): ... class local: - def __getattribute__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... + 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: int | None + @property + def ident(self) -> int | None: ... daemon: bool def __init__( self, @@ -59,6 +141,7 @@ class Thread: if sys.version_info >= (3, 8): @property def native_id(self) -> int | None: ... # only available on some platforms + def is_alive(self) -> bool: ... if sys.version_info < (3, 9): def isAlive(self) -> bool: ... @@ -75,7 +158,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -86,9 +169,7 @@ class _RLock: def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... __enter__ = acquire - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... RLock = _RLock @@ -96,7 +177,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -108,9 +189,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... if sys.version_info >= (3, 9): @@ -145,9 +224,12 @@ class Timer(Thread): def cancel(self) -> None: ... class Barrier: - parties: int - n_waiting: int - broken: bool + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... def __init__(self, parties: int, action: Callable[[], None] | None = ..., timeout: float | None = ...) -> None: ... def wait(self, timeout: float | None = ...) -> int: ... def reset(self) -> None: ... diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 6e23b331d1c8..c1a8727b1ea0 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import structseq -from types import SimpleNamespace -from typing import Any, Union -from typing_extensions import final +from typing import Any, Protocol, Union +from typing_extensions import Literal, final _TimeTuple = tuple[int, int, int, int, int, int, int, int, int] @@ -80,7 +79,13 @@ def time() -> float: ... if sys.platform != "win32": def tzset() -> None: ... # Unix only -def get_clock_info(name: str) -> SimpleNamespace: ... +class _ClockInfo(Protocol): + adjustable: bool + implementation: str + monotonic: bool + resolution: float + +def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"]) -> _ClockInfo: ... def monotonic() -> float: ... def perf_counter() -> float: ... def process_time() -> float: ... @@ -94,6 +99,10 @@ 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: ... + + if sys.platform == "linux": + def pthread_getcpuclockid(thread_id: int) -> int: ... + def monotonic_ns() -> int: ... def perf_counter_ns() -> int: ... def process_time_ns() -> int: ... diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index d82dd80598dc..3135c21a6022 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,5 +1,7 @@ from typing import IO, Any, Callable, Sequence, Union +__all__ = ["Timer", "timeit", "repeat", "default_timer"] + _Timer = Callable[[], float] _Stmt = Union[str, Callable[[], Any]] @@ -25,7 +27,4 @@ def repeat( number: int = ..., globals: dict[str, Any] | None = ..., ) -> list[float]: ... - -_timerFunc = Callable[[], float] - -def main(args: Sequence[str] | None = ..., *, _wrap_timer: Callable[[_timerFunc], _timerFunc] | None = ...) -> None: ... +def main(args: Sequence[str] | None = ..., *, _wrap_timer: Callable[[_Timer], _Timer] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 50de97f48fdc..2393b0e5be49 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -5,9 +5,144 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Callable, Generic, Mapping, Optional, Protocol, Sequence, Type, TypeVar, Union, overload +from typing import Any, Callable, Generic, Mapping, Optional, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal, TypedDict +if sys.version_info >= (3, 9): + __all__ = [ + "TclError", + "NO", + "FALSE", + "OFF", + "YES", + "TRUE", + "ON", + "N", + "S", + "W", + "E", + "NW", + "SW", + "NE", + "SE", + "NS", + "EW", + "NSEW", + "CENTER", + "NONE", + "X", + "Y", + "BOTH", + "LEFT", + "TOP", + "RIGHT", + "BOTTOM", + "RAISED", + "SUNKEN", + "FLAT", + "RIDGE", + "GROOVE", + "SOLID", + "HORIZONTAL", + "VERTICAL", + "NUMERIC", + "CHAR", + "WORD", + "BASELINE", + "INSIDE", + "OUTSIDE", + "SEL", + "SEL_FIRST", + "SEL_LAST", + "END", + "INSERT", + "CURRENT", + "ANCHOR", + "ALL", + "NORMAL", + "DISABLED", + "ACTIVE", + "HIDDEN", + "CASCADE", + "CHECKBUTTON", + "COMMAND", + "RADIOBUTTON", + "SEPARATOR", + "SINGLE", + "BROWSE", + "MULTIPLE", + "EXTENDED", + "DOTBOX", + "UNDERLINE", + "PIESLICE", + "CHORD", + "ARC", + "FIRST", + "LAST", + "BUTT", + "PROJECTING", + "ROUND", + "BEVEL", + "MITER", + "MOVETO", + "SCROLL", + "UNITS", + "PAGES", + "TkVersion", + "TclVersion", + "READABLE", + "WRITABLE", + "EXCEPTION", + "EventType", + "Event", + "NoDefaultRoot", + "Variable", + "StringVar", + "IntVar", + "DoubleVar", + "BooleanVar", + "mainloop", + "getint", + "getdouble", + "getboolean", + "Misc", + "CallWrapper", + "XView", + "YView", + "Wm", + "Tk", + "Tcl", + "Pack", + "Place", + "Grid", + "BaseWidget", + "Widget", + "Toplevel", + "Button", + "Canvas", + "Checkbutton", + "Entry", + "Frame", + "Label", + "Listbox", + "Menu", + "Menubutton", + "Message", + "Radiobutton", + "Scale", + "Scrollbar", + "Text", + "OptionMenu", + "Image", + "PhotoImage", + "BitmapImage", + "image_names", + "image_types", + "Spinbox", + "LabelFrame", + "PanedWindow", + ] + # 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 @@ -101,9 +236,9 @@ class EventType(str, Enum): VirtualEvent: str Visibility: str -_W = TypeVar("_W", bound="Misc") +_W = TypeVar("_W", bound=Misc) # Events considered covariant because you should never assign to event.widget. -_W_co = TypeVar("_W_co", covariant=True, bound="Misc") +_W_co = TypeVar("_W_co", covariant=True, bound=Misc) class Event(Generic[_W_co]): serial: int @@ -126,7 +261,7 @@ class Event(Generic[_W_co]): widget: _W_co delta: int -def NoDefaultRoot(): ... +def NoDefaultRoot() -> None: ... _TraceMode = Literal["array", "read", "write", "unset"] @@ -139,9 +274,10 @@ class Variable: 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_vdelete(self, mode, cbname) -> None: ... # deprecated def trace_vinfo(self): ... # deprecated trace = trace_variable # deprecated + def __eq__(self, other: object) -> bool: ... class StringVar(Variable): def __init__(self, master: Misc | None = ..., value: str | None = ..., name: str | None = ...) -> None: ... @@ -187,13 +323,13 @@ class Misc: def destroy(self) -> None: ... def deletecommand(self, name: str) -> None: ... def tk_strictMotif(self, boolean: Any | None = ...): ... - def tk_bisque(self): ... - def tk_setPalette(self, *args, **kw): ... + def tk_bisque(self) -> None: ... + def tk_setPalette(self, *args, **kw) -> None: ... def wait_variable(self, name: str | Variable = ...) -> None: ... waitvar = wait_variable def wait_window(self, window: Misc | None = ...) -> None: ... def wait_visibility(self, window: Misc | None = ...) -> None: ... - def setvar(self, name: str = ..., value: str = ...): ... + def setvar(self, name: str = ..., value: str = ...) -> None: ... def getvar(self, name: str = ...): ... def getint(self, s): ... def getdouble(self, s): ... @@ -214,30 +350,32 @@ class Misc: # 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: Literal[0] | Misc | None = ...): ... + def bell(self, displayof: Literal[0] | Misc | None = ...) -> 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 clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...) -> None: ... def grab_current(self): ... - def grab_release(self): ... + def grab_release(self) -> None: ... def grab_set(self) -> None: ... def grab_set_global(self) -> None: ... - def grab_status(self): ... - def option_add(self, pattern, value, priority: Any | None = ...): ... - def option_clear(self): ... + def grab_status(self) -> Literal["local", "global"] | None: ... + def option_add( + self, pattern, value, priority: int | Literal["widgetDefault", "startupFile", "userDefault", "interactive"] | None = ... + ) -> None: ... + def option_clear(self) -> None: ... def option_get(self, name, className): ... - def option_readfile(self, fileName, priority: Any | None = ...): ... - def selection_clear(self, **kw): ... + def option_readfile(self, fileName, priority: Any | None = ...) -> None: ... + def selection_clear(self, **kw) -> None: ... def selection_get(self, **kw): ... - def selection_handle(self, command, **kw): ... - def selection_own(self, **kw): ... + def selection_handle(self, command, **kw) -> None: ... + def selection_own(self, **kw) -> None: ... def selection_own_get(self, **kw): ... def send(self, interp, cmd, *args): ... - def lower(self, belowThis: Any | None = ...): ... - def tkraise(self, aboveThis: Any | None = ...): ... + def lower(self, belowThis: Any | None = ...) -> None: ... + def tkraise(self, aboveThis: Any | None = ...) -> None: ... lift = tkraise - def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = ...): ... - def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = ...): ... + def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = ...) -> int: ... + def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = ...) -> str: ... 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: ... @@ -287,7 +425,10 @@ class Misc: def winfo_y(self) -> int: ... def update(self) -> None: ... def update_idletasks(self) -> None: ... - def bindtags(self, tagList: Any | None = ...): ... + @overload + def bindtags(self, tagList: None = ...) -> tuple[str, ...]: ... + @overload + def bindtags(self, tagList: list[str] | tuple[str, ...]) -> None: ... # bind with isinstance(func, str) doesn't return anything, but all other # binds do. The default value of func is not str. @overload @@ -330,7 +471,7 @@ class Misc: 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 quit(self) -> None: ... def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ... def register( self, func: Callable[..., Any], subst: Callable[..., Sequence[Any]] | None = ..., needcleanup: int = ... @@ -434,7 +575,7 @@ class CallWrapper: func: Any subst: Any widget: Any - def __init__(self, func, subst, widget): ... + def __init__(self, func, subst, widget) -> None: ... def __call__(self, *args): ... class XView: @@ -488,11 +629,11 @@ class Wm: # 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: Any | None = ...): ... + def wm_focusmodel(self, model: Literal["active", "passive"] | None = ...) -> Literal["active", "passive", ""]: ... focusmodel = wm_focusmodel def wm_forget(self, window: Wm) -> None: ... forget = wm_forget - def wm_frame(self): ... + def wm_frame(self) -> str: ... frame = wm_frame @overload def wm_geometry(self, newGeometry: None = ...) -> str: ... @@ -511,15 +652,15 @@ class Wm: iconify = wm_iconify def wm_iconmask(self, bitmap: Any | None = ...): ... iconmask = wm_iconmask - def wm_iconname(self, newName: Any | None = ...): ... + def wm_iconname(self, newName: Any | None = ...) -> str: ... iconname = wm_iconname def wm_iconphoto(self, default: bool, __image1: Image, *args: Image) -> None: ... iconphoto = wm_iconphoto - def wm_iconposition(self, x: Any | None = ..., y: Any | None = ...): ... + def wm_iconposition(self, x: int | None = ..., y: int | None = ...) -> tuple[int, int] | None: ... iconposition = wm_iconposition def wm_iconwindow(self, pathName: Any | None = ...): ... iconwindow = wm_iconwindow - def wm_manage(self, widget): ... + def wm_manage(self, widget) -> None: ... manage = wm_manage @overload def wm_maxsize(self, width: None = ..., height: None = ...) -> tuple[int, int]: ... @@ -536,7 +677,7 @@ class Wm: @overload def wm_overrideredirect(self, boolean: bool) -> None: ... overrideredirect = wm_overrideredirect - def wm_positionfrom(self, who: Any | None = ...): ... + def wm_positionfrom(self, who: Literal["program", "user"] | None = ...) -> Literal["", "program", "user"]: ... positionfrom = wm_positionfrom @overload def wm_protocol(self, name: str, func: Callable[[], Any] | str) -> None: ... @@ -550,7 +691,7 @@ class Wm: @overload def wm_resizable(self, width: bool, height: bool) -> None: ... resizable = wm_resizable - def wm_sizefrom(self, who: Any | None = ...): ... + def wm_sizefrom(self, who: Literal["program", "user"] | None = ...) -> Literal["", "program", "user"]: ... sizefrom = wm_sizefrom @overload def wm_state(self, newstate: None = ...) -> str: ... @@ -571,12 +712,14 @@ class Wm: withdraw = wm_withdraw class _ExceptionReportingCallback(Protocol): - def __call__(self, __exc: Type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... + def __call__(self, __exc: type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... class Tk(Misc, Wm): master: None def __init__( - # please update ttkthemes stub if you change this + # Make sure to keep in sync with other functions that use the same + # args. + # use `git grep screenName` to find them self, screenName: str | None = ..., baseName: str | None = ..., @@ -610,46 +753,42 @@ class Tk(Misc, Wm): @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: _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] - def eval(self, __code: 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 + # Please keep in sync with _tkinter.TkappType. + # Some methods are intentionally missing because they are inherited from Misc instead. + def adderrorinfo(self, __msg): ... + def call(self, __command: Any, *args: Any) -> Any: ... + def createcommand(self, __name, __func): ... + if sys.platform != "win32": + def createfilehandler(self, __file, __mask, __func): ... + def deletefilehandler(self, __file): ... + + def createtimerhandler(self, __milliseconds, __func): ... + def dooneevent(self, __flags: int = ...): ... + def eval(self, __script: str) -> str: ... + def evalfile(self, __fileName): ... + def exprboolean(self, __s): ... + def exprdouble(self, __s): ... + def exprlong(self, __s): ... + def exprstring(self, __s): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self): ... + def loadtk(self) -> None: ... + def record(self, __script): ... if sys.version_info < (3, 11): - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + def split(self, __arg): ... + + def splitlist(self, __arg): ... + def unsetvar(self, *args, **kwargs): ... + def wantobjects(self, *args, **kwargs): ... + def willdispatch(self): ... -def Tcl(screenName: Any | None = ..., baseName: Any | None = ..., className: str = ..., useTk: bool = ...): ... +def Tcl(screenName: str | None = ..., baseName: str | None = ..., className: str = ..., useTk: bool = ...) -> Tk: ... _InMiscTotal = TypedDict("_InMiscTotal", {"in": Misc}) _InMiscNonTotal = TypedDict("_InMiscNonTotal", {"in": Misc}, total=False) @@ -769,7 +908,7 @@ class Grid: class BaseWidget(Misc): master: Misc widgetName: Any - def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ... + def __init__(self, master, widgetName, cnf=..., kw=..., extra=...) -> None: ... def destroy(self) -> None: ... # This class represents any widget except Toplevel or Tk. @@ -942,7 +1081,7 @@ class Button(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def flash(self): ... + def flash(self) -> None: ... def invoke(self) -> Any: ... class Canvas(Widget, XView, YView): @@ -1059,7 +1198,7 @@ class Canvas(Widget, XView, YView): @overload def tag_bind( self, - tagOrId: str | int, + tagOrId: str | _CanvasItemId, sequence: str | None = ..., func: Callable[[Event[Canvas]], Any] | None = ..., add: Literal["", "+"] | bool | None = ..., @@ -1069,16 +1208,16 @@ class Canvas(Widget, XView, YView): self, tagOrId: str | int, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ... ) -> None: ... @overload - def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... - def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = ...) -> None: ... + def tag_bind(self, tagOrId: str | _CanvasItemId, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... + def tag_unbind(self, tagOrId: str | _CanvasItemId, sequence: str, funcid: str | None = ...) -> None: ... def canvasx(self, screenx, gridspacing: Any | None = ...): ... def canvasy(self, screeny, gridspacing: Any | None = ...): ... @overload - def coords(self) -> list[float]: ... + def coords(self, __tagOrId: str | _CanvasItemId) -> list[float]: ... @overload - def coords(self, __args: list[int] | list[float] | tuple[float, ...]) -> None: ... + def coords(self, __tagOrId: str | _CanvasItemId, __args: list[int] | list[float] | tuple[float, ...]) -> None: ... @overload - def coords(self, __x1: float, __y1: float, *args: float) -> None: ... + def coords(self, __tagOrId: str | _CanvasItemId, __x1: float, __y1: float, *args: float) -> None: ... # create_foo() methods accept coords as a list, a tuple, or as separate arguments. # Keyword arguments should be the same in each pair of overloads. def create_arc(self, *args, **kw) -> _CanvasItemId: ... @@ -1398,7 +1537,7 @@ class Canvas(Widget, XView, YView): width: _ScreenUnits = ..., window: Widget = ..., ) -> _CanvasItemId: ... - def dchars(self, *args): ... + def dchars(self, *args) -> None: ... def delete(self, *tagsOrCanvasIds: str | _CanvasItemId) -> None: ... @overload def dtag(self, __tag: str, __tag_to_delete: str | None = ...) -> None: ... @@ -1406,18 +1545,19 @@ class Canvas(Widget, XView, YView): def dtag(self, __id: _CanvasItemId, __tag_to_delete: str) -> None: ... def focus(self, *args): ... def gettags(self, __tagOrId: str | _CanvasItemId) -> tuple[str, ...]: ... - def icursor(self, *args): ... + def icursor(self, *args) -> None: ... def index(self, *args): ... - def insert(self, *args): ... + def insert(self, *args) -> None: ... def itemcget(self, tagOrId, option): ... # itemconfigure kwargs depend on item type, which is not known when type checking def itemconfigure( self, tagOrId: str | _CanvasItemId, cnf: dict[str, Any] | None = ..., **kw: Any ) -> dict[str, tuple[str, str, str, str, str]] | None: ... itemconfig = itemconfigure - def move(self, *args): ... + def move(self, *args) -> None: ... if sys.version_info >= (3, 8): def moveto(self, tagOrId: str | _CanvasItemId, x: Literal[""] | float = ..., y: Literal[""] | float = ...) -> None: ... + def postscript(self, cnf=..., **kw): ... # tkinter does: # lower = tag_lower @@ -1429,14 +1569,14 @@ class Canvas(Widget, XView, YView): def tag_raise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... def tkraise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] def lift(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] - 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 scale(self, *args) -> None: ... + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y, gain: int = ...) -> None: ... + def select_adjust(self, tagOrId, index) -> None: ... + def select_clear(self) -> None: ... + def select_from(self, tagOrId, index) -> None: ... def select_item(self): ... - def select_to(self, tagOrId, index): ... + def select_to(self, tagOrId, index) -> None: ... def type(self, tagOrId): ... class Checkbutton(Widget): @@ -1550,11 +1690,11 @@ class Checkbutton(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def deselect(self): ... - def flash(self): ... + def deselect(self) -> None: ... + def flash(self) -> None: ... def invoke(self) -> Any: ... - def select(self): ... - def toggle(self): ... + def select(self) -> None: ... + def toggle(self) -> None: ... _EntryIndex = Union[str, int] # "INDICES" in manual page @@ -1654,8 +1794,8 @@ class Entry(Widget, XView): def icursor(self, index: _EntryIndex) -> None: ... def index(self, index: _EntryIndex) -> int: ... def insert(self, index: _EntryIndex, string: str) -> None: ... - def scan_mark(self, x): ... - def scan_dragto(self, x): ... + def scan_mark(self, x) -> None: ... + def scan_dragto(self, x) -> None: ... def selection_adjust(self, index: _EntryIndex) -> None: ... def selection_clear(self) -> None: ... # type: ignore[override] def selection_from(self, index: _EntryIndex) -> None: ... @@ -1890,26 +2030,26 @@ class Listbox(Widget, XView, YView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def activate(self, index): ... - def bbox(self, index): ... + def activate(self, index) -> None: ... + def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def curselection(self): ... - def delete(self, first, last: Any | None = ...): ... + def delete(self, first, last: Any | None = ...) -> None: ... def get(self, first, last: Any | None = ...): ... def index(self, index): ... - def insert(self, index, *elements): ... + def insert(self, index, *elements) -> None: ... 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): ... + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y) -> None: ... + def see(self, index) -> None: ... + def selection_anchor(self, index) -> None: ... select_anchor: Any - def selection_clear(self, first, last: Any | None = ...): ... # type: ignore[override] + def selection_clear(self, first, last: Any | None = ...) -> None: ... # type: ignore[override] select_clear: Any def selection_includes(self, index): ... select_includes: Any - def selection_set(self, first, last: Any | None = ...): ... + def selection_set(self, first, last: Any | None = ...) -> None: ... select_set: Any - def size(self): ... + def size(self) -> int: ... # type: ignore[override] def itemcget(self, index, option): ... def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... itemconfig: Any @@ -2434,10 +2574,10 @@ class Radiobutton(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def deselect(self): ... - def flash(self): ... + def deselect(self) -> None: ... + def flash(self) -> None: ... def invoke(self) -> Any: ... - def select(self): ... + def select(self) -> None: ... class Scale(Widget): def __init__( @@ -2525,10 +2665,10 @@ class Scale(Widget): @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: Any | None = ...): ... - def identify(self, x, y): ... + def get(self) -> float: ... + def set(self, value) -> None: ... + def coords(self, value: float | None = ...) -> tuple[int, int]: ... + def identify(self, x, y) -> Literal["", "slider", "trough1", "trough2"]: ... class Scrollbar(Widget): def __init__( @@ -2594,11 +2734,11 @@ class Scrollbar(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def activate(self, index: Any | None = ...): ... - def delta(self, deltax, deltay): ... - def fraction(self, x, y): ... - def identify(self, x, y): ... - def get(self): ... - def set(self, first, last): ... + def delta(self, deltax: int, deltay: int) -> float: ... + def fraction(self, x: int, y: int) -> float: ... + def identify(self, x: int, y: int) -> Literal["arrow1", "arrow2", "slider", "trough1", "trough2", ""]: ... + def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... + def set(self, first: float, last: float) -> None: ... _TextIndex = Union[_tkinter.Tcl_Obj, str, float, Misc] @@ -2876,13 +3016,13 @@ class Text(Widget, XView, YView): def window_cget(self, index, option): ... def window_configure(self, index, cnf: Any | None = ..., **kw): ... window_config = window_configure - def window_create(self, index, cnf=..., **kw): ... + def window_create(self, index, cnf=..., **kw) -> None: ... def window_names(self): ... def yview_pickplace(self, *what): ... # deprecated class _setit: - def __init__(self, var, value, callback: Any | None = ...): ... - def __call__(self, *args): ... + def __init__(self, var, value, callback: Any | None = ...) -> None: ... + def __call__(self, *args) -> None: ... # manual page: tk_optionMenu class OptionMenu(Menubutton): @@ -2909,9 +3049,11 @@ class _Image(Protocol): class Image: name: Any tk: _tkinter.TkappType - def __init__(self, imgtype, name: Any | None = ..., cnf=..., master: Misc | _tkinter.TkappType | None = ..., **kw): ... - def __del__(self): ... - def __setitem__(self, key, value): ... + def __init__( + self, imgtype, name: Any | None = ..., cnf=..., master: Misc | _tkinter.TkappType | None = ..., **kw + ) -> None: ... + def __del__(self) -> None: ... + def __setitem__(self, key, value) -> None: ... def __getitem__(self, key): ... configure: Any config: Any @@ -3107,13 +3249,13 @@ class Spinbox(Widget, XView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def bbox(self, index): ... - def delete(self, first, last: Any | None = ...): ... - def get(self): ... + def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def delete(self, first, last: Any | None = ...) -> Literal[""]: ... + def get(self) -> str: ... def icursor(self, index): ... - def identify(self, x, y): ... - def index(self, index): ... - def insert(self, index, s): ... + def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: ... + def index(self, index: _EntryIndex) -> int: ... + def insert(self, index: _EntryIndex, s: str) -> Literal[""]: ... # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: ... def scan(self, *args): ... @@ -3253,10 +3395,10 @@ class PanedWindow(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def add(self, child: Widget, **kw): ... - def remove(self, child): ... + def add(self, child: Widget, **kw) -> None: ... + def remove(self, child) -> None: ... forget: Any - def identify(self, x, y): ... + def identify(self, x: int, y: int): ... def proxy(self, *args): ... def proxy_coord(self): ... def proxy_forget(self): ... diff --git a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi index b5fdc7c54914..e0473afa5a7a 100644 --- a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi +++ b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi @@ -1,6 +1,10 @@ +import sys from tkinter.commondialog import Dialog from typing import Any, ClassVar +if sys.version_info >= (3, 9): + __all__ = ["Chooser", "askcolor"] + class Chooser(Dialog): command: ClassVar[str] diff --git a/mypy/typeshed/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi index aee58111c73f..1c5fb0f53706 100644 --- a/mypy/typeshed/stdlib/tkinter/commondialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/commondialog.pyi @@ -1,5 +1,9 @@ +import sys from typing import Any, ClassVar, Mapping +if sys.version_info >= (3, 9): + __all__ = ["Dialog"] + class Dialog: command: ClassVar[str | None] master: Any | None diff --git a/mypy/typeshed/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi index bc927e1f24ac..f9c8487c44a9 100644 --- a/mypy/typeshed/stdlib/tkinter/dialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/dialog.pyi @@ -1,6 +1,10 @@ +import sys from tkinter import Widget from typing import Any, Mapping +if sys.version_info >= (3, 9): + __all__ = ["Dialog"] + DIALOG_ICON: str class Dialog(Widget): diff --git a/mypy/typeshed/stdlib/tkinter/dnd.pyi b/mypy/typeshed/stdlib/tkinter/dnd.pyi index 339291a20d0f..e2cfc43f606a 100644 --- a/mypy/typeshed/stdlib/tkinter/dnd.pyi +++ b/mypy/typeshed/stdlib/tkinter/dnd.pyi @@ -1,6 +1,10 @@ +import sys from tkinter import Event, Misc, Tk, Widget from typing import ClassVar, Protocol +if sys.version_info >= (3, 9): + __all__ = ["dnd_start", "DndHandler"] + class _DndSource(Protocol): def dnd_end(self, target: Widget | None, event: Event[Misc] | None) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index b818d5e8253e..dc0e01a6d1d1 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,8 +1,26 @@ +import sys from _typeshed import StrOrBytesPath from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog from typing import IO, Any, ClassVar, Iterable from typing_extensions import Literal +if sys.version_info >= (3, 9): + __all__ = [ + "FileDialog", + "LoadFileDialog", + "SaveFileDialog", + "Open", + "SaveAs", + "Directory", + "askopenfilename", + "asksaveasfilename", + "askopenfilenames", + "askopenfile", + "askopenfiles", + "asksaveasfile", + "askdirectory", + ] + dialogstates: dict[Any, tuple[Any, Any]] class FileDialog: @@ -46,7 +64,7 @@ class LoadFileDialog(FileDialog): class SaveFileDialog(FileDialog): title: str - def ok_command(self): ... + def ok_command(self) -> None: ... class _Dialog(commondialog.Dialog): ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 211e8ec9a0be..e16f325b589a 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -4,6 +4,9 @@ import tkinter from typing import Any, Union, overload from typing_extensions import Literal, TypedDict +if sys.version_info >= (3, 9): + __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] + NORMAL: Literal["normal"] ROMAN: Literal["roman"] BOLD: Literal["bold"] @@ -101,6 +104,7 @@ class Font: @overload def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... def measure(self, text: str, displayof: tkinter.Misc | None = ...) -> int: ... + def __eq__(self, other: object) -> bool: ... def families(root: tkinter.Misc | None = ..., displayof: tkinter.Misc | None = ...) -> tuple[str, ...]: ... def names(root: tkinter.Misc | None = ...) -> tuple[str, ...]: ... diff --git a/mypy/typeshed/stdlib/tkinter/messagebox.pyi b/mypy/typeshed/stdlib/tkinter/messagebox.pyi index fc4afcef0cc2..96109b116786 100644 --- a/mypy/typeshed/stdlib/tkinter/messagebox.pyi +++ b/mypy/typeshed/stdlib/tkinter/messagebox.pyi @@ -1,6 +1,19 @@ +import sys from tkinter.commondialog import Dialog from typing import Any, ClassVar +if sys.version_info >= (3, 9): + __all__ = [ + "showinfo", + "showwarning", + "showerror", + "askquestion", + "askokcancel", + "askyesno", + "askyesnocancel", + "askretrycancel", + ] + ERROR: str INFO: str QUESTION: str diff --git a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi index 246979d5afd7..00309431d457 100644 --- a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi +++ b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi @@ -1,6 +1,8 @@ from tkinter import Frame, Misc, Scrollbar, Text from typing import Any +__all__ = ["ScrolledText"] + # The methods from Pack, Place, and Grid are dynamically added over the parent's impls class ScrolledText(Text): frame: Frame diff --git a/mypy/typeshed/stdlib/tkinter/simpledialog.pyi b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi index ec801afaceee..fbe78530721f 100644 --- a/mypy/typeshed/stdlib/tkinter/simpledialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi @@ -4,7 +4,7 @@ from typing import Any class Dialog(Toplevel): def __init__(self, parent: Misc | None, title: str | None = ...) -> None: ... def body(self, master) -> None: ... - def buttonbox(self): ... + def buttonbox(self) -> None: ... class SimpleDialog: def __init__( @@ -22,6 +22,6 @@ class SimpleDialog: def wm_delete_window(self) -> None: ... def done(self, num: int) -> None: ... -def askfloat(title: str | None, prompt: str, **kwargs: Any) -> float: ... -def askinteger(title: str | None, prompt: str, **kwargs: Any) -> int: ... -def askstring(title: str | None, prompt: str, **kwargs: Any) -> str: ... +def askfloat(title: str | None, prompt: str, **kwargs: Any) -> float | None: ... +def askinteger(title: str | None, prompt: str, **kwargs: Any) -> int | None: ... +def askstring(title: str | None, prompt: str, **kwargs: Any) -> str | None: ... diff --git a/mypy/typeshed/stdlib/tkinter/tix.pyi b/mypy/typeshed/stdlib/tkinter/tix.pyi index 6842ab7b1108..6f9201a1bdf9 100644 --- a/mypy/typeshed/stdlib/tkinter/tix.pyi +++ b/mypy/typeshed/stdlib/tkinter/tix.pyi @@ -45,7 +45,7 @@ class tixCommand: def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = ...) -> None: ... class Tk(tkinter.Tk, tixCommand): - def __init__(self, screenName: str | None = ..., baseName: str | None = ..., className: str = ...): ... + def __init__(self, screenName: str | None = ..., baseName: str | None = ..., className: str = ...) -> None: ... class TixWidget(tkinter.Widget): def __init__( diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index f7319291da6d..41a5b64c5c35 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -5,7 +5,63 @@ from tkinter.font import _FontDescription from typing import Any, Callable, Union, overload from typing_extensions import Literal, TypedDict -def tclobjs_to_py(adict): ... +if sys.version_info >= (3, 7): + __all__ = [ + "Button", + "Checkbutton", + "Combobox", + "Entry", + "Frame", + "Label", + "Labelframe", + "LabelFrame", + "Menubutton", + "Notebook", + "Panedwindow", + "PanedWindow", + "Progressbar", + "Radiobutton", + "Scale", + "Scrollbar", + "Separator", + "Sizegrip", + "Spinbox", + "Style", + "Treeview", + "LabeledScale", + "OptionMenu", + "tclobjs_to_py", + "setup_master", + ] +else: + __all__ = [ + "Button", + "Checkbutton", + "Combobox", + "Entry", + "Frame", + "Label", + "Labelframe", + "LabelFrame", + "Menubutton", + "Notebook", + "Panedwindow", + "PanedWindow", + "Progressbar", + "Radiobutton", + "Scale", + "Scrollbar", + "Separator", + "Sizegrip", + "Style", + "Treeview", + "LabeledScale", + "OptionMenu", + "tclobjs_to_py", + "setup_master", + ] + +def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... def setup_master(master: Any | None = ...): ... # from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound @@ -14,16 +70,16 @@ _TtkCompound = Literal["text", "image", tkinter._Compound] class Style: master: Any tk: _tkinter.TkappType - def __init__(self, master: tkinter.Misc | None = ...): ... + def __init__(self, master: tkinter.Misc | None = ...) -> None: ... def configure(self, style, query_opt: Any | None = ..., **kw): ... def map(self, style, query_opt: Any | None = ..., **kw): ... def lookup(self, style, option, state: Any | None = ..., default: Any | None = ...): ... def layout(self, style, layoutspec: Any | None = ...): ... - def element_create(self, elementname, etype, *args, **kw): ... + def element_create(self, elementname, etype, *args, **kw) -> None: ... def element_names(self): ... def element_options(self, elementname): ... - def theme_create(self, themename, parent: Any | None = ..., settings: Any | None = ...): ... - def theme_settings(self, themename, settings): ... + def theme_create(self, themename, parent: Any | None = ..., settings: Any | None = ...) -> None: ... + def theme_settings(self, themename, settings) -> None: ... def theme_names(self) -> tuple[str, ...]: ... @overload def theme_use(self, themename: str) -> None: ... @@ -31,8 +87,8 @@ class Style: def theme_use(self, themename: None = ...) -> str: ... class Widget(tkinter.Widget): - def __init__(self, master: tkinter.Misc | None, widgetname, kw: Any | None = ...): ... - def identify(self, x, y): ... + def __init__(self, master: tkinter.Misc | None, widgetname, kw: Any | None = ...) -> None: ... + def identify(self, x: int, y: int) -> str: ... def instate(self, statespec, callback: Any | None = ..., *args, **kw): ... def state(self, statespec: Any | None = ...): ... @@ -207,8 +263,8 @@ class Entry(Widget, tkinter.Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def bbox(self, index): ... - def identify(self, x, y): ... + def bbox(self, index) -> tuple[int, int, int, int]: ... # type: ignore[override] + def identify(self, x: int, y: int) -> str: ... def validate(self): ... class Combobox(Entry): @@ -293,8 +349,8 @@ class Combobox(Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def current(self, newindex: Any | None = ...): ... - def set(self, value): ... + def current(self, newindex: int | None = ...) -> int: ... + def set(self, value: Any) -> None: ... class Frame(Widget): def __init__( @@ -521,11 +577,11 @@ class Notebook(Widget): compound: tkinter._Compound = ..., underline: int = ..., ) -> None: ... - def forget(self, tab_id): ... - def hide(self, tab_id): ... - def identify(self, x, y): ... + def forget(self, tab_id) -> None: ... + def hide(self, tab_id) -> None: ... + def identify(self, x: int, y: int) -> str: ... def index(self, tab_id): ... - def insert(self, pos, child, **kw): ... + def insert(self, pos, child, **kw) -> None: ... def select(self, tab_id: Any | None = ...): ... def tab(self, tab_id, option: Any | None = ..., **kw): ... def tabs(self): ... @@ -575,7 +631,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... forget: Any - def insert(self, pos, child, **kw): ... + def insert(self, pos, child, **kw) -> None: ... def pane(self, pane, option: Any | None = ..., **kw): ... def sashpos(self, index, newpos: Any | None = ...): ... @@ -618,9 +674,9 @@ class Progressbar(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def start(self, interval: Any | None = ...): ... - def step(self, amount: Any | None = ...): ... - def stop(self): ... + def start(self, interval: Literal["idle"] | int | None = ...) -> None: ... + def step(self, amount: float | None = ...) -> None: ... + def stop(self) -> None: ... class Radiobutton(Widget): def __init__( @@ -669,7 +725,8 @@ class Radiobutton(Widget): config = configure def invoke(self) -> Any: ... -class Scale(Widget, tkinter.Scale): +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scale(Widget, tkinter.Scale): # type: ignore[misc] def __init__( self, master: tkinter.Misc | None = ..., @@ -727,9 +784,10 @@ class Scale(Widget, tkinter.Scale): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - def get(self, x: Any | None = ..., y: Any | None = ...): ... + def get(self, x: int | None = ..., y: int | None = ...) -> float: ... -class Scrollbar(Widget, tkinter.Scrollbar): +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] def __init__( self, master: tkinter.Misc | None = ..., @@ -902,7 +960,7 @@ class _TreeviewTagDict(TypedDict): class _TreeviewHeaderDict(TypedDict): text: str - image: list[str] + image: list[str] | Literal[""] anchor: tkinter._Anchor command: str state: str # Doesn't seem to appear anywhere else than in these dicts @@ -994,7 +1052,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def heading(self, column: _TreeviewColumnId, option: Literal["text"]) -> str: ... @overload - def heading(self, column: _TreeviewColumnId, option: Literal["image"]) -> tuple[str]: ... + def heading(self, column: _TreeviewColumnId, option: Literal["image"]) -> tuple[str] | str: ... @overload def heading(self, column: _TreeviewColumnId, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... @overload @@ -1002,6 +1060,8 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def heading(self, column: _TreeviewColumnId, option: str) -> Any: ... @overload + def heading(self, column: _TreeviewColumnId, option: None = ...) -> _TreeviewHeaderDict: ... # type: ignore[misc] + @overload def heading( self, column: _TreeviewColumnId, @@ -1011,8 +1071,8 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): image: tkinter._ImageSpec = ..., anchor: tkinter._Anchor = ..., command: str | Callable[[], Any] = ..., - ) -> _TreeviewHeaderDict | None: ... - def identify(self, component, x, y): ... + ) -> None: ... + def identify(self, component, x, y): ... # Internal Method. Leave untyped def identify_row(self, y: int) -> str: ... def identify_column(self, x: int) -> str: ... def identify_region(self, x: int, y: int) -> Literal["heading", "separator", "tree", "cell", "nothing"]: ... @@ -1044,6 +1104,8 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def item(self, item: str, option: str) -> Any: ... @overload + def item(self, item: str, option: None = ...) -> _TreeviewItemDict: ... # type: ignore[misc] + @overload def item( self, item: str, @@ -1054,7 +1116,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): values: list[Any] | tuple[Any, ...] | Literal[""] = ..., open: bool = ..., tags: str | list[str] | tuple[str, ...] = ..., - ) -> _TreeviewItemDict | None: ... + ) -> None: ... def move(self, item: str, parent: str, index: int) -> None: ... reattach = move def next(self, item: str) -> str: ... # returning empty string means last item @@ -1065,6 +1127,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def selection(self) -> tuple[str, ...]: ... else: def selection(self, selop: Any | None = ..., items: Any | None = ...) -> tuple[str, ...]: ... + def selection_set(self, items: str | list[str] | tuple[str, ...]) -> None: ... def selection_add(self, items: str | list[str] | tuple[str, ...]) -> None: ... def selection_remove(self, items: str | list[str] | tuple[str, ...]) -> None: ... @@ -1119,7 +1182,7 @@ class LabeledScale(Frame): from_: float = ..., to: float = ..., *, - compound: Literal["top"] | Literal["bottom"] = ..., + compound: Literal["top", "bottom"] = ..., **kw: Any, ) -> None: ... # destroy is overridden, signature does not change @@ -1134,9 +1197,9 @@ class OptionMenu(Menubutton): *values: str, # rest of these are keyword-only because *args syntax used above style: str = ..., - direction: Literal["above"] | Literal["below"] | Literal["left"] | Literal["right"] | Literal["flush"] = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., command: Callable[[tkinter.StringVar], Any] | None = ..., ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change - def set_menu(self, default: Any | None = ..., *values): ... + def set_menu(self, default: Any | None = ..., *values) -> None: ... diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index 9451015e9df5..49329ec442f0 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -1,5 +1,284 @@ import sys +if sys.version_info >= (3, 10): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "COLONEQUAL", + "OP", + "AWAIT", + "ASYNC", + "TYPE_IGNORE", + "TYPE_COMMENT", + "SOFT_KEYWORD", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "COLONEQUAL", + "OP", + "AWAIT", + "ASYNC", + "TYPE_IGNORE", + "TYPE_COMMENT", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "OP", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + ] +else: + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "OP", + "AWAIT", + "ASYNC", + "ERRORTOKEN", + "N_TOKENS", + "NT_OFFSET", + ] + ENDMARKER: int NAME: int NUMBER: int diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 7614ebfe403e..e8f64a7d0702 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -1,9 +1,314 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open -from token import * # noqa: F403 +from token import * from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Union +if sys.version_info >= (3, 10): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "COLONEQUAL", + "OP", + "AWAIT", + "ASYNC", + "TYPE_IGNORE", + "TYPE_COMMENT", + "SOFT_KEYWORD", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + "tokenize", + "generate_tokens", + "detect_encoding", + "untokenize", + "TokenInfo", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "COLONEQUAL", + "OP", + "AWAIT", + "ASYNC", + "TYPE_IGNORE", + "TYPE_COMMENT", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + "tokenize", + "generate_tokens", + "detect_encoding", + "untokenize", + "TokenInfo", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "OP", + "ERRORTOKEN", + "COMMENT", + "NL", + "ENCODING", + "N_TOKENS", + "NT_OFFSET", + "tokenize", + "detect_encoding", + "untokenize", + "TokenInfo", + ] +else: + __all__ = [ + "tok_name", + "ISTERMINAL", + "ISNONTERMINAL", + "ISEOF", + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "ATEQUAL", + "RARROW", + "ELLIPSIS", + "OP", + "AWAIT", + "ASYNC", + "ERRORTOKEN", + "N_TOKENS", + "NT_OFFSET", + "COMMENT", + "tokenize", + "detect_encoding", + "NL", + "untokenize", + "ENCODING", + "TokenInfo", + ] + +if sys.version_info >= (3, 8): + from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES +else: + EXACT_TOKEN_TYPES: dict[str, int] + if sys.version_info < (3, 7): COMMENT: int NL: int diff --git a/mypy/typeshed/stdlib/tomllib.pyi b/mypy/typeshed/stdlib/tomllib.pyi new file mode 100644 index 000000000000..3a6ce93f87e1 --- /dev/null +++ b/mypy/typeshed/stdlib/tomllib.pyi @@ -0,0 +1,10 @@ +from _typeshed import SupportsRead +from collections.abc import Callable +from typing import Any + +__all__ = ("loads", "load", "TOMLDecodeError") + +class TOMLDecodeError(ValueError): ... + +def load(__fp: SupportsRead[bytes], *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... +def loads(__s: str, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index ee8dffa67820..640b014594a2 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -4,6 +4,8 @@ from _typeshed import StrPath from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar from typing_extensions import ParamSpec +__all__ = ["Trace", "CoverageResults"] + _T = TypeVar("_T") _P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] @@ -46,6 +48,7 @@ class Trace: def runfunc(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... else: def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... + def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 4e36490c24e4..4df5c10077bf 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,7 +1,30 @@ import sys -from _typeshed import SupportsWrite +from _typeshed import Self, SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, Mapping, Optional, Type, overload +from typing import IO, Any, Generator, Iterable, Iterator, Mapping, Optional, overload +from typing_extensions import Literal + +__all__ = [ + "extract_stack", + "extract_tb", + "format_exception", + "format_exception_only", + "format_list", + "format_stack", + "format_tb", + "print_exc", + "format_exc", + "print_exception", + "print_last", + "print_stack", + "print_tb", + "clear_frames", + "FrameSummary", + "StackSummary", + "TracebackException", + "walk_stack", + "walk_tb", +] _PT = tuple[str, int, str, Optional[str]] @@ -10,7 +33,7 @@ def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | if sys.version_info >= (3, 10): @overload def print_exception( - __exc: Type[BaseException] | None, + __exc: type[BaseException] | None, value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = ..., @@ -23,7 +46,7 @@ if sys.version_info >= (3, 10): ) -> None: ... @overload def format_exception( - __exc: Type[BaseException] | None, + __exc: type[BaseException] | None, value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = ..., @@ -34,7 +57,7 @@ if sys.version_info >= (3, 10): else: def print_exception( - etype: Type[BaseException] | None, + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., @@ -42,7 +65,7 @@ else: chain: bool = ..., ) -> None: ... def format_exception( - etype: Type[BaseException] | None, + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., @@ -60,10 +83,10 @@ def format_list(extracted_list: list[FrameSummary]) -> list[str]: ... def print_list(extracted_list: list[FrameSummary], file: SupportsWrite[str] | None = ...) -> None: ... if sys.version_info >= (3, 10): - def format_exception_only(__exc: Type[BaseException] | None, value: BaseException | None = ...) -> list[str]: ... + def format_exception_only(__exc: type[BaseException] | None, value: BaseException | None = ...) -> list[str]: ... else: - def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> list[str]: ... + def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... def format_exc(limit: int | None = ..., chain: bool = ...) -> str: ... def format_tb(tb: TracebackType | None, limit: int | None = ...) -> list[str]: ... @@ -77,7 +100,7 @@ class TracebackException: __context__: TracebackException __suppress_context__: bool stack: StackSummary - exc_type: Type[BaseException] + exc_type: type[BaseException] filename: str lineno: int text: str @@ -86,7 +109,7 @@ class TracebackException: if sys.version_info >= (3, 10): def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, exc_traceback: TracebackType | None, *, @@ -98,18 +121,18 @@ class TracebackException: ) -> None: ... @classmethod def from_exception( - cls, + cls: type[Self], exc: BaseException, *, limit: int | None = ..., lookup_lines: bool = ..., capture_locals: bool = ..., compact: bool = ..., - ) -> TracebackException: ... + ) -> Self: ... else: def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, exc_traceback: TracebackType | None, *, @@ -120,31 +143,62 @@ class TracebackException: ) -> None: ... @classmethod def from_exception( - cls, exc: BaseException, *, limit: int | None = ..., lookup_lines: bool = ..., capture_locals: bool = ... - ) -> TracebackException: ... + cls: type[Self], exc: BaseException, *, limit: int | None = ..., lookup_lines: bool = ..., capture_locals: bool = ... + ) -> Self: ... + + def __eq__(self, other: object) -> bool: ... def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... def format_exception_only(self) -> Generator[str, None, None]: ... class FrameSummary(Iterable[Any]): + if sys.version_info >= (3, 11): + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = ..., + locals: Mapping[str, str] | None = ..., + line: str | None = ..., + end_lineno: int | None = ..., + colno: int | None = ..., + end_colno: int | None = ..., + ) -> None: ... + end_lineno: int | None + colno: int | None + end_colno: int | None + else: + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = ..., + locals: Mapping[str, str] | None = ..., + line: str | None = ..., + ) -> None: ... filename: str - lineno: int + lineno: int | None name: str - line: str locals: dict[str, str] | None - def __init__( - self, - filename: str, - lineno: int, - name: str, - *, - lookup_line: bool = ..., - locals: Mapping[str, str] | None = ..., - line: str | None = ..., - ) -> 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: ... + @property + def line(self) -> str | None: ... + @overload + def __getitem__(self, pos: Literal[0]) -> str: ... + @overload + def __getitem__(self, pos: Literal[1]) -> int: ... + @overload + def __getitem__(self, pos: Literal[2]) -> str: ... + @overload + def __getitem__(self, pos: Literal[3]) -> str | None: ... + @overload + def __getitem__(self, pos: int) -> Any: ... def __iter__(self) -> Iterator[Any]: ... + def __eq__(self, other: object) -> bool: ... + if sys.version_info >= (3, 8): + def __len__(self) -> Literal[4]: ... class StackSummary(list[FrameSummary]): @classmethod diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index 4d7bbb7994a6..cebf0f7a8b08 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,21 +1,25 @@ import sys from _tracemalloc import * -from typing import Optional, Sequence, Union, overload +from typing import Any, Optional, Sequence, Union, overload from typing_extensions import SupportsIndex def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... -class DomainFilter: +class BaseFilter: inclusive: bool - domain: int + def __init__(self, inclusive: bool) -> None: ... + +class DomainFilter(BaseFilter): + @property + def domain(self) -> int: ... def __init__(self, inclusive: bool, domain: int) -> None: ... -class Filter: +class Filter(BaseFilter): domain: int | None - inclusive: bool lineno: int | None - filename_pattern: str + @property + def filename_pattern(self) -> str: ... all_frames: bool def __init__( self, inclusive: bool, filename_pattern: str, lineno: int | None = ..., all_frames: bool = ..., domain: int | None = ... @@ -26,6 +30,7 @@ class Statistic: size: int traceback: Traceback def __init__(self, traceback: Traceback, size: int, count: int) -> None: ... + def __eq__(self, other: object) -> bool: ... class StatisticDiff: count: int @@ -34,13 +39,26 @@ class StatisticDiff: size_diff: int traceback: Traceback def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... + def __eq__(self, other: object) -> bool: ... _FrameTupleT = tuple[str, int] class Frame: - filename: str - lineno: int + @property + def filename(self) -> str: ... + @property + def lineno(self) -> int: ... def __init__(self, frame: _FrameTupleT) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Frame) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Frame) -> bool: ... + def __ge__(self, other: Frame) -> bool: ... + def __le__(self, other: Frame) -> bool: ... + else: + def __gt__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... if sys.version_info >= (3, 9): _TraceTupleT = Union[tuple[int, int, Sequence[_FrameTupleT], Optional[int]], tuple[int, int, Sequence[_FrameTupleT]]] @@ -48,14 +66,19 @@ else: _TraceTupleT = tuple[int, int, Sequence[_FrameTupleT]] class Trace: - domain: int - size: int - traceback: Traceback + @property + def domain(self) -> int: ... + @property + def size(self) -> int: ... + @property + def traceback(self) -> Traceback: ... def __init__(self, trace: _TraceTupleT) -> None: ... + def __eq__(self, other: object) -> bool: ... class Traceback(Sequence[Frame]): if sys.version_info >= (3, 9): - total_nframe: int | None + @property + def total_nframe(self) -> int | None: ... def __init__(self, frames: Sequence[_FrameTupleT], total_nframe: int | None = ...) -> None: ... else: def __init__(self, frames: Sequence[_FrameTupleT]) -> None: ... @@ -63,11 +86,23 @@ class Traceback(Sequence[Frame]): def format(self, limit: int | None = ..., most_recent_first: bool = ...) -> list[str]: ... else: def format(self, limit: int | None = ...) -> list[str]: ... + @overload - def __getitem__(self, i: SupportsIndex) -> Frame: ... + def __getitem__(self, index: SupportsIndex) -> Frame: ... @overload - def __getitem__(self, s: slice) -> Sequence[Frame]: ... + def __getitem__(self, index: slice) -> Sequence[Frame]: ... + def __contains__(self, frame: Frame) -> bool: ... # type: ignore[override] def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Traceback) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Traceback) -> bool: ... + def __ge__(self, other: Traceback) -> bool: ... + def __le__(self, other: Traceback) -> bool: ... + else: + def __gt__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... class Snapshot: def __init__(self, traces: Sequence[_TraceTupleT], traceback_limit: int) -> None: ... diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index e5efcb4f6ed9..164ea461399b 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -1,5 +1,131 @@ -from tkinter import Canvas, Frame, PhotoImage -from typing import Any, Callable, ClassVar, Sequence, TypeVar, Union, overload +from _typeshed import Self +from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar +from typing import Any, Callable, ClassVar, Sequence, Union, overload + +__all__ = [ + "ScrolledCanvas", + "TurtleScreen", + "Screen", + "RawTurtle", + "Turtle", + "RawPen", + "Pen", + "Shape", + "Vec2D", + "addshape", + "bgcolor", + "bgpic", + "bye", + "clearscreen", + "colormode", + "delay", + "exitonclick", + "getcanvas", + "getshapes", + "listen", + "mainloop", + "mode", + "numinput", + "onkey", + "onkeypress", + "onkeyrelease", + "onscreenclick", + "ontimer", + "register_shape", + "resetscreen", + "screensize", + "setup", + "setworldcoordinates", + "textinput", + "title", + "tracer", + "turtles", + "update", + "window_height", + "window_width", + "back", + "backward", + "begin_fill", + "begin_poly", + "bk", + "circle", + "clear", + "clearstamp", + "clearstamps", + "clone", + "color", + "degrees", + "distance", + "dot", + "down", + "end_fill", + "end_poly", + "fd", + "fillcolor", + "filling", + "forward", + "get_poly", + "getpen", + "getscreen", + "get_shapepoly", + "getturtle", + "goto", + "heading", + "hideturtle", + "home", + "ht", + "isdown", + "isvisible", + "left", + "lt", + "onclick", + "ondrag", + "onrelease", + "pd", + "pen", + "pencolor", + "pendown", + "pensize", + "penup", + "pos", + "position", + "pu", + "radians", + "right", + "reset", + "resizemode", + "rt", + "seth", + "setheading", + "setpos", + "setposition", + "settiltangle", + "setundobuffer", + "setx", + "sety", + "shape", + "shapesize", + "shapetransform", + "shearfactor", + "showturtle", + "speed", + "st", + "stamp", + "tilt", + "tiltangle", + "towards", + "turtlesize", + "undo", + "undobufferentries", + "up", + "width", + "write", + "xcor", + "ycor", + "write_docstringdict", + "done", + "Terminator", +] # 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 @@ -18,7 +144,17 @@ _PolygonCoords = Sequence[tuple[float, float]] # Vec2D is actually a custom subclass of 'tuple'. Vec2D = tuple[float, float] -class ScrolledCanvas(Frame): ... +# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas +class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] + bg: str + hscroll: Scrollbar + vscroll: Scrollbar + def __init__( + self, master: Misc | None, width: int = ..., height: int = ..., canvwidth: int = ..., canvheight: int = ... + ) -> None: ... + canvwidth: int + canvheight: int + def reset(self, canvwidth: int | None = ..., canvheight: int | None = ..., bg: str | None = ...) -> None: ... class TurtleScreenBase: cv: Canvas @@ -205,8 +341,6 @@ class TPen: st = showturtle ht = hideturtle -_T = TypeVar("_T") - class RawTurtle(TPen, TNavigator): screen: TurtleScreen screens: ClassVar[list[TurtleScreen]] @@ -217,7 +351,7 @@ class RawTurtle(TPen, TNavigator): def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self: Self) -> Self: ... @overload def shape(self, name: None = ...) -> str: ... @overload @@ -262,7 +396,7 @@ class RawTurtle(TPen, TNavigator): def end_poly(self) -> None: ... def get_poly(self) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self: Self) -> Self: ... getpen = getturtle def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index caf745b99554..510f8d9eb551 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -16,16 +16,158 @@ from typing import ( KeysView, Mapping, MutableSequence, - Type, TypeVar, ValuesView, overload, ) from typing_extensions import Literal, ParamSpec, final +if sys.version_info >= (3, 10): + __all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "CellType", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "BuiltinMethodType", + "WrapperDescriptorType", + "MethodWrapperType", + "MethodDescriptorType", + "ClassMethodDescriptorType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "resolve_bases", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + "GenericAlias", + "UnionType", + "EllipsisType", + "NoneType", + "NotImplementedType", + ] +elif sys.version_info >= (3, 9): + __all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "CellType", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "BuiltinMethodType", + "WrapperDescriptorType", + "MethodWrapperType", + "MethodDescriptorType", + "ClassMethodDescriptorType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "resolve_bases", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + "GenericAlias", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "CellType", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "BuiltinMethodType", + "WrapperDescriptorType", + "MethodWrapperType", + "MethodDescriptorType", + "ClassMethodDescriptorType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "resolve_bases", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "BuiltinMethodType", + "WrapperDescriptorType", + "MethodWrapperType", + "MethodDescriptorType", + "ClassMethodDescriptorType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "resolve_bases", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + ] +else: + __all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + ] + # Note, all classes "defined" here require special handling. -_T = TypeVar("_T") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") _T_co = TypeVar("_T_co", covariant=True) @@ -42,15 +184,21 @@ class _Cell: # Make sure this class definition stays roughly in line with `builtins.function` @final class FunctionType: - __closure__: tuple[_Cell, ...] | None + @property + def __closure__(self) -> tuple[_Cell, ...] | None: ... __code__: CodeType __defaults__: tuple[Any, ...] | None __dict__: dict[str, Any] - __globals__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... __name__: str __qualname__: str __annotations__: dict[str, Any] __kwdefaults__: dict[str, Any] + if sys.version_info >= (3, 10): + @property + def __builtins__(self) -> dict[str, Any]: ... + def __init__( self, code: CodeType, @@ -60,31 +208,49 @@ class FunctionType: closure: tuple[_Cell, ...] | None = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: object | None, type: type | None = ...) -> MethodType: ... + @overload + def __get__(self, obj: None, type: type) -> FunctionType: ... + @overload + def __get__(self, obj: object, type: type | None = ...) -> MethodType: ... LambdaType = FunctionType @final class CodeType: - """Create a code object. Not for the faint of heart.""" - - co_argcount: int + @property + def co_argcount(self) -> 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, ...] + @property + def co_posonlyargcount(self) -> int: ... + + @property + def co_kwonlyargcount(self) -> int: ... + @property + def co_nlocals(self) -> int: ... + @property + def co_stacksize(self) -> int: ... + @property + def co_flags(self) -> int: ... + @property + def co_code(self) -> bytes: ... + @property + def co_consts(self) -> tuple[Any, ...]: ... + @property + def co_names(self) -> tuple[str, ...]: ... + @property + def co_varnames(self) -> tuple[str, ...]: ... + @property + def co_filename(self) -> str: ... + @property + def co_name(self) -> str: ... + @property + def co_firstlineno(self) -> int: ... + @property + def co_lnotab(self) -> bytes: ... + @property + def co_freevars(self) -> tuple[str, ...]: ... + @property + def co_cellvars(self) -> tuple[str, ...]: ... if sys.version_info >= (3, 8): def __init__( self, @@ -146,7 +312,8 @@ class CodeType: co_linetable: object = ..., ) -> CodeType: ... def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... - co_linetable: object + @property + def co_linetable(self) -> object: ... elif sys.version_info >= (3, 8): def replace( self, @@ -175,7 +342,7 @@ class CodeType: class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): __hash__: None # type: ignore[assignment] def __init__(self, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> None: ... - def __getitem__(self, k: _KT) -> _VT_co: ... + def __getitem__(self, __k: _KT) -> _VT_co: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... def copy(self) -> dict[_KT, _VT_co]: ... @@ -191,14 +358,15 @@ class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): class SimpleNamespace: __hash__: None # type: ignore[assignment] 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: ... + def __getattribute__(self, __name: str) -> Any: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + def __delattr__(self, __name: str) -> None: ... class ModuleType: __name__: str __file__: str | None - __dict__: dict[str, Any] + @property + def __dict__(self) -> dict[str, Any]: ... # type: ignore[override] __loader__: _LoaderProtocol | None __package__: str | None __path__: MutableSequence[str] @@ -211,37 +379,49 @@ class ModuleType: @final class GeneratorType(Generator[_T_co, _T_contra, _V_co]): - gi_code: CodeType - gi_frame: FrameType - gi_running: bool - gi_yieldfrom: GeneratorType[_T_co, _T_contra, Any] | None + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + @property + def gi_yieldfrom(self) -> GeneratorType[_T_co, _T_contra, Any] | None: ... + __name__: str + __qualname__: str def __iter__(self) -> GeneratorType[_T_co, _T_contra, _V_co]: ... def __next__(self) -> _T_co: ... def close(self) -> None: ... def send(self, __arg: _T_contra) -> _T_co: ... @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> _T_co: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... @final class AsyncGeneratorType(AsyncGenerator[_T_co, _T_contra]): - ag_await: Awaitable[Any] | None - ag_frame: FrameType - ag_running: bool - ag_code: CodeType + @property + def ag_await(self) -> Awaitable[Any] | None: ... + @property + def ag_frame(self) -> FrameType: ... + @property + def ag_running(self) -> bool: ... + @property + def ag_code(self) -> CodeType: ... + __name__: str + __qualname__: str def __aiter__(self) -> AsyncGeneratorType[_T_co, _T_contra]: ... - def __anext__(self) -> Awaitable[_T_co]: ... - def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... + def __anext__(self) -> Coroutine[Any, Any, _T_co]: ... + def asend(self, __val: _T_contra) -> Coroutine[Any, Any, _T_co]: ... @overload - def athrow( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> Awaitable[_T_co]: ... + async def athrow( + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + ) -> _T_co: ... @overload - def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... - def aclose(self) -> Awaitable[None]: ... + async def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... + def aclose(self) -> Coroutine[Any, Any, None]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @@ -249,52 +429,65 @@ class AsyncGeneratorType(AsyncGenerator[_T_co, _T_contra]): class CoroutineType(Coroutine[_T_co, _T_contra, _V_co]): __name__: str __qualname__: str - cr_await: Any | None - cr_code: CodeType - cr_frame: FrameType - cr_running: bool + @property + def cr_await(self) -> Any | None: ... + @property + def cr_code(self) -> CodeType: ... + @property + def cr_frame(self) -> FrameType: ... + @property + def cr_running(self) -> bool: ... + if sys.version_info >= (3, 7): + @property + def cr_origin(self) -> tuple[tuple[str, int, str], ...] | None: ... + def close(self) -> None: ... def __await__(self) -> Generator[Any, None, _V_co]: ... def send(self, __arg: _T_contra) -> _T_co: ... @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> _T_co: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... 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. - """ - + # 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: object | None, type: type | None) -> FunctionType: ... @final class MethodType: - __closure__: tuple[_Cell, ...] | None # inherited from the added function - __defaults__: tuple[Any, ...] | None # inherited from the added function - __func__: _StaticFunctionType - __self__: object - __name__: str # inherited from the added function - __qualname__: str # inherited from the added function - def __init__(self, func: Callable[..., Any], obj: object) -> None: ... + @property + def __closure__(self) -> tuple[_Cell, ...] | None: ... # inherited from the added function + @property + def __defaults__(self) -> tuple[Any, ...] | None: ... # inherited from the added function + @property + def __func__(self) -> _StaticFunctionType: ... + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... # inherited from the added function + @property + def __qualname__(self) -> str: ... # inherited from the added function + def __init__(self, __func: Callable[..., Any], __obj: object) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... @final class BuiltinFunctionType: - __self__: object | ModuleType - __name__: str - __qualname__: str + @property + def __self__(self) -> object | ModuleType: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... BuiltinMethodType = BuiltinFunctionType @@ -302,32 +495,48 @@ BuiltinMethodType = BuiltinFunctionType if sys.version_info >= (3, 7): @final class WrapperDescriptorType: - __name__: str - __qualname__: str - __objclass__: type + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __get__(self, __obj: Any, __type: type = ...) -> Any: ... + @final class MethodWrapperType: - __self__: object - __name__: str - __qualname__: str - __objclass__: type + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def __eq__(self, __other: object) -> bool: ... + def __ne__(self, __other: object) -> bool: ... + @final class MethodDescriptorType: - __name__: str - __qualname__: str - __objclass__: type + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Any, type: type = ...) -> Any: ... + @final class ClassMethodDescriptorType: - __name__: str - __qualname__: str - __objclass__: type + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Any, type: type = ...) -> Any: ... @@ -349,16 +558,23 @@ class TracebackType: @final class FrameType: - f_back: FrameType | None - f_builtins: dict[str, Any] - f_code: CodeType - f_globals: dict[str, Any] - f_lasti: int + @property + def f_back(self) -> FrameType | None: ... + @property + def f_builtins(self) -> dict[str, Any]: ... + @property + def f_code(self) -> CodeType: ... + @property + def f_globals(self) -> dict[str, Any]: ... + @property + def f_lasti(self) -> int: ... # see discussion in #6769: f_lineno *can* sometimes be None, # but you should probably file a bug report with CPython if you encounter it being None in the wild. # An `int | None` annotation here causes too many false-positive errors. - f_lineno: int | Any - f_locals: dict[str, Any] + @property + def f_lineno(self) -> int | Any: ... + @property + def f_locals(self) -> dict[str, Any]: ... f_trace: Callable[[FrameType, str, Any], Any] | None if sys.version_info >= (3, 7): f_trace_lines: bool @@ -367,19 +583,27 @@ class FrameType: @final class GetSetDescriptorType: - __name__: str - __objclass__: type + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __get__(self, __obj: Any, __type: type = ...) -> Any: ... def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... + def __delete__(self, __obj: Any) -> None: ... @final class MemberDescriptorType: - __name__: str - __objclass__: type + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... def __get__(self, __obj: Any, __type: type = ...) -> Any: ... def __set__(self, __instance: Any, __value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... + def __delete__(self, __obj: Any) -> None: ... if sys.version_info >= (3, 7): def new_class( @@ -421,9 +645,12 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 9): class GenericAlias: - __origin__: type - __args__: tuple[Any, ...] - __parameters__: tuple[Any, ...] + @property + def __origin__(self) -> type: ... + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... def __init__(self, origin: type, args: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... # incomplete @@ -437,6 +664,7 @@ if sys.version_info >= (3, 10): NotImplementedType = _NotImplementedType # noqa F811 from builtins @final class UnionType: - __args__: tuple[Any, ...] - def __or__(self, obj: Any) -> UnionType: ... - def __ror__(self, obj: Any) -> UnionType: ... + @property + def __args__(self) -> tuple[Any, ...]: ... + def __or__(self, __obj: Any) -> UnionType: ... + def __ror__(self, __obj: Any) -> UnionType: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 6e461b8aa260..295bfa8d1137 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,6 +1,6 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys -from _typeshed import SupportsKeysAndGetItem +from _typeshed import Self as TypeshedSelf, SupportsKeysAndGetItem from abc import ABCMeta, abstractmethod from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final @@ -11,31 +11,482 @@ if sys.version_info >= (3, 7): if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 11): + __all__ = [ + "Annotated", + "Any", + "Callable", + "ClassVar", + "Concatenate", + "Final", + "ForwardRef", + "Generic", + "Literal", + "Optional", + "ParamSpec", + "Protocol", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "Collection", + "AsyncGenerator", + "AsyncContextManager", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "ChainMap", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "OrderedDict", + "Set", + "FrozenSet", + "NamedTuple", + "TypedDict", + "Generator", + "BinaryIO", + "IO", + "Match", + "Pattern", + "TextIO", + "AnyStr", + "assert_never", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "is_typeddict", + "Never", + "NewType", + "no_type_check", + "no_type_check_decorator", + "NoReturn", + "overload", + "ParamSpecArgs", + "ParamSpecKwargs", + "reveal_type", + "runtime_checkable", + "Self", + "Text", + "TYPE_CHECKING", + "TypeAlias", + "TypeGuard", + ] +elif sys.version_info >= (3, 10): + __all__ = [ + "Annotated", + "Any", + "Callable", + "ClassVar", + "Concatenate", + "Final", + "ForwardRef", + "Generic", + "Literal", + "Optional", + "ParamSpec", + "Protocol", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "Collection", + "AsyncGenerator", + "AsyncContextManager", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "ChainMap", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "OrderedDict", + "Set", + "FrozenSet", + "NamedTuple", + "TypedDict", + "Generator", + "BinaryIO", + "IO", + "Match", + "Pattern", + "TextIO", + "AnyStr", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "is_typeddict", + "NewType", + "no_type_check", + "no_type_check_decorator", + "NoReturn", + "overload", + "ParamSpecArgs", + "ParamSpecKwargs", + "runtime_checkable", + "Text", + "TYPE_CHECKING", + "TypeAlias", + "TypeGuard", + ] +elif sys.version_info >= (3, 9): + __all__ = [ + "Annotated", + "Any", + "Callable", + "ClassVar", + "Final", + "ForwardRef", + "Generic", + "Literal", + "Optional", + "Protocol", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "Collection", + "AsyncGenerator", + "AsyncContextManager", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "ChainMap", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "OrderedDict", + "Set", + "FrozenSet", + "NamedTuple", + "TypedDict", + "Generator", + "BinaryIO", + "IO", + "Match", + "Pattern", + "TextIO", + "AnyStr", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "NewType", + "no_type_check", + "no_type_check_decorator", + "NoReturn", + "overload", + "runtime_checkable", + "Text", + "TYPE_CHECKING", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "Any", + "Callable", + "ClassVar", + "Final", + "ForwardRef", + "Generic", + "Literal", + "Optional", + "Protocol", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "Collection", + "AsyncGenerator", + "AsyncContextManager", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "ChainMap", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "OrderedDict", + "Set", + "FrozenSet", + "NamedTuple", + "TypedDict", + "Generator", + "AnyStr", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "NewType", + "no_type_check", + "no_type_check_decorator", + "NoReturn", + "overload", + "runtime_checkable", + "Text", + "TYPE_CHECKING", + ] +elif sys.version_info >= (3, 7): + __all__ = [ + "Any", + "Callable", + "ClassVar", + "ForwardRef", + "Generic", + "Optional", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "Collection", + "AsyncGenerator", + "AsyncContextManager", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsInt", + "SupportsRound", + "ChainMap", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "OrderedDict", + "Set", + "FrozenSet", + "NamedTuple", + "Generator", + "AnyStr", + "cast", + "get_type_hints", + "NewType", + "no_type_check", + "no_type_check_decorator", + "NoReturn", + "overload", + "Text", + "TYPE_CHECKING", + ] +else: + __all__ = [ + "Any", + "Callable", + "ClassVar", + "Generic", + "Optional", + "Tuple", + "Type", + "TypeVar", + "Union", + "AbstractSet", + "GenericMeta", + "ByteString", + "Container", + "ContextManager", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Sequence", + "Sized", + "ValuesView", + "Reversible", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsInt", + "SupportsRound", + "Counter", + "Deque", + "Dict", + "DefaultDict", + "List", + "Set", + "FrozenSet", + "NamedTuple", + "Generator", + "AnyStr", + "cast", + "get_type_hints", + "NewType", + "no_type_check", + "no_type_check_decorator", + "overload", + "Text", + "TYPE_CHECKING", + ] + Any = object() +@_final class TypeVar: __name__: str - __bound__: Type[Any] | None - __constraints__: Tuple[Type[Any], ...] + __bound__: Any | None + __constraints__: tuple[Any, ...] __covariant__: bool __contravariant__: bool def __init__( - self, - name: str, - *constraints: Type[Any], - bound: None | Type[Any] | str = ..., - covariant: bool = ..., - contravariant: bool = ..., + self, name: str, *constraints: Any, bound: Any | None = ..., covariant: bool = ..., contravariant: bool = ... ) -> None: ... if sys.version_info >= (3, 10): - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... # Used for an undocumented mypy feature. Does not exist at runtime. _promote = object() +# N.B. Keep this definition in sync with typing_extensions._SpecialForm +@_final class _SpecialForm: - def __getitem__(self, typeargs: Any) -> object: ... + def __getitem__(self, parameters: Any) -> object: ... if sys.version_info >= (3, 10): def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... @@ -46,23 +497,34 @@ _T = TypeVar("_T") def overload(func: _F) -> _F: ... +# Unlike the vast majority module-level objects in stub files, +# these `_SpecialForm` objects in typing need the default value `= ...`, +# due to the fact that they are used elswhere in the same file. +# Otherwise, flake8 erroneously flags them as undefined. +# `_SpecialForm` objects in typing.py that are not used elswhere in the same file +# do not need the default value assignment. 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 = ... NoReturn: _SpecialForm = ... + +Optional: _SpecialForm +Tuple: _SpecialForm +ClassVar: _SpecialForm if sys.version_info >= (3, 8): - Final: _SpecialForm = ... + Final: _SpecialForm def final(f: _T) -> _T: ... - Literal: _SpecialForm = ... + Literal: _SpecialForm # TypedDict is a (non-subscriptable) special form. TypedDict: object +if sys.version_info >= (3, 11): + Self: _SpecialForm + Never: _SpecialForm = ... + if sys.version_info < (3, 7): class GenericMeta(type): ... @@ -70,26 +532,27 @@ if sys.version_info >= (3, 10): class ParamSpecArgs: __origin__: ParamSpec def __init__(self, origin: ParamSpec) -> None: ... + class ParamSpecKwargs: __origin__: ParamSpec def __init__(self, origin: ParamSpec) -> None: ... + class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: Any | None __covariant__: bool __contravariant__: bool - def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... - ) -> None: ... + def __init__(self, name: str, *, bound: Any | None = ..., contravariant: bool = ..., covariant: bool = ...) -> None: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... - Concatenate: _SpecialForm = ... - TypeAlias: _SpecialForm = ... - TypeGuard: _SpecialForm = ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... + Concatenate: _SpecialForm + TypeAlias: _SpecialForm + TypeGuard: _SpecialForm + class NewType: def __init__(self, name: str, tp: type) -> None: ... def __call__(self, x: _T) -> _T: ... @@ -133,18 +596,14 @@ if sys.version_info >= (3, 7): OrderedDict = _Alias() if sys.version_info >= (3, 9): - Annotated: _SpecialForm = ... + Annotated: _SpecialForm # Predefined type variables. -AnyStr = TypeVar("AnyStr", str, bytes) +AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 -if sys.version_info >= (3, 8): - # This class did actually exist in 3.7, but had a different base. - # We'll just pretend it didn't exist though: the main external use case for _ProtocolMeta is - # to inherit from for your own custom protocol metaclasses. If you're using 3.7, at runtime - # you'd use typing_extensions.Protocol, which would be unrelated to typing._ProtocolMeta and - # so you'd run into metaclass conflicts at runtime if you used typing._ProtocolMeta. - class _ProtocolMeta(ABCMeta): ... +# Technically in 3.7 this inherited from GenericMeta. But let's not reflect that, since +# type checkers tend to assume that Protocols all have the ABCMeta metaclass. +class _ProtocolMeta(ABCMeta): ... # Abstract base classes. @@ -284,24 +743,24 @@ class AsyncIterable(Protocol[_T_co]): @runtime_checkable class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): @abstractmethod - def __anext__(self) -> Awaitable[_T_co]: ... + async def __anext__(self) -> _T_co: ... def __aiter__(self) -> AsyncIterator[_T_co]: ... class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): @abstractmethod - def __anext__(self) -> Awaitable[_T_co]: ... + async def __anext__(self) -> _T_co: ... @abstractmethod - def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... + async def asend(self, __value: _T_contra) -> _T_co: ... @overload @abstractmethod - def athrow( + async def athrow( self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> Awaitable[_T_co]: ... + ) -> _T_co: ... @overload @abstractmethod - def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... + async def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... @abstractmethod - def aclose(self) -> Awaitable[None]: ... + async def aclose(self) -> None: ... @abstractmethod def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... @property @@ -327,14 +786,14 @@ class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): class Sequence(Collection[_T_co], Reversible[_T_co], Generic[_T_co]): @overload @abstractmethod - def __getitem__(self, i: int) -> _T_co: ... + def __getitem__(self, index: int) -> _T_co: ... @overload @abstractmethod - def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + def __getitem__(self, index: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... def count(self, value: Any) -> int: ... - def __contains__(self, x: object) -> bool: ... + def __contains__(self, value: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... @@ -343,22 +802,22 @@ class MutableSequence(Sequence[_T], Generic[_T]): def insert(self, index: int, value: _T) -> None: ... @overload @abstractmethod - def __getitem__(self, i: int) -> _T: ... + def __getitem__(self, index: int) -> _T: ... @overload @abstractmethod - def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + def __getitem__(self, index: slice) -> MutableSequence[_T]: ... @overload @abstractmethod - def __setitem__(self, i: int, o: _T) -> None: ... + def __setitem__(self, index: int, value: _T) -> None: ... @overload @abstractmethod - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ... @overload @abstractmethod - def __delitem__(self, i: int) -> None: ... + def __delitem__(self, index: int) -> None: ... @overload @abstractmethod - def __delitem__(self, i: slice) -> None: ... + def __delitem__(self, index: slice) -> None: ... # Mixin methods def append(self, value: _T) -> None: ... def clear(self) -> None: ... @@ -366,20 +825,21 @@ class MutableSequence(Sequence[_T], Generic[_T]): def reverse(self) -> None: ... def pop(self, index: int = ...) -> _T: ... def remove(self, value: _T) -> None: ... - def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + def __iadd__(self: TypeshedSelf, values: Iterable[_T]) -> TypeshedSelf: ... class AbstractSet(Collection[_T_co], Generic[_T_co]): @abstractmethod def __contains__(self, x: object) -> bool: ... + def _hash(self) -> int: ... # 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[_T_co | _T]: ... - def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... + def __le__(self, other: AbstractSet[Any]) -> bool: ... + def __lt__(self, other: AbstractSet[Any]) -> bool: ... + def __gt__(self, other: AbstractSet[Any]) -> bool: ... + def __ge__(self, other: AbstractSet[Any]) -> bool: ... + def __and__(self, other: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, other: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... + def __sub__(self, other: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, other: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... def isdisjoint(self, other: Iterable[Any]) -> bool: ... class MutableSet(AbstractSet[_T], Generic[_T]): @@ -391,48 +851,50 @@ class MutableSet(AbstractSet[_T], Generic[_T]): def clear(self) -> None: ... def pop(self) -> _T: ... def remove(self, value: _T) -> None: ... - def __ior__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... - def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[_T | _S]: ... - def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ior__(self: TypeshedSelf, it: AbstractSet[_T]) -> TypeshedSelf: ... # type: ignore[override,misc] + def __iand__(self: TypeshedSelf, it: AbstractSet[Any]) -> TypeshedSelf: ... + def __ixor__(self: TypeshedSelf, it: AbstractSet[_T]) -> TypeshedSelf: ... # type: ignore[override,misc] + def __isub__(self: TypeshedSelf, it: AbstractSet[Any]) -> TypeshedSelf: ... class MappingView(Sized): def __init__(self, mapping: Mapping[Any, Any]) -> None: ... # undocumented def __len__(self) -> int: ... -class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): +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 __and__(self, other: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... + def __rand__(self, other: Iterable[_T]) -> set[_T]: ... + def __contains__(self, item: 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[tuple[_KT_co, _VT_co] | _T]: ... - def __ror__(self, o: Iterable[_T]) -> set[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[tuple[_KT_co, _VT_co] | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + + def __or__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __ror__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __sub__(self, other: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... + def __rsub__(self, other: Iterable[_T]) -> set[_T]: ... + def __xor__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __rxor__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): def __init__(self, mapping: Mapping[_KT_co, Any]) -> 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 __and__(self, other: Iterable[Any]) -> set[_KT_co]: ... + def __rand__(self, other: Iterable[_T]) -> set[_T]: ... + def __contains__(self, key: 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[_KT_co | _T]: ... - def __ror__(self, o: Iterable[_T]) -> set[_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[_KT_co | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... + + def __or__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... + def __ror__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... + def __sub__(self, other: Iterable[Any]) -> set[_KT_co]: ... + def __rsub__(self, other: Iterable[_T]) -> set[_T]: ... + def __xor__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... + def __rxor__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): def __init__(self, mapping: Mapping[Any, _VT_co]) -> None: ... # undocumented - def __contains__(self, o: object) -> bool: ... + def __contains__(self, value: object) -> bool: ... def __iter__(self) -> Iterator[_VT_co]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_VT_co]: ... @@ -440,16 +902,18 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): @runtime_checkable class ContextManager(Protocol[_T_co]): def __enter__(self) -> _T_co: ... + @abstractmethod def __exit__( self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None ) -> bool | None: ... @runtime_checkable class AsyncContextManager(Protocol[_T_co]): - def __aenter__(self) -> Awaitable[_T_co]: ... - def __aexit__( + async def __aenter__(self) -> _T_co: ... + @abstractmethod + async def __aexit__( self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> Awaitable[bool | None]: ... + ) -> bool | None: ... class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, @@ -458,9 +922,9 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): def __getitem__(self, __k: _KT) -> _VT_co: ... # Mixin methods @overload - def get(self, key: _KT) -> _VT_co | None: ... + def get(self, __key: _KT) -> _VT_co | None: ... @overload - def get(self, __key: _KT, __default: _VT_co | _T) -> _VT_co | _T: ... + def get(self, __key: _KT, default: _VT_co | _T) -> _VT_co | _T: ... def items(self) -> ItemsView[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... @@ -475,19 +939,32 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): @overload def pop(self, __key: _KT) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, __key: _KT, default: _VT | _T) -> _VT | _T: ... def popitem(self) -> tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + # This overload should be allowed only if the value type is compatible with None. + # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT) -> _T | None: ... + @overload + 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]], + # 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]. + # 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. + # + # Various mapping classes have __ior__ methods that should be kept roughly in line with .update(): + # -- dict.__ior__ + # -- os._Environ.__ior__ + # -- collections.UserDict.__ior__ + # -- collections.ChainMap.__ior__ + # -- weakref.WeakValueDictionary.__ior__ + # -- weakref.WeakKeyDictionary.__ior__ @overload def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload @@ -497,8 +974,11 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): Text = str -TYPE_CHECKING = True +TYPE_CHECKING: bool +# In stubs, the arguments of the IO class are marked as positional-only. +# This differs from runtime, but better reflects the fact that in reality +# classes deriving from IO use different names for the arguments. class IO(Iterator[AnyStr], Generic[AnyStr]): # TODO use abstract properties @property @@ -516,27 +996,27 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): @abstractmethod def isatty(self) -> bool: ... @abstractmethod - def read(self, n: int = ...) -> AnyStr: ... + def read(self, __n: int = ...) -> AnyStr: ... @abstractmethod def readable(self) -> bool: ... @abstractmethod - def readline(self, limit: int = ...) -> AnyStr: ... + def readline(self, __limit: int = ...) -> AnyStr: ... @abstractmethod - def readlines(self, hint: int = ...) -> list[AnyStr]: ... + def readlines(self, __hint: int = ...) -> list[AnyStr]: ... @abstractmethod - def seek(self, offset: int, whence: int = ...) -> int: ... + def seek(self, __offset: int, __whence: int = ...) -> int: ... @abstractmethod def seekable(self) -> bool: ... @abstractmethod def tell(self) -> int: ... @abstractmethod - def truncate(self, size: int | None = ...) -> int: ... + def truncate(self, __size: int | None = ...) -> int: ... @abstractmethod def writable(self) -> bool: ... @abstractmethod - def write(self, s: AnyStr) -> int: ... + def write(self, __s: AnyStr) -> int: ... @abstractmethod - def writelines(self, lines: Iterable[AnyStr]) -> None: ... + def writelines(self, __lines: Iterable[AnyStr]) -> None: ... @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -545,7 +1025,7 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, t: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, __t: Type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None ) -> bool | None: ... class BinaryIO(IO[bytes]): @@ -571,15 +1051,21 @@ class ByteString(Sequence[int], metaclass=ABCMeta): ... @_final class Match(Generic[AnyStr]): - pos: int - endpos: int - lastindex: int | None - lastgroup: str | None - string: AnyStr + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... # The regular expression object whose match() or search() method produced # this match instance. - re: Pattern[AnyStr] + @property + def re(self) -> Pattern[AnyStr]: ... def expand(self, template: AnyStr) -> AnyStr: ... # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload @@ -587,13 +1073,13 @@ class Match(Generic[AnyStr]): @overload def group(self, __group: str | int) -> AnyStr | Any: ... @overload - def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> Tuple[AnyStr | Any, ...]: ... + def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... # Each item of groups()'s return tuple is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload - def groups(self) -> Tuple[AnyStr | Any, ...]: ... + def groups(self) -> tuple[AnyStr | Any, ...]: ... @overload - def groups(self, default: _T) -> Tuple[AnyStr | _T, ...]: ... + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... # Each value in groupdict()'s return dict is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload @@ -604,21 +1090,27 @@ class Match(Generic[AnyStr]): def end(self, __group: int | str = ...) -> int: ... def span(self, __group: int | str = ...) -> tuple[int, int]: ... @property - def regs(self) -> Tuple[tuple[int, int], ...]: ... # undocumented + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def __getitem__(self, __key: _Literal[0]) -> AnyStr: ... @overload def __getitem__(self, __key: int | str) -> AnyStr | Any: ... + def __copy__(self) -> Match[AnyStr]: ... + def __deepcopy__(self, __memo: Any) -> Match[AnyStr]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @_final class Pattern(Generic[AnyStr]): - flags: int - groupindex: Mapping[str, int] - groups: int - pattern: AnyStr + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... @@ -633,6 +1125,8 @@ class Pattern(Generic[AnyStr]): 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 __copy__(self) -> Pattern[AnyStr]: ... + def __deepcopy__(self, __memo: Any) -> Pattern[AnyStr]: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -670,7 +1164,7 @@ else: if sys.version_info >= (3, 8): def get_origin(tp: Any) -> Any | None: ... - def get_args(tp: Any) -> Tuple[Any, ...]: ... + def get_args(tp: Any) -> tuple[Any, ...]: ... @overload def cast(typ: Type[_T], val: Any) -> _T: ... @@ -679,15 +1173,19 @@ def cast(typ: str, val: Any) -> Any: ... @overload def cast(typ: object, val: Any) -> Any: ... +if sys.version_info >= (3, 11): + def reveal_type(__obj: _T) -> _T: ... + def assert_never(__arg: Never) -> Never: ... + # Type constructors -class NamedTuple(Tuple[Any, ...]): +class NamedTuple(tuple[Any, ...]): if sys.version_info < (3, 8): _field_types: collections.OrderedDict[str, type] elif sys.version_info < (3, 9): _field_types: dict[str, type] _field_defaults: dict[str, Any] - _fields: Tuple[str, ...] + _fields: tuple[str, ...] _source: str @overload def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ... @@ -699,11 +1197,12 @@ class NamedTuple(Tuple[Any, ...]): def _asdict(self) -> dict[str, Any]: ... else: def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + + def _replace(self: TypeshedSelf, **kwargs: Any) -> TypeshedSelf: ... # 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: ... + def copy(self: TypeshedSelf) -> TypeshedSelf: ... # 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: ... @@ -714,28 +1213,31 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... - def __or__(self: _T, __value: _T) -> _T: ... - def __ior__(self: _T, __value: _T) -> _T: ... + def __or__(self: TypeshedSelf, __value: TypeshedSelf) -> TypeshedSelf: ... + def __ior__(self: TypeshedSelf, __value: TypeshedSelf) -> TypeshedSelf: ... # This itself is only available during type checking def type_check_only(func_or_cls: _F) -> _F: ... if sys.version_info >= (3, 7): + @_final class ForwardRef: __forward_arg__: str __forward_code__: CodeType __forward_evaluated__: bool __forward_value__: Any | None __forward_is_argument__: bool + __forward_is_class__: bool + __forward_module__: Any | None if sys.version_info >= (3, 9): # The module and is_class arguments were added in later Python 3.9 versions. def __init__(self, arg: str, is_argument: bool = ..., module: Any | None = ..., *, is_class: bool = ...) -> None: ... else: def __init__(self, arg: str, is_argument: bool = ...) -> None: ... + def _evaluate(self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None) -> Any | None: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 11): def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index e7f288377b83..193fa4feb4f3 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,6 +1,7 @@ import abc import sys -from typing import ( +from _typeshed import Self as TypeshedSelf # see #6932 for why the alias cannot have a leading underscore +from typing import ( # noqa Y022 TYPE_CHECKING as TYPE_CHECKING, Any, AsyncContextManager as AsyncContextManager, @@ -33,36 +34,38 @@ _T = TypeVar("_T") _F = TypeVar("_F", bound=Callable[..., Any]) _TC = TypeVar("_TC", bound=Type[object]) +# unfortunately we have to duplicate this class definition from typing.pyi or we break pytype class _SpecialForm: - def __getitem__(self, typeargs: Any) -> Any: ... + def __getitem__(self, parameters: Any) -> object: ... + if sys.version_info >= (3, 10): + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +# Do not import (and re-export) Protocol or runtime_checkable from +# typing module because type checkers need to be able to distinguish +# typing.Protocol and typing_extensions.Protocol so they can properly +# warn users about potential runtime exceptions when using typing.Protocol +# on older versions of Python. +Protocol: _SpecialForm = ... def runtime_checkable(cls: _TC) -> _TC: ... # This alias for above is kept here for backwards compatibility. runtime = runtime_checkable -Protocol: _SpecialForm = ... -Final: _SpecialForm = ... -Self: _SpecialForm = ... -Required: _SpecialForm = ... -NotRequired: _SpecialForm = ... +Final: _SpecialForm def final(f: _F) -> _F: ... -Literal: _SpecialForm = ... +Literal: _SpecialForm def IntVar(name: str) -> Any: ... # returns a new TypeVar -if sys.version_info < (3, 8): - # Technically in 3.6 this inherited from GenericMeta. But let's not reflect that, since - # type checkers tend to assume that Protocols all have the ABCMeta metaclass. - class _ProtocolMeta(abc.ABCMeta): ... - # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): __required_keys__: frozenset[str] __optional_keys__: frozenset[str] __total__: bool - def copy(self: _T) -> _T: ... + def copy(self: TypeshedSelf) -> TypeshedSelf: ... # 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: ... @@ -75,7 +78,7 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def __delitem__(self, k: NoReturn) -> None: ... # TypedDict is a (non-subscriptable) special form. -TypedDict: object = ... +TypedDict: object OrderedDict = _Alias() @@ -89,36 +92,74 @@ if sys.version_info >= (3, 7): def get_args(tp: Any) -> tuple[Any, ...]: ... def get_origin(tp: Any) -> Any | None: ... -Annotated: _SpecialForm = ... -_AnnotatedAlias: Any = ... # undocumented +Annotated: _SpecialForm +_AnnotatedAlias: Any # undocumented @runtime_checkable class SupportsIndex(Protocol, metaclass=abc.ABCMeta): @abc.abstractmethod def __index__(self) -> int: ... -# PEP 612 support for Python < 3.9 +# New things in 3.10 if sys.version_info >= (3, 10): - from typing import Concatenate as Concatenate, ParamSpec as ParamSpec, TypeAlias as TypeAlias, TypeGuard as TypeGuard + from typing import ( + Concatenate as Concatenate, + ParamSpec as ParamSpec, + TypeAlias as TypeAlias, + TypeGuard as TypeGuard, + is_typeddict as is_typeddict, + ) else: class ParamSpecArgs: __origin__: ParamSpec def __init__(self, origin: ParamSpec) -> None: ... + class ParamSpecKwargs: __origin__: ParamSpec def __init__(self, origin: ParamSpec) -> None: ... + class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: type[Any] | None __covariant__: bool __contravariant__: bool def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, name: str, *, bound: None | type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... ) -> None: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... - Concatenate: _SpecialForm = ... - TypeAlias: _SpecialForm = ... - TypeGuard: _SpecialForm = ... + Concatenate: _SpecialForm + TypeAlias: _SpecialForm + TypeGuard: _SpecialForm + def is_typeddict(tp: object) -> bool: ... + +# New things in 3.11 +if sys.version_info >= (3, 11): + from typing import Never as Never, Self as Self, assert_never as assert_never, reveal_type as reveal_type +else: + Self: _SpecialForm + Never: _SpecialForm + def reveal_type(__obj: _T) -> _T: ... + def assert_never(__arg: NoReturn) -> NoReturn: ... + +# Experimental (hopefully these will be in 3.11) +Required: _SpecialForm +NotRequired: _SpecialForm +LiteralString: _SpecialForm +Unpack: _SpecialForm + +@final +class TypeVarTuple: + __name__: str + def __init__(self, name: str) -> None: ... + def __iter__(self) -> Any: ... # Unpack[Self] + +def dataclass_transform( + *, + eq_default: bool = ..., + order_default: bool = ..., + kw_only_default: bool = ..., + field_descriptors: tuple[type[Any] | Callable[..., Any], ...] = ..., +) -> Callable[[_T], _T]: ... diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index ead25ba4062c..aec8867df48d 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -1,10 +1,13 @@ import sys from typing import Any, TypeVar +from typing_extensions import final ucd_3_2_0: UCD -ucnhash_CAPI: Any unidata_version: str +if sys.version_info < (3, 10): + ucnhash_CAPI: Any + _T = TypeVar("_T") def bidirectional(__chr: str) -> str: ... @@ -23,7 +26,7 @@ def mirrored(__chr: str) -> int: ... def name(__chr: str, __default: _T = ...) -> str | _T: ... def normalize(__form: str, __unistr: str) -> str: ... def numeric(__chr: str, __default: _T = ...) -> float | _T: ... - +@final class UCD: # The methods below are constructed from the same array in C # (unicodedata_functions) and hence identical to the methods above. diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index d3b0efaa83ff..4bbf98c992c1 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -1,5 +1,4 @@ import sys -from unittest.async_case import * from .case import ( FunctionTestCase as FunctionTestCase, @@ -29,6 +28,59 @@ from .signals import ( from .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite if sys.version_info >= (3, 8): + from unittest.async_case import * + from .case import addModuleCleanup as addModuleCleanup + __all__ = [ + "TestResult", + "TestCase", + "IsolatedAsyncioTestCase", + "TestSuite", + "TextTestRunner", + "TestLoader", + "FunctionTestCase", + "main", + "defaultTestLoader", + "SkipTest", + "skip", + "skipIf", + "skipUnless", + "expectedFailure", + "TextTestResult", + "installHandler", + "registerResult", + "removeResult", + "removeHandler", + "addModuleCleanup", + "getTestCaseNames", + "makeSuite", + "findTestCases", + ] + +else: + __all__ = [ + "TestResult", + "TestCase", + "TestSuite", + "TextTestRunner", + "TestLoader", + "FunctionTestCase", + "main", + "defaultTestLoader", + "SkipTest", + "skip", + "skipIf", + "skipUnless", + "expectedFailure", + "TextTestResult", + "installHandler", + "registerResult", + "removeResult", + "removeHandler", + "getTestCaseNames", + "makeSuite", + "findTestCases", + ] + def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/_log.pyi b/mypy/typeshed/stdlib/unittest/_log.pyi index f9e406199cd4..4de5d502e004 100644 --- a/mypy/typeshed/stdlib/unittest/_log.pyi +++ b/mypy/typeshed/stdlib/unittest/_log.pyi @@ -1,7 +1,7 @@ import logging import sys from types import TracebackType -from typing import ClassVar, Generic, NamedTuple, Type, TypeVar +from typing import ClassVar, Generic, NamedTuple, TypeVar from unittest.case import TestCase _L = TypeVar("_L", None, _LoggingWatcher) @@ -21,7 +21,8 @@ class _AssertLogsContext(Generic[_L]): no_logs: bool else: def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... + def __enter__(self) -> _L: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool | None: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index bdf534b37c9f..0442ec444559 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,10 +1,11 @@ -import sys -from typing import Any, Awaitable, Callable +from typing import Awaitable, Callable +from typing_extensions import ParamSpec 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: ... +_P = ParamSpec("_P") + +class IsolatedAsyncioTestCase(TestCase): + async def asyncSetUp(self) -> None: ... + async def asyncTearDown(self) -> None: ... + def addAsyncCleanup(self, __func: Callable[_P, Awaitable[object]], *args: _P.args, **kwargs: _P.kwargs) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 858bf38e700d..87441920fe50 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -19,10 +19,10 @@ from typing import ( NoReturn, Pattern, Sequence, - Type, TypeVar, overload, ) +from typing_extensions import ParamSpec from warnings import WarningMessage if sys.version_info >= (3, 9): @@ -30,6 +30,7 @@ if sys.version_info >= (3, 9): _E = TypeVar("_E", bound=BaseException) _FT = TypeVar("_FT", bound=Callable[..., Any]) +_P = ParamSpec("_P") DIFF_OMITTED: str @@ -43,9 +44,11 @@ else: # this is generic over the logging watcher, but in lower versions # the watcher is hard-coded. _L = TypeVar("_L") + class _LoggingWatcher(NamedTuple): records: list[logging.LogRecord] output: list[str] + class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): LOGGING_FORMAT: ClassVar[str] test_case: TestCase @@ -55,11 +58,11 @@ else: def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... def __enter__(self) -> _LoggingWatcher: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... if sys.version_info >= (3, 8): - def addModuleCleanup(__function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def addModuleCleanup(__function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... def doModuleCleanups() -> None: ... def expectedFailure(test_item: _FT) -> _FT: ... @@ -71,7 +74,7 @@ class SkipTest(Exception): def __init__(self, reason: str) -> None: ... class TestCase: - failureException: Type[BaseException] + failureException: type[BaseException] longMessage: bool maxDiff: int | None # undocumented @@ -79,6 +82,7 @@ class TestCase: # undocumented _testMethodDoc: str def __init__(self, methodName: str = ...) -> None: ... + def __eq__(self, other: object) -> bool: ... def setUp(self) -> None: ... def tearDown(self) -> None: ... @classmethod @@ -107,51 +111,58 @@ class TestCase: 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: ... + # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp` + # are not using `ParamSpec` intentionally, + # because they might be used with explicitly wrong arg types to raise some error in tests. @overload def assertRaises( # type: ignore[misc] self, - expected_exception: Type[BaseException] | tuple[Type[BaseException], ...], - callable: Callable[..., Any], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], + callable: Callable[..., object], *args: Any, **kwargs: Any, ) -> None: ... @overload - def assertRaises(self, expected_exception: Type[_E] | tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertRaises(self, expected_exception: type[_E] | tuple[type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... @overload def assertRaisesRegex( # type: ignore[misc] self, - expected_exception: Type[BaseException] | tuple[Type[BaseException], ...], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], + callable: Callable[..., object], *args: Any, **kwargs: Any, ) -> None: ... @overload def assertRaisesRegex( self, - expected_exception: Type[_E] | tuple[Type[_E], ...], + expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], msg: Any = ..., ) -> _AssertRaisesContext[_E]: ... @overload def assertWarns( # type: ignore[misc] - self, expected_warning: Type[Warning] | tuple[Type[Warning], ...], callable: Callable[..., Any], *args: Any, **kwargs: Any + self, + expected_warning: type[Warning] | tuple[type[Warning], ...], + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, ) -> None: ... @overload - def assertWarns(self, expected_warning: Type[Warning] | tuple[Type[Warning], ...], msg: Any = ...) -> _AssertWarnsContext: ... + def assertWarns(self, expected_warning: type[Warning] | tuple[type[Warning], ...], msg: Any = ...) -> _AssertWarnsContext: ... @overload def assertWarnsRegex( # type: ignore[misc] self, - expected_warning: Type[Warning] | tuple[Type[Warning], ...], + expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], - *args: Any, - **kwargs: Any, + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, ) -> None: ... @overload def assertWarnsRegex( self, - expected_warning: Type[Warning] | tuple[Type[Warning], ...], + expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], msg: Any = ..., ) -> _AssertWarnsContext: ... @@ -162,6 +173,7 @@ class TestCase: def assertNoLogs( self, logger: str | logging.Logger | None = ..., level: int | str | None = ... ) -> _AssertLogsContext[None]: ... + @overload def assertAlmostEqual( self, first: float, second: float, places: int | None = ..., msg: Any = ..., delta: float | None = ... @@ -193,10 +205,10 @@ class TestCase: def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... def assertNotRegex(self, text: AnyStr, unexpected_regex: 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 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: Type[Sequence[Any]] | None = ... + self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = ..., seq_type: type[Sequence[Any]] | None = ... ) -> 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: ... @@ -208,18 +220,20 @@ class TestCase: def id(self) -> str: ... def shortDescription(self) -> str | None: ... if sys.version_info >= (3, 8): - def addCleanup(self, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def addCleanup(self, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... else: - def addCleanup(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def addCleanup(self, function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def doCleanups(self) -> None: ... if sys.version_info >= (3, 8): @classmethod - def addClassCleanup(cls, __function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def addClassCleanup(cls, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... @classmethod def doClassCleanups(cls) -> None: ... + def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented - if sys.version_info < (3, 11): + if sys.version_info < (3, 12): 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: ... @@ -230,13 +244,13 @@ class TestCase: @overload def failUnlessRaises( # type: ignore[misc] self, - exception: Type[BaseException] | tuple[Type[BaseException], ...], - callable: Callable[..., Any] = ..., - *args: Any, - **kwargs: Any, + exception: type[BaseException] | tuple[type[BaseException], ...], + callable: Callable[_P, object] = ..., + *args: _P.args, + **kwargs: _P.kwargs, ) -> None: ... @overload - def failUnlessRaises(self, exception: Type[_E] | tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def failUnlessRaises(self, exception: 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 = ... @@ -250,16 +264,16 @@ class TestCase: @overload def assertRaisesRegexp( # type: ignore[misc] self, - exception: Type[BaseException] | tuple[Type[BaseException], ...], + exception: type[BaseException] | tuple[type[BaseException], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], + callable: Callable[..., object], *args: Any, **kwargs: Any, ) -> None: ... @overload def assertRaisesRegexp( self, - exception: Type[_E] | tuple[Type[_E], ...], + exception: type[_E] | tuple[type[_E], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], msg: Any = ..., ) -> _AssertRaisesContext[_E]: ... @@ -281,7 +295,7 @@ class _AssertRaisesContext(Generic[_E]): exception: _E def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -293,5 +307,5 @@ class _AssertWarnsContext: warnings: list[WarningMessage] def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi index aca7e4f9554f..8b3c82233cec 100644 --- a/mypy/typeshed/stdlib/unittest/loader.pyi +++ b/mypy/typeshed/stdlib/unittest/loader.pyi @@ -3,7 +3,7 @@ import unittest.case import unittest.result import unittest.suite from types import ModuleType -from typing import Any, Callable, Pattern, Sequence, Type +from typing import Any, Callable, Pattern, Sequence _SortComparisonMethod = Callable[[str, str], int] _SuiteClass = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] @@ -11,7 +11,7 @@ _SuiteClass = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] VALID_MODULE_NAME: Pattern[str] class TestLoader: - errors: list[Type[BaseException]] + errors: list[type[BaseException]] testMethodPrefix: str sortTestMethodsUsing: _SortComparisonMethod @@ -19,18 +19,18 @@ class TestLoader: testNamePatterns: list[str] | None 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: ModuleType | None = ...) -> unittest.suite.TestSuite: ... def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = ...) -> unittest.suite.TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... + def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ... def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> unittest.suite.TestSuite: ... defaultTestLoader: TestLoader if sys.version_info >= (3, 7): def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], + testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ..., testNamePatterns: list[str] | None = ..., @@ -38,11 +38,11 @@ if sys.version_info >= (3, 7): else: def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... + testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... ) -> Sequence[str]: ... def makeSuite( - testCaseClass: Type[unittest.case.TestCase], + testCaseClass: type[unittest.case.TestCase], prefix: str = ..., sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ..., diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index 6d1117ecaf79..d3c0ca722f4d 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -4,7 +4,7 @@ import unittest.loader import unittest.result import unittest.suite from types import ModuleType -from typing import Any, Iterable, Protocol, Type +from typing import Any, Iterable, Protocol MAIN_EXAMPLES: str MODULE_EXAMPLES: str @@ -30,7 +30,7 @@ class TestProgram: module: None | str | ModuleType = ..., defaultTest: str | Iterable[str] | None = ..., argv: list[str] | None = ..., - testRunner: Type[_TestRunner] | _TestRunner | None = ..., + testRunner: type[_TestRunner] | _TestRunner | None = ..., testLoader: unittest.loader.TestLoader = ..., exit: bool = ..., verbosity: int = ..., @@ -47,6 +47,7 @@ class TestProgram: def createTests(self, from_discovery: bool = ..., Loader: unittest.loader.TestLoader | None = ...) -> 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 72d0bab95c2e..4f520528cd2e 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,8 +1,11 @@ import sys -from typing import Any, Awaitable, Callable, Generic, Iterable, Mapping, Sequence, Type, TypeVar, overload +from _typeshed import Self +from contextlib import _GeneratorContextManager +from typing import Any, Awaitable, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload +from typing_extensions import Literal _T = TypeVar("_T") -_TT = TypeVar("_TT", bound=Type[Any]) +_TT = TypeVar("_TT", bound=type[Any]) _R = TypeVar("_R") if sys.version_info >= (3, 8): @@ -73,25 +76,36 @@ class _Sentinel: sentinel: Any DEFAULT: Any +_ArgsKwargs = tuple[tuple[Any, ...], Mapping[str, Any]] +_NameArgsKwargs = tuple[str, tuple[Any, ...], Mapping[str, Any]] +_CallValue = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs + class _Call(tuple[Any, ...]): def __new__( - cls, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... - ) -> Any: ... + cls: type[Self], + value: _CallValue = ..., + name: str | None = ..., + parent: Any | None = ..., + two: bool = ..., + from_kall: bool = ..., + ) -> Self: ... name: Any parent: Any from_kall: Any def __init__( - self, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... + self, value: _CallValue = ..., name: str | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... ) -> None: ... - def __eq__(self, other: Any) -> bool: ... - __ne__: Any + def __eq__(self, other: object) -> bool: ... + def __ne__(self, __other: object) -> bool: ... def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: Any) -> Any: ... + def __getattribute__(self, attr: str) -> Any: ... if sys.version_info >= (3, 8): @property - def args(self): ... + def args(self) -> tuple[Any, ...]: ... @property - def kwargs(self): ... + def kwargs(self) -> Mapping[str, Any]: ... + def call_list(self) -> Any: ... call: _Call @@ -103,13 +117,13 @@ class Base: def __init__(self, *args: Any, **kwargs: Any) -> None: ... class NonCallableMock(Base, Any): - def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + def __new__(__cls: type[Self], *args: Any, **kw: Any) -> Self: ... def __init__( self, - spec: list[str] | object | Type[object] | None = ..., + spec: list[str] | object | type[object] | None = ..., wraps: Any | None = ..., name: str | None = ..., - spec_set: list[str] | object | Type[object] | None = ..., + spec_set: list[str] | object | type[object] | None = ..., parent: NonCallableMock | None = ..., _spec_state: Any | None = ..., _new_name: str = ..., @@ -120,6 +134,8 @@ class NonCallableMock(Base, Any): **kwargs: Any, ) -> None: ... def __getattr__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __setattr__(self, name: str, value: Any) -> None: ... if sys.version_info >= (3, 8): def _calls_repr(self, prefix: str = ...) -> str: ... def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... @@ -137,10 +153,12 @@ class NonCallableMock(Base, Any): else: def assert_called(_mock_self) -> None: ... def assert_called_once(_mock_self) -> None: ... + def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... 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: ... @@ -224,17 +242,22 @@ class _patch(Generic[_T]): new_callable: Any | None, kwargs: Mapping[str, Any], ) -> None: ... + def copy(self) -> _patch[_T]: ... @overload def __call__(self, func: _TT) -> _TT: ... @overload def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... if sys.version_info >= (3, 8): - def decoration_helper(self, patched, args, keywargs): ... + def decoration_helper( + self, patched: _patch[Any], args: Sequence[Any], keywargs: Any + ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... + def decorate_class(self, klass: _TT) -> _TT: ... def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ... if sys.version_info >= (3, 8): def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... + def get_original(self) -> tuple[Any, bool]: ... target: Any temp_original: Any @@ -258,7 +281,7 @@ class _patch_dict: class _patcher: TEST_PREFIX: str - dict: Type[_patch_dict] + dict: type[_patch_dict] if sys.version_info >= (3, 8): # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], @@ -366,6 +389,7 @@ class _patcher: new_callable: Any | None = ..., **kwargs: Any, ) -> _patch[MagicMock]: ... + def multiple( self, target: Any, @@ -404,28 +428,44 @@ if sys.version_info >= (3, 8): await_count: int await_args: _Call | None await_args_list: _CallList + class AsyncMagicMixin(MagicMixin): def __init__(self, *args: Any, **kw: Any) -> None: ... - class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... + + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... # type: ignore # argument disparities between base classes class MagicProxy: - name: Any + name: str parent: Any - def __init__(self, name, parent) -> None: ... + def __init__(self, name: str, parent: Any) -> None: ... if sys.version_info < (3, 8): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def create_mock(self): ... - def __get__(self, obj, _type: Any | None = ...): ... + + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Any | None = ...) -> Any: ... class _ANY: - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> Literal[True]: ... + def __ne__(self, other: object) -> Literal[False]: ... ANY: Any -def create_autospec( - spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Any | None = ..., _name: Any | None = ..., **kwargs: Any -) -> Any: ... +if sys.version_info >= (3, 10): + def create_autospec( + spec: Any, + spec_set: Any = ..., + instance: Any = ..., + _parent: Any | None = ..., + _name: Any | None = ..., + *, + unsafe: bool = ..., + **kwargs: Any, + ) -> Any: ... + +else: + def create_autospec( + spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Any | None = ..., _name: Any | None = ..., **kwargs: Any + ) -> Any: ... class _SpecState: spec: Any diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index 9a19aef77d21..1c79f8ab648c 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -1,8 +1,8 @@ import unittest.case from types import TracebackType -from typing import Any, Callable, TextIO, Type, TypeVar, Union +from typing import Any, Callable, TextIO, 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]) diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index 85481880ab17..479a9f2c304c 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -1,7 +1,7 @@ import unittest.case import unittest.result import unittest.suite -from typing import Callable, TextIO, Type +from typing import Callable, Iterable, TextIO _ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] @@ -10,12 +10,12 @@ class TextTestResult(unittest.result.TestResult): dots: bool # undocumented separator1: str separator2: str - showall: bool # undocumented + 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: ... + def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ... class TextTestRunner: resultclass: _ResultClassType @@ -27,7 +27,7 @@ class TextTestRunner: failfast: bool = ..., buffer: bool = ..., resultclass: _ResultClassType | None = ..., - warnings: Type[Warning] | None = ..., + warnings: type[Warning] | None = ..., *, tb_locals: bool = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi index 396b46eadf5a..f1e168a674a7 100644 --- a/mypy/typeshed/stdlib/unittest/suite.pyi +++ b/mypy/typeshed/stdlib/unittest/suite.pyi @@ -15,6 +15,7 @@ class BaseTestSuite(Iterable[_TestType]): def debug(self) -> None: ... def countTestCases(self) -> int: ... def __iter__(self) -> Iterator[_TestType]: ... + def __eq__(self, other: object) -> bool: ... class TestSuite(BaseTestSuite): 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 680ca24b7c33..30ab6061b100 100644 --- a/mypy/typeshed/stdlib/unittest/util.pyi +++ b/mypy/typeshed/stdlib/unittest/util.pyi @@ -11,7 +11,7 @@ _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 _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]]: ... diff --git a/mypy/typeshed/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi index 1d91fedceeca..48c8287e979a 100644 --- a/mypy/typeshed/stdlib/urllib/error.pyi +++ b/mypy/typeshed/stdlib/urllib/error.pyi @@ -2,13 +2,15 @@ from email.message import Message from typing import IO from urllib.response import addinfourl -# Stubs for urllib.error +__all__ = ["URLError", "HTTPError", "ContentTooShortError"] class URLError(IOError): reason: str | BaseException def __init__(self, reason: str | BaseException, filename: str | None = ...) -> None: ... class HTTPError(URLError, addinfourl): + @property + def reason(self) -> str: ... # type: ignore[override] code: int def __init__(self, url: str, code: int, msg: str, hdrs: Message, fp: IO[bytes] | None) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index 7404b5382014..b3cdc73e2fb1 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -4,6 +4,30 @@ from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = [ + "urlparse", + "urlunparse", + "urljoin", + "urldefrag", + "urlsplit", + "urlunsplit", + "urlencode", + "parse_qs", + "parse_qsl", + "quote", + "quote_plus", + "quote_from_bytes", + "unquote", + "unquote_plus", + "unquote_to_bytes", + "DefragResult", + "ParseResult", + "SplitResult", + "DefragResultBytes", + "ParseResultBytes", + "SplitResultBytes", +] + _Str = Union[bytes, str] uses_relative: list[str] @@ -21,14 +45,18 @@ class _ResultMixinBase(Generic[AnyStr]): class _ResultMixinStr(_ResultMixinBase[str]): def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... -class _ResultMixinBytes(_ResultMixinBase[str]): +class _ResultMixinBytes(_ResultMixinBase[bytes]): def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... class _NetlocResultMixinBase(Generic[AnyStr]): - username: AnyStr | None - password: AnyStr | None - hostname: AnyStr | None - port: int | None + @property + def username(self) -> AnyStr | None: ... + @property + def password(self) -> AnyStr | None: ... + @property + def hostname(self) -> AnyStr | None: ... + @property + def port(self) -> int | None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -36,8 +64,10 @@ class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... class _DefragResultBase(tuple[Any, ...], Generic[AnyStr]): - url: AnyStr - fragment: AnyStr + @property + def url(self) -> AnyStr: ... + @property + def fragment(self) -> AnyStr: ... class _SplitResultBase(NamedTuple): scheme: str @@ -140,3 +170,4 @@ def urlunparse(components: Sequence[AnyStr | None]) -> AnyStr: ... def urlunsplit(components: tuple[AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None, AnyStr | None]) -> AnyStr: ... @overload def urlunsplit(components: Sequence[AnyStr | None]) -> AnyStr: ... +def unwrap(url: str) -> str: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 3749d7a390ea..265ef2196715 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -1,19 +1,57 @@ import ssl import sys -from _typeshed import StrOrBytesPath +from _typeshed import StrOrBytesPath, SupportsRead from email.message import Message from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol from http.cookiejar import CookieJar -from typing import IO, Any, Callable, ClassVar, Mapping, NoReturn, Pattern, Sequence, TypeVar, overload +from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, MutableMapping, NoReturn, Pattern, Sequence, TypeVar, overload from urllib.error import HTTPError from urllib.response import addclosehook, addinfourl +__all__ = [ + "Request", + "OpenerDirector", + "BaseHandler", + "HTTPDefaultErrorHandler", + "HTTPRedirectHandler", + "HTTPCookieProcessor", + "ProxyHandler", + "HTTPPasswordMgr", + "HTTPPasswordMgrWithDefaultRealm", + "HTTPPasswordMgrWithPriorAuth", + "AbstractBasicAuthHandler", + "HTTPBasicAuthHandler", + "ProxyBasicAuthHandler", + "AbstractDigestAuthHandler", + "HTTPDigestAuthHandler", + "ProxyDigestAuthHandler", + "HTTPHandler", + "FileHandler", + "FTPHandler", + "CacheFTPHandler", + "DataHandler", + "UnknownHandler", + "HTTPErrorProcessor", + "urlopen", + "install_opener", + "build_opener", + "pathname2url", + "url2pathname", + "getproxies", + "urlretrieve", + "urlcleanup", + "URLopener", + "FancyURLopener", + "HTTPSHandler", +] + _T = TypeVar("_T") _UrlopenRet = Any +_DataType = bytes | SupportsRead[bytes] | Iterable[bytes] | None def urlopen( url: str | Request, - data: bytes | None = ..., + data: _DataType | None = ..., timeout: float | None = ..., *, cafile: str | None = ..., @@ -51,8 +89,8 @@ class Request: host: str origin_req_host: str selector: str - data: bytes | None - headers: dict[str, str] + data: _DataType + headers: MutableMapping[str, str] unredirected_hdrs: dict[str, str] unverifiable: bool method: str | None @@ -60,8 +98,8 @@ class Request: def __init__( self, url: str, - data: bytes | None = ..., - headers: dict[str, str] = ..., + data: _DataType = ..., + headers: MutableMapping[str, str] = ..., origin_req_host: str | None = ..., unverifiable: bool = ..., method: str | None = ..., @@ -83,7 +121,7 @@ class Request: class OpenerDirector: addheaders: list[tuple[str, str]] def add_handler(self, handler: BaseHandler) -> None: ... - def open(self, fullurl: str | Request, data: bytes | None = ..., timeout: float | None = ...) -> _UrlopenRet: ... + def open(self, fullurl: str | Request, data: _DataType = ..., timeout: float | None = ...) -> _UrlopenRet: ... def error(self, proto: str, *args: Any) -> _UrlopenRet: ... def close(self) -> None: ... @@ -92,6 +130,7 @@ class BaseHandler: parent: OpenerDirector def add_parent(self, parent: OpenerDirector) -> None: ... def close(self) -> None: ... + def __lt__(self, other: object) -> bool: ... class HTTPDefaultErrorHandler(BaseHandler): def http_error_default( @@ -241,7 +280,7 @@ def urlretrieve( url: str, filename: StrOrBytesPath | None = ..., reporthook: Callable[[int, int, int], None] | None = ..., - data: bytes | None = ..., + data: _DataType = ..., ) -> tuple[str, HTTPMessage]: ... def urlcleanup() -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index 18b498b40744..2efec0d47d44 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -2,18 +2,18 @@ import sys from _typeshed import Self from email.message import Message from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Type, TypeVar +from typing import IO, Any, BinaryIO, Callable, Iterable -_AIUT = TypeVar("_AIUT", bound=addbase) +__all__ = ["addbase", "addclosehook", "addinfo", "addinfourl"] class addbase(BinaryIO): fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - def __iter__(self: _AIUT) -> _AIUT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> bytes: ... def close(self) -> None: ... # These methods don't actually exist, but the class inherits at runtime from @@ -51,6 +51,7 @@ class addinfourl(addinfo): if sys.version_info >= (3, 9): @property def status(self) -> int | None: ... + def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = ...) -> None: ... def geturl(self) -> str: ... def getcode(self) -> int | None: ... diff --git a/mypy/typeshed/stdlib/urllib/robotparser.pyi b/mypy/typeshed/stdlib/urllib/robotparser.pyi index 361126327993..d1d69546db42 100644 --- a/mypy/typeshed/stdlib/urllib/robotparser.pyi +++ b/mypy/typeshed/stdlib/urllib/robotparser.pyi @@ -1,7 +1,9 @@ import sys from typing import Iterable, NamedTuple -class _RequestRate(NamedTuple): +__all__ = ["RobotFileParser"] + +class RequestRate(NamedTuple): requests: int seconds: int @@ -14,6 +16,6 @@ class RobotFileParser: def mtime(self) -> int: ... def modified(self) -> None: ... def crawl_delay(self, useragent: str) -> str | None: ... - def request_rate(self, useragent: str) -> _RequestRate | None: ... + def request_rate(self, useragent: str) -> RequestRate | None: ... if sys.version_info >= (3, 8): def site_maps(self) -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index aacd458c02c7..05aa4afef2a7 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,6 +1,8 @@ import sys from typing import BinaryIO, Union +__all__ = ["Error", "encode", "decode"] + _File = Union[str, BinaryIO] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 782c0491ffb2..4d46e89beddd 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,5 +1,4 @@ import sys -from typing import Any # Because UUID has properties called int and bytes we need to rename these temporarily. _Int = int @@ -8,6 +7,7 @@ _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 @@ -38,6 +38,7 @@ class UUID: int: _Int | None = ..., version: _Int | None = ..., ) -> None: ... + @property def bytes(self) -> _Bytes: ... @property @@ -71,11 +72,11 @@ class UUID: @property def version(self) -> _Int | None: ... def __int__(self) -> _Int: ... - def __eq__(self, other: Any) -> bool: ... - def __lt__(self, other: Any) -> bool: ... - def __le__(self, other: Any) -> bool: ... - def __gt__(self, other: Any) -> bool: ... - def __ge__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: UUID) -> bool: ... + def __le__(self, other: UUID) -> bool: ... + def __gt__(self, other: UUID) -> bool: ... + def __ge__(self, other: UUID) -> bool: ... def getnode() -> int: ... def uuid1(node: _Int | None = ..., clock_seq: _Int | None = ...) -> UUID: ... diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index 7650e87d98b4..815490a205ab 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -35,6 +35,7 @@ class EnvBuilder: with_pip: bool = ..., prompt: str | None = ..., ) -> None: ... + def create(self, env_dir: StrOrBytesPath) -> None: ... def clear_directory(self, path: StrOrBytesPath) -> None: ... # undocumented def ensure_directories(self, env_dir: StrOrBytesPath) -> SimpleNamespace: ... diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index b1c9f4dda8ed..1799d69f5ba6 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,32 +1,43 @@ from _warnings import warn as warn, warn_explicit as warn_explicit from types import ModuleType, TracebackType -from typing import Any, Sequence, TextIO, Type, overload +from typing import Any, Sequence, TextIO, overload from typing_extensions import Literal +__all__ = [ + "warn", + "warn_explicit", + "showwarning", + "formatwarning", + "filterwarnings", + "simplefilter", + "resetwarnings", + "catch_warnings", +] + _ActionKind = Literal["default", "error", "ignore", "always", "module", "once"] -filters: Sequence[tuple[str, str | None, Type[Warning], str | None, int]] # undocumented, do not mutate +filters: Sequence[tuple[str, str | None, type[Warning], str | None, int]] # undocumented, do not mutate def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... + message: Warning | str, category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... ) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... +def formatwarning(message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... def filterwarnings( action: _ActionKind, message: str = ..., - category: Type[Warning] = ..., + category: type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ..., ) -> None: ... -def simplefilter(action: _ActionKind, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... +def simplefilter(action: _ActionKind, category: type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... def resetwarnings() -> None: ... class _OptionError(Exception): ... class WarningMessage: message: Warning | str - category: Type[Warning] + category: type[Warning] filename: str lineno: int file: TextIO | None @@ -35,7 +46,7 @@ class WarningMessage: def __init__( self, message: Warning | str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., @@ -52,7 +63,7 @@ class catch_warnings: def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... def __enter__(self) -> list[WarningMessage] | None: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... class _catch_warnings_without_records(catch_warnings): diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 3ce1b88a6835..13fa12348cb3 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,12 +1,18 @@ import sys -from _typeshed import Self -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union +from _typeshed import ReadableBuffer, Self +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union, overload +from typing_extensions import Literal + +if sys.version_info >= (3, 9): + __all__ = ["open", "Error", "Wave_read", "Wave_write"] +else: + __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] _File = Union[str, IO[bytes]] class Error(Exception): ... -WAVE_FORMAT_PCM: int +WAVE_FORMAT_PCM: Literal[1] class _wave_params(NamedTuple): nchannels: int @@ -57,12 +63,15 @@ class Wave_write: 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 writeframesraw(self, data: ReadableBuffer) -> None: ... + def writeframes(self, data: ReadableBuffer) -> None: ... def close(self) -> None: ... -# Returns a Wave_read if mode is rb and Wave_write if mode is wb +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Wave_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Wave_write: ... +@overload def open(f: _File, mode: str | None = ...) -> Any: ... if sys.version_info < (3, 9): diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index fd1cad7fe840..820488529143 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,5 +1,8 @@ +import sys +from _typeshed import Self, SupportsKeysAndGetItem from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar, overload +from typing_extensions import ParamSpec from _weakref import ( CallableProxyType as CallableProxyType, @@ -11,31 +14,56 @@ from _weakref import ( ref as ref, ) -_S = TypeVar("_S") +__all__ = [ + "ref", + "proxy", + "getweakrefcount", + "getweakrefs", + "WeakKeyDictionary", + "ReferenceType", + "ProxyType", + "CallableProxyType", + "ProxyTypes", + "WeakValueDictionary", + "WeakSet", + "WeakMethod", + "finalize", +] + _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) +_P = ParamSpec("_P") -ProxyTypes: tuple[Type[Any], ...] +ProxyTypes: tuple[type[Any], ...] class WeakMethod(ref[_CallableT], Generic[_CallableT]): - def __new__(cls, meth: _CallableT, callback: Callable[[_CallableT], object] | None = ...) -> WeakMethod[_CallableT]: ... + def __new__(cls: type[Self], meth: _CallableT, callback: Callable[[_CallableT], object] | None = ...) -> Self: ... def __call__(self) -> _CallableT | None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self: WeakValueDictionary[_KT, _VT], __other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + @overload + def __init__( + self: WeakValueDictionary[str, _VT], __other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = ..., **kwargs: _VT + ) -> None: ... def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __contains__(self, o: object) -> bool: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self: Self, memo: Any) -> Self: ... # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] @@ -47,11 +75,19 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT # This __new__ method uses a non-standard name for the "cls" parameter - def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore + def __new__(type: type[Self], ob: _T, callback: Callable[[_T], Any], key: _KT) -> Self: ... # type: ignore def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): @@ -60,13 +96,14 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... - def __contains__(self, o: object) -> bool: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self: Self, memo: Any) -> Self: ... # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] @@ -77,11 +114,20 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... -class finalize: - def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... +class finalize: # TODO: This is a good candidate for to be a `Generic[_P, _T]` class + def __init__(self, __obj: object, __func: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None: ... def __call__(self, _: Any = ...) -> Any | None: ... def detach(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... def peek(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... - alive: bool + @property + def alive(self) -> bool: ... atexit: bool diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index 459d886ac930..ce8fca262d2d 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -1,5 +1,9 @@ import sys +from abc import abstractmethod from typing import Callable, Sequence +from typing_extensions import Literal + +__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] class Error(Exception): ... @@ -23,16 +27,19 @@ class BaseBrowser: name: str basename: str def __init__(self, name: str = ...) -> None: ... + @abstractmethod def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... def open_new(self, url: str) -> bool: ... def open_new_tab(self, url: str) -> bool: ... class GenericBrowser(BaseBrowser): def __init__(self, name: str | Sequence[str]) -> None: ... + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... class BackgroundBrowser(GenericBrowser): ... class UnixBrowser(BaseBrowser): + def open(self, url: str, new: Literal[0, 1, 2] = ..., autoraise: bool = ...) -> bool: ... # type: ignore[override] raise_opts: list[str] | None background: bool redirect_stdout: bool @@ -49,12 +56,20 @@ class Galeon(UnixBrowser): class Chrome(UnixBrowser): ... class Opera(UnixBrowser): ... class Elinks(UnixBrowser): ... -class Konqueror(BaseBrowser): ... -class Grail(BaseBrowser): ... + +class Konqueror(BaseBrowser): + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Grail(BaseBrowser): + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... if sys.platform == "win32": - class WindowsDefault(BaseBrowser): ... + class WindowsDefault(BaseBrowser): + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... if sys.platform == "darwin": - class MacOSX(BaseBrowser): ... - class MacOSXOSAScript(BaseBrowser): ... # In runtime this class does not have `name` and `basename` + class MacOSX(BaseBrowser): + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + + class MacOSXOSAScript(BaseBrowser): # In runtime this class does not have `name` and `basename` + def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 57f0c4b3ddba..e55be6b5e8ba 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from types import TracebackType -from typing import Any, Type, Union +from typing import Any, Union from typing_extensions import Literal, final if sys.platform == "win32": @@ -95,7 +95,7 @@ if sys.platform == "win32": def __int__(self) -> int: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... def Close(self) -> None: ... def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi index 3d79f3b043f2..588bd5969e98 100644 --- a/mypy/typeshed/stdlib/winsound.pyi +++ b/mypy/typeshed/stdlib/winsound.pyi @@ -3,21 +3,21 @@ from typing import 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 + SND_FILENAME: Literal[131072] + SND_ALIAS: Literal[65536] + SND_LOOP: Literal[8] + SND_MEMORY: Literal[4] + SND_PURGE: Literal[64] + SND_ASYNC: Literal[1] + SND_NODEFAULT: Literal[2] + SND_NOSTOP: Literal[16] + SND_NOWAIT: Literal[8192] - MB_ICONASTERISK: int - MB_ICONEXCLAMATION: int - MB_ICONHAND: int - MB_ICONQUESTION: int - MB_OK: int + MB_ICONASTERISK: Literal[64] + MB_ICONEXCLAMATION: Literal[48] + MB_ICONHAND: Literal[16] + MB_ICONQUESTION: Literal[32] + MB_OK: Literal[0] 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 eccc0d164767..731cb52ea9db 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,12 +1,14 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, MutableMapping, Optional, Type +from typing import IO, Callable, MutableMapping, Optional from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +__all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISCGIHandler", "read_environ"] + +_exc_info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... @@ -23,8 +25,8 @@ class BaseHandler: os_environ: MutableMapping[str, str] - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented traceback_limit: int | None error_status: str diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 76d0b269793d..389d30c22db2 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -1,9 +1,11 @@ from http.server import BaseHTTPRequestHandler, HTTPServer -from typing import Type, TypeVar, overload +from typing import TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment +__all__ = ["WSGIServer", "WSGIRequestHandler", "demo_app", "make_server"] + server_version: str # undocumented sys_version: str # undocumented software_version: str # undocumented @@ -30,8 +32,8 @@ def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[by _S = TypeVar("_S", bound=WSGIServer) @overload -def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +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] = ... + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... ) -> _S: ... diff --git a/mypy/typeshed/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi index c769c77d36e9..f2c3135df786 100644 --- a/mypy/typeshed/stdlib/wsgiref/util.pyi +++ b/mypy/typeshed/stdlib/wsgiref/util.pyi @@ -3,6 +3,8 @@ from typing import IO, Any, Callable from .types import WSGIEnvironment +__all__ = ["FileWrapper", "guess_scheme", "application_uri", "request_uri", "shift_path_info", "setup_testing_defaults"] + class FileWrapper: filelike: IO[bytes] blksize: int @@ -10,6 +12,7 @@ class FileWrapper: def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... if sys.version_info < (3, 11): def __getitem__(self, key: Any) -> bytes: ... + def __iter__(self) -> FileWrapper: ... def __next__(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index 68e22727bc73..35491756c288 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -1,6 +1,8 @@ from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication from typing import Any, Callable, Iterable, Iterator, NoReturn +__all__ = ["validator"] + class WSGIWarning(Warning): ... def validator(application: WSGIApplication) -> WSGIApplication: ... diff --git a/mypy/typeshed/stdlib/xdrlib.pyi b/mypy/typeshed/stdlib/xdrlib.pyi index f59843f8ee9d..e9716e29014d 100644 --- a/mypy/typeshed/stdlib/xdrlib.pyi +++ b/mypy/typeshed/stdlib/xdrlib.pyi @@ -1,5 +1,7 @@ from typing import Callable, Sequence, TypeVar +__all__ = ["Error", "Packer", "Unpacker", "ConversionError"] + _T = TypeVar("_T") class Error(Exception): diff --git a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi index 38e6d05e4743..411401d11ccd 100644 --- a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi @@ -1,8 +1,10 @@ -from typing import Any, Iterable, Type, TypeVar +from typing import Any, Iterable, TypeVar + +__all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] _T = TypeVar("_T") -StringTypes: tuple[Type[str]] +StringTypes: tuple[type[str]] class NodeList(list[_T]): length: int @@ -14,4 +16,4 @@ class EmptyNodeList(tuple[Any, ...]): def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index e9a26e30d721..d8bcc299b991 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,11 +1,11 @@ import sys import xml.dom -from _typeshed import Self -from typing import IO, Any +from _typeshed import Self, SupportsRead +from typing import Any from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader -def parse(file: str | IO[Any], parser: XMLReader | None = ..., bufsize: int | None = ...): ... +def parse(file: str | SupportsRead[bytes] | SupportsRead[str], parser: XMLReader | None = ..., bufsize: int | None = ...): ... def parseString(string: str | bytes, parser: XMLReader | None = ...): ... def getDOMImplementation(features=...) -> DOMImplementation | None: ... @@ -22,12 +22,14 @@ class Node(xml.dom.Node): def lastChild(self) -> Node | None: ... @property def localName(self) -> str | None: ... + def __bool__(self) -> bool: ... if sys.version_info >= (3, 9): def toxml(self, encoding: Any | None = ..., standalone: Any | None = ...): ... def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ..., standalone: Any | None = ...): ... else: def toxml(self, encoding: Any | None = ...): ... def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ...): ... + def hasChildNodes(self) -> bool: ... def insertBefore(self, newChild, refChild): ... def appendChild(self, node): ... @@ -86,7 +88,7 @@ class NamedNodeMap: def values(self): ... def get(self, name, value: Any | None = ...): ... def __len__(self) -> int: ... - def __eq__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... def __ge__(self, other: Any) -> bool: ... def __gt__(self, other: Any) -> bool: ... def __le__(self, other: Any) -> bool: ... @@ -329,4 +331,5 @@ class Document(Node, DocumentLS): def writexml( self, writer, indent: str = ..., addindent: str = ..., newl: str = ..., encoding: Any | None = ... ) -> None: ... + def renameNode(self, n, namespaceURI: str, name): ... diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index c2b7aa0772fa..7ae2dcf3eadd 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,5 +1,6 @@ import sys -from typing import IO, Any, Sequence, Union +from _typeshed import SupportsRead +from typing import Any, Sequence, Union from typing_extensions import Literal from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler @@ -62,13 +63,14 @@ class ErrorHandler: def fatalError(self, exception) -> None: ... class DOMEventStream: - stream: IO[bytes] + stream: SupportsRead[bytes] | SupportsRead[str] parser: XMLReader bufsize: int - def __init__(self, stream: IO[bytes], parser: XMLReader, bufsize: int) -> None: ... + def __init__(self, stream: SupportsRead[bytes] | SupportsRead[str], parser: XMLReader, bufsize: int) -> None: ... pulldom: Any if sys.version_info < (3, 11): def __getitem__(self, pos): ... + def __next__(self): ... def __iter__(self): ... def getEvent(self) -> _Event: ... @@ -85,5 +87,7 @@ class SAX2DOM(PullDOM): default_bufsize: int -def parse(stream_or_string: str | IO[bytes], parser: XMLReader | None = ..., bufsize: int | None = ...) -> DOMEventStream: ... +def parse( + stream_or_string: str | SupportsRead[bytes] | SupportsRead[str], parser: XMLReader | None = ..., bufsize: int | None = ... +) -> DOMEventStream: ... def parseString(string: str, parser: XMLReader | None = ...) -> DOMEventStream: ... diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi index 2738d735e73f..0615edb8073e 100644 --- a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -4,6 +4,8 @@ from urllib.request import OpenerDirector from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS from xml.dom.minidom import Node +__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] + # UNKNOWN TYPES: # - `Options.errorHandler`. # The same as `_DOMBuilderErrorHandlerType`? diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index b355bef1208c..5cd85cc21753 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -20,6 +20,7 @@ if sys.version_info >= (3, 9): def include( elem: Element, loader: Callable[..., str | Element] | None = ..., base_url: str | None = ..., max_depth: int | None = ... ) -> None: ... + class LimitedRecursiveIncludeError(FatalIncludeError): ... else: diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index c4236cf292bb..aef8285eec5b 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -1,7 +1,6 @@ import sys -from _typeshed import FileDescriptor, StrOrBytesPath, SupportsWrite +from _typeshed import FileDescriptor, StrOrBytesPath, SupportsRead, SupportsWrite from typing import ( - IO, Any, Callable, Generator, @@ -16,10 +15,96 @@ from typing import ( Union, overload, ) -from typing_extensions import Literal, SupportsIndex +from typing_extensions import Literal, SupportsIndex, TypeGuard + +if sys.version_info >= (3, 9): + __all__ = [ + "Comment", + "dump", + "Element", + "ElementTree", + "fromstring", + "fromstringlist", + "indent", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "VERSION", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", + "canonicalize", + "C14NWriterTarget", + ] +elif sys.version_info >= (3, 8): + __all__ = [ + "Comment", + "dump", + "Element", + "ElementTree", + "fromstring", + "fromstringlist", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "VERSION", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", + "canonicalize", + "C14NWriterTarget", + ] +else: + __all__ = [ + "Comment", + "dump", + "Element", + "ElementTree", + "fromstring", + "fromstringlist", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "VERSION", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", + ] _T = TypeVar("_T") -_File = Union[StrOrBytesPath, FileDescriptor, IO[Any]] +_FileRead = Union[StrOrBytesPath, FileDescriptor, SupportsRead[bytes], SupportsRead[str]] +_FileWriteC14N = Union[StrOrBytesPath, FileDescriptor, SupportsWrite[bytes]] +_FileWrite = Union[_FileWriteC14N, SupportsWrite[str]] VERSION: str @@ -27,7 +112,8 @@ class ParseError(SyntaxError): code: int position: tuple[int, int] -def iselement(element: object) -> bool: ... +# In reality it works based on `.tag` attribute duck typing. +def iselement(element: object) -> TypeGuard[Element]: ... if sys.version_info >= (3, 8): @overload @@ -35,7 +121,7 @@ if sys.version_info >= (3, 8): xml_data: str | bytes | None = ..., *, out: None = ..., - from_file: _File | None = ..., + from_file: _FileRead | None = ..., with_comments: bool = ..., strip_text: bool = ..., rewrite_prefixes: bool = ..., @@ -49,7 +135,7 @@ if sys.version_info >= (3, 8): xml_data: str | bytes | None = ..., *, out: SupportsWrite[str], - from_file: _File | None = ..., + from_file: _FileRead | None = ..., with_comments: bool = ..., strip_text: bool = ..., rewrite_prefixes: bool = ..., @@ -84,19 +170,22 @@ class Element(MutableSequence[Element]): def iterfind(self, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... def itertext(self) -> Generator[str, None, None]: ... def keys(self) -> KeysView[str]: ... + # makeelement returns the type of self in Python impl, but not in C impl def makeelement(self, __tag: str, __attrib: dict[str, str]) -> Element: ... def remove(self, __subelement: Element) -> None: ... def set(self, __key: str, __value: str) -> None: ... - def __delitem__(self, i: SupportsIndex | slice) -> None: ... + def __copy__(self) -> Element: ... # returns the type of self in Python impl, but not in C impl + def __deepcopy__(self, __memo: Any) -> Element: ... # Only exists in C impl + def __delitem__(self, __i: SupportsIndex | slice) -> None: ... @overload - def __getitem__(self, i: SupportsIndex) -> Element: ... + def __getitem__(self, __i: SupportsIndex) -> Element: ... @overload - def __getitem__(self, s: slice) -> MutableSequence[Element]: ... + def __getitem__(self, __s: slice) -> MutableSequence[Element]: ... def __len__(self) -> int: ... @overload - def __setitem__(self, i: SupportsIndex, o: Element) -> None: ... + def __setitem__(self, __i: SupportsIndex, __o: Element) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... + def __setitem__(self, __s: slice, __o: Iterable[Element]) -> None: ... if sys.version_info < (3, 9): def getchildren(self) -> list[Element]: ... def getiterator(self, tag: str | None = ...) -> list[Element]: ... @@ -110,14 +199,20 @@ PI: Callable[..., Element] class QName: text: str def __init__(self, text_or_uri: str, tag: str | None = ...) -> None: ... + def __lt__(self, other: QName | str) -> bool: ... + def __le__(self, other: QName | str) -> bool: ... + def __gt__(self, other: QName | str) -> bool: ... + def __ge__(self, other: QName | str) -> bool: ... + def __eq__(self, other: object) -> bool: ... class ElementTree: - def __init__(self, element: Element | None = ..., file: _File | None = ...) -> None: ... + def __init__(self, element: Element | None = ..., file: _FileRead | None = ...) -> None: ... def getroot(self) -> Element: ... - def parse(self, source: _File, parser: XMLParser | None = ...) -> Element: ... + def parse(self, source: _FileRead, parser: XMLParser | None = ...) -> Element: ... def iter(self, tag: str | None = ...) -> Generator[Element, None, None]: ... if sys.version_info < (3, 9): def getiterator(self, tag: str | None = ...) -> list[Element]: ... + def find(self, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... @overload def findtext(self, path: str, default: None = ..., namespaces: dict[str, str] | None = ...) -> str | None: ... @@ -127,7 +222,7 @@ class ElementTree: def iterfind(self, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... def write( self, - file_or_filename: _File, + file_or_filename: _FileWrite, encoding: str | None = ..., xml_declaration: bool | None = ..., default_namespace: str | None = ..., @@ -135,7 +230,7 @@ class ElementTree: *, short_empty_elements: bool = ..., ) -> None: ... - def write_c14n(self, file: _File) -> None: ... + def write_c14n(self, file: _FileWriteC14N) -> None: ... def register_namespace(prefix: str, uri: str) -> None: ... @@ -230,8 +325,10 @@ def dump(elem: Element) -> None: ... if sys.version_info >= (3, 9): def indent(tree: Element | ElementTree, space: str = ..., level: int = ...) -> None: ... -def parse(source: _File, parser: XMLParser | None = ...) -> ElementTree: ... -def iterparse(source: _File, events: Sequence[str] | None = ..., parser: XMLParser | None = ...) -> Iterator[tuple[str, Any]]: ... +def parse(source: _FileRead, parser: XMLParser | None = ...) -> ElementTree: ... +def iterparse( + source: _FileRead, events: Sequence[str] | None = ..., parser: XMLParser | None = ... +) -> Iterator[tuple[str, Any]]: ... class XMLPullParser: def __init__(self, events: Sequence[str] | None = ..., *, _parser: XMLParser | None = ...) -> None: ... @@ -274,6 +371,7 @@ class TreeBuilder: insert_pis: bool else: def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... + def close(self) -> Element: ... def data(self, __data: str | bytes) -> None: ... def start(self, __tag: str | bytes, __attrs: dict[str | bytes, str | bytes]) -> Element: ... @@ -315,5 +413,6 @@ class XMLParser: else: def __init__(self, html: int = ..., target: Any = ..., encoding: str | None = ...) -> None: ... def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... + def close(self) -> Any: ... def feed(self, __data: str | bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi index c41e2bee0eb1..02272d803c18 100644 --- a/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/cElementTree.pyi @@ -1 +1 @@ -from xml.etree.ElementTree import * # noqa: F403 +from xml.etree.ElementTree import * diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index a123e7e894e2..418164aa887f 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,8 +1,12 @@ import sys -from typing import IO, Any, Iterable, NoReturn +from _typeshed import SupportsRead, _T_co +from typing import Any, Iterable, NoReturn, Protocol from xml.sax.handler import ContentHandler, ErrorHandler from xml.sax.xmlreader import Locator, XMLReader +class _SupportsReadClose(SupportsRead[_T_co], Protocol[_T_co]): + def close(self) -> None: ... + class SAXException(Exception): def __init__(self, msg: str, exception: Exception | None = ...) -> None: ... def getMessage(self) -> str: ... @@ -28,6 +32,8 @@ if sys.version_info >= (3, 8): else: def make_parser(parser_list: list[str] = ...) -> XMLReader: ... -def parse(source: str | IO[str] | IO[bytes], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... +def parse( + source: str | _SupportsReadClose[bytes] | _SupportsReadClose[str], handler: ContentHandler, errorHandler: ErrorHandler = ... +) -> None: ... def parseString(string: bytes | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index e9f9e03ae56d..d44c15cb64ed 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -6,7 +6,7 @@ from _typeshed import Self, SupportsRead, SupportsWrite from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Callable, Iterable, Mapping, Protocol, Type, Union, overload +from typing import Any, Callable, Iterable, Mapping, Protocol, Union, overload from typing_extensions import Literal class _SupportsTimeTuple(Protocol): @@ -83,10 +83,11 @@ class Binary: def __init__(self, data: bytes | None = ...) -> None: ... def decode(self, data: bytes) -> None: ... def encode(self, out: SupportsWrite[str]) -> None: ... + def __eq__(self, other: object) -> bool: ... def _binary(data: bytes) -> Binary: ... # undocumented -WRAPPERS: tuple[Type[DateTime], Type[Binary]] # undocumented +WRAPPERS: tuple[type[DateTime], type[Binary]] # undocumented class ExpatParser: # undocumented def __init__(self, target: Unmarshaller) -> None: ... @@ -96,7 +97,7 @@ class ExpatParser: # undocumented class Marshaller: dispatch: dict[ - Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] + type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] ] # TODO: Replace 'Any' with some kind of binding memo: dict[Any, None] @@ -176,7 +177,7 @@ class MultiCall: __server: ServerProxy __call_list: list[tuple[str, tuple[_Marshallable, ...]]] def __init__(self, server: ServerProxy) -> None: ... - def __getattr__(self, item: str) -> _MultiCallMethod: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... def __call__(self) -> MultiCallIterator: ... # A little white lie @@ -228,6 +229,7 @@ class Transport: ) -> 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 = ... @@ -254,6 +256,7 @@ class SafeTransport(Transport): ) -> None: ... else: def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ..., *, context: Any | None = ...) -> None: ... + def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... class ServerProxy: @@ -292,6 +295,7 @@ class ServerProxy: *, context: Any | None = ..., ) -> None: ... + def __getattr__(self, name: str) -> _Method: ... @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... @@ -301,7 +305,7 @@ class ServerProxy: def __call__(self, attr: str) -> Callable[[], None] | Transport: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> 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 48105d1461f0..0a07424949df 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -3,7 +3,7 @@ import pydoc import socketserver import sys from datetime import datetime -from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol, Type, Union +from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol, Union from xmlrpc.client import Fault # TODO: Recursive type on tuple, list, dict @@ -48,6 +48,7 @@ class SimpleXMLRPCDispatcher: # undocumented def register_function(self, function: _DispatchProtocol | None = ..., name: str | None = ...) -> Callable[..., Any]: ... else: def register_function(self, function: _DispatchProtocol, name: str | None = ...) -> Callable[..., Any]: ... + def register_introspection_functions(self) -> None: ... def register_multicall_functions(self) -> None: ... def _marshaled_dispatch( @@ -81,7 +82,7 @@ class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., @@ -97,7 +98,7 @@ class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., @@ -150,7 +151,7 @@ class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., diff --git a/mypy/typeshed/stdlib/xxlimited.pyi b/mypy/typeshed/stdlib/xxlimited.pyi index 0dddbb876638..b2fb72ad2c0b 100644 --- a/mypy/typeshed/stdlib/xxlimited.pyi +++ b/mypy/typeshed/stdlib/xxlimited.pyi @@ -1,8 +1,10 @@ import sys from typing import Any +from typing_extensions import final class Str: ... +@final class Xxo: def demo(self) -> None: ... @@ -15,4 +17,5 @@ if sys.version_info >= (3, 10): else: class error: ... class Null: ... + def roj(__b: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi index 581d2b72a664..17c3503ad6eb 100644 --- a/mypy/typeshed/stdlib/zipapp.pyi +++ b/mypy/typeshed/stdlib/zipapp.pyi @@ -2,6 +2,8 @@ import sys from pathlib import Path from typing import BinaryIO, Callable, Union +__all__ = ["ZipAppError", "create_archive", "get_interpreter"] + _Path = Union[str, Path, BinaryIO] class ZipAppError(ValueError): ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index c64690ba8ca9..b837528d7dfa 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -1,11 +1,43 @@ import io import sys -from _typeshed import Self, StrPath +from _typeshed import Self, StrOrBytesPath, StrPath from os import PathLike from types import TracebackType -from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, Type, overload +from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, overload from typing_extensions import Literal +if sys.version_info >= (3, 8): + __all__ = [ + "BadZipFile", + "BadZipfile", + "error", + "ZIP_STORED", + "ZIP_DEFLATED", + "ZIP_BZIP2", + "ZIP_LZMA", + "is_zipfile", + "ZipInfo", + "ZipFile", + "PyZipFile", + "LargeZipFile", + "Path", + ] +else: + __all__ = [ + "BadZipFile", + "BadZipfile", + "error", + "ZIP_STORED", + "ZIP_DEFLATED", + "ZIP_BZIP2", + "ZIP_LZMA", + "is_zipfile", + "ZipInfo", + "ZipFile", + "PyZipFile", + "LargeZipFile", + ] + _DateTuple = tuple[int, int, int, int, int, int] _ReadWriteMode = Literal["r", "w"] _ReadWriteBinaryMode = Literal["r", "w", "rb", "wb"] @@ -25,6 +57,12 @@ class _ZipStream(Protocol): # def tell(self) -> int: ... # def seek(self, __n: int) -> object: ... +# Stream shape as required by _EndRecData() and _EndRecData64(). +class _SupportsReadSeekTell(Protocol): + def read(self, __n: int = ...) -> bytes: ... + def seek(self, __cookie: int, __whence: int) -> object: ... + def tell(self) -> int: ... + class _ClosableZipStream(_ZipStream, Protocol): def close(self) -> object: ... @@ -96,9 +134,9 @@ class ZipExtFile(io.BufferedIOBase): decrypter: Callable[[Sequence[int]], bytes] | None = ..., close_fileobj: Literal[False] = ..., ) -> None: ... + def read(self, n: int | None = ...) -> bytes: ... def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] - def __repr__(self) -> str: ... def peek(self, n: int = ...) -> bytes: ... def read1(self, n: int | None) -> bytes: ... # type: ignore[override] if sys.version_info >= (3, 7): @@ -143,9 +181,10 @@ class ZipFile: def __init__( self, file: StrPath | IO[bytes], mode: _ZipFileMode = ..., compression: int = ..., allowZip64: bool = ... ) -> None: ... + def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def close(self) -> None: ... def getinfo(self, name: str) -> ZipInfo: ... @@ -211,10 +250,13 @@ class ZipInfo: def __init__(self, filename: str = ..., date_time: _DateTuple = ...) -> None: ... if sys.version_info >= (3, 8): @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = ..., *, strict_timestamps: bool = ...) -> ZipInfo: ... + def from_file( + cls: type[Self], filename: StrPath, arcname: StrPath | None = ..., *, strict_timestamps: bool = ... + ) -> Self: ... else: @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = ...) -> ZipInfo: ... + def from_file(cls: type[Self], filename: StrPath, arcname: StrPath | None = ...) -> Self: ... + def is_dir(self) -> bool: ... def FileHeader(self, zip64: bool | None = ...) -> bytes: ... @@ -230,12 +272,14 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 10): @property def filename(self) -> PathLike[str]: ... # undocumented + def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = ...) -> None: ... if sys.version_info >= (3, 9): def open(self, mode: _ReadWriteBinaryMode = ..., *args: Any, pwd: bytes | None = ..., **kwargs: Any) -> IO[bytes]: ... else: @property def open(self) -> _PathOpenProtocol: ... + def iterdir(self) -> Iterator[Path]: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... @@ -253,9 +297,10 @@ if sys.version_info >= (3, 8): def joinpath(self, *other: StrPath) -> Path: ... else: def joinpath(self, add: StrPath) -> Path: ... # undocumented + def __truediv__(self, add: StrPath) -> Path: ... -def is_zipfile(filename: StrPath | IO[bytes]) -> bool: ... +def is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: ... ZIP_STORED: int ZIP_DEFLATED: int diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index 3435092a4722..a0e6d9e258dc 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -7,6 +7,9 @@ from typing import Any if sys.version_info >= (3, 7): from importlib.abc import ResourceReader +if sys.version_info >= (3, 8): + __all__ = ["ZipImportError", "zipimporter"] + class ZipImportError(ImportError): ... class zipimporter: @@ -20,6 +23,7 @@ class zipimporter: def get_filename(self, fullname: str) -> str: ... if sys.version_info >= (3, 7): def get_resource_reader(self, fullname: str) -> ResourceReader | None: ... # undocumented + def get_source(self, fullname: str) -> str | None: ... def is_package(self, fullname: str) -> bool: ... def load_module(self, fullname: str) -> ModuleType: ... diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index 646c96bd2bef..cfd6784bb771 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,29 +1,30 @@ +import sys from array import array from typing import Any from typing_extensions import Literal -DEFLATED: int -DEF_MEM_LEVEL: int +DEFLATED: Literal[8] +DEF_MEM_LEVEL: int # can change +DEF_BUF_SIZE: Literal[16384] MAX_WBITS: int -ZLIB_VERSION: str +ZLIB_VERSION: str # can change +ZLIB_RUNTIME_VERSION: str # can change Z_NO_COMPRESSION: Literal[0] Z_PARTIAL_FLUSH: Literal[1] -Z_BEST_COMPRESSION: int -Z_BEST_SPEED: int +Z_BEST_COMPRESSION: Literal[9] +Z_BEST_SPEED: Literal[1] Z_BLOCK: Literal[5] -Z_DEFAULT_COMPRESSION: int -Z_DEFAULT_STRATEGY: int -Z_FILTERED: int -Z_FINISH: int -Z_FIXED: int -Z_FULL_FLUSH: int -Z_HUFFMAN_ONLY: int -Z_NO_FLUSH: int -Z_RLE: int -Z_SYNC_FLUSH: int +Z_DEFAULT_COMPRESSION: Literal[-1] +Z_DEFAULT_STRATEGY: Literal[0] +Z_FILTERED: Literal[1] +Z_FINISH: Literal[4] +Z_FIXED: Literal[4] +Z_FULL_FLUSH: Literal[3] +Z_HUFFMAN_ONLY: Literal[2] +Z_NO_FLUSH: Literal[0] +Z_RLE: Literal[3] +Z_SYNC_FLUSH: Literal[2] Z_TREES: Literal[6] -DEF_BUF_SIZE: int -ZLIB_RUNTIME_VERSION: str class error(Exception): ... @@ -41,7 +42,13 @@ class _Decompress: def copy(self) -> _Decompress: ... def adler32(__data: bytes, __value: int = ...) -> int: ... -def compress(__data: bytes, level: int = ...) -> bytes: ... + +if sys.version_info >= (3, 11): + def compress(__data: bytes, level: int = ..., wbits: int = ...) -> bytes: ... + +else: + def compress(__data: bytes, level: int = ...) -> bytes: ... + def compressobj( level: int = ..., method: int = ..., wbits: int = ..., memLevel: int = ..., strategy: int = ..., zdict: bytes | None = ... ) -> _Compress: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 4f924e0cc4bf..d766eab6b7ef 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,9 +1,8 @@ -import typing -from _typeshed import StrPath +from _typeshed import Self, StrPath from datetime import tzinfo -from typing import Any, Iterable, Protocol, Sequence, Type +from typing import Any, Iterable, Protocol, Sequence -_T = typing.TypeVar("_T", bound="ZoneInfo") +__all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] class _IOBytes(Protocol): def read(self, __size: int) -> bytes: ... @@ -14,9 +13,9 @@ class ZoneInfo(tzinfo): def key(self) -> str: ... def __init__(self, key: str) -> None: ... @classmethod - def no_cache(cls: Type[_T], key: str) -> _T: ... + def no_cache(cls: type[Self], key: str) -> Self: ... @classmethod - def from_file(cls: Type[_T], __fobj: _IOBytes, key: str | None = ...) -> _T: ... + def from_file(cls: type[Self], __fobj: _IOBytes, key: str | None = ...) -> Self: ... @classmethod def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index dd182c485177..33b47244d385 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,19 +1,20 @@ import abc import sys -from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, Type, TypeVar, ValuesView +from _typeshed import Self +from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, TypeVar, 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: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... + def update(self: Self, __m: Self) -> None: ... if sys.version_info >= (3, 0): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... @@ -23,9 +24,10 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def viewitems(self) -> ItemsView[str, object]: ... def viewkeys(self) -> KeysView[str]: ... def viewvalues(self) -> ValuesView[object]: ... + def __delitem__(self, k: NoReturn) -> None: ... -def TypedDict(typename: str, fields: dict[str, Type[Any]], total: bool = ...) -> Type[dict[str, Any]]: ... +def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... def Arg(type: _T = ..., name: str | None = ...) -> _T: ... def DefaultArg(type: _T = ..., name: str | None = ...) -> _T: ... def NamedArg(type: _T = ..., name: str | None = ...) -> _T: ... @@ -37,9 +39,10 @@ def KwArg(type: _T = ...) -> _T: ... # Deprecated: Use typing.NoReturn instead. class NoReturn: ... -# 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: ... +# This is consistent with implementation. Usage intends for this as +# a class decorator, but mypy does not support type[_T] for abstract +# classes until this issue is resolved, https://github.com/python/mypy/issues/4717. +def trait(cls: _T) -> _T: ... def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... class FlexibleAlias(Generic[_T, _U]): ... From 262b6704918bf6aec5b4f873f69feaed0cef6d67 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 6 Apr 2022 11:56:33 +0100 Subject: [PATCH 2/4] Sync typeshed Source commit: https://github.com/python/typeshed/commit/3c85f36b7f9afd599409d10a214aafdecf38251e --- .../typeshed/stdlib/@python2/SocketServer.pyi | 2 +- mypy/typeshed/stdlib/@python2/__builtin__.pyi | 27 +-- mypy/typeshed/stdlib/@python2/_codecs.pyi | 12 +- mypy/typeshed/stdlib/@python2/_curses.pyi | 4 +- .../stdlib/@python2/_dummy_threading.pyi | 4 +- mypy/typeshed/stdlib/@python2/_io.pyi | 4 +- mypy/typeshed/stdlib/@python2/_msi.pyi | 16 +- .../stdlib/@python2/_typeshed/__init__.pyi | 14 +- .../stdlib/@python2/_typeshed/wsgi.pyi | 2 +- mypy/typeshed/stdlib/@python2/_winreg.pyi | 4 +- mypy/typeshed/stdlib/@python2/aifc.pyi | 4 +- mypy/typeshed/stdlib/@python2/argparse.pyi | 8 +- mypy/typeshed/stdlib/@python2/array.pyi | 8 +- mypy/typeshed/stdlib/@python2/asyncore.pyi | 2 +- mypy/typeshed/stdlib/@python2/base64.pyi | 6 +- mypy/typeshed/stdlib/@python2/binhex.pyi | 4 +- mypy/typeshed/stdlib/@python2/builtins.pyi | 27 +-- mypy/typeshed/stdlib/@python2/bz2.pyi | 6 +- mypy/typeshed/stdlib/@python2/calendar.pyi | 4 +- mypy/typeshed/stdlib/@python2/cmath.pyi | 4 +- mypy/typeshed/stdlib/@python2/codecs.pyi | 8 +- mypy/typeshed/stdlib/@python2/contextlib.pyi | 4 +- mypy/typeshed/stdlib/@python2/copy_reg.pyi | 4 +- mypy/typeshed/stdlib/@python2/copyreg.pyi | 4 +- .../stdlib/@python2/ctypes/__init__.pyi | 41 ++-- mypy/typeshed/stdlib/@python2/datetime.pyi | 14 +- .../typeshed/stdlib/@python2/dbm/__init__.pyi | 6 +- mypy/typeshed/stdlib/@python2/dbm/dumb.pyi | 6 +- mypy/typeshed/stdlib/@python2/dbm/gnu.pyi | 10 +- mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi | 10 +- mypy/typeshed/stdlib/@python2/decimal.pyi | 4 +- mypy/typeshed/stdlib/@python2/difflib.pyi | 8 +- mypy/typeshed/stdlib/@python2/dis.pyi | 6 +- .../stdlib/@python2/distutils/ccompiler.pyi | 4 +- .../@python2/distutils/fancy_getopt.pyi | 4 +- .../stdlib/@python2/distutils/version.pyi | 4 +- .../@python2/email/mime/application.pyi | 4 +- mypy/typeshed/stdlib/@python2/fnmatch.pyi | 4 +- mypy/typeshed/stdlib/@python2/fractions.pyi | 4 +- mypy/typeshed/stdlib/@python2/ftplib.pyi | 4 +- mypy/typeshed/stdlib/@python2/genericpath.pyi | 6 +- mypy/typeshed/stdlib/@python2/hashlib.pyi | 4 +- mypy/typeshed/stdlib/@python2/hmac.pyi | 4 +- mypy/typeshed/stdlib/@python2/imaplib.pyi | 4 +- mypy/typeshed/stdlib/@python2/imghdr.pyi | 4 +- mypy/typeshed/stdlib/@python2/inspect.pyi | 6 +- .../stdlib/@python2/lib2to3/pgen2/grammar.pyi | 4 +- .../stdlib/@python2/lib2to3/pytree.pyi | 6 +- .../stdlib/@python2/logging/__init__.pyi | 10 +- .../stdlib/@python2/logging/handlers.pyi | 2 +- mypy/typeshed/stdlib/@python2/mailbox.pyi | 19 +- mypy/typeshed/stdlib/@python2/mailcap.pyi | 4 +- .../stdlib/@python2/msilib/sequence.pyi | 3 +- mypy/typeshed/stdlib/@python2/netrc.pyi | 4 +- mypy/typeshed/stdlib/@python2/nntplib.pyi | 4 +- mypy/typeshed/stdlib/@python2/optparse.pyi | 4 +- mypy/typeshed/stdlib/@python2/os/__init__.pyi | 3 +- mypy/typeshed/stdlib/@python2/pickle.pyi | 6 +- mypy/typeshed/stdlib/@python2/pkgutil.pyi | 7 +- mypy/typeshed/stdlib/@python2/plistlib.pyi | 4 +- mypy/typeshed/stdlib/@python2/pstats.pyi | 4 +- mypy/typeshed/stdlib/@python2/py_compile.pyi | 4 +- .../stdlib/@python2/pyexpat/__init__.pyi | 4 +- mypy/typeshed/stdlib/@python2/readline.pyi | 4 +- mypy/typeshed/stdlib/@python2/rlcompleter.pyi | 4 +- mypy/typeshed/stdlib/@python2/sets.pyi | 4 +- mypy/typeshed/stdlib/@python2/shutil.pyi | 4 +- mypy/typeshed/stdlib/@python2/signal.pyi | 4 +- mypy/typeshed/stdlib/@python2/smtpd.pyi | 11 +- mypy/typeshed/stdlib/@python2/sndhdr.pyi | 4 +- mypy/typeshed/stdlib/@python2/socket.pyi | 6 +- mypy/typeshed/stdlib/@python2/sre_parse.pyi | 10 +- mypy/typeshed/stdlib/@python2/ssl.pyi | 10 +- mypy/typeshed/stdlib/@python2/struct.pyi | 8 +- mypy/typeshed/stdlib/@python2/subprocess.pyi | 10 +- mypy/typeshed/stdlib/@python2/sunau.pyi | 4 +- mypy/typeshed/stdlib/@python2/termios.pyi | 4 +- mypy/typeshed/stdlib/@python2/threading.pyi | 4 +- mypy/typeshed/stdlib/@python2/timeit.pyi | 6 +- mypy/typeshed/stdlib/@python2/trace.pyi | 4 +- mypy/typeshed/stdlib/@python2/traceback.pyi | 4 +- mypy/typeshed/stdlib/@python2/tty.pyi | 4 +- mypy/typeshed/stdlib/@python2/turtle.pyi | 10 +- .../stdlib/@python2/typing_extensions.pyi | 5 +- mypy/typeshed/stdlib/@python2/unittest.pyi | 2 +- mypy/typeshed/stdlib/@python2/urllib2.pyi | 4 +- mypy/typeshed/stdlib/@python2/urlparse.pyi | 4 +- mypy/typeshed/stdlib/@python2/uu.pyi | 4 +- mypy/typeshed/stdlib/@python2/wave.pyi | 4 +- mypy/typeshed/stdlib/@python2/weakref.pyi | 2 +- .../stdlib/@python2/xml/dom/minicompat.pyi | 2 +- .../stdlib/@python2/xml/dom/xmlbuilder.pyi | 4 +- .../stdlib/@python2/xml/etree/ElementTree.pyi | 7 +- mypy/typeshed/stdlib/@python2/xmlrpclib.pyi | 6 +- mypy/typeshed/stdlib/@python2/zipfile.pyi | 8 +- mypy/typeshed/stdlib/_ast.pyi | 134 ++++++++++++++ mypy/typeshed/stdlib/_codecs.pyi | 4 +- mypy/typeshed/stdlib/_curses.pyi | 4 +- mypy/typeshed/stdlib/_dummy_thread.pyi | 3 +- mypy/typeshed/stdlib/_dummy_threading.pyi | 16 +- mypy/typeshed/stdlib/_imp.pyi | 2 +- mypy/typeshed/stdlib/_socket.pyi | 4 +- mypy/typeshed/stdlib/_thread.pyi | 10 +- mypy/typeshed/stdlib/_tkinter.pyi | 4 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 47 +++-- mypy/typeshed/stdlib/_typeshed/dbapi.pyi | 5 +- mypy/typeshed/stdlib/_typeshed/wsgi.pyi | 5 +- mypy/typeshed/stdlib/aifc.pyi | 4 +- mypy/typeshed/stdlib/array.pyi | 4 +- mypy/typeshed/stdlib/asyncio/base_events.pyi | 16 +- .../stdlib/asyncio/base_subprocess.pyi | 4 +- mypy/typeshed/stdlib/asyncio/events.pyi | 15 +- .../stdlib/asyncio/format_helpers.pyi | 4 +- mypy/typeshed/stdlib/asyncio/locks.pyi | 2 +- mypy/typeshed/stdlib/asyncio/streams.pyi | 6 +- mypy/typeshed/stdlib/asyncio/subprocess.pyi | 4 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 6 +- mypy/typeshed/stdlib/asyncio/trsock.pyi | 6 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 2 +- .../typeshed/stdlib/asyncio/windows_utils.pyi | 2 +- mypy/typeshed/stdlib/binhex.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 50 +++-- mypy/typeshed/stdlib/cProfile.pyi | 2 +- mypy/typeshed/stdlib/calendar.pyi | 6 +- mypy/typeshed/stdlib/cgi.pyi | 2 +- mypy/typeshed/stdlib/cgitb.pyi | 4 +- mypy/typeshed/stdlib/cmath.pyi | 6 +- .../stdlib/concurrent/futures/_base.pyi | 9 +- mypy/typeshed/stdlib/configparser.pyi | 4 +- mypy/typeshed/stdlib/contextlib.pyi | 19 +- mypy/typeshed/stdlib/copyreg.pyi | 4 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 27 +-- mypy/typeshed/stdlib/dataclasses.pyi | 26 +-- mypy/typeshed/stdlib/datetime.pyi | 82 +++++--- mypy/typeshed/stdlib/dbm/__init__.pyi | 6 +- mypy/typeshed/stdlib/dbm/dumb.pyi | 6 +- mypy/typeshed/stdlib/dbm/gnu.pyi | 6 +- mypy/typeshed/stdlib/dbm/ndbm.pyi | 6 +- mypy/typeshed/stdlib/decimal.pyi | 4 +- mypy/typeshed/stdlib/dis.pyi | 6 +- mypy/typeshed/stdlib/distutils/ccompiler.pyi | 4 +- .../stdlib/distutils/fancy_getopt.pyi | 4 +- mypy/typeshed/stdlib/distutils/version.pyi | 4 +- mypy/typeshed/stdlib/email/__init__.pyi | 7 +- .../stdlib/email/_header_value_parser.pyi | 4 +- mypy/typeshed/stdlib/email/feedparser.pyi | 17 +- mypy/typeshed/stdlib/email/message.pyi | 10 +- .../stdlib/email/mime/application.pyi | 5 +- mypy/typeshed/stdlib/email/mime/audio.pyi | 5 +- mypy/typeshed/stdlib/email/mime/base.pyi | 4 +- mypy/typeshed/stdlib/email/mime/image.pyi | 5 +- mypy/typeshed/stdlib/email/mime/multipart.pyi | 5 +- mypy/typeshed/stdlib/email/parser.pyi | 9 +- mypy/typeshed/stdlib/email/utils.pyi | 6 +- mypy/typeshed/stdlib/enum.pyi | 14 +- mypy/typeshed/stdlib/errno.pyi | 22 ++- mypy/typeshed/stdlib/fileinput.pyi | 5 +- mypy/typeshed/stdlib/fractions.pyi | 4 +- mypy/typeshed/stdlib/grp.pyi | 8 +- mypy/typeshed/stdlib/hmac.pyi | 4 +- mypy/typeshed/stdlib/http/client.pyi | 8 +- mypy/typeshed/stdlib/http/cookies.pyi | 4 +- mypy/typeshed/stdlib/imaplib.pyi | 4 +- mypy/typeshed/stdlib/imp.pyi | 3 +- mypy/typeshed/stdlib/importlib/abc.pyi | 4 +- mypy/typeshed/stdlib/importlib/machinery.pyi | 4 +- mypy/typeshed/stdlib/importlib/resources.pyi | 6 +- mypy/typeshed/stdlib/io.pyi | 12 +- mypy/typeshed/stdlib/itertools.pyi | 16 +- .../typeshed/stdlib/lib2to3/pgen2/grammar.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/pytree.pyi | 6 +- mypy/typeshed/stdlib/locale.pyi | 6 +- mypy/typeshed/stdlib/logging/__init__.pyi | 12 +- mypy/typeshed/stdlib/logging/handlers.pyi | 6 +- mypy/typeshed/stdlib/lzma.pyi | 4 +- mypy/typeshed/stdlib/mailbox.pyi | 4 +- mypy/typeshed/stdlib/mailcap.pyi | 4 +- mypy/typeshed/stdlib/math.pyi | 4 +- mypy/typeshed/stdlib/msilib/sequence.pyi | 3 +- .../stdlib/multiprocessing/__init__.pyi | 4 +- .../stdlib/multiprocessing/context.pyi | 4 +- .../stdlib/multiprocessing/managers.pyi | 4 +- .../stdlib/multiprocessing/process.pyi | 5 +- .../stdlib/multiprocessing/sharedctypes.pyi | 5 +- .../stdlib/multiprocessing/synchronize.pyi | 4 +- mypy/typeshed/stdlib/netrc.pyi | 3 +- mypy/typeshed/stdlib/nntplib.pyi | 6 +- mypy/typeshed/stdlib/os/__init__.pyi | 69 ++++--- mypy/typeshed/stdlib/pickle.pyi | 8 +- mypy/typeshed/stdlib/pkgutil.pyi | 6 +- mypy/typeshed/stdlib/pstats.pyi | 4 +- mypy/typeshed/stdlib/pwd.pyi | 4 +- mypy/typeshed/stdlib/pyexpat/__init__.pyi | 4 +- mypy/typeshed/stdlib/random.pyi | 6 +- mypy/typeshed/stdlib/re.pyi | 4 +- mypy/typeshed/stdlib/resource.pyi | 21 ++- mypy/typeshed/stdlib/runpy.pyi | 4 +- mypy/typeshed/stdlib/selectors.pyi | 2 +- mypy/typeshed/stdlib/shutil.pyi | 4 +- mypy/typeshed/stdlib/signal.pyi | 10 +- mypy/typeshed/stdlib/smtplib.pyi | 4 +- mypy/typeshed/stdlib/socket.pyi | 7 +- mypy/typeshed/stdlib/spwd.pyi | 14 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 5 +- mypy/typeshed/stdlib/sre_parse.pyi | 10 +- mypy/typeshed/stdlib/ssl.pyi | 12 +- mypy/typeshed/stdlib/statistics.pyi | 4 +- mypy/typeshed/stdlib/subprocess.pyi | 12 +- mypy/typeshed/stdlib/sunau.pyi | 8 +- mypy/typeshed/stdlib/sys.pyi | 19 +- mypy/typeshed/stdlib/telnetlib.pyi | 5 +- mypy/typeshed/stdlib/tempfile.pyi | 6 +- mypy/typeshed/stdlib/termios.pyi | 4 +- mypy/typeshed/stdlib/threading.pyi | 4 +- mypy/typeshed/stdlib/time.pyi | 8 +- mypy/typeshed/stdlib/timeit.pyi | 4 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 26 +-- mypy/typeshed/stdlib/tkinter/font.pyi | 20 +- mypy/typeshed/stdlib/tkinter/ttk.pyi | 4 +- mypy/typeshed/stdlib/tokenize.pyi | 4 +- mypy/typeshed/stdlib/trace.pyi | 4 +- mypy/typeshed/stdlib/traceback.pyi | 4 +- mypy/typeshed/stdlib/tracemalloc.pyi | 4 +- mypy/typeshed/stdlib/tty.pyi | 4 +- mypy/typeshed/stdlib/turtle.pyi | 2 +- mypy/typeshed/stdlib/types.pyi | 12 +- mypy/typeshed/stdlib/typing.pyi | 60 +++--- mypy/typeshed/stdlib/typing_extensions.pyi | 2 +- mypy/typeshed/stdlib/unittest/mock.pyi | 175 +++++++----------- mypy/typeshed/stdlib/unittest/suite.pyi | 4 +- mypy/typeshed/stdlib/urllib/parse.pyi | 6 +- mypy/typeshed/stdlib/uu.pyi | 4 +- mypy/typeshed/stdlib/wave.pyi | 8 +- mypy/typeshed/stdlib/winreg.pyi | 4 +- mypy/typeshed/stdlib/wsgiref/handlers.pyi | 4 +- mypy/typeshed/stdlib/xml/dom/pulldom.pyi | 6 +- mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi | 10 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 7 +- mypy/typeshed/stdlib/xmlrpc/client.pyi | 8 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 6 +- mypy/typeshed/stdlib/zipapp.pyi | 4 +- 241 files changed, 1174 insertions(+), 982 deletions(-) diff --git a/mypy/typeshed/stdlib/@python2/SocketServer.pyi b/mypy/typeshed/stdlib/@python2/SocketServer.pyi index 7c72675e677c..545ee8464f16 100644 --- a/mypy/typeshed/stdlib/@python2/SocketServer.pyi +++ b/mypy/typeshed/stdlib/@python2/SocketServer.pyi @@ -1,6 +1,6 @@ import sys from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, Text, Union +from typing import Any, BinaryIO, Callable, ClassVar, Text class BaseServer: address_family: int diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index b6ac2b78aca8..d936e08b8266 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -12,6 +12,7 @@ from typing import ( BinaryIO, ByteString, Callable, + ClassVar, Container, Generic, ItemsView, @@ -69,8 +70,8 @@ class object: def __setattr__(self, name: str, value: Any) -> None: ... def __eq__(self, o: object) -> bool: ... def __ne__(self, o: object) -> bool: ... - def __str__(self) -> str: ... # noqa Y029 - def __repr__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 def __hash__(self) -> int: ... def __format__(self, format_spec: str) -> str: ... def __getattribute__(self, name: str) -> Any: ... @@ -336,7 +337,7 @@ class unicode(basestring, Sequence[unicode]): def __ge__(self, x: unicode) -> bool: ... def __len__(self) -> int: ... # The argument type is incompatible with Sequence - def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore + def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore[override] def __iter__(self) -> Iterator[unicode]: ... def __int__(self) -> int: ... def __float__(self) -> float: ... @@ -414,7 +415,7 @@ class str(Sequence[str], basestring): def zfill(self, __width: int) -> str: ... def __add__(self, s: AnyStr) -> AnyStr: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: str | Text) -> bool: ... # type: ignore + def __contains__(self, o: str | Text) -> bool: ... # type: ignore[override] def __eq__(self, x: object) -> bool: ... def __ge__(self, x: Text) -> bool: ... def __getitem__(self, i: int | slice) -> str: ... @@ -490,7 +491,7 @@ class bytearray(MutableSequence[int], ByteString): def __iter__(self) -> Iterator[int]: ... def __int__(self) -> int: ... def __float__(self) -> float: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, i: int) -> int: ... @overload @@ -506,7 +507,7 @@ class bytearray(MutableSequence[int], ByteString): def __add__(self, s: bytes) -> bytearray: ... def __mul__(self, n: int) -> bytearray: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: int | bytes) -> bool: ... # type: ignore + def __contains__(self, o: int | bytes) -> bool: ... # type: ignore[override] def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: bytes) -> bool: ... @@ -574,7 +575,7 @@ class slice(object): def __init__(self, stop: Any) -> None: ... @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] def indices(self, len: int) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): @@ -621,7 +622,7 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, i: int) -> _T: ... @overload @@ -683,7 +684,7 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... @@ -725,7 +726,7 @@ class set(MutableSet[_T], Generic[_T]): 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 + __hash__: ClassVar[None] # type: ignore[assignment] class frozenset(AbstractSet[_T_co], Generic[_T_co]): def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... @@ -784,10 +785,10 @@ class property(object): long = int -class _NotImplementedType(Any): # type: ignore +class _NotImplementedType(Any): # type: ignore[misc] # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better - __call__: NotImplemented # type: ignore + __call__: NotImplemented # type: ignore[valid-type] NotImplemented: _NotImplementedType @@ -964,7 +965,7 @@ 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 range(__x: int, __y: int = ..., __step: int = ...) -> list[int]: ... def raw_input(__prompt: Any = ...) -> str: ... @overload def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/_codecs.pyi b/mypy/typeshed/stdlib/@python2/_codecs.pyi index fa6922207c25..1028cfec1aef 100644 --- a/mypy/typeshed/stdlib/@python2/_codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/_codecs.pyi @@ -1,19 +1,19 @@ import codecs import sys -from typing import Any, Callable, Text, Union +from typing import Any, Callable, Text # For convenience: _Handler = Callable[[Exception], tuple[Text, int]] -_String = Union[bytes, str] -_Errors = Union[str, Text, None] -_Decodable = Union[bytes, Text] -_Encodable = Union[bytes, Text] +_String = bytes | str +_Errors = str | Text | None +_Decodable = bytes | Text +_Encodable = bytes | Text # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap(object): def size(self) -> int: ... -_MapT = Union[dict[int, int], _EncodingMap] +_MapT = dict[int, int] | _EncodingMap def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str | Text, __handler: _Handler) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_curses.pyi b/mypy/typeshed/stdlib/@python2/_curses.pyi index 4b2941e74753..81de0ea96e3f 100644 --- a/mypy/typeshed/stdlib/@python2/_curses.pyi +++ b/mypy/typeshed/stdlib/@python2/_curses.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, BinaryIO, Union, overload +from typing import IO, Any, BinaryIO, overload -_chtype = Union[str, bytes, int] +_chtype = str | bytes | int # ACS codes are only initialized after initscr is called ACS_BBSS: int diff --git a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi index c03c52a7907c..e7b0a9e4b363 100644 --- a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi @@ -1,8 +1,8 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Text +from typing import Any, Callable, Iterable, Mapping, Text # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi index 3671bbd2177d..65c59ccf7715 100644 --- a/mypy/typeshed/stdlib/@python2/_io.pyi +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -1,8 +1,8 @@ from _typeshed import Self from mmap import mmap -from typing import IO, Any, BinaryIO, Iterable, Text, TextIO, Union +from typing import IO, Any, BinaryIO, Iterable, Text, TextIO -_bytearray_like = Union[bytearray, mmap] +_bytearray_like = bytearray | mmap DEFAULT_BUFFER_SIZE: int diff --git a/mypy/typeshed/stdlib/@python2/_msi.pyi b/mypy/typeshed/stdlib/@python2/_msi.pyi index 754febe68da9..b7e852f38ae9 100644 --- a/mypy/typeshed/stdlib/@python2/_msi.pyi +++ b/mypy/typeshed/stdlib/@python2/_msi.pyi @@ -10,8 +10,8 @@ if sys.platform == "win32": 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 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Summary, not exposed by the implementation class _Summary: def GetProperty(self, propid: int) -> str | bytes | None: ... @@ -19,8 +19,8 @@ if sys.platform == "win32": def SetProperty(self, propid: int, value: str | bytes) -> None: ... def Persist(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Database, not exposed by the implementation class _Database: def OpenView(self, sql: str) -> _View: ... @@ -28,8 +28,8 @@ if sys.platform == "win32": def GetSummaryInformation(self, updateCount: int) -> _Summary: ... def Close(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Record, not exposed by the implementation class _Record: def GetFieldCount(self) -> int: ... @@ -40,8 +40,8 @@ if sys.platform == "win32": 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 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def UuidCreate() -> str: ... def FCICreate(cabname: str, files: list[str]) -> None: ... def OpenDatabase(name: str, flags: int) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi index 0d1dc3866b56..657164f81f6d 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi @@ -14,7 +14,7 @@ import array import mmap -from typing import Any, Container, Iterable, Protocol, Text, TypeVar, Union +from typing import Any, Container, Iterable, Protocol, Text, TypeVar from typing_extensions import Literal, final _KT = TypeVar("_KT") @@ -28,7 +28,7 @@ _T_contra = TypeVar("_T_contra", contravariant=True) # Use for "self" annotations: # def __enter__(self: Self) -> Self: ... -Self = TypeVar("Self") # noqa Y001 +Self = TypeVar("Self") # noqa: Y001 class IdentityFunction(Protocol): def __call__(self, __x: _T) -> _T: ... @@ -104,7 +104,7 @@ OpenTextModeUpdating = Literal[ ] OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] +OpenTextMode = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading OpenBinaryModeUpdating = Literal[ "rb+", "r+b", @@ -133,13 +133,13 @@ OpenBinaryModeUpdating = Literal[ ] OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] -OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] +OpenBinaryMode = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting class HasFileno(Protocol): def fileno(self) -> int: ... FileDescriptor = int -FileDescriptorLike = Union[int, HasFileno] +FileDescriptorLike = int | HasFileno class SupportsRead(Protocol[_T_co]): def read(self, __length: int = ...) -> _T_co: ... @@ -153,8 +153,8 @@ class SupportsNoArgReadline(Protocol[_T_co]): class SupportsWrite(Protocol[_T_contra]): def write(self, __s: _T_contra) -> Any: ... -ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] +ReadableBuffer = bytes | bytearray | memoryview | array.array[Any] | mmap.mmap | buffer +WriteableBuffer = bytearray | memoryview | array.array[Any] | mmap.mmap | buffer # Used by type checkers for checks involving None (does not exist at runtime) @final diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi index 6dc2b5cc021d..4380949c9c1c 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi @@ -4,7 +4,7 @@ # file. They are provided for type checking purposes. from sys import _OptExcInfo -from typing import Any, Callable, Iterable, Optional, Protocol, Text +from typing import Any, Callable, Iterable, Protocol, Text class StartResponse(Protocol): def __call__( diff --git a/mypy/typeshed/stdlib/@python2/_winreg.pyi b/mypy/typeshed/stdlib/@python2/_winreg.pyi index e432d883e4d5..395024fcc2fd 100644 --- a/mypy/typeshed/stdlib/@python2/_winreg.pyi +++ b/mypy/typeshed/stdlib/@python2/_winreg.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import Self from types import TracebackType -from typing import Any, Union +from typing import Any if sys.platform == "win32": - _KeyType = Union[HKEYType, int] + _KeyType = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... diff --git a/mypy/typeshed/stdlib/@python2/aifc.pyi b/mypy/typeshed/stdlib/@python2/aifc.pyi index b8049e857304..766ccde956f9 100644 --- a/mypy/typeshed/stdlib/@python2/aifc.pyi +++ b/mypy/typeshed/stdlib/@python2/aifc.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, NamedTuple, Text, Union, overload +from typing import IO, Any, NamedTuple, Text, overload from typing_extensions import Literal class Error(Exception): ... @@ -11,7 +11,7 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] _Marker = tuple[int, int, bytes] class Aifc_read: diff --git a/mypy/typeshed/stdlib/@python2/argparse.pyi b/mypy/typeshed/stdlib/@python2/argparse.pyi index e82a8c621e40..a9a57ea0ea55 100644 --- a/mypy/typeshed/stdlib/@python2/argparse.pyi +++ b/mypy/typeshed/stdlib/@python2/argparse.pyi @@ -1,10 +1,10 @@ -from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, Union, overload +from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, overload _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _N = TypeVar("_N") -_Text = Union[str, unicode] +_Text = str | unicode ONE_OR_MORE: str OPTIONAL: str @@ -107,11 +107,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): @overload def parse_args(self, args: Sequence[Text] | None = ...) -> Namespace: ... @overload - def parse_args(self, args: Sequence[Text] | None, namespace: None) -> Namespace: ... # type: ignore + def parse_args(self, args: Sequence[Text] | None, namespace: None) -> Namespace: ... # type: ignore[misc] @overload def parse_args(self, args: Sequence[Text] | None, namespace: _N) -> _N: ... @overload - def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore + def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore[misc] @overload def parse_args(self, *, namespace: _N) -> _N: ... def add_subparsers( diff --git a/mypy/typeshed/stdlib/@python2/array.pyi b/mypy/typeshed/stdlib/@python2/array.pyi index 1ef8c3a7c8c3..a47b845d1933 100644 --- a/mypy/typeshed/stdlib/@python2/array.pyi +++ b/mypy/typeshed/stdlib/@python2/array.pyi @@ -1,11 +1,11 @@ from _typeshed import Self -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, overload from typing_extensions import Literal _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _FloatTypeCode = Literal["f", "d"] _UnicodeTypeCode = Literal["u"] -_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] +_TypeCode = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, Text) @@ -28,7 +28,7 @@ class array(MutableSequence[_T], Generic[_T]): 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 index(self, __v: _T) -> int: ... # Overrides Sequence def insert(self, __i: int, __v: _T) -> None: ... def pop(self, __i: int = ...) -> _T: ... def read(self, f: BinaryIO, n: int) -> None: ... @@ -45,7 +45,7 @@ class array(MutableSequence[_T], Generic[_T]): def __getitem__(self, i: int) -> _T: ... @overload def __getitem__(self, s: slice) -> array[_T]: ... - @overload # type: ignore # Overrides MutableSequence + @overload # type: ignore[override] def __setitem__(self, i: int, o: _T) -> None: ... @overload def __setitem__(self, s: slice, o: array[_T]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/asyncore.pyi b/mypy/typeshed/stdlib/@python2/asyncore.pyi index 1daa1aac87a7..a9f07613bb9c 100644 --- a/mypy/typeshed/stdlib/@python2/asyncore.pyi +++ b/mypy/typeshed/stdlib/@python2/asyncore.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import FileDescriptorLike from socket import SocketType -from typing import Any, Optional, overload +from typing import Any, overload # cyclic dependence with asynchat _maptype = dict[int, Any] diff --git a/mypy/typeshed/stdlib/@python2/base64.pyi b/mypy/typeshed/stdlib/@python2/base64.pyi index 00856aafddbe..4a32006ea98b 100644 --- a/mypy/typeshed/stdlib/@python2/base64.pyi +++ b/mypy/typeshed/stdlib/@python2/base64.pyi @@ -1,7 +1,7 @@ -from typing import IO, Union +from typing import IO -_encodable = Union[bytes, unicode] -_decodable = Union[bytes, unicode] +_encodable = bytes | unicode +_decodable = bytes | unicode def b64encode(s: _encodable, altchars: bytes | None = ...) -> bytes: ... def b64decode(s: _decodable, altchars: bytes | None = ..., validate: bool = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/binhex.pyi b/mypy/typeshed/stdlib/@python2/binhex.pyi index 4e295b8ed903..10a5a3ee5633 100644 --- a/mypy/typeshed/stdlib/@python2/binhex.pyi +++ b/mypy/typeshed/stdlib/@python2/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Union +from typing import IO, Any class Error(Exception): ... @@ -13,7 +13,7 @@ class FInfo: Flags: int _FileInfoTuple = tuple[str, FInfo, int, int] -_FileHandleUnion = Union[str, IO[bytes]] +_FileHandleUnion = str | IO[bytes] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index b6ac2b78aca8..d936e08b8266 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -12,6 +12,7 @@ from typing import ( BinaryIO, ByteString, Callable, + ClassVar, Container, Generic, ItemsView, @@ -69,8 +70,8 @@ class object: def __setattr__(self, name: str, value: Any) -> None: ... def __eq__(self, o: object) -> bool: ... def __ne__(self, o: object) -> bool: ... - def __str__(self) -> str: ... # noqa Y029 - def __repr__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 def __hash__(self) -> int: ... def __format__(self, format_spec: str) -> str: ... def __getattribute__(self, name: str) -> Any: ... @@ -336,7 +337,7 @@ class unicode(basestring, Sequence[unicode]): def __ge__(self, x: unicode) -> bool: ... def __len__(self) -> int: ... # The argument type is incompatible with Sequence - def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore + def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore[override] def __iter__(self) -> Iterator[unicode]: ... def __int__(self) -> int: ... def __float__(self) -> float: ... @@ -414,7 +415,7 @@ class str(Sequence[str], basestring): def zfill(self, __width: int) -> str: ... def __add__(self, s: AnyStr) -> AnyStr: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: str | Text) -> bool: ... # type: ignore + def __contains__(self, o: str | Text) -> bool: ... # type: ignore[override] def __eq__(self, x: object) -> bool: ... def __ge__(self, x: Text) -> bool: ... def __getitem__(self, i: int | slice) -> str: ... @@ -490,7 +491,7 @@ class bytearray(MutableSequence[int], ByteString): def __iter__(self) -> Iterator[int]: ... def __int__(self) -> int: ... def __float__(self) -> float: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, i: int) -> int: ... @overload @@ -506,7 +507,7 @@ class bytearray(MutableSequence[int], ByteString): def __add__(self, s: bytes) -> bytearray: ... def __mul__(self, n: int) -> bytearray: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: int | bytes) -> bool: ... # type: ignore + def __contains__(self, o: int | bytes) -> bool: ... # type: ignore[override] def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: bytes) -> bool: ... @@ -574,7 +575,7 @@ class slice(object): def __init__(self, stop: Any) -> None: ... @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] def indices(self, len: int) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): @@ -621,7 +622,7 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, i: int) -> _T: ... @overload @@ -683,7 +684,7 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... - __hash__: None # type: ignore + __hash__: ClassVar[None] # type: ignore[assignment] class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... @@ -725,7 +726,7 @@ class set(MutableSet[_T], Generic[_T]): 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 + __hash__: ClassVar[None] # type: ignore[assignment] class frozenset(AbstractSet[_T_co], Generic[_T_co]): def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... @@ -784,10 +785,10 @@ class property(object): long = int -class _NotImplementedType(Any): # type: ignore +class _NotImplementedType(Any): # type: ignore[misc] # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better - __call__: NotImplemented # type: ignore + __call__: NotImplemented # type: ignore[valid-type] NotImplemented: _NotImplementedType @@ -964,7 +965,7 @@ 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 range(__x: int, __y: int = ..., __step: int = ...) -> list[int]: ... def raw_input(__prompt: Any = ...) -> str: ... @overload def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/bz2.pyi b/mypy/typeshed/stdlib/@python2/bz2.pyi index bec8994dbe29..95377347cce8 100644 --- a/mypy/typeshed/stdlib/@python2/bz2.pyi +++ b/mypy/typeshed/stdlib/@python2/bz2.pyi @@ -1,9 +1,9 @@ import io from _typeshed import ReadableBuffer, Self, WriteableBuffer -from typing import IO, Any, Iterable, Text, Union +from typing import IO, Any, Iterable, Text from typing_extensions import SupportsIndex -_PathOrFile = Union[Text, IO[bytes]] +_PathOrFile = Text | IO[bytes] def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... @@ -13,7 +13,7 @@ class BZ2File(io.BufferedIOBase, IO[bytes]): def __init__(self, filename: _PathOrFile, mode: str = ..., buffering: Any | None = ..., compresslevel: int = ...) -> None: ... def read(self, size: int | None = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... - def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore + def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore[override] def readinto(self, b: WriteableBuffer) -> int: ... def readlines(self, size: SupportsIndex = ...) -> list[bytes]: ... def seek(self, offset: int, whence: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/calendar.pyi b/mypy/typeshed/stdlib/@python2/calendar.pyi index f21e6406a5c5..f14b0735fa67 100644 --- a/mypy/typeshed/stdlib/@python2/calendar.pyi +++ b/mypy/typeshed/stdlib/@python2/calendar.pyi @@ -1,8 +1,8 @@ import datetime from time import struct_time -from typing import Any, Iterable, Optional, Sequence +from typing import Any, Iterable, Sequence -_LocaleType = tuple[Optional[str], Optional[str]] +_LocaleType = tuple[str | None, str | None] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cmath.pyi b/mypy/typeshed/stdlib/@python2/cmath.pyi index ef54d7f43854..1053b2269812 100644 --- a/mypy/typeshed/stdlib/@python2/cmath.pyi +++ b/mypy/typeshed/stdlib/@python2/cmath.pyi @@ -1,8 +1,8 @@ -from typing import SupportsComplex, SupportsFloat, Union +from typing import SupportsComplex, SupportsFloat e: float pi: float -_C = Union[SupportsFloat, SupportsComplex, complex] +_C = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/@python2/codecs.pyi b/mypy/typeshed/stdlib/@python2/codecs.pyi index 2780d473b781..9ed83567c148 100644 --- a/mypy/typeshed/stdlib/@python2/codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/codecs.pyi @@ -1,7 +1,7 @@ import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, Union, overload +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, overload from typing_extensions import Literal # TODO: this only satisfies the most common interface, where @@ -55,11 +55,11 @@ _BytesToBytesEncodingT = Literal[ @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 +def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... @overload def encode(obj: _Decoded, encoding: str = ..., errors: str = ...) -> _Encoded: ... @overload -def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore +def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore[misc] @overload def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> Text: ... @overload @@ -243,7 +243,7 @@ class StreamRecoder(BinaryIO): def next(self) -> bytes: ... def __iter__(self: Self) -> Self: ... def write(self, data: bytes) -> int: ... - def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None + def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore[override] # it's supposed to return None def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... def __enter__(self: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/@python2/contextlib.pyi b/mypy/typeshed/stdlib/@python2/contextlib.pyi index 8e68238fc6e2..4f39ba5dad5e 100644 --- a/mypy/typeshed/stdlib/@python2/contextlib.pyi +++ b/mypy/typeshed/stdlib/@python2/contextlib.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, TypeVar +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Protocol, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") @@ -7,7 +7,7 @@ _T_co = TypeVar("_T_co", covariant=True) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] +_ExitFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool] class GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... diff --git a/mypy/typeshed/stdlib/@python2/copy_reg.pyi b/mypy/typeshed/stdlib/@python2/copy_reg.pyi index 5aec88298ab3..2fccfcbf2208 100644 --- a/mypy/typeshed/stdlib/@python2/copy_reg.pyi +++ b/mypy/typeshed/stdlib/@python2/copy_reg.pyi @@ -1,7 +1,7 @@ -from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union +from typing import Any, Callable, Hashable, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Any | None]] __all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] diff --git a/mypy/typeshed/stdlib/@python2/copyreg.pyi b/mypy/typeshed/stdlib/@python2/copyreg.pyi index 5aec88298ab3..2fccfcbf2208 100644 --- a/mypy/typeshed/stdlib/@python2/copyreg.pyi +++ b/mypy/typeshed/stdlib/@python2/copyreg.pyi @@ -1,7 +1,7 @@ -from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union +from typing import Any, Callable, Hashable, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Any | None]] __all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] diff --git a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi index 9fab35ebd022..18d5cbc77e94 100644 --- a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi @@ -9,7 +9,6 @@ from typing import ( Iterable, Iterator, Mapping, - Optional, Sequence, Text, TypeVar, @@ -59,16 +58,16 @@ pythonapi: PyDLL # Anything that implements the read-write buffer interface. # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol # for it. Instead we have to list the most common stdlib buffer classes in a Union. -_WritableBuffer = _UnionT[bytearray, memoryview, array[Any], _CData] +_WritableBuffer = bytearray | memoryview | array[Any] | _CData # Same as _WritableBuffer, but also includes read-only buffer types (like bytes). -_ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] +_ReadOnlyBuffer = _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 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] class _CData(metaclass=_CDataMeta): _b_base: int = ... @@ -81,18 +80,18 @@ class _CData(metaclass=_CDataMeta): @classmethod def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + def from_param(cls: type[_CT], obj: Any) -> _CT | _CArgObject: ... @classmethod def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CData] +_ECT = Callable[[type[_CData] | None, _FuncPointer, tuple[_CData, ...]], _CData] _PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[type[_CData], Callable[[int], Any], None] = ... + restype: type[_CData] | Callable[[int], Any] | None = ... argtypes: Sequence[type[_CData]] = ... errcheck: _ECT = ... @overload @@ -125,25 +124,25 @@ 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] +_CVoidPLike = _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] +_CVoidConstPLike = _CVoidPLike | bytes def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... +def alignment(obj_or_type: _CData | type[_CData]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _UnionT[_CData, _CArgObject, int], typ: type[_CastT]) -> _CastT: ... -def create_string_buffer(init: _UnionT[int, bytes], size: int | None = ...) -> Array[c_char]: ... +def cast(obj: _CData | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... +def create_string_buffer(init: int | bytes, size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer -def create_unicode_buffer(init: _UnionT[int, Text], size: int | None = ...) -> Array[c_wchar]: ... +def create_unicode_buffer(init: int | Text, size: int | None = ...) -> Array[c_wchar]: ... if sys.platform == "win32": def DllCanUnloadNow() -> int: ... @@ -183,7 +182,7 @@ 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 sizeof(obj_or_type: _CData | type[_CData]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -198,10 +197,10 @@ class _SimpleCData(Generic[_T], _CData): class c_byte(_SimpleCData[int]): ... class c_char(_SimpleCData[bytes]): - def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ... + def __init__(self, value: int | bytes = ...) -> None: ... -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): - def __init__(self, value: _UnionT[int, bytes] | None = ...) -> None: ... +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): + def __init__(self, value: int | bytes | None = ...) -> None: ... class c_double(_SimpleCData[float]): ... class c_longdouble(_SimpleCData[float]): ... @@ -225,11 +224,11 @@ 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_void_p(_PointerLike, _SimpleCData[int | None]): ... class c_wchar(_SimpleCData[Text]): ... -class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): - def __init__(self, value: _UnionT[int, Text] | None = ...) -> None: ... +class c_wchar_p(_PointerLike, _SimpleCData[Text | None]): + def __init__(self, value: int | Text | None = ...) -> None: ... class c_bool(_SimpleCData[bool]): def __init__(self, value: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/datetime.pyi b/mypy/typeshed/stdlib/@python2/datetime.pyi index 6a259cf4d0e4..62791461c885 100644 --- a/mypy/typeshed/stdlib/@python2/datetime.pyi +++ b/mypy/typeshed/stdlib/@python2/datetime.pyi @@ -1,8 +1,8 @@ from _typeshed import Self from time import struct_time -from typing import AnyStr, ClassVar, SupportsAbs, Union, overload +from typing import AnyStr, ClassVar, SupportsAbs, overload -_Text = Union[str, unicode] +_Text = str | unicode MINYEAR: int MAXYEAR: int @@ -214,13 +214,13 @@ class datetime(date): def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, other: datetime) -> bool: ... # type: ignore - def __lt__(self, other: datetime) -> bool: ... # type: ignore - def __ge__(self, other: datetime) -> bool: ... # type: ignore - def __gt__(self, other: datetime) -> bool: ... # type: ignore + def __le__(self, other: datetime) -> bool: ... # type: ignore[override] + def __lt__(self, other: datetime) -> bool: ... # type: ignore[override] + def __ge__(self, other: datetime) -> bool: ... # type: ignore[override] + def __gt__(self, other: datetime) -> bool: ... # type: ignore[override] def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... - @overload # type: ignore + @overload # type: ignore[override] def __sub__(self, other: datetime) -> timedelta: ... @overload def __sub__(self, other: timedelta) -> datetime: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi index 9c867074df06..e9c1d01a5c9b 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping from typing_extensions import Literal -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class _Database(MutableMapping[_KeyType, bytes]): def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi index e040f23ce2b0..acb4b3b7ae7f 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes error = OSError diff --git a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi index 1eecfac66a5f..c6eed0be2098 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload _T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class error(OSError): ... @@ -30,7 +30,7 @@ class _gdbm: 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 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi index 12d9f31881c1..764aed01a357 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload _T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class error(OSError): ... @@ -29,7 +29,7 @@ class _dbm: 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 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/@python2/decimal.pyi b/mypy/typeshed/stdlib/@python2/decimal.pyi index f798d8811c87..5ea7348c2eaf 100644 --- a/mypy/typeshed/stdlib/@python2/decimal.pyi +++ b/mypy/typeshed/stdlib/@python2/decimal.pyi @@ -2,9 +2,9 @@ from _typeshed import Self from types import TracebackType from typing import Any, Container, NamedTuple, Sequence, Text, Union -_Decimal = Union[Decimal, int] +_Decimal = Decimal | int _DecimalNew = Union[Decimal, float, Text, tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float] +_ComparableNum = Decimal | float class DecimalTuple(NamedTuple): sign: int diff --git a/mypy/typeshed/stdlib/@python2/difflib.pyi b/mypy/typeshed/stdlib/@python2/difflib.pyi index c4e59f54c66d..f4214cec2260 100644 --- a/mypy/typeshed/stdlib/@python2/difflib.pyi +++ b/mypy/typeshed/stdlib/@python2/difflib.pyi @@ -1,11 +1,11 @@ -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, overload _T = TypeVar("_T") # Aliases can't point to type vars, so we need to redeclare AnyStr _StrType = TypeVar("_StrType", Text, bytes) -_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] +_JunkCallback = Callable[[Text], bool] | Callable[[str], bool] class Match(NamedTuple): a: int @@ -29,9 +29,7 @@ class SequenceMatcher(Generic[_T]): # mypy thinks the signatures of the overloads overlap, but the types still work fine @overload -def get_close_matches( # type: ignore - word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... -) -> list[AnyStr]: ... +def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ...) -> list[AnyStr]: ... # type: ignore[misc] @overload def get_close_matches( word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... diff --git a/mypy/typeshed/stdlib/@python2/dis.pyi b/mypy/typeshed/stdlib/@python2/dis.pyi index f6be1a8dfa83..79cc30a68a0a 100644 --- a/mypy/typeshed/stdlib/@python2/dis.pyi +++ b/mypy/typeshed/stdlib/@python2/dis.pyi @@ -13,12 +13,12 @@ from opcode import ( opmap as opmap, opname as opname, ) -from typing import Any, Callable, Iterator, Union +from typing import Any, Callable, Iterator # 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] +_have_code = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_have_code_or_string = _have_code | str | bytes COMPILER_FLAG_NAMES: dict[int, str] diff --git a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi index 7c7023ed0b65..4cdc62ce3bae 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi @@ -1,6 +1,6 @@ -from typing import Any, Callable, Optional, Union +from typing import Any, Callable, Union -_Macro = Union[tuple[str], tuple[str, Optional[str]]] +_Macro = Union[tuple[str], tuple[str, str | None]] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi index 02301aed63f4..bf3754aab8ea 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi @@ -1,6 +1,6 @@ -from typing import Any, Mapping, Optional, overload +from typing import Any, Mapping, overload -_Option = tuple[str, Optional[str], str] +_Option = tuple[str, str | None, str] _GR = tuple[list[str], OptionDummy] def fancy_getopt( diff --git a/mypy/typeshed/stdlib/@python2/distutils/version.pyi b/mypy/typeshed/stdlib/@python2/distutils/version.pyi index b3bb9ea4909f..0e37a3a1a90c 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/version.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/version.pyi @@ -20,7 +20,7 @@ class StrictVersion(Version): prerelease: tuple[Text, int] | None def __init__(self, vstring: Text | None = ...) -> None: ... def parse(self: Self, vstring: Text) -> Self: ... - def __str__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... class LooseVersion(Version): @@ -29,5 +29,5 @@ class LooseVersion(Version): version: tuple[Text | int, ...] def __init__(self, vstring: Text | None = ...) -> None: ... def parse(self: Self, vstring: Text) -> Self: ... - def __str__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi index 308b296c4d53..cb8c281261fe 100644 --- a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi @@ -1,7 +1,7 @@ from email.mime.nonmultipart import MIMENonMultipart -from typing import Callable, Optional, Union +from typing import Callable, Union -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, str | None, str]] class MIMEApplication(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/@python2/fnmatch.pyi b/mypy/typeshed/stdlib/@python2/fnmatch.pyi index ead2dd5bf38e..942a52bbac9a 100644 --- a/mypy/typeshed/stdlib/@python2/fnmatch.pyi +++ b/mypy/typeshed/stdlib/@python2/fnmatch.pyi @@ -1,6 +1,6 @@ -from typing import AnyStr, Iterable, Union +from typing import AnyStr, Iterable -_EitherStr = Union[str, unicode] +_EitherStr = str | unicode def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/fractions.pyi b/mypy/typeshed/stdlib/@python2/fractions.pyi index 7835e9aa56b6..27de79248c03 100644 --- a/mypy/typeshed/stdlib/@python2/fractions.pyi +++ b/mypy/typeshed/stdlib/@python2/fractions.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Union, overload +from typing import overload from typing_extensions import Literal -_ComparableNum = Union[int, float, Decimal, Real] +_ComparableNum = int | float | Decimal | Real @overload def gcd(a: int, b: int) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/ftplib.pyi b/mypy/typeshed/stdlib/@python2/ftplib.pyi index b8c2bbd40371..870d00d804ce 100644 --- a/mypy/typeshed/stdlib/@python2/ftplib.pyi +++ b/mypy/typeshed/stdlib/@python2/ftplib.pyi @@ -1,10 +1,10 @@ from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext -from typing import Any, BinaryIO, Callable, Text, Union +from typing import Any, BinaryIO, Callable, Text from typing_extensions import Literal -_IntOrStr = Union[int, Text] +_IntOrStr = int | Text MSG_OOB: int FTP_PORT: int diff --git a/mypy/typeshed/stdlib/@python2/genericpath.pyi b/mypy/typeshed/stdlib/@python2/genericpath.pyi index fecb3b70af42..7ff27a62f959 100644 --- a/mypy/typeshed/stdlib/@python2/genericpath.pyi +++ b/mypy/typeshed/stdlib/@python2/genericpath.pyi @@ -1,14 +1,14 @@ from _typeshed import SupportsLessThanT -from typing import Sequence, Text, Union, overload +from typing import Sequence, Text, overload from typing_extensions import Literal # All overloads can return empty string. Ideally, Literal[""] would be a valid # Iterable[T], so that Union[List[T], Literal[""]] could be used as a return # type. But because this only works when T is str, we need Sequence[T] instead. @overload -def commonprefix(m: Sequence[str]) -> str | Literal[""]: ... # type: ignore +def commonprefix(m: Sequence[str]) -> str | Literal[""]: ... # type: ignore[misc] @overload -def commonprefix(m: Sequence[Text]) -> Text: ... # type: ignore +def commonprefix(m: Sequence[Text]) -> Text: ... @overload def commonprefix(m: Sequence[list[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/hashlib.pyi b/mypy/typeshed/stdlib/@python2/hashlib.pyi index 8f881aaaf419..86e6c21159a6 100644 --- a/mypy/typeshed/stdlib/@python2/hashlib.pyi +++ b/mypy/typeshed/stdlib/@python2/hashlib.pyi @@ -1,6 +1,4 @@ -from typing import Union - -_DataType = Union[str, unicode, bytearray, buffer, memoryview] +_DataType = str | unicode | bytearray | buffer | memoryview class _hash(object): # This is not actually in the module namespace. @property diff --git a/mypy/typeshed/stdlib/@python2/hmac.pyi b/mypy/typeshed/stdlib/@python2/hmac.pyi index cc39d8c65c8f..a244f4112e87 100644 --- a/mypy/typeshed/stdlib/@python2/hmac.pyi +++ b/mypy/typeshed/stdlib/@python2/hmac.pyi @@ -1,10 +1,10 @@ from _typeshed import ReadableBuffer from types import ModuleType -from typing import Any, AnyStr, Callable, Union, overload +from typing import Any, AnyStr, Callable, overload # TODO more precise type for object of hashlib _Hash = Any -_DigestMod = Union[str, Callable[[], _Hash], ModuleType] +_DigestMod = str | Callable[[], _Hash] | ModuleType digest_size: None diff --git a/mypy/typeshed/stdlib/@python2/imaplib.pyi b/mypy/typeshed/stdlib/@python2/imaplib.pyi index fc17ca0aaec1..72003eb48233 100644 --- a/mypy/typeshed/stdlib/@python2/imaplib.pyi +++ b/mypy/typeshed/stdlib/@python2/imaplib.pyi @@ -3,14 +3,14 @@ import time from builtins import list as List # alias to avoid name clashes with `IMAP4.list` from socket import socket as _socket from ssl import SSLSocket -from typing import IO, Any, Callable, Pattern, Text, Union +from typing import IO, Any, Callable, Pattern, Text 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]]]] +_AnyResponseData = list[None] | list[bytes | tuple[bytes, bytes]] class IMAP4: error: type[Exception] = ... diff --git a/mypy/typeshed/stdlib/@python2/imghdr.pyi b/mypy/typeshed/stdlib/@python2/imghdr.pyi index dcfc3506fb9a..36db49902983 100644 --- a/mypy/typeshed/stdlib/@python2/imghdr.pyi +++ b/mypy/typeshed/stdlib/@python2/imghdr.pyi @@ -1,11 +1,11 @@ -from typing import Any, BinaryIO, Callable, Protocol, Text, Union, overload +from typing import Any, BinaryIO, Callable, Protocol, Text, overload class _ReadableBinary(Protocol): def tell(self) -> int: ... def read(self, size: int) -> bytes: ... def seek(self, offset: int) -> Any: ... -_File = Union[Text, _ReadableBinary] +_File = Text | _ReadableBinary @overload def what(file: _File, h: None = ...) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/inspect.pyi b/mypy/typeshed/stdlib/@python2/inspect.pyi index aa0450ce6785..8ffcc3edcb87 100644 --- a/mypy/typeshed/stdlib/@python2/inspect.pyi +++ b/mypy/typeshed/stdlib/@python2/inspect.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence, Union +from typing import Any, AnyStr, Callable, NamedTuple, Sequence, Union # Types and members class EndOfBlock(Exception): ... @@ -104,9 +104,9 @@ class Traceback(NamedTuple): lineno: int function: str code_context: list[str] | None - index: int | None # type: ignore + index: int | None # type: ignore[assignment] -_FrameInfo = tuple[FrameType, str, int, str, Optional[list[str]], Optional[int]] +_FrameInfo = tuple[FrameType, str, int, str, list[str] | None, int | None] def getouterframes(frame: FrameType, context: int = ...) -> list[_FrameInfo]: ... def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi index 32eed63d42f9..9d05082fc30c 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi @@ -1,7 +1,7 @@ from _typeshed import Self, StrPath -from typing import Optional, Text +from typing import Text -_Label = tuple[int, Optional[Text]] +_Label = tuple[int, Text | None] _DFA = list[list[tuple[int, int]]] _DFAS = tuple[_DFA, dict[int, int]] diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi index 130f03dabdb7..a3969e60d95e 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi @@ -1,12 +1,12 @@ from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, Text, TypeVar, Union +from typing import Any, Callable, Iterator, Text, TypeVar _P = TypeVar("_P") -_NL = Union[Node, Leaf] +_NL = Node | Leaf _Context = tuple[Text, int, int] _Results = dict[Text, _NL] -_RawNode = tuple[int, Text, _Context, Optional[list[_NL]]] +_RawNode = tuple[int, Text, _Context, list[_NL] | None] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi index 9ca64dc966ae..059906d139ee 100644 --- a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -2,13 +2,13 @@ import threading from _typeshed import StrPath, SupportsWrite from time import struct_time from types import FrameType, TracebackType -from typing import IO, Any, Callable, Generic, Mapping, MutableMapping, Optional, Sequence, Text, TypeVar, Union, overload +from typing import IO, Any, Callable, Generic, Mapping, MutableMapping, Sequence, Text, TypeVar, Union, overload -_SysExcInfoType = Union[tuple[type, BaseException, Optional[TracebackType]], tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType] +_SysExcInfoType = Union[tuple[type, BaseException, TracebackType | None], tuple[None, None, None]] +_ExcInfoType = None | bool | _SysExcInfoType _ArgsType = Union[tuple[Any, ...], Mapping[str, Any]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, Text] +_FilterType = Filter | Callable[[LogRecord], int] +_Level = int | Text raiseExceptions: bool logThreads: bool diff --git a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi index 360e76c66558..212980e32ac6 100644 --- a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi @@ -52,7 +52,7 @@ class SocketHandler(Handler): def createSocket(self) -> None: ... class DatagramHandler(SocketHandler): - def makeSocket(self) -> SocketType: ... # type: ignore + def makeSocket(self) -> SocketType: ... # type: ignore[override] class SysLogHandler(Handler): LOG_EMERG: int diff --git a/mypy/typeshed/stdlib/@python2/mailbox.pyi b/mypy/typeshed/stdlib/@python2/mailbox.pyi index 9c4aa66cdbb7..9d3f4d866aba 100644 --- a/mypy/typeshed/stdlib/@python2/mailbox.pyi +++ b/mypy/typeshed/stdlib/@python2/mailbox.pyi @@ -1,26 +1,11 @@ import email.message from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Text, - TypeVar, - Union, - overload, -) +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, Text, TypeVar, overload from typing_extensions import Literal _T = TypeVar("_T") _MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] +_MessageData = email.message.Message | bytes | str | IO[str] | IO[bytes] class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... diff --git a/mypy/typeshed/stdlib/@python2/mailcap.pyi b/mypy/typeshed/stdlib/@python2/mailcap.pyi index 56218d1370fe..6e0c918280ad 100644 --- a/mypy/typeshed/stdlib/@python2/mailcap.pyi +++ b/mypy/typeshed/stdlib/@python2/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Mapping, Sequence, Union +from typing import Mapping, Sequence -_Cap = dict[str, Union[str, int]] +_Cap = dict[str, str | int] def findmatch( caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... diff --git a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi index 87dff754009d..30346aba3367 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi @@ -1,9 +1,8 @@ import sys -from typing import Optional if sys.platform == "win32": - _SequenceType = list[tuple[str, Optional[str], int]] + _SequenceType = list[tuple[str, str | None, int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType diff --git a/mypy/typeshed/stdlib/@python2/netrc.pyi b/mypy/typeshed/stdlib/@python2/netrc.pyi index 3d92c7b4d43b..fc5fababa7e7 100644 --- a/mypy/typeshed/stdlib/@python2/netrc.pyi +++ b/mypy/typeshed/stdlib/@python2/netrc.pyi @@ -1,4 +1,4 @@ -from typing import Optional, Text +from typing import Text class NetrcParseError(Exception): filename: str | None @@ -7,7 +7,7 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: Text | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = tuple[str, Optional[str], Optional[str]] +_NetrcTuple = tuple[str, str | None, str | None] class netrc: hosts: dict[str, _NetrcTuple] diff --git a/mypy/typeshed/stdlib/@python2/nntplib.pyi b/mypy/typeshed/stdlib/@python2/nntplib.pyi index 602617665ea8..7cacb07bdb77 100644 --- a/mypy/typeshed/stdlib/@python2/nntplib.pyi +++ b/mypy/typeshed/stdlib/@python2/nntplib.pyi @@ -3,9 +3,9 @@ import socket import ssl from _typeshed import Self from builtins import list as List # alias to avoid a name clash with a method named `list` in `_NNTPBase` -from typing import IO, Any, Iterable, NamedTuple, Union +from typing import IO, Any, Iterable, NamedTuple -_File = Union[IO[bytes], bytes, str, None] +_File = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str diff --git a/mypy/typeshed/stdlib/@python2/optparse.pyi b/mypy/typeshed/stdlib/@python2/optparse.pyi index a99bc0a6fb3b..d033cb9a6da6 100644 --- a/mypy/typeshed/stdlib/@python2/optparse.pyi +++ b/mypy/typeshed/stdlib/@python2/optparse.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Union, overload +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, overload # See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g -_Text = Union[str, unicode] +_Text = str | unicode NO_DEFAULT: tuple[_Text, ...] SUPPRESS_HELP: _Text diff --git a/mypy/typeshed/stdlib/@python2/os/__init__.pyi b/mypy/typeshed/stdlib/@python2/os/__init__.pyi index 2ca9bce243ae..c2e806ff0fb6 100644 --- a/mypy/typeshed/stdlib/@python2/os/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/os/__init__.pyi @@ -16,7 +16,6 @@ from typing import ( Sequence, Text, TypeVar, - Union, overload, ) @@ -269,7 +268,7 @@ def execlpe(file: Text, __arg0: 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]]] +_ExecVArgs = tuple[bytes | Text, ...] | list[bytes] | list[Text] | list[bytes | Text] def execv(path: Text, args: _ExecVArgs) -> NoReturn: ... def execve(path: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... diff --git a/mypy/typeshed/stdlib/@python2/pickle.pyi b/mypy/typeshed/stdlib/@python2/pickle.pyi index bb9b6614f329..c3052f5c3113 100644 --- a/mypy/typeshed/stdlib/@python2/pickle.pyi +++ b/mypy/typeshed/stdlib/@python2/pickle.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Iterator, Optional, Union +from typing import IO, Any, Callable, Iterator, Union HIGHEST_PROTOCOL: int bytes_types: tuple[type[Any], ...] # undocumented @@ -16,8 +16,8 @@ _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]]], + tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None], + tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None], ] class Pickler: diff --git a/mypy/typeshed/stdlib/@python2/pkgutil.pyi b/mypy/typeshed/stdlib/@python2/pkgutil.pyi index 3b006b376641..aa220bc3ae61 100644 --- a/mypy/typeshed/stdlib/@python2/pkgutil.pyi +++ b/mypy/typeshed/stdlib/@python2/pkgutil.pyi @@ -1,13 +1,14 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Iterable, Iterator, Union +from typing import IO, Any, Callable, Iterable, Iterator, TypeVar Loader = Any MetaPathFinder = Any PathEntryFinder = Any -_ModuleInfoLike = tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] +_PathT = TypeVar("_PathT", bound=Iterable[str]) +_ModuleInfoLike = tuple[MetaPathFinder | PathEntryFinder, str, bool] -def extend_path(path: list[str], name: str) -> list[str]: ... +def extend_path(path: _PathT, name: str) -> _PathT: ... class ImpImporter: def __init__(self, path: str | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/plistlib.pyi b/mypy/typeshed/stdlib/@python2/plistlib.pyi index 02a1cb506d1d..488757b4c81e 100644 --- a/mypy/typeshed/stdlib/@python2/plistlib.pyi +++ b/mypy/typeshed/stdlib/@python2/plistlib.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, Mapping, Text, Union +from typing import IO, Any, Mapping, Text -_Path = Union[str, Text] +_Path = str | Text def readPlist(pathOrFile: _Path | IO[bytes]) -> Any: ... def writePlist(value: Mapping[str, Any], pathOrFile: _Path | IO[bytes]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pstats.pyi b/mypy/typeshed/stdlib/@python2/pstats.pyi index e2cf6e437826..6b956764efa9 100644 --- a/mypy/typeshed/stdlib/@python2/pstats.pyi +++ b/mypy/typeshed/stdlib/@python2/pstats.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Text, TypeVar, Union, overload +from typing import IO, Any, Iterable, Text, TypeVar, overload -_Selector = Union[str, float, int] +_Selector = str | float | int _T = TypeVar("_T", bound=Stats) class Stats: diff --git a/mypy/typeshed/stdlib/@python2/py_compile.pyi b/mypy/typeshed/stdlib/@python2/py_compile.pyi index 3c26f451116e..ccd05029fe0e 100644 --- a/mypy/typeshed/stdlib/@python2/py_compile.pyi +++ b/mypy/typeshed/stdlib/@python2/py_compile.pyi @@ -1,6 +1,6 @@ -from typing import Text, Union +from typing import Text -_EitherStr = Union[bytes, Text] +_EitherStr = bytes | Text class PyCompileError(Exception): exc_type_name: str diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi index 8faaec294316..5c58a0a1fe73 100644 --- a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi @@ -1,7 +1,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Optional, Text +from typing import Any, Callable, Text EXPAT_VERSION: str # undocumented version_info: tuple[int, int, int] # undocumented @@ -19,7 +19,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = tuple[int, int, Optional[str], tuple[Any, ...]] +_Model = tuple[int, int, str | None, tuple[Any, ...]] class XMLParserType(object): def Parse(self, __data: Text | bytes, __isfinal: bool = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/readline.pyi b/mypy/typeshed/stdlib/@python2/readline.pyi index 9b82d9bae636..af642410b007 100644 --- a/mypy/typeshed/stdlib/@python2/readline.pyi +++ b/mypy/typeshed/stdlib/@python2/readline.pyi @@ -2,8 +2,8 @@ import sys from typing import Callable, Optional, Sequence, Text if sys.platform != "win32": - _CompleterT = Optional[Callable[[str, int], Optional[str]]] - _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + _CompleterT = Optional[Callable[[str, int], str | None]] + _CompDispT = Callable[[str, Sequence[str], int], None] | None def parse_and_bind(__string: str) -> None: ... def read_init_file(__filename: Text | None = ...) -> None: ... def get_line_buffer() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi index e075e241b794..6cf58fbf20cf 100644 --- a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi @@ -1,6 +1,6 @@ -from typing import Any, Union +from typing import Any -_Text = Union[str, unicode] +_Text = str | unicode class Completer: def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sets.pyi b/mypy/typeshed/stdlib/@python2/sets.pyi index 7cafbaf8a7c7..637bc879fa74 100644 --- a/mypy/typeshed/stdlib/@python2/sets.pyi +++ b/mypy/typeshed/stdlib/@python2/sets.pyi @@ -1,8 +1,8 @@ from _typeshed import Self -from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar, Union +from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar _T = TypeVar("_T") -_Setlike = Union[BaseSet[_T], Iterable[_T]] +_Setlike = BaseSet[_T] | Iterable[_T] class BaseSet(Iterable[_T]): def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shutil.pyi b/mypy/typeshed/stdlib/@python2/shutil.pyi index f92cf1c9f1a0..173ce9c284af 100644 --- a/mypy/typeshed/stdlib/@python2/shutil.pyi +++ b/mypy/typeshed/stdlib/@python2/shutil.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar, Union +from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar _AnyStr = TypeVar("_AnyStr", str, unicode) _AnyPath = TypeVar("_AnyPath", str, unicode) @@ -21,7 +21,7 @@ def copytree( ) -> _PathReturn: ... def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Callable[[Any, _AnyPath, Any], Any] | None = ...) -> None: ... -_CopyFn = Union[Callable[[str, str], None], Callable[[Text, Text], None]] +_CopyFn = Callable[[str, str], None] | Callable[[Text, Text], None] def move(src: Text, dst: Text) -> _PathReturn: ... def make_archive( diff --git a/mypy/typeshed/stdlib/@python2/signal.pyi b/mypy/typeshed/stdlib/@python2/signal.pyi index 7f86f03e638a..f39f38c41c8f 100644 --- a/mypy/typeshed/stdlib/@python2/signal.pyi +++ b/mypy/typeshed/stdlib/@python2/signal.pyi @@ -1,5 +1,5 @@ from types import FrameType -from typing import Callable, Union +from typing import Callable SIG_DFL: int SIG_IGN: int @@ -55,7 +55,7 @@ CTRL_BREAK_EVENT: int class ItimerError(IOError): ... -_HANDLER = Union[Callable[[int, FrameType], None], int, None] +_HANDLER = Callable[[int, FrameType], None] | int | None def alarm(time: int) -> int: ... def getsignal(signalnum: int) -> _HANDLER: ... diff --git a/mypy/typeshed/stdlib/@python2/smtpd.pyi b/mypy/typeshed/stdlib/@python2/smtpd.pyi index 6778611a56d9..c7741d183415 100644 --- a/mypy/typeshed/stdlib/@python2/smtpd.pyi +++ b/mypy/typeshed/stdlib/@python2/smtpd.pyi @@ -9,8 +9,7 @@ class SMTPChannel(asynchat.async_chat): COMMAND: int DATA: int def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ... - # base asynchat.async_chat.push() accepts bytes - def push(self, msg: Text) -> None: ... # type: ignore + def push(self, msg: Text) -> None: ... def collect_incoming_data(self, data: bytes) -> None: ... def found_terminator(self) -> None: ... def smtp_HELO(self, arg: str) -> None: ... @@ -35,11 +34,7 @@ class SMTPServer(asyncore.dispatcher): class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str - ) -> str | None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str) -> str | None: ... # type: ignore[override] class MailmanProxy(PureProxy): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str - ) -> str | None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str) -> str | None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/@python2/sndhdr.pyi b/mypy/typeshed/stdlib/@python2/sndhdr.pyi index 0213a5d0cbb3..fea65b28899c 100644 --- a/mypy/typeshed/stdlib/@python2/sndhdr.pyi +++ b/mypy/typeshed/stdlib/@python2/sndhdr.pyi @@ -1,6 +1,6 @@ -from typing import Text, Union +from typing import Text -_SndHeaders = tuple[str, int, int, int, Union[int, str]] +_SndHeaders = tuple[str, int, int, int, int | str] def what(filename: Text) -> _SndHeaders | None: ... def whathdr(filename: Text) -> _SndHeaders | None: ... diff --git a/mypy/typeshed/stdlib/@python2/socket.pyi b/mypy/typeshed/stdlib/@python2/socket.pyi index 0981ce28a786..296a9fa5e5a5 100644 --- a/mypy/typeshed/stdlib/@python2/socket.pyi +++ b/mypy/typeshed/stdlib/@python2/socket.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, BinaryIO, Iterable, Text, Union, overload +from typing import Any, BinaryIO, Iterable, Text, overload # ----- Constants ----- # Some socket families are listed in the "Socket families" section of the docs, @@ -373,11 +373,11 @@ class timeout(error): # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[tuple[Any, ...], str] +_Address = tuple[Any, ...] | str _RetAddress = Any # TODO Most methods allow bytes as address objects -_WriteBuffer = Union[bytearray, memoryview] +_WriteBuffer = bytearray | memoryview _CMSG = tuple[int, int, bytes] diff --git a/mypy/typeshed/stdlib/@python2/sre_parse.pyi b/mypy/typeshed/stdlib/@python2/sre_parse.pyi index c4307bb9bb53..9929b804126e 100644 --- a/mypy/typeshed/stdlib/@python2/sre_parse.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_parse.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union +from typing import Any, Iterable, Match, Pattern as _Pattern SPECIAL_CHARS: str REPEAT_CHARS: str @@ -21,12 +21,12 @@ class Pattern: def closegroup(self, gid: int) -> None: ... def checkgroup(self, gid: int) -> bool: ... -_OpSubpatternType = tuple[Optional[int], int, int, SubPattern] +_OpSubpatternType = tuple[int | None, 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] +_AvType = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType = str | _AvType class SubPattern: pattern: str @@ -56,7 +56,7 @@ 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]]] +_Template = tuple[list[tuple[int, int]], list[int | None]] 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/ssl.pyi b/mypy/typeshed/stdlib/@python2/ssl.pyi index 4eccf5875d55..2c6b32567249 100644 --- a/mypy/typeshed/stdlib/@python2/ssl.pyi +++ b/mypy/typeshed/stdlib/@python2/ssl.pyi @@ -1,18 +1,18 @@ import socket import sys from _typeshed import Self, StrPath -from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Text, Union, overload +from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Text, Union, overload from typing_extensions import Literal _PCTRTT = tuple[tuple[str, str], ...] _PCTRTTT = tuple[_PCTRTT, ...] -_PeerCertRetDictType = dict[str, Union[str, _PCTRTTT, _PCTRTT]] -_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] +_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType = _PeerCertRetDictType | bytes | None _EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] -_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] +_PasswordType = Union[Callable[[], str | bytes], str, bytes] _SC1ArgT = SSLSocket -_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] +_SrvnmeCbType = Callable[[_SC1ArgT, str | None, SSLSocket], int | None] class SSLError(OSError): library: str diff --git a/mypy/typeshed/stdlib/@python2/struct.pyi b/mypy/typeshed/stdlib/@python2/struct.pyi index 7129fbc4cfb6..0296c737089a 100644 --- a/mypy/typeshed/stdlib/@python2/struct.pyi +++ b/mypy/typeshed/stdlib/@python2/struct.pyi @@ -1,12 +1,12 @@ from array import array from mmap import mmap -from typing import Any, Text, Union +from typing import Any, Text class error(Exception): ... -_FmtType = Union[bytes, Text] -_BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] -_WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] +_FmtType = bytes | Text +_BufferType = array[int] | bytes | bytearray | buffer | memoryview | mmap +_WriteBufferType = 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: ... diff --git a/mypy/typeshed/stdlib/@python2/subprocess.pyi b/mypy/typeshed/stdlib/@python2/subprocess.pyi index d2149c81aaaf..e6ab3dfcbb73 100644 --- a/mypy/typeshed/stdlib/@python2/subprocess.pyi +++ b/mypy/typeshed/stdlib/@python2/subprocess.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, TypeVar, Union +from typing import IO, Any, Callable, Generic, Mapping, Sequence, Text, TypeVar -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, Text] -_CMD = Union[_TXT, Sequence[_TXT]] -_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] +_FILE = None | int | IO[Any] +_TXT = bytes | Text +_CMD = _TXT | Sequence[_TXT] +_ENV = Mapping[bytes, _TXT] | Mapping[Text, _TXT] # Same args as Popen.__init__ def call( diff --git a/mypy/typeshed/stdlib/@python2/sunau.pyi b/mypy/typeshed/stdlib/@python2/sunau.pyi index 6d5caee7b199..85b4d12b4d8a 100644 --- a/mypy/typeshed/stdlib/@python2/sunau.pyi +++ b/mypy/typeshed/stdlib/@python2/sunau.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, NoReturn, Text, Union +from typing import IO, Any, NoReturn, Text -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/termios.pyi b/mypy/typeshed/stdlib/@python2/termios.pyi index 6ef2f6818827..c6a90df31b59 100644 --- a/mypy/typeshed/stdlib/@python2/termios.pyi +++ b/mypy/typeshed/stdlib/@python2/termios.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Union +from typing import Any if sys.platform != "win32": - _Attr = list[Union[int, list[Union[bytes, int]]]] + _Attr = list[int | list[bytes | int]] # TODO constants not really documented B0: int diff --git a/mypy/typeshed/stdlib/@python2/threading.pyi b/mypy/typeshed/stdlib/@python2/threading.pyi index 611552dc92ab..b62b3a121b80 100644 --- a/mypy/typeshed/stdlib/@python2/threading.pyi +++ b/mypy/typeshed/stdlib/@python2/threading.pyi @@ -1,8 +1,8 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Text, TypeVar +from typing import Any, Callable, Iterable, Mapping, Text, TypeVar # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] diff --git a/mypy/typeshed/stdlib/@python2/timeit.pyi b/mypy/typeshed/stdlib/@python2/timeit.pyi index 3a7f6e0e0841..b95c89fa312d 100644 --- a/mypy/typeshed/stdlib/@python2/timeit.pyi +++ b/mypy/typeshed/stdlib/@python2/timeit.pyi @@ -1,8 +1,8 @@ -from typing import IO, Any, Callable, Sequence, Text, Union +from typing import IO, Any, Callable, Sequence, Text -_str = Union[str, Text] +_str = str | Text _Timer = Callable[[], float] -_stmt = Union[_str, Callable[[], Any]] +_stmt = _str | Callable[[], Any] default_timer: _Timer diff --git a/mypy/typeshed/stdlib/@python2/trace.pyi b/mypy/typeshed/stdlib/@python2/trace.pyi index aa35754cfdfc..ea9dfba5bb83 100644 --- a/mypy/typeshed/stdlib/@python2/trace.pyi +++ b/mypy/typeshed/stdlib/@python2/trace.pyi @@ -1,12 +1,12 @@ import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar +from typing import Any, Callable, Mapping, Sequence, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") _P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = tuple[str, Optional[str], str] +_fileModuleFunction = tuple[str, str | None, str] class CoverageResults: def __init__( diff --git a/mypy/typeshed/stdlib/@python2/traceback.pyi b/mypy/typeshed/stdlib/@python2/traceback.pyi index 94c75e5ef6b1..34fc00ed7daa 100644 --- a/mypy/typeshed/stdlib/@python2/traceback.pyi +++ b/mypy/typeshed/stdlib/@python2/traceback.pyi @@ -1,7 +1,7 @@ from types import FrameType, TracebackType -from typing import IO, Optional +from typing import IO -_PT = tuple[str, int, str, Optional[str]] +_PT = tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_exception( diff --git a/mypy/typeshed/stdlib/@python2/tty.pyi b/mypy/typeshed/stdlib/@python2/tty.pyi index 56e85108c75e..fc7e90bc0ff9 100644 --- a/mypy/typeshed/stdlib/@python2/tty.pyi +++ b/mypy/typeshed/stdlib/@python2/tty.pyi @@ -1,7 +1,7 @@ import sys -from typing import IO, Union +from typing import IO -_FD = Union[int, IO[str]] +_FD = int | IO[str] if sys.platform != "win32": # XXX: Undocumented integer constants diff --git a/mypy/typeshed/stdlib/@python2/turtle.pyi b/mypy/typeshed/stdlib/@python2/turtle.pyi index cb52479864a2..037b9851381f 100644 --- a/mypy/typeshed/stdlib/@python2/turtle.pyi +++ b/mypy/typeshed/stdlib/@python2/turtle.pyi @@ -15,7 +15,7 @@ _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. _PenState = dict[str, Any] -_Speed = Union[str, float] +_Speed = str | float _PolygonCoords = Sequence[tuple[float, float]] # TODO: Type this more accurately @@ -175,7 +175,7 @@ class TPen(object): def isvisible(self) -> bool: ... # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload - def pen(self) -> _PenState: ... # type: ignore + def pen(self) -> _PenState: ... # type: ignore[misc] @overload def pen( self, @@ -215,7 +215,7 @@ class RawTurtle(TPen, TNavigator): def shape(self, name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload - def shapesize(self) -> tuple[float, float, float]: ... # type: ignore + def shapesize(self) -> tuple[float, float, float]: ... # type: ignore[misc] @overload def shapesize( self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... @@ -423,7 +423,7 @@ def isvisible() -> bool: ... # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload -def pen() -> _PenState: ... # type: ignore +def pen() -> _PenState: ... # type: ignore[misc] @overload def pen( pen: _PenState | None = ..., @@ -459,7 +459,7 @@ def shape(name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapesize() -> tuple[float, float, float]: ... # type: ignore +def shapesize() -> tuple[float, float, float]: ... # type: ignore[misc] @overload def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... def settiltangle(angle: float) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi index 53957910576c..62ef6f7b787c 100644 --- a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi @@ -1,6 +1,6 @@ import abc from _typeshed import Self -from typing import ( # noqa Y022 +from typing import ( # noqa: Y022 TYPE_CHECKING as TYPE_CHECKING, Any, Callable, @@ -47,8 +47,7 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... - # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. - def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore + def 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]: ... diff --git a/mypy/typeshed/stdlib/@python2/unittest.pyi b/mypy/typeshed/stdlib/@python2/unittest.pyi index 9db413d996bb..887e7055207d 100644 --- a/mypy/typeshed/stdlib/@python2/unittest.pyi +++ b/mypy/typeshed/stdlib/@python2/unittest.pyi @@ -10,7 +10,7 @@ _FT = TypeVar("_FT") _P = ParamSpec("_P") _ExceptionType = Union[type[BaseException], tuple[type[BaseException], ...]] -_Regexp = Union[Text, Pattern[Text]] +_Regexp = Text | Pattern[Text] _SysExcInfoType = Union[tuple[type[BaseException], BaseException, types.TracebackType], tuple[None, None, None]] diff --git a/mypy/typeshed/stdlib/@python2/urllib2.pyi b/mypy/typeshed/stdlib/@python2/urllib2.pyi index 990384ebdcd1..1ea1bce28db1 100644 --- a/mypy/typeshed/stdlib/@python2/urllib2.pyi +++ b/mypy/typeshed/stdlib/@python2/urllib2.pyi @@ -1,9 +1,9 @@ import ssl from httplib import HTTPConnectionProtocol, HTTPResponse -from typing import Any, AnyStr, Callable, Mapping, Sequence, Text, Union +from typing import Any, AnyStr, Callable, Mapping, Sequence, Text from urllib import addinfourl -_string = Union[str, unicode] +_string = str | unicode class URLError(IOError): reason: str | BaseException diff --git a/mypy/typeshed/stdlib/@python2/urlparse.pyi b/mypy/typeshed/stdlib/@python2/urlparse.pyi index 625928a74135..16c32753c7c5 100644 --- a/mypy/typeshed/stdlib/@python2/urlparse.pyi +++ b/mypy/typeshed/stdlib/@python2/urlparse.pyi @@ -1,6 +1,6 @@ -from typing import AnyStr, NamedTuple, Sequence, Union, overload +from typing import AnyStr, NamedTuple, Sequence, overload -_String = Union[str, unicode] +_String = str | unicode uses_relative: list[str] uses_netloc: list[str] diff --git a/mypy/typeshed/stdlib/@python2/uu.pyi b/mypy/typeshed/stdlib/@python2/uu.pyi index e8717aecbe36..a9585bac60a1 100644 --- a/mypy/typeshed/stdlib/@python2/uu.pyi +++ b/mypy/typeshed/stdlib/@python2/uu.pyi @@ -1,6 +1,6 @@ -from typing import BinaryIO, Text, Union +from typing import BinaryIO, Text -_File = Union[Text, BinaryIO] +_File = Text | BinaryIO class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/wave.pyi b/mypy/typeshed/stdlib/@python2/wave.pyi index ceae301145d8..d13f74664f43 100644 --- a/mypy/typeshed/stdlib/@python2/wave.pyi +++ b/mypy/typeshed/stdlib/@python2/wave.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, BinaryIO, NoReturn, Text, Union +from typing import IO, Any, BinaryIO, NoReturn, Text -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/weakref.pyi b/mypy/typeshed/stdlib/@python2/weakref.pyi index 8c65ab21a568..959c3e1b9d1e 100644 --- a/mypy/typeshed/stdlib/@python2/weakref.pyi +++ b/mypy/typeshed/stdlib/@python2/weakref.pyi @@ -43,7 +43,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT # This __new__ method uses a non-standard name for the "cls" parameter - def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore + def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi index 254f8a0c1657..e37b7cd89176 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi @@ -11,7 +11,7 @@ class NodeList(list[_T]): class EmptyNodeList(tuple[Any, ...]): length: int def item(self, index: int) -> None: ... - def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore + def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi index d8936bdc2ab4..a77c99790fda 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/xmlbuilder.pyi @@ -2,5 +2,5 @@ from typing import Any def __getattr__(name: str) -> Any: ... # incomplete -class DocumentLS(Any): ... # type: ignore -class DOMImplementationLS(Any): ... # type: ignore +class DocumentLS(Any): ... +class DOMImplementationLS(Any): ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi index a6cbae35d04f..f17ae5211252 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi @@ -12,7 +12,6 @@ from typing import ( Sequence, Text, TypeVar, - Union, overload, ) @@ -29,7 +28,7 @@ _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] +_parser_input_type = 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 @@ -38,7 +37,7 @@ _parser_input_type = Union[bytes, Text] # 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] +_str_argument_type = str | Text # Type for return values from individual tag/attr/text values # in python2, if the tag/attribute/text wasn't decode-able as ascii, it @@ -46,7 +45,7 @@ _str_argument_type = Union[str, Text] # _fixtext function in the source). Client code knows best: _str_result_type = Any -_file_or_filename = Union[Text, FileDescriptor, IO[Any]] +_file_or_filename = Text | FileDescriptor | IO[Any] class Element(MutableSequence[Element]): tag: _str_result_type diff --git a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi index 0defb96bffb8..2365bcf90cd1 100644 --- a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi +++ b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi @@ -10,7 +10,7 @@ from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, MutableMapping, _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] +_dateTimeComp = unicode | DateTime | datetime # A "host description" used by Transport factories _hostDesc = Union[str, tuple[str, Mapping[Any, Any]]] @@ -58,8 +58,8 @@ class DateTime: 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 __eq__(self, other: _dateTimeComp) -> bool: ... # type: ignore[override] + def __ne__(self, other: _dateTimeComp) -> bool: ... # type: ignore[override] def timetuple(self) -> struct_time: ... def __cmp__(self, other: _dateTimeComp) -> int: ... def decode(self, data: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/zipfile.pyi b/mypy/typeshed/stdlib/@python2/zipfile.pyi index 0f376d2d93b8..63c93b482855 100644 --- a/mypy/typeshed/stdlib/@python2/zipfile.pyi +++ b/mypy/typeshed/stdlib/@python2/zipfile.pyi @@ -1,9 +1,9 @@ import io from _typeshed import Self, StrPath from types import TracebackType -from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text, Union +from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text -_SZI = Union[Text, ZipInfo] +_SZI = Text | ZipInfo _DT = tuple[int, int, int, int, int, int] class BadZipfile(Exception): ... @@ -30,9 +30,9 @@ class ZipExtFile(io.BufferedIOBase): close_fileobj: bool = ..., ) -> None: ... def read(self, n: int | None = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore + def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] def peek(self, n: int = ...) -> bytes: ... - def read1(self, n: int | None) -> bytes: ... # type: ignore + def read1(self, n: int | None) -> bytes: ... class _Writer(Protocol): def write(self, __s: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index eea49588cb95..f801b5deb0d9 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -10,6 +10,8 @@ if sys.version_info >= (3, 8): _identifier = str class AST: + if sys.version_info >= (3, 10): + __match_args__ = () _attributes: ClassVar[tuple[str, ...]] _fields: ClassVar[tuple[str, ...]] def __init__(self, *args: Any, **kwargs: Any) -> None: ... @@ -27,26 +29,38 @@ if sys.version_info >= (3, 8): class type_ignore(AST): ... class TypeIgnore(type_ignore): + if sys.version_info >= (3, 10): + __match_args__ = ("lineno", "tag") tag: str class FunctionType(mod): + if sys.version_info >= (3, 10): + __match_args__ = ("argtypes", "returns") argtypes: list[expr] returns: expr class Module(mod): + if sys.version_info >= (3, 10): + __match_args__ = ("body", "type_ignores") body: list[stmt] if sys.version_info >= (3, 8): type_ignores: list[TypeIgnore] class Interactive(mod): + if sys.version_info >= (3, 10): + __match_args__ = ("body",) body: list[stmt] class Expression(mod): + if sys.version_info >= (3, 10): + __match_args__ = ("body",) body: expr class stmt(AST): ... class FunctionDef(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") name: _identifier args: arguments body: list[stmt] @@ -54,6 +68,8 @@ class FunctionDef(stmt): returns: expr | None class AsyncFunctionDef(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") name: _identifier args: arguments body: list[stmt] @@ -61,6 +77,8 @@ class AsyncFunctionDef(stmt): returns: expr | None class ClassDef(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("name", "bases", "keywords", "body", "decorator_list") name: _identifier bases: list[expr] keywords: list[keyword] @@ -68,85 +86,123 @@ class ClassDef(stmt): decorator_list: list[expr] class Return(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("value",) value: expr | None class Delete(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("targets",) targets: list[expr] class Assign(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("targets", "value", "type_comment") targets: list[expr] value: expr class AugAssign(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "op", "value") target: expr op: operator value: expr class AnnAssign(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "annotation", "value", "simple") target: expr annotation: expr value: expr | None simple: int class For(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") target: expr iter: expr body: list[stmt] orelse: list[stmt] class AsyncFor(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") target: expr iter: expr body: list[stmt] orelse: list[stmt] class While(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("test", "body", "orelse") test: expr body: list[stmt] orelse: list[stmt] class If(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("test", "body", "orelse") test: expr body: list[stmt] orelse: list[stmt] class With(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("items", "body", "type_comment") items: list[withitem] body: list[stmt] class AsyncWith(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("items", "body", "type_comment") items: list[withitem] body: list[stmt] class Raise(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("exc", "cause") exc: expr | None cause: expr | None class Try(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("body", "handlers", "orelse", "finalbody") body: list[stmt] handlers: list[ExceptHandler] orelse: list[stmt] finalbody: list[stmt] class Assert(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("test", "msg") test: expr msg: expr | None class Import(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("names",) names: list[alias] class ImportFrom(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("module", "names", "level") module: _identifier | None names: list[alias] level: int class Global(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("names",) names: list[_identifier] class Nonlocal(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("names",) names: list[_identifier] class Expr(stmt): + if sys.version_info >= (3, 10): + __match_args__ = ("value",) value: expr class Pass(stmt): ... @@ -155,76 +211,112 @@ class Continue(stmt): ... class expr(AST): ... class BoolOp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("op", "values") op: boolop values: list[expr] class BinOp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("left", "op", "right") left: expr op: operator right: expr class UnaryOp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("op", "operand") op: unaryop operand: expr class Lambda(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("args", "body") args: arguments body: expr class IfExp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("test", "body", "orelse") test: expr body: expr orelse: expr class Dict(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("keys", "values") keys: list[expr | None] values: list[expr] class Set(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elts",) elts: list[expr] class ListComp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] class SetComp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] class DictComp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("key", "value", "generators") key: expr value: expr generators: list[comprehension] class GeneratorExp(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] class Await(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value",) value: expr class Yield(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value",) value: expr | None class YieldFrom(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value",) value: expr class Compare(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("left", "ops", "comparators") left: expr ops: list[cmpop] comparators: list[expr] class Call(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("func", "args", "keywords") func: expr args: list[expr] keywords: list[keyword] class FormattedValue(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value", "conversion", "format_spec") value: expr conversion: int | None format_spec: expr | None class JoinedStr(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("values",) values: list[expr] if sys.version_info < (3, 8): @@ -243,6 +335,8 @@ if sys.version_info < (3, 8): class Ellipsis(expr): ... # Deprecated in 3.8; use Constant class Constant(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value", "kind") value: Any # None, str, bytes, bool, int, float, complex, Ellipsis kind: str | None # Aliases for value, for backwards compatibility @@ -251,10 +345,14 @@ class Constant(expr): if sys.version_info >= (3, 8): class NamedExpr(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "value") target: expr value: expr class Attribute(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value", "attr", "ctx") value: expr attr: _identifier ctx: expr_context @@ -266,6 +364,8 @@ else: _SliceT = slice class Slice(_SliceT): + if sys.version_info >= (3, 10): + __match_args__ = ("lower", "upper", "step") lower: expr | None upper: expr | None step: expr | None @@ -278,23 +378,33 @@ if sys.version_info < (3, 9): value: expr class Subscript(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value", "slice", "ctx") value: expr slice: _SliceT ctx: expr_context class Starred(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("value", "ctx") value: expr ctx: expr_context class Name(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("id", "ctx") id: _identifier ctx: expr_context class List(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elts", "ctx") elts: list[expr] ctx: expr_context class Tuple(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("elts", "ctx") elts: list[expr] ctx: expr_context @@ -346,6 +456,8 @@ class NotEq(cmpop): ... class NotIn(cmpop): ... class comprehension(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "iter", "ifs", "is_async") target: expr iter: expr ifs: list[expr] @@ -354,11 +466,15 @@ class comprehension(AST): class excepthandler(AST): ... class ExceptHandler(excepthandler): + if sys.version_info >= (3, 10): + __match_args__ = ("type", "name", "body") type: expr | None name: _identifier | None body: list[stmt] class arguments(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") if sys.version_info >= (3, 8): posonlyargs: list[arg] args: list[arg] @@ -369,23 +485,32 @@ class arguments(AST): defaults: list[expr] class arg(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("arg", "annotation", "type_comment") arg: _identifier annotation: expr | None class keyword(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("arg", "value") arg: _identifier | None value: expr class alias(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("name", "asname") name: _identifier asname: _identifier | None class withitem(AST): + if sys.version_info >= (3, 10): + __match_args__ = ("context_expr", "optional_vars") context_expr: expr optional_vars: expr | None if sys.version_info >= (3, 10): class Match(stmt): + __match_args__ = ("subject", "cases") subject: expr cases: list[match_case] @@ -394,36 +519,45 @@ if sys.version_info >= (3, 10): _pattern = pattern class match_case(AST): + __match_args__ = ("pattern", "guard", "body") pattern: _pattern guard: expr | None body: list[stmt] class MatchValue(pattern): + __match_args__ = ("value",) value: expr class MatchSingleton(pattern): + __match_args__ = ("value",) value: Literal[True, False, None] class MatchSequence(pattern): + __match_args__ = ("patterns",) patterns: list[pattern] class MatchStar(pattern): + __match_args__ = ("name",) name: _identifier | None class MatchMapping(pattern): + __match_args__ = ("keys", "patterns", "rest") keys: list[expr] patterns: list[pattern] rest: _identifier | None class MatchClass(pattern): + __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") cls: expr patterns: list[pattern] kwd_attrs: list[_identifier] kwd_patterns: list[pattern] class MatchAs(pattern): + __match_args__ = ("pattern", "name") pattern: _pattern | None name: _identifier | None class MatchOr(pattern): + __match_args__ = ("patterns",) patterns: list[pattern] diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 470722a293a3..1781a2418ca0 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,12 +1,12 @@ import codecs import sys -from typing import Any, Callable, Union +from typing import Any, Callable # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: def size(self) -> int: ... -_MapT = Union[dict[int, int], _EncodingMap] +_MapT = dict[int, int] | _EncodingMap _Handler = Callable[[Exception], tuple[str, int]] def register(__search_function: Callable[[str], Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 7022097628fc..e193759bdc6e 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import SupportsRead -from typing import IO, Any, NamedTuple, Union, overload +from typing import IO, Any, NamedTuple, overload from typing_extensions import final if sys.platform != "win32": - _chtype = Union[str, bytes, int] + _chtype = str | bytes | int # ACS codes are only initialized after initscr is called ACS_BBSS: int diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index 6e936726a48f..97ba17ae497d 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -1,3 +1,4 @@ +from types import TracebackType from typing import Any, Callable, NoReturn TIMEOUT_MAX: int @@ -14,7 +15,7 @@ class LockType: def __init__(self) -> None: ... def acquire(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... def __enter__(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... - def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... def release(self) -> bool: ... def locked(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index f63bec448f90..1cbb8f1ee8c8 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,9 +1,9 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar +from typing import Any, Callable, Iterable, Mapping, TypeVar # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") @@ -80,8 +80,9 @@ class local: class Thread: name: str - ident: int | None daemon: bool + @property + def ident(self) -> int | None: ... def __init__( self, group: None = ..., @@ -183,9 +184,12 @@ class Timer(Thread): def cancel(self) -> None: ... class Barrier: - parties: int - n_waiting: int - broken: bool + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... def __init__(self, parties: int, action: Callable[[], None] | None = ..., timeout: float | None = ...) -> None: ... def wait(self, timeout: float | None = ...) -> int: ... def reset(self) -> None: ... diff --git a/mypy/typeshed/stdlib/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi index 23272591df4c..e2bbb9385ceb 100644 --- a/mypy/typeshed/stdlib/_imp.pyi +++ b/mypy/typeshed/stdlib/_imp.pyi @@ -7,7 +7,7 @@ if sys.version_info >= (3, 7): check_hash_based_pycs: str def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... -def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> None: ... +def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> types.ModuleType: ... def acquire_lock() -> None: ... def exec_builtin(__mod: types.ModuleType) -> int: ... def exec_dynamic(__mod: types.ModuleType) -> int: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 1395d69dab41..a8cf16823d4e 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable -from typing import Any, SupportsInt, Union, overload +from typing import Any, SupportsInt, overload if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -15,7 +15,7 @@ _CMSGArg = tuple[int, int, ReadableBuffer] # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[tuple[Any, ...], str] +_Address = tuple[Any, ...] | str _RetAddress = Any # TODO Most methods allow bytes as address objects diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 744799f1f66f..04abf8dc869c 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import structseq from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn, Optional -from typing_extensions import final +from typing import Any, Callable, NoReturn +from typing_extensions import Final, final error = RuntimeError @@ -33,9 +33,9 @@ TIMEOUT_MAX: float if sys.version_info >= (3, 8): def get_native_id() -> int: ... # only available on some platforms @final - class _ExceptHookArgs( - structseq[Any], tuple[type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]] - ): + class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") @property def exc_type(self) -> type[BaseException]: ... @property diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index 6dfe070dafac..c2cf55505afb 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any +from typing import Any, ClassVar from typing_extensions import Literal, final # _tkinter is meant to be only used internally by tkinter, but some tkinter @@ -19,7 +19,7 @@ from typing_extensions import Literal, final class Tcl_Obj: string: str | bytes typename: str - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] def __eq__(self, __other): ... def __ge__(self, __other): ... def __gt__(self, __other): ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 103af47c7524..b348a329522b 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -7,8 +7,8 @@ import ctypes import mmap import sys from os import PathLike -from typing import AbstractSet, Any, Container, Generic, Iterable, Protocol, TypeVar, Union -from typing_extensions import Final, Literal, final +from typing import AbstractSet, Any, Awaitable, Container, Generic, Iterable, Protocol, TypeVar +from typing_extensions import Final, Literal, TypeAlias, final _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -21,7 +21,14 @@ _T_contra = TypeVar("_T_contra", contravariant=True) # Use for "self" annotations: # def __enter__(self: Self) -> Self: ... -Self = TypeVar("Self") # noqa Y001 +Self = TypeVar("Self") # noqa: Y001 + +# For partially known annotations. Usually, fields where type annotations +# haven't been added are left unannotated, but in some situations this +# isn't possible or a type is already partially known. In cases like these, +# use Incomplete instead of Any as a marker. For example, use +# "Incomplete | None" instead of "Any | None". +Incomplete: TypeAlias = Any # stable class IdentityFunction(Protocol): @@ -33,7 +40,7 @@ class SupportsNext(Protocol[_T_co]): # stable class SupportsAnext(Protocol[_T_co]): - async def __anext__(self) -> _T_co: ... + def __anext__(self) -> Awaitable[_T_co]: ... # Comparison protocols @@ -51,7 +58,7 @@ class SupportsDunderGE(Protocol): class SupportsAllComparisons(SupportsDunderLT, SupportsDunderGT, SupportsDunderLE, SupportsDunderGE, Protocol): ... -SupportsRichComparison = Union[SupportsDunderLT, SupportsDunderGT] +SupportsRichComparison: TypeAlias = SupportsDunderLT | SupportsDunderGT SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 class SupportsDivMod(Protocol[_T_contra, _T_co]): @@ -88,9 +95,9 @@ class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, def __delitem__(self, __v: _KT_contra) -> None: ... # These aliases are simple strings in Python 2. -StrPath = Union[str, PathLike[str]] # stable -BytesPath = Union[bytes, PathLike[bytes]] # stable -StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable +StrPath: TypeAlias = str | PathLike[str] # stable +BytesPath: TypeAlias = bytes | PathLike[bytes] # stable +StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable OpenTextModeUpdating = Literal[ "r+", @@ -126,10 +133,10 @@ OpenTextModeUpdating = Literal[ "t+x", "+tx", ] -OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] -OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] -OpenBinaryModeUpdating = Literal[ +OpenTextModeWriting: TypeAlias = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] +OpenTextModeReading: TypeAlias = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] +OpenTextMode: TypeAlias = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading +OpenBinaryModeUpdating: TypeAlias = Literal[ "rb+", "r+b", "+rb", @@ -155,16 +162,16 @@ OpenBinaryModeUpdating = Literal[ "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] +OpenBinaryModeWriting: TypeAlias = Literal["wb", "bw", "ab", "ba", "xb", "bx"] +OpenBinaryModeReading: TypeAlias = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] +OpenBinaryMode: TypeAlias = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting # stable class HasFileno(Protocol): def fileno(self) -> int: ... -FileDescriptor = int # stable -FileDescriptorLike = Union[int, HasFileno] # stable +FileDescriptor: TypeAlias = int # stable +FileDescriptorLike: TypeAlias = int | HasFileno # stable # stable class SupportsRead(Protocol[_T_co]): @@ -182,13 +189,13 @@ class SupportsNoArgReadline(Protocol[_T_co]): class SupportsWrite(Protocol[_T_contra]): def write(self, __s: _T_contra) -> object: ... -ReadOnlyBuffer = bytes # stable +ReadOnlyBuffer: TypeAlias = bytes # stable # 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. -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, ctypes._CData] # stable +WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable # Same as _WriteableBuffer, but also includes read-only buffer types (like bytes). -ReadableBuffer = Union[ReadOnlyBuffer, WriteableBuffer] # stable +ReadableBuffer: TypeAlias = ReadOnlyBuffer | WriteableBuffer # stable # stable if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi index eee4fc03874e..022e95996bb3 100644 --- a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi @@ -3,11 +3,12 @@ from collections.abc import Mapping, Sequence from typing import Any, Protocol +from typing_extensions import TypeAlias -DBAPITypeCode = Any | None +DBAPITypeCode: TypeAlias = Any | None # Strictly speaking, this should be a Sequence, but the type system does # not support fixed-length sequences. -DBAPIColumnDescription = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] +DBAPIColumnDescription: TypeAlias = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] class DBAPIConnection(Protocol): def close(self) -> object: ... diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index 031d1472b6c5..9f036d8f2d33 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -4,6 +4,7 @@ from sys import _OptExcInfo from typing import Any, Callable, Iterable, Protocol +from typing_extensions import TypeAlias # stable class StartResponse(Protocol): @@ -11,8 +12,8 @@ class StartResponse(Protocol): self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... ) -> Callable[[bytes], Any]: ... -WSGIEnvironment = dict[str, Any] # stable -WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable +WSGIEnvironment: TypeAlias = dict[str, Any] # stable +WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable # WSGI input streams per PEP 3333, stable class InputStream(Protocol): diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index 8fc188980312..db3d8d991029 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, NamedTuple, Union, overload +from typing import IO, Any, NamedTuple, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -19,7 +19,7 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] _Marker = tuple[int, int, bytes] class Aifc_read: diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index a13052707178..69b4d35d9fe9 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, overload from typing_extensions import Literal, SupportsIndex _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _FloatTypeCode = Literal["f", "d"] _UnicodeTypeCode = Literal["u"] -_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] +_TypeCode = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, str) diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 1d52942bf6c5..71e4487baf99 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -8,12 +8,15 @@ from asyncio.tasks import Task from asyncio.transports import BaseTransport, ReadTransport, SubprocessTransport, WriteTransport from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 7): from contextvars import Context +if sys.version_info >= (3, 9): + __all__ = ("BaseEventLoop", "Server") +elif sys.version_info >= (3, 7): __all__ = ("BaseEventLoop",) else: __all__ = ["BaseEventLoop"] @@ -23,7 +26,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext class Server(AbstractServer): if sys.version_info >= (3, 7): @@ -100,7 +103,14 @@ class BaseEventLoop(AbstractEventLoop): def set_default_executor(self, executor: Any) -> None: ... # Network I/O methods returning Futures. async def getaddrinfo( - self, host: str | None, port: str | int | None, *, family: int = ..., type: int = ..., proto: int = ..., flags: int = ... + self, + host: bytes | str | None, + port: str | int | None, + *, + family: int = ..., + type: int = ..., + proto: int = ..., + flags: int = ..., ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index 94c7c01dd1bc..21c56bde1eac 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,10 +1,10 @@ import subprocess from collections import deque -from typing import IO, Any, Callable, Optional, Sequence, Union +from typing import IO, Any, Callable, Sequence from . import events, futures, protocols, transports -_File = Optional[Union[int, IO[Any]]] +_File = int | IO[Any] | None class BaseSubprocessTransport(transports.SubprocessTransport): diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 37079dc091e5..cc0391f92bc4 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload from typing_extensions import Literal from .base_events import Server @@ -78,7 +78,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext class Handle: _cancelled: bool @@ -123,7 +123,7 @@ class AbstractServer: def close(self) -> None: ... if sys.version_info >= (3, 7): async def __aenter__(self: Self) -> Self: ... - async def __aexit__(self, *exc: Any) -> None: ... + async def __aexit__(self, *exc: object) -> None: ... @abstractmethod def get_loop(self) -> AbstractEventLoop: ... @abstractmethod @@ -211,7 +211,14 @@ class AbstractEventLoop: # Network I/O methods returning Futures. @abstractmethod async def getaddrinfo( - self, host: str | None, port: str | int | None, *, family: int = ..., type: int = ..., proto: int = ..., flags: int = ... + self, + host: bytes | str | None, + port: str | int | None, + *, + family: int = ..., + type: int = ..., + proto: int = ..., + flags: int = ..., ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... @abstractmethod async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index bf4412264ced..5e483a578c3e 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -1,12 +1,12 @@ import functools import traceback from types import FrameType, FunctionType -from typing import Any, Iterable, Union, overload +from typing import Any, Iterable, overload class _HasWrapper: __wrapper__: _HasWrapper | FunctionType -_FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] +_FuncType = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] @overload def _get_function_source(func: _FuncType) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index d0edcbdcaeda..01b1c5b4591d 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -25,7 +25,7 @@ else: class _ContextManager: def __init__(self, lock: Lock | Semaphore) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... class _ContextManagerMixin: # Apparently this exists to *prohibit* use as a context manager. diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 2b0993ee03d7..98349222d5a2 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import Self, StrPath -from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional +from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Sequence from . import events, protocols, transports from .base_events import Server @@ -64,7 +64,7 @@ else: "start_unix_server", ] -_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] +_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] if sys.version_info < (3, 8): class IncompleteReadError(EOFError): @@ -87,7 +87,7 @@ if sys.version_info >= (3, 10): ) -> tuple[StreamReader, StreamWriter]: ... async def start_server( client_connected_cb: _ClientConnectedCallback, - host: str | None = ..., + host: str | Sequence[str] | None = ..., port: int | str | None = ..., *, limit: int = ..., diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index f2725a8992ae..3a617d6fb628 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -2,7 +2,7 @@ import subprocess import sys from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports -from typing import IO, Any, Callable, Union +from typing import IO, Any, Callable from typing_extensions import Literal if sys.version_info >= (3, 7): @@ -13,7 +13,7 @@ else: if sys.version_info >= (3, 8): _ExecArg = StrOrBytesPath else: - _ExecArg = Union[str, bytes] + _ExecArg = str | bytes PIPE: int STDOUT: int diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 140fc106bf42..885688065ddc 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -2,7 +2,7 @@ import concurrent.futures import sys from collections.abc import Awaitable, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Coroutine, Generic, Optional, TextIO, TypeVar, Union, overload +from typing import Any, Coroutine, Generic, TextIO, TypeVar, overload from typing_extensions import Literal from .events import AbstractEventLoop @@ -56,8 +56,8 @@ _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _FT = TypeVar("_FT", bound=Future[Any]) -_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] -_TaskYieldType = Optional[Future[object]] +_FutureT = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] +_TaskYieldType = Future[object] | None FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 5bbdadf8c269..3fe1e19d1311 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -2,12 +2,12 @@ import socket import sys from builtins import type as Type # alias to avoid name clashes with property named "type" from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, Union, overload +from typing import Any, BinaryIO, Iterable, NoReturn, overload # These are based in socket, maybe move them out into _typeshed.pyi or such -_Address = Union[tuple[Any, ...], str] +_Address = tuple[Any, ...] | str _RetAddress = Any -_WriteBuffer = Union[bytearray, memoryview] +_WriteBuffer = bytearray | memoryview _CMSG = tuple[int, int, bytes] class TransportSocket: diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index b8c569b10cd4..78d87dc4e9e9 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -11,7 +11,7 @@ from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy, _ProtocolFact from .selector_events import BaseSelectorEventLoop # This is also technically not available on Win, -# but other parts of typeshed need this defintion. +# but other parts of typeshed need this definition. # So, it is special cased. class AbstractChildWatcher: @abstractmethod diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index 35a44be509af..1156f905659e 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -31,7 +31,7 @@ if sys.platform == "win32": def __del__(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: type | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... @property def handle(self) -> int: ... def fileno(self) -> int: ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index e531ccd508bf..db002503c75f 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Union +from typing import IO, Any from typing_extensions import Literal __all__ = ["binhex", "hexbin", "Error"] @@ -16,7 +16,7 @@ class FInfo: Flags: int _FileInfoTuple = tuple[str, FInfo, int, int] -_FileHandleUnion = Union[str, IO[bytes]] +_FileHandleUnion = str | IO[bytes] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 9ce6959a1abf..ce2042bcac63 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -29,8 +29,10 @@ from typing import ( IO, AbstractSet, Any, + Awaitable, BinaryIO, ByteString, + ClassVar, Generic, Iterable, Iterator, @@ -72,6 +74,8 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _SupportsNextT = TypeVar("_SupportsNextT", bound=SupportsNext[Any], covariant=True) _SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant=True) +_AwaitableT = TypeVar("_AwaitableT", bound=Awaitable[Any]) +_AwaitableT_co = TypeVar("_AwaitableT_co", bound=Awaitable[Any], covariant=True) class _SupportsIter(Protocol[_T_co]): def __iter__(self) -> _T_co: ... @@ -97,8 +101,8 @@ class object: def __delattr__(self, __name: str) -> None: ... def __eq__(self, __o: object) -> bool: ... def __ne__(self, __o: object) -> bool: ... - def __str__(self) -> str: ... # noqa Y029 - def __repr__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 def __hash__(self) -> int: ... def __format__(self, __format_spec: str) -> str: ... def __getattribute__(self, __name: str) -> Any: ... @@ -653,7 +657,7 @@ class bytearray(MutableSequence[int], ByteString): def maketrans(__frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @overload @@ -780,7 +784,7 @@ class slice: def __init__(self, __stop: Any) -> None: ... @overload def __init__(self, __start: Any, __stop: Any, __step: Any = ...) -> None: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): @@ -851,7 +855,7 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> _T: ... @overload @@ -911,7 +915,7 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def pop(self, __key: _KT) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... def __len__(self) -> int: ... def __getitem__(self, __k: _KT) -> _VT: ... def __setitem__(self, __k: _KT, __v: _VT) -> None: ... @@ -919,7 +923,7 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_KT]: ... - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... @@ -962,7 +966,7 @@ class set(MutableSet[_T], Generic[_T]): 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[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @@ -1068,8 +1072,15 @@ class _PathLike(Protocol[_AnyStr_co]): if sys.version_info >= (3, 10): def aiter(__async_iterable: _SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... + + class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): + def __anext__(self) -> _AwaitableT_co: ... + @overload - async def anext(__i: SupportsAnext[_T]) -> _T: ... + # `anext` is not, in fact, an async function. When default is not provided + # `anext` is just a passthrough for `obj.__anext__` + # See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 + def anext(__i: _SupportsSynchronousAnext[_AwaitableT]) -> _AwaitableT: ... @overload async def anext(__i: SupportsAnext[_T], default: _VT) -> _T | _VT: ... @@ -1252,7 +1263,7 @@ def next(__i: SupportsNext[_T]) -> _T: ... def next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ... def oct(__number: int | SupportsIndex) -> str: ... -_OpenFile = Union[StrOrBytesPath, int] +_OpenFile = StrOrBytesPath | int _Opener = Callable[[str, int], int] # Text mode: always returns a TextIOWrapper @@ -1371,7 +1382,7 @@ class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): class _SupportsPow3(Protocol[_E, _M, _T_co]): def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... -_SupportsSomeKindOfPow = Union[_SupportsPow2[Any, Any], _SupportsPow3NoneOnly[Any, Any], _SupportsPow3[Any, Any, Any]] +_SupportsSomeKindOfPow = _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] if sys.version_info >= (3, 8): @overload @@ -1467,17 +1478,22 @@ def sorted( @overload def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ... +class _SupportsSum(Protocol): + def __add__(self, __x: Any) -> Any: ... + +_SumT = TypeVar("_SumT", bound=_SupportsSum) +_SumS = TypeVar("_SumS", bound=_SupportsSum) + +@overload +def sum(__iterable: Iterable[_SumT]) -> _SumT | Literal[0]: ... + if sys.version_info >= (3, 8): @overload - def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... - @overload - def sum(__iterable: Iterable[_T], start: _S) -> _T | _S: ... + def sum(__iterable: Iterable[_SumT], start: _SumS) -> _SumT | _SumS: ... else: @overload - def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... - @overload - def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... + def sum(__iterable: Iterable[_SumT], __start: _SumS) -> _SumT | _SumS: ... # The argument to `vars()` has to have a `__dict__` attribute, so can't be annotated with `object` # (A "SupportsDunderDict" protocol doesn't work) diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index edaa67109952..6f15e461e007 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -31,6 +31,6 @@ class Profile: def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... if sys.version_info >= (3, 8): def __enter__(self: Self) -> Self: ... - def __exit__(self, *exc_info: Any) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index 17b59b9bc2c9..05ceca4a3ae0 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -1,7 +1,7 @@ import datetime import sys +from collections.abc import Iterable, Sequence from time import struct_time -from typing import Any, Iterable, Optional, Sequence from typing_extensions import Literal __all__ = [ @@ -31,7 +31,7 @@ __all__ = [ "weekheader", ] -_LocaleType = tuple[Optional[str], Optional[str]] +_LocaleType = tuple[str | None, str | None] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... @@ -106,7 +106,7 @@ class HTMLCalendar(Calendar): class different_locale: def __init__(self, locale: _LocaleType) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... class LocaleTextCalendar(TextCalendar): def __init__(self, firstweekday: int = ..., locale: _LocaleType | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 1c11beec0c35..0bd4e515ce51 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -127,7 +127,7 @@ class FieldStorage: separator: str = ..., ) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... def getvalue(self, key: str, default: Any = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index fb9d69161d5b..2db108ce75ec 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,8 +1,8 @@ from _typeshed import StrOrBytesPath from types import FrameType, TracebackType -from typing import IO, Any, Callable, Optional +from typing import IO, Any, Callable -_ExcInfo = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_ExcInfo = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] __UNDEF__: object # undocumented sentinel diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 04c2b632d411..ee51861fdaa0 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,5 +1,5 @@ import sys -from typing import SupportsComplex, SupportsFloat, Union +from typing import SupportsComplex, SupportsFloat if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -13,9 +13,9 @@ nanj: complex tau: float if sys.version_info >= (3, 8): - _C = Union[SupportsFloat, SupportsComplex, SupportsIndex, complex] + _C = SupportsFloat | SupportsComplex | SupportsIndex | complex else: - _C = Union[SupportsFloat, SupportsComplex, complex] + _C = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index cf822fc557a2..4967d01f90dc 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -4,6 +4,7 @@ from _typeshed import Self from abc import abstractmethod from collections.abc import Container, Iterable, Iterator, Sequence from logging import Logger +from types import TracebackType from typing import Any, Callable, Generic, Protocol, TypeVar, overload from typing_extensions import Literal, ParamSpec, SupportsIndex @@ -73,12 +74,16 @@ class Executor: def shutdown(self, wait: bool = ...) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool | None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... def as_completed(fs: Iterable[Future[_T]], timeout: float | None = ...) -> Iterator[Future[_T]]: ... # Ideally this would be a namedtuple, but mypy doesn't support generic tuple types. See #1976 class DoneAndNotDoneFutures(Sequence[set[Future[_T]]]): + if sys.version_info >= (3, 10): + __match_args__ = ("done", "not_done") @property def done(self) -> set[Future[_T]]: ... @property @@ -125,4 +130,4 @@ class _AcquireFutures: futures: Iterable[Future[Any]] def __init__(self, futures: Iterable[Future[Any]]) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index 6b043263775c..55df2ce58de7 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, ClassVar, Optional, Pattern, TypeVar, overload +from typing import Any, ClassVar, Pattern, TypeVar, overload from typing_extensions import Literal __all__ = [ @@ -205,7 +205,7 @@ class SectionProxy(MutableMapping[str, str]): # SectionProxy can have arbitrary attributes when custom converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... -class ConverterMapping(MutableMapping[str, Optional[_converter]]): +class ConverterMapping(MutableMapping[str, _converter | None]): GETTERCRE: Pattern[Any] def __init__(self, parser: RawConfigParser) -> None: ... def __getitem__(self, key: str) -> _converter: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index c2731dea7807..a60f8811e0ac 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import ( # noqa Y027 +from typing import ( # noqa: Y027 IO, Any, AsyncGenerator, @@ -12,7 +12,6 @@ from typing import ( # noqa Y027 Generator, Generic, Iterator, - Optional, Protocol, TypeVar, overload, @@ -81,17 +80,17 @@ else: AbstractContextManager = ContextManager if sys.version_info >= (3, 7): - from typing import AsyncContextManager # noqa Y022 + from typing import AsyncContextManager # noqa: Y022 AbstractAsyncContextManager = AsyncContextManager _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) +_T_io = TypeVar("_T_io", bound=IO[str] | None) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], Optional[bool]] +_ExitFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) class ContextDecorator: @@ -155,7 +154,7 @@ class closing(AbstractContextManager[_SupportsCloseT]): if sys.version_info >= (3, 10): class _SupportsAclose(Protocol): - async def aclose(self) -> object: ... + def aclose(self) -> Awaitable[object]: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): @@ -190,7 +189,7 @@ class ExitStack(AbstractContextManager[ExitStack]): ) -> bool: ... if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] + _ExitCoroFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): @@ -218,9 +217,9 @@ if sys.version_info >= (3, 10): @overload def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Any) -> None: ... + def __exit__(self, *exctype: object) -> None: ... async def __aenter__(self) -> _T: ... - async def __aexit__(self, *exctype: Any) -> None: ... + async def __aexit__(self, *exctype: object) -> None: ... elif sys.version_info >= (3, 7): class nullcontext(AbstractContextManager[_T]): @@ -230,7 +229,7 @@ elif sys.version_info >= (3, 7): @overload def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Any) -> None: ... + def __exit__(self, *exctype: object) -> None: ... if sys.version_info >= (3, 11): _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=int | StrOrBytesPath) diff --git a/mypy/typeshed/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index 8ac3e87ef3fe..4844a8028c5c 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,7 +1,7 @@ -from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union +from typing import Any, Callable, Hashable, SupportsInt, TypeVar, Union _T = TypeVar("_T") -_Reduce = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Any | None]] __all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index d4caa7a88d76..4a03886e8dd2 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -1,20 +1,7 @@ import sys from _typeshed import ReadableBuffer, Self, WriteableBuffer from abc import abstractmethod -from typing import ( - Any, - Callable, - ClassVar, - Generic, - Iterable, - Iterator, - Mapping, - Optional, - Sequence, - TypeVar, - Union as _UnionT, - overload, -) +from typing import Any, Callable, ClassVar, Generic, Iterable, Iterator, Mapping, Sequence, TypeVar, Union as _UnionT, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -97,7 +84,7 @@ class _CData(metaclass=_CDataMeta): class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CData] +_ECT = Callable[[type[_CData] | None, _FuncPointer, tuple[_CData, ...]], _CData] _PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): @@ -134,12 +121,12 @@ 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] +_CVoidPLike = _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] +_CVoidConstPLike = _CVoidPLike | bytes def addressof(obj: _CData) -> int: ... def alignment(obj_or_type: _CData | type[_CData]) -> int: ... @@ -208,7 +195,7 @@ class c_byte(_SimpleCData[int]): ... class c_char(_SimpleCData[bytes]): def __init__(self, value: int | bytes = ...) -> None: ... -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): def __init__(self, value: int | bytes | None = ...) -> None: ... class c_double(_SimpleCData[float]): ... @@ -233,10 +220,10 @@ 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_void_p(_PointerLike, _SimpleCData[int | None]): ... class c_wchar(_SimpleCData[str]): ... -class c_wchar_p(_PointerLike, _SimpleCData[Optional[str]]): +class c_wchar_p(_PointerLike, _SimpleCData[str | None]): def __init__(self, value: int | str | None = ...) -> None: ... class c_bool(_SimpleCData[bool]): diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index f8e4044932ed..d82e9a2bb526 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -65,11 +65,20 @@ def astuple(obj: Any) -> tuple[Any, ...]: ... @overload def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... -if sys.version_info >= (3, 10): +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]]: ... + +else: + @overload + def dataclass(_cls: type[_T]) -> type[_T]: ... + @overload + def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ... + +if sys.version_info >= (3, 10): @overload def dataclass( *, @@ -84,22 +93,7 @@ if sys.version_info >= (3, 10): slots: bool = ..., ) -> Callable[[type[_T]], type[_T]]: ... -elif 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 = ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index df33fb88f37e..18a4d2dd2856 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -65,7 +65,12 @@ class date: def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... - def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... + if sys.version_info >= (3, 6): + def replace(self: Self, year: int = ..., month: int = ..., day: int = ...) -> Self: ... + else: + # Prior to Python 3.6, the `replace` method always returned `date`, even in subclasses + 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: ... @@ -139,16 +144,29 @@ class time: def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def replace( - self, - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., - *, - fold: int = ..., - ) -> time: ... + if sys.version_info >= (3, 6): + def replace( + self: Self, + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + *, + fold: int = ..., + ) -> Self: ... + else: + # Prior to Python 3.6, the `replace` method always returned `time`, even in subclasses + def replace( + self, + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + *, + fold: int = ..., + ) -> time: ... _date = date _time = time @@ -260,19 +278,35 @@ class datetime(date): def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... - def replace( - self, - year: int = ..., - month: int = ..., - day: int = ..., - hour: int = ..., - minute: int = ..., - second: int = ..., - microsecond: int = ..., - tzinfo: _tzinfo | None = ..., - *, - fold: int = ..., - ) -> datetime: ... + if sys.version_info >= (3, 6): + def replace( + self: Self, + year: int = ..., + month: int = ..., + day: int = ..., + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + *, + fold: int = ..., + ) -> Self: ... + else: + # Prior to Python 3.6, the `replace` method always returned `datetime`, even in subclasses + def replace( + self, + year: int = ..., + month: int = ..., + day: int = ..., + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + *, + fold: int = ..., + ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: Self, tz: _tzinfo | None = ...) -> Self: ... else: diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 630a0d16c1c7..d43a2415caff 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,12 +1,12 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping from typing_extensions import Literal __all__ = ["open", "whichdb", "error"] -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes _TFlags = Literal[ "r", "w", diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index c877ef8593d8..5af95ace72ad 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,11 +1,11 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping __all__ = ["error", "open"] -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes error = OSError diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index b0e657d6ae4b..9a603228a691 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = Union[str, bytes] - _ValueType = Union[str, bytes] + _KeyType = str | bytes + _ValueType = str | bytes open_flags: str diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index 336720c79f37..8405bec2bcf2 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = Union[str, bytes] - _ValueType = Union[str, bytes] + _KeyType = str | bytes + _ValueType = str | bytes class error(OSError): ... library: str diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index dfd0670e474e..819ed1641448 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -4,9 +4,9 @@ from _typeshed import Self from types import TracebackType from typing import Any, Container, NamedTuple, Sequence, Union, overload -_Decimal = Union[Decimal, int] +_Decimal = Decimal | int _DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float, numbers.Rational] +_ComparableNum = Decimal | float | numbers.Rational __libmpdec_version__: str diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index dcb82cb7aefc..910458c08e00 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -2,7 +2,7 @@ import sys import types from _typeshed import Self from opcode import * # `dis` re-exports it as a part of public API -from typing import IO, Any, Callable, Iterator, NamedTuple, Union +from typing import IO, Any, Callable, Iterator, NamedTuple __all__ = [ "code_info", @@ -34,8 +34,8 @@ __all__ = [ # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_HaveCodeOrStringType = Union[_HaveCodeType, str, bytes] +_HaveCodeType = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_HaveCodeOrStringType = _HaveCodeType | str | bytes class Instruction(NamedTuple): opname: str diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index 7c7023ed0b65..4cdc62ce3bae 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -1,6 +1,6 @@ -from typing import Any, Callable, Optional, Union +from typing import Any, Callable, Union -_Macro = Union[tuple[str], tuple[str, Optional[str]]] +_Macro = Union[tuple[str], tuple[str, str | None]] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index dce8394b6289..c2a5bd4c20a1 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,6 +1,6 @@ -from typing import Any, Iterable, Mapping, Optional, overload +from typing import Any, Iterable, Mapping, overload -_Option = tuple[str, Optional[str], str] +_Option = tuple[str, str | None, str] _GR = tuple[list[str], OptionDummy] def fancy_getopt( diff --git a/mypy/typeshed/stdlib/distutils/version.pyi b/mypy/typeshed/stdlib/distutils/version.pyi index 210aa5cf718b..8745e8c9f680 100644 --- a/mypy/typeshed/stdlib/distutils/version.pyi +++ b/mypy/typeshed/stdlib/distutils/version.pyi @@ -23,7 +23,7 @@ class StrictVersion(Version): prerelease: tuple[str, int] | None def __init__(self, vstring: str | None = ...) -> None: ... def parse(self: Self, vstring: str) -> Self: ... - def __str__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 def _cmp(self: Self, other: Self | str) -> bool: ... class LooseVersion(Version): @@ -32,5 +32,5 @@ class LooseVersion(Version): version: tuple[str | int, ...] def __init__(self, vstring: str | None = ...) -> None: ... def parse(self: Self, vstring: str) -> Self: ... - def __str__(self) -> str: ... # noqa Y029 + def __str__(self) -> str: ... # noqa: Y029 def _cmp(self: Self, other: Self | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index e2c22554a092..49e18ccb8c2e 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -1,6 +1,11 @@ from email.message import Message from email.policy import Policy -from typing import IO, Callable +from typing import IO, Callable, TypeVar, Union + +# Definitions imported by multiple submodules in typeshed +_MessageT = TypeVar("_MessageT", bound=Message) # noqa: Y018 +_ParamType = Union[str, tuple[str | None, str | None, str]] +_ParamsType = Union[str, None, tuple[str, str | None, str]] 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/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index 18d5f1b9ac22..749b6454a8f8 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, Pattern, Union +from typing import Any, Iterable, Iterator, Pattern from typing_extensions import Final WSP: Final[set[str]] @@ -22,7 +22,7 @@ def quote_string(value: Any) -> str: ... if sys.version_info >= (3, 7): rfc2047_matcher: Pattern[str] -class TokenList(list[Union[TokenList, Terminal]]): +class TokenList(list[TokenList | Terminal]): token_type: str | None syntactic_break: bool ew_combine_allowed: bool diff --git a/mypy/typeshed/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi index fd27a7242649..b1c7e0f7d127 100644 --- a/mypy/typeshed/stdlib/email/feedparser.pyi +++ b/mypy/typeshed/stdlib/email/feedparser.pyi @@ -1,23 +1,22 @@ +from email import _MessageT from email.message import Message from email.policy import Policy -from typing import Callable, Generic, TypeVar, overload +from typing import Callable, Generic, overload __all__ = ["FeedParser", "BytesFeedParser"] -_M = TypeVar("_M", bound=Message) - -class FeedParser(Generic[_M]): +class FeedParser(Generic[_MessageT]): @overload def __init__(self: FeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... @overload - def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy = ...) -> None: ... def feed(self, data: str) -> None: ... - def close(self) -> _M: ... + def close(self) -> _MessageT: ... -class BytesFeedParser(Generic[_M]): +class BytesFeedParser(Generic[_MessageT]): @overload def __init__(self: BytesFeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... @overload - def __init__(self, _factory: Callable[[], _M], *, policy: Policy = ...) -> None: ... + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy = ...) -> None: ... def feed(self, data: bytes) -> None: ... - def close(self) -> _M: ... + def close(self) -> _MessageT: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 9e140d4f273d..97de1cf5daf6 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -1,16 +1,16 @@ +from email import _ParamsType, _ParamType from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy +from typing import Any, Generator, Iterator, Sequence, TypeVar -from typing import Any, Generator, Iterator, Optional, Sequence, TypeVar, Union +__all__ = ["Message", "EmailMessage"] _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]] +_PayloadType = list[Message] | str | bytes +_CharsetType = Charset | str | None _HeaderType = Any class Message: diff --git a/mypy/typeshed/stdlib/email/mime/application.pyi b/mypy/typeshed/stdlib/email/mime/application.pyi index 978324c03863..4966a17d9471 100644 --- a/mypy/typeshed/stdlib/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/email/mime/application.pyi @@ -1,11 +1,10 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Union __all__ = ["MIMEApplication"] -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] - class MIMEApplication(MIMENonMultipart): def __init__( self, diff --git a/mypy/typeshed/stdlib/email/mime/audio.pyi b/mypy/typeshed/stdlib/email/mime/audio.pyi index aa7b9ceb2dea..fd107d7fcbc6 100644 --- a/mypy/typeshed/stdlib/email/mime/audio.pyi +++ b/mypy/typeshed/stdlib/email/mime/audio.pyi @@ -1,11 +1,10 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Union __all__ = ["MIMEAudio"] -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] - class MIMEAudio(MIMENonMultipart): def __init__( self, diff --git a/mypy/typeshed/stdlib/email/mime/base.pyi b/mypy/typeshed/stdlib/email/mime/base.pyi index faa561fcb3a1..c8f2fe6db79d 100644 --- a/mypy/typeshed/stdlib/email/mime/base.pyi +++ b/mypy/typeshed/stdlib/email/mime/base.pyi @@ -1,10 +1,8 @@ import email.message +from email import _ParamsType from email.policy import Policy -from typing import Optional, Union __all__ = ["MIMEBase"] -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] - class MIMEBase(email.message.Message): def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = ..., **_params: _ParamsType) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/image.pyi b/mypy/typeshed/stdlib/email/mime/image.pyi index 4e767e6aa6d8..480f6dcab34b 100644 --- a/mypy/typeshed/stdlib/email/mime/image.pyi +++ b/mypy/typeshed/stdlib/email/mime/image.pyi @@ -1,11 +1,10 @@ +from collections.abc import Callable +from email import _ParamsType from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Union __all__ = ["MIMEImage"] -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] - class MIMEImage(MIMENonMultipart): def __init__( self, diff --git a/mypy/typeshed/stdlib/email/mime/multipart.pyi b/mypy/typeshed/stdlib/email/mime/multipart.pyi index 3b70d5875661..6cd480ccf0a4 100644 --- a/mypy/typeshed/stdlib/email/mime/multipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/multipart.pyi @@ -1,12 +1,11 @@ +from collections.abc import Sequence +from email import _ParamsType from email.message import Message from email.mime.base import MIMEBase from email.policy import Policy -from typing import Optional, Sequence, Union __all__ = ["MIMEMultipart"] -_ParamsType = Union[str, None, tuple[str, Optional[str], str]] - class MIMEMultipart(MIMEBase): def __init__( self, diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index bbc5d0124b3a..1846bdcc36b2 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,14 +1,13 @@ import email.feedparser +from email import _MessageT from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO, TypeVar +from typing import BinaryIO, Callable, TextIO __all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] -_M = TypeVar("_M", bound=Message) - -FeedParser = email.feedparser.FeedParser[_M] -BytesFeedParser = email.feedparser.BytesFeedParser[_M] +FeedParser = email.feedparser.FeedParser[_MessageT] +BytesFeedParser = email.feedparser.BytesFeedParser[_MessageT] class Parser: def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 2b7f1bab3ce0..aeffb0ef1981 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -1,7 +1,8 @@ import datetime import sys +from email import _ParamType from email.charset import Charset -from typing import Optional, Union, overload +from typing import overload __all__ = [ "collapse_rfc2231_value", @@ -21,8 +22,7 @@ __all__ = [ "unquote", ] -_ParamType = Union[str, tuple[Optional[str], Optional[str], str]] -_PDTZ = tuple[int, int, int, int, int, int, int, int, int, Optional[int]] +_PDTZ = tuple[int, int, int, int, int, int, int, int, int, int | None] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 077a2f423e49..f49bcd7a00e0 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -4,7 +4,7 @@ from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping -from typing import Any, TypeVar, Union, overload +from typing import Any, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 11): @@ -52,7 +52,7 @@ _EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) # # >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) # -_EnumNames = Union[str, Iterable[str], Iterable[Iterable[Union[str, Any]]], Mapping[str, Any]] +_EnumNames = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... @@ -95,11 +95,11 @@ class EnumMeta(ABCMeta): def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ... def __len__(self) -> int: ... def __bool__(self) -> Literal[True]: ... + # Simple value lookup + @overload # type: ignore[override] + def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... + # Functional Enum API if sys.version_info >= (3, 11): - # Simple value lookup - @overload # type: ignore[override] - def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... - # Functional Enum API @overload def __call__( cls, @@ -113,8 +113,6 @@ class EnumMeta(ABCMeta): boundary: FlagBoundary | None = ..., ) -> type[Enum]: ... else: - @overload # type: ignore[override] - def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... @overload def __call__( cls, diff --git a/mypy/typeshed/stdlib/errno.pyi b/mypy/typeshed/stdlib/errno.pyi index 5180b5940eae..12410af23e71 100644 --- a/mypy/typeshed/stdlib/errno.pyi +++ b/mypy/typeshed/stdlib/errno.pyi @@ -37,7 +37,6 @@ EPIPE: int EDOM: int ERANGE: int EDEADLK: int -EDEADLCK: int ENAMETOOLONG: int ENOLCK: int ENOSYS: int @@ -136,3 +135,24 @@ ENOMEDIUM: int # undocumented ENOTRECOVERABLE: int # undocumented EOWNERDEAD: int # undocumented ERFKILL: int # undocumented +EAUTH: int # undocumented +EBADARCH: int # undocumented +EBADEXEC: int # undocumented +EBADMACHO: int # undocumented +EBADRPC: int # undocumented +EDEVERR: int # undocumented +EFTYPE: int # undocumented +EL: int # undocumented +ELOCKUNMAPPED: int # undocumented +ENEEDAUTH: int # undocumented +ENOATTR: int # undocumented +ENOPOLICY: int # undocumented +ENOTACTIVE: int # undocumented +EPROCLIM: int # undocumented +EPROCUNAVAIL: int # undocumented +EPROGMISMATCH: int # undocumented +EPROGUNAVAIL: int # undocumented +EPWROFF: int # undocumented +EQFULL: int # undocumented +ERPCMISMATCH: int # undocumented +ESHLIBVERS: int # undocumented diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 787f75b8950a..a3b62948ca20 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,5 +1,6 @@ import sys from _typeshed import Self, StrOrBytesPath +from types import TracebackType from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator __all__ = [ @@ -98,7 +99,9 @@ class FileInput(Iterator[AnyStr], Generic[AnyStr]): def __del__(self) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> AnyStr: ... if sys.version_info < (3, 11): diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index ecbfb07e1dfd..00989fb1fc02 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -2,10 +2,10 @@ import sys from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal -_ComparableNum = Union[int, float, Decimal, Real] +_ComparableNum = int | float | Decimal | Real if sys.version_info >= (3, 9): __all__ = ["Fraction"] diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index 732c36b3dda7..4b66b84b6389 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -1,11 +1,13 @@ import sys from _typeshed import structseq -from typing import Any, Optional -from typing_extensions import final +from typing import Any +from typing_extensions import Final, final if sys.platform != "win32": @final - class struct_group(structseq[Any], tuple[str, Optional[str], int, list[str]]): + class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") @property def gr_name(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index fbb0397ac40b..6d355147f51e 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -1,11 +1,11 @@ import sys from _typeshed import ReadableBuffer from types import ModuleType -from typing import Any, AnyStr, Callable, Union, overload +from typing import Any, AnyStr, Callable, overload # TODO more precise type for object of hashlib _Hash = Any -_DigestMod = Union[str, Callable[[], _Hash], ModuleType] +_DigestMod = str | Callable[[], _Hash] | ModuleType trans_5C: bytes trans_36: bytes diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 93f132d678f9..801a195c9fb3 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -5,7 +5,7 @@ import sys import types from _typeshed import Self, WriteableBuffer from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, Union, overload +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, overload __all__ = [ "HTTPResponse", @@ -29,7 +29,7 @@ __all__ = [ "HTTPSConnection", ] -_DataType = Union[bytes, IO[Any], Iterable[bytes], str] +_DataType = bytes | IO[Any] | Iterable[bytes] | str _T = TypeVar("_T") HTTP_PORT: int @@ -100,7 +100,7 @@ class HTTPMessage(email.message.Message): def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... -class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes +class HTTPResponse(io.BufferedIOBase, BinaryIO): msg: HTTPMessage headers: HTTPMessage version: int @@ -130,7 +130,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore # argument disp def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> bool | None: ... + ) -> None: ... def info(self) -> email.message.Message: ... def geturl(self) -> str: ... def getcode(self) -> int: ... diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index 5e01e603781d..2cc05961a303 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,12 +1,12 @@ import sys -from typing import Any, Generic, Iterable, Mapping, TypeVar, Union, overload +from typing import Any, Generic, Iterable, Mapping, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] -_DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] +_DataType = str | Mapping[str, str | Morsel[Any]] _T = TypeVar("_T") @overload diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index e85e7d4ad90a..ab6490cea570 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -5,7 +5,7 @@ from _typeshed import Self from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, Pattern, Union +from typing import IO, Any, Callable, Pattern from typing_extensions import Literal __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] @@ -14,7 +14,7 @@ __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags" # E.g. Tuple[Literal["OK"], List[bytes]] _CommandResults = tuple[str, list[Any]] -_AnyResponseData = Union[list[None], list[Union[bytes, tuple[bytes, bytes]]]] +_AnyResponseData = list[None] | list[bytes | tuple[bytes, bytes]] _list = list # conflicts with a method named "list" diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index ec09d18de32c..3054a4465f99 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -1,6 +1,7 @@ import types from _typeshed import StrPath from os import PathLike +from types import TracebackType from typing import IO, Any, Protocol from _imp import ( @@ -45,7 +46,7 @@ class _FileLike(Protocol): def read(self) -> str | bytes: ... def close(self) -> Any: ... def __enter__(self) -> Any: ... - def __exit__(self, *args: Any) -> Any: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> Any: ... # PathLike doesn't work for the pathname argument here def load_source(name: str, pathname: str, file: _FileLike | None = ...) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 16f514a74eb5..877f8ff1a65c 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -12,10 +12,10 @@ from _typeshed import ( from abc import ABCMeta, abstractmethod from importlib.machinery import ModuleSpec from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, Union, overload, runtime_checkable +from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, overload, runtime_checkable from typing_extensions import Literal -_Path = Union[bytes, str] +_Path = bytes | str class Finder(metaclass=ABCMeta): ... diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index 7efe287f7205..f15ac48af5c5 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -133,10 +133,10 @@ class FileFinder(importlib.abc.PathEntryFinder): cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... -class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): # type: ignore # argument disparities +class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): def set_data(self, path: importlib.abc._Path, data: bytes, *, _mode: int = ...) -> None: ... -class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... # type: ignore # argument disparities +class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... class ExtensionFileLoader(importlib.abc.ExecutionLoader): def __init__(self, name: str, path: importlib.abc._Path) -> None: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index cee3259332ff..e6e3035e5dac 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -3,7 +3,7 @@ import sys from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, Iterator, TextIO, Union +from typing import Any, BinaryIO, Iterator, TextIO if sys.version_info >= (3, 10): __all__ = [ @@ -37,8 +37,8 @@ elif sys.version_info >= (3, 9): else: __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] -Package = Union[str, ModuleType] -Resource = Union[str, os.PathLike[Any]] +Package = str | ModuleType +Resource = str | os.PathLike[Any] def open_binary(package: Package, resource: Resource) -> BinaryIO: ... def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index c32691edb686..ef4789251cc3 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -72,7 +72,7 @@ class IOBase: def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... + ) -> None: ... def close(self) -> None: ... def fileno(self) -> int: ... def flush(self) -> None: ... @@ -108,7 +108,7 @@ class BufferedIOBase(IOBase): def read(self, __size: int | None = ...) -> bytes: ... def read1(self, __size: int = ...) -> bytes: ... -class FileIO(RawIOBase, BinaryIO): # type: ignore # argument disparities between the base classes +class FileIO(RawIOBase, BinaryIO): mode: str name: StrOrBytesPath | int # type: ignore[assignment] def __init__( @@ -120,7 +120,7 @@ class FileIO(RawIOBase, BinaryIO): # type: ignore # argument disparities betwee def read(self, __size: int = ...) -> bytes: ... def __enter__(self: Self) -> Self: ... -class BytesIO(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between the base classes +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 @@ -134,7 +134,7 @@ class BytesIO(BufferedIOBase, BinaryIO): # type: ignore # argument disparities else: def read1(self, __size: int | None) -> bytes: ... # type: ignore[override] -class BufferedReader(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes +class BufferedReader(BufferedIOBase, BinaryIO): def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def peek(self, __size: int = ...) -> bytes: ... @@ -143,7 +143,7 @@ class BufferedReader(BufferedIOBase, BinaryIO): # type: ignore # argument dispa else: def read1(self, __size: int) -> bytes: ... # type: ignore[override] -class BufferedWriter(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes +class BufferedWriter(BufferedIOBase, BinaryIO): def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def write(self, __buffer: ReadableBuffer) -> int: ... @@ -175,7 +175,7 @@ class TextIOBase(IOBase): def read(self, __size: int | None = ...) -> str: ... def tell(self) -> int: ... -class TextIOWrapper(TextIOBase, TextIO): # type: ignore # argument disparities between base classes +class TextIOWrapper(TextIOBase, TextIO): def __init__( self, buffer: IO[bytes], diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 35765712202a..bec03b1876ac 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,18 +1,6 @@ import sys from _typeshed import Self, _T_co -from typing import ( - Any, - Callable, - Generic, - Iterable, - Iterator, - SupportsComplex, - SupportsFloat, - SupportsInt, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, Generic, Iterable, Iterator, SupportsComplex, SupportsFloat, SupportsInt, TypeVar, overload from typing_extensions import Literal, SupportsIndex if sys.version_info >= (3, 9): @@ -21,7 +9,7 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) -_Step = Union[int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex] +_Step = int | float | SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex Predicate = Callable[[_T], object] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index 3c3b90c52f7c..b5836e1b90c5 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,7 +1,6 @@ from _typeshed import Self, StrPath -from typing import Optional -_Label = tuple[int, Optional[str]] +_Label = tuple[int, str | None] _DFA = list[list[tuple[int, int]]] _DFAS = tuple[_DFA, dict[int, int]] diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index b0e61c3a38ac..68e5d8ba1323 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,11 +1,11 @@ from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, Union +from typing import Any, Callable, Iterator -_NL = Union[Node, Leaf] +_NL = Node | Leaf _Context = tuple[str, int, int] _Results = dict[str, _NL] -_RawNode = tuple[int, str, _Context, Optional[list[_NL]]] +_RawNode = tuple[int, str, _Context, list[_NL] | None] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index 899bf0000a2c..e5227beca149 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -32,7 +32,7 @@ __all__ = [ # as a type annotation or type alias. from builtins import str as _str from decimal import Decimal -from typing import Any, Callable, Iterable, Mapping, Sequence +from typing import Any, Callable, Iterable, Mapping CODESET: int D_T_FMT: int @@ -107,11 +107,11 @@ CHAR_MAX: int class Error(Exception): ... -def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... +def setlocale(category: int, locale: _str | Iterable[_str | None] | None = ...) -> _str: ... def localeconv() -> Mapping[_str, int | _str | list[int]]: ... def nl_langinfo(__key: int) -> _str: ... def getdefaultlocale(envvars: tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... -def getlocale(category: int = ...) -> Sequence[_str]: ... +def getlocale(category: int = ...) -> tuple[_str | None, _str | None]: ... def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... def normalize(localename: _str) -> _str: ... def resetlocale(category: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index c860938c31ea..8de4d0d88260 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -6,7 +6,7 @@ from io import TextIOWrapper from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, TypeVar, Union, overload +from typing import Any, ClassVar, Generic, Pattern, TextIO, TypeVar, Union, overload from typing_extensions import Literal __all__ = [ @@ -54,11 +54,11 @@ __all__ = [ "raiseExceptions", ] -_SysExcInfoType = Union[tuple[type[BaseException], BaseException, Optional[TracebackType]], tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] -_ArgsType = Union[tuple[object, ...], Mapping[str, object]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, str] +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, TracebackType | None], tuple[None, None, None]] +_ExcInfoType = None | bool | _SysExcInfoType | BaseException +_ArgsType = tuple[object, ...] | Mapping[str, object] +_FilterType = Filter | Callable[[LogRecord], int] +_Level = int | str _FormatStyle = Literal["%", "{", "$"] raiseExceptions: bool diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 06cddd94fc69..640236149000 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -78,7 +78,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): when: str # undocumented backupCount: int # undocumented utc: bool # undocumented - atTime: datetime.datetime | None # undocumented + atTime: datetime.time | None # undocumented interval: int # undocumented suffix: str # undocumented dayOfWeek: int # undocumented @@ -94,7 +94,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): encoding: str | None = ..., delay: bool = ..., utc: bool = ..., - atTime: datetime.datetime | None = ..., + atTime: datetime.time | None = ..., errors: str | None = ..., ) -> None: ... else: @@ -107,7 +107,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): encoding: str | None = ..., delay: bool = ..., utc: bool = ..., - atTime: datetime.datetime | None = ..., + atTime: datetime.time | None = ..., ) -> None: ... def doRollover(self) -> None: ... diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index c469c218abcb..45bf24b3ef6d 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,6 +1,6 @@ import io from _typeshed import ReadableBuffer, Self, StrOrBytesPath -from typing import IO, Any, Mapping, Sequence, TextIO, Union, overload +from typing import IO, Any, Mapping, Sequence, TextIO, overload from typing_extensions import Literal, final __all__ = [ @@ -45,7 +45,7 @@ __all__ = [ _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] _OpenTextWritingMode = Literal["wt", "xt", "at"] -_PathOrFile = Union[StrOrBytesPath, IO[bytes]] +_PathOrFile = StrOrBytesPath | IO[bytes] _FilterChain = Sequence[Mapping[str, Any]] diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 3fafd8891840..143891d3240b 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import Self, StrOrBytesPath from abc import ABCMeta, abstractmethod from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -31,7 +31,7 @@ __all__ = [ _T = TypeVar("_T") _MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] +_MessageData = email.message.Message | bytes | str | IO[str] | IO[bytes] class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... diff --git a/mypy/typeshed/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index 7bf2ebd1bdfe..232ab99c314d 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Mapping, Sequence, Union +from typing import Mapping, Sequence -_Cap = dict[str, Union[str, int]] +_Cap = dict[str, str | int] __all__ = ["getcaps", "findmatch"] diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index 2218f68174d1..e4ab311990be 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import SupportsTrunc -from typing import Iterable, SupportsFloat, Union, overload +from typing import Iterable, SupportsFloat, overload from typing_extensions import SupportsIndex if sys.version_info >= (3, 8): - _SupportsFloatOrIndex = Union[SupportsFloat, SupportsIndex] + _SupportsFloatOrIndex = SupportsFloat | SupportsIndex else: _SupportsFloatOrIndex = SupportsFloat diff --git a/mypy/typeshed/stdlib/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi index 87dff754009d..30346aba3367 100644 --- a/mypy/typeshed/stdlib/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/msilib/sequence.pyi @@ -1,9 +1,8 @@ import sys -from typing import Optional if sys.platform == "win32": - _SequenceType = list[tuple[str, Optional[str], int]] + _SequenceType = list[tuple[str, str | None, int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 3f489ca43dba..3a8a382b8a27 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -20,7 +20,7 @@ from multiprocessing.process import active_children as active_children, current_ # multiprocessing.queues or the aliases defined below. See #4266 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal if sys.version_info >= (3, 8): @@ -134,7 +134,7 @@ _SemaphoreType = synchronize.Semaphore # be identical (modulo self). # Synchronization primitives -_LockLike = Union[synchronize.Lock, synchronize.RLock] +_LockLike = synchronize.Lock | synchronize.RLock RawValue = context._default_context.RawValue RawArray = context._default_context.RawArray Value = context._default_context.Value diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index db8e6216b6ad..315918a04b98 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -8,7 +8,7 @@ from multiprocessing import queues, synchronize from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, ClassVar, TypeVar, Union, overload +from typing import Any, ClassVar, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 8): @@ -16,7 +16,7 @@ if sys.version_info >= (3, 8): else: __all__: list[str] = [] -_LockLike = Union[synchronize.Lock, synchronize.RLock] +_LockLike = synchronize.Lock | synchronize.RLock _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index fef3e1e21eb2..a0f76b636c4b 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -96,7 +96,9 @@ class BaseManager: create_method: bool = ..., ) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: type[BaseException], exc_val: BaseException, exc_tb: TracebackType) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... # Conflicts with method names _dict = dict diff --git a/mypy/typeshed/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi index f4464c08c9bd..1601decbbebc 100644 --- a/mypy/typeshed/stdlib/multiprocessing/process.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/process.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, Mapping +from collections.abc import Callable, Iterable, Mapping +from typing import Any if sys.version_info >= (3, 8): __all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] @@ -16,7 +17,7 @@ class BaseProcess: group: None = ..., target: Callable[..., Any] | None = ..., name: str | None = ..., - args: tuple[Any, ...] = ..., + args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ..., *, daemon: bool | None = ..., diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi index 50d5a3d71973..8b1b1c1cee6e 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -3,6 +3,7 @@ from collections.abc import Callable, Iterable, Sequence from ctypes import _CData, _SimpleCData, c_char from multiprocessing.context import BaseContext from multiprocessing.synchronize import _LockLike +from types import TracebackType from typing import Any, Generic, Protocol, TypeVar, overload from typing_extensions import Literal @@ -82,7 +83,9 @@ class SynchronizedBase(Generic[_CT]): def get_obj(self) -> _CT: ... def get_lock(self) -> _LockLike: ... def __enter__(self) -> bool: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__( + self, __exc_type: type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None + ) -> None: ... class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): value: _T diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index cb576abcc815..0cfc815b2d82 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -3,11 +3,11 @@ import threading from contextlib import AbstractContextManager from multiprocessing.context import BaseContext from types import TracebackType -from typing import Any, Callable, Union +from typing import Any, Callable __all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] -_LockLike = Union[Lock, RLock] +_LockLike = Lock | RLock class Barrier(threading.Barrier): def __init__( diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index b1c3f5ec5024..45f6cfbeda7b 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,5 +1,4 @@ from _typeshed import StrOrBytesPath -from typing import Optional __all__ = ["netrc", "NetrcParseError"] @@ -10,7 +9,7 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: StrOrBytesPath | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = tuple[str, Optional[str], Optional[str]] +_NetrcTuple = tuple[str, str | None, str | None] class netrc: hosts: dict[str, _NetrcTuple] diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 77cab1e154e8..cc48cb83ae4c 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -3,7 +3,7 @@ import socket import ssl import sys from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple, Union +from typing import IO, Any, Iterable, NamedTuple from typing_extensions import Literal __all__ = [ @@ -18,7 +18,7 @@ __all__ = [ "NNTP_SSL", ] -_File = Union[IO[bytes], bytes, str, None] +_File = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str @@ -73,7 +73,7 @@ class NNTP: timeout: float = ..., ) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def getwelcome(self) -> str: ... def getcapabilities(self) -> dict[str, _list[str]]: ... def set_debuglevel(self, level: int) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 615dff880689..2ef781bbe288 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -32,11 +32,10 @@ from typing import ( Protocol, Sequence, TypeVar, - Union, overload, runtime_checkable, ) -from typing_extensions import Literal, final +from typing_extensions import Final, Literal, final from . import path as _path @@ -315,6 +314,8 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. # # More items may be added at the end by some implementations. + if sys.version_info >= (3, 10): + __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") @property def st_mode(self) -> int: ... # protection bits, @property @@ -382,7 +383,7 @@ def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... -_FdOrAnyPath = Union[int, StrOrBytesPath] +_FdOrAnyPath = int | StrOrBytesPath @final class DirEntry(Generic[AnyStr]): @@ -409,6 +410,19 @@ else: @final class statvfs_result(structseq[int], _StatVfsTuple): + if sys.version_info >= (3, 10): + __match_args__: Final = ( + "f_bsize", + "f_frsize", + "f_blocks", + "f_bfree", + "f_bavail", + "f_files", + "f_ffree", + "f_favail", + "f_flag", + "f_namemax", + ) @property def f_bsize(self) -> int: ... @property @@ -450,6 +464,8 @@ def strerror(__code: int) -> str: ... def umask(__mask: int) -> int: ... @final class uname_result(structseq[str], tuple[str, str, str, str, str]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") @property def sysname(self) -> str: ... @property @@ -655,6 +671,8 @@ if sys.platform != "win32": @final class terminal_size(structseq[int], tuple[int, int]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("columns", "lines") @property def columns(self) -> int: ... @property @@ -733,20 +751,15 @@ class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_Scand def __exit__(self, *args: object) -> None: ... def close(self) -> None: ... +@overload +def scandir(path: None = ...) -> _ScandirIterator[str]: ... + if sys.version_info >= (3, 7): - @overload - def scandir(path: None = ...) -> _ScandirIterator[str]: ... @overload def scandir(path: int) -> _ScandirIterator[str]: ... - @overload - def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... - -else: - @overload - def scandir(path: None = ...) -> _ScandirIterator[str]: ... - @overload - def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... +@overload +def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... def stat(path: _FdOrAnyPath, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> stat_result: ... if sys.version_info < (3, 7): @@ -832,17 +845,17 @@ def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoRetur # 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[StrOrBytesPath, ...], - 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]]] +_ExecVArgs = ( + tuple[StrOrBytesPath, ...] + | list[bytes] + | list[str] + | list[PathLike[Any]] + | list[bytes | str] + | list[bytes | PathLike[Any]] + | list[str | PathLike[Any]] + | list[bytes | str | PathLike[Any]] +) +_ExecEnv = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... def execve(path: _FdOrAnyPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... @@ -879,6 +892,8 @@ else: def system(command: StrOrBytesPath) -> int: ... @final class times_result(structseq[float], tuple[float, float, float, float, float]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") @property def user(self) -> float: ... @property @@ -905,6 +920,8 @@ else: if sys.platform != "darwin": @final class waitid_result(structseq[int], tuple[int, int, int, int, int]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") @property def si_pid(self) -> int: ... @property @@ -962,6 +979,8 @@ else: if sys.platform != "win32": @final class sched_param(structseq[int], tuple[int]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("sched_priority",) def __new__(cls: type[Self], sched_priority: int) -> Self: ... @property def sched_priority(self) -> int: ... @@ -1006,7 +1025,7 @@ if sys.version_info >= (3, 8): def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], Any]) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def add_dll_directory(path: str) -> _AddedDllDirectory: ... if sys.platform == "linux": diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index d48d3ead75c5..26ee94ca2682 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Union +from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Protocol, Union from typing_extensions import final if sys.version_info >= (3, 8): @@ -189,7 +189,7 @@ if sys.version_info >= (3, 8): def __init__(self, buffer: Any) -> None: ... def raw(self) -> memoryview: ... def release(self) -> None: ... - _BufferCallback = Optional[Callable[[PickleBuffer], Any]] + _BufferCallback = Callable[[PickleBuffer], Any] | None def dump( obj: Any, file: _WritableFileobj, @@ -227,8 +227,8 @@ _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]]], + tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None], + tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None], ] class Pickler: diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 607c6b371507..7c27f6702a7e 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import SupportsRead from importlib.abc import Loader, MetaPathFinder, PathEntryFinder -from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple +from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple, TypeVar __all__ = [ "get_importer", @@ -18,12 +18,14 @@ __all__ = [ "ModuleInfo", ] +_PathT = TypeVar("_PathT", bound=Iterable[str]) + class ModuleInfo(NamedTuple): module_finder: MetaPathFinder | PathEntryFinder name: str ispkg: bool -def extend_path(path: list[str], name: str) -> list[str]: ... +def extend_path(path: _PathT, name: str) -> _PathT: ... class ImpImporter: def __init__(self, path: str | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index c4fe28477fb5..a7b8bebe4066 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self, StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Union, overload +from typing import IO, Any, Iterable, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -12,7 +12,7 @@ elif sys.version_info >= (3, 7): else: __all__ = ["Stats"] -_Selector = Union[str, float, int] +_Selector = str | float | int if sys.version_info >= (3, 7): from enum import Enum diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 84f6dc5ccf91..80813479d7af 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -1,11 +1,13 @@ import sys from _typeshed import structseq from typing import Any -from typing_extensions import final +from typing_extensions import Final, final if sys.platform != "win32": @final class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") @property def pw_name(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 5aca55c2b813..24c93965b21f 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,7 +1,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Optional +from typing import Any, Callable from typing_extensions import final EXPAT_VERSION: str # undocumented @@ -20,7 +20,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = tuple[int, int, Optional[str], tuple[Any, ...]] +_Model = tuple[int, int, str | None, tuple[Any, ...]] @final class XMLParserType: diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 16aa31a0f742..612a54cb95b0 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -90,9 +90,11 @@ class Random(_random.Random): k: int = ..., ) -> list[_T]: ... def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 11): + def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = ...) -> list[_T]: ... + elif sys.version_info >= (3, 9): def sample( - self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ... + self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = ... ) -> list[_T]: ... else: def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int) -> list[_T]: ... diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index b9c41e1caa16..57dab8eb820f 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -2,7 +2,7 @@ import enum import sre_compile import sys from sre_constants import error as error -from typing import Any, AnyStr, Callable, Iterator, Union, overload +from typing import Any, AnyStr, Callable, Iterator, overload # ----- re variables and constants ----- if sys.version_info >= (3, 7): @@ -147,7 +147,7 @@ T = RegexFlag.T TEMPLATE = RegexFlag.TEMPLATE if sys.version_info >= (3, 11): NOFLAG = RegexFlag.NOFLAG -_FlagsType = Union[int, RegexFlag] +_FlagsType = int | RegexFlag if sys.version_info < (3, 7): # undocumented diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 427f4995ecfd..f2e979ff89af 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import structseq from typing import overload -from typing_extensions import final +from typing_extensions import Final, final if sys.platform != "win32": RLIMIT_AS: int @@ -29,6 +29,25 @@ if sys.platform != "win32": class struct_rusage( structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] ): + if sys.version_info >= (3, 10): + __match_args__: Final = ( + "ru_utime", + "ru_stime", + "ru_maxrss", + "ru_ixrss", + "ru_idrss", + "ru_isrss", + "ru_minflt", + "ru_majflt", + "ru_nswap", + "ru_inblock", + "ru_oublock", + "ru_msgsnd", + "ru_msgrcv", + "ru_nsignals", + "ru_nvcsw", + "ru_nivcsw", + ) @property def ru_utime(self) -> float: ... @property diff --git a/mypy/typeshed/stdlib/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi index 05e0ec65dc49..256f8dab14e9 100644 --- a/mypy/typeshed/stdlib/runpy.pyi +++ b/mypy/typeshed/stdlib/runpy.pyi @@ -9,13 +9,13 @@ class _TempModule: module: ModuleType def __init__(self, mod_name: str) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... class _ModifiedArgv0: value: Any def __init__(self, value: Any) -> None: ... def __enter__(self) -> None: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def run_module( mod_name: str, init_globals: dict[str, Any] | None = ..., run_name: str | None = ..., alter_sys: bool = ... diff --git a/mypy/typeshed/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi index c3fe7ec47ace..23a94a29a74d 100644 --- a/mypy/typeshed/stdlib/selectors.pyi +++ b/mypy/typeshed/stdlib/selectors.pyi @@ -27,7 +27,7 @@ class BaseSelector(metaclass=ABCMeta): @abstractmethod def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... class SelectSelector(BaseSelector): def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = ...) -> SelectorKey: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 030f16cd99b7..5fa5f6669f1b 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,7 +1,7 @@ import os import sys from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, overload __all__ = [ "copyfileobj", @@ -82,7 +82,7 @@ else: def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... -_CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] +_CopyFn = Callable[[str, str], None] | Callable[[StrPath, StrPath], None] # N.B. shutil.move appears to take bytes arguments, however, # this does not work when dst is (or is within) an existing directory. diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 50f1e0ff0cf1..2defe7995991 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import structseq from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Optional, Union -from typing_extensions import final +from typing import Any, Callable, Iterable, Union +from typing_extensions import Final, final NSIG: int @@ -60,8 +60,8 @@ class Handlers(IntEnum): SIG_DFL: Handlers SIG_IGN: Handlers -_SIGNUM = Union[int, Signals] -_HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] +_SIGNUM = int | Signals +_HANDLER = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] def default_int_handler(__signalnum: int, __frame: FrameType | None) -> None: ... @@ -148,6 +148,8 @@ else: SIGRTMIN: Signals @final class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") @property def si_signo(self) -> int: ... @property diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 5bf95d2eec8c..3136667dcd11 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -4,7 +4,7 @@ from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Pattern, Protocol, Sequence, Union, overload +from typing import Any, Pattern, Protocol, Sequence, overload if sys.version_info >= (3, 7): __all__ = [ @@ -43,7 +43,7 @@ else: _Reply = tuple[int, bytes] _SendErrs = dict[str, _Reply] # Should match source_address for socket.create_connection -_SourceAddress = tuple[Union[bytearray, bytes, str], int] +_SourceAddress = tuple[bytearray | bytes | str, int] SMTP_PORT: int SMTP_SSL_PORT: int diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 461ea41406c8..7801940f8564 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -619,10 +619,5 @@ if sys.version_info >= (3, 8): # the 5th tuple item is an address def getaddrinfo( - host: bytearray | bytes | str | None, - port: str | int | None, - family: int = ..., - type: int = ..., - proto: int = ..., - flags: int = ..., + host: bytes | str | None, port: str | int | None, family: int = ..., type: int = ..., proto: int = ..., flags: int = ... ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 82d9b8dbfffc..27b1061e1b0e 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -1,11 +1,23 @@ import sys from _typeshed import structseq from typing import Any -from typing_extensions import final +from typing_extensions import Final, final if sys.platform != "win32": @final class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): + if sys.version_info >= (3, 10): + __match_args__: Final = ( + "sp_namp", + "sp_pwdp", + "sp_lstchg", + "sp_min", + "sp_max", + "sp_warn", + "sp_inact", + "sp_expire", + "sp_flag", + ) @property def sp_namp(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 456c94362a8e..05e5a176d8ff 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from datetime import date, datetime, time +from types import TracebackType from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, TypeVar from typing_extensions import Literal, final @@ -183,7 +184,9 @@ class Connection: def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, __type: type | None, __value: BaseException | None, __traceback: Any | None) -> Literal[False]: ... + def __exit__( + self, __type: type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None + ) -> Literal[False]: ... class Cursor(Iterator[Any]): arraysize: Any diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index 56d551180f5f..05e71c255967 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -1,7 +1,7 @@ import sys from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union, overload +from typing import Any, Iterable, Match, Pattern as _Pattern, overload SPECIAL_CHARS: str REPEAT_CHARS: str @@ -37,11 +37,11 @@ if sys.version_info >= (3, 8): else: Pattern = _State -_OpSubpatternType = tuple[Optional[int], int, int, SubPattern] +_OpSubpatternType = tuple[int | None, 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] +_AvType = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType _CodeType = tuple[_NIC, _AvType] class SubPattern: @@ -87,8 +87,8 @@ class Tokenizer: def fix_flags(src: str | bytes, flags: int) -> int: ... -_TemplateType = tuple[list[tuple[int, int]], list[Optional[str]]] -_TemplateByteType = tuple[list[tuple[int, int]], list[Optional[bytes]]] +_TemplateType = tuple[list[tuple[int, int]], list[str | None]] +_TemplateByteType = tuple[list[tuple[int, int]], list[bytes | None]] if sys.version_info >= (3, 8): def parse(str: str, flags: int = ..., state: State | None = ...) -> SubPattern: ... @overload diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 83932e5790c4..b7fe6914db0e 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -2,17 +2,17 @@ import enum import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, Iterable, NamedTuple, Optional, Union, overload +from typing import Any, Callable, Iterable, NamedTuple, Union, overload from typing_extensions import Literal, TypedDict, final _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] +_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType = _PeerCertRetDictType | bytes | None +_EnumRetType = list[tuple[bytes, str, set[str] | bool]] +_PasswordType = Union[Callable[[], str | bytes], str, bytes] -_SrvnmeCbType = Callable[[Union[SSLSocket, SSLObject], Optional[str], SSLSocket], Optional[int]] +_SrvnmeCbType = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] class _Cipher(TypedDict): aead: bool diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 879ea3c74ec7..446a778794f1 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self, SupportsRichComparisonT from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar, Union +from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar from typing_extensions import Literal if sys.version_info >= (3, 10): @@ -65,7 +65,7 @@ else: ] # Most functions in this module accept homogeneous collections of one of these types -_Number = Union[float, Decimal, Fraction] +_Number = float | Decimal | Fraction _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index a0e446d19c8e..ced2e708f8ff 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -102,18 +102,18 @@ else: # 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] +_FILE = None | int | IO[Any] +_TXT = bytes | str if sys.version_info >= (3, 8): - _CMD = Union[StrOrBytesPath, Sequence[StrOrBytesPath]] + _CMD = StrOrBytesPath | Sequence[StrOrBytesPath] else: # Python 3.6 doesn't support _CMD being a single PathLike. # See: https://bugs.python.org/issue31961 - _CMD = Union[_TXT, Sequence[StrOrBytesPath]] + _CMD = _TXT | Sequence[StrOrBytesPath] if sys.platform == "win32": _ENV = Mapping[str, str] else: - _ENV = Union[Mapping[bytes, StrOrBytesPath], Mapping[str, StrOrBytesPath]] + _ENV = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index f96dbaaf7be8..73aa8999caa1 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import Self -from typing import IO, Any, NamedTuple, NoReturn, Union, overload +from typing import IO, Any, NamedTuple, NoReturn, overload from typing_extensions import Literal -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... @@ -33,7 +33,7 @@ class _sunau_params(NamedTuple): class Au_read: def __init__(self, f: _File) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def getfp(self) -> IO[bytes] | None: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -53,7 +53,7 @@ class Au_read: class Au_write: def __init__(self, f: _File) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 89b636cd08af..4fca35a2c82d 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -5,20 +5,7 @@ from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import ( - Any, - AsyncGenerator, - Callable, - Coroutine, - NoReturn, - Optional, - Protocol, - Sequence, - TextIO, - TypeVar, - Union, - overload, -) +from typing import Any, AsyncGenerator, Callable, Coroutine, NoReturn, Protocol, Sequence, TextIO, TypeVar, Union, overload from typing_extensions import Literal, final _T = TypeVar("_T") @@ -255,7 +242,7 @@ _ProfileFunc = Callable[[FrameType, str, Any], Any] def getprofile() -> _ProfileFunc | None: ... def setprofile(profilefunc: _ProfileFunc | None) -> None: ... -_TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] +_TraceFunc = Callable[[FrameType, str, Any], Callable[[FrameType, str, Any], Any] | None] def gettrace() -> _TraceFunc | None: ... def settrace(tracefunc: _TraceFunc | None) -> None: ... @@ -322,7 +309,7 @@ if sys.version_info >= (3, 8): def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... -_AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] +_AsyncgenHook = Callable[[AsyncGenerator[Any, Any]], None] | None @final class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index f522d206550d..359be6e49781 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -1,5 +1,6 @@ import socket from _typeshed import Self +from types import TracebackType from typing import Any, Callable, Match, Pattern, Sequence __all__ = ["Telnet"] @@ -113,4 +114,6 @@ class Telnet: self, list: Sequence[Pattern[bytes] | bytes], timeout: float | None = ... ) -> tuple[int, Match[bytes] | None, bytes]: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 3821c002c542..19a4dbee2ee7 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -2,7 +2,7 @@ import os import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Union, overload +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -29,7 +29,7 @@ TMP_MAX: int tempdir: str | None template: str -_DirT = Union[AnyStr, os.PathLike[AnyStr]] +_DirT = AnyStr | os.PathLike[AnyStr] if sys.version_info >= (3, 8): @overload @@ -185,7 +185,7 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): delete: bool def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: ... # These methods don't exist directly on this object, but diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index 6ef2f6818827..c6a90df31b59 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Union +from typing import Any if sys.platform != "win32": - _Attr = list[Union[int, list[Union[bytes, int]]]] + _Attr = list[int | list[bytes | int]] # TODO constants not really documented B0: int diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index d6a64d0aefb5..c3fa57fafa7c 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,9 +1,9 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar +from typing import Any, Callable, Iterable, Mapping, TypeVar # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index c1a8727b1ea0..25f8d7056cd8 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import structseq -from typing import Any, Protocol, Union -from typing_extensions import Literal, final +from typing import Any, Protocol +from typing_extensions import Final, Literal, final _TimeTuple = tuple[int, int, int, int, int, int, int, int, int] @@ -37,7 +37,9 @@ if sys.version_info >= (3, 9) and sys.platform == "linux": # even if an iterable with length >9 is passed. # https://github.com/python/typeshed/pull/6560#discussion_r767162532 @final -class struct_time(structseq[Union[Any, int]], _TimeTuple): +class struct_time(structseq[Any | int], _TimeTuple): + if sys.version_info >= (3, 10): + __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") @property def tm_year(self) -> int: ... @property diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index 3135c21a6022..bfaea728ff42 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, Callable, Sequence, Union +from typing import IO, Any, Callable, Sequence __all__ = ["Timer", "timeit", "repeat", "default_timer"] _Timer = Callable[[], float] -_Stmt = Union[str, Callable[[], Any]] +_Stmt = str | Callable[[], Any] default_timer: _Timer diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 2393b0e5be49..2a6172ba46a3 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -5,7 +5,7 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Callable, Generic, Mapping, Optional, Protocol, Sequence, TypeVar, Union, overload +from typing import Any, Callable, Generic, Mapping, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 9): @@ -173,16 +173,16 @@ EXCEPTION = _tkinter.EXCEPTION # 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]] # accepts string of tcl code, return value is returned from Button.invoke() +_ButtonCommand = str | Callable[[], Any] # accepts string of tcl code, return value is returned from Button.invoke() _CanvasItemId = int _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, list[str], tuple[str, ...] -] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] -_GridIndex = Union[int, str, Literal["all"]] -_ImageSpec = Union[_Image, str] # str can be from e.g. tkinter.image_names() +_EntryValidateCommand = ( + str | list[str] | tuple[str, ...] | Callable[[], bool] +) # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] +_GridIndex = int | str | Literal["all"] +_ImageSpec = _Image | str # str can be from e.g. tkinter.image_names() _Padding = Union[ _ScreenUnits, tuple[_ScreenUnits], @@ -191,9 +191,9 @@ _Padding = Union[ tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], ] _Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief -_ScreenUnits = Union[str, float] # Often the right type instead of int. 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' +_ScreenUnits = str | float # Often the right type instead of int. Manual page: Tk_GetPixels +_XYScrollCommand = str | Callable[[float, float], Any] # -xscrollcommand and -yscrollcommand in 'options' manual page +_TakeFocusValue = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' class EventType(str, Enum): Activate: str @@ -1696,7 +1696,7 @@ class Checkbutton(Widget): def select(self) -> None: ... def toggle(self) -> None: ... -_EntryIndex = Union[str, int] # "INDICES" in manual page +_EntryIndex = str | int # "INDICES" in manual page class Entry(Widget, XView): def __init__( @@ -2054,7 +2054,7 @@ class Listbox(Widget, XView, YView): def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... itemconfig: Any -_MenuIndex = Union[str, int] +_MenuIndex = str | int class Menu(Widget): def __init__( @@ -2740,7 +2740,7 @@ class Scrollbar(Widget): def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... def set(self, first: float, last: float) -> None: ... -_TextIndex = Union[_tkinter.Tcl_Obj, str, float, Misc] +_TextIndex = _tkinter.Tcl_Obj | str | float | Misc class Text(Widget, XView, YView): def __init__( diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index e16f325b589a..4b0101b32788 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -1,7 +1,7 @@ import _tkinter import sys import tkinter -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 9): @@ -12,17 +12,13 @@ ROMAN: Literal["roman"] BOLD: Literal["bold"] ITALIC: Literal["italic"] -_FontDescription = Union[ - # "Helvetica 12" - str, - # A font object constructed in Python - Font, - # ("Helvetica", 12, BOLD) - list[Any], - tuple[Any, ...], - # A font object constructed in Tcl - _tkinter.Tcl_Obj, -] +_FontDescription = ( + str # "Helvetica 12" + | Font # A font object constructed in Python + | list[Any] # ("Helvetica", 12, BOLD) + | tuple[Any, ...] + | _tkinter.Tcl_Obj # A font object constructed in Tcl +) class _FontDict(TypedDict): family: str diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 41a5b64c5c35..c48b5cd7aa0d 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -2,7 +2,7 @@ import _tkinter import sys import tkinter from tkinter.font import _FontDescription -from typing import Any, Callable, Union, overload +from typing import Any, Callable, overload from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 7): @@ -972,7 +972,7 @@ class _TreeviewColumnDict(TypedDict): anchor: tkinter._Anchor id: str -_TreeviewColumnId = Union[int, str] # manual page: "COLUMN IDENTIFIERS" +_TreeviewColumnId = int | str # manual page: "COLUMN IDENTIFIERS" class Treeview(Widget, tkinter.XView, tkinter.YView): def __init__( diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index e8f64a7d0702..7b17e8de6153 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open from token import * -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Union +from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO if sys.version_info >= (3, 10): __all__ = [ @@ -331,7 +331,7 @@ class TokenInfo(_TokenInfo): def exact_type(self) -> int: ... # Backwards compatible tokens can be sequences of a shorter length too -_Token = Union[TokenInfo, Sequence[Union[int, str, _Position]]] +_Token = TokenInfo | Sequence[int | str | _Position] class TokenError(Exception): ... class StopTokenizing(Exception): ... # undocumented diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 640b014594a2..6128064478bc 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -1,7 +1,7 @@ import sys import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar +from typing import Any, Callable, Mapping, Sequence, TypeVar from typing_extensions import ParamSpec __all__ = ["Trace", "CoverageResults"] @@ -9,7 +9,7 @@ __all__ = ["Trace", "CoverageResults"] _T = TypeVar("_T") _P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = tuple[str, Optional[str], str] +_fileModuleFunction = tuple[str, str | None, str] class CoverageResults: def __init__( diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 4df5c10077bf..859bfef64622 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, Mapping, Optional, overload +from typing import IO, Any, Generator, Iterable, Iterator, Mapping, overload from typing_extensions import Literal __all__ = [ @@ -26,7 +26,7 @@ __all__ = [ "walk_tb", ] -_PT = tuple[str, int, str, Optional[str]] +_PT = tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index cebf0f7a8b08..e2e6800cbab4 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,6 +1,6 @@ import sys from _tracemalloc import * -from typing import Any, Optional, Sequence, Union, overload +from typing import Any, Sequence, Union, overload from typing_extensions import SupportsIndex def get_object_traceback(obj: object) -> Traceback | None: ... @@ -61,7 +61,7 @@ class Frame: def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... if sys.version_info >= (3, 9): - _TraceTupleT = Union[tuple[int, int, Sequence[_FrameTupleT], Optional[int]], tuple[int, int, Sequence[_FrameTupleT]]] + _TraceTupleT = Union[tuple[int, int, Sequence[_FrameTupleT], int | None], tuple[int, int, Sequence[_FrameTupleT]]] else: _TraceTupleT = tuple[int, int, Sequence[_FrameTupleT]] diff --git a/mypy/typeshed/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi index 015669a68084..63f594a8fbb1 100644 --- a/mypy/typeshed/stdlib/tty.pyi +++ b/mypy/typeshed/stdlib/tty.pyi @@ -1,8 +1,8 @@ import sys -from typing import IO, Union +from typing import IO if sys.platform != "win32": - _FD = Union[int, IO[str]] + _FD = int | IO[str] # XXX: Undocumented integer constants IFLAG: int diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index 164ea461399b..2ff965465be6 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -137,7 +137,7 @@ _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. _PenState = dict[str, Any] -_Speed = Union[str, float] +_Speed = str | float _PolygonCoords = Sequence[tuple[float, float]] # TODO: Type this more accurately diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 510f8d9eb551..9b2fa1f4a2aa 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -7,6 +7,7 @@ from typing import ( AsyncGenerator, Awaitable, Callable, + ClassVar, Coroutine, Generator, Generic, @@ -178,7 +179,7 @@ _V_co = TypeVar("_V_co", covariant=True) @final class _Cell: - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] cell_contents: Any # Make sure this class definition stays roughly in line with `builtins.function` @@ -199,6 +200,7 @@ class FunctionType: @property def __builtins__(self) -> dict[str, Any]: ... + __module__: str def __init__( self, code: CodeType, @@ -340,7 +342,7 @@ class CodeType: @final class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] def __init__(self, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> None: ... def __getitem__(self, __k: _KT) -> _VT_co: ... def __iter__(self) -> Iterator[_KT]: ... @@ -356,7 +358,7 @@ class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... class SimpleNamespace: - __hash__: None # type: ignore[assignment] + __hash__: ClassVar[None] # type: ignore[assignment] def __init__(self, **kwargs: Any) -> None: ... def __getattribute__(self, __name: str) -> Any: ... def __setattr__(self, __name: str, __value: Any) -> None: ... @@ -658,10 +660,10 @@ if sys.version_info >= (3, 10): @final class NoneType: def __bool__(self) -> Literal[False]: ... - EllipsisType = ellipsis # noqa F811 from builtins + EllipsisType = ellipsis # noqa: F821 from builtins from builtins import _NotImplementedType - NotImplementedType = _NotImplementedType # noqa F811 from builtins + NotImplementedType = _NotImplementedType @final class UnionType: @property diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 295bfa8d1137..4ad3ab3da274 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -28,7 +28,9 @@ if sys.version_info >= (3, 11): "Tuple", "Type", "TypeVar", + "TypeVarTuple", "Union", + "Unpack", "AbstractSet", "ByteString", "Container", @@ -80,6 +82,7 @@ if sys.version_info >= (3, 11): "TextIO", "AnyStr", "assert_never", + "assert_type", "cast", "final", "get_args", @@ -524,6 +527,12 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 11): Self: _SpecialForm Never: _SpecialForm = ... + Unpack: _SpecialForm + + class TypeVarTuple: + __name__: str + def __init__(self, name: str) -> None: ... + def __iter__(self) -> Any: ... if sys.version_info < (3, 7): class GenericMeta(type): ... @@ -554,14 +563,14 @@ if sys.version_info >= (3, 10): TypeGuard: _SpecialForm class NewType: - def __init__(self, name: str, tp: type) -> None: ... + def __init__(self, name: str, tp: Any) -> None: ... def __call__(self, x: _T) -> _T: ... def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... __supertype__: type else: - def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + def NewType(name: str, tp: Any) -> Any: ... # These type variables are used by the container types. _S = TypeVar("_S") @@ -743,26 +752,22 @@ class AsyncIterable(Protocol[_T_co]): @runtime_checkable class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): @abstractmethod - async def __anext__(self) -> _T_co: ... + def __anext__(self) -> Awaitable[_T_co]: ... def __aiter__(self) -> AsyncIterator[_T_co]: ... class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): + def __anext__(self) -> Awaitable[_T_co]: ... @abstractmethod - async def __anext__(self) -> _T_co: ... - @abstractmethod - async def asend(self, __value: _T_contra) -> _T_co: ... + def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... @overload @abstractmethod - async def athrow( + def athrow( self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... - ) -> _T_co: ... + ) -> Awaitable[_T_co]: ... @overload @abstractmethod - async def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... - @abstractmethod - async def aclose(self) -> None: ... - @abstractmethod - def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... + def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... + def aclose(self) -> Awaitable[None]: ... @property def ag_await(self) -> Any: ... @property @@ -1026,7 +1031,7 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): @abstractmethod def __exit__( self, __t: Type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None - ) -> bool | None: ... + ) -> None: ... class BinaryIO(IO[bytes]): @abstractmethod @@ -1133,21 +1138,19 @@ class Pattern(Generic[AnyStr]): # Functions if sys.version_info >= (3, 7): - _get_type_hints_obj_allowed_types = Union[ - object, - Callable[..., Any], - FunctionType, - BuiltinFunctionType, - MethodType, - ModuleType, - WrapperDescriptorType, - MethodWrapperType, - MethodDescriptorType, - ] + _get_type_hints_obj_allowed_types = ( + 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, - ] + _get_type_hints_obj_allowed_types = object | Callable[..., Any] | FunctionType | BuiltinFunctionType | MethodType | ModuleType if sys.version_info >= (3, 9): def get_type_hints( @@ -1176,6 +1179,7 @@ def cast(typ: object, val: Any) -> Any: ... if sys.version_info >= (3, 11): def reveal_type(__obj: _T) -> _T: ... def assert_never(__arg: Never) -> Never: ... + def assert_type(__val: _T, __typ: Any) -> _T: ... # Type constructors diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 193fa4feb4f3..892218f68283 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,7 +1,7 @@ import abc import sys from _typeshed import Self as TypeshedSelf # see #6932 for why the alias cannot have a leading underscore -from typing import ( # noqa Y022 +from typing import ( # noqa: Y022,Y027 TYPE_CHECKING as TYPE_CHECKING, Any, AsyncContextManager as AsyncContextManager, diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 4f520528cd2e..f5cd4218cea0 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self from contextlib import _GeneratorContextManager +from types import TracebackType from typing import Any, Awaitable, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload from typing_extensions import Literal @@ -263,7 +264,9 @@ class _patch(Generic[_T]): temp_original: Any is_local: bool def __enter__(self) -> _T: ... - def __exit__(self, *exc_info: Any) -> None: ... + def __exit__( + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + ) -> None: ... def start(self) -> _T: ... def stop(self) -> None: ... @@ -275,121 +278,71 @@ class _patch_dict: def __call__(self, f: Any) -> Any: ... def decorate_class(self, klass: Any) -> Any: ... def __enter__(self) -> Any: ... - def __exit__(self, *args: Any) -> Any: ... + def __exit__(self, *args: object) -> Any: ... start: Any stop: Any +if sys.version_info >= (3, 8): + _Mock = MagicMock | AsyncMock +else: + _Mock = MagicMock + class _patcher: TEST_PREFIX: str dict: type[_patch_dict] - if sys.version_info >= (3, 8): - # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. - # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], - # but that's impossible with the current type system. - @overload - def __call__( # type: ignore[misc] - self, - target: Any, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def __call__( - self, - target: Any, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock | AsyncMock]: ... - else: - @overload - def __call__( # type: ignore[misc] - self, - target: Any, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def __call__( - self, - target: Any, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock]: ... - if sys.version_info >= (3, 8): - @overload - def object( # type: ignore[misc] - self, - target: Any, - attribute: str, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def object( - self, - target: Any, - attribute: str, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock | AsyncMock]: ... - else: - @overload - def object( # type: ignore[misc] - self, - target: Any, - attribute: str, - new: _T, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[_T]: ... - @overload - def object( - self, - target: Any, - attribute: str, - *, - spec: Any | None = ..., - create: bool = ..., - spec_set: Any | None = ..., - autospec: Any | None = ..., - new_callable: Any | None = ..., - **kwargs: Any, - ) -> _patch[MagicMock]: ... - + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( # type: ignore[misc] + self, + target: Any, + new: _T, + spec: Any | None = ..., + create: bool = ..., + spec_set: Any | None = ..., + autospec: Any | None = ..., + new_callable: Any | None = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + @overload + def __call__( + self, + target: Any, + *, + spec: Any | None = ..., + create: bool = ..., + spec_set: Any | None = ..., + autospec: Any | None = ..., + new_callable: Any | None = ..., + **kwargs: Any, + ) -> _patch[_Mock]: ... + @overload + def object( # type: ignore[misc] + self, + target: Any, + attribute: str, + new: _T, + spec: Any | None = ..., + create: bool = ..., + spec_set: Any | None = ..., + autospec: Any | None = ..., + new_callable: Any | None = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + @overload + def object( + self, + target: Any, + attribute: str, + *, + spec: Any | None = ..., + create: bool = ..., + spec_set: Any | None = ..., + autospec: Any | None = ..., + new_callable: Any | None = ..., + **kwargs: Any, + ) -> _patch[_Mock]: ... def multiple( self, target: Any, @@ -432,7 +385,7 @@ if sys.version_info >= (3, 8): class AsyncMagicMixin(MagicMixin): def __init__(self, *args: Any, **kw: Any) -> None: ... - class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... # type: ignore # argument disparities between base classes + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... class MagicProxy: name: str diff --git a/mypy/typeshed/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi index f1e168a674a7..ca483b06ac9f 100644 --- a/mypy/typeshed/stdlib/unittest/suite.pyi +++ b/mypy/typeshed/stdlib/unittest/suite.pyi @@ -1,8 +1,8 @@ import unittest.case import unittest.result -from typing import Iterable, Iterator, Union +from typing import Iterable, Iterator -_TestType = Union[unittest.case.TestCase, TestSuite] +_TestType = unittest.case.TestCase | TestSuite class BaseTestSuite(Iterable[_TestType]): _tests: list[unittest.case.TestCase] diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index b3cdc73e2fb1..a45e23dd9084 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Union, overload +from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -28,7 +28,7 @@ __all__ = [ "SplitResultBytes", ] -_Str = Union[bytes, str] +_Str = bytes | str uses_relative: list[str] uses_netloc: list[str] @@ -64,6 +64,8 @@ class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... class _DefragResultBase(tuple[Any, ...], Generic[AnyStr]): + if sys.version_info >= (3, 10): + __match_args__ = ("url", "fragment") @property def url(self) -> AnyStr: ... @property diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index 05aa4afef2a7..d75df67a1f76 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,9 +1,9 @@ import sys -from typing import BinaryIO, Union +from typing import BinaryIO __all__ = ["Error", "encode", "decode"] -_File = Union[str, BinaryIO] +_File = str | BinaryIO class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 13fa12348cb3..de20c6c4f5d4 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer, Self -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union, overload +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -8,7 +8,7 @@ if sys.version_info >= (3, 9): else: __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... @@ -25,7 +25,7 @@ class _wave_params(NamedTuple): class Wave_read: def __init__(self, f: _File) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def getfp(self) -> BinaryIO | None: ... def rewind(self) -> None: ... def close(self) -> None: ... @@ -45,7 +45,7 @@ class Wave_read: class Wave_write: def __init__(self, f: _File) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, *args: Any) -> None: ... + def __exit__(self, *args: object) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... def setsampwidth(self, sampwidth: int) -> None: ... diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index e55be6b5e8ba..5dc7e4363d6f 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,11 +1,11 @@ import sys from _typeshed import Self from types import TracebackType -from typing import Any, Union +from typing import Any from typing_extensions import Literal, final if sys.platform == "win32": - _KeyType = Union[HKEYType, int] + _KeyType = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... diff --git a/mypy/typeshed/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi index 731cb52ea9db..9e2153788cac 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,6 +1,6 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, MutableMapping, Optional +from typing import IO, Callable, MutableMapping from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment @@ -8,7 +8,7 @@ from .util import FileWrapper __all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISCGIHandler", "read_environ"] -_exc_info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_exc_info = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index 7ae2dcf3eadd..b2bec64fd1dc 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import SupportsRead -from typing import Any, Sequence, Union +from typing import Any, Sequence from typing_extensions import Literal from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler @@ -15,8 +15,8 @@ PROCESSING_INSTRUCTION: Literal["PROCESSING_INSTRUCTION"] IGNORABLE_WHITESPACE: Literal["IGNORABLE_WHITESPACE"] CHARACTERS: Literal["CHARACTERS"] -_DocumentFactory = Union[DOMImplementation, None] -_Node = Union[Document, Element, Text] +_DocumentFactory = DOMImplementation | None +_Node = Document | Element | Text _Event = tuple[ Literal[ diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi index 0615edb8073e..ec47ec134e08 100644 --- a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -1,4 +1,4 @@ -from typing import Any, NoReturn, Optional +from typing import Any, NoReturn from typing_extensions import Literal from urllib.request import OpenerDirector from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS @@ -18,13 +18,13 @@ __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] # probably the same as `Options.errorHandler`? # Maybe `xml.sax.handler.ErrorHandler`? -_DOMBuilderErrorHandlerType = Optional[Any] +_DOMBuilderErrorHandlerType = Any | None # probably some kind of IO... -_DOMInputSourceCharacterStreamType = Optional[Any] +_DOMInputSourceCharacterStreamType = Any | None # probably a string?? -_DOMInputSourceStringDataType = Optional[Any] +_DOMInputSourceStringDataType = Any | None # probably a string?? -_DOMInputSourceEncodingType = Optional[Any] +_DOMInputSourceEncodingType = Any | None class Options: namespaces: int diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index aef8285eec5b..7b50b4279021 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -12,7 +12,6 @@ from typing import ( MutableSequence, Sequence, TypeVar, - Union, overload, ) from typing_extensions import Literal, SupportsIndex, TypeGuard @@ -102,9 +101,9 @@ else: ] _T = TypeVar("_T") -_FileRead = Union[StrOrBytesPath, FileDescriptor, SupportsRead[bytes], SupportsRead[str]] -_FileWriteC14N = Union[StrOrBytesPath, FileDescriptor, SupportsWrite[bytes]] -_FileWrite = Union[_FileWriteC14N, SupportsWrite[str]] +_FileRead = StrOrBytesPath | FileDescriptor | SupportsRead[bytes] | SupportsRead[str] +_FileWriteC14N = StrOrBytesPath | FileDescriptor | SupportsWrite[bytes] +_FileWrite = _FileWriteC14N | SupportsWrite[str] VERSION: str diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index d44c15cb64ed..a59be37f9e81 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -12,9 +12,11 @@ from typing_extensions import Literal class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... -_DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] -_Marshallable = Union[None, bool, int, float, str, bytes, tuple[Any, ...], list[Any], dict[Any, Any], datetime, DateTime, Binary] -_XMLDate = Union[int, datetime, tuple[int, ...], time.struct_time] +_DateTimeComparable = DateTime | datetime | str | _SupportsTimeTuple +_Marshallable = ( + bool | int | float | str | bytes | None | tuple[Any, ...] | list[Any] | dict[Any, Any] | datetime | DateTime | Binary +) +_XMLDate = int | datetime | tuple[int, ...] | time.struct_time _HostType = Union[tuple[str, dict[str, str]], str] def escape(s: str) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 0a07424949df..2ed0b03c7151 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -3,11 +3,11 @@ import pydoc import socketserver import sys from datetime import datetime -from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol, Union +from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol from xmlrpc.client import Fault # TODO: Recursive type on tuple, list, dict -_Marshallable = Union[None, bool, int, float, str, bytes, tuple[Any, ...], list[Any], dict[Any, Any], datetime] +_Marshallable = None | bool | int | float | str | bytes | tuple[Any, ...] | list[Any] | dict[Any, Any] | datetime # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy class _DispatchArity0(Protocol): @@ -30,7 +30,7 @@ class _DispatchArity4(Protocol): class _DispatchArityN(Protocol): def __call__(self, *args: _Marshallable) -> _Marshallable: ... -_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] +_DispatchProtocol = _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 diff --git a/mypy/typeshed/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi index 17c3503ad6eb..c3cf8321dbc4 100644 --- a/mypy/typeshed/stdlib/zipapp.pyi +++ b/mypy/typeshed/stdlib/zipapp.pyi @@ -1,10 +1,10 @@ import sys from pathlib import Path -from typing import BinaryIO, Callable, Union +from typing import BinaryIO, Callable __all__ = ["ZipAppError", "create_archive", "get_interpreter"] -_Path = Union[str, Path, BinaryIO] +_Path = str | Path | BinaryIO class ZipAppError(ValueError): ... From b1f65848245df0925022f5f9916477e6fc2f18a8 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 6 Apr 2022 13:47:47 +0100 Subject: [PATCH 3/4] Fix tests --- test-data/unit/check-flags.test | 10 ++++++++++ test-data/unit/check-functools.test | 5 +++++ test-data/unit/check-generic-alias.test | 8 -------- test-data/unit/pythoneval.test | 4 ++-- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/test-data/unit/check-flags.test b/test-data/unit/check-flags.test index a20413577776..5cda01fab855 100644 --- a/test-data/unit/check-flags.test +++ b/test-data/unit/check-flags.test @@ -1378,6 +1378,16 @@ p: Future # E: Missing type parameters for generic type "Future" \ # N: Subscripting classes that are not generic at runtime may require escaping, see https://mypy.readthedocs.io/en/stable/runtime_troubles.html#not-generic-runtime q: Queue # E: Missing type parameters for generic type "Queue" \ # N: Subscripting classes that are not generic at runtime may require escaping, see https://mypy.readthedocs.io/en/stable/runtime_troubles.html#not-generic-runtime +[file asyncio/__init__.pyi] +from asyncio.futures import Future as Future +[file asyncio/futures.pyi] +from typing import TypeVar, Generic +_T = TypeVar('_T') +class Future(Generic[_T]): ... +[file queue.pyi] +from typing import TypeVar, Generic +_T = TypeVar('_T') +class Queue(Generic[_T]): ... [builtins fixtures/async_await.pyi] [typing fixtures/typing-full.pyi] diff --git a/test-data/unit/check-functools.test b/test-data/unit/check-functools.test index 33653c8d3fbc..5f9159ab9c52 100644 --- a/test-data/unit/check-functools.test +++ b/test-data/unit/check-functools.test @@ -126,4 +126,9 @@ reveal_type(Child().f) # N: Revealed type is "builtins.str" reveal_type(Child().g) # N: Revealed type is "builtins.int" Child().f = "Hello World" Child().g = "invalid" # E: Incompatible types in assignment (expression has type "str", variable has type "int") +[file functools.pyi] +import sys +from typing import TypeVar, Generic +_T = TypeVar('_T') +class cached_property(Generic[_T]): ... [builtins fixtures/property.pyi] diff --git a/test-data/unit/check-generic-alias.test b/test-data/unit/check-generic-alias.test index bba3f5f9bd04..574a57607d11 100644 --- a/test-data/unit/check-generic-alias.test +++ b/test-data/unit/check-generic-alias.test @@ -199,14 +199,6 @@ t23: collections.abc.ValuesView[str] [builtins fixtures/tuple.pyi] -[case testGenericAliasImportRe] -# flags: --python-version 3.9 -from re import Pattern, Match -t1: Pattern[str] -t2: Match[str] -[builtins fixtures/tuple.pyi] - - [case testGenericBuiltinTupleTyping] # flags: --python-version 3.6 from typing import Tuple diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index a0b98d2501c7..4cb0d66e8a98 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -1084,8 +1084,8 @@ _testTypedDictGet.py:8: note: Revealed type is "builtins.str" _testTypedDictGet.py:9: note: Revealed type is "builtins.object" _testTypedDictGet.py:10: error: All overload variants of "get" of "Mapping" require at least one argument _testTypedDictGet.py:10: note: Possible overload variants: -_testTypedDictGet.py:10: note: def get(self, key: str) -> object -_testTypedDictGet.py:10: note: def [_T] get(self, str, object) -> object +_testTypedDictGet.py:10: note: def get(self, str) -> object +_testTypedDictGet.py:10: note: def [_T] get(self, str, default: object) -> object _testTypedDictGet.py:12: note: Revealed type is "builtins.object" [case testTypedDictMappingMethods] From 4545b9b8ee1fa30c0896b1fb096f76dc3e2cbac0 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 6 Apr 2022 14:12:52 +0100 Subject: [PATCH 4/4] Update test case --- test-data/unit/pythoneval.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index 4cb0d66e8a98..4faa5d14c52a 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -850,7 +850,7 @@ MyDDict(dict)[0] _program.py:6: error: Argument 1 to "defaultdict" has incompatible type "Type[List[Any]]"; expected "Callable[[], str]" _program.py:9: error: Invalid index type "str" for "defaultdict[int, str]"; expected type "int" _program.py:9: error: Incompatible types in assignment (expression has type "int", target has type "str") -_program.py:19: error: Dict entry 0 has incompatible type "str": "List[]"; expected "int": "List[]" +_program.py:19: error: Argument 1 to "tst" has incompatible type "defaultdict[str, List[]]"; expected "defaultdict[int, List[]]" _program.py:23: error: Invalid index type "str" for "MyDDict[Dict[_KT, _VT]]"; expected type "int" [case testNoSubcriptionOfStdlibCollections]