diff --git a/Doc/howto/a-conceptual-overview-of-asyncio.rst b/Doc/howto/a-conceptual-overview-of-asyncio.rst index d68f7cc6921fc9b..af1e39480cc1f6f 100644 --- a/Doc/howto/a-conceptual-overview-of-asyncio.rst +++ b/Doc/howto/a-conceptual-overview-of-asyncio.rst @@ -9,12 +9,11 @@ model of how :mod:`asyncio` fundamentally works, helping you understand the how and why behind the recommended patterns. You might be curious about some key :mod:`!asyncio` concepts. -You'll be comfortably able to answer these questions by the end of this -article: +By the end of this article, you'll be able to comfortably answer these questions: - What's happening behind the scenes when an object is awaited? - How does :mod:`!asyncio` differentiate between a task which doesn't need - CPU-time (such as a network request or file read) as opposed to a task that + CPU time (such as a network request or file read) as opposed to a task that does (such as computing n-factorial)? - How to write an asynchronous variant of an operation, such as an async sleep or database request. @@ -35,7 +34,7 @@ A conceptual overview part 1: the high-level -------------------------------------------- In part 1, we'll cover the main, high-level building blocks of :mod:`!asyncio`: -the event loop, coroutine functions, coroutine objects, tasks and ``await``. +the event loop, coroutine functions, coroutine objects, tasks, and ``await``. ========== Event Loop @@ -56,7 +55,7 @@ Once it pauses or completes, it returns control to the event loop. The event loop will then select another job from its pool and invoke it. You can *roughly* think of the collection of jobs as a queue: jobs are added and then processed one at a time, generally (but not always) in order. -This process repeats indefinitely with the event loop cycling endlessly +This process repeats indefinitely, with the event loop cycling endlessly onwards. If there are no more jobs pending execution, the event loop is smart enough to rest and avoid needlessly wasting CPU cycles, and will come back when there's @@ -276,7 +275,7 @@ in this case, a call to resume ``plant_a_tree()``. Generally speaking, when the awaited task finishes (``dig_the_hole_task``), the original task or coroutine (``plant_a_tree()``) is added back to the event -loops to-do list to be resumed. +loop's to-do list to be resumed. This is a basic, yet reliable mental model. In practice, the control handoffs are slightly more complex, but not by much. @@ -310,7 +309,7 @@ Consider this program:: The first statement in the coroutine ``main()`` creates ``task_b`` and schedules it for execution via the event loop. Then, ``coro_a()`` is repeatedly awaited. Control never cedes to the -event loop which is why we see the output of all three ``coro_a()`` +event loop, which is why we see the output of all three ``coro_a()`` invocations before ``coro_b()``'s output: .. code-block:: none @@ -338,8 +337,8 @@ This behavior of ``await coroutine`` can trip a lot of people up! That example highlights how using only ``await coroutine`` could unintentionally hog control from other tasks and effectively stall the event loop. -:func:`asyncio.run` can help you detect such occurences via the -``debug=True`` flag which accordingly enables +:func:`asyncio.run` can help you detect such occurrences via the +``debug=True`` flag, which enables :ref:`debug mode `. Among other things, it will log any coroutines that monopolize execution for 100ms or longer. @@ -348,8 +347,8 @@ The design intentionally trades off some conceptual clarity around usage of ``await`` for improved performance. Each time a task is awaited, control needs to be passed all the way up the call stack to the event loop. -That might sound minor, but in a large program with many ``await``'s and a deep -callstack that overhead can add up to a meaningful performance drag. +That might sound minor, but in a large program with many ``await`` statements and a deep +call stack, that overhead can add up to a meaningful performance drag. ------------------------------------------------ A conceptual overview part 2: the nuts and bolts @@ -372,7 +371,7 @@ resume a coroutine. If the coroutine was paused and is now being resumed, the argument ``arg`` will be sent in as the return value of the ``yield`` statement which originally paused it. -If the coroutine is being used for the first time (as opposed to being resumed) +If the coroutine is being used for the first time (as opposed to being resumed), ``arg`` must be ``None``. .. code-block:: @@ -403,14 +402,14 @@ If the coroutine is being used for the first time (as opposed to being resumed) returned_value = e.value print(f"Coroutine main() finished and provided value: {returned_value}.") -:ref:`yield `, like usual, pauses execution and returns control +:ref:`yield `, as usual, pauses execution and returns control to the caller. In the example above, the ``yield``, on line 3, is called by ``... = await rock`` on line 11. More broadly speaking, ``await`` calls the :meth:`~object.__await__` method of the given object. ``await`` also does one more very special thing: it propagates (or "passes -along") any ``yield``\ s it receives up the call-chain. +along") any ``yield``\ s it receives up the call chain. In this case, that's back to ``... = coroutine.send(None)`` on line 16. The coroutine is resumed via the ``coroutine.send(42)`` call on line 21. @@ -462,12 +461,12 @@ computation's status and result. The term is a nod to the idea of something still to come or not yet happened, and the object is a way to keep an eye on that something. -A future has a few important attributes. One is its state which can be either -"pending", "cancelled" or "done". +A future has a few important attributes. One is its state, which can be either +"pending", "cancelled", or "done". Another is its result, which is set when the state transitions to done. Unlike a coroutine, a future does not represent the actual computation to be done; instead, it represents the status and result of that computation, kind of -like a status light (red, yellow or green) or indicator. +like a status light (red, yellow, or green) or indicator. :class:`asyncio.Task` subclasses :class:`asyncio.Future` in order to gain these various capabilities. @@ -490,8 +489,8 @@ We'll go through an example of how you could leverage a future to create your own variant of asynchronous sleep (``async_sleep``) which mimics :func:`asyncio.sleep`. -This snippet registers a few tasks with the event loop and then awaits a -coroutine wrapped in a task: ``async_sleep(3)``. +This snippet registers a few tasks with the event loop and then awaits the task +created by ``asyncio.create_task``, which wraps the ``async_sleep(3)`` coroutine. We want that task to finish only after three seconds have elapsed, but without preventing other tasks from running. @@ -540,8 +539,8 @@ will monitor how much time has elapsed and, accordingly, call # Block until the future is marked as done. await future -Below, we'll use a rather bare object, ``YieldToEventLoop()``, to ``yield`` -from ``__await__`` in order to cede control to the event loop. +Below, we use a rather bare ``YieldToEventLoop()`` object to ``yield`` +from its ``__await__`` method, ceding control to the event loop. This is effectively the same as calling ``asyncio.sleep(0)``, but this approach offers more clarity, not to mention it's somewhat cheating to use ``asyncio.sleep`` when showcasing how to implement it! @@ -552,13 +551,13 @@ The ``watcher_task``, which runs the coroutine ``_sleep_watcher(...)``, will be invoked once per full cycle of the event loop. On each resumption, it'll check the time and if not enough has elapsed, then it'll pause once again and hand control back to the event loop. -Eventually, enough time will have elapsed, and ``_sleep_watcher(...)`` will -mark the future as done, and then itself finish too by breaking out of the +Once enough time has elapsed, ``_sleep_watcher(...)`` +marks the future as done and completes by exiting its infinite ``while`` loop. Given this helper task is only invoked once per cycle of the event loop, you'd be correct to note that this asynchronous sleep will sleep *at least* three seconds, rather than exactly three seconds. -Note this is also of true of ``asyncio.sleep``. +Note this is also true of ``asyncio.sleep``. :: @@ -601,6 +600,6 @@ For reference, you could implement it without futures, like so:: else: await YieldToEventLoop() -But, that's all for now. Hopefully you're ready to more confidently dive into +But that's all for now. Hopefully you're ready to more confidently dive into some async programming or check out advanced topics in the :mod:`rest of the documentation `. diff --git a/Doc/library/cmath.rst b/Doc/library/cmath.rst index 26518a0458fd813..b6d5dbee21dcd5a 100644 --- a/Doc/library/cmath.rst +++ b/Doc/library/cmath.rst @@ -338,7 +338,7 @@ Constants .. data:: nan A floating-point "not a number" (NaN) value. Equivalent to - ``float('nan')``. + ``float('nan')``. See also :data:`math.nan`. .. versionadded:: 3.6 diff --git a/Doc/library/http.rst b/Doc/library/http.rst index ce3fb9f81205026..b0bdfc65e4508dd 100644 --- a/Doc/library/http.rst +++ b/Doc/library/http.rst @@ -139,7 +139,8 @@ equal to the constant name (i.e. ``http.HTTPStatus.OK`` is also available as .. versionchanged:: 3.13 Implemented RFC9110 naming for status constants. Old constant names are preserved for - backwards compatibility. + backwards compatibility: ``413 REQUEST_ENTITY_TOO_LARGE``, ``414 REQUEST_URI_TOO_LONG``, + ``416 REQUESTED_RANGE_NOT_SATISFIABLE`` and ``422 UNPROCESSABLE_ENTITY``. HTTP status category -------------------- diff --git a/Doc/library/pyexpat.rst b/Doc/library/pyexpat.rst index 9aae5c9da7471da..ec25c21c300676a 100644 --- a/Doc/library/pyexpat.rst +++ b/Doc/library/pyexpat.rst @@ -223,10 +223,10 @@ XMLParser Objects Calling ``SetReparseDeferralEnabled(True)`` allows re-enabling reparse deferral. - Note that :meth:`SetReparseDeferralEnabled` has been backported to some - prior releases of CPython as a security fix. Check for availability of - :meth:`SetReparseDeferralEnabled` using :func:`hasattr` if used in code - running across a variety of Python versions. + :meth:`!SetReparseDeferralEnabled` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. .. versionadded:: 3.13 @@ -257,6 +257,11 @@ against some common XML vulnerabilities. The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset` should not be used as they may have no special meaning. + :meth:`!SetBillionLaughsAttackProtectionActivationThreshold` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. + .. note:: Activation thresholds below 4 MiB are known to break support for DITA 1.3 @@ -288,6 +293,11 @@ against some common XML vulnerabilities. The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset` should not be used as they may have no special meaning. + :meth:`!SetBillionLaughsAttackProtectionMaximumAmplification` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. + .. note:: The maximum amplification factor is only considered if the threshold @@ -309,6 +319,11 @@ against some common XML vulnerabilities. The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset` should not be used as they may have no special meaning. + :meth:`!SetAllocTrackerActivationThreshold` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. + .. versionadded:: next .. method:: xmlparser.SetAllocTrackerMaximumAmplification(max_factor, /) @@ -334,6 +349,11 @@ against some common XML vulnerabilities. The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset` should not be used as they may have no special meaning. + :meth:`!SetAllocTrackerMaximumAmplification` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. + .. note:: The maximum amplification factor is only considered if the threshold diff --git a/Doc/library/smtplib.rst b/Doc/library/smtplib.rst index c5f8516f768a68b..c5a3de52090cee7 100644 --- a/Doc/library/smtplib.rst +++ b/Doc/library/smtplib.rst @@ -80,8 +80,8 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions). An :class:`SMTP_SSL` instance behaves exactly the same as instances of :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is - required from the beginning of the connection and using :meth:`starttls` is - not appropriate. If *host* is not specified, the local host is used. If + required from the beginning of the connection and using :meth:`~SMTP.starttls` + is not appropriate. If *host* is not specified, the local host is used. If *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments *local_hostname*, *timeout* and *source_address* have the same meaning as they do in the :class:`SMTP` class. *context*, also optional, @@ -112,7 +112,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions). The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It's common to use Unix sockets for LMTP, so our - :meth:`connect` method must support that as well as a regular host:port + :meth:`~SMTP.connect` method must support that as well as a regular host:port server. The optional arguments *local_hostname* and *source_address* have the same meaning as they do in the :class:`SMTP` class. To specify a Unix socket, you must use an absolute path for *host*, starting with a '/'. @@ -147,9 +147,15 @@ A nice selection of exceptions is defined as well: .. exception:: SMTPResponseException Base class for all exceptions that include an SMTP error code. These exceptions - are generated in some instances when the SMTP server returns an error code. The - error code is stored in the :attr:`smtp_code` attribute of the error, and the - :attr:`smtp_error` attribute is set to the error message. + are generated in some instances when the SMTP server returns an error code. + + .. attribute:: smtp_code + + The error code. + + .. attribute:: smtp_error + + The error message. .. exception:: SMTPSenderRefused @@ -161,9 +167,13 @@ A nice selection of exceptions is defined as well: .. exception:: SMTPRecipientsRefused - All recipient addresses refused. The errors for each recipient are accessible - through the attribute :attr:`recipients`, which is a dictionary of exactly the - same sort as :meth:`SMTP.sendmail` returns. + All recipient addresses refused. + + .. attribute:: recipients + + A dictionary of exactly the same sort as returned + by :meth:`SMTP.sendmail` containing the errors for + each recipient. .. exception:: SMTPDataError @@ -213,7 +223,6 @@ SMTP Objects An :class:`SMTP` instance has the following methods: - .. method:: SMTP.set_debuglevel(level) Set the debug output level. A value of 1 or ``True`` for *level* results in @@ -417,7 +426,7 @@ An :class:`SMTP` instance has the following methods: .. versionchanged:: 3.4 The method now supports hostname check with - :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indicator* (see :const:`~ssl.HAS_SNI`). .. versionchanged:: 3.5 @@ -435,7 +444,7 @@ An :class:`SMTP` instance has the following methods: ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT`` commands can be passed as *rcpt_options*. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as - :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.) + :meth:`!mail`, :meth:`!rcpt` and :meth:`!data` to send the message.) .. note:: @@ -467,10 +476,7 @@ An :class:`SMTP` instance has the following methods: This method may raise the following exceptions: :exc:`SMTPRecipientsRefused` - All recipients were refused. Nobody got the mail. The :attr:`recipients` - attribute of the exception object is a dictionary with information about the - refused recipients (like the one returned when at least one recipient was - accepted). + All recipients were refused. Nobody got the mail. :exc:`SMTPHeloError` The server didn't reply properly to the ``HELO`` greeting. @@ -546,6 +552,30 @@ Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``, Normally these do not need to be called directly, so they are not documented here. For details, consult the module code. +Additionally, an SMTP instance has the following attributes: + + +.. attribute:: SMTP.helo_resp + + The response to the ``HELO`` command, see :meth:`helo`. + + +.. attribute:: SMTP.ehlo_resp + + The response to the ``EHLO`` command, see :meth:`ehlo`. + + +.. attribute:: SMTP.does_esmtp + + A boolean value indicating whether the server supports ESMTP, see + :meth:`ehlo`. + + +.. attribute:: SMTP.esmtp_features + + A dictionary of the names of SMTP service extensions supported by the server, + see :meth:`ehlo`. + .. _smtp-example: diff --git a/Doc/library/time.rst b/Doc/library/time.rst index 3e6f5a97b49be90..8aff2b2dc67482a 100644 --- a/Doc/library/time.rst +++ b/Doc/library/time.rst @@ -244,8 +244,8 @@ Functions The result has the following attributes: - - *adjustable*: ``True`` if the clock can be changed automatically (e.g. by - a NTP daemon) or manually by the system administrator, ``False`` otherwise + - *adjustable*: ``True`` if the clock can be set to jump forward or backward + in time, ``False`` otherwise. Does not refer to gradual NTP rate adjustments. - *implementation*: The name of the underlying C function used to get the clock value. Refer to :ref:`time-clock-id-constants` for possible values. - *monotonic*: ``True`` if the clock cannot go backward, diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index 00075ac2a23e6be..881708a4dd702e6 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -1398,10 +1398,10 @@ XMLParser Objects Disabling reparse deferral has security consequences; please see :meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled` for details. - Note that :meth:`flush` has been backported to some prior releases of - CPython as a security fix. Check for availability of :meth:`flush` - using :func:`hasattr` if used in code running across a variety of Python - versions. + :meth:`!flush` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. .. versionadded:: 3.13 @@ -1476,10 +1476,10 @@ XMLPullParser Objects Disabling reparse deferral has security consequences; please see :meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled` for details. - Note that :meth:`flush` has been backported to some prior releases of - CPython as a security fix. Check for availability of :meth:`flush` - using :func:`hasattr` if used in code running across a variety of Python - versions. + :meth:`!flush` + has been backported to some prior releases of CPython as a security fix. + Check for availability using :func:`hasattr` if used in code running + across a variety of Python versions. .. versionadded:: 3.13 diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index 9aca25e3214a164..c655d6c52ecc162 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -1938,8 +1938,9 @@ Conditional expressions conditional_expression: `or_test` ["if" `or_test` "else" `expression`] expression: `conditional_expression` | `lambda_expr` -Conditional expressions (sometimes called a "ternary operator") have the lowest -priority of all Python operations. +A conditional expression (sometimes called a "ternary operator") is an +alternative to the if-else statement. As it is an expression, it returns a value +and can appear as a sub-expression. The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is diff --git a/Doc/tools/.nitignore b/Doc/tools/.nitignore index 60a80fe2c72a724..29fd3cfda458f0d 100644 --- a/Doc/tools/.nitignore +++ b/Doc/tools/.nitignore @@ -29,7 +29,6 @@ Doc/library/profile.rst Doc/library/pyexpat.rst Doc/library/resource.rst Doc/library/select.rst -Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/ssl.rst Doc/library/stdtypes.rst diff --git a/Doc/whatsnew/3.15.rst b/Doc/whatsnew/3.15.rst index a6be27162965ea1..c5321ee9983625d 100644 --- a/Doc/whatsnew/3.15.rst +++ b/Doc/whatsnew/3.15.rst @@ -3,7 +3,7 @@ What's new in Python 3.15 **************************** -:Editor: TBD +:Editor: Hugo van Kemenade .. Rules for maintenance: @@ -56,8 +56,8 @@ For full details, see the :ref:`changelog `. so it's worth checking back even after reading earlier versions. -Summary --- release highlights -============================== +Summary -- Release highlights +============================= .. This section singles out the most important changes in Python 3.15. Brevity is key. @@ -65,6 +65,13 @@ Summary --- release highlights .. PEP-sized items next. +* :pep:`799`: :ref:`A dedicated profiling package for organizing Python + profiling tools ` +* :pep:`686`: :ref:`Python now uses UTF-8 as the default encoding + ` +* :pep:`782`: :ref:`A new PyBytesWriter C API to create a Python bytes object + ` +* :ref:`Improved error messages ` New features @@ -72,8 +79,8 @@ New features .. _whatsnew315-sampling-profiler: -High frequency statistical sampling profiler --------------------------------------------- +:pep:`799`: High frequency statistical sampling profiler +-------------------------------------------------------- A new statistical sampling profiler has been added to the new :mod:`!profiling` module as :mod:`!profiling.sampling`. This profiler enables low-overhead performance analysis of @@ -95,23 +102,33 @@ Key features include: * **Multiple output formats**: Generate both detailed statistics and flamegraph data * **Thread-aware profiling**: Option to profile all threads or just the main thread -Profile process 1234 for 10 seconds with default settings:: +Profile process 1234 for 10 seconds with default settings: + +.. code-block:: shell python -m profiling.sampling 1234 -Profile with custom interval and duration, save to file:: +Profile with custom interval and duration, save to file: + +.. code-block:: shell python -m profiling.sampling -i 50 -d 30 -o profile.stats 1234 -Generate collapsed stacks for flamegraph:: +Generate collapsed stacks for flamegraph: + +.. code-block:: shell python -m profiling.sampling --collapsed 1234 -Profile all threads and sort by total time:: +Profile all threads and sort by total time: + +.. code-block:: shell python -m profiling.sampling -a --sort-tottime 1234 -The profiler generates statistical estimates of where time is spent:: +The profiler generates statistical estimates of where time is spent: + +.. code-block:: text Real-time sampling stats: Mean: 100261.5Hz (9.97µs) Min: 86333.4Hz (11.58µs) Max: 118807.2Hz (8.42µs) Samples: 400001 Captured 498841 samples in 5.00 seconds @@ -166,9 +183,13 @@ analysis, highlighting functions with high CPU usage and call frequency patterns This capability is particularly valuable for debugging performance issues in production systems where traditional profiling approaches would be too intrusive. + .. seealso:: :pep:`799` for further details. + (Contributed by Pablo Galindo and László Kiss Kollár in :gh:`135953`.) +.. _whatsnew315-improved-error-messages: + Improved error messages ----------------------- @@ -211,9 +232,11 @@ Improved error messages Other language changes ====================== +.. _whatsnew315-utf8-default: + * Python now uses UTF-8_ as the default encoding, independent of the system's environment. This means that I/O operations without an explicit encoding, - e.g. ``open('flying-circus.txt')``, will use UTF-8. + for example, ``open('flying-circus.txt')``, will use UTF-8. UTF-8 is a widely-supported Unicode_ character encoding that has become a *de facto* standard for representing text, including nearly every webpage on the internet, many common file formats, programming languages, and more. @@ -227,7 +250,7 @@ Other language changes To retain the previous behaviour, Python's UTF-8 mode may be disabled with the :envvar:`PYTHONUTF8=0 ` environment variable or the - :option:`-X utf8=0 <-X>` command line option. + :option:`-X utf8=0 <-X>` command-line option. .. seealso:: :pep:`686` for further details. @@ -294,6 +317,14 @@ New modules Improved modules ================ +calendar +-------- + +* Calendar pages generated by the :class:`calendar.HTMLCalendar` class now support + dark mode and have been migrated to the HTML5 standard for improved accessibility. + (Contributed by Jiahao Li and Hugo van Kemenade in :gh:`137634`.) + + collections ----------- @@ -378,7 +409,7 @@ locale ------ * :func:`~locale.setlocale` now supports language codes with ``@``-modifiers. - ``@``-modifier are no longer silently removed in :func:`~locale.getlocale`, + ``@``-modifiers are no longer silently removed in :func:`~locale.getlocale`, but included in the language code. (Contributed by Serhiy Storchaka in :gh:`137729`.) @@ -602,71 +633,6 @@ module_name -Deprecated -========== - -CLI ---- - -* Deprecate :option:`-b` and :option:`!-bb` command line options - and schedule them to become no-op in Python 3.17. - These were primarily helpers for the Python 2 -> 3 transition. - Starting with Python 3.17, no :exc:`BytesWarning` will be raised - for these cases; use a type checker instead. - - (Contributed by Nikita Sobolev in :gh:`136355`.) - -hashlib -------- - -* In hash function constructors such as :func:`~hashlib.new` or the - direct hash-named constructors such as :func:`~hashlib.md5` and - :func:`~hashlib.sha256`, their optional initial data parameter could - also be passed a keyword argument named ``data=`` or ``string=`` in - various :mod:`hashlib` implementations. - - Support for the ``string`` keyword argument name is now deprecated and - is slated for removal in Python 3.19. Prefer passing the initial data as - a positional argument for maximum backwards compatibility. - - (Contributed by Bénédikt Tran in :gh:`134978`.) - -__version__ ------------ - -* The ``__version__`` attribute has been deprecated in these standard library - modules and will be removed in Python 3.20. - Use :py:data:`sys.version_info` instead. - - - :mod:`argparse` - - :mod:`csv` - - :mod:`!ctypes.macholib` - - :mod:`ipaddress` - - :mod:`json` - - :mod:`logging` (``__date__`` also deprecated) - - :mod:`optparse` - - :mod:`pickle` - - :mod:`platform` - - :mod:`re` - - :mod:`socketserver` - - :mod:`tabnanny` - - :mod:`tkinter.font` - - :mod:`tkinter.ttk` - - (Contributed by Hugo van Kemenade in :gh:`76007`.) - -.. Add deprecations above alphabetically, not here at the end. - -.. include:: ../deprecations/pending-removal-in-3.16.rst - -.. include:: ../deprecations/pending-removal-in-3.17.rst - -.. include:: ../deprecations/pending-removal-in-3.19.rst - -.. include:: ../deprecations/pending-removal-in-3.20.rst - -.. include:: ../deprecations/pending-removal-in-future.rst - Removed ======= @@ -704,6 +670,12 @@ importlib.resources (Contributed by Semyon Moroz in :gh:`138044`) +mimetypes +--------- + +* Add ``application/toml``. (Contributed by Gil Forcada in :gh:`139959`.) + + pathlib ------- @@ -764,7 +736,7 @@ typing * Code like ``class B2(A[T2], Protocol[T1, T2]): ...`` now correctly handles type parameters order: it is ``(T1, T2)``, not ``(T2, T1)`` - as it was incorrectly infered in runtime before. + as it was incorrectly inferred in runtime before. (Contributed by Nikita Sobolev in :gh:`137191`.) * :class:`typing.ByteString` has been removed from ``typing.__all__``. @@ -806,20 +778,70 @@ zipimport (Contributed by Jiahao Li in :gh:`133656`.) -Porting to Python 3.15 -====================== +Deprecated +========== -This section lists previously described changes and other bugfixes -that may require changes to your code. +New deprecations +---------------- +* CLI: -Build changes -============= + * Deprecate :option:`-b` and :option:`!-bb` command-line options + and schedule them to become no-op in Python 3.17. + These were primarily helpers for the Python 2 -> 3 transition. + Starting with Python 3.17, no :exc:`BytesWarning` will be raised + for these cases; use a type checker instead. -* Removed implicit fallback to the bundled copy of the ``libmpdec`` library. - Now this should be explicitly enabled with :option:`--with-system-libmpdec` - set to ``no`` or with :option:`!--without-system-libmpdec`. - (Contributed by Sergey B Kirpichev in :gh:`115119`.) + (Contributed by Nikita Sobolev in :gh:`136355`.) + +* :mod:`hashlib`: + + * In hash function constructors such as :func:`~hashlib.new` or the + direct hash-named constructors such as :func:`~hashlib.md5` and + :func:`~hashlib.sha256`, their optional initial data parameter could + also be passed a keyword argument named ``data=`` or ``string=`` in + various :mod:`hashlib` implementations. + + Support for the ``string`` keyword argument name is now deprecated and + is slated for removal in Python 3.19. Prefer passing the initial data as + a positional argument for maximum backwards compatibility. + + (Contributed by Bénédikt Tran in :gh:`134978`.) + +* ``__version__`` + + * The ``__version__`` attribute has been deprecated in these standard library + modules and will be removed in Python 3.20. + Use :py:data:`sys.version_info` instead. + + - :mod:`argparse` + - :mod:`csv` + - :mod:`!ctypes.macholib` + - :mod:`ipaddress` + - :mod:`json` + - :mod:`logging` (``__date__`` also deprecated) + - :mod:`optparse` + - :mod:`pickle` + - :mod:`platform` + - :mod:`re` + - :mod:`socketserver` + - :mod:`tabnanny` + - :mod:`tkinter.font` + - :mod:`tkinter.ttk` + + (Contributed by Hugo van Kemenade in :gh:`76007`.) + +.. Add deprecations above alphabetically, not here at the end. + +.. include:: ../deprecations/pending-removal-in-3.16.rst + +.. include:: ../deprecations/pending-removal-in-3.17.rst + +.. include:: ../deprecations/pending-removal-in-3.19.rst + +.. include:: ../deprecations/pending-removal-in-3.20.rst + +.. include:: ../deprecations/pending-removal-in-future.rst C API changes @@ -842,6 +864,8 @@ New features and :c:data:`Py_mod_abi`. (Contributed by Petr Viktorin in :gh:`137210`.) +.. _whatsnew315-pep782: + * Implement :pep:`782`, the :ref:`PyBytesWriter API `. Add functions: @@ -893,39 +917,6 @@ Porting to Python 3.15 underlying syscall, instead of raising a :exc:`SystemError`. -Deprecated C APIs ------------------ - -* For unsigned integer formats in :c:func:`PyArg_ParseTuple`, - accepting Python integers with value that is larger than the maximal value - for the C type or less than the minimal value for the corresponding - signed integer type of the same size is now deprecated. - (Contributed by Serhiy Storchaka in :gh:`132629`.) - -* :c:func:`PyBytes_FromStringAndSize(NULL, len) ` - and :c:func:`_PyBytes_Resize` are :term:`soft deprecated`, - use the :c:type:`PyBytesWriter` API instead. - (Contributed by Victor Stinner in :gh:`129813`.) - -* Deprecate :c:member:`~PyComplexObject.cval` field of the the - :c:type:`PyComplexObject` type. - Use :c:func:`PyComplex_AsCComplex` and :c:func:`PyComplex_FromCComplex` - to convert a Python complex number to/from the C :c:type:`Py_complex` - representation. - (Contributed by Sergey B Kirpichev in :gh:`128813`.) - -* Functions :c:func:`_Py_c_sum`, :c:func:`_Py_c_diff`, :c:func:`_Py_c_neg`, - :c:func:`_Py_c_prod`, :c:func:`_Py_c_quot`, :c:func:`_Py_c_pow` and - :c:func:`_Py_c_abs` are :term:`soft deprecated`. - (Contributed by Sergey B Kirpichev in :gh:`128813`.) - -* :c:member:`~PyConfig.bytes_warning` is deprecated - since 3.15 and will be removed in 3.17. - (Contributed by Nikita Sobolev in :gh:`136355`.) - - -.. Add C API deprecations above alphabetically, not here at the end. - Removed C APIs -------------- @@ -994,3 +985,53 @@ on Python 3.13 and older. .. |pythoncapi_compat_project| replace:: |pythoncapi_compat_project_link|_ .. |pythoncapi_compat_project_link| replace:: pythoncapi-compat project .. _pythoncapi_compat_project_link: https://github.com/python/pythoncapi-compat + + +Deprecated C APIs +----------------- + +* For unsigned integer formats in :c:func:`PyArg_ParseTuple`, + accepting Python integers with value that is larger than the maximal value + for the C type or less than the minimal value for the corresponding + signed integer type of the same size is now deprecated. + (Contributed by Serhiy Storchaka in :gh:`132629`.) + +* :c:func:`PyBytes_FromStringAndSize(NULL, len) ` + and :c:func:`_PyBytes_Resize` are :term:`soft deprecated`, + use the :c:type:`PyBytesWriter` API instead. + (Contributed by Victor Stinner in :gh:`129813`.) + +* Deprecate :c:member:`~PyComplexObject.cval` field of the the + :c:type:`PyComplexObject` type. + Use :c:func:`PyComplex_AsCComplex` and :c:func:`PyComplex_FromCComplex` + to convert a Python complex number to/from the C :c:type:`Py_complex` + representation. + (Contributed by Sergey B Kirpichev in :gh:`128813`.) + +* Functions :c:func:`_Py_c_sum`, :c:func:`_Py_c_diff`, :c:func:`_Py_c_neg`, + :c:func:`_Py_c_prod`, :c:func:`_Py_c_quot`, :c:func:`_Py_c_pow` and + :c:func:`_Py_c_abs` are :term:`soft deprecated`. + (Contributed by Sergey B Kirpichev in :gh:`128813`.) + +* :c:member:`~PyConfig.bytes_warning` is deprecated + since 3.15 and will be removed in 3.17. + (Contributed by Nikita Sobolev in :gh:`136355`.) + + +.. Add C API deprecations above alphabetically, not here at the end. + + +Build changes +============= + +* Removed implicit fallback to the bundled copy of the ``libmpdec`` library. + Now this should be explicitly enabled with :option:`--with-system-libmpdec` + set to ``no`` or with :option:`!--without-system-libmpdec`. + (Contributed by Sergey B Kirpichev in :gh:`115119`.) + + +Porting to Python 3.15 +====================== + +This section lists previously described changes and other bugfixes +that may require changes to your code. diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 9b8e42a2342536b..97a629fe92ccec4 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -3340,7 +3340,10 @@ def _fill_logical(self, context, opa, opb): return opa, opb def logical_and(self, other, context=None): - """Applies an 'and' operation between self and other's digits.""" + """Applies an 'and' operation between self and other's digits. + + Both self and other must be logical numbers. + """ if context is None: context = getcontext() @@ -3357,14 +3360,20 @@ def logical_and(self, other, context=None): return _dec_from_triple(0, result.lstrip('0') or '0', 0) def logical_invert(self, context=None): - """Invert all its digits.""" + """Invert all its digits. + + The self must be logical number. + """ if context is None: context = getcontext() return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), context) def logical_or(self, other, context=None): - """Applies an 'or' operation between self and other's digits.""" + """Applies an 'or' operation between self and other's digits. + + Both self and other must be logical numbers. + """ if context is None: context = getcontext() @@ -3381,7 +3390,10 @@ def logical_or(self, other, context=None): return _dec_from_triple(0, result.lstrip('0') or '0', 0) def logical_xor(self, other, context=None): - """Applies an 'xor' operation between self and other's digits.""" + """Applies an 'xor' operation between self and other's digits. + + Both self and other must be logical numbers. + """ if context is None: context = getcontext() diff --git a/Lib/calendar.py b/Lib/calendar.py index 678c7be5aac094e..ed6b74b248042eb 100644 --- a/Lib/calendar.py +++ b/Lib/calendar.py @@ -498,30 +498,29 @@ def formatday(self, day, weekday): """ if day == 0: # day outside month - return ' ' % self.cssclass_noday + return f' ' else: - return '%d' % (self.cssclasses[weekday], day) + return f'{day}' def formatweek(self, theweek): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) - return '%s' % s + return f'{s}' def formatweekday(self, day): """ Return a weekday name as a table header. """ - return '%s' % ( - self.cssclasses_weekday_head[day], day_abbr[day]) + return f'{day_abbr[day]}' def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) - return '%s' % s + return f'{s}' def formatmonthname(self, theyear, themonth, withyear=True): """ @@ -529,11 +528,10 @@ def formatmonthname(self, theyear, themonth, withyear=True): """ _validate_month(themonth) if withyear: - s = '%s %s' % (standalone_month_name[themonth], theyear) + s = f'{standalone_month_name[themonth]} {theyear}' else: s = standalone_month_name[themonth] - return '%s' % ( - self.cssclass_month_head, s) + return f'{s}' def formatmonth(self, theyear, themonth, withyear=True): """ @@ -541,8 +539,7 @@ def formatmonth(self, theyear, themonth, withyear=True): """ v = [] a = v.append - a('' % ( - self.cssclass_month)) + a(f'
') a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') @@ -562,11 +559,9 @@ def formatyear(self, theyear, width=3): v = [] a = v.append width = max(width, 1) - a('
' % - self.cssclass_year) + a(f'
') a('\n') - a('' % ( - width, self.cssclass_year_head, theyear)) + a(f'') for i in range(JANUARY, JANUARY+12, width): # months in this row months = range(i, min(i+width, 13)) @@ -587,14 +582,19 @@ def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): encoding = 'utf-8' v = [] a = v.append - a('\n' % encoding) - a('\n') - a('\n') + a('\n') + a('\n') a('\n') - a('\n' % encoding) + a(f'\n') + a('\n') + a(f'Calendar for {theyear}\n') + a('\n') if css is not None: - a('\n' % css) - a('Calendar for %d\n' % theyear) + a(f'\n') a('\n') a('\n') a(self.formatyear(theyear, width)) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index 7d0f4c1fd400d53..6c0efb671975d4d 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -500,6 +500,7 @@ def _default_mime_types(): '.ps' : 'application/postscript', '.ai' : 'application/postscript', '.eps' : 'application/postscript', + '.toml' : 'application/toml', '.trig' : 'application/trig', '.m3u' : 'application/vnd.apple.mpegurl', '.m3u8' : 'application/vnd.apple.mpegurl', @@ -587,9 +588,9 @@ def _default_mime_types(): '.aiff' : 'audio/x-aiff', '.ra' : 'audio/x-pn-realaudio', '.wav' : 'audio/vnd.wave', + '.weba' : 'audio/webm', '.otf' : 'font/otf', '.ttf' : 'font/ttf', - '.weba' : 'audio/webm', '.woff' : 'font/woff', '.woff2' : 'font/woff2', '.avif' : 'image/avif', diff --git a/Lib/site.py b/Lib/site.py index f0e74eeee2f2e2b..7c6810792cfa7ee 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -449,9 +449,9 @@ def setcopyright(): """Set 'copyright' and 'credits' in builtins""" builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright) builtins.credits = _sitebuiltins._Printer("credits", """\ - Thanks to CWI, CNRI, BeOpen, Zope Corporation, the Python Software - Foundation, and a cast of thousands for supporting Python - development. See www.python.org for more information.""") +Thanks to CWI, CNRI, BeOpen, Zope Corporation, the Python Software +Foundation, and a cast of thousands for supporting Python +development. See www.python.org for more information.""") files, dirs = [], [] # Not all modules are required to have a __file__ attribute. See # PEP 420 for more details. diff --git a/Lib/test/test_calendar.py b/Lib/test/test_calendar.py index c129b3e51ba13da..020f9d61cae3cf6 100644 --- a/Lib/test/test_calendar.py +++ b/Lib/test/test_calendar.py @@ -113,18 +113,25 @@ default_format = dict(year="year", month="month", encoding="ascii") +result_2004_css = """""" + result_2004_html = """\ - - - + + - - + +Calendar for 2004 +{css_styles} + -
%s
{theyear}
-
2004
+
+
2004
@@ -133,7 +140,7 @@
January
MonTueWedThuFriSatSun
   1234
19202122232425
262728293031 
-
+
@@ -142,7 +149,7 @@
February
MonTueWedThuFriSatSun
      1
16171819202122
23242526272829
-
+
@@ -151,7 +158,7 @@
March
MonTueWedThuFriSatSun
1234567
22232425262728
293031    
-
+
@@ -160,7 +167,7 @@
April
MonTueWedThuFriSatSun
   1234
19202122232425
2627282930  
-
+
@@ -170,7 +177,7 @@
May
MonTueWedThuFriSatSun
     12
24252627282930
31      
-
+
@@ -179,7 +186,7 @@
June
MonTueWedThuFriSatSun
 123456
21222324252627
282930    
-
+
@@ -188,7 +195,7 @@
July
MonTueWedThuFriSatSun
   1234
19202122232425
262728293031 
-
+
@@ -198,7 +205,7 @@
August
MonTueWedThuFriSatSun
      1
23242526272829
3031     
-
+
@@ -207,7 +214,7 @@
September
MonTueWedThuFriSatSun
  12345
20212223242526
27282930   
-
+
@@ -216,7 +223,7 @@
October
MonTueWedThuFriSatSun
    123
18192021222324
25262728293031
-
+
@@ -225,7 +232,7 @@
November
MonTueWedThuFriSatSun
1234567
22232425262728
2930     
-
+
@@ -385,10 +392,12 @@ def check_htmlcalendar_encoding(self, req, res): cal = calendar.HTMLCalendar() format_ = default_format.copy() format_["encoding"] = req or 'utf-8' + format_with_css = {**format_, "css_styles": result_2004_css} + formatted_html = result_2004_html.format(**format_with_css) output = cal.formatyearpage(2004, encoding=req) self.assertEqual( output, - result_2004_html.format(**format_).encode(res) + formatted_html.encode(res) ) def test_output(self): @@ -1183,7 +1192,7 @@ def test_option_type(self): output = run('--type', 'text', '2004') self.assertEqual(output, conv(result_2004_text)) output = run('--type', 'html', '2004') - self.assertStartsWith(output, b'') self.assertIn(b'Calendar for 2004', output) def test_html_output_current_year(self): @@ -1196,15 +1205,16 @@ def test_html_output_current_year(self): def test_html_output_year_encoding(self): for run in self.runners: output = run('-t', 'html', '--encoding', 'ascii', '2004') - self.assertEqual(output, result_2004_html.format(**default_format).encode('ascii')) + format_with_css = default_format.copy() + format_with_css["css_styles"] = result_2004_css + self.assertEqual(output, result_2004_html.format(**format_with_css).encode('ascii')) def test_html_output_year_css(self): self.assertFailure('-t', 'html', '-c') self.assertFailure('-t', 'html', '--css') for run in self.runners: output = run('-t', 'html', '--css', 'custom.css', '2004') - self.assertIn(b'', output) + self.assertIn(b'', output) class MiscTestCase(unittest.TestCase): @@ -1258,7 +1268,7 @@ def test_formatweek_head(self): def test_format_year(self): self.assertIn( - ('
December
MonTueWedThuFriSatSun
  12345
' % + ('
' % self.cal.cssclass_year), self.cal.formatyear(2017)) def test_format_year_head(self): diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index c1806b1c1337786..a29815bf49b1e7d 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -230,6 +230,7 @@ def check_extensions(): ("application/gzip", ".gz"), ("application/ogg", ".ogx"), ("application/postscript", ".ps"), + ("application/toml", ".toml"), ("application/vnd.apple.mpegurl", ".m3u"), ("application/vnd.ms-excel", ".xls"), ("application/vnd.ms-fontobject", ".eot"), diff --git a/Lib/threading.py b/Lib/threading.py index fac88d8b20c60da..4ebceae70298700 100644 --- a/Lib/threading.py +++ b/Lib/threading.py @@ -653,7 +653,8 @@ def wait(self, timeout=None): (or fractions thereof). This method returns the internal flag on exit, so it will always return - True except if a timeout is given and the operation times out. + ``True`` except if a timeout is given and the operation times out, when + it will return ``False``. """ with self._cond: diff --git a/Misc/NEWS.d/next/Library/2023-03-21-10-59-40.gh-issue-102431.eUDnf4.rst b/Misc/NEWS.d/next/Library/2023-03-21-10-59-40.gh-issue-102431.eUDnf4.rst new file mode 100644 index 000000000000000..e82ddb6e1011ad9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-03-21-10-59-40.gh-issue-102431.eUDnf4.rst @@ -0,0 +1,2 @@ +Clarify constraints for "logical" arguments in methods of +:class:`decimal.Context`. diff --git a/Misc/NEWS.d/next/Library/2025-08-11-14-18-32.gh-issue-137634.M7iBG6.rst b/Misc/NEWS.d/next/Library/2025-08-11-14-18-32.gh-issue-137634.M7iBG6.rst new file mode 100644 index 000000000000000..e1d7c72d7e320c1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-08-11-14-18-32.gh-issue-137634.M7iBG6.rst @@ -0,0 +1,2 @@ +Calendar pages generated by the :class:`calendar.HTMLCalendar` class now support +dark mode and have been migrated to the HTML5 standard for improved accessibility. diff --git a/Misc/NEWS.d/next/Library/2025-09-16-16-46-58.gh-issue-138993.-8s8_T.rst b/Misc/NEWS.d/next/Library/2025-09-16-16-46-58.gh-issue-138993.-8s8_T.rst new file mode 100644 index 000000000000000..1be588f2ba568c1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-09-16-16-46-58.gh-issue-138993.-8s8_T.rst @@ -0,0 +1 @@ +Dedent :data:`credits` text. diff --git a/Misc/NEWS.d/next/Library/2025-10-02-17-40-10.gh-issue-70765.zVlLZn.rst b/Misc/NEWS.d/next/Library/2025-10-02-17-40-10.gh-issue-70765.zVlLZn.rst index e1a9bbe9afe4d17..d20f881eb09d553 100644 --- a/Misc/NEWS.d/next/Library/2025-10-02-17-40-10.gh-issue-70765.zVlLZn.rst +++ b/Misc/NEWS.d/next/Library/2025-10-02-17-40-10.gh-issue-70765.zVlLZn.rst @@ -1,5 +1,5 @@ :mod:`http.server`: fix default handling of HTTP/0.9 requests in :class:`~http.server.BaseHTTPRequestHandler`. Previously, -:meth:`!BaseHTTPRequestHandler.parse_request`` incorrectly +:meth:`!BaseHTTPRequestHandler.parse_request` incorrectly waited for headers in the request although those are not supported in HTTP/0.9. Patch by Bénédikt Tran. diff --git a/Misc/NEWS.d/next/Library/2025-10-11-17-41-26.gh-issue-139958.AnCakj.rst b/Misc/NEWS.d/next/Library/2025-10-11-17-41-26.gh-issue-139958.AnCakj.rst new file mode 100644 index 000000000000000..f129f8beb241d77 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-10-11-17-41-26.gh-issue-139958.AnCakj.rst @@ -0,0 +1,2 @@ +The ``application/toml`` mime type is now supported by :mod:`mimetypes`. +Patch by Gil Forcada. diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c index 04b6695f8af06a6..4e2a49531263605 100644 --- a/Modules/_decimal/_decimal.c +++ b/Modules/_decimal/_decimal.c @@ -5235,13 +5235,15 @@ _decimal_Decimal_copy_negate_impl(PyObject *self, PyTypeObject *cls) /*[clinic input] _decimal.Decimal.logical_invert = _decimal.Decimal.exp -Return the digit-wise inversion of the (logical) operand. +Invert all its digits. + +The self must be logical number. [clinic start generated code]*/ static PyObject * _decimal_Decimal_logical_invert_impl(PyObject *self, PyTypeObject *cls, PyObject *context) -/*[clinic end generated code: output=c626ed4b104a97b7 input=3531dac8b9548dad]*/ +/*[clinic end generated code: output=c626ed4b104a97b7 input=7158d5b525417955]*/ Dec_UnaryFuncVA(mpd_qinvert) /*[clinic input] @@ -5471,37 +5473,43 @@ _decimal_Decimal_same_quantum_impl(PyObject *self, PyTypeObject *cls, /*[clinic input] _decimal.Decimal.logical_and = _decimal.Decimal.compare -Return the digit-wise 'and' of the two (logical) operands. +Applies an 'and' operation between self and other's digits. + +Both self and other must be logical numbers. [clinic start generated code]*/ static PyObject * _decimal_Decimal_logical_and_impl(PyObject *self, PyTypeObject *cls, PyObject *other, PyObject *context) -/*[clinic end generated code: output=9a4cbb74c180b0bb input=2b319baee8970929]*/ +/*[clinic end generated code: output=9a4cbb74c180b0bb input=f22460f1285782d2]*/ Dec_BinaryFuncVA(mpd_qand) /*[clinic input] _decimal.Decimal.logical_or = _decimal.Decimal.compare -Return the digit-wise 'or' of the two (logical) operands. +Applies an 'or' operation between self and other's digits. + +Both self and other must be logical numbers. [clinic start generated code]*/ static PyObject * _decimal_Decimal_logical_or_impl(PyObject *self, PyTypeObject *cls, PyObject *other, PyObject *context) -/*[clinic end generated code: output=063c4de18dc41ecb input=75e0e1d4dd373b90]*/ +/*[clinic end generated code: output=063c4de18dc41ecb input=b5afa1e1fdebdfce]*/ Dec_BinaryFuncVA(mpd_qor) /*[clinic input] _decimal.Decimal.logical_xor = _decimal.Decimal.compare -Return the digit-wise 'xor' of the two (logical) operands. +Applies an 'xor' operation between self and other's digits. + +Both self and other must be logical numbers. [clinic start generated code]*/ static PyObject * _decimal_Decimal_logical_xor_impl(PyObject *self, PyTypeObject *cls, PyObject *other, PyObject *context) -/*[clinic end generated code: output=829b09cb49926ad7 input=a1ed8d6ac38c1c9e]*/ +/*[clinic end generated code: output=829b09cb49926ad7 input=84d722ada08a2da7]*/ Dec_BinaryFuncVA(mpd_qxor) /*[clinic input] @@ -7099,13 +7107,26 @@ DecCtx_UnaryFunc(mpd_qlogb) /*[clinic input] _decimal.Context.logical_invert = _decimal.Context.abs -Invert all digits of x. +Invert all the digits in the operand. + +The operand must be a logical number. + + >>> ExtendedContext.logical_invert(Decimal('0')) + Decimal('111111111') + >>> ExtendedContext.logical_invert(Decimal('1')) + Decimal('111111110') + >>> ExtendedContext.logical_invert(Decimal('111111111')) + Decimal('0') + >>> ExtendedContext.logical_invert(Decimal('101010101')) + Decimal('10101010') + >>> ExtendedContext.logical_invert(1101) + Decimal('111110010') [clinic start generated code]*/ static PyObject * _decimal_Context_logical_invert_impl(PyObject *context, PyTypeObject *cls, PyObject *x) -/*[clinic end generated code: output=97760277a958e2b0 input=1fa8dcc59c557fcc]*/ +/*[clinic end generated code: output=97760277a958e2b0 input=8e568f4c745ab596]*/ DecCtx_UnaryFunc(mpd_qinvert) /*[clinic input] @@ -7262,37 +7283,100 @@ _decimal_Context_copy_sign_impl(PyObject *context, PyTypeObject *cls, /*[clinic input] _decimal.Context.logical_and = _decimal.Context.add -Digit-wise and of x and y. +Applies the logical operation 'and' between each operand's digits. + +The operands must be both logical numbers. + + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) + Decimal('0') + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) + Decimal('0') + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) + Decimal('0') + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) + Decimal('1') + >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) + Decimal('1000') + >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) + Decimal('10') + >>> ExtendedContext.logical_and(110, 1101) + Decimal('100') + >>> ExtendedContext.logical_and(Decimal(110), 1101) + Decimal('100') + >>> ExtendedContext.logical_and(110, Decimal(1101)) + Decimal('100') [clinic start generated code]*/ static PyObject * _decimal_Context_logical_and_impl(PyObject *context, PyTypeObject *cls, PyObject *x, PyObject *y) -/*[clinic end generated code: output=009dfa08ecaa2ac8 input=30ee33b5b365fd80]*/ +/*[clinic end generated code: output=009dfa08ecaa2ac8 input=bcb7d3d6ab7530de]*/ DecCtx_BinaryFunc(mpd_qand) /*[clinic input] _decimal.Context.logical_or = _decimal.Context.add -Digit-wise or of x and y. +Applies the logical operation 'or' between each operand's digits. + +The operands must be both logical numbers. + + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) + Decimal('0') + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) + Decimal('1') + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) + Decimal('1') + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) + Decimal('1') + >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) + Decimal('1110') + >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) + Decimal('1110') + >>> ExtendedContext.logical_or(110, 1101) + Decimal('1111') + >>> ExtendedContext.logical_or(Decimal(110), 1101) + Decimal('1111') + >>> ExtendedContext.logical_or(110, Decimal(1101)) + Decimal('1111') [clinic start generated code]*/ static PyObject * _decimal_Context_logical_or_impl(PyObject *context, PyTypeObject *cls, PyObject *x, PyObject *y) -/*[clinic end generated code: output=eb38617e8d31bf12 input=3b1a6725d0262fb9]*/ +/*[clinic end generated code: output=eb38617e8d31bf12 input=47b45d296fb90846]*/ DecCtx_BinaryFunc(mpd_qor) /*[clinic input] _decimal.Context.logical_xor = _decimal.Context.add -Digit-wise xor of x and y. +Applies the logical operation 'xor' between each operand's digits. + +The operands must be both logical numbers. + + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) + Decimal('0') + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) + Decimal('1') + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) + Decimal('1') + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) + Decimal('0') + >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) + Decimal('110') + >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) + Decimal('1101') + >>> ExtendedContext.logical_xor(110, 1101) + Decimal('1011') + >>> ExtendedContext.logical_xor(Decimal(110), 1101) + Decimal('1011') + >>> ExtendedContext.logical_xor(110, Decimal(1101)) + Decimal('1011') [clinic start generated code]*/ static PyObject * _decimal_Context_logical_xor_impl(PyObject *context, PyTypeObject *cls, PyObject *x, PyObject *y) -/*[clinic end generated code: output=23cd81fdcd865d5a input=5ebbbe8bb35da380]*/ +/*[clinic end generated code: output=23cd81fdcd865d5a input=fcaaf828c1d2d089]*/ DecCtx_BinaryFunc(mpd_qxor) /*[clinic input] diff --git a/Modules/_decimal/clinic/_decimal.c.h b/Modules/_decimal/clinic/_decimal.c.h index ccfbf63a7cead55..b09200845d12e98 100644 --- a/Modules/_decimal/clinic/_decimal.c.h +++ b/Modules/_decimal/clinic/_decimal.c.h @@ -2744,7 +2744,9 @@ PyDoc_STRVAR(_decimal_Decimal_logical_invert__doc__, "logical_invert($self, /, context=None)\n" "--\n" "\n" -"Return the digit-wise inversion of the (logical) operand."); +"Invert all its digits.\n" +"\n" +"The self must be logical number."); #define _DECIMAL_DECIMAL_LOGICAL_INVERT_METHODDEF \ {"logical_invert", _PyCFunction_CAST(_decimal_Decimal_logical_invert), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Decimal_logical_invert__doc__}, @@ -3336,7 +3338,9 @@ PyDoc_STRVAR(_decimal_Decimal_logical_and__doc__, "logical_and($self, /, other, context=None)\n" "--\n" "\n" -"Return the digit-wise \'and\' of the two (logical) operands."); +"Applies an \'and\' operation between self and other\'s digits.\n" +"\n" +"Both self and other must be logical numbers."); #define _DECIMAL_DECIMAL_LOGICAL_AND_METHODDEF \ {"logical_and", _PyCFunction_CAST(_decimal_Decimal_logical_and), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Decimal_logical_and__doc__}, @@ -3402,7 +3406,9 @@ PyDoc_STRVAR(_decimal_Decimal_logical_or__doc__, "logical_or($self, /, other, context=None)\n" "--\n" "\n" -"Return the digit-wise \'or\' of the two (logical) operands."); +"Applies an \'or\' operation between self and other\'s digits.\n" +"\n" +"Both self and other must be logical numbers."); #define _DECIMAL_DECIMAL_LOGICAL_OR_METHODDEF \ {"logical_or", _PyCFunction_CAST(_decimal_Decimal_logical_or), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Decimal_logical_or__doc__}, @@ -3468,7 +3474,9 @@ PyDoc_STRVAR(_decimal_Decimal_logical_xor__doc__, "logical_xor($self, /, other, context=None)\n" "--\n" "\n" -"Return the digit-wise \'xor\' of the two (logical) operands."); +"Applies an \'xor\' operation between self and other\'s digits.\n" +"\n" +"Both self and other must be logical numbers."); #define _DECIMAL_DECIMAL_LOGICAL_XOR_METHODDEF \ {"logical_xor", _PyCFunction_CAST(_decimal_Decimal_logical_xor), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Decimal_logical_xor__doc__}, @@ -6235,7 +6243,20 @@ PyDoc_STRVAR(_decimal_Context_logical_invert__doc__, "logical_invert($self, x, /)\n" "--\n" "\n" -"Invert all digits of x."); +"Invert all the digits in the operand.\n" +"\n" +"The operand must be a logical number.\n" +"\n" +" >>> ExtendedContext.logical_invert(Decimal(\'0\'))\n" +" Decimal(\'111111111\')\n" +" >>> ExtendedContext.logical_invert(Decimal(\'1\'))\n" +" Decimal(\'111111110\')\n" +" >>> ExtendedContext.logical_invert(Decimal(\'111111111\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_invert(Decimal(\'101010101\'))\n" +" Decimal(\'10101010\')\n" +" >>> ExtendedContext.logical_invert(1101)\n" +" Decimal(\'111110010\')"); #define _DECIMAL_CONTEXT_LOGICAL_INVERT_METHODDEF \ {"logical_invert", _PyCFunction_CAST(_decimal_Context_logical_invert), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_logical_invert__doc__}, @@ -6556,7 +6577,28 @@ PyDoc_STRVAR(_decimal_Context_logical_and__doc__, "logical_and($self, x, y, /)\n" "--\n" "\n" -"Digit-wise and of x and y."); +"Applies the logical operation \'and\' between each operand\'s digits.\n" +"\n" +"The operands must be both logical numbers.\n" +"\n" +" >>> ExtendedContext.logical_and(Decimal(\'0\'), Decimal(\'0\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_and(Decimal(\'0\'), Decimal(\'1\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_and(Decimal(\'1\'), Decimal(\'0\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_and(Decimal(\'1\'), Decimal(\'1\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_and(Decimal(\'1100\'), Decimal(\'1010\'))\n" +" Decimal(\'1000\')\n" +" >>> ExtendedContext.logical_and(Decimal(\'1111\'), Decimal(\'10\'))\n" +" Decimal(\'10\')\n" +" >>> ExtendedContext.logical_and(110, 1101)\n" +" Decimal(\'100\')\n" +" >>> ExtendedContext.logical_and(Decimal(110), 1101)\n" +" Decimal(\'100\')\n" +" >>> ExtendedContext.logical_and(110, Decimal(1101))\n" +" Decimal(\'100\')"); #define _DECIMAL_CONTEXT_LOGICAL_AND_METHODDEF \ {"logical_and", _PyCFunction_CAST(_decimal_Context_logical_and), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_logical_and__doc__}, @@ -6603,7 +6645,28 @@ PyDoc_STRVAR(_decimal_Context_logical_or__doc__, "logical_or($self, x, y, /)\n" "--\n" "\n" -"Digit-wise or of x and y."); +"Applies the logical operation \'or\' between each operand\'s digits.\n" +"\n" +"The operands must be both logical numbers.\n" +"\n" +" >>> ExtendedContext.logical_or(Decimal(\'0\'), Decimal(\'0\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_or(Decimal(\'0\'), Decimal(\'1\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_or(Decimal(\'1\'), Decimal(\'0\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_or(Decimal(\'1\'), Decimal(\'1\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_or(Decimal(\'1100\'), Decimal(\'1010\'))\n" +" Decimal(\'1110\')\n" +" >>> ExtendedContext.logical_or(Decimal(\'1110\'), Decimal(\'10\'))\n" +" Decimal(\'1110\')\n" +" >>> ExtendedContext.logical_or(110, 1101)\n" +" Decimal(\'1111\')\n" +" >>> ExtendedContext.logical_or(Decimal(110), 1101)\n" +" Decimal(\'1111\')\n" +" >>> ExtendedContext.logical_or(110, Decimal(1101))\n" +" Decimal(\'1111\')"); #define _DECIMAL_CONTEXT_LOGICAL_OR_METHODDEF \ {"logical_or", _PyCFunction_CAST(_decimal_Context_logical_or), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_logical_or__doc__}, @@ -6650,7 +6713,28 @@ PyDoc_STRVAR(_decimal_Context_logical_xor__doc__, "logical_xor($self, x, y, /)\n" "--\n" "\n" -"Digit-wise xor of x and y."); +"Applies the logical operation \'xor\' between each operand\'s digits.\n" +"\n" +"The operands must be both logical numbers.\n" +"\n" +" >>> ExtendedContext.logical_xor(Decimal(\'0\'), Decimal(\'0\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_xor(Decimal(\'0\'), Decimal(\'1\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_xor(Decimal(\'1\'), Decimal(\'0\'))\n" +" Decimal(\'1\')\n" +" >>> ExtendedContext.logical_xor(Decimal(\'1\'), Decimal(\'1\'))\n" +" Decimal(\'0\')\n" +" >>> ExtendedContext.logical_xor(Decimal(\'1100\'), Decimal(\'1010\'))\n" +" Decimal(\'110\')\n" +" >>> ExtendedContext.logical_xor(Decimal(\'1111\'), Decimal(\'10\'))\n" +" Decimal(\'1101\')\n" +" >>> ExtendedContext.logical_xor(110, 1101)\n" +" Decimal(\'1011\')\n" +" >>> ExtendedContext.logical_xor(Decimal(110), 1101)\n" +" Decimal(\'1011\')\n" +" >>> ExtendedContext.logical_xor(110, Decimal(1101))\n" +" Decimal(\'1011\')"); #define _DECIMAL_CONTEXT_LOGICAL_XOR_METHODDEF \ {"logical_xor", _PyCFunction_CAST(_decimal_Context_logical_xor), METH_METHOD|METH_FASTCALL|METH_KEYWORDS, _decimal_Context_logical_xor__doc__}, @@ -6896,4 +6980,4 @@ _decimal_Context_same_quantum(PyObject *context, PyTypeObject *cls, PyObject *co #ifndef _DECIMAL_CONTEXT_APPLY_METHODDEF #define _DECIMAL_CONTEXT_APPLY_METHODDEF #endif /* !defined(_DECIMAL_CONTEXT_APPLY_METHODDEF) */ -/*[clinic end generated code: output=e938de3a355a353a input=a9049054013a1b77]*/ +/*[clinic end generated code: output=b288181c82fdc9f1 input=a9049054013a1b77]*/