From: JinWang An Date: Wed, 18 Jan 2023 06:01:25 +0000 (+0900) Subject: Imported Upstream version 3.9.11 X-Git-Tag: upstream/3.9.11^0 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=4604666e8033d3ef9b91951b93f63c9312e751fe;p=platform%2Fupstream%2Fpython3.git Imported Upstream version 3.9.11 --- diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst index 614eb245..df38ba43 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/object.rst b/Doc/c-api/object.rst index 05faa723..9f874382 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 9207d860..44ee009f 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 a8006167..d58a53b1 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -474,7 +474,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. @@ -1909,6 +1909,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. @@ -1933,17 +1944,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. - - .. _heap-types: Heap Types @@ -2340,7 +2340,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 0d13d949..a6ae8ba1 100644 --- a/Doc/c-api/unicode.rst +++ b/Doc/c-api/unicode.rst @@ -1025,7 +1025,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. @@ -1239,7 +1239,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. @@ -1457,7 +1457,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. @@ -1619,7 +1619,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 551846ea..3595a7b9 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 d0aee4e6..01fa5c77 100644 --- a/Doc/faq/design.rst +++ b/Doc/faq/design.rst @@ -267,12 +267,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() @@ -280,14 +277,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 aecb56ea..1d2aca6f 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,161 +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. The one -solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error`` -equal to ``E_EOF``, which means the input is incomplete. Here's a sample code -fragment, untested, inspired by code from Alex Farber:: - - #define PY_SSIZE_T_CLEAN - #include - #include - #include - #include - #include - #include - - int testcomplete(char *code) - /* code should end in \n */ - /* return -1 for error, 0 for incomplete, 1 for complete */ - { - node *n; - perrdetail e; - - n = PyParser_ParseString(code, &_PyParser_Grammar, - Py_file_input, &e); - if (n == NULL) { - if (e.error == E_EOF) - return 0; - return -1; - } - - PyNode_Free(n); - return 1; - } - -Another 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 d838e614..3cf041e1 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -1820,7 +1820,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`:: diff --git a/Doc/glossary.rst b/Doc/glossary.rst index da9dc9ce..f759c3fb 100644 --- a/Doc/glossary.rst +++ b/Doc/glossary.rst @@ -278,12 +278,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 9f0dd2f1..4b76e061 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 ----------------------- diff --git a/Doc/howto/logging_flow.png b/Doc/howto/logging_flow.png index fac4acd7..d65e597f 100644 Binary files a/Doc/howto/logging_flow.png and b/Doc/howto/logging_flow.png differ diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst index 424ae547..35be01e8 100644 --- a/Doc/library/abc.rst +++ b/Doc/library/abc.rst @@ -185,15 +185,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 140851ce..2a6d82fa 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -1193,10 +1193,13 @@ Allows customizing how exceptions are handled in the event loop. * 'message': Error message; * 'exception' (optional): Exception object; * 'future' (optional): :class:`asyncio.Future` instance; + * 'task' (optional): :class:`asyncio.Task` instance; * 'handle' (optional): :class:`asyncio.Handle` instance; * 'protocol' (optional): :ref:`Protocol ` instance; * 'transport' (optional): :ref:`Transport ` instance; - * 'socket' (optional): :class:`socket.socket` instance. + * 'socket' (optional): :class:`socket.socket` instance; + * 'asyncgen' (optional): Asynchronous generator that caused + the exception. .. note:: diff --git a/Doc/library/asyncio-stream.rst b/Doc/library/asyncio-stream.rst index bf431cfb..a960b26c 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, *, \ loop=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. @@ -73,6 +74,10 @@ and work with streams: The *ssl_handshake_timeout* parameter. + .. versionadded:: 3.8 + + Added *happy_eyeballs_delay* and *interleave* parameters. + .. coroutinefunction:: start_server(client_connected_cb, host=None, \ port=None, *, loop=None, limit=None, \ family=socket.AF_UNSPEC, \ diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index e8bee20b..38b12e44 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -991,7 +991,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 @@ -1019,7 +1019,7 @@ enforced. This decorator should not be used for :keyword:`async def` coroutines. - .. deprecated-removed:: 3.8 3.10 + .. deprecated-removed:: 3.8 3.11 Use :keyword:`async def` instead. diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst index 2f7497c0..3386208d 100644 --- a/Doc/library/codecs.rst +++ b/Doc/library/codecs.rst @@ -691,8 +691,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 e00b75fa..f3b8e2ab 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -277,7 +277,7 @@ For example:: 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() diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst index 60d33f59..e5c78246 100644 --- a/Doc/library/configparser.rst +++ b/Doc/library/configparser.rst @@ -243,6 +243,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 43920210..dc35965b 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/datetime.rst b/Doc/library/datetime.rst index 217cdf22..f447b7bc 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 6c21c6b9..c4945679 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 8df557e4..9a9c707d 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -210,7 +210,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 73e84944..faef21b5 100644 Binary files a/Doc/library/hashlib-blake2-tree.png and b/Doc/library/hashlib-blake2-tree.png differ diff --git a/Doc/library/html.parser.rst b/Doc/library/html.parser.rst index ac844a68..03aff25c 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 08b0ddf5..dea79108 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 4fa4f1e5..b8febb9a 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 1f73017e..7652d501 100644 --- a/Doc/library/importlib.metadata.rst +++ b/Doc/library/importlib.metadata.rst @@ -199,6 +199,8 @@ function:: ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"] +.. _distributions: + Distributions ============= diff --git a/Doc/library/io.rst b/Doc/library/io.rst index 0ff05cfc..9f62dd21 100644 --- a/Doc/library/io.rst +++ b/Doc/library/io.rst @@ -230,8 +230,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 @@ -385,8 +384,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 @@ -439,7 +437,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 @@ -776,8 +774,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/multiprocessing.rst b/Doc/library/multiprocessing.rst index 96bc6c15..b62e1f8d 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 f8d567af..2f7b3701 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -1909,7 +1909,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: @@ -4623,7 +4624,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 49057f67..01f8684a 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/sqlite3.rst b/Doc/library/sqlite3.rst index 0ffb8ff0..9e695065 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`. To use the module, start by creating a :class:`Connection` object that @@ -254,14 +254,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 @@ -318,7 +332,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 @@ -520,7 +534,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. @@ -591,7 +605,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. @@ -730,11 +744,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 @@ -951,7 +965,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 0b231f17..c3acf61d 100644 --- a/Doc/library/ssl.rst +++ b/Doc/library/ssl.rst @@ -1719,10 +1719,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 bfa0e744..b10909d8 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -4740,33 +4740,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]``. + +* 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]``. -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. +``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:: @@ -4791,7 +4812,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:: @@ -4818,8 +4839,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): @@ -4828,7 +4849,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') @@ -4836,10 +4857,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` @@ -4877,12 +4899,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. @@ -4897,8 +4936,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]) @@ -4918,9 +4957,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 d1bdf434..3ecae27b 100644 --- a/Doc/library/string.rst +++ b/Doc/library/string.rst @@ -424,12 +424,13 @@ When no explicit alignment is given, preceding the *width* field by a zero sign-aware zero-padding for numeric types. This is equivalent to a *fill* character of ``'0'`` with an *alignment* type of ``'='``. -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 55dcc172..f9e9f63f 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 @@ -463,13 +464,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 9e182826..03986db1 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -412,10 +412,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 @@ -432,7 +429,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 915489fa..6bd7d003 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/time.rst b/Doc/library/time.rst index 11aba5dd..45f2ef14 100644 --- a/Doc/library/time.rst +++ b/Doc/library/time.rst @@ -253,6 +253,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) @@ -434,10 +440,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. | | +-----------+------------------------------------------------+-------+ @@ -458,7 +464,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()) @@ -879,10 +885,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..ca21fe62 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 c122d8f8..6495e63e 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 e1b2a87b..999852a5 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -644,8 +644,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 2da54488..13fc418e 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 @@ -1052,26 +1056,120 @@ 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__`` - and ``Point2D.__total__``. To allow using this feature with older versions - of Python that do not support :pep:`526`, ``TypedDict`` supports two additional - equivalent syntactic forms:: + To allow using this feature with older versions of Python that do not + support :pep:`526`, ``TypedDict`` supports two additional equivalent + syntactic forms: + + * Using a literal :class:`dict` as the second argument:: - Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) - By default, all keys must be present in a TypedDict. It is possible - to override this by specifying totality. + * Using keyword arguments:: + + 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:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + # Alternative syntax + Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False) + + This means that a ``Point2D`` ``TypedDict`` can have any of the keys + omitted. A type checker is only expected to support a literal ``False`` or + ``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 point2D(TypedDict, total=False): + 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 - This means that a point2D TypedDict can have any of the keys omitted. A type - checker is only expected to support a literal False or True as the value of - the total argument. True is the default, and makes all items defined in the - class body be required. + 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 :attr:`__annotations__`, + :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``. diff --git a/Doc/library/uuid.rst b/Doc/library/uuid.rst index 415e25be..ddfbbda2 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 98454e18..b387240a 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 967308b9..f4320db6 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1895,7 +1895,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 606e7734..4ffb6512 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -802,30 +802,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 @@ -836,14 +850,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 c5952426..2c84a97a 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 fcca12dc..79f40113 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 e9999716..89970975 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/extensions/peg_highlight.py b/Doc/tools/extensions/peg_highlight.py index 8bc24670..4262687d 100644 --- a/Doc/tools/extensions/peg_highlight.py +++ b/Doc/tools/extensions/peg_highlight.py @@ -45,8 +45,8 @@ class PEGLexer(RegexLexer): ], "variables": [(_name + _text_ws + "(=)", bygroups(None, None, None),),], "invalids": [ - (r"^(\s+\|\s+invalid_\w+\s*\n)", bygroups(None)), - (r"^(\s+\|\s+incorrect_\w+\s*\n)", bygroups(None)), + (r"^(\s+\|\s+.*invalid_\w+.*\n)", bygroups(None)), + (r"^(\s+\|\s+.*incorrect_\w+.*\n)", bygroups(None)), (r"^(#.*invalid syntax.*(?:.|\n)*)", bygroups(None),), ], "root": [ diff --git a/Doc/tools/susp-ignored.csv b/Doc/tools/susp-ignored.csv index 02fe9175..48480ed5 100644 --- a/Doc/tools/susp-ignored.csv +++ b/Doc/tools/susp-ignored.csv @@ -213,7 +213,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 08202f03..289d4423 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -710,7 +710,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 9c18ff19..03bf2d7b 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 c04a34a6..be21b55f 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.7.rst b/Doc/whatsnew/3.7.rst index 9204cc7f..7a00e376 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -537,7 +537,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 0662adba..6aed8d2b 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/Include/patchlevel.h b/Include/patchlevel.h index 23fbd55f..bf343ad9 100644 --- a/Include/patchlevel.h +++ b/Include/patchlevel.h @@ -18,12 +18,12 @@ /*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 9 -#define PY_MICRO_VERSION 10 +#define PY_MICRO_VERSION 11 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL #define PY_RELEASE_SERIAL 0 /* Version as a string */ -#define PY_VERSION "3.9.10" +#define PY_VERSION "3.9.11" /*--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 acfaff80..023ac7cf 100644 --- a/Lib/_collections_abc.py +++ b/Lib/_collections_abc.py @@ -816,7 +816,7 @@ class KeysView(MappingView, Set): __slots__ = () @classmethod - def _from_iterable(self, it): + def _from_iterable(cls, it): return set(it) def __contains__(self, key): @@ -834,7 +834,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 4804ed27..7a9a2779 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -314,8 +314,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 @@ -1821,7 +1820,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 40569437..fbdfd517 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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__( diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py index 8c1fb496..7a14e5e1 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): @@ -864,6 +869,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, @@ -1005,6 +1011,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 @@ -1438,6 +1447,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( @@ -1540,6 +1552,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 bed4da52..aaab09c2 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 b4cd414b..e3f95cf2 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 @@ -450,7 +450,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 69fa43e8..09987b16 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 cd3f7c6a..14ae87e0 100644 --- a/Lib/asyncio/queues.py +++ b/Lib/asyncio/queues.py @@ -3,6 +3,7 @@ __all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty') import collections import heapq import warnings +from types import GenericAlias from . import events from . import locks @@ -76,8 +77,7 @@ class Queue: 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 59cb6b1b..71080b8a 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 cad25b26..00fc16c0 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 27a3c8c5..53252f20 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 @@ -147,8 +148,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) @@ -768,7 +768,7 @@ def _gather(*coros_or_futures, loop=None, 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() @@ -823,6 +823,7 @@ def _gather(*coros_or_futures, loop=None, return_exceptions=False): children = [] nfuts = 0 nfinished = 0 + 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 45e155c9..73b1fa2d 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/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py index 992b8c4d..66acd62e 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 9c137469..49571f97 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 2a140a26..e510cc7f 100644 --- a/Lib/ensurepip/__init__.py +++ b/Lib/ensurepip/__init__.py @@ -12,7 +12,7 @@ from . import _bundled __all__ = ["version", "bootstrap"] _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 46d3012c..00000000 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 00000000..7ba048e2 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 d7cce204..2d2300c2 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 @@ -1240,7 +1238,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] @@ -1257,29 +1254,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): @@ -1287,6 +1284,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 9f001b1d..bcedcd64 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 6abde0af..77d8f711 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 99ffa6fa..64f276b4 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 af5b2d52..a1b12a05 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 41b70dbc..2aaa5580 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 e5fa9280..705eec42 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 c72e46ff..173e9709 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 13ace90e..abedde04 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 b189c2c2..01b13e35 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 a603f5ec..03bf3832 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 f68e144d..5605c564 100644 --- a/Lib/idlelib/NEWS.txt +++ b/Lib/idlelib/NEWS.txt @@ -1,8 +1,43 @@ What's New in IDLE 3.9.z -(since 3.9.0) +after 3.9.0 until 3.9.12 +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-45296: On Windows, change exit/quit message to suggest Ctrl-D, which +works, instead of , which does not work in IDLE. + +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-41611: Avoid occasional uncaught exceptions and freezing when using +completions on macOS. + +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. @@ -30,6 +65,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 256×256 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 bc3d978f..8870fda3 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 b9cb5026..3bd0a0cd 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 edc539cd..d48622db 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).

    @@ -971,7 +973,7 @@ also used for testing.

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