From: JinWang An Date: Wed, 18 Jan 2023 06:01:39 +0000 (+0900) Subject: Imported Upstream version 3.10.3 X-Git-Tag: upstream/3.10.3^0 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=ef4f58bcc37991d15b5b514d85a65cfb06028949;p=platform%2Fupstream%2Fpython3.git Imported Upstream version 3.10.3 --- diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst index dc05659..bcd9621 100644 --- a/Doc/c-api/exceptions.rst +++ b/Doc/c-api/exceptions.rst @@ -253,6 +253,14 @@ For convenience, some of these functions will always return a .. versionadded:: 3.3 +.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path) + + Much like :c:func:`PyErr_SetImportError` but this function allows for + specifying a subclass of :exc:`ImportError` to raise. + + .. versionadded:: 3.6 + + .. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) Set file, line, and offset information for the current exception. If the @@ -320,13 +328,6 @@ an error value). :mod:`warnings` module and the :option:`-W` option in the command line documentation. There is no C API for warning control. -.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path) - - Much like :c:func:`PyErr_SetImportError` but this function allows for - specifying a subclass of :exc:`ImportError` to raise. - - .. versionadded:: 3.6 - .. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry) diff --git a/Doc/c-api/init_config.rst b/Doc/c-api/init_config.rst index c037f19..b8b4151 100644 --- a/Doc/c-api/init_config.rst +++ b/Doc/c-api/init_config.rst @@ -634,7 +634,7 @@ PyConfig .. c:member:: int dump_refs - Dump Python refererences? + Dump Python references? If non-zero, dump all objects which are still alive at exit. diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst index 17e3707..41a3aff 100644 --- a/Doc/c-api/object.rst +++ b/Doc/c-api/object.rst @@ -81,8 +81,9 @@ Object Protocol return ``0`` on success. This is the equivalent of the Python statement ``o.attr_name = v``. - If *v* is ``NULL``, the attribute is deleted, however this feature is - deprecated in favour of using :c:func:`PyObject_DelAttr`. + If *v* is ``NULL``, the attribute is deleted. This behaviour is deprecated + in favour of using :c:func:`PyObject_DelAttr`, but there are currently no + plans to remove it. .. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) diff --git a/Doc/c-api/reflection.rst b/Doc/c-api/reflection.rst index 64ce4d1..fe7741a 100644 --- a/Doc/c-api/reflection.rst +++ b/Doc/c-api/reflection.rst @@ -31,7 +31,7 @@ Reflection See also :c:func:`PyThreadState_GetFrame`. -.. c:function:: int PyFrame_GetBack(PyFrameObject *frame) +.. c:function:: PyFrameObject* PyFrame_GetBack(PyFrameObject *frame) Get the *frame* next outer frame. @@ -42,7 +42,7 @@ Reflection .. versionadded:: 3.9 -.. c:function:: int PyFrame_GetCode(PyFrameObject *frame) +.. c:function:: PyCodeObject* PyFrame_GetCode(PyFrameObject *frame) Get the *frame* code. diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index e491c26..9349220 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -476,7 +476,7 @@ PyObject Slots -------------- The type object structure extends the :c:type:`PyVarObject` structure. The -:attr:`ob_size` field is used for dynamic types (created by :func:`type_new`, +:attr:`ob_size` field is used for dynamic types (created by :func:`type_new`, usually called from a class statement). Note that :c:data:`PyType_Type` (the metatype) initializes :c:member:`~PyTypeObject.tp_itemsize`, which means that its instances (i.e. type objects) *must* have the :attr:`ob_size` field. @@ -1232,7 +1232,7 @@ and :c:type:`PyType_Type` effectively act as defaults.) .. note:: :const:`Py_TPFLAGS_MAPPING` and :const:`Py_TPFLAGS_SEQUENCE` are - mutually exclusive; it is an error enable both flags simultaneously. + mutually exclusive; it is an error to enable both flags simultaneously. **Inheritance:** @@ -1254,7 +1254,7 @@ and :c:type:`PyType_Type` effectively act as defaults.) .. note:: :const:`Py_TPFLAGS_MAPPING` and :const:`Py_TPFLAGS_SEQUENCE` are - mutually exclusive; it is an error enable both flags simultaneously. + mutually exclusive; it is an error to enable both flags simultaneously. **Inheritance:** @@ -1999,6 +1999,17 @@ and :c:type:`PyType_Type` effectively act as defaults.) For this field to be taken into account (even through inheritance), you must also set the :const:`Py_TPFLAGS_HAVE_FINALIZE` flags bit. + Also, note that, in a garbage collected Python, + :c:member:`~PyTypeObject.tp_dealloc` may be called from + any Python thread, not just the thread which created the object (if the object + becomes part of a refcount cycle, that cycle might be collected by a garbage + collection on any thread). This is not a problem for Python API calls, since + the thread on which tp_dealloc is called will own the Global Interpreter Lock + (GIL). However, if the object being destroyed in turn destroys objects from some + other C or C++ library, care should be taken to ensure that destroying those + objects on the thread which called tp_dealloc will not violate any assumptions + of the library. + **Inheritance:** This field is inherited by subtypes. @@ -2023,17 +2034,6 @@ and :c:type:`PyType_Type` effectively act as defaults.) .. versionadded:: 3.9 (the field exists since 3.8 but it's only used since 3.9) -Also, note that, in a garbage collected Python, :c:member:`~PyTypeObject.tp_dealloc` may be called from -any Python thread, not just the thread which created the object (if the object -becomes part of a refcount cycle, that cycle might be collected by a garbage -collection on any thread). This is not a problem for Python API calls, since -the thread on which tp_dealloc is called will own the Global Interpreter Lock -(GIL). However, if the object being destroyed in turn destroys objects from some -other C or C++ library, care should be taken to ensure that destroying those -objects on the thread which called tp_dealloc will not violate any assumptions -of the library. - - .. _static-types: Static Types @@ -2439,7 +2439,8 @@ Async Object Structures PyObject *am_aiter(PyObject *self); - Must return an :term:`awaitable` object. See :meth:`__anext__` for details. + Must return an :term:`asynchronous iterator` object. + See :meth:`__anext__` for details. This slot may be set to ``NULL`` if an object does not implement asynchronous iteration protocol. diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst index 343eaf1..a08cebc 100644 --- a/Doc/c-api/unicode.rst +++ b/Doc/c-api/unicode.rst @@ -1008,7 +1008,7 @@ Error handling is set by errors which may also be set to ``NULL`` meaning to use the default handling defined for the codec. Default error handling for all built-in codecs is "strict" (:exc:`ValueError` is raised). -The codecs all use a similar interface. Only deviation from the following +The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity. @@ -1225,7 +1225,7 @@ These are the UTF-16 codec APIs: ``1``, any byte order mark is copied to the output (where it will result in either a ``\ufeff`` or a ``\ufffe`` character). - After completion, *\*byteorder* is set to the current byte order at the end + After completion, ``*byteorder`` is set to the current byte order at the end of input data. If *byteorder* is ``NULL``, the codec starts in native order mode. @@ -1443,7 +1443,7 @@ Character Map Codecs This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs -included in the :mod:`encodings` package). The codec uses mapping to encode and +included in the :mod:`encodings` package). The codec uses mappings to encode and decode characters. The mapping objects provided must support the :meth:`__getitem__` mapping interface; dictionaries and sequences work well. @@ -1605,7 +1605,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. .. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) Split a Unicode string at line breaks, returning a list of Unicode strings. - CRLF is considered to be one line break. If *keepend* is ``0``, the Line break + CRLF is considered to be one line break. If *keepend* is ``0``, the line break characters are not included in the resulting strings. diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst index 3354a2b..5b8735d 100644 --- a/Doc/c-api/veryhigh.rst +++ b/Doc/c-api/veryhigh.rst @@ -75,6 +75,8 @@ the same library that the Python runtime is using. :c:func:`PyRun_SimpleFile`. *filename* is decoded from the filesystem encoding (:func:`sys.getfilesystemencoding`). If *filename* is ``NULL``, this function uses ``"???"`` as the filename. + If *closeit* is true, the file is closed before + ``PyRun_SimpleFileExFlags()`` returns. .. c:function:: int PyRun_SimpleString(const char *command) diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst index 0437b59..ff83a1b 100644 --- a/Doc/faq/design.rst +++ b/Doc/faq/design.rst @@ -266,12 +266,9 @@ For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:: - def function_1(...): - ... - functions = {'a': function_1, 'b': function_2, - 'c': self.method_1, ...} + 'c': self.method_1} func = functions[value] func() @@ -279,14 +276,14 @@ example:: For calling methods on objects, you can simplify yet further by using the :func:`getattr` built-in to retrieve methods with a particular name:: - def visit_a(self, ...): - ... - ... + class MyVisitor: + def visit_a(self): + ... - def dispatch(self, value): - method_name = 'visit_' + str(value) - method = getattr(self, method_name) - method() + def dispatch(self, value): + method_name = 'visit_' + str(value) + method = getattr(self, method_name) + method() It's suggested that you use a prefix for the method names, such as ``visit_`` in this example. Without such a prefix, if values are coming from an untrusted diff --git a/Doc/faq/extending.rst b/Doc/faq/extending.rst index 3379e41..1d2aca6 100644 --- a/Doc/faq/extending.rst +++ b/Doc/faq/extending.rst @@ -254,7 +254,6 @@ For Red Hat, install the python-devel RPM to get the necessary files. For Debian, run ``apt-get install python-dev``. - How do I tell "incomplete input" from "invalid input"? ------------------------------------------------------ @@ -273,130 +272,6 @@ you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at you custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c`` for more hints. -However sometimes you have to run the embedded Python interpreter in the same -thread as your rest application and you can't allow the -:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. -A solution is trying to compile the received string with -:c:func:`Py_CompileString`. If it compiles without errors, try to execute the -returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the -input for later. If the compilation fails, find out if it's an error or just -more input is required - by extracting the message string from the exception -tuple and comparing it to the string "unexpected EOF while parsing". Here is a -complete example using the GNU readline library (you may want to ignore -**SIGINT** while calling readline()):: - - #include - #include - - #define PY_SSIZE_T_CLEAN - #include - #include - #include - #include - - int main (int argc, char* argv[]) - { - int i, j, done = 0; /* lengths of line, code */ - char ps1[] = ">>> "; - char ps2[] = "... "; - char *prompt = ps1; - char *msg, *line, *code = NULL; - PyObject *src, *glb, *loc; - PyObject *exc, *val, *trb, *obj, *dum; - - Py_Initialize (); - loc = PyDict_New (); - glb = PyDict_New (); - PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ()); - - while (!done) - { - line = readline (prompt); - - if (NULL == line) /* Ctrl-D pressed */ - { - done = 1; - } - else - { - i = strlen (line); - - if (i > 0) - add_history (line); /* save non-empty lines */ - - if (NULL == code) /* nothing in code yet */ - j = 0; - else - j = strlen (code); - - code = realloc (code, i + j + 2); - if (NULL == code) /* out of memory */ - exit (1); - - if (0 == j) /* code was empty, so */ - code[0] = '\0'; /* keep strncat happy */ - - strncat (code, line, i); /* append line to code */ - code[i + j] = '\n'; /* append '\n' to code */ - code[i + j + 1] = '\0'; - - src = Py_CompileString (code, "", Py_single_input); - - if (NULL != src) /* compiled just fine - */ - { - if (ps1 == prompt || /* ">>> " or */ - '\n' == code[i + j - 1]) /* "... " and double '\n' */ - { /* so execute it */ - dum = PyEval_EvalCode (src, glb, loc); - Py_XDECREF (dum); - Py_XDECREF (src); - free (code); - code = NULL; - if (PyErr_Occurred ()) - PyErr_Print (); - prompt = ps1; - } - } /* syntax error or E_EOF? */ - else if (PyErr_ExceptionMatches (PyExc_SyntaxError)) - { - PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ - - if (PyArg_ParseTuple (val, "sO", &msg, &obj) && - !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ - { - Py_XDECREF (exc); - Py_XDECREF (val); - Py_XDECREF (trb); - prompt = ps2; - } - else /* some other syntax error */ - { - PyErr_Restore (exc, val, trb); - PyErr_Print (); - free (code); - code = NULL; - prompt = ps1; - } - } - else /* some non-syntax error */ - { - PyErr_Print (); - free (code); - code = NULL; - prompt = ps1; - } - - free (line); - } - } - - Py_XDECREF(glb); - Py_XDECREF(loc); - Py_Finalize(); - exit(0); - } - - How do I find undefined g++ symbols __builtin_new or __pure_virtual? -------------------------------------------------------------------- diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index 154563a..a1adf85 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -1819,7 +1819,7 @@ for ``None``. This reads like plain English in code and avoids confusion with other objects that may have boolean values that evaluate to false. 2) Detecting optional arguments can be tricky when ``None`` is a valid input -value. In those situations, you can create an singleton sentinel object +value. In those situations, you can create a singleton sentinel object guaranteed to be distinct from other objects. For example, here is how to implement a method that behaves like :meth:`dict.pop`:: @@ -1908,7 +1908,7 @@ The *cached_property* approach only works with methods that do not take any arguments. It does not create a reference to the instance. The cached method result will be kept only as long as the instance is alive. -The advantage is that when an instance is not longer used, the cached +The advantage is that when an instance is no longer used, the cached method result will be released right away. The disadvantage is that if instances accumulate, so too will the accumulated method results. They can grow without bound. diff --git a/Doc/glossary.rst b/Doc/glossary.rst index 1bbd05a..ddf085b 100644 --- a/Doc/glossary.rst +++ b/Doc/glossary.rst @@ -292,12 +292,12 @@ Glossary The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:: - def f(...): + def f(arg): ... f = staticmethod(f) @staticmethod - def f(...): + def f(arg): ... The same concept exists for classes, but is less commonly used there. See diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst index 6ce062d..f2e2f7e 100644 --- a/Doc/howto/descriptor.rst +++ b/Doc/howto/descriptor.rst @@ -696,10 +696,14 @@ a pure Python equivalent: >>> b.g == b['g'] == ('getattr_hook', b, 'g') True +Note, there is no :meth:`__getattr__` hook in the :meth:`__getattribute__` +code. That is why calling :meth:`__getattribute__` directly or with +``super().__getattribute__`` will bypass :meth:`__getattr__` entirely. -Interestingly, attribute lookup doesn't call :meth:`object.__getattribute__` -directly. Instead, both the dot operator and the :func:`getattr` function -perform attribute lookup by way of a helper function: +Instead, it is the dot operator and the :func:`getattr` function that are +responsible for invoking :meth:`__getattr__` whenever :meth:`__getattribute__` +raises an :exc:`AttributeError`. Their logic is encapsulated in a helper +function: .. testcode:: @@ -744,12 +748,6 @@ perform attribute lookup by way of a helper function: ... AttributeError: 'ClassWithoutGetAttr' object has no attribute 'z' -So if :meth:`__getattr__` exists, it is called whenever :meth:`__getattribute__` -raises :exc:`AttributeError` (either directly or in one of the descriptor calls). - -Also, if a user calls :meth:`object.__getattribute__` directly, the -:meth:`__getattr__` hook is bypassed entirely. - Invocation from a class ----------------------- @@ -1544,7 +1542,7 @@ variables: 'Simulate how the type metaclass adds member objects for slots' def __new__(mcls, clsname, bases, mapping): - 'Emuluate type_new() in Objects/typeobject.c' + 'Emulate type_new() in Objects/typeobject.c' # type_new() calls PyTypeReady() which calls add_methods() slot_names = mapping.get('slot_names', []) for offset, name in enumerate(slot_names): diff --git a/Doc/howto/logging_flow.png b/Doc/howto/logging_flow.png index fac4acd..d65e597 100644 Binary files a/Doc/howto/logging_flow.png and b/Doc/howto/logging_flow.png differ diff --git a/Doc/library/__main__.rst b/Doc/library/__main__.rst index c5f36a7..d0a65e7 100644 --- a/Doc/library/__main__.rst +++ b/Doc/library/__main__.rst @@ -253,7 +253,7 @@ attribute will include the package's path if imported:: This won't work for ``__main__.py`` files in the root directory of a .zip file though. Hence, for consistency, minimal ``__main__.py`` like the :mod:`venv` -one mentioned above are preferred. +one mentioned below are preferred. .. seealso:: diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst index 1a6ed47..3b74622 100644 --- a/Doc/library/abc.rst +++ b/Doc/library/abc.rst @@ -186,15 +186,15 @@ The :mod:`abc` module also provides the following decorator: class C(ABC): @abstractmethod - def my_abstract_method(self, ...): + def my_abstract_method(self, arg1): ... @classmethod @abstractmethod - def my_abstract_classmethod(cls, ...): + def my_abstract_classmethod(cls, arg2): ... @staticmethod @abstractmethod - def my_abstract_staticmethod(...): + def my_abstract_staticmethod(arg3): ... @property @@ -255,7 +255,7 @@ The :mod:`abc` module also supports the following legacy decorators: class C(ABC): @classmethod @abstractmethod - def my_abstract_classmethod(cls, ...): + def my_abstract_classmethod(cls, arg): ... @@ -276,7 +276,7 @@ The :mod:`abc` module also supports the following legacy decorators: class C(ABC): @staticmethod @abstractmethod - def my_abstract_staticmethod(...): + def my_abstract_staticmethod(arg): ... diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst index b1700c9..300092d 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -343,7 +343,7 @@ Creating Futures and Tasks the name of the task using :meth:`Task.set_name`. .. versionchanged:: 3.8 - Added the ``name`` parameter. + Added the *name* parameter. .. method:: loop.set_task_factory(factory) @@ -456,7 +456,20 @@ Opening network connections to wait for the TLS handshake to complete before aborting the connection. ``60.0`` seconds if ``None`` (default). - .. versionadded:: 3.8 + .. versionchanged:: 3.5 + + Added support for SSL/TLS in :class:`ProactorEventLoop`. + + .. versionchanged:: 3.6 + + The socket option :py:data:`~socket.TCP_NODELAY` is set by default + for all TCP connections. + + .. versionchanged:: 3.7 + + Added the *ssl_handshake_timeout* parameter. + + .. versionchanged:: 3.8 Added the *happy_eyeballs_delay* and *interleave* parameters. @@ -471,19 +484,6 @@ Opening network connections For more information: https://tools.ietf.org/html/rfc6555 - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* parameter. - - .. versionchanged:: 3.6 - - The socket option :py:data:`~socket.TCP_NODELAY` is set by default - for all TCP connections. - - .. versionchanged:: 3.5 - - Added support for SSL/TLS in :class:`ProactorEventLoop`. - .. seealso:: The :func:`open_connection` function is a high-level alternative @@ -588,12 +588,8 @@ Opening network connections .. availability:: Unix. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* parameter. - .. versionchanged:: 3.7 - + Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be a :term:`path-like object`. @@ -672,15 +668,6 @@ Creating network servers :meth:`Server.serve_forever` to make the server to start accepting connections. - .. versionadded:: 3.7 - - Added *ssl_handshake_timeout* and *start_serving* parameters. - - .. versionchanged:: 3.6 - - The socket option :py:data:`~socket.TCP_NODELAY` is set by default - for all TCP connections. - .. versionchanged:: 3.5 Added support for SSL/TLS in :class:`ProactorEventLoop`. @@ -689,6 +676,12 @@ Creating network servers The *host* parameter can be a sequence of strings. + .. versionchanged:: 3.6 + + Added *ssl_handshake_timeout* and *start_serving* parameters. + The socket option :py:data:`~socket.TCP_NODELAY` is set by default + for all TCP connections. + .. seealso:: The :func:`start_server` function is a higher-level alternative API @@ -713,12 +706,9 @@ Creating network servers .. availability:: Unix. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* and *start_serving* parameters. - .. versionchanged:: 3.7 + Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path* parameter can now be a :class:`~pathlib.Path` object. .. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \ @@ -746,11 +736,11 @@ Creating network servers Returns a ``(transport, protocol)`` pair. - .. versionadded:: 3.7 + .. versionadded:: 3.5.3 - The *ssl_handshake_timeout* parameter. + .. versionchanged:: 3.7 - .. versionadded:: 3.5.3 + Added the *ssl_handshake_timeout* parameter. Transferring files diff --git a/Doc/library/asyncio-future.rst b/Doc/library/asyncio-future.rst index 3496387..7426e82 100644 --- a/Doc/library/asyncio-future.rst +++ b/Doc/library/asyncio-future.rst @@ -194,7 +194,7 @@ Future Object schedule the callbacks, and return ``True``. .. versionchanged:: 3.9 - Added the ``msg`` parameter. + Added the *msg* parameter. .. method:: exception() diff --git a/Doc/library/asyncio-queue.rst b/Doc/library/asyncio-queue.rst index e6f26bb..d86fbc2 100644 --- a/Doc/library/asyncio-queue.rst +++ b/Doc/library/asyncio-queue.rst @@ -36,6 +36,9 @@ Queue the queue is always known and can be returned by calling the :meth:`qsize` method. + .. versionchanged:: 3.10 + Removed the *loop* parameter. + This class is :ref:`not thread safe `. @@ -105,13 +108,6 @@ Queue Raises :exc:`ValueError` if called more times than there were items placed in the queue. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. - Priority Queue ============== diff --git a/Doc/library/asyncio-stream.rst b/Doc/library/asyncio-stream.rst index 95a8e46..3558277 100644 --- a/Doc/library/asyncio-stream.rst +++ b/Doc/library/asyncio-stream.rst @@ -51,7 +51,8 @@ and work with streams: .. coroutinefunction:: open_connection(host=None, port=None, *, \ limit=None, ssl=None, family=0, proto=0, \ flags=0, sock=None, local_addr=None, \ - server_hostname=None, ssl_handshake_timeout=None) + server_hostname=None, ssl_handshake_timeout=None, \ + happy_eyeballs_delay=None, interleave=None) Establish a network connection and return a pair of ``(reader, writer)`` objects. @@ -66,16 +67,14 @@ and work with streams: The rest of the arguments are passed directly to :meth:`loop.create_connection`. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* parameter. + .. versionchanged:: 3.7 + Added the *ssl_handshake_timeout* parameter. - .. deprecated-removed:: 3.8 3.10 + .. versionadded:: 3.8 + Added *happy_eyeballs_delay* and *interleave* parameters. - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. coroutinefunction:: start_server(client_connected_cb, host=None, \ @@ -104,16 +103,11 @@ and work with streams: The rest of the arguments are passed directly to :meth:`loop.create_server`. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* and *start_serving* parameters. - - .. deprecated-removed:: 3.8 3.10 + .. versionchanged:: 3.7 + Added the *ssl_handshake_timeout* and *start_serving* parameters. - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. rubric:: Unix Sockets @@ -131,20 +125,12 @@ and work with streams: .. availability:: Unix. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* parameter. - .. versionchanged:: 3.7 - + Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be a :term:`path-like object` - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \ @@ -159,20 +145,12 @@ and work with streams: .. availability:: Unix. - .. versionadded:: 3.7 - - The *ssl_handshake_timeout* and *start_serving* parameters. - .. versionchanged:: 3.7 - + Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path* parameter can now be a :term:`path-like object`. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. StreamReader diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst index fd1f9c9..748b704 100644 --- a/Doc/library/asyncio-subprocess.rst +++ b/Doc/library/asyncio-subprocess.rst @@ -75,12 +75,8 @@ Creating Subprocesses See the documentation of :meth:`loop.subprocess_exec` for other parameters. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \ @@ -106,12 +102,8 @@ Creating Subprocesses escape whitespace and special shell characters in strings that are going to be used to construct shell commands. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. note:: diff --git a/Doc/library/asyncio-sync.rst b/Doc/library/asyncio-sync.rst index 88e523a..f4063db 100644 --- a/Doc/library/asyncio-sync.rst +++ b/Doc/library/asyncio-sync.rst @@ -63,11 +63,8 @@ Lock finally: lock.release() - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This class has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. coroutinemethod:: acquire() @@ -111,11 +108,8 @@ Event :meth:`clear` method. The :meth:`~Event.wait` method blocks until the flag is set to *true*. The flag is set to *false* initially. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This class has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. _asyncio_example_sync_event: @@ -189,11 +183,8 @@ Condition ``None``. In the latter case a new Lock object is created automatically. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This class has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. The preferred way to use a Condition is an :keyword:`async with` statement:: @@ -291,11 +282,8 @@ Semaphore internal counter (``1`` by default). If the given value is less than ``0`` a :exc:`ValueError` is raised. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This class has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. The preferred way to use a Semaphore is an :keyword:`async with` statement:: @@ -349,12 +337,8 @@ BoundedSemaphore a :exc:`ValueError` in :meth:`~Semaphore.release` if it increases the internal counter above the initial *value*. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This class has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. --------- diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 1175b05..efd4d1b 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -282,7 +282,7 @@ Creating Tasks .. versionadded:: 3.7 .. versionchanged:: 3.8 - Added the ``name`` parameter. + Added the *name* parameter. Sleeping @@ -328,12 +328,8 @@ Sleeping asyncio.run(display_date()) - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. Running Tasks Concurrently @@ -368,11 +364,8 @@ Running Tasks Concurrently cancellation of one submitted Task/Future to cause other Tasks/Futures to be cancelled. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. _asyncio_example_gather: @@ -425,11 +418,8 @@ Running Tasks Concurrently If the *gather* itself is cancelled, the cancellation is propagated regardless of *return_exceptions*. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. deprecated:: 3.10 Deprecation warning is emitted if no positional arguments are provided @@ -473,11 +463,8 @@ Shielding From Cancellation except CancelledError: res = None - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. deprecated:: 3.10 Deprecation warning is emitted if *aw* is not Future-like object @@ -510,11 +497,8 @@ Timeouts If the wait is cancelled, the future *aw* is also cancelled. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. _asyncio_example_waitfor: @@ -543,11 +527,8 @@ Timeouts for *aw* to be cancelled. Previously, it raised :exc:`asyncio.TimeoutError` immediately. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. Waiting Primitives @@ -605,11 +586,8 @@ Waiting Primitives ``wait()`` directly is deprecated as it leads to :ref:`confusing behavior `. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. _asyncio_example_wait_coroutine: .. note:: @@ -638,18 +616,14 @@ Waiting Primitives if task in done: # Everything will work as expected now. - .. deprecated-removed:: 3.8 3.10 - - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. - .. deprecated-removed:: 3.8 3.11 Passing coroutine objects to ``wait()`` directly is deprecated. + .. versionchanged:: 3.10 + Removed the *loop* parameter. + .. function:: as_completed(aws, *, timeout=None) @@ -661,11 +635,8 @@ Waiting Primitives Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures are done. - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. Example:: @@ -673,11 +644,8 @@ Waiting Primitives earliest_result = await coro # ... - .. deprecated-removed:: 3.8 3.10 - The ``loop`` parameter. This function has been implicitly getting the - current running loop since 3.7. See - :ref:`What's New in 3.10's Removed section ` - for more information. + .. versionchanged:: 3.10 + Removed the *loop* parameter. .. deprecated:: 3.10 Deprecation warning is emitted if not all awaitable objects in the *aws* @@ -860,10 +828,7 @@ Task Object Added support for the :mod:`contextvars` module. .. versionchanged:: 3.8 - Added the ``name`` parameter. - - .. deprecated-removed:: 3.8 3.10 - The *loop* parameter. + Added the *name* parameter. .. deprecated:: 3.10 Deprecation warning is emitted if *loop* is not specified @@ -885,7 +850,7 @@ Task Object discouraged. .. versionchanged:: 3.9 - Added the ``msg`` parameter. + Added the *msg* parameter. .. _asyncio_example_task_cancel: @@ -1057,7 +1022,7 @@ Generator-based Coroutines .. note:: Support for generator-based coroutines is **deprecated** and - is scheduled for removal in Python 3.10. + is removed in Python 3.11. Generator-based coroutines predate async/await syntax. They are Python generators that use ``yield from`` expressions to await diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst index f34ee17..edcd4ae 100644 --- a/Doc/library/bisect.rst +++ b/Doc/library/bisect.rst @@ -43,7 +43,7 @@ The following functions are provided: .. function:: bisect_right(a, x, lo=0, hi=len(a), *, key=None) - bisect(a, x, lo=0, hi=len(a)) + bisect(a, x, lo=0, hi=len(a), *, key=None) Similar to :func:`bisect_left`, but returns an insertion point which comes after (to the right of) any existing entries of *x* in *a*. @@ -80,7 +80,7 @@ The following functions are provided: .. function:: insort_right(a, x, lo=0, hi=len(a), *, key=None) - insort(a, x, lo=0, hi=len(a)) + insort(a, x, lo=0, hi=len(a), *, key=None) Similar to :func:`insort_left`, but inserting *x* in *a* after any existing entries of *x*. diff --git a/Doc/library/calendar.rst b/Doc/library/calendar.rst index c3c04db..f641760 100644 --- a/Doc/library/calendar.rst +++ b/Doc/library/calendar.rst @@ -31,7 +31,7 @@ interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is .. class:: Calendar(firstweekday=0) Creates a :class:`Calendar` object. *firstweekday* is an integer specifying the - first day of the week. ``0`` is Monday (the default), ``6`` is Sunday. + first day of the week. :const:`MONDAY` is ``0`` (the default), :const:`SUNDAY` is ``6``. A :class:`Calendar` object provides several methods that can be used for preparing the calendar data for formatting. This class doesn't do any formatting @@ -409,6 +409,15 @@ The :mod:`calendar` module exports the following data attributes: locale. This follows normal convention of January being month number 1, so it has a length of 13 and ``month_abbr[0]`` is the empty string. +.. data:: MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY + SUNDAY + + Aliases for day numbers, where ``MONDAY`` is ``0`` and ``SUNDAY`` is ``6``. .. seealso:: diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst index ef71832..1a1ce92 100644 --- a/Doc/library/codecs.rst +++ b/Doc/library/codecs.rst @@ -694,8 +694,9 @@ compatible with the Python codec registry. .. method:: writelines(list) - Writes the concatenated list of strings to the stream (possibly by reusing - the :meth:`write` method). The standard bytes-to-bytes codecs + Writes the concatenated iterable of strings to the stream (possibly by reusing + the :meth:`write` method). Infinite or + very large iterables are not supported. The standard bytes-to-bytes codecs do not support this method. diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index b8a717d..67b64dd 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -271,12 +271,12 @@ For example:: .. versionadded:: 3.1 .. versionchanged:: 3.7 As a :class:`dict` subclass, :class:`Counter` - Inherited the capability to remember insertion order. Math operations + inherited the capability to remember insertion order. Math operations on *Counter* objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand. - Counter objects support three methods beyond those available for all + Counter objects support additional methods beyond those available for all dictionaries: .. method:: elements() @@ -366,19 +366,26 @@ Several mathematical operations are provided for combining :class:`Counter` objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and -maximum of corresponding counts. Each operation can accept inputs with signed +maximum of corresponding counts. Equality and inclusion compare +corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less. +.. doctest:: + >>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # add two counters together: c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keeping only positive counts) Counter({'a': 2}) - >>> c & d # intersection: min(c[x], d[x]) # doctest: +SKIP + >>> c & d # intersection: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) >>> c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2}) + >>> c == d # equality: c[x] == d[x] + False + >>> c <= d # inclusion: c[x] <= d[x] + False Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter. @@ -1085,18 +1092,35 @@ Some differences from :class:`dict` still remain: Space efficiency, iteration speed, and the performance of update operations were secondary. -* Algorithmically, :class:`OrderedDict` can handle frequent reordering - operations better than :class:`dict`. This makes it suitable for tracking - recent accesses (for example in an `LRU cache - `_). +* The :class:`OrderedDict` algorithm can handle frequent reordering operations + better than :class:`dict`. As shown in the recipes below, this makes it + suitable for implementing various kinds of LRU caches. * The equality operation for :class:`OrderedDict` checks for matching order. + A regular :class:`dict` can emulate the order sensitive equality test with + ``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``. + * The :meth:`popitem` method of :class:`OrderedDict` has a different signature. It accepts an optional argument to specify which item is popped. -* :class:`OrderedDict` has a :meth:`move_to_end` method to - efficiently reposition an element to an endpoint. + A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)`` + with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item. + + A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)`` + with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the + leftmost (first) item if it exists. + +* :class:`OrderedDict` has a :meth:`move_to_end` method to efficiently + reposition an element to an endpoint. + + A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k, + last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its + associated value to the rightmost (last) position. + + A regular :class:`dict` does not have an efficient equivalent for + OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key + and its associated value to the leftmost (first) position. * Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method. diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst index 1ebda53..323dd2a 100644 --- a/Doc/library/configparser.rst +++ b/Doc/library/configparser.rst @@ -267,6 +267,9 @@ out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser's mode, blank lines may be treated as parts of multiline values or ignored. +By default, a valid section name can be any string that does not contain '\\n' or ']'. +To change this, see :attr:`ConfigParser.SECTCRE`. + Configuration files may include comments, prefixed by specific characters (``#`` and ``;`` by default [1]_). Comments may appear on their own on an otherwise empty line, possibly indented. [1]_ diff --git a/Doc/library/copyreg.rst b/Doc/library/copyreg.rst index 4392021..dc35965 100644 --- a/Doc/library/copyreg.rst +++ b/Doc/library/copyreg.rst @@ -33,8 +33,8 @@ Such constructors may be factory functions or class instances. The optional *constructor* parameter, if provided, is a callable object which can be used to reconstruct the object when called with the tuple of arguments - returned by *function* at pickling time. :exc:`TypeError` will be raised if - *object* is a class or *constructor* is not callable. + returned by *function* at pickling time. A :exc:`TypeError` is raised if the + *constructor* is not callable. See the :mod:`pickle` module for more details on the interface expected of *function* and *constructor*. Note that the diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index 6a9863c..1fe5bda 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -475,6 +475,8 @@ Module contents In a single dataclass, it is an error to specify more than one field whose type is :const:`KW_ONLY`. + .. versionadded:: 3.10 + .. exception:: FrozenInstanceError Raised when an implicitly defined :meth:`__setattr__` or diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 217cdf2..f447b7b 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -2375,7 +2375,7 @@ requires, and these work on all platforms with a standard C implementation. +-----------+--------------------------------+------------------------+-------+ | ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7), | | | (Sunday as the first day of | | \(9) | -| | the week) as a zero padded | | | +| | the week) as a zero-padded | | | | | decimal number. All days in a | | | | | new year preceding the first | | | | | Sunday are considered to be in | | | @@ -2383,10 +2383,10 @@ requires, and these work on all platforms with a standard C implementation. +-----------+--------------------------------+------------------------+-------+ | ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7), | | | (Monday as the first day of | | \(9) | -| | the week) as a decimal number. | | | -| | All days in a new year | | | -| | preceding the first Monday | | | -| | are considered to be in | | | +| | the week) as a zero-padded | | | +| | decimal number. All days in a | | | +| | new year preceding the first | | | +| | Monday are considered to be in | | | | | week 0. | | | +-----------+--------------------------------+------------------------+-------+ | ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) | diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst index f8a692e..2f97bb8 100644 --- a/Doc/library/exceptions.rst +++ b/Doc/library/exceptions.rst @@ -38,15 +38,14 @@ information on defining exceptions is available in the Python Tutorial under Exception context ----------------- -When raising (or re-raising) an exception in an :keyword:`except` or -:keyword:`finally` clause -:attr:`__context__` is automatically set to the last exception caught; if the -new exception is not handled the traceback that is eventually displayed will -include the originating exception(s) and the final exception. - -When raising a new exception (rather than using a bare ``raise`` to re-raise -the exception currently being handled), the implicit exception context can be -supplemented with an explicit cause by using :keyword:`from` with +When raising a new exception while another exception +is already being handled, the new exception's +:attr:`__context__` attribute is automatically set to the handled +exception. An exception may be handled when an :keyword:`except` or +:keyword:`finally` clause, or a :keyword:`with` statement, is used. + +This implicit exception context can be +supplemented with an explicit cause by using :keyword:`!from` with :keyword:`raise`:: raise new_exc from original_exc diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 9a9c87e..9523136 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -248,7 +248,7 @@ are always available. They are listed here in alphabetical order. class C: @classmethod - def f(cls, arg1, arg2, ...): ... + def f(cls, arg1, arg2): ... The ``@classmethod`` form is a function :term:`decorator` -- see :ref:`function` for details. diff --git a/Doc/library/hashlib-blake2-tree.png b/Doc/library/hashlib-blake2-tree.png index 73e8494..faef21b 100644 Binary files a/Doc/library/hashlib-blake2-tree.png and b/Doc/library/hashlib-blake2-tree.png differ diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst index 53320d9..aa24131 100644 --- a/Doc/library/hashlib.rst +++ b/Doc/library/hashlib.rst @@ -249,16 +249,19 @@ include a `salt `_. a proper source, e.g. :func:`os.urandom`. The number of *iterations* should be chosen based on the hash algorithm and - computing power. As of 2013, at least 100,000 iterations of SHA-256 are - suggested. + computing power. As of 2022, hundreds of thousands of iterations of SHA-256 + are suggested. For rationale as to why and how to choose what is best for + your application, read *Appendix A.2.2* of NIST-SP-800-132_. The answers + on the `stackexchange pbkdf2 iterations question`_ explain in detail. *dklen* is the length of the derived key. If *dklen* is ``None`` then the digest size of the hash algorithm *hash_name* is used, e.g. 64 for SHA-512. - >>> import hashlib - >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000) + >>> from hashlib import pbkdf2_hmac + >>> our_app_iters = 500_000 # Application specific, read above. + >>> dk = pbkdf2_hmac('sha256', b'password', b'bad salt'*2, our_app_iters) >>> dk.hex() - '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5' + '15530bba69924174860db778f2c6f8104d3aaf9d26241840c8c4a641c8d000a9' .. versionadded:: 3.4 @@ -731,7 +734,8 @@ Domain Dedication 1.0 Universal: .. _SHA-3: https://en.wikipedia.org/wiki/NIST_hash_function_competition .. _ChaCha: https://cr.yp.to/chacha.html .. _pyblake2: https://pythonhosted.org/pyblake2/ - +.. _NIST-SP-800-132: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf +.. _stackexchange pbkdf2 iterations question: https://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pbkdf2-sha256/ .. seealso:: @@ -754,3 +758,6 @@ Domain Dedication 1.0 Universal: https://www.ietf.org/rfc/rfc8018.txt PKCS #5: Password-Based Cryptography Specification Version 2.1 + + https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf + NIST Recommendation for Password-Based Key Derivation. diff --git a/Doc/library/html.parser.rst b/Doc/library/html.parser.rst index ac844a6..03aff25 100644 --- a/Doc/library/html.parser.rst +++ b/Doc/library/html.parser.rst @@ -126,7 +126,7 @@ implementations do nothing (except for :meth:`~HTMLParser.handle_startendtag`): .. method:: HTMLParser.handle_starttag(tag, attrs) - This method is called to handle the start of a tag (e.g. ``
``). + This method is called to handle the start tag of an element (e.g. ``
``). The *tag* argument is the name of the tag converted to lower case. The *attrs* argument is a list of ``(name, value)`` pairs containing the attributes found diff --git a/Doc/library/http.server.rst b/Doc/library/http.server.rst index c3cee07..0de0283 100644 --- a/Doc/library/http.server.rst +++ b/Doc/library/http.server.rst @@ -412,17 +412,22 @@ the current directory:: .. _http-server-cli: :mod:`http.server` can also be invoked directly using the :option:`-m` -switch of the interpreter with a ``port number`` argument. Similar to +switch of the interpreter. Similar to the previous example, this serves files relative to the current directory:: - python -m http.server 8000 + python -m http.server -By default, server binds itself to all interfaces. The option ``-b/--bind`` +The server listens to port 8000 by default. The default can be overridden +by passing the desired port number as an argument:: + + python -m http.server 9000 + +By default, the server binds itself to all interfaces. The option ``-b/--bind`` specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:: - python -m http.server 8000 --bind 127.0.0.1 + python -m http.server --bind 127.0.0.1 .. versionadded:: 3.4 ``--bind`` argument was introduced. @@ -430,14 +435,14 @@ to bind to localhost only:: .. versionadded:: 3.8 ``--bind`` argument enhanced to support IPv6 -By default, server uses the current directory. The option ``-d/--directory`` +By default, the server uses the current directory. The option ``-d/--directory`` specifies a directory to which it should serve the files. For example, the following command uses a specific directory:: python -m http.server --directory /tmp/ .. versionadded:: 3.7 - ``--directory`` specify alternate directory + ``--directory`` argument was introduced. .. class:: CGIHTTPRequestHandler(request, client_address, server) @@ -482,4 +487,4 @@ the following command uses a specific directory:: :class:`CGIHTTPRequestHandler` can be enabled in the command line by passing the ``--cgi`` option:: - python -m http.server --cgi 8000 + python -m http.server --cgi diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst index d740973..d602104 100644 --- a/Doc/library/idle.rst +++ b/Doc/library/idle.rst @@ -96,11 +96,13 @@ Save Copy As... Print Window Print the current window to the default printer. -Close - Close the current window (ask to save if unsaved). +Close Window + Close the current window (if an unsaved editor, ask to save; if an unsaved + Shell, ask to quit execution). Calling ``exit()`` or ``close()`` in the Shell + window also closes Shell. If this is the only window, also exit IDLE. -Exit - Close all windows and quit IDLE (ask to save unsaved windows). +Exit IDLE + Close all windows and quit IDLE (ask to save unsaved edit windows). Edit menu (Shell and Editor) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/Doc/library/importlib.metadata.rst b/Doc/library/importlib.metadata.rst index 99bcfeb..a6caa99 100644 --- a/Doc/library/importlib.metadata.rst +++ b/Doc/library/importlib.metadata.rst @@ -264,6 +264,7 @@ Python packages or modules:: .. versionadded:: 3.10 +.. _distributions: Distributions ============= @@ -335,6 +336,3 @@ a custom finder, return instances of this derived ``Distribution`` in the .. _`entry point API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points .. _`metadata API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api .. _`importlib_resources`: https://importlib-resources.readthedocs.io/en/latest/index.html - - -.. rubric:: Footnotes diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index ed33cbb..d7ef2ad 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -187,8 +187,9 @@ attributes: | | co_name | name with which this code | | | | object was defined | +-----------+-------------------+---------------------------+ -| | co_names | tuple of names of local | -| | | variables | +| | co_names | tuple of names other | +| | | than arguments and | +| | | function locals | +-----------+-------------------+---------------------------+ | | co_nlocals | number of local variables | +-----------+-------------------+---------------------------+ diff --git a/Doc/library/io.rst b/Doc/library/io.rst index de88c57..d512334 100644 --- a/Doc/library/io.rst +++ b/Doc/library/io.rst @@ -306,8 +306,7 @@ I/O Base Classes .. class:: IOBase - The abstract base class for all I/O classes, acting on streams of bytes. - There is no public constructor. + The abstract base class for all I/O classes. This class provides empty abstract implementations for many methods that derived classes can override selectively; the default @@ -461,8 +460,7 @@ I/O Base Classes .. class:: RawIOBase - Base class for raw binary streams. It inherits :class:`IOBase`. There is no - public constructor. + Base class for raw binary streams. It inherits :class:`IOBase`. Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives @@ -515,7 +513,7 @@ I/O Base Classes .. class:: BufferedIOBase Base class for binary streams that support some kind of buffering. - It inherits :class:`IOBase`. There is no public constructor. + It inherits :class:`IOBase`. The main difference with :class:`RawIOBase` is that methods :meth:`read`, :meth:`readinto` and :meth:`write` will try (respectively) to read as much @@ -852,8 +850,7 @@ Text I/O .. class:: TextIOBase Base class for text streams. This class provides a character and line based - interface to stream I/O. It inherits :class:`IOBase`. There is no public - constructor. + interface to stream I/O. It inherits :class:`IOBase`. :class:`TextIOBase` provides or overrides these data attributes and methods in addition to those from :class:`IOBase`: diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 61d8b86..6e1ba3c 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -813,11 +813,20 @@ which incur interpreter overhead. return starmap(func, repeat(args)) return starmap(func, repeat(args, times)) - def grouper(iterable, n, fillvalue=None): + def grouper(iterable, n, *, incomplete='fill', fillvalue=None): "Collect data into non-overlapping fixed-length chunks or blocks" - # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx + # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx + # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError + # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF args = [iter(iterable)] * n - return zip_longest(*args, fillvalue=fillvalue) + if incomplete == 'fill': + return zip_longest(*args, fillvalue=fillvalue) + if incomplete == 'strict': + return zip(*args, strict=True) + if incomplete == 'ignore': + return zip(*args) + else: + raise ValueError('Expected fill, strict, or ignore') def triplewise(iterable): "Return overlapping triplets from an iterable" @@ -884,6 +893,12 @@ which incur interpreter overhead. yield from it return true_iterator(), remainder_iterator() + def subslices(seq): + "Return all contiguous non-empty subslices of a sequence" + # subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index e81dd7e..096e649 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -569,8 +569,15 @@ The :mod:`multiprocessing` package mostly replicates the API of the .. attribute:: exitcode The child's exit code. This will be ``None`` if the process has not yet - terminated. A negative value *-N* indicates that the child was terminated - by signal *N*. + terminated. + + If the child's :meth:`run` method returned normally, the exit code + will be 0. If it terminated via :func:`sys.exit` with an integer + argument *N*, the exit code will be *N*. + + If the child terminated due to an exception not caught within + :meth:`run`, the exit code will be 1. If it was terminated by + signal *N*, the exit code will be the negative value *-N*. .. attribute:: authkey @@ -1040,9 +1047,9 @@ Miscellaneous .. versionadded:: 3.4 -.. function:: set_executable() +.. function:: set_executable(executable) - Sets the path of the Python interpreter to use when starting a child process. + Set the path of the Python interpreter to use when starting a child process. (By default :data:`sys.executable` is used). Embedders will probably need to do some thing like :: diff --git a/Doc/library/os.rst b/Doc/library/os.rst index 629a32f..2a1ea05 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -2041,7 +2041,8 @@ features: Create a directory named *path* with numeric mode *mode*. - If the directory already exists, :exc:`FileExistsError` is raised. + If the directory already exists, :exc:`FileExistsError` is raised. If a parent + directory in the path does not exist, :exc:`FileNotFoundError` is raised. .. _mkdir_modebits: @@ -4869,7 +4870,7 @@ Random numbers .. function:: urandom(size) - Return a string of *size* random bytes suitable for cryptographic use. + Return a bytestring of *size* random bytes suitable for cryptographic use. This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, diff --git a/Doc/library/pathlib-inheritance.svg b/Doc/library/pathlib-inheritance.svg index 49057f6..01f8684 100644 --- a/Doc/library/pathlib-inheritance.svg +++ b/Doc/library/pathlib-inheritance.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst index 0ec5900..cbf27d2 100644 --- a/Doc/library/queue.rst +++ b/Doc/library/queue.rst @@ -201,15 +201,14 @@ Example of how to wait for enqueued tasks to be completed:: print(f'Finished {item}') q.task_done() - # turn-on the worker thread + # Turn-on the worker thread. threading.Thread(target=worker, daemon=True).start() - # send thirty task requests to the worker + # Send thirty task requests to the worker. for item in range(30): q.put(item) - print('All task requests sent\n', end='') - # block until all tasks are done + # Block until all tasks are done. q.join() print('All work completed') diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst index 1c3bde3..e7c191b 100644 --- a/Doc/library/sqlite3.rst +++ b/Doc/library/sqlite3.rst @@ -17,7 +17,7 @@ SQLite for internal data storage. It's also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle. -The sqlite3 module was written by Gerhard Häring. It provides a SQL interface +The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by :pep:`249`, and requires SQLite 3.7.15 or newer. @@ -255,14 +255,28 @@ Module functions and constants for the connection, you can set the *cached_statements* parameter. The currently implemented default is to cache 100 statements. - If *uri* is true, *database* is interpreted as a URI. This allows you - to specify options. For example, to open a database in read-only mode - you can use:: + If *uri* is :const:`True`, *database* is interpreted as a + :abbr:`URI (Uniform Resource Identifier)` with a file path and an optional + query string. The scheme part *must* be ``"file:"``. The path can be a + relative or absolute file path. The query string allows us to pass + parameters to SQLite. Some useful URI tricks include:: - db = sqlite3.connect('file:path/to/database?mode=ro', uri=True) + # Open a database in read-only mode. + con = sqlite3.connect("file:template.db?mode=ro", uri=True) - More information about this feature, including a list of recognized options, can - be found in the `SQLite URI documentation `_. + # Don't implicitly create a new database file if it does not already exist. + # Will raise sqlite3.OperationalError if unable to open a database file. + con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True) + + # Create a shared named in-memory database. + con1 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True) + con2 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True) + con1.executescript("create table t(t); insert into t values(28);") + rows = con2.execute("select * from t").fetchall() + + More information about this feature, including a list of recognized + parameters, can be found in the + `SQLite URI documentation `_. .. audit-event:: sqlite3.connect database sqlite3.connect .. audit-event:: sqlite3.connect/handle connection_handle sqlite3.connect @@ -323,7 +337,7 @@ Connection Objects .. class:: Connection - A SQLite database connection has the following attributes and methods: + An SQLite database connection has the following attributes and methods: .. attribute:: isolation_level @@ -530,7 +544,7 @@ Connection Objects .. method:: load_extension(path) - This routine loads a SQLite extension from a shared library. You have to + This routine loads an SQLite extension from a shared library. You have to enable extension loading with :meth:`enable_load_extension` before you can use this routine. @@ -606,7 +620,7 @@ Connection Objects .. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250) - This method makes a backup of a SQLite database even while it's being accessed + This method makes a backup of an SQLite database even while it's being accessed by other clients, or concurrently by the same connection. The copy will be written into the mandatory argument *target*, that must be another :class:`Connection` instance. @@ -743,11 +757,11 @@ Cursor Objects .. method:: setinputsizes(sizes) - Required by the DB-API. Is a no-op in :mod:`sqlite3`. + Required by the DB-API. Does nothing in :mod:`sqlite3`. .. method:: setoutputsize(size [, column]) - Required by the DB-API. Is a no-op in :mod:`sqlite3`. + Required by the DB-API. Does nothing in :mod:`sqlite3`. .. attribute:: rowcount @@ -961,7 +975,7 @@ This is how SQLite types are converted to Python types by default: +-------------+----------------------------------------------+ The type system of the :mod:`sqlite3` module is extensible in two ways: you can -store additional Python types in a SQLite database via object adaptation, and +store additional Python types in an SQLite database via object adaptation, and you can let the :mod:`sqlite3` module convert SQLite types to different Python types via converters. diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst index a20f97a..3531cc3 100644 --- a/Doc/library/ssl.rst +++ b/Doc/library/ssl.rst @@ -1753,10 +1753,10 @@ to speed up repeated connections from the same clients. Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`. - :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`, - :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that + The :meth:`SSLSocket.getpeercert`, + :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compression` methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore - will not contain return meaningful values nor can they be called safely. + will not return meaningful values nor can they be called safely. The *sni_callback* function must return ``None`` to allow the TLS negotiation to continue. If a TLS failure is required, a constant diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 8fa252b..b330335 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -4796,33 +4796,54 @@ Generic Alias Type object: GenericAlias pair: Generic; Alias -``GenericAlias`` objects are created by subscripting a class (usually a -container), such as ``list[int]``. They are intended primarily for +``GenericAlias`` objects are generally created by +:ref:`subscripting ` a class. They are most often used with +:ref:`container classes `, such as :class:`list` or +:class:`dict`. For example, ``list[int]`` is a ``GenericAlias`` object created +by subscripting the ``list`` class with the argument :class:`int`. +``GenericAlias`` objects are intended primarily for use with :term:`type annotations `. -Usually, the :ref:`subscription ` of container objects calls the -method :meth:`__getitem__` of the object. However, the subscription of some -containers' classes may call the classmethod :meth:`__class_getitem__` of the -class instead. The classmethod :meth:`__class_getitem__` should return a -``GenericAlias`` object. - .. note:: - If the :meth:`__getitem__` of the class' metaclass is present, it will take - precedence over the :meth:`__class_getitem__` defined in the class (see - :pep:`560` for more details). -The ``GenericAlias`` object acts as a proxy for :term:`generic types -`, implementing *parameterized generics* - a specific instance -of a generic which provides the types for container elements. + It is generally only possible to subscript a class if the class implements + the special method :meth:`~object.__class_getitem__`. + +A ``GenericAlias`` object acts as a proxy for a :term:`generic type`, +implementing *parameterized generics*. + +For a container class, the +argument(s) supplied to a :ref:`subscription ` of the class may +indicate the type(s) of the elements an object contains. For example, +``set[bytes]`` can be used in type annotations to signify a :class:`set` in +which all the elements are of type :class:`bytes`. + +For a class which defines :meth:`~object.__class_getitem__` but is not a +container, the argument(s) supplied to a subscription of the class will often +indicate the return type(s) of one or more methods defined on an object. For +example, :mod:`regular expressions ` can be used on both the :class:`str` data +type and the :class:`bytes` data type: + +* If ``x = re.search('foo', 'foo')``, ``x`` will be a + :ref:`re.Match ` object where the return values of + ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can + represent this kind of object in type annotations with the ``GenericAlias`` + ``re.Match[str]``. -The user-exposed type for the ``GenericAlias`` object can be accessed from -:class:`types.GenericAlias` and used for :func:`isinstance` checks. It can -also be used to create ``GenericAlias`` objects directly. +* If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`), + ``y`` will also be an instance of ``re.Match``, but the return + values of ``y.group(0)`` and ``y[0]`` will both be of type + :class:`bytes`. In type annotations, we would represent this + variety of :ref:`re.Match ` objects with ``re.Match[bytes]``. + +``GenericAlias`` objects are instances of the class +:class:`types.GenericAlias`, which can also be used to create ``GenericAlias`` +objects directly. .. describe:: T[X, Y, ...] - Creates a ``GenericAlias`` representing a type ``T`` containing elements - of types *X*, *Y*, and more depending on the ``T`` used. + Creates a ``GenericAlias`` representing a type ``T`` parameterized by types + *X*, *Y*, and more depending on the ``T`` used. For example, a function expecting a :class:`list` containing :class:`float` elements:: @@ -4847,7 +4868,7 @@ The builtin functions :func:`isinstance` and :func:`issubclass` do not accept The Python runtime does not enforce :term:`type annotations `. This extends to generic types and their type parameters. When creating -an object from a ``GenericAlias``, container elements are not checked +a container object from a ``GenericAlias``, the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors:: @@ -4874,8 +4895,8 @@ Calling :func:`repr` or :func:`str` on a generic shows the parameterized type:: >>> str(list[int]) 'list[int]' -The :meth:`__getitem__` method of generics will raise an exception to disallow -mistakes like ``dict[str][str]``:: +The :meth:`~object.__getitem__` method of generic containers will raise an +exception to disallow mistakes like ``dict[str][str]``:: >>> dict[str][str] Traceback (most recent call last): @@ -4884,7 +4905,7 @@ mistakes like ``dict[str][str]``:: However, such expressions are valid when :ref:`type variables ` are used. The index must have as many elements as there are type variable items -in the ``GenericAlias`` object's :attr:`__args__ `. :: +in the ``GenericAlias`` object's :attr:`~genericalias.__args__`. :: >>> from typing import TypeVar >>> Y = TypeVar('Y') @@ -4892,10 +4913,11 @@ in the ``GenericAlias`` object's :attr:`__args__ `. :: dict[str, int] -Standard Generic Collections -^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Standard Generic Classes +^^^^^^^^^^^^^^^^^^^^^^^^ -These standard library collections support parameterized generics. +The following standard library classes support parameterized generics. This +list is non-exhaustive. * :class:`tuple` * :class:`list` @@ -4933,12 +4955,29 @@ These standard library collections support parameterized generics. * :class:`collections.abc.ValuesView` * :class:`contextlib.AbstractContextManager` * :class:`contextlib.AbstractAsyncContextManager` +* :class:`dataclasses.Field` +* :class:`functools.cached_property` +* :class:`functools.partialmethod` +* :class:`os.PathLike` +* :class:`queue.LifoQueue` +* :class:`queue.Queue` +* :class:`queue.PriorityQueue` +* :class:`queue.SimpleQueue` * :ref:`re.Pattern ` * :ref:`re.Match ` +* :class:`shelve.BsdDbShelf` +* :class:`shelve.DbfilenameShelf` +* :class:`shelve.Shelf` +* :class:`types.MappingProxyType` +* :class:`weakref.WeakKeyDictionary` +* :class:`weakref.WeakMethod` +* :class:`weakref.WeakSet` +* :class:`weakref.WeakValueDictionary` + -Special Attributes of Generic Alias -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Special Attributes of ``GenericAlias`` objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ All parameterized generics implement special read-only attributes. @@ -4953,8 +4992,8 @@ All parameterized generics implement special read-only attributes. .. attribute:: genericalias.__args__ This attribute is a :class:`tuple` (possibly of length 1) of generic - types passed to the original :meth:`__class_getitem__` - of the generic container:: + types passed to the original :meth:`~object.__class_getitem__` of the + generic class:: >>> dict[str, list[int]].__args__ (, list[int]) @@ -4979,9 +5018,17 @@ All parameterized generics implement special read-only attributes. .. seealso:: - * :pep:`585` -- "Type Hinting Generics In Standard Collections" - * :meth:`__class_getitem__` -- Used to implement parameterized generics. - * :ref:`generics` -- Generics in the :mod:`typing` module. + :pep:`484` - Type Hints + Introducing Python's framework for type annotations. + + :pep:`585` - Type Hinting Generics In Standard Collections + Introducing the ability to natively parameterize standard-library + classes, provided they implement the special class method + :meth:`~object.__class_getitem__`. + + :ref:`Generics`, :ref:`user-defined generics ` and :class:`typing.Generic` + Documentation on how to implement generic classes that can be + parameterized at runtime and understood by static type-checkers. .. versionadded:: 3.9 diff --git a/Doc/library/string.rst b/Doc/library/string.rst index b27782f..b710864 100644 --- a/Doc/library/string.rst +++ b/Doc/library/string.rst @@ -428,12 +428,13 @@ character of ``'0'`` with an *alignment* type of ``'='``. Preceding the *width* field by ``'0'`` no longer affects the default alignment for strings. -The *precision* is a decimal number indicating how many digits should be -displayed after the decimal point for a floating point value formatted with -``'f'`` and ``'F'``, or before and after the decimal point for a floating point -value formatted with ``'g'`` or ``'G'``. For non-number types the field +The *precision* is a decimal integer indicating how many digits should be +displayed after the decimal point for presentation types +``'f'`` and ``'F'``, or before and after the decimal point for presentation +types ``'g'`` or ``'G'``. For string presentation types the field indicates the maximum field size - in other words, how many characters will be -used from the field content. The *precision* is not allowed for integer values. +used from the field content. The *precision* is not allowed for integer +presentation types. Finally, the *type* determines how the data should be presented. diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst index 21a96a4..ab9f1d8 100644 --- a/Doc/library/subprocess.rst +++ b/Doc/library/subprocess.rst @@ -264,13 +264,14 @@ default values. The arguments that are most commonly needed are: *stdin*, *stdout* and *stderr* specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive - integer), an existing file object, and ``None``. :data:`PIPE` indicates - that a new pipe to the child should be created. :data:`DEVNULL` indicates - that the special file :data:`os.devnull` will be used. With the default - settings of ``None``, no redirection will occur; the child's file handles - will be inherited from the parent. Additionally, *stderr* can be - :data:`STDOUT`, which indicates that the stderr data from the child - process should be captured into the same file handle as for *stdout*. + integer), an existing file object with a valid file descriptor, and ``None``. + :data:`PIPE` indicates that a new pipe to the child should be created. + :data:`DEVNULL` indicates that the special file :data:`os.devnull` will + be used. With the default settings of ``None``, no redirection will occur; + the child's file handles will be inherited from the parent. + Additionally, *stderr* can be :data:`STDOUT`, which indicates that the + stderr data from the child process should be captured into the same file + handle as for *stdout*. .. index:: single: universal newlines; subprocess module @@ -482,13 +483,14 @@ functions. *stdin*, *stdout* and *stderr* specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive - integer), an existing :term:`file object`, and ``None``. :data:`PIPE` - indicates that a new pipe to the child should be created. :data:`DEVNULL` - indicates that the special file :data:`os.devnull` will be used. With the - default settings of ``None``, no redirection will occur; the child's file - handles will be inherited from the parent. Additionally, *stderr* can be - :data:`STDOUT`, which indicates that the stderr data from the applications - should be captured into the same file handle as for stdout. + integer), an existing :term:`file object` with a valid file descriptor, + and ``None``. :data:`PIPE` indicates that a new pipe to the child should + be created. :data:`DEVNULL` indicates that the special file + :data:`os.devnull` will be used. With the default settings of ``None``, + no redirection will occur; the child's file handles will be inherited from + the parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates + that the stderr data from the applications should be captured into the same + file handle as for stdout. If *preexec_fn* is set to a callable object, this object will be called in the child process just before the child is executed. diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 29cb54b..b59fa2c 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -429,10 +429,7 @@ always available. .. function:: exit([arg]) - Exit from Python. This is implemented by raising the :exc:`SystemExit` - exception, so cleanup actions specified by finally clauses of :keyword:`try` - statements are honored, and it is possible to intercept the exit attempt at - an outer level. + Raise a :exc:`SystemExit` exception, signaling an intention to exit the interpreter. The optional argument *arg* can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero @@ -449,7 +446,8 @@ always available. Since :func:`exit` ultimately "only" raises an exception, it will only exit the process when called from the main thread, and the exception is not - intercepted. + intercepted. Cleanup actions specified by finally clauses of :keyword:`try` statements + are honored, and it is possible to intercept the exit attempt at an outer level. .. versionchanged:: 3.6 If an error occurs in the cleanup after the Python interpreter diff --git a/Doc/library/tempfile.rst b/Doc/library/tempfile.rst index b8a5fa0..6b23a1b 100644 --- a/Doc/library/tempfile.rst +++ b/Doc/library/tempfile.rst @@ -62,6 +62,9 @@ The module defines the following user-callable items: The :py:data:`os.O_TMPFILE` flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later). + On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias + for NamedTemporaryFile. + .. audit-event:: tempfile.mkstemp fullpath tempfile.TemporaryFile .. versionchanged:: 3.5 diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst index 8c76643..14434fb 100644 --- a/Doc/library/threading.rst +++ b/Doc/library/threading.rst @@ -428,8 +428,8 @@ since it is impossible to detect the termination of alien threads. .. attribute:: daemon - A boolean value indicating whether this thread is a daemon thread (True) - or not (False). This must be set before :meth:`~Thread.start` is called, + A boolean value indicating whether this thread is a daemon thread (``True``) + or not (``False``). This must be set before :meth:`~Thread.start` is called, otherwise :exc:`RuntimeError` is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to @@ -503,7 +503,7 @@ All methods are executed atomically. value, block for at most the number of seconds specified by *timeout* and as long as the lock cannot be acquired. A *timeout* argument of ``-1`` specifies an unbounded wait. It is forbidden to specify a *timeout* - when *blocking* is false. + when *blocking* is ``False``. The return value is ``True`` if the lock is acquired successfully, ``False`` if not (for example if the *timeout* expired). @@ -531,7 +531,7 @@ All methods are executed atomically. .. method:: locked() - Return true if the lock is acquired. + Return ``True`` if the lock is acquired. @@ -580,17 +580,17 @@ Reentrant locks also support the :ref:`context management protocol ` is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. - When invoked with the *blocking* argument set to true, do the same thing as when + When invoked with the *blocking* argument set to ``True``, do the same thing as when called without arguments, and return ``True``. - When invoked with the *blocking* argument set to false, do not block. If a call + When invoked with the *blocking* argument set to ``False``, do not block. If a call without an argument would block, return ``False`` immediately; otherwise, do the same thing as when called without arguments, and return ``True``. When invoked with the floating-point *timeout* argument set to a positive value, block for at most the number of seconds specified by *timeout* and as long as the lock cannot be acquired. Return ``True`` if the lock has - been acquired, false if the timeout has elapsed. + been acquired, ``False`` if the timeout has elapsed. .. versionchanged:: 3.2 The *timeout* parameter is new. @@ -831,7 +831,7 @@ Semaphores also support the :ref:`context management protocol `. thread will be awoken by each call to :meth:`~Semaphore.release`. The order in which threads are awoken should not be relied on. - When invoked with *blocking* set to false, do not block. If a call + When invoked with *blocking* set to ``False``, do not block. If a call without an argument would block, return ``False`` immediately; otherwise, do the same thing as when called without arguments, and return ``True``. diff --git a/Doc/library/time.rst b/Doc/library/time.rst index cfd67e8..ed1f71d 100644 --- a/Doc/library/time.rst +++ b/Doc/library/time.rst @@ -259,6 +259,12 @@ Functions :const:`None`, the current time as returned by :func:`.time` is used. The dst flag is set to ``1`` when DST applies to the given time. + :func:`localtime` may raise :exc:`OverflowError`, if the timestamp is + outside the range of values supported by the platform C :c:func:`localtime` + or :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or + :c:func:`gmtime` failure. It's common for this to be restricted to years + between 1970 and 2038. + .. function:: mktime(t) @@ -456,10 +462,10 @@ Functions | | negative time difference from UTC/GMT of the | | | | form +HHMM or -HHMM, where H represents decimal| | | | hour digits and M represents decimal minute | | - | | digits [-23:59, +23:59]. | | + | | digits [-23:59, +23:59]. [1]_ | | +-----------+------------------------------------------------+-------+ | ``%Z`` | Time zone name (no characters if no time zone | | - | | exists). | | + | | exists). Deprecated. [1]_ | | +-----------+------------------------------------------------+-------+ | ``%%`` | A literal ``'%'`` character. | | +-----------+------------------------------------------------+-------+ @@ -480,7 +486,7 @@ Functions calculations when the day of the week and the year are specified. Here is an example, a format for dates compatible with that specified in the - :rfc:`2822` Internet email standard. [#]_ :: + :rfc:`2822` Internet email standard. [1]_ :: >>> from time import gmtime, strftime >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) @@ -908,10 +914,9 @@ Timezone Constants .. rubric:: Footnotes -.. [#] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the - preferred hour/minute offset is not supported by all ANSI C libraries. Also, a +.. [1] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the + preferred hour/minute offset is not supported by all ANSI C libraries. Also, a strict reading of the original 1982 :rfc:`822` standard calls for a two-digit - year (%y rather than %Y), but practice moved to 4-digit years long before the + year (``%y`` rather than ``%Y``), but practice moved to 4-digit years long before the year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`. - diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst index d4e8b749..ca21fe6 100644 --- a/Doc/library/timeit.rst +++ b/Doc/library/timeit.rst @@ -282,6 +282,13 @@ It is possible to provide a setup statement that is executed only once at the be $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' 1000000 loops, best of 5: 0.342 usec per loop +In the output, there are three fields. The loop count, which tells you how many +times the statement body was run per timing loop repetition. The repetition +count ('best of 5') which tells you how many times the timing loop was +repeated, and finally the time the statement body took on average within the +best repetition of the timing loop. That is, the time the fastest repetition +took divided by the loop count. + :: >>> import timeit diff --git a/Doc/library/tk_msg.png b/Doc/library/tk_msg.png index c122d8f..6495e63 100644 Binary files a/Doc/library/tk_msg.png and b/Doc/library/tk_msg.png differ diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst index a48bc13..65395d8 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -756,8 +756,8 @@ callback color Colors can be given as the names of X colors in the rgb.txt file, or as strings - representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit" - ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here + representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit: + ``"#RRRGGGBBB"``, or 16 bit: ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here represent any legal hex digit. See page 160 of Ousterhout's book for details. cursor diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 929749b..6fa3eee 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -32,6 +32,10 @@ In the function ``greeting``, the argument ``name`` is expected to be of type :class:`str` and the return type :class:`str`. Subtypes are accepted as arguments. +New features are frequently added to the ``typing`` module. +The `typing_extensions `_ package +provides backports of these new features to older versions of Python. + .. _relevant-peps: Relevant PEPs @@ -1384,9 +1388,6 @@ These are not used in annotations. They are building blocks for declaring types. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') - The type info for introspection can be accessed via ``Point2D.__annotations__``, - ``Point2D.__total__``, ``Point2D.__required_keys__``, and - ``Point2D.__optional_keys__``. To allow using this feature with older versions of Python that do not support :pep:`526`, ``TypedDict`` supports two additional equivalent syntactic forms:: @@ -1394,6 +1395,18 @@ These are not used in annotations. They are building blocks for declaring types. Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + The functional syntax should also be used when any of the keys are not valid + :ref:`identifiers`, for example because they are keywords or contain hyphens. + Example:: + + # raises SyntaxError + class Point2D(TypedDict): + in: int # 'in' is a keyword + x-y: int # name with hyphens + + # OK, functional syntax + Point2D = TypedDict('Point2D', {'in': int, 'x-y': int}) + By default, all keys must be present in a ``TypedDict``. It is possible to override this by specifying totality. Usage:: @@ -1407,6 +1420,82 @@ These are not used in annotations. They are building blocks for declaring types. ``True`` as the value of the ``total`` argument. ``True`` is the default, and makes all items defined in the class body required. + It is possible for a ``TypedDict`` type to inherit from one or more other ``TypedDict`` types + using the class-based syntax. + Usage:: + + class Point3D(Point2D): + z: int + + ``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to this + definition:: + + class Point3D(TypedDict): + x: int + y: int + z: int + + A ``TypedDict`` cannot inherit from a non-TypedDict class, + notably including :class:`Generic`. For example:: + + class X(TypedDict): + x: int + + class Y(TypedDict): + y: int + + class Z(object): pass # A non-TypedDict class + + class XY(X, Y): pass # OK + + class XZ(X, Z): pass # raises TypeError + + T = TypeVar('T') + class XT(X, Generic[T]): pass # raises TypeError + + A ``TypedDict`` can be introspected via annotations dicts + (see :ref:`annotations-howto` for more information on annotations best practices), + :attr:`__total__`, :attr:`__required_keys__`, and :attr:`__optional_keys__`. + + .. attribute:: __total__ + + ``Point2D.__total__`` gives the value of the ``total`` argument. + Example:: + + >>> from typing import TypedDict + >>> class Point2D(TypedDict): pass + >>> Point2D.__total__ + True + >>> class Point2D(TypedDict, total=False): pass + >>> Point2D.__total__ + False + >>> class Point3D(Point2D): pass + >>> Point3D.__total__ + True + + .. attribute:: __required_keys__ + .. attribute:: __optional_keys__ + + ``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return + :class:`frozenset` objects containing required and non-required keys, respectively. + Currently the only way to declare both required and non-required keys in the + same ``TypedDict`` is mixed inheritance, declaring a ``TypedDict`` with one value + for the ``total`` argument and then inheriting it from another ``TypedDict`` with + a different value for ``total``. + Usage:: + + >>> class Point2D(TypedDict, total=False): + ... x: int + ... y: int + ... + >>> class Point3D(Point2D): + ... z: int + ... + >>> Point3D.__required_keys__ == frozenset({'z'}) + True + >>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) + True + See :pep:`589` for more examples and detailed rules of using ``TypedDict``. .. versionadded:: 3.8 diff --git a/Doc/library/uuid.rst b/Doc/library/uuid.rst index 415e25b..ddfbbda 100644 --- a/Doc/library/uuid.rst +++ b/Doc/library/uuid.rst @@ -118,7 +118,7 @@ which relays any information about the UUID's safety, using this enumeration: .. attribute:: UUID.hex - The UUID as a 32-character hexadecimal string. + The UUID as a 32-character lowercase hexadecimal string. .. attribute:: UUID.int diff --git a/Doc/library/xml.dom.rst b/Doc/library/xml.dom.rst index 98454e1..b387240 100644 --- a/Doc/library/xml.dom.rst +++ b/Doc/library/xml.dom.rst @@ -73,7 +73,7 @@ implementations are free to support the strict mapping from IDL). See section `Document Object Model (DOM) Level 1 Specification `_ The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`. - `Python Language Mapping Specification `_ + `Python Language Mapping Specification `_ This specifies the mapping from OMG IDL to Python. diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index be1f714..55ac99c 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1904,7 +1904,7 @@ Customizing class creation -------------------------- Whenever a class inherits from another class, :meth:`~object.__init_subclass__` is -called on that class. This way, it is possible to write classes which +called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they're applied to, ``__init_subclass__`` solely applies to future subclasses of the diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index d4aae29..9f136c9 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -810,30 +810,44 @@ Subscriptions object: dictionary pair: sequence; item -Subscription of a sequence (string, tuple or list) or mapping (dictionary) -object usually selects an item from the collection: +The subscription of an instance of a :ref:`container class ` +will generally select an element from the container. The subscription of a +:term:`generic class ` will generally return a +:ref:`GenericAlias ` object. .. productionlist:: python-grammar subscription: `primary` "[" `expression_list` "]" -The primary must evaluate to an object that supports subscription (lists or -dictionaries for example). User-defined objects can support subscription by -defining a :meth:`__getitem__` method. +When an object is subscripted, the interpreter will evaluate the primary and +the expression list. -For built-in objects, there are two types of objects that support subscription: +The primary must evaluate to an object that supports subscription. An object +may support subscription through defining one or both of +:meth:`~object.__getitem__` and :meth:`~object.__class_getitem__`. When the +primary is subscripted, the evaluated result of the expression list will be +passed to one of these methods. For more details on when ``__class_getitem__`` +is called instead of ``__getitem__``, see :ref:`classgetitem-versus-getitem`. -If the primary is a mapping, the expression list must evaluate to an object -whose value is one of the keys of the mapping, and the subscription selects the -value in the mapping that corresponds to that key. (The expression list is a -tuple except if it has exactly one item.) +If the expression list contains at least one comma, it will evaluate to a +:class:`tuple` containing the items of the expression list. Otherwise, the +expression list will evaluate to the value of the list's sole member. -If the primary is a sequence, the expression list must evaluate to an integer -or a slice (as discussed in the following section). +For built-in objects, there are two types of objects that support subscription +via :meth:`~object.__getitem__`: + +1. Mappings. If the primary is a :term:`mapping`, the expression list must + evaluate to an object whose value is one of the keys of the mapping, and the + subscription selects the value in the mapping that corresponds to that key. + An example of a builtin mapping class is the :class:`dict` class. +2. Sequences. If the primary is a :term:`sequence`, the expression list must + evaluate to an :class:`int` or a :class:`slice` (as discussed in the + following section). Examples of builtin sequence classes include the + :class:`str`, :class:`list` and :class:`tuple` classes. The formal syntax makes no special provision for negative indices in -sequences; however, built-in sequences all provide a :meth:`__getitem__` +:term:`sequences `. However, built-in sequences all provide a :meth:`~object.__getitem__` method that interprets negative indices by adding the length of the sequence -to the index (so that ``x[-1]`` selects the last item of ``x``). The +to the index so that, for example, ``x[-1]`` selects the last item of ``x``. The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing @@ -844,14 +858,10 @@ this method will need to explicitly add that support. single: character pair: string; item -A string's items are characters. A character is not a separate data type but a +A :class:`string ` is a special kind of sequence whose items are +*characters*. A character is not a separate data type but a string of exactly one character. -Subscription of certain :term:`classes ` or :term:`types ` -creates a :ref:`generic alias `. -In this case, user-defined classes can support subscription by providing a -:meth:`__class_getitem__` classmethod. - .. _slicings: diff --git a/Doc/reference/import.rst b/Doc/reference/import.rst index 9834f95..c01535d 100644 --- a/Doc/reference/import.rst +++ b/Doc/reference/import.rst @@ -84,9 +84,9 @@ considered a package. All modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python's standard attribute access syntax. Thus -you might have a module called :mod:`sys` and a package called :mod:`email`, -which in turn has a subpackage called :mod:`email.mime` and a module within -that subpackage called :mod:`email.mime.text`. +you might have a package called :mod:`email`, which in turn has a subpackage +called :mod:`email.mime` and a module within that subpackage called +:mod:`email.mime.text`. Regular packages diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst index bb1209d..92dfcb0 100644 --- a/Doc/reference/simple_stmts.rst +++ b/Doc/reference/simple_stmts.rst @@ -563,10 +563,10 @@ The :keyword:`!raise` statement .. productionlist:: python-grammar raise_stmt: "raise" [`expression` ["from" `expression`]] -If no expressions are present, :keyword:`raise` re-raises the last exception -that was active in the current scope. If no exception is active in the current -scope, a :exc:`RuntimeError` exception is raised indicating that this is an -error. +If no expressions are present, :keyword:`raise` re-raises the +exception that is currently being handled, which is also known as the *active exception*. +If there isn't currently an active exception, a :exc:`RuntimeError` exception is raised +indicating that this is an error. Otherwise, :keyword:`raise` evaluates the first expression as the exception object. It must be either a subclass or an instance of :class:`BaseException`. @@ -581,8 +581,8 @@ The :dfn:`type` of the exception is the exception instance's class, the A traceback object is normally created automatically when an exception is raised and attached to it as the :attr:`__traceback__` attribute, which is writable. You can create an exception and set your own traceback in one step using the -:meth:`with_traceback` exception method (which returns the same exception -instance, with its traceback set to its argument), like so:: +:meth:`~BaseException.with_traceback` exception method (which returns the +same exception instance, with its traceback set to its argument), like so:: raise Exception("foo occurred").with_traceback(tracebackobj) @@ -614,8 +614,10 @@ exceptions will be printed:: File "", line 4, in RuntimeError: Something bad happened -A similar mechanism works implicitly if an exception is raised inside an -exception handler or a :keyword:`finally` clause: the previous exception is then +A similar mechanism works implicitly if a new exception is raised when +an exception is already being handled. An exception may be handled +when an :keyword:`except` or :keyword:`finally` clause, or a +:keyword:`with` statement, is used. The previous exception is then attached as the new exception's :attr:`__context__` attribute:: >>> try: diff --git a/Doc/tools/extensions/escape4chm.py b/Doc/tools/extensions/escape4chm.py index e999971..8997097 100644 --- a/Doc/tools/extensions/escape4chm.py +++ b/Doc/tools/extensions/escape4chm.py @@ -5,6 +5,7 @@ effect on some MBCS Windows systems. https://bugs.python.org/issue32174 """ +import pathlib import re from html.entities import codepoint2name @@ -39,12 +40,12 @@ def fixup_keywords(app, exception): return getLogger(__name__).info('fixing HTML escapes in keywords file...') - outdir = app.builder.outdir + outdir = pathlib.Path(app.builder.outdir) outname = app.builder.config.htmlhelp_basename - with app.builder.open_file(outdir, outname + '.hhk', 'r') as f: + with open(outdir / (outname + '.hhk'), 'rb') as f: index = f.read() - with app.builder.open_file(outdir, outname + '.hhk', 'w') as f: - f.write(index.replace(''', ''')) + with open(outdir / (outname + '.hhk'), 'wb') as f: + f.write(index.replace(b''', b''')) def setup(app): # `html-page-context` event emitted when the HTML builder has diff --git a/Doc/tools/susp-ignored.csv b/Doc/tools/susp-ignored.csv index 2453faa..9f4a44f 100644 --- a/Doc/tools/susp-ignored.csv +++ b/Doc/tools/susp-ignored.csv @@ -212,7 +212,10 @@ library/socket,,:can,"return (can_id, can_dlc, data[:can_dlc])" library/socket,,:len,fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) library/sqlite3,,:year,"cur.execute(""select * from lang where first_appeared=:year"", {""year"": 1972})" library/sqlite3,,:memory, -library/sqlite3,,:path,"db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)" +library/sqlite3,,:template,"con = sqlite3.connect(""file:template.db?mode=ro"", uri=True)" +library/sqlite3,,:nosuchdb,"con = sqlite3.connect(""file:nosuchdb.db?mode=rw"", uri=True)" +library/sqlite3,,:mem1,"con1 = sqlite3.connect(""file:mem1?mode=memory&cache=shared"", uri=True)" +library/sqlite3,,:mem1,"con2 = sqlite3.connect(""file:mem1?mode=memory&cache=shared"", uri=True)" library/ssl,,:My,"Organizational Unit Name (eg, section) []:My Group" library/ssl,,:My,"Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc." library/ssl,,:myserver,"Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com" diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst index fad8746..f6e013b 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -250,7 +250,7 @@ at a more abstract level. The :keyword:`!pass` is silently ignored:: :keyword:`!match` Statements ============================ -A match statement takes an expression and compares its value to successive +A :keyword:`match` statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it can also extract components (sequence elements or @@ -884,7 +884,7 @@ zero or more normal arguments may occur. :: file.write(separator.join(args)) -Normally, these ``variadic`` arguments will be last in the list of formal +Normally, these *variadic* arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the ``*args`` parameter are 'keyword-only' arguments, meaning that they can only be used as diff --git a/Doc/using/win_installer.png b/Doc/using/win_installer.png index 9c18ff1..03bf2d7 100644 Binary files a/Doc/using/win_installer.png and b/Doc/using/win_installer.png differ diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst index 68ee09c..cad7f69 100644 --- a/Doc/using/windows.rst +++ b/Doc/using/windows.rst @@ -129,8 +129,8 @@ suppressing the UI in order to change some of the defaults. To completely hide the installer UI and install Python silently, pass the ``/quiet`` option. To skip past the user interaction but still display progress and errors, pass the ``/passive`` option. The ``/uninstall`` -option may be passed to immediately begin removing Python - no prompt will be -displayed. +option may be passed to immediately begin removing Python - no confirmation +prompt will be displayed. All other options are passed as ``name=value``, where the value is usually ``0`` to disable a feature, ``1`` to enable a feature, or a path. The full list diff --git a/Doc/whatsnew/3.10.rst b/Doc/whatsnew/3.10.rst index c07523c..5788e32 100644 --- a/Doc/whatsnew/3.10.rst +++ b/Doc/whatsnew/3.10.rst @@ -1137,10 +1137,18 @@ IDLE and idlelib ---------------- Make IDLE invoke :func:`sys.excepthook` (when started without '-n'). -User hooks were previously ignored. (Patch by Ken Hilton in +User hooks were previously ignored. (Contributed by Ken Hilton in :issue:`43008`.) -This change was backported to a 3.9 maintenance release. +Rearrange the settings dialog. Split the General tab into Windows +and Shell/Ed tabs. Move help sources, which extend the Help menu, to the +Extensions tab. Make space for new options and shorten the dialog. The +latter makes the dialog better fit small screens. (Contributed by Terry Jan +Reedy in :issue:`40468`.) Move the indent space setting from the Font tab to +the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in +:issue:`33962`.) + +The changes above were backported to a 3.9 maintenance release. Add a Shell sidebar. Move the primary prompt ('>>>') to the sidebar. Add secondary prompts ('...') to the sidebar. Left click and optional @@ -1153,18 +1161,20 @@ in :issue:`37903`.) Use spaces instead of tabs to indent interactive code. This makes interactive code entries 'look right'. Making this feasible was a -major motivation for adding the shell sidebar. Contributed by +major motivation for adding the shell sidebar. (Contributed by Terry Jan Reedy in :issue:`37892`.) -We expect to backport these shell changes to a future 3.9 maintenance -release. - Highlight the new :ref:`soft keywords ` :keyword:`match`, :keyword:`case `, and :keyword:`_ ` in pattern-matching statements. However, this highlighting is not perfect and will be incorrect in some rare cases, including some ``_``-s in ``case`` patterns. (Contributed by Tal Einat in :issue:`44010`.) +New in 3.10 maintenance releases. + +Apply syntax highlighting to `.pyi` files. (Contributed by Alex +Waygood and Terry Jan Reedy in :issue:`45447`.) + importlib.metadata ------------------ diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst index 1199535..dcbd092 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -538,7 +538,7 @@ Other Language Changes * The new :option:`-X` ``importtime`` option or the :envvar:`PYTHONPROFILEIMPORTTIME` environment variable can be used to show the timing of each module import. - (Contributed by Victor Stinner in :issue:`31415`.) + (Contributed by Inada Naoki in :issue:`31415`.) New Modules diff --git a/Doc/whatsnew/3.9.rst b/Doc/whatsnew/3.9.rst index 296c64d..e2455bc 100644 --- a/Doc/whatsnew/3.9.rst +++ b/Doc/whatsnew/3.9.rst @@ -484,8 +484,25 @@ Najera in :issue:`38944`.) Added keywords to module name completion list. (Contributed by Terry J. Reedy in :issue:`37765`.) +New in 3.9 maintenance releases + +Make IDLE invoke :func:`sys.excepthook` (when started without '-n'). +User hooks were previously ignored. (Contributed by Ken Hilton in +:issue:`43008`.) + The changes above have been backported to 3.8 maintenance releases. +Rearrange the settings dialog. Split the General tab into Windows +and Shell/Ed tabs. Move help sources, which extend the Help menu, to the +Extensions tab. Make space for new options and shorten the dialog. The +latter makes the dialog better fit small screens. (Contributed by Terry Jan +Reedy in :issue:`40468`.) Move the indent space setting from the Font tab to +the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in +:issue:`33962`.) + +Apply syntax highlighting to `.pyi` files. (Contributed by Alex +Waygood and Terry Jan Reedy in :issue:`45447`.) + imaplib ------- diff --git a/Grammar/python.gram b/Grammar/python.gram index f730658..99e0135 100644 --- a/Grammar/python.gram +++ b/Grammar/python.gram @@ -846,6 +846,7 @@ invalid_kwarg: RAISE_SYNTAX_ERROR_KNOWN_RANGE( a, b, "expression cannot contain assignment, perhaps you meant \"==\"?") } +# IMPORTANT: Note that the "_without_invalid" suffix causes the rule to not call invalid rules under it expression_without_invalid[expr_ty]: | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) } | disjunction @@ -863,14 +864,14 @@ invalid_expression: RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") } | a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") } -invalid_named_expression: +invalid_named_expression(memo): | a=expression ':=' expression { RAISE_SYNTAX_ERROR_KNOWN_LOCATION( a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) } | a=NAME '=' b=bitwise_or !('='|':=') { - p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") } + RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Maybe you meant '==' or ':=' instead of '='?") } | !(list|tuple|genexp|'True'|'None'|'False') a=bitwise_or b='=' bitwise_or !('='|':=') { - p->in_raw_rule ? NULL : RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?", + RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot assign to %s here. Maybe you meant '==' instead of '='?", _PyPegen_get_expr_name(a)) } invalid_assignment: diff --git a/Include/cpython/compile.h b/Include/cpython/compile.h index a202c0b..518a376 100644 --- a/Include/cpython/compile.h +++ b/Include/cpython/compile.h @@ -18,8 +18,10 @@ #define PyCF_IGNORE_COOKIE 0x0800 #define PyCF_TYPE_COMMENTS 0x1000 #define PyCF_ALLOW_TOP_LEVEL_AWAIT 0x2000 +#define PyCF_ALLOW_INCOMPLETE_INPUT 0x4000 #define PyCF_COMPILE_MASK (PyCF_ONLY_AST | PyCF_ALLOW_TOP_LEVEL_AWAIT | \ - PyCF_TYPE_COMMENTS | PyCF_DONT_IMPLY_DEDENT) + PyCF_TYPE_COMMENTS | PyCF_DONT_IMPLY_DEDENT | \ + PyCF_ALLOW_INCOMPLETE_INPUT) typedef struct { int cf_flags; /* bitmask of CO_xxx flags relevant to future */ diff --git a/Include/errcode.h b/Include/errcode.h index 2e07fc2..54ae929 100644 --- a/Include/errcode.h +++ b/Include/errcode.h @@ -26,6 +26,8 @@ extern "C" { #define E_TOODEEP 20 /* Too many indentation levels */ #define E_DEDENT 21 /* No matching outer block for dedent */ #define E_DECODE 22 /* Error in decoding into Unicode */ +#define E_EOFS 23 /* EOF in triple-quoted string */ +#define E_EOLS 24 /* EOL in single-quoted string */ #define E_LINECONT 25 /* Unexpected characters after a line continuation */ #define E_BADSINGLE 27 /* Ill-formed single statement input */ #define E_INTERACT_STOP 28 /* Interactive mode stopped tokenization */ diff --git a/Include/patchlevel.h b/Include/patchlevel.h index 5769674..5bb246e 100644 --- a/Include/patchlevel.h +++ b/Include/patchlevel.h @@ -18,12 +18,12 @@ /*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 10 -#define PY_MICRO_VERSION 2 +#define PY_MICRO_VERSION 3 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL #define PY_RELEASE_SERIAL 0 /* Version as a string */ -#define PY_VERSION "3.10.2" +#define PY_VERSION "3.10.3" /*--end constants--*/ /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py index 87a9cd2..40417dc 100644 --- a/Lib/_collections_abc.py +++ b/Lib/_collections_abc.py @@ -500,7 +500,10 @@ class _CallableGenericAlias(GenericAlias): if subparams: subargs = tuple(subst[x] for x in subparams) arg = arg[subargs] - new_args.append(arg) + if isinstance(arg, tuple): + new_args.extend(arg) + else: + new_args.append(arg) # args[0] occurs due to things like Z[[int, str, bool]] from PEP 612 if not isinstance(new_args[0], list): @@ -868,7 +871,7 @@ class KeysView(MappingView, Set): __slots__ = () @classmethod - def _from_iterable(self, it): + def _from_iterable(cls, it): return set(it) def __contains__(self, key): @@ -886,7 +889,7 @@ class ItemsView(MappingView, Set): __slots__ = () @classmethod - def _from_iterable(self, it): + def _from_iterable(cls, it): return set(it) def __contains__(self, item): diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 56e9a0c..fb867fb 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -338,8 +338,7 @@ except AttributeError: class IOBase(metaclass=abc.ABCMeta): - """The abstract base class for all I/O classes, acting on streams of - bytes. There is no public constructor. + """The abstract base class for all I/O classes. This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations @@ -1845,7 +1844,7 @@ class TextIOBase(IOBase): """Base class for text I/O. This class provides a character and line based interface to stream - I/O. There is no public constructor. + I/O. """ def read(self, size=-1): diff --git a/Lib/argparse.py b/Lib/argparse.py index e177e4f..2c0dd85 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -726,7 +726,7 @@ def _get_action_name(argument): if argument is None: return None elif argument.option_strings: - return '/'.join(argument.option_strings) + return '/'.join(argument.option_strings) elif argument.metavar not in (None, SUPPRESS): return argument.metavar elif argument.dest not in (None, SUPPRESS): @@ -878,7 +878,7 @@ class BooleanOptionalAction(Action): option_string = '--no-' + option_string[2:] _option_strings.append(option_string) - if help is not None and default is not None: + if help is not None and default is not None and default is not SUPPRESS: help += " (default: %(default)s)" super().__init__( @@ -1256,9 +1256,9 @@ class FileType(object): # the special argument "-" means sys.std{in,out} if string == '-': if 'r' in self._mode: - return _sys.stdin - elif 'w' in self._mode: - return _sys.stdout + return _sys.stdin.buffer if 'b' in self._mode else _sys.stdin + elif any(c in self._mode for c in 'wax'): + return _sys.stdout.buffer if 'b' in self._mode else _sys.stdout else: msg = _('argument "-" with mode %r') % self._mode raise ValueError(msg) diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py index f726e91..952da11 100644 --- a/Lib/asyncio/base_events.py +++ b/Lib/asyncio/base_events.py @@ -49,7 +49,7 @@ from . import trsock from .log import logger -__all__ = 'BaseEventLoop', +__all__ = 'BaseEventLoop','Server', # Minimum number of _scheduled timer handles before cleanup of @@ -202,6 +202,11 @@ else: pass +def _check_ssl_socket(sock): + if ssl is not None and isinstance(sock, ssl.SSLSocket): + raise TypeError("Socket cannot be of type SSLSocket") + + class _SendfileFallbackProtocol(protocols.Protocol): def __init__(self, transp): if not isinstance(transp, transports._FlowControlMixin): @@ -863,6 +868,7 @@ class BaseEventLoop(events.AbstractEventLoop): *, fallback=True): if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") + _check_ssl_socket(sock) self._check_sendfile_params(sock, file, offset, count) try: return await self._sock_sendfile_native(sock, file, @@ -1004,6 +1010,9 @@ class BaseEventLoop(events.AbstractEventLoop): raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') + if sock is not None: + _check_ssl_socket(sock) + if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 @@ -1437,6 +1446,9 @@ class BaseEventLoop(events.AbstractEventLoop): raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') + if sock is not None: + _check_ssl_socket(sock) + if host is not None or port is not None: if sock is not None: raise ValueError( @@ -1531,6 +1543,9 @@ class BaseEventLoop(events.AbstractEventLoop): raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') + if sock is not None: + _check_ssl_socket(sock) + transport, protocol = await self._create_connection_transport( sock, protocol_factory, ssl, '', server_side=True, ssl_handshake_timeout=ssl_handshake_timeout) diff --git a/Lib/asyncio/futures.py b/Lib/asyncio/futures.py index 10f8f05..8e8cd87 100644 --- a/Lib/asyncio/futures.py +++ b/Lib/asyncio/futures.py @@ -8,6 +8,7 @@ import concurrent.futures import contextvars import logging import sys +from types import GenericAlias from . import base_futures from . import events @@ -106,8 +107,7 @@ class Future: context['source_traceback'] = self._source_traceback self._loop.call_exception_handler(context) - def __class_getitem__(cls, type): - return cls + __class_getitem__ = classmethod(GenericAlias) @property def _log_traceback(self): diff --git a/Lib/asyncio/proactor_events.py b/Lib/asyncio/proactor_events.py index 45c11ee..411685b 100644 --- a/Lib/asyncio/proactor_events.py +++ b/Lib/asyncio/proactor_events.py @@ -158,7 +158,7 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, # end then it may fail with ERROR_NETNAME_DELETED if we # just close our end. First calling shutdown() seems to # cure it, but maybe using DisconnectEx() would be better. - if hasattr(self._sock, 'shutdown'): + if hasattr(self._sock, 'shutdown') and self._sock.fileno() != -1: self._sock.shutdown(socket.SHUT_RDWR) self._sock.close() self._sock = None @@ -452,7 +452,8 @@ class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): self.close() -class _ProactorDatagramTransport(_ProactorBasePipeTransport): +class _ProactorDatagramTransport(_ProactorBasePipeTransport, + transports.DatagramTransport): max_size = 256 * 1024 def __init__(self, loop, sock, protocol, address=None, waiter=None, extra=None): diff --git a/Lib/asyncio/protocols.py b/Lib/asyncio/protocols.py index 69fa43e..09987b1 100644 --- a/Lib/asyncio/protocols.py +++ b/Lib/asyncio/protocols.py @@ -109,10 +109,6 @@ class Protocol(BaseProtocol): class BufferedProtocol(BaseProtocol): """Interface for stream protocol with manual buffer control. - Important: this has been added to asyncio in Python 3.7 - *on a provisional basis*! Consider it as an experimental API that - might be changed or removed in Python 3.8. - Event methods, such as `create_server` and `create_connection`, accept factories that return protocols that implement this interface. diff --git a/Lib/asyncio/queues.py b/Lib/asyncio/queues.py index a87ec8b..10dd689 100644 --- a/Lib/asyncio/queues.py +++ b/Lib/asyncio/queues.py @@ -2,6 +2,7 @@ __all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty') import collections import heapq +from types import GenericAlias from . import locks from . import mixins @@ -69,8 +70,7 @@ class Queue(mixins._LoopBoundMixin): def __str__(self): return f'<{type(self).__name__} {self._format()}>' - def __class_getitem__(cls, type): - return cls + __class_getitem__ = classmethod(GenericAlias) def _format(self): result = f'maxsize={self._maxsize!r}' diff --git a/Lib/asyncio/selector_events.py b/Lib/asyncio/selector_events.py index 59cb6b1..71080b8 100644 --- a/Lib/asyncio/selector_events.py +++ b/Lib/asyncio/selector_events.py @@ -40,11 +40,6 @@ def _test_selector_event(selector, fd, event): return bool(key.events & event) -def _check_ssl_socket(sock): - if ssl is not None and isinstance(sock, ssl.SSLSocket): - raise TypeError("Socket cannot be of type SSLSocket") - - class BaseSelectorEventLoop(base_events.BaseEventLoop): """Selector event loop. @@ -357,7 +352,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop): The maximum amount of data to be received at once is specified by nbytes. """ - _check_ssl_socket(sock) + base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") try: @@ -398,7 +393,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop): The received data is written into *buf* (a writable buffer). The return value is the number of bytes written. """ - _check_ssl_socket(sock) + base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") try: @@ -439,7 +434,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop): raised, and there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection. """ - _check_ssl_socket(sock) + base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") try: @@ -488,13 +483,15 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop): This method is a coroutine. """ - _check_ssl_socket(sock) + base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( - address, family=sock.family, proto=sock.proto, loop=self) + address, family=sock.family, type=sock.type, proto=sock.proto, + loop=self, + ) _, _, _, _, address = resolved[0] fut = self.create_future() @@ -553,7 +550,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop): object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. """ - _check_ssl_socket(sock) + base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") fut = self.create_future() diff --git a/Lib/asyncio/sslproto.py b/Lib/asyncio/sslproto.py index cad25b2..00fc16c 100644 --- a/Lib/asyncio/sslproto.py +++ b/Lib/asyncio/sslproto.py @@ -367,6 +367,12 @@ class _SSLProtocolTransport(transports._FlowControlMixin, """Return the current size of the write buffer.""" return self._ssl_protocol._transport.get_write_buffer_size() + def get_write_buffer_limits(self): + """Get the high and low watermarks for write flow control. + Return a tuple (low, high) where low and high are + positive number of bytes.""" + return self._ssl_protocol._transport.get_write_buffer_limits() + @property def _protocol_paused(self): # Required for sendfile fallback pause_writing/resume_writing logic diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 53eef84..c4bedb5 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -17,6 +17,7 @@ import itertools import types import warnings import weakref +from types import GenericAlias from . import base_tasks from . import coroutines @@ -123,8 +124,7 @@ class Task(futures._PyFuture): # Inherit Python Task implementation self._loop.call_exception_handler(context) super().__del__() - def __class_getitem__(cls, type): - return cls + __class_getitem__ = classmethod(GenericAlias) def _repr_info(self): return base_tasks._task_repr_info(self) @@ -621,17 +621,23 @@ def _ensure_future(coro_or_future, *, loop=None): raise ValueError('The future belongs to a different loop than ' 'the one specified as the loop argument') return coro_or_future - + called_wrap_awaitable = False if not coroutines.iscoroutine(coro_or_future): if inspect.isawaitable(coro_or_future): coro_or_future = _wrap_awaitable(coro_or_future) + called_wrap_awaitable = True else: raise TypeError('An asyncio.Future, a coroutine or an awaitable ' 'is required') if loop is None: loop = events._get_event_loop(stacklevel=4) - return loop.create_task(coro_or_future) + try: + return loop.create_task(coro_or_future) + except RuntimeError: + if not called_wrap_awaitable: + coro_or_future.close() + raise @types.coroutine @@ -715,7 +721,7 @@ def gather(*coros_or_futures, return_exceptions=False): nonlocal nfinished nfinished += 1 - if outer.done(): + if outer is None or outer.done(): if not fut.cancelled(): # Mark exception retrieved. fut.exception() @@ -771,6 +777,7 @@ def gather(*coros_or_futures, return_exceptions=False): nfuts = 0 nfinished = 0 loop = None + outer = None # bpo-46672 for arg in coros_or_futures: if arg not in arg_to_fut: fut = _ensure_future(arg, loop=loop) diff --git a/Lib/asyncio/transports.py b/Lib/asyncio/transports.py index 45e155c..73b1fa2 100644 --- a/Lib/asyncio/transports.py +++ b/Lib/asyncio/transports.py @@ -99,6 +99,12 @@ class WriteTransport(BaseTransport): """Return the current size of the write buffer.""" raise NotImplementedError + def get_write_buffer_limits(self): + """Get the high and low watermarks for write flow control. + Return a tuple (low, high) where low and high are + positive number of bytes.""" + raise NotImplementedError + def write(self, data): """Write some data bytes to the transport. diff --git a/Lib/calendar.py b/Lib/calendar.py index 7311a01..cbea9ec 100644 --- a/Lib/calendar.py +++ b/Lib/calendar.py @@ -15,7 +15,9 @@ __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr", "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar", - "LocaleHTMLCalendar", "weekheader"] + "LocaleHTMLCalendar", "weekheader", + "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", + "SATURDAY", "SUNDAY"] # Exception raised for bad input (with string parameter for details) error = ValueError diff --git a/Lib/codeop.py b/Lib/codeop.py index 6b56be4..568e9bb 100644 --- a/Lib/codeop.py +++ b/Lib/codeop.py @@ -10,30 +10,6 @@ and: syntax error (OverflowError and ValueError can be produced by malformed literals). -Approach: - -First, check if the source consists entirely of blank lines and -comments; if so, replace it with 'pass', because the built-in -parser doesn't always do the right thing for these. - -Compile three times: as is, with \n, and with \n\n appended. If it -compiles as is, it's complete. If it compiles with one \n appended, -we expect more. If it doesn't compile either way, we compare the -error we get when compiling with \n or \n\n appended. If the errors -are the same, the code is broken. But if the errors are different, we -expect more. Not intuitive; not even guaranteed to hold in future -releases; but this matches the compiler's behavior from Python 1.4 -through 2.2, at least. - -Caveat: - -It is possible (but not likely) that the parser stops parsing with a -successful outcome before reaching the end of the source; in this -case, trailing symbols may be ignored instead of causing an error. -For example, a backslash followed by two newlines may be followed by -arbitrary garbage. This will be fixed once the API for the parser is -better. - The two interfaces are: compile_command(source, filename, symbol): @@ -64,7 +40,11 @@ _features = [getattr(__future__, fname) __all__ = ["compile_command", "Compile", "CommandCompiler"] -PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h. +# The following flags match the values from Include/cpython/compile.h +# Caveat emptor: These flags are undocumented on purpose and depending +# on their effect outside the standard library is **unsupported**. +PyCF_DONT_IMPLY_DEDENT = 0x200 +PyCF_ALLOW_INCOMPLETE_INPUT = 0x4000 def _maybe_compile(compiler, source, filename, symbol): # Check for source consisting of only blank lines and comments. @@ -86,24 +66,12 @@ def _maybe_compile(compiler, source, filename, symbol): with warnings.catch_warnings(): warnings.simplefilter("error") - code1 = err1 = err2 = None - try: - code1 = compiler(source + "\n", filename, symbol) - except SyntaxError as e: - err1 = e - try: - code2 = compiler(source + "\n\n", filename, symbol) + compiler(source + "\n", filename, symbol) except SyntaxError as e: - err2 = e - - try: - if not code1 and _is_syntax_error(err1, err2): - raise err1 - else: - return None - finally: - err1 = err2 = None + if "incomplete input" in str(e): + return None + raise def _is_syntax_error(err1, err2): rep1 = repr(err1) @@ -115,7 +83,7 @@ def _is_syntax_error(err1, err2): return False def _compile(source, filename, symbol): - return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) + return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT | PyCF_ALLOW_INCOMPLETE_INPUT) def compile_command(source, filename="", symbol="single"): r"""Compile a command and determine whether it is incomplete. @@ -144,7 +112,7 @@ class Compile: statement, it "remembers" and compiles all subsequent program texts with the statement in force.""" def __init__(self): - self.flags = PyCF_DONT_IMPLY_DEDENT + self.flags = PyCF_DONT_IMPLY_DEDENT | PyCF_ALLOW_INCOMPLETE_INPUT def __call__(self, source, filename, symbol): codeob = compile(source, filename, symbol, self.flags, True) diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index bae0805..818588f 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -766,6 +766,10 @@ class Counter(dict): # To strip negative and zero counts, add-in an empty counter: # c += Counter() # + # Results are ordered according to when an element is first + # encountered in the left operand and then by the order + # encountered in the right operand. + # # When the multiplicities are all zero or one, multiset operations # are guaranteed to be equivalent to the corresponding operations # for regular sets. diff --git a/Lib/configparser.py b/Lib/configparser.py index 042a5c7..3470624 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -316,7 +316,7 @@ class ParsingError(Error): def filename(self): """Deprecated, use `source'.""" warnings.warn( - "The 'filename' attribute will be removed in future versions. " + "The 'filename' attribute will be removed in Python 3.12. " "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) @@ -326,7 +326,7 @@ class ParsingError(Error): def filename(self, value): """Deprecated, user `source'.""" warnings.warn( - "The 'filename' attribute will be removed in future versions. " + "The 'filename' attribute will be removed in Python 3.12. " "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) @@ -757,7 +757,7 @@ class RawConfigParser(MutableMapping): def readfp(self, fp, filename=None): """Deprecated, use read_file instead.""" warnings.warn( - "This method will be removed in future versions. " + "This method will be removed in Python 3.12. " "Use 'parser.read_file()' instead.", DeprecationWarning, stacklevel=2 ) @@ -1232,7 +1232,7 @@ class SafeConfigParser(ConfigParser): super().__init__(*args, **kwargs) warnings.warn( "The SafeConfigParser class has been renamed to ConfigParser " - "in Python 3.2. This alias will be removed in future versions." + "in Python 3.2. This alias will be removed in Python 3.12." " Use ConfigParser directly instead.", DeprecationWarning, stacklevel=2 ) diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py index 992b8c4..66acd62 100644 --- a/Lib/ctypes/test/test_bitfields.py +++ b/Lib/ctypes/test/test_bitfields.py @@ -1,5 +1,6 @@ from ctypes import * from ctypes.test import need_symbol +from test import support import unittest import os @@ -39,6 +40,8 @@ class C_Test(unittest.TestCase): setattr(b, name, i) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii'))) + # bpo-46913: _ctypes/cfield.c h_get() has an undefined behavior + @support.skip_if_sanitizer(ub=True) def test_shorts(self): b = BITS() name = "M" diff --git a/Lib/ctypes/test/test_python_api.py b/Lib/ctypes/test/test_python_api.py index 9c13746..49571f9 100644 --- a/Lib/ctypes/test/test_python_api.py +++ b/Lib/ctypes/test/test_python_api.py @@ -1,5 +1,5 @@ from ctypes import * -import unittest, sys +import unittest from test import support ################################################################ @@ -10,10 +10,6 @@ from _ctypes import PyObj_FromPtr ################################################################ from sys import getrefcount as grc -if sys.version_info > (2, 4): - c_py_ssize_t = c_size_t -else: - c_py_ssize_t = c_int class PythonAPITestCase(unittest.TestCase): @@ -21,7 +17,7 @@ class PythonAPITestCase(unittest.TestCase): PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize PyBytes_FromStringAndSize.restype = py_object - PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t + PyBytes_FromStringAndSize.argtypes = c_char_p, c_size_t self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc") diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py index 0a5730c..3fbe8b2 100644 --- a/Lib/ensurepip/__init__.py +++ b/Lib/ensurepip/__init__.py @@ -12,7 +12,7 @@ from importlib import resources __all__ = ["version", "bootstrap"] _PACKAGE_NAMES = ('setuptools', 'pip') _SETUPTOOLS_VERSION = "58.1.0" -_PIP_VERSION = "21.2.4" +_PIP_VERSION = "22.0.4" _PROJECTS = [ ("setuptools", _SETUPTOOLS_VERSION, "py3"), ("pip", _PIP_VERSION, "py3"), diff --git a/Lib/ensurepip/_bundled/pip-21.2.4-py3-none-any.whl b/Lib/ensurepip/_bundled/pip-21.2.4-py3-none-any.whl deleted file mode 100644 index 46d3012..0000000 Binary files a/Lib/ensurepip/_bundled/pip-21.2.4-py3-none-any.whl and /dev/null differ diff --git a/Lib/ensurepip/_bundled/pip-22.0.4-py3-none-any.whl b/Lib/ensurepip/_bundled/pip-22.0.4-py3-none-any.whl new file mode 100644 index 0000000..7ba048e Binary files /dev/null and b/Lib/ensurepip/_bundled/pip-22.0.4-py3-none-any.whl differ diff --git a/Lib/http/server.py b/Lib/http/server.py index e985dfd..58abadf 100644 --- a/Lib/http/server.py +++ b/Lib/http/server.py @@ -103,8 +103,6 @@ import socketserver import sys import time import urllib.parse -import contextlib -from functools import partial from http import HTTPStatus @@ -1239,7 +1237,6 @@ def test(HandlerClass=BaseHTTPRequestHandler, """ ServerClass.address_family, addr = _get_best_family(bind, port) - HandlerClass.protocol_version = protocol with ServerClass(addr, HandlerClass) as httpd: host, port = httpd.socket.getsockname()[:2] @@ -1256,29 +1253,29 @@ def test(HandlerClass=BaseHTTPRequestHandler, if __name__ == '__main__': import argparse + import contextlib parser = argparse.ArgumentParser() parser.add_argument('--cgi', action='store_true', - help='Run as CGI Server') + help='run as CGI server') parser.add_argument('--bind', '-b', metavar='ADDRESS', - help='Specify alternate bind address ' - '[default: all interfaces]') + help='specify alternate bind address ' + '(default: all interfaces)') parser.add_argument('--directory', '-d', default=os.getcwd(), - help='Specify alternative directory ' - '[default:current directory]') - parser.add_argument('port', action='store', - default=8000, type=int, + help='specify alternate directory ' + '(default: current directory)') + parser.add_argument('port', action='store', default=8000, type=int, nargs='?', - help='Specify alternate port [default: 8000]') + help='specify alternate port (default: 8000)') args = parser.parse_args() if args.cgi: handler_class = CGIHTTPRequestHandler else: - handler_class = partial(SimpleHTTPRequestHandler, - directory=args.directory) + handler_class = SimpleHTTPRequestHandler # ensure dual-stack is not disabled; ref #38907 class DualStackServer(ThreadingHTTPServer): + def server_bind(self): # suppress exception when protocol is IPv4 with contextlib.suppress(Exception): @@ -1286,6 +1283,10 @@ if __name__ == '__main__': socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) return super().server_bind() + def finish_request(self, request, client_address): + self.RequestHandlerClass(request, client_address, self, + directory=args.directory) + test( HandlerClass=handler_class, ServerClass=DualStackServer, diff --git a/Lib/idlelib/Icons/idle_16.gif b/Lib/idlelib/Icons/idle_16.gif index 9f001b1..bcedcd6 100644 Binary files a/Lib/idlelib/Icons/idle_16.gif and b/Lib/idlelib/Icons/idle_16.gif differ diff --git a/Lib/idlelib/Icons/idle_16.png b/Lib/idlelib/Icons/idle_16.png index 6abde0a..77d8f71 100644 Binary files a/Lib/idlelib/Icons/idle_16.png and b/Lib/idlelib/Icons/idle_16.png differ diff --git a/Lib/idlelib/Icons/idle_256.png b/Lib/idlelib/Icons/idle_256.png index 99ffa6f..64f276b 100644 Binary files a/Lib/idlelib/Icons/idle_256.png and b/Lib/idlelib/Icons/idle_256.png differ diff --git a/Lib/idlelib/Icons/idle_32.gif b/Lib/idlelib/Icons/idle_32.gif index af5b2d5..a1b12a0 100644 Binary files a/Lib/idlelib/Icons/idle_32.gif and b/Lib/idlelib/Icons/idle_32.gif differ diff --git a/Lib/idlelib/Icons/idle_32.png b/Lib/idlelib/Icons/idle_32.png index 41b70db..2aaa558 100644 Binary files a/Lib/idlelib/Icons/idle_32.png and b/Lib/idlelib/Icons/idle_32.png differ diff --git a/Lib/idlelib/Icons/idle_48.png b/Lib/idlelib/Icons/idle_48.png index e5fa928..705eec4 100644 Binary files a/Lib/idlelib/Icons/idle_48.png and b/Lib/idlelib/Icons/idle_48.png differ diff --git a/Lib/idlelib/Icons/minusnode.gif b/Lib/idlelib/Icons/minusnode.gif index c72e46f..173e970 100644 Binary files a/Lib/idlelib/Icons/minusnode.gif and b/Lib/idlelib/Icons/minusnode.gif differ diff --git a/Lib/idlelib/Icons/plusnode.gif b/Lib/idlelib/Icons/plusnode.gif index 13ace90..abedde0 100644 Binary files a/Lib/idlelib/Icons/plusnode.gif and b/Lib/idlelib/Icons/plusnode.gif differ diff --git a/Lib/idlelib/Icons/python.gif b/Lib/idlelib/Icons/python.gif index b189c2c..01b13e3 100644 Binary files a/Lib/idlelib/Icons/python.gif and b/Lib/idlelib/Icons/python.gif differ diff --git a/Lib/idlelib/Icons/tk.gif b/Lib/idlelib/Icons/tk.gif index a603f5e..03bf383 100644 Binary files a/Lib/idlelib/Icons/tk.gif and b/Lib/idlelib/Icons/tk.gif differ diff --git a/Lib/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt index 396820e..424e971 100644 --- a/Lib/idlelib/NEWS.txt +++ b/Lib/idlelib/NEWS.txt @@ -1,12 +1,56 @@ +What's New in IDLE 3.10.z +after 3.10.0 until 3.10.? +Released on 2022-05-16 +========================= + + +bpo-28950: Apply IDLE syntax highlighting to `.pyi` files. Add util.py +for common components. Patch by Alex Waygood and Terry Jan Reedy. + +bpo-46630: Make query dialogs on Windows start with a cursor in the +entry box. + +bpo-46591: Make the IDLE doc URL on the About IDLE dialog clickable. + +bpo-45296: Clarify close, quit, and exit in IDLE. In the File menu, +'Close' and 'Exit' are now 'Close Window' (the current one) and 'Exit' +is now 'Exit IDLE' (by closing all windows). In Shell, 'quit()' and +'exit()' mean 'close Shell'. If there are no other windows, +this also exits IDLE. + +bpo-45495: Add context keywords 'case' and 'match' to completions list. + +bpo-45296: On Windows, change exit/quit message to suggest Ctrl-D, which +works, instead of , which does not work in IDLE. + + What's New in IDLE 3.10.0 (since 3.9.0) -Released on 2021-10-04? +Released on 2021-10-04 ========================= +bpo-40128: Mostly fix completions on macOS when not using tcl/tk 8.6.11 +(as with 3.9). + +bpo-33962: Move the indent space setting from the Font tab to the new Windows +tab. Patch by Mark Roseman and Terry Jan Reedy. + +bpo-40468: Split the settings dialog General tab into Windows and Shell/Ed +tabs. Move help sources, which extend the Help menu, to the Extensions tab. +Make space for new options and shorten the dialog. The latter makes the +dialog better fit small screens. + +bpo-44010: Highlight the new match statement's soft keywords: match, case, +and _. This highlighting is not perfect and will be incorrect in some rare +cases, especially for some _s in case patterns. + bpo-44026: Include interpreter's typo fix suggestions in message line for NameErrors and AttributeErrors. Patch by E. Paine. +bpo-41611: Avoid occasional uncaught exceptions and freezing when using +completions on macOS. + bpo-37903: Add mouse actions to the shell sidebar. Left click and optional drag selects one or more lines of text, as with the editor line number sidebar. Right click after selecting text lines @@ -14,6 +58,9 @@ displays a context menu with 'copy with prompts'. This zips together prompts from the sidebar with lines from the selected text. This option also appears on the context menu for the text. +bpo-43981: Fix reference leaks in test_sidebar and test_squeezer. +Patches by Terry Jan Reedy and Pablo Galindo + bpo-37892: Change Shell input indents from tabs to spaces. Shell input now 'looks right'. Making this feasible motivated the shell sidebar. @@ -22,6 +69,9 @@ bpo-37903: Move the Shell input prompt to a side bar. bpo-43655: Make window managers on macOS and X Window recognize IDLE dialog windows as dialogs. +bpo-42225: Document that IDLE can fail on Unix either from misconfigured IP +masquerade rules or failure displaying complex colored (non-ascii) characters. + bpo-43283: Document why printing to IDLE's Shell is often slower than printing to a system terminal and that it can be made faster by pre-formatting a single string before printing. @@ -50,6 +100,12 @@ by using inspect.getdoc. bpo-33987: Mostly finish using ttk widgets, mainly for editor, settings, and searches. Some patches by Mark Roseman. +bpo-40511: Stop unnecessary "flashing" when typing opening and closing +parentheses inside the parentheses of a function call. + +bpo-38439: Add a 256x256 pixel IDLE icon to the Windows .ico file. Created by +Andrew Clover. Remove the low-color gif variations from the .ico file. + bpo-41775: Make 'IDLE Shell' the shell title. bpo-35764: Rewrite the Calltips doc section. diff --git a/Lib/idlelib/README.txt b/Lib/idlelib/README.txt index bc3d978..8870fda 100644 --- a/Lib/idlelib/README.txt +++ b/Lib/idlelib/README.txt @@ -82,6 +82,7 @@ tabbedpages.py # Define tabbed pages widget (nim). textview.py # Define read-only text widget (nim). tree.py # Define tree widget, used in browsers (nim). undo.py # Manage undo stack. +util.py # Define objects imported elsewhere with no dependencies (nim) windows.py # Manage window list and define listed top level. zoomheight.py # Zoom window to full height of screen. diff --git a/Lib/idlelib/editor.py b/Lib/idlelib/editor.py index fcc8a3f..6c52efd 100644 --- a/Lib/idlelib/editor.py +++ b/Lib/idlelib/editor.py @@ -27,6 +27,7 @@ from idlelib import query from idlelib import replace from idlelib import search from idlelib.tree import wheel_event +from idlelib.util import py_extensions from idlelib import window # The default tab setting for a Text widget, in average-width characters. @@ -757,7 +758,7 @@ class EditorWindow: if not filename or os.path.isdir(filename): return True base, ext = os.path.splitext(os.path.basename(filename)) - if os.path.normcase(ext) in (".py", ".pyw"): + if os.path.normcase(ext) in py_extensions: return True line = self.text.get('1.0', '1.0 lineend') return line.startswith('#!') and 'python' in line diff --git a/Lib/idlelib/help.html b/Lib/idlelib/help.html index 2468afa..41626ec 100644 --- a/Lib/idlelib/help.html +++ b/Lib/idlelib/help.html @@ -5,7 +5,7 @@ - IDLE — Python 3.11.0a0 documentation + IDLE — Python 3.11.0a4 documentation @@ -18,7 +18,7 @@ @@ -71,7 +71,7 @@
  • - 3.11.0a0 Documentation » + 3.11.0a4 Documentation »
  • @@ -163,9 +163,11 @@ file.

    Print Window

    Print the current window to the default printer.

    -
    Close

    Close the current window (ask to save if unsaved).

    +
    Close Window

    Close the current window (if an unsaved editor, ask to save; if an unsaved +Shell, ask to quit execution). Calling exit() or close() in the Shell +window also closes Shell. If this is the only window, also exit IDLE.

    -
    Exit

    Close all windows and quit IDLE (ask to save unsaved windows).

    +
    Exit IDLE

    Close all windows and quit IDLE (ask to save unsaved edit windows).

    @@ -976,7 +978,7 @@ also used for testing.

  • - 3.11.0a0 Documentation » + 3.11.0a4 Documentation »
  • @@ -1000,7 +1002,7 @@ also used for testing.