Compare commits

...

445 Commits

Author SHA1 Message Date
Jason R. Coombs a78f0158a2 Merge branch 'master' into revert-23107-revert-13893-fix-issue-37193 2020-12-27 12:46:59 -05:00
Erlend Egeberg Aasland bf64d9064a
bpo-1635741: sqlite3 uses Py_NewRef/Py_XNewRef (GH-23170) 2020-12-27 12:05:33 +01:00
Erlend Egeberg Aasland 3ccef1ca47
bpo-40956: Convert _sqlite3.Connection to Argument Clinic, part 2 (GH-23838) 2020-12-27 17:32:18 +09:00
Serhiy Storchaka b02ad2458b
bpo-42749: Fix testing bignum if Tkinter is compiled with Tk 8.4 and dynamic linked with Tk >= 8.5 (GH-23955) 2020-12-27 10:13:30 +02:00
Victor Stinner f4507231e3
bpo-42745: finalize_interp_types() calls _PyType_Fini() (GH-23953)
Call _PyType_Fini() in subinterpreters.

Fix reference leaks in subinterpreters.
2020-12-26 20:26:08 +01:00
Pablo Galindo 3bcc4ead3f
Add small validator utility for PEG grammars (GH-23519) 2020-12-26 19:11:29 +00:00
Shantanu 7865f516f3
bpo-16396: fix BPO number in changelog (GH-23951)
Automerge-Triggered-By: GH:jaraco
2020-12-26 07:36:56 -08:00
Dong-hee Na 0b281f94b9
bpo-42748: test_asdl_parser now uses exec_module instead of load_module (#23954) 2020-12-26 16:25:21 +03:00
Victor Stinner ea251806b8
bpo-40521: Per-interpreter interned strings (GH-20085)
Make the Unicode dictionary of interned strings compatible with
subinterpreters.

Remove the INTERN_NAME_STRINGS macro in typeobject.c: names are
always now interned (even if EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
macro is defined).

_PyUnicode_ClearInterned() now uses PyDict_Next() to no longer
allocate memory, to ensure that the interned dictionary is cleared.
2020-12-26 02:58:33 +01:00
Victor Stinner 993e88cf08
bpo-42694: Prevent creating _curses_panel.panel (GH-23948)
Fix regression introduced in
commit 1baf030a902392fe92d934ed0fb6a385cf7d8869: restore removed code
to prevent creating a _curses_panel.panel instance directly.
2020-12-26 02:17:46 +01:00
Victor Stinner 4101018488
bpo-42745: Make the type cache per-interpreter (GH-23947)
Make the type attribute lookup cache per-interpreter.

Add private _PyType_InitCache() function, called by PyInterpreterState_New().

Continue to share next_version_tag between interpreters, since static
types are still shared by interpreters.

Remove MCACHE macro: the cache is no longer disabled if the
EXPERIMENTAL_ISOLATED_SUBINTERPRETERS macro is defined.
2020-12-26 01:45:43 +01:00
Raymond Hettinger 77fde8dc16
Add convolve() to the itertools recipes (GH-23928) 2020-12-25 16:43:20 -08:00
Victor Stinner ba3d67c2fb
bpo-39465: Fix _PyUnicode_FromId() for subinterpreters (GH-20058)
Make _PyUnicode_FromId() function compatible with subinterpreters.
Each interpreter now has an array of identifier objects (interned
strings decoded from UTF-8).

* Add PyInterpreterState.unicode.identifiers: array of identifiers
  objects.
* Add _PyRuntimeState.unicode_ids used to allocate unique indexes
  to _Py_Identifier.
* Rewrite the _Py_Identifier structure.

Microbenchmark on _PyUnicode_FromId(&PyId_a) with _Py_IDENTIFIER(a):

[ref] 2.42 ns +- 0.00 ns -> [atomic] 3.39 ns +- 0.00 ns: 1.40x slower

This change adds 1 ns per _PyUnicode_FromId() call in average.
2020-12-26 00:41:46 +01:00
Ken Jin f0853bcedf
Sync what's new in 3.9 with 3.9 branch (GH-23943) 2020-12-25 23:08:17 +00:00
Eric Snow 5ae9be68d9
bpo-36876: [c-analyzer tool] Additional CLI updates for "capi" command. (gh-23929)
https://bugs.python.org/issue36876
2020-12-25 15:57:30 -07:00
Serhiy Storchaka c1ae21c965
Rename Tkinter tests for widget options (GH-23944)
Every test for widget option starts now with "test_configure_"
to distinguish it from tests for widget commands.
2020-12-26 00:10:29 +02:00
Desmond Cheong 36a779e64c
bpo-35728: Add root parameter to tkinter.font.nametofont() (GH-23885) 2020-12-25 23:18:06 +02:00
Serhiy Storchaka 675c97eb6c
bpo-42721: Improve using simple dialogs without root window (GH-23897)
When simple query dialogs (tkinter.simpledialog), message boxes
(tkinter.messagebox) or color choose dialog (tkinter.colorchooser)
are created without arguments master and parent, and the default
root window is not yet created, a new temporary hidden root window
will be created automatically. It will not be set as the default root
window and will be destroyed right after closing the dialog window.
It will help to use these simple dialog windows in programs which do
not need other GUI.

Previously, message boxes and color chooser created the blank root
window and left it after closing the dialog window, and query dialogs
just raised an exception.

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
2020-12-25 20:19:20 +02:00
Irit Katriel 586f3dbe15
bpo-28964: add line number of node (if available) to ast.literal_eval error messages (GH-23677) 2020-12-25 20:04:31 +03:00
Serhiy Storchaka bb70b2afe3
bpo-15303: Support widgets with boolean value False in Tkinter (GH-23904)
Use `widget is None` instead of checking the boolean value of a widget.
2020-12-25 17:04:26 +02:00
Serhiy Storchaka 954a7427ba
bpo-42734: Fix crasher bogus_code_obj.py (GH-23939)
It did not work because the signature of code object constructor
was changed. Also, it used old format of bytecode (pre-wordcode).
2020-12-25 17:03:37 +02:00
Erlend Egeberg Aasland 7f162e867c
bpo-29076: Add fish support to macOS installer (GH-23302) 2020-12-25 03:01:30 -08:00
Gregory P. Smith 64abf37344
bpo-42388: Fix subprocess.check_output input=None when text=True (GH-23467)
When the modern text= spelling of the universal_newlines= parameter was added
for Python 3.7, check_output's special case around input=None was overlooked.
So it behaved differently with universal_newlines=True vs text=True.  This
reconciles the behavior to be consistent and adds a test to guarantee it.

Also clarifies the existing check_output documentation.

Co-authored-by: Alexey Izbyshev <izbyshev@ispras.ru>
2020-12-24 20:57:21 -08:00
Gregory P. Smith 8badadec53
bpo-42727: Fix the NEWS entry .rst (GH-23932)
It was causing CI failures.  the offending file came from https://github.com/python/cpython/pull/23917

```
python3 tools/rstlint.py ../Misc/NEWS.d/next/
[2] ../Misc/NEWS.d/next/Library/2020-12-23-19-43-06.bpo-42727.WH3ODh.rst:1: default role used
[2] ../Misc/NEWS.d/next/Library/2020-12-23-19-43-06.bpo-42727.WH3ODh.rst:2: default role used
2 problems with severity 2 found.
Makefile:204: recipe for target 'check' failed
```
2020-12-24 20:31:18 -08:00
Ethan Furman 786d97a66c
bpo-42727: [Enum] use super() and include **kwds (GH-23927)
for multiple inheritance support:

use super().new
pass **kwds to super().new
2020-12-24 19:31:10 -08:00
Serhiy Storchaka c6c43b2874
bpo-42685: Improve placing of simple query windows. (GH-23856)
* If parent is specified and mapped, the query widget is
  centered at the center of parent. Its position and size
  can be corrected so that it fits in the virtual root window.
* Otherwise it is centered at the center of the screen.
2020-12-24 20:26:28 +02:00
Ethan Furman 6ec0adefad
[Enum] EnumMeta.__prepare__ now accepts **kwds (#23917) 2020-12-24 10:05:02 -08:00
Eric Snow 7ec59d8861
bpo-36876: [c-analyzer tool] Add a "capi" subcommand to the c-analyzer tool. (gh-23918)
This will help identify which C-API items will need to be updated for subinterpreter support.

https://bugs.python.org/issue36876
2020-12-24 11:04:19 -07:00
Augusto Hack b57ada98da
closes bpo-42726: gdb libpython: InstanceProxy support for py3 (GH-23912)
On Fedora 31 gdb is using python 3.7.9, calling `proxyval` on an instance with a dictionary fails because of the `dict.iteritems` usage. This PR changes the code to be compatible with py2 and py3.

This changed seemed small enough to not need an issue and news blurb, if one is required please let me know.

Automerge-Triggered-By: GH:benjaminp
2020-12-24 09:16:04 -08:00
Batuhan Taskaya a9ef95b811
GH: Add isidentical to the CODEOWNERS (GH-23923) 2020-12-24 14:30:46 +03:00
kj 73607be686
bpo-41559: Implement PEP 612 - Add ParamSpec and Concatenate to typing (#23702) 2020-12-23 20:33:48 -08:00
Raymond Hettinger cc3467a57b
bpo-38308: Add optional weighting to statistics.harmonic_mean() (GH-23914) 2020-12-23 19:52:09 -08:00
kj 6dd3da3cf4
bpo-42195: Override _CallableGenericAlias's __getitem__ (GH-23915)
Added `__getitem__` for `_CallableGenericAlias` so that it returns a subclass (itself) of `types.GenericAlias` rather than the default behavior of returning a plain `types.GenericAlias`. This fixes `repr` issues occuring after `TypeVar` substitution arising from the previous behavior.
2020-12-23 18:47:40 -08:00
Batuhan Taskaya eee1c7745a
bpo-41960: Add globalns and localns parameters to inspect.signature and Signature.from_callable (GH-22583) 2020-12-24 01:45:13 +03:00
Raymond Hettinger 6b1ac809b9
bpo-25246: Optimize deque.remove() (GH-23898) 2020-12-23 11:45:06 -08:00
Victor Stinner a12491681f
bpo-32381: pymain_run_command() uses PyCF_IGNORE_COOKIE (GH-23724)
The coding cookie (ex: "# coding: latin1") is now ignored in the
command passed to the -c command line option.

Since pymain_run_command() uses UTF-8, pass PyCF_IGNORE_COOKIE
compiler flag to the parser.

pymain_run_python() no longer propages compiler flags between
function calls.
2020-12-23 19:16:56 +01:00
Raymond Hettinger 41b223d29c
bpo-9694: Fix misleading phrase "optional arguments" (GH-23858) 2020-12-23 09:40:56 -08:00
Victor Stinner bfda4f5776
bpo-28468: Fix typo in _os_release_candidates (GH-23913)
Automerge-Triggered-By: GH:tiran
2020-12-23 08:35:53 -08:00
Mark Shannon 28b75c80dc
bpo-42246: Don't eliminate jumps to jumps, if it will break PEP 626. (GH-23896) 2020-12-23 11:43:10 +00:00
Matt Fowler d90ff37681
BPO-42703: Fix incorrect documentation links for asyncio.Event (GH-23881) 2020-12-23 12:44:52 +02:00
Christian Heimes 6d9ec8bbfa
bpo-1635741: Port resource extension module to module state (GH-23462)
Signed-off-by: Christian Heimes <christian@python.org>
2020-12-23 08:55:11 +01:00
Christian Heimes cf3565ca9a
bpo-42620: Improve socket.getsockname doc string (GH-23742)
Signed-off-by: Christian Heimes <christian@python.org>
2020-12-22 23:25:57 -08:00
Victor Stinner 52a327c1cb
bpo-39465: Add pycore_atomic_funcs.h header (GH-20766)
Add pycore_atomic_funcs.h internal header file: similar to
pycore_atomic.h but don't require to declare variables as atomic.

Add _Py_atomic_size_get() and _Py_atomic_size_set() functions.
2020-12-23 03:41:08 +01:00
Joannah Nanjekye 46b5c6be29
Fix typos in sysmodule (GH-23883) 2020-12-22 18:31:46 -04:00
Irit Katriel 069560b117
bpo-34463: Make python tracebacks identical to C tracebacks for SyntaxErrors without a lineno (GH-23427) 2020-12-22 21:53:09 +02:00
Raymond Hettinger 6afb730e2a
bpo-29030: Document interaction between *choices* and *metavar*. (GH-23884) 2020-12-22 09:24:26 -08:00
Andre Delfino 60eccd0956
[doc] Fix missing commas in signatures (#23693)
* Fix star in signatures

* Fix comma in signatures
2020-12-22 11:02:52 -05:00
erykoff b3c77ecbbe
bpo-42688: Fix ffi alloc/free when using external libffi on macos (GH-23868)
Automerge-Triggered-By: GH:ronaldoussoren
2020-12-22 03:12:07 -08:00
Batuhan Taskaya fbc7723778
bpo-39159: Declare error that might be raised from literal_eval (GH-19899) 2020-12-21 16:15:40 -08:00
AMIR b8fde8b541
bpo-42008: Fix internal _random.Random() seeding for the one argument case (GH-22668) 2020-12-21 15:45:50 -08:00
Fernando Toledo 711381dfb0
Fix typo in docstring (GH-23515) 2020-12-21 16:06:31 +02:00
Mark Shannon f2dbfd7e20
bpo-42634: Mark reraise after except blocks as artificial. (GH-23877)
* Mark reraise after except blocks as artificial.

* Update importlib

* Update dis test.
2020-12-21 13:53:50 +00:00
Géry Ogam d515c610c6
bpo-35790: Correct the description of sys.exc_info() and add a code example (GH-11625) 2020-12-21 14:13:08 +01:00
Daniel Hahler 37a6d5f802
[WIP/RFC] bpo-15872: tests: remove oddity from test_rmtree_errors (GH-22967)
This was added for (some) Windows buildbots back in 2012, and should
either not be necessary anymore, or it should probably get investigated
why "\*.*" gets added to filenames in the first place.

Ref:

Automerge-Triggered-By: GH:hynek
2020-12-20 22:38:02 -08:00
pxinwr ab74c014ae
bpo-31904: Fix site and sysconfig modules for VxWorks RTOS (GH-21821) 2020-12-20 23:27:42 +01:00
Colin Watson c95f8bc270
bpo-42669: Document that `except` rejects nested tuples (GH-23822)
In Python 2, it was possible to use `except` with a nested tuple, and occasionally natural.  For example, `zope.formlib.interfaces.InputErrors` is a tuple of several exception classes, and one might reasonably think to do something like this:

    try:
        self.getInputValue()
        return True
    except (InputErrors, SomethingElse):
        return False

As of Python 3.0, this raises `TypeError: catching classes that do not inherit from BaseException is not allowed` instead: one must instead either break it up into multiple `except` clauses or flatten the tuple.  However, the reference documentation was never updated to match this new restriction.  Make it clear that the definition is no longer recursive.

Automerge-Triggered-By: GH:ericvsmith
2020-12-20 10:24:10 -08:00
Raymond Hettinger b0398a4b7f
bpo-42572: Improve argparse docs for the type parameter. (GH-23849) 2020-12-20 10:14:54 -08:00
Matti Picus a44ce6c9f7
bpo-42604: always set EXT_SUFFIX=${SOABI}${SHLIB_SUFFIX} when using configure (GH-23708)
Now all platforms use a value for the "EXT_SUFFIX" build variable derived
from SOABI (for instance in FreeBSD, "EXT_SUFFIX" is now ".cpython-310d.so"
instead of ".so"). Previously only Linux, Mac and VxWorks were using a value
for "EXT_SUFFIX" that included "SOABI".

Co-authored-by: Pablo Galindo <pablogsal@gmail.com>
2020-12-20 02:56:57 +00:00
sblondon 09a36cdfb7
bpo-41724: Explain when the conversion is not possible with detect_types enabled (GH-23855)
* Explain when the conversion is not possible with detect_types enabled
2020-12-19 17:52:39 -05:00
Andre Delfino c56f9df049
[doc] Mention with and except clauses in globals() (GH-13232) 2020-12-19 16:48:06 +01:00
Serhiy Storchaka 3d569fd6dc
bpo-42630: Improve error reporting in Tkinter for absent default root (GH-23781)
* Tkinter functions and constructors which need a default root window
  raise now RuntimeError with descriptive message instead of obscure
  AttributeError or NameError if it is not created yet or cannot
  be created automatically.

* Add tests for all functions which use default root window.

* Fix import in the pynche script.
2020-12-19 12:17:08 +02:00
masklinn 1e27b57dbc
bpo-42470: Do not warn on sequences which are also sets in random.sample() (GH-23665) 2020-12-18 20:33:36 -08:00
Casper Smet e009612476
Fixed typo in itertools documentation (GH-23816) 2020-12-18 20:28:21 -08:00
Raymond Hettinger 5646414ae1
bpo-42559: Not that getrandbits() is non-negative. (GH-23843) 2020-12-18 17:03:10 -08:00
Raymond Hettinger 51f4688254
bpo-34805: Guarantee that __subclasses__() is in definition order. (GH-23844) 2020-12-18 16:53:50 -08:00
Irit Katriel fb34096140
bpo-24792: Fix zipimporter masking the cause of import errors (GH-22204)
zipimport's _unmarshal_code swallows import errors and then _get_module_code doesn't know the cause of the error, and returns the generic, and sometimes incorrect, 'could not find...'.

Automerge-Triggered-By: GH:brettcannon
2020-12-18 16:09:54 -08:00
Andre Delfino e8d2264210
bpo-36769: Document that fnmatch.filter supports any kind of iterable (#13039) 2020-12-18 20:10:20 +01:00
Ammar Askar 8c5d0347ef
bpo-34398: Allow glossary results to show up on search page (GH-8773) 2020-12-18 20:00:51 +01:00
kj d75f6f78e6
bpo-42675: Document collections.abc.Callable changes (GH-23839) 2020-12-18 09:39:26 -08:00
Richard Kojedzinszky 17ef4319a3
bpo-41891: ensure asyncio.wait_for waits for task completion (#22461) 2020-12-18 09:26:04 -08:00
Dong-hee Na 2179349d8c
bpo-40956: Fix sqlite3 AC code (GH-23837) 2020-12-19 00:41:33 +09:00
Erlend Egeberg Aasland 1ba82bbc50
bpo-40956: Convert _sqlite3.Connection to Argument Clinic (GH-23341) 2020-12-18 23:25:35 +09:00
Matt Wozniski 84ebcf271a
bpo-17140: Document multiprocessing's ThreadPool (GH-23812)
Up until now, the `multiprocessing.pool.ThreadPool` class has gone
undocumented, despite being a public class in multiprocessing that is
included in `multiprocessing.pool.__all__`.
2020-12-18 13:05:46 +00:00
Julien Palard b9735420aa
bpo-42238: Check Misc/NEWS.d/next/ for reStructuredText issues. (GH-23802) 2020-12-18 10:48:08 +01:00
Mark Dickinson 886b2e5c7a
bpo-39096: Format specification documentation fixes for numeric types (GH-23575) 2020-12-18 10:24:06 +01:00
Victor Stinner 6104013838
bpo-1635741: Port _thread to multiphase init (GH-23811)
Port the _thread extension module to the multiphase initialization
API (PEP 489) and convert its static types to heap types.

Add a traverse function to the lock type, so the garbage collector
can break reference cycles.
2020-12-18 01:39:00 +01:00
Max Bernstein 6e799be0a1
bpo-42199: Fix bytecode_helper assertNotInBytecode (#23031)
* bpo-42199: Fix bytecode_helper assertNotInBytecode

Add tests.

* 📜🤖 Added by blurb_it.

Co-authored-by: Dino Viehland <dinoviehland@fb.com>
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
2020-12-17 16:30:29 -08:00
Zackery Spytz 074ad5123f
bpo-42670: Fix a missing word in the itertools.product() docs (GH-23823) 2020-12-17 12:24:43 -08:00
pxinwr 75dabfe7a8
bpo-31904: posixpath.expanduser() handles None user home on VxWorks (GH-23530) 2020-12-17 20:22:29 +01:00
Andre Delfino 96a09df644
[doc] Fix a few margins due to bad markup (GH-23619) 2020-12-17 09:25:55 -08:00
Mark Shannon bf353f3c2d
bpo-42246: Make sure that `f_lasti`, and thus `f_lineno`, is set correctly after raising or reraising an exception (GH-23803)
* Ensure that f_lasti is set correctly after an exception is raised to conform to PEP 626.

* Update importlib

* Add NEWS.
2020-12-17 13:55:28 +00:00
Irit Katriel 40125ab325
bpo-26564: fix obsolete comment in traceback.c (GH-23819) 2020-12-17 13:33:07 +01:00
pxinwr ba760f3710
bpo-31904: Skip some asyncio tests on VxWorks (#23815) 2020-12-17 12:04:47 +02:00
Andre Delfino dcc997cd28
[doc] Fix erroneous backslashes in signatures and names (GH-23658)
The issue being resolved is shown in the 3.10 docs (if you select docs for older versions you won't see a visual glitch).

The newer sphinx version that produces the 3.10 docs doesn't treat the backslash to escape things in some situations it previously did.
2020-12-16 17:37:28 -08:00
Mike Lei c143cc379c
Correct referenced RFC number in cgi module (GH-22827)
The quoted sentence can be found from the last paragraph of RFC 2046, Section 5.1, while the content of RFC 2026 is unrelated to this module.
2020-12-16 17:34:19 -08:00
Matthew Suozzo a6ba2b9015
Fix indentation for get_stats_profile() docs (GH-23618)
The existing method is indented one too many times which
makes it look like a sub-method of print_callees().
2020-12-17 01:17:22 +02:00
Daniel Hahler 051b981867
bpo-37961: Fix regression in tracemalloc.Traceback.__repr__ (GH-23805)
Regression in 8d59eb1b66.
2020-12-16 22:38:32 +01:00
Chris Jerdonek 66d3b589c4
bpo-38323: Add guard clauses in MultiLoopChildWatcher. (#22756)
This is a trivial refactor in preparation for a fix for bpo-38323.
2020-12-16 19:50:25 +02:00
Irit Katriel c590c2338e
bpo-23915: update and elucidate documentation of with_traceback (GH-23680) 2020-12-16 17:03:32 +01:00
Antoine fc3dca3e16
Clarify eval() doc from library/functions. (GH-22700) 2020-12-16 16:45:19 +01:00
Victor Stinner aefb69b23f
bpo-40686: Fix compiler warnings on _zoneinfo.c (GH-23614)
"uint8_t day" is unsigned and so "day < 0" test is always true.
Remove the test to fix the following warnings on Windows:

modules\_zoneinfo.c(1224): warning C4068: unknown pragma
modules\_zoneinfo.c(1225): warning C4068: unknown pragma
modules\_zoneinfo.c(1227): warning C4068: unknown pragma
2020-12-16 16:26:15 +01:00
Julien Palard 37caeb172b
Fix reStructuredText typo in NEWS.d. (GH-23800) 2020-12-16 16:22:19 +01:00
Victor Stinner fcc6935384
Add symbols of the stable ABI to python3dll.c (GH-23598)
Add the following symbols to python3dll.c:

* PyFrame_GetCode (bpo-40421)
* PyFrame_GetLineNumber (bpo-40421)
* PyModule_AddObjectRef (bpo-1635741)
* PyObject_CallNoArgs (bpo-37194)
* PyThreadState_GetFrame (bpo-39947)
* PyThreadState_GetID (bpo-39947)
* PyThreadState_GetInterpreter (bpo-39947)
2020-12-16 15:08:23 +01:00
Mark Shannon 5274b682bc
bpo-42645: Make sure that return/break/continue are only traced once when exiting via a finally block. (GH-23780)
* Make sure that return/break/continue are only traced once when exiting via a finally block.

* Add test for return in try-finally.

* Update importlib
2020-12-16 13:07:01 +00:00
Om G c71581c7a4
bpo-42615: Delete redundant jump instructions that only bypass empty blocks (GH-23733)
* Delete jump instructions that bypass empty blocks

* Add news entry

* Explicitly check for unconditional jump opcodes

Using the is_jump function results in the inclusion of instructions like
returns for which this optimization is not really valid. So, instead
explicitly check that the instruction is an unconditional jump.

* Handle conditional jumps, delete jumps gracefully

* Ensure b_nofallthrough and b_reachable are valid

* Add test for redundant jumps

* Regenerate importlib.h and edit Misc/ACKS

* Fix bad whitespace
2020-12-16 12:18:05 +00:00
Victor Stinner 8203c73f3b
bpo-1635741: Refactor _threadmodule.c (GH-23793)
* Fix ExceptHookArgsType name: "_thread.ExceptHookArgs", instead of
  "_thread._ExceptHookArgs".
* PyInit__thread() no longer intializes interp->num_threads to 0:
  it is already done in PyInterpreterState_New().
* Use PyModule_AddType(), Py_NewRef() and Py_XNewRef().
* Replace str_dict variable with _Py_IDENTIFIER(__dict__).
* Remove assert(Py_IS_TYPE(obj, &Locktype)) from release_sentinel()
  to avoid having to retrive the type from this callback.
* Add thread_bootstate_free()
* Rename t_bootstrap() to thread_run()
* bootstate structure: rename keyw member to kwargs
2020-12-16 12:20:33 +01:00
Victor Stinner 1c653f17cb
bpo-42613: Fix freeze.py config directory (GH-23792)
Fix freeze.py tool to use the prope config and library directories.
2020-12-16 12:12:36 +01:00
Victor Stinner 99d28c5670
bpo-40364: asyncio uses os.waitstatus_to_exitcode() (GH-23798)
test_unix_events.py no longer checks if waitstatus_to_exitcode() mock
has been called or not to make the test more functional, rather than
checking the exact implementation.
2020-12-16 12:11:24 +01:00
Serhiy Storchaka 5f0fe8ec70
bpo-19733: Re-enable tests for -image option in Tkinter (GH-23785) 2020-12-16 12:31:49 +02:00
Victor Stinner 79782fe4f8
bpo-41804: Enhance test_epoll.test_control_and_wait() (GH-23795)
Use shorter timeout and replace send() with sendall().
2020-12-16 11:16:25 +01:00
Matthias Bussonnier b32d8b4f9b
bpo-42644: Validate values in logging.disable() (#23786)
* bpo-42644: Validate values in logging.disable()

Technically make the value of manager a property that checks and convert
values assigned to it properly. This has the side effect of making
`logging.disable` also accept strings representing the various level of
warnings.

We want to validate the type of the disable attribute at assignment
time, as it is later compared to other levels when emitting warnings and
would generate a `TypeError: '>=' not supported between ....` in a
different part of the code base, which can make it difficult to track
down.

When assigned an incorrect value; it will raise a TypeError when the
wrong type, or ValueError if an invalid str.

Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
2020-12-16 11:43:39 +02:00
Vladimir 3f9fe23c05
bpo-42179: Clarify exception chaining (GH-23160)
* Update errors.rst

Clarify exception chaining behaviour and give a reference to the library documentation.

* Update errors.rst

Wording

* Update errors.rst

Spelling

* Update errors.rst

Remove mentioning of special attributes as folks think it's too much for beginners.
2020-12-15 18:47:26 -08:00
Mariatta 801165e1a9
Update Stale action message (GH-23791)
We don't close PRs after it becomes stale.
2020-12-15 18:36:33 -08:00
Jason R. Coombs 928dbfc16c
bpo-42090: zipfile.Path.joinpath now accepts multiple arguments (GH-22976)
Automerge-Triggered-By: GH:jaraco
2020-12-15 18:12:54 -08:00
pxinwr b230409f21
bpo-31904: Skip os.path.expanduser() tests on VxWorks (GH-23776) 2020-12-15 22:24:00 +01:00
pxinwr 9a0dea6137
bpo-31904: Skip some tests of changing owner in _test_all_chown_common() on VxWorks (GH-23716) 2020-12-15 22:21:53 +01:00
pxinwr e1e3c2dac3
bpo-31904: Disable os.popen and popen test cases on VxWorks (GH-21687) 2020-12-15 22:20:07 +01:00
Mariatta 9cc8fa6ac8
Adding "stale" GitHub Action (GH-21247)
Adding "stale" GitHub Action

Added the "stale" GitHub action to the CPython repo.
PR's older than 30 days will be labeled as stale using the "stale-pr" label.

Closes https://github.com/python/core-workflow/issues/372

Co-authored-by: Brett Cannon <brett@python.org>
2020-12-15 11:58:43 -08:00
E-Paine b9ced83cf4
bpo-40219: Lowered ttk LabeledScale dummy (GH-21467) 2020-12-15 21:42:55 +02:00
Mariatta 0603f8087a
Let dependabot create PRs against the maintenance branches (GH-22992)
With this, we don't have to manually trigger backport whenever there is update to GitHub Actions dependencies.
2020-12-15 11:04:55 -08:00
Pablo Galindo 0911411e0c
Update stable ABI script for MacOS and update list of exported symbols (GH-23783) 2020-12-15 18:16:13 +00:00
Victor Stinner 7f14a3756b
bpo-42641: Enhance test_select.test_select() (GH-23782)
Enhance test_select.test_select(): it now takes 500 ms rather than 10
seconds.

* Use Python rather than a shell as the child process to make the
  test more portable.
* Use a sleep of 50 ms per line rather than 1 second.
* Use subprocess.Popen rather than os.popen().
2020-12-15 18:06:36 +01:00
Julien Palard c8a10d2fab
bpo-36675: Doc: Reveal doctest directives (GH-23620) 2020-12-15 17:23:03 +01:00
Victor Stinner 3ca2b8fd75
bpo-42639: atexit._run_exitfuncs() uses sys.unraisablehook (GH-23779)
atexit._run_exitfuncs() now logs callback exceptions using
sys.unraisablehook, rather than logging them directly into
sys.stderr and raising the last exception.

Run GeneralTest of test_atexit in a subprocess since it calls
atexit._clear() which clears all atexit callbacks.

_PyAtExit_Fini() sets state->callbacks to NULL.
2020-12-15 17:12:02 +01:00
Victor Stinner ceb420251c
bpo-32381: pymain_run_file() uses PySys_FormatStderr() (GH-23778)
If config->run_filename doesn't exist, log the error into sys.stderr
using "%R" format, to escape properly unencodable characters (usually
with backslashreplace).
2020-12-15 16:25:27 +01:00
Victor Stinner f7049b5fb6
bpo-42639: Add script_helper.run_test_script() (GH-23777)
* Add run_test_script() function to test.support.script_helper.
* Rename Lib/test/eintrdata/eintr_tester.py to
  Lib/test/_test_eintr.py.
* test_eintr.py uses run_test_script().
2020-12-15 16:08:16 +01:00
Petr Viktorin 6a02b38475
bpo-14935: Remove static state from the _csv module (GH-23224)
Uses code from: https://github.com/python/cpython/pull/16078

Co-authored-by: Marcel Plch <gmarcel.plch@gmail.com>
Co-authored-by: Eddie Elizondo <eduardo.elizondorueda@gmail.com>
Co-authored-by: Hai Shi <shihai1992@gmail.com>
2020-12-15 15:14:35 +01:00
Victor Stinner b8fa135908
bpo-42639: Move atexit state to PyInterpreterState (GH-23763)
* Add _PyAtExit_Call() function and remove pyexitfunc and
  pyexitmodule members of PyInterpreterState. The function
  logs atexit callback errors using _PyErr_WriteUnraisableMsg().
* Add _PyAtExit_Init() and _PyAtExit_Fini() functions.
* Remove traverse, clear and free functions of the atexit module.

Co-authored-by: Dong-hee Na <donghee.na@python.org>
2020-12-15 14:34:19 +01:00
Mark Shannon 8473cf89bd
bpo-42246: Remove DO_NOT_EMIT_BYTECODE macros, so that while loops and if statements conform to PEP 626. (GH-23743) 2020-12-15 11:07:50 +00:00
Terry Jan Reedy 6f79e60b66
bpo-33610: Edit idlelib.codecontext (GH-23773)
Add sentence to module docstring and import tkinter items.
2020-12-15 00:24:01 -05:00
pxinwr c117426bf8
bpo-31904: Enable libpython3.so shared library for VxWorks (GH-23741) 2020-12-14 23:14:43 +01:00
Victor Stinner 357704c9f2
bpo-42639: atexit now logs callbacks exceptions (GH-23771)
At Python exit, if a callback registered with atexit.register()
fails, its exception is now logged. Previously, only some exceptions
were logged, and the last exception was always silently ignored.

Add _PyAtExit_Call() function and remove
PyInterpreterState.atexit_func member. call_py_exitfuncs() now calls
directly _PyAtExit_Call().

The atexit module must now always be built as a built-in module.
2020-12-14 23:07:54 +01:00
Victor Stinner 83d52044ae
bpo-42639: Cleanup atexitmodule.c (GH-23770)
* Rename "atexitmodule_state" to "struct atexit_state".
* Rename "modstate" to "state".
* Rename "self" parameter to "module".
* test_atexit uses textwrap.dedent().
* Remove _Py_PyAtExit() function: inline it into atexit_exec().
* PyInterpreterState: rename pyexitfunc to atexit_func, rename
  pyexitmodule to atexit_module.
2020-12-14 22:40:40 +01:00
vabr-g fdb9efce6a
bpo-41877: Check for misspelled speccing arguments (GH-23737)
patch, patch.object and create_autospec silently ignore misspelled
arguments such as autospect, auto_spec and set_spec. This can lead
to tests failing to check what they are supposed to check.

This change adds a check causing a RuntimeError if the above
functions get any of the above misspellings as arguments. It also
adds a new argument, "unsafe", which can be set to True to disable
this check.

Also add "!r" to format specifiers in added error messages.
2020-12-14 10:30:09 -08:00
Gregory P. Smith 42c9f0fd0a
bpo-36541: Add lib2to3 grammar PEP-570 pos-only arg parsing (GH-23759)
Add positional only args support to lib2to3 pgen2.

This adds 3.8's PEP-570 support to lib2to3's pgen2.  lib2to3, while
being deprecated is still used by things to parse all versions of Python
code today.  We need it to support parsing modern 3.8 and 3.9 constructs.

Also add tests for complex *expr and **expr's.
2020-12-14 09:10:10 -08:00
Mark Shannon f5e97b72fe
bpo-42635: Mark JUMP_ABSOLUTE at end of 'for' loop as artificial to avoid spurious line events. (GH-23761) 2020-12-14 11:28:39 +00:00
Mark Shannon 56aa20f9eb
Don't generate spurious line number in try-except-finally. (#23760) 2020-12-14 10:19:10 +00:00
Joshua Root 674fa0a740
bpo-42598: Fix implicit function declarations in configure (GH-23690)
This is invalid in C99 and later and is an error with some compilers
(e.g. clang in Xcode 12), and can thus cause configure checks to
produce incorrect results.
2020-12-13 15:56:34 -05:00
kj 463c7d3d14
bpo-42195: Ensure consistency of Callable's __args__ in collections.abc and typing (GH-23060) 2020-12-13 10:38:24 -08:00
Pablo Galindo 43c4fb6c90
bpo-30858: Improve error location for expressions with assignments (GH-23753)
Co-authored-by: Lysandros Nikolaou <lisandrosnik@gmail.com>
2020-12-13 16:46:48 +00:00
sblondon da431f789b
Add two spaces around equal sign (#23719)
Fit to PEP8 coding style
2020-12-12 21:27:22 -08:00
Ethan Furman b5a6db9111
bpo-39717: [tarfile] update nested exception raising (GH-23739)
- `from None` if the new exception uses, or doesn't need, the previous one
- `from e` if the previous exception is still relevant
2020-12-12 13:26:44 -08:00
Nick Gaya 4b8cdfcb22
bpo-41879: Doc: Fix description of async for statement (GH-23548)
Fix the wording in the documentation of `async for` to correctly describe asynchronous iterables.  This fix is relevant for version 3.7 onward.
2020-12-11 00:27:35 -08:00
Alex Grönholm 67b769f515
bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736) 2020-12-10 13:49:05 -08:00
Ethan Furman a658287179
bpo-34750: [Enum] add `_EnumDict.update()` support (GH-23725)
This allows easier Enum construction in unusual cases, such as including dynamic member definitions into a class definition:

# created dynamically
foo_defines = {'FOO_CAT': 'aloof', 'BAR_DOG': 'friendly', 'FOO_HORSE': 'big'}

class Foo(Enum):
    vars().update({
            k: v
            for k, v in foo_defines.items()
            if k.startswith('FOO_')
            })
    def upper(self):
        # example method
        return self.value.upper()
2020-12-10 13:07:00 -08:00
Ethan Furman efb13be72c
bpo-42385: [Enum] add `_generate_next_value_` to StrEnum (GH-23735)
The default for auto() is to return an integer, which doesn't work for `StrEnum`.  The new `_generate_next_value_` for `StrEnum` returns the member name, lower cased.
2020-12-10 12:20:06 -08:00
vabr-g 9fc571359a
bpo-41877: Improve docs for assert misspellings check in mock (GH-23729)
This is a follow-up to
4662fa9bfe.
That original commit expanded guards against misspelling assertions on
mocks. This follow-up updates the documentation and improves the error
message by pointing out the potential cause and solution.

Automerge-Triggered-By: GH:gpshead
2020-12-10 10:35:28 -08:00
Victor Stinner b5c7b38f5e
bpo-42591: Export missing Py_FrozenMain() symbol (GH-23730)
Export the Py_FrozenMain() function: fix a Python 3.9.0 regression.
Python 3.9 uses -fvisibility=hidden and the function was not exported
explicitly and so not exported.

Add also Py_FrozenMain to the stable ABI on Windows.
2020-12-10 18:39:17 +01:00
Ethan Furman 7cf0aad96d
bpo-42517: [Enum] do not convert private names into members (GH-23722)
private names, such as `_Color__hue` and `_Color__hue_` are now normal attributes, and do not become members nor raise exceptions
2020-12-09 17:12:11 -08:00
Ethan Furman 6bd94de168
bpo-42567: [Enum] call __init_subclass__ after members are added (GH-23714)
When creating an Enum, type.__new__ calls __init_subclass__, but at that point the members have not been added.

This patch suppresses the initial call, then manually calls the ancestor __init_subclass__ before returning the new Enum class.
2020-12-09 16:41:22 -08:00
Andre Delfino 2a35137328
[doc] Link to issue regarding logging.disable level param default value (GH-23726) 2020-12-09 15:37:39 -08:00
Andre Delfino 35cacce525
[doc] Document logging.basicConfig default format (GH-23710)
Automerge-Triggered-By: GH:vsajip
2020-12-09 13:56:17 -08:00
pxinwr d5dcb65317
bpo-31904: Define THREAD_STACK_SIZE for VxWorks (GH-23718) 2020-12-09 22:47:28 +01:00
Victor Stinner a82f63f5af
bpo-32381: Add _PyRun_AnyFileObject() (GH-23723)
pymain_run_file() no longer encodes the filename: pass the filename
as an object to the new _PyRun_AnyFileObject() function.

Add new private functions:

* _PyRun_AnyFileObject()
* _PyRun_InteractiveLoopObject()
* _Py_FdIsInteractive()
2020-12-09 22:37:27 +01:00
Victor Stinner ca06440207
bpo-32381: Remove unused _Py_fopen() function (GH-23711)
Remove the private _Py_fopen() function which is no longer needed.
Use _Py_wfopen() or _Py_fopen_obj() instead.
2020-12-09 20:54:31 +01:00
Victor Stinner 550e4673be
bpo-32381: Add _PyRun_SimpleFileObject() (GH-23709)
pymain_run_startup() now pass the filename as a Python object to
_PyRun_SimpleFileObject().
2020-12-09 00:32:54 +01:00
pxinwr 98a5417193
bpo-41439: Skip test_ssl and test_uuid tests if fork() is not supported (GH-21684) 2020-12-09 00:20:19 +01:00
pxinwr eb7594f857
bpo-41443: Add more attribute checking in test_posix (GH-21688) 2020-12-09 00:18:37 +01:00
Victor Stinner fe6e5e7cfd
bpo-35134: Add Include/cpython/pythonrun.h file (GH-23701)
Py_CompileString() is now always declared as a function by
Include/pythonrun.h. It is overriden with a macro in
Include/cpython/pythonrun.h.
2020-12-08 23:51:54 +01:00
Victor Stinner 815506d852
bpo-32381: Rewrite PyErr_ProgramText() (GH-23700)
PyErr_ProgramText() now calls PyErr_ProgramTextObject().
2020-12-08 23:51:26 +01:00
Ethan Furman 6d3dfee271
[Enum] reformat and add doc strings (GH-23705) 2020-12-08 12:26:56 -08:00
Ethan Furman 37440eef7f
bpo-41907: [Enum] fix format() behavior for IntFlag (GH-22497) 2020-12-08 11:14:10 -08:00
Petr Viktorin c168b5078f
bpo-42111: Make the xxlimited module an example of best extension module practices (GH-23226)
- Copy existing xxlimited to xxlimited53 (named for the limited API version it uses)
- Build both modules, both in debug and release
- Test both modules
2020-12-08 08:36:53 -08:00
Terry Jan Reedy 4aa67853cc
bpo-41910: move news entry (GH-23695) 2020-12-08 10:29:49 -05:00
Hai Shi 0f91f586ae
bpo-42599: Remove useless PyModule_GetWarningsModule() (GH-23691)
Removed PyModule_GetWarningsModule() which is useless due to 
the _warnings module was converted to a builtin module in 2.6.
2020-12-08 15:42:42 +01:00
Victor Stinner b6d98c10ff
bpo-32381: Fix PyRun_SimpleFileExFlags() encoding (GH-23642)
Fix encoding name when running a ".pyc" file on Windows:
PyRun_SimpleFileExFlags() now uses the correct encoding to decode the
filename.

* Add pyrun_file() subfunction.
* Add pyrun_simple_file() subfunction.
* PyRun_SimpleFileExFlags() now calls _Py_fopen_obj() rather than
  _Py_fopen().
2020-12-08 14:38:08 +01:00
Pablo Galindo 233fddfe39
Post 3.10.0a3 2020-12-08 02:31:04 +00:00
Pablo Galindo 0914a48776 Python 3.10.0a3
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl/Og7MACgkQ/+h0BBaL
 2EcD1g/+PNszWfcR3hosGrNMXjMfiwDWEC3h994icYm/ozz5S8grP+4nktolVd04
 ub9uebxJL11BkRFpZgpWFtHKGRL6EmKj/LeFPBdFa3liAW4aCu3DuvCxzw3E6PPX
 KCxU368mC3by878zTZs0Blud0jbowb850grRaDd5/vfsWF87rAVtf2KoLkIMSXa+
 mSB6XqV0GWD05g1oIuiebZ2jO4ljLigH6ijqysjOd2Ehyky42+HSw59PpHgU5OPI
 IVtSkekziVufOnRY3ab873KtsI3sXeLOtdvIcdd0QqvoFtFFVQP44A6uYdkuPCOH
 R1hbW9SKY0GOo8HrMAiNFz7JjCcT3uND2Ls5dS6Z3HJgSkugGh9R19ooKShoZ0vj
 P0gqJkKKeiHemxGBC1c68MnvKHXzj02JrxUyq24S0xyFcIQHxd8wUQw6jkgj+RW3
 tYMJ7XEp2DoM+4zatJVs9lAmgcEKCE+dQfLEoFqqbvJLcT0n9jcqmMTbecWCZa/H
 RPawAvheoESutu5urzBvhsapIWadwb79KKs7GdAFid05OxodxmVWl7i7QfPTBg9m
 2mV94CFcMrovs2UpWbQ2N9QfGneuJ7DixUcZuOoB3tBy/Q0mDPgBwM9EiMPYYNpd
 +YyN5ObV9V5RO2QOkpKyIXjR5QeSBVUVt9TZn9Ly9jEQWOYRl9w=
 =LzsP
 -----END PGP SIGNATURE-----
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl/O5UQACgkQ/+h0BBaL
 2EclRw//XrllDMqAx0ikjtJQ7X4ZkO2b10+LW1b0z/KLOyWzlmJc5ceGzOxxHAAR
 RQw/djT0nRpgs3/almKI4t5CVUBvvOFnS6lqp5KyaZM6JJ4kuNBMbb+8QLknZkyS
 CcpNo5T4jO9hrbv9JlwTFiD6xbaYgURiGtz46nMf4mT4JxTTAY+4jIKV/qj9g+xh
 S3YKBcw90tbKydBZT7D2wDUpR6+roNr4s2ZpbjX47IqT8CP+HaTLu+mlVD35EzWk
 o8I9k2ONgaj72WNxnZ+N484L+u9MVNS+7urBR8tpNQL99AH+MaamWMx984TnEcIO
 AMB7pez3cejadjU/W3PcCziajop9j1vZBsNp3hBh6xWYR8Ut1uT+mO89p75QZu9U
 qzIBmpwch3I8jHmPDvRty2kO87v76wKo8+h5J8U+okOTQi2+1m/zaRZGGDUTe40e
 nk3+JMcxricvHGEHYm5XpNY5NPiAqxPGzTec9eqkdlUrEJrs3Cfwbcz5jHQnvY2T
 AiXWerz9UKxNUW/ljNw6s+S+dAKK11RLcN+jaz/fwwQksW6OJDUI6e+MkwcChq3l
 5XkOaXUnjAX0qakEdnaGSvHqv9VkRLEFXyAgZ90q6qybKkTvLiLgodJpwAq4TTjR
 cYpRpmfTbVh2BOLf9mUsgO9KpiQ5hbpvX38TKPDhOiBx6+qTpxw=
 =30Oc
 -----END PGP SIGNATURE-----

Merge tag 'v3.10.0a3'

Python 3.10.0a3
2020-12-08 02:30:25 +00:00
pxinwr 06afac6c57
bpo-41462: Add os.set_blocking() support for VxWorks RTOS (GH-21713) 2020-12-07 21:41:12 +01:00
Matěj Cepl b63a620014
bpo-42579: Make workaround for various versions of Sphinx more robust (GH-23662)
The solution in gh#python/cpython#13236 is too strict because it
effectively requires the use of Sphinx >= 2.0. It is not too difficult to
make the same solution more robust so it works with all normal versions
of Sphinx.
2020-12-07 20:05:13 +00:00
Pablo Galindo 8bae2a958e
Python 3.10.0a3 2020-12-07 19:34:10 +00:00
Matti Picus c0afb7fa0e
bpo-39825: Fixes sysconfig.get_config_var('EXT_SUFFIX') on Windows to match distutils (GH-22088) 2020-12-07 17:33:20 +00:00
Victor Stinner 0ef96c2b2a
bpo-30459: Cast the result of PyCell_SET to void (GH-23654) 2020-12-07 11:56:20 +01:00
Ethan Furman c266736ec1
bpo-41889: [Enum] fix multiple-inheritance regression (GH-22487) 2020-12-07 00:17:31 -08:00
Ned Deily 212337369a
Update macos installer ReadMe for 3.10.0a3 (GH-23671) 2020-12-06 22:55:12 -05:00
Terry Jan Reedy 57e5113610
bpo-42508: Keep IDLE running on macOS (GH-23577)
Remove obsolete workaround that prevented running files with
shortcuts when using new universal2 installers built on macOS 11.
Ignore buggy 2nd run_module_event call.
2020-12-06 22:22:33 -05:00
Raymond Hettinger 752cdf21eb
bpo-38843: Document behavior of default when the attribute is already set (GH-23653) 2020-12-06 18:29:08 -08:00
Serhiy Storchaka 8a62887dfb
bpo-42582: Remove asyncio._all_tasks_compat(). (GH-23664)
It was used to implement now removed asyncio.Task.all_tasks().
2020-12-06 18:54:33 +02:00
kj 6a7fb9d31b
bpo-42576: Clarify only debug builds are affected in news (GH-23663) 2020-12-06 08:37:59 -08:00
idanw206 c598a04dd2
bpo-42532: Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function (GH23613)
Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function
2020-12-06 09:59:36 +00:00
kj 804d6893b8
bpo-42576: Raise TypeError when passing in keyword arguments to GenericAlias (GH-23656)
Use `_PyArg_NoKeywords` instead of `_PyArg_NoKwnames` when checking the `kwds` tuple when creating `GenericAlias`. This fixes an interpreter crash when passing in keyword arguments to `GenericAlias`'s constructor.

Needs backport to 3.9.

Automerge-Triggered-By: GH:gvanrossum
2020-12-05 08:02:14 -08:00
Senthil Kumaran da3d2abe6b
GH-5054: CGIHTTPRequestHandler.run_cgi() HTTP_ACCEPT improperly parsed (#23638) 2020-12-05 05:26:24 -08:00
Zackery Spytz 556d97f473
bpo-30459: Cast the result of PyList_SET_ITEM() to void (GH-19975)
Do the same for PyTuple_SET_ITEM().
2020-12-05 11:34:51 +01:00
Ned Deily 29afab6c5f
bpo-41116: Fix setup.py test for macOS Tcl/Tk frameworks (GH-23649)
If no explicit macOS SDK was specified, setup.py should check for
Tcl and TK frameworks in /Library/Frameworks; the previous commit
inadvertently broke that test.
2020-12-04 23:02:09 -05:00
Brandt Bucher 226a012d1c
bpo-42536: GC track recycled tuples (GH-23623)
Several built-in and standard library types now ensure that their internal result tuples are always tracked by the garbage collector:

- collections.OrderedDict.items
- dict.items
- enumerate
- functools.reduce
- itertools.combinations
- itertools.combinations_with_replacement
- itertools.permutations
- itertools.product
- itertools.zip_longest
- zip

Previously, they could have become untracked by a prior garbage collection.
2020-12-04 19:45:57 -08:00
Brett Cannon 2de5097ba4
bpo-26131: Deprecate usage of load_module() (GH-23469)
Raise an ImportWarning when the import system falls back on load_module(). As for implementations of load_module(), raise a DeprecationWarning.
2020-12-04 15:39:21 -08:00
Pablo Galindo 79c1849b9e
bpo-42545: Improve the error message in the stable API script (GH-23648) 2020-12-04 23:19:21 +00:00
Pablo Galindo 85f1dedb8d
bpo-42545: Check that all symbols in the limited ABI are exported (GH-23616) 2020-12-04 22:05:58 +00:00
Irit Katriel 2e0760bb2e
bpo-17735: inspect.findsource now raises OSError when co_lineno is out of range (GH-23633)
This can happen when a file was edited after it was imported.
2020-12-04 23:22:03 +02:00
pxinwr 8d4f57dbd1
bpo-31904: fix test_doctest.py failures for VxWorks (GH-23419)
Fix test_doctest.py failures for VxWorks by avoiding exact error message checks. (better for everyone all around)
2020-12-04 12:19:32 -08:00
Irit Katriel 6e1eec71f5
bpo-42116: Fix inspect.getsource handling of trailing comments (GH-23630) 2020-12-04 18:45:38 +02:00
Victor Stinner 066394018a
bpo-41473: Reenable test_gdb on gdb 9.2 and newer (GH-23637)
https://bugzilla.redhat.com/show_bug.cgi?id=1866884 is fixed in gdb
10.1 (failed to reproduce on gdb-10.1-1.fc34.aarch64).
2020-12-04 16:23:56 +01:00
Mark Shannon eaccc12aa9
bpo-42246: Don't forget the entry block when ensuring that all exits have a line number (GH-23636)
Don't forget the entry block when ensuring that all exits have a line number.
2020-12-04 15:22:12 +00:00
Yurii Karabas f24b8101a0
bpo-42562: Fix issue when dis failed to parse function that has no line numbers (GH-23632)
Fix issue when dis failed to parse function that has only annotations
2020-12-04 15:20:53 +00:00
Zackery Spytz db68544122
bpo-42523: Fix supported versions in "Using Python on Windows" (GH-23603) 2020-12-03 17:22:04 +00:00
Victor Stinner 8b6c4a921a
bpo-42262: Py_NewRef() casts its argument to PyObject* (GH-23626)
Write also unit tests on Py_NewRef() and Py_XNewRef().
2020-12-03 14:01:10 +01:00
Victor Stinner 7e5e13d113
bpo-42553: Fix test_asyncio.test_call_later() (GH-23627)
Fix test_asyncio.test_call_later() race condition: don't measure
asyncio performance in the call_later() unit test. The test failed
randomly on the CI.
2020-12-03 13:56:41 +01:00
Serhiy Storchaka 2ad93821a6
bpo-42431: Fix outdated bytes comments (GH-23458)
Also move definitions of internal macros F_LJUST etc to private header.
2020-12-03 12:46:16 +02:00
Serhiy Storchaka f3c3ea91a7
bpo-42328: Skip some tests with themes vista and xpnative on Windows 7 (GH-23612) 2020-12-03 10:48:26 +02:00
Senthil Kumaran 3ec9d01901
Remove the conditional for setting query. (#23604) 2020-12-02 19:48:14 -08:00
FX Coudert 5291639e61
bpo-42504: fix for MACOSX_DEPLOYMENT_TARGET=11 (GH-23556)
macOS releases numbering has changed as of macOS 11 Big Sur.  Previously, major releases were of the form 10.x, 10.x+1, 10.x+2, etc; as of Big Sur, they are now x, x+1, etc, so, for example, 10.15, 10.15.1, ..., 10.15.7, 11, 11.0.1, 11.1, ..., 12, 12.1, etc. Allow Python to build with single-digit deployment target values. Patch provided by FX Coudert.
2020-12-02 22:20:18 -05:00
Pablo Galindo dedc2cd5f0
bpo-41625: Do not add os.splice on AIX due to compatibility issues (GH-23608) 2020-12-02 17:57:18 +00:00
Pablo Galindo 99b594404d
bpo-42521: Add note about 'Python -d' only working on debug builds (GH-23607) 2020-12-02 17:56:17 +00:00
Mark Shannon 5977a7989d
bpo-42246: Make sure that line number is correct after a return, as required by PEP 626 (GH-23495)
Make sure that line number is correct after a return, as defined by PEP 626.
2020-12-02 13:31:40 +00:00
Mark Shannon 4e7a69bdb6
bpo-42500: Fix recursion in or after except (GH-23568)
* Use counter, rather boolean state when handling soft overflows.
2020-12-02 13:30:55 +00:00
Pablo Galindo 93a0ef7647
Correct return type in Modules/_ssl.c::sslmodule_legacy (GH-23609) 2020-12-02 06:07:56 +00:00
Pablo Galindo 46bd5ed94c
bpo-40939: Restore some stable API functions incorrectly deleted (GH-23606) 2020-12-02 05:16:31 +00:00
pxinwr e483d281bd
bpo-31904: Fix test_netrc for VxWorks RTOS (GH-21675)
Fix test_netrc on VxWorks: create temporary directories using temp_cwd().
2020-12-01 21:34:42 +01:00
Victor Stinner 1867b462de
bpo-37221: PyCode_New() didn't change in Python 3.8 (GH-23595) 2020-12-01 16:22:25 +01:00
dependabot[bot] 8acd0e0d49
build(deps): bump actions/upload-artifact from v2.2.0 to v2.2.1 (GH-23583)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from v2.2.0 to v2.2.1.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v2.2.0...726a6dcd0199f578459862705eed35cda05af50b)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-12-01 09:00:11 -06:00
dependabot[bot] a43fea8857
build(deps): bump actions/cache from v2.1.2 to v2.1.3 (23582)
Bumps [actions/cache](https://github.com/actions/cache) from v2.1.2 to v2.1.3.
- [Release notes](https://github.com/actions/cache/releases)
- [Commits](https://github.com/actions/cache/compare/v2.1.2...0781355a23dac32fd3bac414512f4b903437991a)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-12-01 08:59:12 -06:00
Andre Delfino bc662c0bd7
[doc] Fix abc.update_abstractmethods markup (GH-23576)
Add link to ABCMeta while at it.
2020-12-01 01:45:11 -08:00
Andre Delfino 80a429eae9
Fix bz2 examples markup (#23580) 2020-12-01 10:41:12 +01:00
Victor Stinner 32bd68c839
bpo-42519: Replace PyObject_MALLOC() with PyObject_Malloc() (GH-23587)
No longer use deprecated aliases to functions:

* Replace PyObject_MALLOC() with PyObject_Malloc()
* Replace PyObject_REALLOC() with PyObject_Realloc()
* Replace PyObject_FREE() with PyObject_Free()
* Replace PyObject_Del() with PyObject_Free()
* Replace PyObject_DEL() with PyObject_Free()
2020-12-01 10:37:39 +01:00
Victor Stinner 00d7abd7ef
bpo-42519: Replace PyMem_MALLOC() with PyMem_Malloc() (GH-23586)
No longer use deprecated aliases to functions:

* Replace PyMem_MALLOC() with PyMem_Malloc()
* Replace PyMem_REALLOC() with PyMem_Realloc()
* Replace PyMem_FREE() with PyMem_Free()
* Replace PyMem_Del() with PyMem_Free()
* Replace PyMem_DEL() with PyMem_Free()

Modify also the PyMem_DEL() macro to use directly PyMem_Free().
2020-12-01 09:56:42 +01:00
pxinwr b2d0c66e88
bpo-31904: Fix fifo test cases for VxWorks (GH-20254) 2020-12-01 09:20:50 +01:00
Raymond Hettinger cc061d0e6f
bpo-38200: Add itertools.pairwise() (GH-23549) 2020-11-30 20:42:54 -08:00
Irit Katriel 427613f005
bpo-42482: remove reference to exc_traceback from TracebackException (GH-23531) 2020-11-30 17:35:25 -08:00
pxinwr 1244c816d7
bpo-31904: Support signal module on VxWorks (GH-23391) 2020-11-30 22:48:33 +01:00
Christian Heimes 5c73afc36e
bpo-28468: Add platform.freedesktop_os_release() (GH-23492)
Add platform.freedesktop_os_release() function to parse freedesktop.org
os-release files.

Signed-off-by: Christian Heimes <christian@python.org>
Co-authored-by: Victor Stinner <vstinner@python.org>
2020-11-30 22:34:45 +01:00
Pablo Galindo 9bdc40ee3e
Refactor the grammar to match the language specification docs (GH-23574) 2020-11-30 19:42:38 +00:00
James Gerity bcc9579227
bpo-42485: [Doc] Link to PEP 617 from full grammar specification (GH-23532)
Co-authored-by: Lysandros Nikolaou <lisandrosnik@gmail.com>
2020-11-30 19:08:26 +00:00
Raymond Hettinger 7f82f22eba
bpo-42501: Revise the usage note for Enums with the choices (GH-23563) 2020-11-30 09:55:13 -08:00
Terry Jan Reedy e41bfd15dd
bpo-42508: Remove bogus idlelib.pyshell.ModifiedInterpreter attribute (GH-23570)
restart_subprocess is a method of self, the pyshell.InteractiveInterpreter instance. The latter does not have an interp attribute redundantly referring to itself. (The PyShell instance does have an interp attribute, referring to the InteractiveInterpreter instance.)
2020-11-30 12:09:43 -05:00
Andreas Poehlmann 0be9ce305f
bpo-42487: don't call __getitem__ of underlying maps in ChainMap.__iter__ (GH-23534) 2020-11-30 08:34:15 -08:00
Yasser A 9f004634a2
bpo-42451: Indicate that PyTuple_GetItem does not support negative indices (GH-23529) 2020-11-30 10:53:11 +01:00
Zackery Spytz 9654592478
bpo-42506: Fix unexpected output in test_format (GH-23564) 2020-11-30 17:39:12 +09:00
Serhiy Storchaka 6cc2c419f6
bpo-42142: Try to fix timeouts in ttk tests (GH-23474)
Instead of using wait_visibility() which waits event <VisibilityNotify> in dead loop
use update() which should proceed all queued events.
2020-11-30 10:24:07 +02:00
Raymond Hettinger fc40b3020c
bpo-42450: Minor updates to the itertools recipes (GH-23555) 2020-11-29 10:47:22 -08:00
Renato Cunha 86684319d3
bpo-42406: Fix whichmodule() with multiprocessing (GH-23403)
* bpo-42406: Fix whichmodule() with multiprocessing

Signed-off-by: Renato L. de F. Cunha <renatoc@br.ibm.com>
Co-authored-by: Gregory P. Smith <greg@krypto.org>
2020-11-29 10:23:15 -08:00
Yurii Karabas 86150d39c8
bpo-42392: Remove deprecated loop parameter from docs (GH-23552) 2020-11-29 14:50:57 +02:00
Mark Dickinson c642374b3e
bpo-39096: Improve description of 'e', 'f' and 'g' presentation types (#23537)
* Improve description of 'e', 'f' and 'g' presentation types

* Drop the 'E' from Scientific 'E' notation; remove >= 0 qualifications

* Fix false statement that the alternate form is valid for Decimal

* Nitpick: remove the Harvard/Oxford comma

* Add note that the decimal point is also removed if no digits follow it, except in alternate form
2020-11-29 09:34:36 +00:00
pxinwr 00a6568ba3
bpo-31904: remove libnet dependency from detect_socket() for VxWorks (GH-23394)
Previously on VxWorks compiling socket extension module needs the libnet to link. Now VxWorks has moved the replied functions to libc. So removing libnet from setup.py.
2020-11-28 14:14:16 -08:00
pxinwr 6a273fdc2a
bpo-31904: skip some tests related to fifo on VxWorks (GH-23473)
On VxWork RTOS, FIFO must be created under directory "/fifos/". Some test cases related to fifo is invalid on VxWorks. So skip them.
2020-11-28 14:06:36 -08:00
pxinwr a86a274b72
bpo-31904: add shell requirement for test_pipes (GH-23489)
VxWorks has no user space shell provided so it can't support pipes module. Also add shell requirement for running test_pipes.
2020-11-28 14:04:50 -08:00
pxinwr 996a1ef8ae
skip test_test of test_mailcap on VxWorks (GH-23507) 2020-11-28 13:49:47 -08:00
pxinwr 64c8f81047
skip test_getaddrinfo_ipv6_scopeid_symbolic and test_getnameinfo_ipv6_scopeid_symbolic on VxWorks (GH-23518) 2020-11-28 13:48:38 -08:00
Zackery Spytz 7a240aef15
Fix an error in the news entry for _posixsubprocess multiphase init (GH-23516)
Commit 035deee265 converted the
_posixsubprocess module to multiphase initialization, but the news entry
mentions the _posixshmem module.
2020-11-28 13:46:30 -08:00
Andre Delfino fa840cc81d
Fix dis markup (GH-23524) 2020-11-28 13:43:22 -08:00
Andre Delfino 4b44472966
Fix multiprocessing markup (GH-23525) 2020-11-28 13:42:23 -08:00
Soumendra Ganguly 74311aeb45
bpo-41818: Fix test_master_read() so that it succeeds on all platforms that either raise OSError or return b"" upon reading from master (GH-23536)
Signed-off-by: Soumendra Ganguly <soumendraganguly@gmail.com>
2020-11-28 23:04:20 +02:00
pxinwr aa1b8a168d
bpo-31904: Fix test_os.test_getcwd_long_path() failure for VxWorks (GH-20256) 2020-11-28 21:21:30 +01:00
Zackery Spytz d41ec65ab7
bpo-42489: Fix the signature for list.sort() in the tutorial (GH-23538) 2020-11-28 16:53:39 +02:00
Zackery Spytz 8085f742f4
bpo-34215: Clarify IncompleteReadError message when "expected" is None (GH-21925)
Co-Authored-By: Tyler Bell <mrbell321@gmail.com>
2020-11-28 16:27:28 +02:00
Wansoo Kim 5b0194ed31
bpo-41241: Unnecessary Type casting in 'if condition' (GH-21396)
This is my first issue!
So, if there's anything wrong, please tell me!

Also, thank you always for all the contributors!

Automerge-Triggered-By: GH:asvetlov
2020-11-28 03:37:08 -08:00
Yurii Karabas e4fe303b8c
bpo-42392: Remove loop parameter from asyncio.tasks and asyncio.subprocess (GH-23521) 2020-11-28 10:21:17 +02:00
Julien Jerphanion f9195318a8
bpo-42452: Improve colorsys.rgb_to_hls code (GH-23306)
Cache repeated sum and difference to make code slightly faster and easier to read.
2020-11-28 02:11:19 -05:00
Irit Katriel 44ca05afc8
bpo-42474: test TracebackException comparison to non-equal instances (GH-23522)
Closes bpo-42474
2020-11-27 08:38:54 -08:00
Soumendra Ganguly f5a19ead4b
bpo-41818: Make test_openpty() avoid unexpected success due to number of rows and/or number of columns being == 0. (GH-23526) 2020-11-27 12:16:41 +02:00
Volker-Weissmann c8aaf71dde
bpo-17852: Doc: Fix the tutorial about closing files (GH-23135)
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2020-11-27 09:41:32 +09:00
Shane Harvey a1652da2c8
Document optional 'task'/'asyncgen' fields in call_exception_handler (#21735) 2020-11-26 15:24:48 +02:00
Alex Grönholm e3ef4d7f65
bpo-41332: Added missing connect_accepted_socket() to AbstractEventLoop (GH-21533)
Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
Co-authored-by: Kyle Stanley <aeros167@gmail.com>
2020-11-26 12:09:12 +02:00
Yurii Karabas f533cb80cb
bpo-42392: Remove loop parameter from asyncio.streams (GH-23517) 2020-11-26 09:36:37 +02:00
Andrew Svetlov 87f7ab5359
bpo-41818: test_openpty succeed on Gentoo, don't expect to fail on this platform (GH-23514) 2020-11-25 19:06:12 +02:00
basak 9d09e1719c
Typo: fix inverted sense of statement (GH-23288)
Looks like a "not" was inadvertently omitted in commit e6a7ea4.
Classmethods are useful when data stored in specific instances are *not*
needed.

Automerge-Triggered-By: GH:JulienPalard
2020-11-25 06:12:17 -08:00
Soumendra Ganguly c13d89955d
bpo-41818: Updated tests for the standard pty library (GH-22962) 2020-11-25 15:41:25 +02:00
Dong-hee Na be319c0c10
bpo-42299: Remove formatter module (GH-23476) 2020-11-25 22:17:30 +09:00
Yurii Karabas b9127dd6ee
bpo-42392: Improve removal of *loop* parameter in asyncio primitives (GH-23499)
* Update code after merge review from 1st1

* Use a sentinel approach for loop parameter
Remove unnecessary _get_running_loop patching

* Use more clear function name (_verify_parameter_is_marker -> _verify_no_loop)

* Add init method to _LoopBoundMixin to check that loop param wasn't used
2020-11-25 06:50:44 -05:00
Yurii Karabas 7301979b23
bpo-42202: Store func annotations as a tuple (GH-23316)
Reduce memory footprint and improve performance of loading modules having many func annotations.

  >>> sys.getsizeof({"a":"int","b":"int","return":"int"})
  232
  >>> sys.getsizeof(("a","int","b","int","return","int"))
  88

The tuple is converted into dict on the fly when `func.__annotations__` is accessed first.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2020-11-25 19:43:18 +09:00
Raymond Hettinger 85c84920f5
Add more tests to the descriptor howto guide (GH-23506) 2020-11-25 01:54:24 -08:00
Julien Palard 4fedd7123e
bpo-12800: tarfile: Restore fix from 011525ee9 (GH-21409)
Restore fix from 011525ee92.
2020-11-25 10:23:17 +01:00
Julien Palard c9c6e9f89a
bpo-42238: Doc: Remove make suspicious from the CI and docs builds. (GH-23313)
It probably helped a lot a while back, but may not be as usefull
today.  We'll continue monitoring it before deletion, so true
positives can be migrated to rstlint.
2020-11-25 10:18:00 +01:00
kj 8d17d2bd0a
Doc: Minor fixes (GH-23422) 2020-11-25 13:59:59 +09:00
Raymond Hettinger 2d44a6bc4f
Add doctests to the descriptor HowTo (GH-23500) 2020-11-24 20:57:02 -08:00
Hai Shi ed1a5a5bac
bpo-40170: Hide impl detail of Py_TRASHCAN_BEGIN macro (GH-23235)
The Py_TRASHCAN_BEGIN macro no longer accesses PyTypeObject attributes,
but now can get the condition by calling the new private
_PyTrash_cond() function which hides implementation details.
2020-11-24 23:03:31 +01:00
Yurii Karabas 0ec34cab9d
bpo-42392: Remove loop parameter form asyncio locks and Queue (#23420)
Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
2020-11-24 20:08:54 +02:00
Serhiy Storchaka b0b428510c
bpo-42370: Check element before making mouse click in ttk tests (GH-23491) 2020-11-24 19:35:39 +02:00
Victor Stinner ac7d0169d2
bpo-42212: smelly.py also checks the dynamic library (GH-23423)
The smelly.py script now also checks the Python dynamic library and
extension modules, not only the Python static library. Make also the
script more verbose: explain what it does.

The GitHub Action job now builds Python with the libpython dynamic
library.
2020-11-24 13:38:08 +01:00
Serhiy Storchaka 14d81dcaf8
bpo-42260: Improve error handling in _PyConfig_FromDict (GH-23488) 2020-11-24 14:07:32 +02:00
Ned Deily c0c23ea72b
bpo-41100: in test_platform, ignore 10.16 (GH-23485) 2020-11-24 01:20:35 -05:00
Ned Deily 936533ca04
bpo-41100: minor build installer fixes (GH-23480) 2020-11-23 19:04:40 -05:00
Jesús Cea 989af25616
Typo (#23482) 2020-11-24 00:56:30 +01:00
Yaroslav Pankovych 79d2e62c00
Added support for negative indexes to PurePath.parents (GH-21799)
This commit also fixes up some of the overlapping documentation changed
in bpo-35498, which added support for indexing with slices.

Fixes bpo-21041.
https://bugs.python.org/issue21041

Co-authored-by: Paul Ganssle <p.ganssle@gmail.com>
Co-authored-by: Rémi Lapeyre <remi.lapeyre@henki.fr>
2020-11-23 15:06:22 -05:00
Raymond Hettinger ffae93248a
Descriptor HowTo: Improve the fidelity of the member object simulation (GH-23475) 2020-11-23 10:56:59 -08:00
Nick Crews 2f2f9d0b5c
bpo-15450: Allow subclassing of dircmp (GH-23424) (#23424)
Co-authored-by: Chris Jerdonek <chris.jerdonek@gmail.com>
2020-11-23 18:29:37 +02:00
Irit Katriel ff420f0e08
bpo-28850: Fix PrettyPrinter.format overrides ignored for contents of small containers (GH-22120) 2020-11-23 15:31:31 +02:00
Serhiy Storchaka dd844a2916
bpo-42328: Fix tkinter.ttk.Style.map(). (GH-23300)
The function accepts now the representation of the default state as
empty sequence (as returned by Style.map()).
The structure of the result is now the same on all platform
and does not depend on the value of wantobjects.
2020-11-22 22:48:52 +02:00
Serhiy Storchaka 313467efdc
bpo-42435: Speed up comparison of bytes and bytearray object (GH--23461)
* Speed up comparison of bytes objects with non-bytes objects when
  option -b is specified.
* Speed up comparison of bytarray objects with non-buffer object.
2020-11-22 22:00:53 +02:00
John Belmonte 5ef53a88f3
Doc: fix typo in typing.Type docs (GH-23460) 2020-11-22 23:54:19 +09:00
Serhiy Storchaka 686c203cd4
bpo-42423: Accept single base class in PyType_FromModuleAndSpec() (GH-23441) 2020-11-22 13:25:02 +02:00
Serhiy Storchaka c4d45ee670
bpo-42427: Use the errno attribute of OSError instead of args[0] (GH-23449) 2020-11-22 10:28:34 +02:00
Ram Rachum bd8c22e1fa
bpo-42391: Clarify documentation of TestCase.assertIs (GH-23348)
Removing 'evaluate' makes it more consistent with other assertX entries.
2020-11-22 00:59:48 -05:00
Ronald Oussoren 404a719b51
bpo-41116: Ensure system supplied libraries are found on macOS 11 (GH-23301)
On macOS system provided libraries are in a shared library cache
and not at their usual location. This PR teaches distutils to search
in the SDK, even if there was no "-sysroot" argument in
the compiler flags.
2020-11-22 00:14:25 -05:00
Serhiy Storchaka 453bc1da20
bpo-42426: IDLE: Fix reporting offset of the RE error in searchengine (GH-23447) 2020-11-22 00:06:51 -05:00
Ronald Oussoren 442746af64
bpo-41100: Stripping '-arch arm64' didn't work after all (GH-23280) 2020-11-21 21:17:18 -05:00
Ronald Oussoren 690a5fa3dd
bpo-42361: Use Tcl/Tk 8.6.10 when building the installer on recent macOS (GH-23293)
Building on older versions, and in particular macOS 10.9 still use
Tk 8.6.8 because of build problems on that version of macOS.
2020-11-21 18:05:34 -08:00
Ronald Oussoren 0f20bd9042
bpo-38443: Check that the specified universal architectures work (GH-22910)
As [bpo-38443]() says the error message from configure when specifying --enable-universalsdk with a set of architectures that is not supported by the compiler is not very helpful.   This PR explicitly checks if the compiler works and bails out if it doesn't.
2020-11-21 17:13:11 -08:00
Richard Levasseur 68f68fa423
Clarify that Set._from_iterable is not required to be a classmethod. (GH-23272) 2020-11-21 11:56:24 -08:00
Christian Heimes ea97ebab35
bpo-1635741: Port select module to multiphase init (GH-23409) 2020-11-21 20:29:26 +01:00
Christian Heimes 035deee265
bpo-1635741: Port _posixsubprocess module to multiphase init (GH-23406) 2020-11-21 20:28:14 +01:00
Serhiy Storchaka ed1007c0d7
bpo-42425: Fix possible leak in initialization of errmap for OSError (GH-23446) 2020-11-21 19:17:46 +02:00
David CARLIER 0e62efc51e
bpo-42232: mmap module add Darwin specific madvise options. (GH-23076) 2020-11-21 03:39:56 -08:00
Serhiy Storchaka 1db76394ea
bpo-42412: Fix possible leaks and check arguments in PyType_FromModuleAndSpec() (GH-23410)
* There were leaks if Py_tp_bases is used more than once or if some call is
  failed before setting tp_bases.
* There was a crash if the bases argument or the Py_tp_bases slot is not a tuple.
* The documentation was not accurate.
2020-11-21 12:02:53 +02:00
Filipe Laíns 01a202ab6b
bpo-40550: Fix time-of-check/time-of-action issue in subprocess.Popen.send_signal. (GH-20010)
send_signal() now swallows the exception if the process it thought was still alive winds up not to exist anymore (always a plausible race condition despite the checks).

Co-authored-by: Gregory P. Smith <greg@krypto.org>
2020-11-21 01:22:08 -08:00
Devin Jeanpierre 31729366e2
bpo-40791: Make compare_digest more constant-time. (GH-20444)
* bpo-40791: Make compare_digest more constant-time.

The existing volatile `left`/`right` pointers guarantee that the reads will all occur, but does not guarantee that they will be _used_. So a compiler can still short-circuit the loop, saving e.g. the overhead of doing the xors and especially the overhead of the data dependency between `result` and the reads. That would change performance depending on where the first unequal byte occurs. This change removes that optimization.

(This is change #1 from https://bugs.python.org/issue40791 .)
2020-11-21 00:55:23 -08:00
Quentin Hibon aa3a3521ce
bpo-42419: Correct 'deprecatations' is What's New 3.9 (GH-23421) 2020-11-20 23:07:22 -05:00
ArioA 6edf06b24a
bpo-42407: Use possessive appostrophe in multiprocessing doc (GH-23400) 2020-11-20 21:37:54 -05:00
Eric Snow 9f02b479e6
bpo-36876: [c-analyzer tool] Tighten up the results and output. (GH-23431)
We also update the "ignored" file with a temporary list of all known globals.
2020-11-20 15:39:28 -07:00
Shantanu a993e901eb
bpo-28002: Roundtrip f-strings with ast.unparse better (#19612)
By attempting to avoid backslashes in f-string expressions.
We also now proactively raise errors for some backslashes we can't
avoid while unparsing FormattedValues

Co-authored-by: hauntsaninja <>
Co-authored-by: Shantanu <hauntsaninja@users.noreply.github.com>
Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
2020-11-21 00:16:42 +03:00
Raymond Hettinger 9fc319dc03
bpo-42360: Add advice to help avoid pickling issues. (GH-23305) 2020-11-20 12:49:32 -08:00
Zhang Maiyun 4c24b08cd3
Fix wrong availability for signal.SIGCHLD (#23285)
I believe this is a mistake. SIGCHLD is only available on Unix systems, not Windows.
2020-11-20 20:16:46 +02:00
Joshua Cannon 4520584483
bpo-35498: Added slice support to PathLib parents attribute. (GH-11165)
Added slice support to the `pathlib.Path.parents` sequence. For a `Path` `p`, slices of `p.parents` should return the same thing as slices of `tuple(p.parents)`.
2020-11-20 10:40:39 -05:00
Filipe Laíns d20b7ed9c1
bpo-42212: Check if generated files are up-to-date in GitHub Actions (GH-23042)
See https: //github.com/python/core-workflow/issues/380

Signed-off-by: Filipe Laíns <lains@archlinux.org>
2020-11-20 15:14:16 +01:00
Victor Stinner 3be8e220ed
bpo-42403: Use @staticmethod in importlib (GH-23395)
Use @staticmethod on methods using @classmethod but don't use their
cls parameter on the following classes:

* BuiltinImporter
* FrozenImporter
* WindowsRegistryFinder
* PathFinder

Leave methods using @_requires_builtin or @_requires_frozen unchanged,
since this decorator requires the wrapped method to have an extra parameter
(cls or self).
2020-11-20 14:44:02 +01:00
Erlend Egeberg Aasland a6109ef68d
bpo-1635741: Convert _sre types to heap types and establish module state (PEP 384) (GH-23393) 2020-11-20 21:36:23 +09:00
Mohamed Koubaa 2db8e35489
bpo-1635741: Enhance _datetime error handling (GH-23139) 2020-11-20 11:39:40 +01:00
Christian Heimes 5c36da78d7
bpo-42333: Port _ssl extension module to heap types (GH-23392)
All types in _ssl module are now heap types.
2020-11-20 09:40:12 +01:00
Christian Heimes 03c8ddd9e9
bpo-42413: socket.timeout is now an alias of TimeoutError (GH-23413)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-20 00:26:07 -08:00
Terry Jan Reedy 7ddbaa7a1b
bpo-42416: Use inspect.getdoc for IDLE calltips (GH-23416)
Inspect.getdoc(ob) sometimes gets docstrings when ob.__doc__ is None.
2020-11-20 01:59:11 -05:00
kj e1dc0db8c7
bpo-42345: Add whatsnew and versionchanged for typing.Literal in 3.9 (GH-23386)
* Whatsnew entry in 3.9 same as the one in 3.10.
* versionchanged for typing.Literal docs

Needs backport to 3.9.
2020-11-19 09:37:26 -08:00
Yurii Karabas 1b54077ff6
bpo-42345: Fix hash implementation of typing.Literal (GH-23383)
Fix hash implementation of `typing.Literal`.

Update docs regarding `typing.Litaral` caching.

Base implementation was done in PR #23294.
2020-11-19 08:17:38 -08:00
Christian Heimes b437aa83f9
bpo-1635741: Port _posixshmem extension module to multiphase initialization (GH-23404)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-19 07:20:42 -08:00
Dong-hee Na 588c7c9f08
bpo-1635741: Fix _struct for build bot error (GH-23402)
Automerge-Triggered-By: GH:tiran
2020-11-19 06:14:34 -08:00
Christian Heimes 646d7fdefb
bpo-1635741: Port gc module to multiphase initialization (GH-23377)
Signed-off-by: Christian Heimes <christian@python.org>

Automerge-Triggered-By: GH:tiran
2020-11-19 06:08:34 -08:00
Christian Heimes cfeb5437a8
bpo-1635741: Port _struct to multiphase initialization (GH-23398)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-19 22:36:23 +09:00
Victor Stinner 3390347aa0
bpo-42403: Simplify importlib external bootstrap (GH-23397)
Simplify the importlib external bootstrap code:
importlib._bootstrap_external now uses regular imports to import
builtin modules. When it is imported, the builtin __import__()
function is already fully working and so can be used to import
builtin modules like sys.
2020-11-19 13:43:43 +01:00
Victor Stinner 7d9d25dbed
bpo-42403: Fix pyflakes warnings in importlib (GH-23396)
Remove unused imports and unused local variables.
2020-11-19 11:20:57 +01:00
Christian Heimes bf9d70a1a5
bpo-1635741: Port spwd to multiphase initialization (GH-23390)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-19 10:54:03 +01:00
Christian Heimes 3094dd5fb5
bpo-1635741: Port _queue to multiphase initialization (GH-23376)
Signed-off-by: Christian Heimes <christian@python.org>

Automerge-Triggered-By: GH:tiran
2020-11-19 00:24:37 -08:00
Christian Heimes fa2eee975d
bpo-1635741: Port grp and pwd to multiphase initialization (GH-23360)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-18 23:47:32 -08:00
Christian Heimes cc0cd43c0f
bpo-1635741: Port _random to multiphase initialization (GH-23359)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-18 23:46:29 -08:00
David CARLIER 13b865f0e1
bpo-42375: subprocess DragonFlyBSD build update. (GH-23320)
Same as FreeBSD, file descriptors in /dev/fd id from 0 to 63.
2020-11-18 23:24:15 -08:00
kj 4687338d0e
bpo-42345: Add whatsnew for typing.Literal in 3.10 (GH-23385) 2020-11-18 20:44:24 -08:00
Lysandros Nikolaou a85fefe71b
bpo-42381: Document walrus-related syntax changes in whatsnew (GH-23382)
Automerge-Triggered-By: GH:lysnikolaou
2020-11-18 15:49:28 -08:00
Victor Stinner 6f4635fe20
bpo-1635741: Port _warnings to the multi-phase init (GH-23379)
Port the _warnings extension module to the multi-phase initialization
API (PEP 489).
2020-11-19 00:19:06 +01:00
Andre Delfino 829b177436
[doc] Fix smtplib and xml.dom.minidom mark-up (GH-22769) 2020-11-18 23:45:17 +01:00
Victor Stinner 6223071421
bpo-1635741: Convert _imp to multi-phase init (GH-23378)
Convert the _imp extension module to the multi-phase initialization
API (PEP 489).

* Add _PyImport_BootstrapImp() which fix a bootstrap issue: import
  the _imp module before importlib is initialized.
* Add create_builtin() sub-function, used by _imp_create_builtin().
* Initialize PyInterpreterState.import_func earlier, in
  pycore_init_builtins().
* Remove references to _PyImport_Cleanup(). This function has been
  renamed to finalize_modules() and moved to pylifecycle.c.
2020-11-18 23:18:29 +01:00
Miro Hrončok e0251787d8
bpo-39573: Remove What's new entry for Py_SIZE() (GH-23375)
A follow up for 0e2ac21dd4
2020-11-18 22:39:03 +01:00
Vladimir Matveev 7c9487ded4
bpo-42085: Add documentation for Py_TPFLAGS_HAVE_AM_SEND (GH-23374)
Updated docs to include `Py_TPFLAGS_HAVE_AM_SEND`. News section should not be necessary.

Automerge-Triggered-By: GH:asvetlov
2020-11-18 10:58:38 -08:00
Victor Stinner 0e2ac21dd4
bpo-39573: Convert Py_TYPE() and Py_SIZE() back to macros (GH-23366)
This change partically reverts
commit ad3252bad9
and the commit fe2978b3b9.

Many third party C extension modules rely on the ability of using
Py_TYPE() to set an object type: "Py_TYPE(obj) = type;" or to set an
object type using: "Py_SIZE(obj) = size;".
2020-11-18 18:48:06 +01:00
Steve Dower 2156d964a1
bpo-42336: Improve PCbuild batch files (GH-23275) 2020-11-18 17:24:36 +00:00
Christian Heimes 07f2adedf0
bpo-40998: Address compiler warnings found by ubsan (GH-20929)
Signed-off-by: Christian Heimes <christian@python.org>

Automerge-Triggered-By: GH:tiran
2020-11-18 07:38:53 -08:00
Christian Heimes 46f59ebd01
bpo-1635741: Port _hashlib to multiphase initialization (GH-23358)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-18 16:12:13 +01:00
Christian Heimes c7011012fa
bpo-1635741: Port symtable module to multiphase initialization (GH-23361)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-18 07:03:51 -08:00
Victor Stinner d1e38d4023
bpo-40998: Fix a refleak in create_filter() (GH-23365) 2020-11-18 06:57:10 -08:00
Victor Stinner 8fba9523cf
bpo-42398: Fix "make regen-all" race condition (GH-23362)
Fix a race condition in "make regen-all" when make -jN option is used
to run jobs in parallel. The clinic.py script now only use atomic
write to write files. Moveover, generated files are now left
unchanged if the content does not change, to not change the file
modification time.

The "make regen-all" command runs "make clinic" and "make
regen-importlib" targets:

* "make regen-importlib" builds object files (ex: Modules/_weakref.o)
  from source files (ex: Modules/_weakref.c) and clinic files (ex:
  Modules/clinic/_weakref.c.h)
* "make clinic" always rewrites all clinic files
  (ex: Modules/clinic/_weakref.c.h)

Since there is no dependency between "clinic" and "regen-importlib"
Makefile targets, these two targets can be run in parallel. Moreover,
half of clinic.py file writes are not atomic and so there is a race
condition when "make regen-all" runs jobs in parallel using make -jN
option (which can be passed in MAKEFLAGS environment variable).

Fix clinic.py to make all file writes atomic:

* Add write_file() function to ensure that all file writes are
  atomic: write into a temporary file and then use os.replace().
* Moreover, write_file() doesn't recreate or modify the file if the
  content does not change to avoid modifying the file modification
  file.
* Update test_clinic to verify these assertions with a functional
  test.
* Remove Clinic.force attribute which was no longer used, whereas
  Clinic.verify remains useful.
2020-11-18 15:36:27 +01:00
Christian Heimes ce04e7105b
bpo-41561: skip test_min_max_version_mismatch (GH-22308)
skip test_min_max_version_mismatch when TLS 1.0 is not available

Signed-off-by: Christian Heimes <christian@python.org>
2020-11-18 13:10:53 +01:00
Erlend Egeberg Aasland ccdcb20cbe
bpo-40656: Clean up detect_socket() (GH-20148) 2020-11-17 19:08:58 -05:00
Tom Gringauz d0d4a45067
bpo-42395: Add aclosing to __all__ (GH-23356)
Automerge-Triggered-By: GH:asvetlov
2020-11-17 15:18:05 -08:00
Tom Gringauz 9c98e8cc3e
bpo-42396: Add a whatsnew entry about async contextlib.nullcontext (GH-23357)
Automerge-Triggered-By: GH:asvetlov
2020-11-17 14:58:35 -08:00
Victor Stinner 7f9b25a21a
bpo-41713: Port _signal module to multi-phase init (GH-23355)
Port the _signal extension module to the multi-phase initialization
API (PEP 489).

Co-Authored-By: Mohamed Koubaa <koubaa.m@gmail.com>
2020-11-17 23:28:25 +01:00
Victor Stinner 1de61d3923
bpo-41625: Skip os.splice() tests on AIX (GH-23354)
On AIX, splice() only works with a socket, whereas the test uses a
pipe.
2020-11-17 23:08:10 +01:00
Victor Stinner 29aa624047
bpo-41686: Move _Py_RestoreSignals() to signalmodule.c (GH-23353) 2020-11-17 22:55:30 +01:00
Julien Palard 282282a1c9
Fix: Docstrings hidden by slots. (GH-23352)
Some `__slots__` where before the docstring, hiding them.
2020-11-17 13:50:23 -08:00
Pablo Galindo 2a9eddf070
bpo-41625: Add a guard for Linux for splice() constants in the os module (GH-23350) 2020-11-17 11:57:49 -08:00
Pablo Galindo e59958f8b6
bpo-41625: Specify that Linux >= 2.6.17 *and* glibc >= 2.5 are requir… (GH-23351)
…ed for splice()
2020-11-17 11:57:03 -08:00
Mark Shannon 266b462238
bpo-42349: Compiler clean up. More yak-shaving for PEP 626. (GH-23267)
Make sure that CFG from compiler front-end is correct. Be a bit more aggressive in the compiler back-end.
2020-11-17 19:30:14 +00:00
Pablo Galindo fa96608513
bpo-41625: Add versionadded to os.splice() constants (GH-23340) 2020-11-17 18:13:50 +00:00
Victor Stinner cda23be092
bpo-41686: Refactor signal_exec() (GH-23346)
* Add signal_add_constants() function and add ADD_INT_MACRO macro.
* The Python SIGINT handler is now installed at the end of
  signal_exec().
* Use Py_NewRef().
2020-11-17 18:57:32 +01:00
Victor Stinner 0ae323b87f
bpo-41686: Always create the SIGINT event on Windows (GH-23344)
bpo-41686, bpo-41713: On Windows, the SIGINT event,
_PyOS_SigintEvent(), is now created even if Python is configured to
not install signal handlers (PyConfig.install_signal_handlers=0 or
Py_InitializeEx(0)).

Changes:

* Move global variables initialization from signal_exec() to
  _PySignal_Init() to clarify that they are global variables cleared
  by _PySignal_Fini().
* _PySignal_Fini() now closes sigint_event.
* IntHandler is no longer a global variable.
2020-11-17 18:15:20 +01:00
Erlend Egeberg Aasland a1f401a58b
bpo-42264: Deprecate sqlite3.OptimizedUnicode (GH-23163) 2020-11-17 17:55:12 +02:00
Victor Stinner 296a796951
bpo-41713: Remove PyOS_InitInterrupts() function (GH-23342)
Remove the undocumented PyOS_InitInterrupts() C function.

* Rename PyOS_InitInterrupts() to _PySignal_Init(). It now installs
  other signal handlers, not only SIGINT.
* Rename PyOS_FiniInterrupts() to _PySignal_Fini()
2020-11-17 16:22:23 +01:00
Christian Heimes 975022b77b
bpo-40637: Don't test builtin PBKDF2 without builtin hashes (GH-20980)
Skip testing of pure Python PBKDF2 when one or more builtin hash module
is not available. Otherwise the import of hashlib prints noise on
stderr.

Signed-off-by: Christian Heimes <christian@python.org>
2020-11-17 15:40:35 +01:00
Erlend Egeberg Aasland 2ffba2a102
bpo-41861, _sqlite3 : Add NEWS entry and rename variables (GH-23337) 2020-11-17 13:52:54 +01:00
Yurii Karabas f03d318ca4
bpo-42345: Fix three issues with typing.Literal parameters (GH-23294)
Literal equality no longer depends on the order of arguments.

Fix issue related to `typing.Literal` caching by adding `typed` parameter to `typing._tp_cache` function.

Add deduplication of `typing.Literal` arguments.
2020-11-16 18:23:19 -08:00
Pablo Galindo b0aba1fcdc
bpo-42381: Allow walrus in set literals and set comprehensions (GH-23332)
Currently walruses are not allowerd in set literals and set comprehensions:

>>> {y := 4, 4**2, 3**3}
  File "<stdin>", line 1
    {y := 4, 4**2, 3**3}
       ^
SyntaxError: invalid syntax

but they should be allowed as well per PEP 572
2020-11-17 01:17:12 +00:00
Pablo Galindo a57b3d30f6
bpo-41625: Expose the splice() system call in the os module (GH-21947) 2020-11-17 00:00:38 +00:00
Pablo Galindo cce3f0b0c8
Add GCC pragmas to silence compiler warning about ffi_prep_closure (GH-23327) 2020-11-16 23:59:55 +00:00
Steve Dower 9cc9e27725
bpo-42120: Remove macro defining copysign to _copysign on Windows (GH-23326) 2020-11-16 23:22:42 +00:00
Lysandros Nikolaou cae60187cf
bpo-42316: Allow unparenthesized walrus operator in indexes (GH-23317) 2020-11-17 01:09:35 +02:00
Lysandros Nikolaou cb3e5ed071
bpo-42374: Allow unparenthesized walrus in genexps (GH-23319)
This fixes a regression that was introduced by the new parser.

Automerge-Triggered-By: GH:lysnikolaou
2020-11-16 15:08:35 -08:00
Zackery Spytz f62dad16b8
bpo-38506: Fix the Windows py.exe launcher's misordering of 3.10 (GH-18307) 2020-11-16 21:32:35 +00:00
Lysandros Nikolaou c26d5916d6
bpo-40939: Document removal of the old parser in 3.10 whatsnew (GH-23321)
Automerge-Triggered-By: GH:lysnikolaou
2020-11-16 10:46:37 -08:00
Kevin Adler c79667ff79
bpo-42087: Remove support for AIX 5.3 and below (GH-22830)
As AIX 5.3 and below do not support thread_cputime, it was decided in
https://bugs.python.org/issue40680 to require AIX 6.1 and above. This
commit removes workarounds for — and references to — older, unsupported
AIX versions.
2020-11-16 16:16:10 +01:00
Victor Stinner ae6cd7cfda
bpo-37205: time.time() cannot fail with fatal error (GH-23314)
time.time(), time.perf_counter() and time.monotonic() functions can
no longer fail with a Python fatal error, instead raise a regular
Python exception on failure.

Remove _PyTime_Init(): don't check system, monotonic and perf counter
clocks at startup anymore.

On error, _PyTime_GetSystemClock(), _PyTime_GetMonotonicClock() and
_PyTime_GetPerfCounter() now silently ignore the error and return 0.
They cannot fail with a Python fatal error anymore.

Add py_mach_timebase_info() and win_perf_counter_frequency()
sub-functions.
2020-11-16 16:08:05 +01:00
Victor Stinner 5909a494cd
bpo-42350: Fix Thread._reset_internal_locks() (GH-23268)
Fix the threading.Thread class at fork: do nothing if the thread is
already stopped (ex: fork called at Python exit). Previously, an
error was logged in the child process.
2020-11-16 15:20:34 +01:00
Victor Stinner 3df5c68487
bpo-37205: time.perf_counter() and time.monotonic() are system-wide (GH-23284)
time.perf_counter() on Windows and time.monotonic() on macOS are now
system-wide. Previously, they used an offset computed at startup to
reduce the precision loss caused by the float type. Use
time.perf_counter_ns() and time.monotonic_ns() added in Python 3.7 to
avoid this precision loss.
2020-11-16 13:21:45 +01:00
Yash Shete aa01011003
bpo-42153 Fix link to IMAP documents in imaplib.rst (GH-23297)
The University of Washington stopped hosting the IMAP documents. Link to a rescued copy on GitHub.
2020-11-15 21:02:35 -08:00
kj 384b7a4bd9
bpo-42332: Add weakref slot to types.GenericAlias (GH-23250)
Automerge-Triggered-By: GH:gvanrossum
2020-11-15 19:27:23 -08:00
Raymond Hettinger c272d40e5b
More updates to the descriptor howto guide (GH-23238) 2020-11-15 17:44:28 -08:00
Dominik1123 c3b9592244
bpo-42317: Improve docs of typing.get_args concerning Union (GH-23254) 2020-11-15 17:30:55 -08:00
Serhiy Storchaka a26215db11
bpo-42318: Fix support of non-BMP characters in Tkinter on macOS (GH-23281) 2020-11-15 18:16:59 +02:00
Ronald Oussoren 7a27c7ed4b
bpo-42351: Avoid error when opening header with non-UTF8 encoding (GH-23279)
grep_headers_for() would error out when a header contained
text that cannot be interpreted as UTF-8.
2020-11-14 16:07:47 +01:00
Hai Shi 2b39da4997
bpo-41832: Restore note about NULL in PyType_Slot.pfunc (GH-23243) 2020-11-14 13:03:42 +01:00
Thomas Grainger 8836574a0f
fix typo in ThreadedChildWatcher docs (GH-23277) 2020-11-14 14:02:15 +02:00
Brett Cannon d2e94bb084
bpo-42131: Add PEP 451-related methods to zipimport (GH-23187)
Specifically, find_spec(), create_module(), and exec_module().

Co-authored-by: Nick Coghlan <ncoghlan@gmail.com>
2020-11-13 15:14:58 -08:00
Steve Dower 9b6934230c
bpo-40754: Adds _testinternalcapi to Windows installer for test suite (GH-23271) 2020-11-13 22:24:36 +00:00
Christian Heimes cd9fed6afb
bpo-41001: Add os.eventfd() (#20930)
Co-authored-by: Kyle Stanley <aeros167@gmail.com>
2020-11-13 19:48:52 +01:00
Jürgen Gmach bbeb2d266d
bpo-42344: Improve pseudo implementation for SimpleNamespace (GH-23264) 2020-11-13 13:15:37 -05:00
Christian Heimes f97406be4c
bpo-40968: Send http/1.1 ALPN extension (#20959)
Signed-off-by: Christian Heimes <christian@python.org>
2020-11-13 16:37:52 +01:00
Dong-hee Na 09490a109f
bpo-42042: Use ids attribute instead of names attribute (GH-22739) 2020-11-14 00:15:17 +09:00
Victor Stinner b3b98082c5
bpo-41617: Add _Py__has_builtin() macro (GH-23260)
Fix building pycore_bitutils.h internal header on old clang version
without __builtin_bswap16() (ex: Xcode 4.6.3 on Mac OS X 10.7).

Add a new private _Py__has_builtin() macro to check for availability
of a preprocessor builtin function.

Co-Authored-By: Joshua Root <jmr@macports.org>

Co-authored-by: Joshua Root <jmr@macports.org>
2020-11-13 15:38:17 +01:00
Victor Stinner d96a7a8313
bpo-42296: On Windows, fix CTRL+C regression (GH-23257)
On Windows, fix a regression in signal handling which prevented to
interrupt a program using CTRL+C. The signal handler can be run in a
thread different than the Python thread, in which case the test
deciding if the thread can handle signals is wrong.

On Windows, _PyEval_SignalReceived() now always sets eval_breaker to
1 since it cannot test _Py_ThreadCanHandleSignals(), and
  eval_frame_handle_pending() always calls
  _Py_ThreadCanHandleSignals() to recompute eval_breaker.
2020-11-13 14:44:42 +01:00
Victor Stinner 0cec97eb6a
bpo-38823: Fix compiler warning in _ctypes on Windows (GH-23258)
Explicitly cast PyExc_Exception to PyTypeObject* to fix the warning:

    modules\_ctypes\_ctypes.c(5748): warning C4133: '=':
    incompatible types - from 'PyObject *' to '_typeobject *'
2020-11-13 14:44:11 +01:00
Mark Shannon fd009e606a
bpo-42246: Fix memory leak in compiler (GH-23256)
* Fix potential memory leak in assembler init.

* Fix reference leak when encountering error during compilation of function body.
2020-11-13 12:53:53 +00:00
Mark Shannon cc75ab791d
bpo-42246: Eliminate jumps to exit blocks by copying those blocks. (#23251)
* Compiler: eliminate jumps to short exit blocks by copying.
2020-11-12 19:49:33 +00:00
Mario Corchero 750c5abf43
bpo-42308: Add threading.__excepthook__ (GH-23218)
Add threading.__excepthook__ to allow retrieving the original value
of threading.excepthook in case it is set to a broken or a different
value.
2020-11-12 18:27:44 +01:00
Victor Stinner b5cc05bbe6
bpo-38823: Always build _ctypes with wchar_t (GH-23248)
It is no longer possible to build the _ctypes extension module
without wchar_t type: remove CTYPES_UNICODE macro. Anyway, the
wchar_t type is required to build Python.
2020-11-12 15:38:13 +01:00
Victor Stinner ef75a625cd
bpo-42260: Initialize time and warnings earlier at startup (GH-23249)
* Call _PyTime_Init() and _PyWarnings_InitState() earlier during the
  Python initialization.
* Inline _PyImportHooks_Init() into _PySys_InitCore().
* The _warnings initialization function no longer call
  _PyWarnings_InitState() to prevent resetting filters_version to 0.
* _PyWarnings_InitState() now returns an int and no longer clear the
  state in case of error (it's done anyway at Python exit).
* Rework init_importlib(), fix refleaks on errors.
2020-11-12 15:14:13 +01:00
Victor Stinner d19fa7a337
bpo-38823: Fix refleaks in _ctypes extension init (GH-23247)
Fix reference leaks in the error path of the initialization function
the _ctypes extension module: call Py_DECREF(mod) on error.

Change PyCFuncPtr_Type name from _ctypes.PyCFuncPtr to
_ctypes.CFuncPtr to be consistent with the name exposed in the
_ctypes namespace (_ctypes.CFuncPtr).

Split PyInit__ctypes() function into sub-functions and add macros for
readability.
2020-11-12 14:09:57 +01:00
Mark Shannon c6409156c4
Bump magic number. (GH-23245) 2020-11-12 10:42:44 +00:00
Jakub Stasiak fd4ed57674
bpo-42237: Fix os.sendfile() on illumos (GH-23154) 2020-11-12 11:49:30 +02:00
Mark Shannon 877df851c3
bpo-42246: Partial implementation of PEP 626. (GH-23113)
* Implement new line number table format, as defined in PEP 626.
2020-11-12 09:43:29 +00:00
Andrew Svetlov cda99b4022
Fix memory leak introduced by GH-22780 (GH-23237) 2020-11-11 17:48:53 +02:00
Victor Stinner ba2958ed40
bpo-40170: Fix PyType_Ready() refleak on static type (GH-23236)
bpo-1635741, bpo-40170: When called on a static type with NULL
tp_base, PyType_Ready() no longer increments the reference count of
the PyBaseObject_Type ("object). PyTypeObject.tp_base is a strong
reference on a heap type, but it is borrowed reference on a static
type.

Fix 99 reference leaks at Python exit (showrefcount 18623 => 18524).
2020-11-11 14:27:32 +01:00
Ammar Askar f9a8386e44
bpo-40932: Note security caveat of shlex.quote on Windows (GH-21502)
Added a note in the `subprocess` docs that recommend using `shlex.quote` without mentioning that this is only applicable to Unix. 

Also added a warning straight into the `shlex` docs since it only says "for simple syntaxes resembling that of the Unix shell" and says using `quote` plugs the security hole without mentioning this important caveat.
2020-11-10 23:29:56 -08:00
Batuhan Taskaya fa476fe132
bpo-39411: pyclbr rewrite on AST (#18103)
- Rewrite pyclbr using an AST processor
- Add is_async to the pyclbr.Function
2020-11-11 10:14:12 +03:00
Victor Stinner 95ce7cd0a6
bpo-1635741: Fix typo in PyModule_AddObjectRef() doc (GH-23234)
It is similar to PyModule_AddObject(), not to itself.
2020-11-11 01:52:26 +01:00
kj 78ba7c69ad
bpo-42294: Grammar fixes in doc glossary strong/weak refs (GH-23227) 2020-11-11 00:56:55 +01:00
Diogo Dutra 7e5ef0a571
bpo-42140: Improve asyncio.wait function (GH-22938)
# Improve asyncio.wait function

The original code creates the futures set two times.
We can create this set before, avoiding the second creation.

This new behaviour [breaks the aiokafka library](https://github.com/aio-libs/aiokafka/pull/672), because it gives an iterator to that function, so the second iteration become empty.

Automerge-Triggered-By: GH:1st1
2020-11-10 14:12:52 -08:00
Hai Shi a13b26cac1
bpo-41073: PyType_GetSlot() can now accept static types. (GH-21931)
PyType_GetSlot() can now accept static types.

Co-Authored-By: Petr Viktorin <encukou@gmail.com>

Automerge-Triggered-By: GH:encukou
2020-11-10 12:53:46 -08:00
Victor Stinner ace3f9a0ce
bpo-42260: Fix _PyConfig_Read() if compute_path_config=0 (GH-23220)
Fix _PyConfig_Read() if compute_path_config=0: use values set by
Py_SetPath(), Py_SetPythonHome() and Py_SetProgramName(). Add
compute_path_config parameter to _PyConfig_InitPathConfig().

The following functions now return NULL if called before
Py_Initialize():

* Py_GetExecPrefix()
* Py_GetPath()
* Py_GetPrefix()
* Py_GetProgramFullPath()
* Py_GetProgramName()
* Py_GetPythonHome()

These functions no longer automatically computes the Python Path
Configuration. Moreover, Py_SetPath() no longer computes
program_full_path.
2020-11-10 21:10:22 +01:00
Vladimir Matveev 1e996c3a3b
bpo-42085: Introduce dedicated entry in PyAsyncMethods for sending values (#22780) 2020-11-10 12:09:55 -08:00
Michal Čihař e59b2deffd
bpo-42014: shutil.rmtree: call onerror with correct function (GH-22585)
The onerror is supposed to be called with failed function, but in this case lstat is wrongly used instead of open.

Not sure if this needs bug or not...

Automerge-Triggered-By: GH:hynek
2020-11-10 08:06:02 -08:00
Joongi Kim 3eb2846225
Update whatsnew for 3.10 release about addition of contextlib.aclosing (GH-23217) 2020-11-10 17:19:11 +02:00
Andrew Svetlov 42d873c63a
bpo-42183: Fix a stack overflow error for asyncio Task or Future repr() (GH-23020)
The overflow occurs under some circumstances when a task or future
recursively returns itself.

Co-authored-by: Kyle Stanley <aeros167@gmail.com>
2020-11-10 15:58:31 +02:00
Petr Viktorin 0b9c4c6fcf
bpo-42171: Add PEP573-related items to the limited API (GH-23009) 2020-11-10 05:47:31 -08:00
Ikko Ashimine 9303b9ecc3
Fix typo in test_array.py (GH-23189) 2020-11-10 18:12:36 +05:30
Victor Stinner 9e1b828265
bpo-42260: Compute the path config in the main init (GH-23211)
The path configuration is now computed in the "main" initialization.
The core initialization no longer computes it.

* Add _PyConfig_Read() function to read the configuration without
  computing the path configuration.
* pyinit_core() no longer computes the path configuration: it is now
  computed by init_interp_main().
* The path configuration output members of PyConfig are now optional:

  * executable
  * base_executable
  * prefix
  * base_prefix
  * exec_prefix
  * base_exec_prefix

* _PySys_UpdateConfig() now skips NULL strings in PyConfig.
* _testembed: Rename test_set_config() to test_init_set_config() for
  consistency with other tests.
2020-11-10 13:21:52 +01:00
Ikko Ashimine 38811d68ca
Fix typo in unicodeobject.c (GH-23180)
exeeds -> exceeds

Automerge-Triggered-By: GH:Mariatta
2020-11-09 21:57:34 -08:00
jack1142 bfc6b63102
bpo-36310: Allow pygettext.py to detect calls to gettext in f-strings. (GH-19875)
Adds support to Tools/i18n/pygettext.py for gettext calls in f-strings. This process is done by parsing the f-strings, processing each value, and flagging the ones which contain a gettext call.

Co-authored-by: Batuhan Taskaya <batuhanosmantaskaya@gmail.com>
2020-11-10 01:50:45 +03:00
Yash Shete 1f73c320e2
bpo-41712: Avoid runaway regex match in upload scripts (GH-23166) 2020-11-09 17:38:09 +00:00
Victor Stinner 23c5f93b83
bpo-42294: Add borrowed/strong reference to doc glossary (GH-23206)
Add "borrowed reference" and "strong reference" to the documentation
glossary.

Enhance also Py_INCREF() and Py_NewRef() documentation.
2020-11-09 13:40:47 +01:00
Tom Gringauz a117167d8d
bpo-41543: contextlib.nullcontext can fill in for an async context manager (GH-21870)
Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
2020-11-09 14:34:07 +02:00
Ammar Askar 97e8b1eaea
bpo-40624: Add support for the XPath != operator in xml.etree (GH-22147) 2020-11-09 08:02:39 +01:00
kj 4eb41d055e
bpo-42233: Add union type expression support for GenericAlias and fix de-duplicating of GenericAlias (GH-23077) 2020-11-08 20:00:13 -08:00
Ronald Oussoren 23831a7a90
bpo-41754: Ignore NotADirectoryError in invocation of xdg-settings (GH-23075)
It is not clear why this can happen, but several users have mentioned
getting this exception on macOS.
2020-11-08 10:46:55 +01:00
Ronald Oussoren 41761933c1
bpo-41100: Support macOS 11 and Apple Silicon (GH-22855)
Co-authored-by:  Lawrence D’Anna <lawrence_danna@apple.com>

* Add support for macOS 11 and Apple Silicon (aka arm64)
   
  As a side effect of this work use the system copy of libffi on macOS, and remove the vendored copy

* Support building on recent versions of macOS while deploying to older versions

  This allows building installers on macOS 11 while still supporting macOS 10.9.
2020-11-08 10:05:27 +01:00
Don Kirkby fd6f6fa403
Minor wording change in concurrent.futures. (GH-23194)
Fixes a grammar problem by adding a missing "as", and clarifies the wording of the valid ranges for max_workers.
2020-11-08 11:01:23 +02:00
Erlend Egeberg Aasland 01c6aa43dc
bpo-40077: Convert _queuemodule to use heap types (GH-23136)
@vstinner / @corona10, would you mind reviewing this?
2020-11-07 11:18:37 -08:00
Nick Coghlan 8805a4dad2
bpo-42282: Fold constants inside named expressions (GH-23190)
* The AST optimiser wasn't descending into named expressions, so
  any constant subexpressions weren't being folded at compile time
* Remove "default:" clauses inside the AST optimiser code to reduce the
  risk of similar bugs passing unnoticed in future compiler changes
2020-11-07 22:35:17 +10:00
Julien Palard ee2549c2ba
bpo-41028: Doc: Move switchers to docsbuild-scripts. (GH-20969) 2020-11-07 12:28:31 +01:00
Brett Cannon 825ac38332
bpo-42133: update parts of the stdlib to fall back to `__spec__.loader` when `__loader__` is missing (#22929) 2020-11-06 18:45:56 -08:00
Andre Delfino 7c01f1540f
Remove outdated reference to pywin32 from platform module (GH-22005) 2020-11-06 18:58:14 +00:00
Hai Shi 88c2cfd9ff
bpo-41832: PyType_FromModuleAndSpec() now accepts NULL tp_doc (GH-23123) 2020-11-06 17:04:47 +01:00
Raymond Hettinger 803187796f
Minor grammar edits for the descriptor howto guide (GH-#23175) 2020-11-06 01:30:17 -08:00
Inada Naoki bde33e428d
bpo-42179: Doc/tutorial: Remove mention of __cause__ (GH-23162) 2020-11-06 11:45:01 +09:00
Zackery Spytz 91e93794d5
bpo-26389: Allow passing an exception object in the traceback module (GH-22610)
The format_exception(), format_exception_only(), and
print_exception() functions can now take an exception object as a positional-only argument.

Co-Authored-By: Matthias Bussonnier <bussonniermatthias@gmail.com>
2020-11-05 22:18:44 +00:00
Victor Stinner dc42af8fd1
bpo-42260: PyConfig_Read() only parses argv once (GH-23168)
The PyConfig_Read() function now only parses PyConfig.argv arguments
once: PyConfig.parse_argv is set to 2 after arguments are parsed.
Since Python arguments are strippped from PyConfig.argv, parsing
arguments twice would parse the application options as Python
options.

* Rework the PyConfig documentation.
* Fix _testinternalcapi.set_config() error handling.
* SetConfigTests no longer needs parse_argv=0 when restoring the old
  configuration.
2020-11-05 18:58:07 +01:00
Victor Stinner f3cb814315
bpo-42260: Add _PyConfig_FromDict() (GH-23167)
* Rename config_as_dict() to _PyConfig_AsDict().
* Add 'module_search_paths_set' to _PyConfig_AsDict().
* Add _PyConfig_FromDict().
* Add get_config() and set_config() to _testinternalcapi.
* Add config_check_consistency().
2020-11-05 18:12:33 +01:00
vabr-g 4662fa9bfe
bpo-41877 Check for asert, aseert, assrt in mocks (GH-23165)
Currently, a Mock object which is not unsafe will raise an
AttributeError if an attribute with the prefix assert or assret is
accessed on it. This protects against misspellings of real assert
method calls, which lead to tests passing silently even if the tested
code does not satisfy the intended assertion.

Recently a check was done in a large code base (Google) and three
more frequent ways of misspelling assert were found causing harm:
asert, aseert, assrt. These are now added to the existing check.
2020-11-05 09:04:38 -08:00
kj 133aa2d581
[docs] fix wrongly named AsyncContextDecorator (GH-23164)
Also added versionchanged.
2020-11-05 18:16:27 +02:00
Victor Stinner 53a03aafd5
bpo-42262: Add Py_NewRef() and Py_XNewRef() (GH-23152)
Added Py_NewRef() and Py_XNewRef() functions to increment the reference
count of an object and return the object.
2020-11-05 15:02:12 +01:00
Pablo Galindo 80449f243b
bpo-42266: Handle monkey-patching descriptors in LOAD_ATTR cache (GH-23157) 2020-11-05 09:23:15 +00:00
Kazantcev Andrey 178695b7ae
bpo-40816 Add AsyncContextDecorator class (GH-20516)
Co-authored-by: Yury Selivanov <yury@edgedb.com>
2020-11-05 10:52:24 +02:00
Victor Stinner 048a35659a
bpo-42260: Add _PyInterpreterState_SetConfig() (GH-23158)
* Inline _PyInterpreterState_SetConfig(): replace it with
  _PyConfig_Copy().
* Add _PyErr_SetFromPyStatus()
* Add _PyInterpreterState_GetConfigCopy()
* Add a new _PyInterpreterState_SetConfig() function.
* Add an unit which gets, modifies, and sets the config.
2020-11-05 00:45:56 +01:00
serge-sans-paille 100964e031
Disable peg generator tests when building with PGO (GH-23141)
Otherwise, when running the testsuite, test_peg_generator tries to compile C
code using the optimized flags and fails because it cannot find the profile
data.
2020-11-04 23:01:08 +00:00
Erlend Egeberg Aasland 789359f47c
bpo-1635741: _sqlite3 uses PyModule_AddObjectRef() (GH-23148) 2020-11-04 20:31:51 +01:00
Mohamed Koubaa 7184218e18
bpo-1635741: Fix PyInit_pyexpat() error handling (GH-22489)
Split PyInit_pyexpat() into sub-functions and fix reference leaks
on error paths.
2020-11-04 18:37:23 +01:00
Victor Stinner af1d64d9f7
bpo-42260: Main init modify sys.flags in-place (GH-23150)
When Py_Initialize() is called twice, the second call now updates
more sys attributes for the configuration, rather than only sys.argv.

* Rename _PySys_InitMain() to _PySys_UpdateConfig().
* _PySys_UpdateConfig() now modifies sys.flags in-place, instead of
  creating a new flags object.
* Remove old commented sys.flags flags (unbuffered and skip_first).
* Add private _PySys_GetObject() function.
* When Py_Initialize(), Py_InitializeFromConfig() and
2020-11-04 17:34:34 +01:00
Victor Stinner 58ca33b467
bpo-1635741: Fix ref leak in _PyWarnings_Init() error path (GH-23151)
Replace PyModule_AddObject() with PyModule_AddObjectRef() in the
_warnings module to fix a reference leak on error.

Use also PyModule_AddObjectRef() in importdl.c.
2020-11-04 17:33:06 +01:00
Victor Stinner 18ce7f1d0a
bpo-1635741: _ast uses PyModule_AddObjectRef() (GH-23146)
Replace PyModule_AddObject() with PyModule_AddObjectRef() in the _ast
module (Python-ast.c).
2020-11-04 16:37:07 +01:00
Victor Stinner 988f1ec8d2
bpo-1635741: _contextvars uses PyModule_AddType() (GH-23147)
Replace PyModule_AddObject() with PyModule_AddType() in the
_contextvars module (Python-ast.c).

Add also the module name to _contextvars types name.
2020-11-04 16:33:55 +01:00
Victor Stinner cfb41e80c1
bpo-42260: Reorganize PyConfig (GH-23149)
* Move orig_argv before argv
* Move program_name and platlibdir with other path configuration
  inputs

Give a name to the PyPreConfig and PyConfig structures and separate
the type definitions.
2020-11-04 16:15:54 +01:00
Victor Stinner 8021875bbc
bpo-1635741: Add PyModule_AddObjectRef() function (GH-23122)
Added PyModule_AddObjectRef() function: similar to
PyModule_AddObjectRef() but don't steal a reference to the value on
success.
2020-11-04 13:59:15 +01:00
Victor Stinner 3529718925
bpo-42236: os.device_encoding() respects UTF-8 Mode (GH-23119)
On Unix, the os.device_encoding() function now returns 'UTF-8' rather
than the device encoding if the Python UTF-8 Mode is enabled.
2020-11-04 11:20:10 +01:00
Mario Corchero 0001a1b69e
bpo-42251: Add gettrace and getprofile to threading (GH-23125)
This allows to retrieve the functions that were set in these two, which might differ from sys.gettrace and sys.getprofile within a thread.
2020-11-04 09:27:43 +00:00
Steve Dower db6434c474
Enable signing of nuget.org packages and update to supported timestamp server (GH-23132) 2020-11-03 22:31:49 +00:00
Matthew Suozzo bffb137cb5
Fix incorrect links in ast docs (GH-23017) 2020-11-03 23:28:42 +02:00
Petr Viktorin 57aaaa8d2a
Add _PyType_GetModuleByDef (GH-22835)
See https://mail.python.org/archives/list/capi-sig@python.org/thread/T3P2QNLNLBRFHWSKYSTPMVEIL2EEKFJU/ for discussion.

https://bugs.python.org/issue42100
2020-11-03 22:27:12 +01:00
Pablo Galindo a603c3d371
Post 3.10.0a2 2020-11-03 17:31:32 +00:00
Pablo Galindo a9abbda618 Python 3.10.0a2
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl+gngEACgkQ/+h0BBaL
 2EfDABAAnQ/bHY40QjoQ+us2vufDj3uvm2S7w0LMM+kgrehhqEoG/FmVtfb8XIvD
 S8FFtSa/VkrVUXvxI/mMpWL78se+Qk9rVQJ8dUZ4SvFJVe1NJdCMNV2Ij263QgJU
 r6bNu42EODDrFAgG9vq5ImND1qnGkF+hKlMHYV3HZhTP4drBEY+TMaB55Vmsp9TH
 eBnfY50y+k8w0hJmsZA1LaVLAXU9WHaWVB90/D22Z9MJmmQF5ofsIFXYj+1IcEkE
 P5CLSCRSzVlpdeNiZWrcBIEK8ap4ZkHvwD8RI6Fu3E/h2TXeiDbp/nCHZDPZMVVk
 OVx3Z4BFTNXE4nmRDIiO5+GqIbgG10LFQKOrOvHQr6inookUaFGwJKwkaEheNr2T
 vcgZMy61OEOeiLqCe6AJ/PuNlQ267zslYucUpNqpQpCu8j691OGEHzv+NNcSRrEq
 T/S4spifDVpFPGLRDkFjJe1OQ33bVZFdJx7guY6WJXVkZILS8vghqQYng55CNzd/
 cdMqb5T6BBRb2SDqJ/qvUhyr7D8YML0pP5pywUUGKTdo84+mW5F/N2Q4g28ik9zv
 pgaehbAwS8jgoPbqH0Tz7qpXiWga9fTbFU47Az07xw5tQFD2+C5fdx+b1h2NBz2q
 exccvIw3Fn8zWikrKbeLgaSAWa2saw25dw0DMes8gG9uHD4+1JA=
 =XAGl
 -----END PGP SIGNATURE-----
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl+hk9UACgkQ/+h0BBaL
 2EdkYxAAs5ujyihMfyoRpU9jV7pNIIbpCHMgV2s74ZBh5jnDPYRfIrGtaE/9HlTp
 PPAScsJvnPwBGNdg8Bs1cLAk/VgJC696ccJXmNugfpxs9CSzhEKQ0oF8PPm+oyqH
 LgU6Dv8dP3+ebOko/vnRPTXbL5gdbvVJvNiV5KUjE6FL+IRl2PHlvUdcEplkPXZ4
 179kgP+8hMCB1Ai1KbMDpO2XIgdkJO+iXgXg9QNDCv2zcyr6OegGYI4cPyB3m/YK
 ZiBTnYK48x/l28Gdi+LISOGa4NNQ7R0j+Qao7YDoqe1yy8Ubj3NrLub+nNnSqnqb
 8PYaFz0sWpJ4I/vjrMaUOJ+hKSwdRZqHF/LqfQBFyBCndmhi6tJNqAzcByqi03HL
 YnXlAYJI9T3rFzBOutfjvbFWkiM2DKAL6dWBIsMeuNEO6MQWTwQHKfidXJyx9zCo
 Vv5QLG5daLFDIgI4qBjJ4POxgl+7eR+5sJBNIVz43KhemiRKLdmFKWmv6moloVB+
 1xoNGmwqz4dzmlAMUj2vJiPuUYl6+P38q1dpAChOXx4hOQZ1ybsmUVUD4S+bLGVQ
 f/VYg6B2I/Fr7Yz9HVYe309abKUSzSeYnW9FkAuTHTmZPjgZHdIJl7euTE0FtNOd
 HQ0paNeC44AoqEnghH35FhFXs+wbedszyc++TltTWn32v0nSVk0=
 =qIu/
 -----END PGP SIGNATURE-----

Merge tag 'v3.10.0a2' into master

Python 3.10.0a2
2020-11-03 17:30:57 +00:00
Victor Stinner fd957c124c
bpo-41796: Call _PyAST_Fini() earlier to fix a leak (GH-23131)
Call _PyAST_Fini() on all interpreters, not only on the main
interpreter. Also, call it ealier to fix a reference leak.

Python types contain a reference to themselves in in their
PyTypeObject.tp_mro member. _PyAST_Fini() must called before the last
GC collection to destroy AST types.

_PyInterpreterState_Clear() now calls _PyAST_Fini(). It now also
calls _PyWarnings_Fini() on subinterpeters, not only on the main
interpreter.

Add an assertion in AST init_types() to ensure that the _ast module
is no longer used after _PyAST_Fini() has been called.
2020-11-03 18:07:15 +01:00
Serhiy Storchaka 212d32f45c
bpo-42249: Fix writing binary Plist files larger than 4 GiB. (GH-23121) 2020-11-03 16:15:56 +02:00
Pablo Galindo 114ee5dec0
Python 3.10.0a2 2020-11-03 00:02:08 +00:00
811 changed files with 38188 additions and 20257 deletions

View File

@ -104,7 +104,7 @@ jobs:
matrix:
win32:
arch: win32
buildOpt:
buildOpt: '-p Win32'
testRunTitle: '$(Build.SourceBranchName)-win32'
testRunPlatform: win32
win64:

View File

@ -12,11 +12,11 @@ steps:
inputs:
versionSpec: '>=3.6'
- script: python -m pip install sphinx==2.2.0 blurb python-docs-theme
- script: python -m pip install sphinx==3.2.1 blurb python-docs-theme
displayName: 'Install build dependencies'
- ${{ if ne(parameters.latex, 'true') }}:
- script: make check suspicious html PYTHON=python
- script: make check html PYTHON=python
workingDirectory: '$(build.sourcesDirectory)/Doc'
displayName: 'Build documentation'
@ -31,7 +31,7 @@ steps:
- ${{ if eq(parameters.upload, 'true') }}:
- task: PublishBuildArtifacts@1
displayName: 'Publish docs'
inputs:
PathToPublish: '$(build.sourcesDirectory)/Doc/build'
ArtifactName: docs

View File

@ -104,7 +104,7 @@ jobs:
matrix:
win32:
arch: win32
buildOpt:
buildOpt: '-p Win32'
testRunTitle: '$(System.PullRequest.TargetBranch)-win32'
testRunPlatform: win32
win64:

View File

@ -120,10 +120,11 @@ jobs:
artifactName: unsigned_msix
downloadPath: $(Build.BinariesDirectory)
# MSIX must be signed and timestamped simultaneously
- powershell: |
$failed = $true
foreach ($retry in 1..3) {
signtool sign /a /n "$(SigningCertificate)" /fd sha256 /t http://timestamp.verisign.com/scripts/timestamp.dll /d "$(SigningDescription)" (gi *.msix)
signtool sign /a /n "$(SigningCertificate)" /fd sha256 /tr http://timestamp.digicert.com/ /td sha256 /d "$(SigningDescription)" (gi *.msix)
if ($?) {
$failed = $false
break

View File

@ -4,7 +4,7 @@ jobs:
condition: and(succeeded(), eq(variables['DoNuget'], 'true'))
pool:
vmImage: windows-2019
name: 'Windows Release'
workspace:
clean: all
@ -36,6 +36,14 @@ jobs:
nuget pack "$(Build.BinariesDirectory)\layout\python.nuspec" -OutputDirectory $(Build.ArtifactStagingDirectory) -NoPackageAnalysis -NonInteractive
displayName: 'Create nuget package'
- powershell: |
gci *.nupkg | %{
nuget sign "$_" -CertificateSubjectName "$(SigningCertificate)" -Timestamper http://timestamp.digicert.com/ -Overwrite
}
displayName: 'Sign nuget package'
workingDirectory: $(Build.ArtifactStagingDirectory)
condition: and(succeeded(), variables['SigningCertificate'])
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: nuget'
inputs:

View File

@ -57,7 +57,7 @@ jobs:
$files = (gi ${{ parameters.Include }} -Exclude ${{ parameters.Exclude }})
$failed = $true
foreach ($retry in 1..10) {
signtool timestamp /t http://timestamp.verisign.com/scripts/timestamp.dll $files
signtool timestamp /tr http://timestamp.digicert.com/ /td sha256 $files
if ($?) {
$failed = $false
break

7
.github/CODEOWNERS vendored
View File

@ -19,6 +19,7 @@ Objects/frameobject.c @markshannon
Objects/call.c @markshannon
Python/ceval.c @markshannon
Python/compile.c @markshannon
Python/ast_opt.c @isidentical
# Hashing
**/*hashlib* @python/crypto-team @tiran
@ -84,6 +85,12 @@ Include/pytime.h @pganssle @abalkin
/Lib/test/test_peg_generator/ @pablogsal @lysnikolaou
/Grammar/python.gram @pablogsal @lysnikolaou
# AST
Python/ast.c @isidentical
Parser/asdl.py @isidentical
Parser/asdl_c.py @isidentical
Lib/ast.py @isidentical
# SQLite 3
**/*sqlite* @berkerpeksag

View File

@ -7,3 +7,7 @@ updates:
labels:
- "skip issue"
- "skip news"
target_branch:
- "master"
- "3.9"
- "3.8"

View File

@ -47,6 +47,37 @@ jobs:
# https://github.com/python/core-workflow/issues/373
git diff --name-only origin/$GITHUB_BASE_REF.. | grep -qvE '(\.rst$|^Doc|^Misc)' && echo '::set-output name=run_tests::true' || true
fi
check_generated_files:
name: 'Check if generated files are up to date'
runs-on: ubuntu-latest
needs: check_source
if: needs.check_source.outputs.run_tests == 'true'
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- name: Install Dependencies
run: sudo ./.github/workflows/posix-deps-apt.sh
- name: Build CPython
run: |
# Build Python with the libpython dynamic library
./configure --with-pydebug --enable-shared
make -j4 regen-all
- name: Check for changes
run: |
changes=$(git status --porcelain)
# Check for changes in regenerated files
if ! test -z "$changes"
then
echo "Generated files not up to date. Perhaps you forgot to run make regen-all ;)"
echo "$changes"
exit 1
fi
- name: Check exported libpython symbols
run: make smelly
- name: Check limited ABI symbols
run: make check-limited-abi
build_win32:
name: 'Windows (x86)'
runs-on: windows-latest
@ -59,7 +90,7 @@ jobs:
- name: Display build info
run: .\python.bat -m test.pythoninfo
- name: Tests
run: .\PCbuild\rt.bat -q -uall -u-cpu -rwW --slowest --timeout=1200 -j0
run: .\PCbuild\rt.bat -p Win32 -q -uall -u-cpu -rwW --slowest --timeout=1200 -j0
build_win_amd64:
name: 'Windows (x64)'
@ -73,7 +104,7 @@ jobs:
- name: Display build info
run: .\python.bat -m test.pythoninfo
- name: Tests
run: .\PCbuild\rt.bat -x64 -q -uall -u-cpu -rwW --slowest --timeout=1200 -j0
run: .\PCbuild\rt.bat -p x64 -q -uall -u-cpu -rwW --slowest --timeout=1200 -j0
build_macos:
name: 'macOS'
@ -106,7 +137,7 @@ jobs:
run: sudo ./.github/workflows/posix-deps-apt.sh
- name: 'Restore OpenSSL build'
id: cache-openssl
uses: actions/cache@v2.1.2
uses: actions/cache@v2.1.3
with:
path: ./multissl/openssl/${{ env.OPENSSL_VER }}
key: ${{ runner.os }}-multissl-openssl-${{ env.OPENSSL_VER }}

View File

@ -32,7 +32,7 @@ jobs:
run: sudo ./.github/workflows/posix-deps-apt.sh
- name: 'Restore OpenSSL build'
id: cache-openssl
uses: actions/cache@v2.1.2
uses: actions/cache@v2.1.3
with:
path: ./multissl/openssl/${{ env.OPENSSL_VER }}
key: ${{ runner.os }}-multissl-openssl-${{ env.OPENSSL_VER }}

View File

@ -36,9 +36,9 @@ jobs:
- name: 'Install build dependencies'
run: make -C Doc/ PYTHON=../python venv
- name: 'Build documentation'
run: xvfb-run make -C Doc/ PYTHON=../python SPHINXOPTS="-q -W --keep-going -j4" doctest suspicious html
run: xvfb-run make -C Doc/ PYTHON=../python SPHINXOPTS="-q -W --keep-going -j4" doctest html
- name: 'Upload'
uses: actions/upload-artifact@v2.2.0
uses: actions/upload-artifact@v2.2.1
with:
name: doc-html
path: Doc/build/html

19
.github/workflows/stale.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Mark stale pull requests
on:
schedule:
- cron: "0 0 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-pr-message: 'This PR is stale because it has been open for 30 days with no activity.'
stale-pr-label: 'stale'
days-before-stale: 30
days-before-close: -1

View File

@ -53,7 +53,7 @@ matrix:
- cd Doc
- make venv PYTHON=python
script:
- make check suspicious html SPHINXOPTS="-q -W -j4"
- make check html SPHINXOPTS="-q -W -j4"
- name: "Documentation tests"
os: linux
language: c
@ -192,6 +192,8 @@ script:
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ./python Tools/scripts/patchcheck.py --travis $TRAVIS_PULL_REQUEST; fi
# Check that all symbols exported by libpython start with "Py" or "_Py"
- make smelly
# Check that all symbols in the limited abi are present
- make check-limited-abi
# `-r -w` implicitly provided through `make buildbottest`.
- |
if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then

View File

@ -202,6 +202,7 @@ dist:
check:
$(PYTHON) tools/rstlint.py -i tools -i $(VENVDIR) -i README.rst
$(PYTHON) tools/rstlint.py ../Misc/NEWS.d/next/
serve:
$(PYTHON) ../Tools/scripts/serve.py build/html
@ -215,12 +216,11 @@ serve:
# for development releases: always build
autobuild-dev:
make dist SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A switchers=1'
-make suspicious
make dist SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1'
# for quick rebuilds (HTML only)
autobuild-dev-html:
make html SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A switchers=1'
make html SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1'
# for stable releases: only build if not in pre-release stage (alpha, beta)
# release candidate downloads are okay, since the stable tree can be in that stage

View File

@ -482,7 +482,8 @@ API Functions
*min* and no more than *max*; *min* and *max* may be equal. Additional
arguments must be passed to the function, each of which should be a pointer to a
:c:type:`PyObject*` variable; these will be filled in with the values from
*args*; they will contain borrowed references. The variables which correspond
*args*; they will contain :term:`borrowed references <borrowed reference>`.
The variables which correspond
to optional parameters not given by *args* will not be filled in; these should
be initialized by the caller. This function returns true on success and false if
*args* is not a tuple or contains the wrong number of elements; an exception

View File

@ -376,6 +376,12 @@ Process-wide parameters
The returned string points into static storage; the caller should not modify its
value.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. c:function:: wchar_t* Py_GetPrefix()
@ -389,6 +395,12 @@ Process-wide parameters
script at build time. The value is available to Python code as ``sys.prefix``.
It is only useful on Unix. See also the next function.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. c:function:: wchar_t* Py_GetExecPrefix()
@ -424,6 +436,12 @@ Process-wide parameters
while having :file:`/usr/local/plat` be a different filesystem for each
platform.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. c:function:: wchar_t* Py_GetProgramFullPath()
@ -437,6 +455,12 @@ Process-wide parameters
static storage; the caller should not modify its value. The value is available
to Python code as ``sys.executable``.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. c:function:: wchar_t* Py_GetPath()
@ -455,8 +479,14 @@ Process-wide parameters
can be (and usually is) modified later to change the search path for loading
modules.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. XXX should give the exact rules
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. c:function:: void Py_SetPath(const wchar_t *)
@ -638,6 +668,12 @@ Process-wide parameters
:c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
environment variable if it is set.
This function should not be called before :c:func:`Py_Initialize`, otherwise
it returns ``NULL``.
.. versionchanged:: 3.10
It now returns ``NULL`` if called before :c:func:`Py_Initialize`.
.. _threads:
@ -1077,7 +1113,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`.
Get the current frame of the Python thread state *tstate*.
Return a strong reference. Return ``NULL`` if no frame is currently
Return a :term:`strong reference`. Return ``NULL`` if no frame is currently
executing.
See also :c:func:`PyEval_GetFrame`.

View File

@ -8,46 +8,24 @@ Python Initialization Configuration
.. versionadded:: 3.8
Structures:
Python can be initialized with :c:func:`Py_InitializeFromConfig` and the
:c:type:`PyConfig` structure. It can be preinitialized with
:c:func:`Py_PreInitialize` and the :c:type:`PyPreConfig` structure.
* :c:type:`PyConfig`
* :c:type:`PyPreConfig`
* :c:type:`PyStatus`
* :c:type:`PyWideStringList`
There are two kinds of configuration:
Functions:
* The :ref:`Python Configuration <init-python-config>` can be used to build a
customized Python which behaves as the regular Python. For example,
environments variables and command line arguments are used to configure
Python.
* :c:func:`PyConfig_Clear`
* :c:func:`PyConfig_InitIsolatedConfig`
* :c:func:`PyConfig_InitPythonConfig`
* :c:func:`PyConfig_Read`
* :c:func:`PyConfig_SetArgv`
* :c:func:`PyConfig_SetBytesArgv`
* :c:func:`PyConfig_SetBytesString`
* :c:func:`PyConfig_SetString`
* :c:func:`PyConfig_SetWideStringList`
* :c:func:`PyPreConfig_InitIsolatedConfig`
* :c:func:`PyPreConfig_InitPythonConfig`
* :c:func:`PyStatus_Error`
* :c:func:`PyStatus_Exception`
* :c:func:`PyStatus_Exit`
* :c:func:`PyStatus_IsError`
* :c:func:`PyStatus_IsExit`
* :c:func:`PyStatus_NoMemory`
* :c:func:`PyStatus_Ok`
* :c:func:`PyWideStringList_Append`
* :c:func:`PyWideStringList_Insert`
* :c:func:`Py_ExitStatusException`
* :c:func:`Py_InitializeFromConfig`
* :c:func:`Py_PreInitialize`
* :c:func:`Py_PreInitializeFromArgs`
* :c:func:`Py_PreInitializeFromBytesArgs`
* :c:func:`Py_RunMain`
* :c:func:`Py_GetArgcArgv`
* The :ref:`Isolated Configuration <init-isolated-conf>` can be used to embed
Python into an application. It isolates Python from the system. For example,
environments variables are ignored, the LC_CTYPE locale is left unchanged and
no signal handler is registred.
The preconfiguration (``PyPreConfig`` type) is stored in
``_PyRuntime.preconfig`` and the configuration (``PyConfig`` type) is stored in
``PyInterpreterState.config``.
The :c:func:`Py_RunMain` function can be used to write a customized Python
program.
See also :ref:`Initialization, Finalization, and Threads <initialization>`.
@ -55,8 +33,47 @@ See also :ref:`Initialization, Finalization, and Threads <initialization>`.
:pep:`587` "Python Initialization Configuration".
Example
=======
Example of customized Python always running in isolated mode::
int main(int argc, char **argv)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
/* Decode command line arguments.
Implicitly preinitialize Python (in isolated mode). */
status = PyConfig_SetBytesArgv(&config, argc, argv);
if (PyStatus_Exception(status)) {
goto exception;
}
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return Py_RunMain();
exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
PyWideStringList
----------------
================
.. c:type:: PyWideStringList
@ -95,7 +112,7 @@ PyWideStringList
List items.
PyStatus
--------
========
.. c:type:: PyStatus
@ -128,6 +145,8 @@ PyStatus
Initialization error with a message.
*err_msg* must not be ``NULL``.
.. c:function:: PyStatus PyStatus_NoMemory(void)
Memory allocation failure (out of memory).
@ -185,7 +204,7 @@ Example::
PyPreConfig
-----------
===========
.. c:type:: PyPreConfig
@ -315,7 +334,7 @@ PyPreConfig
.. _c-preinit:
Preinitialize Python with PyPreConfig
-------------------------------------
=====================================
The preinitialization of Python:
@ -324,12 +343,17 @@ The preinitialization of Python:
* Set the :ref:`Python UTF-8 Mode <utf8-mode>`
(:c:member:`PyPreConfig.utf8_mode`)
The current preconfiguration (``PyPreConfig`` type) is stored in
``_PyRuntime.preconfig``.
Functions to preinitialize Python:
.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Preinitialize Python from *preconfig* preconfiguration.
*preconfig* must not be ``NULL``.
.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv)
Preinitialize Python from *preconfig* preconfiguration.
@ -337,6 +361,8 @@ Functions to preinitialize Python:
Parse *argv* command line arguments (bytes strings) if
:c:member:`~PyPreConfig.parse_argv` of *preconfig* is non-zero.
*preconfig* must not be ``NULL``.
.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv)
Preinitialize Python from *preconfig* preconfiguration.
@ -344,6 +370,8 @@ Functions to preinitialize Python:
Parse *argv* command line arguments (wide strings) if
:c:member:`~PyPreConfig.parse_argv` of *preconfig* is non-zero.
*preconfig* must not be ``NULL``.
The caller is responsible to handle exceptions (error or exit) using
:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`.
@ -386,7 +414,7 @@ the :ref:`Python UTF-8 Mode <utf8-mode>`::
PyConfig
--------
========
.. c:type:: PyConfig
@ -447,8 +475,20 @@ PyConfig
Fields which are already initialized are left unchanged.
The :c:func:`PyConfig_Read` function only parses
:c:member:`PyConfig.argv` arguments once: :c:member:`PyConfig.parse_argv`
is set to ``2`` after arguments are parsed. Since Python arguments are
strippped from :c:member:`PyConfig.argv`, parsing arguments twice would
parse the application options as Python options.
:ref:`Preinitialize Python <c-preinit>` if needed.
.. versionchanged:: 3.10
The :c:member:`PyConfig.argv` arguments are now only parsed once,
:c:member:`PyConfig.parse_argv` is set to ``2`` after arguments are
parsed, and arguments are only parsed if
:c:member:`PyConfig.parse_argv` equals ``1``.
.. c:function:: void PyConfig_Clear(PyConfig *config)
Release configuration memory.
@ -496,7 +536,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: wchar_t* base_executable
@ -508,7 +548,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: wchar_t* base_prefix
@ -516,7 +556,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: int buffered_stdio
@ -598,7 +638,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: wchar_t* executable
@ -607,7 +647,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: int faulthandler
@ -690,7 +730,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` input.
Part of the :ref:`Python Path Configuration <init-path-config>` input.
.. c:member:: int import_time
@ -781,7 +821,7 @@ PyConfig
Default: value of the ``PLATLIBDIR`` macro which is set at configure time
by ``--with-platlibdir`` (default: ``"lib"``).
Part of the :ref:`Path Configuration <init-path-config>` input.
Part of the :ref:`Python Path Configuration <init-path-config>` input.
.. versionadded:: 3.9
@ -794,7 +834,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` input.
Part of the :ref:`Python Path Configuration <init-path-config>` input.
.. c:member:: PyWideStringList module_search_paths
.. c:member:: int module_search_paths_set
@ -802,14 +842,14 @@ PyConfig
Module search paths: :data:`sys.path`.
If :c:member:`~PyConfig.module_search_paths_set` is equal to 0, the
function calculating the :ref:`Path Configuration <init-path-config>`
function calculating the :ref:`Python Path Configuration <init-path-config>`
overrides the :c:member:`~PyConfig.module_search_paths` and sets
:c:member:`~PyConfig.module_search_paths_set` to ``1``.
Default: empty list (``module_search_paths``) and ``0``
(``module_search_paths_set``).
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: int optimization_level
@ -831,7 +871,7 @@ PyConfig
If :c:member:`~PyConfig.orig_argv` list is empty and
:c:member:`~PyConfig.argv` is not a list only containing an empty
string, :c:func:`PyConfig_Read()` copies :c:member:`~PyConfig.argv` into
string, :c:func:`PyConfig_Read` copies :c:member:`~PyConfig.argv` into
:c:member:`~PyConfig.orig_argv` before modifying
:c:member:`~PyConfig.argv` (if :c:member:`~PyConfig.parse_argv` is
non-zero).
@ -847,12 +887,22 @@ PyConfig
Parse command line arguments?
If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular
If equals to ``1``, parse :c:member:`~PyConfig.argv` the same way the regular
Python parses :ref:`command line arguments <using-on-cmdline>`, and strip
Python arguments from :c:member:`~PyConfig.argv`.
The :c:func:`PyConfig_Read` function only parses
:c:member:`PyConfig.argv` arguments once: :c:member:`PyConfig.parse_argv`
is set to ``2`` after arguments are parsed. Since Python arguments are
strippped from :c:member:`PyConfig.argv`, parsing arguments twice would
parse the application options as Python options.
Default: ``1`` in Python mode, ``0`` in isolated mode.
.. versionchanged:: 3.10
The :c:member:`PyConfig.argv` arguments are now only parsed if
:c:member:`PyConfig.parse_argv` equals to ``1``.
.. c:member:: int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending
@ -865,7 +915,7 @@ PyConfig
.. c:member:: int pathconfig_warnings
On Unix, if non-zero, calculating the :ref:`Path Configuration
On Unix, if non-zero, calculating the :ref:`Python Path Configuration
<init-path-config>` can log warnings into ``stderr``. If equals to 0,
suppress these warnings.
@ -873,7 +923,7 @@ PyConfig
Default: ``1`` in Python mode, ``0`` in isolated mode.
Part of the :ref:`Path Configuration <init-path-config>` input.
Part of the :ref:`Python Path Configuration <init-path-config>` input.
.. c:member:: wchar_t* prefix
@ -882,7 +932,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` output.
Part of the :ref:`Python Path Configuration <init-path-config>` output.
.. c:member:: wchar_t* program_name
@ -900,7 +950,7 @@ PyConfig
Default: ``NULL``.
Part of the :ref:`Path Configuration <init-path-config>` input.
Part of the :ref:`Python Path Configuration <init-path-config>` input.
.. c:member:: wchar_t* pycache_prefix
@ -1106,7 +1156,7 @@ the :option:`-X` command line option.
Initialization with PyConfig
----------------------------
============================
Function to initialize Python:
@ -1121,6 +1171,9 @@ If :c:func:`PyImport_FrozenModules`, :c:func:`PyImport_AppendInittab` or
:c:func:`PyImport_ExtendInittab` are used, they must be set or called after
Python preinitialization and before the Python initialization.
The current configuration (``PyConfig`` type) is stored in
``PyInterpreterState.config``.
Example setting the program name::
void init_python(void)
@ -1134,17 +1187,17 @@ Example setting the program name::
status = PyConfig_SetString(&config, &config.program_name,
L"/path/to/my_program");
if (PyStatus_Exception(status)) {
goto fail;
goto exception;
}
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto fail;
goto exception;
}
PyConfig_Clear(&config);
return;
fail:
exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}
@ -1200,7 +1253,7 @@ configuration, and then override some parameters::
.. _init-isolated-conf:
Isolated Configuration
----------------------
======================
:c:func:`PyPreConfig_InitIsolatedConfig` and
:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to
@ -1213,7 +1266,7 @@ and user site directory. The C standard streams (ex: ``stdout``) and the
LC_CTYPE locale are left unchanged. Signal handlers are not installed.
Configuration files are still used with this configuration. Set the
:ref:`Path Configuration <init-path-config>` ("output fields") to ignore these
:ref:`Python Path Configuration <init-path-config>` ("output fields") to ignore these
configuration files and avoid the function computing the default path
configuration.
@ -1221,7 +1274,7 @@ configuration.
.. _init-python-config:
Python Configuration
--------------------
====================
:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig`
functions create a configuration to build a customized Python which behaves as
@ -1235,46 +1288,11 @@ and :ref:`Python UTF-8 Mode <utf8-mode>`
(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and
:envvar:`PYTHONCOERCECLOCALE` environment variables.
Example of customized Python always running in isolated mode::
int main(int argc, char **argv)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
/* Decode command line arguments.
Implicitly preinitialize Python (in isolated mode). */
status = PyConfig_SetBytesArgv(&config, argc, argv);
if (PyStatus_Exception(status)) {
goto fail;
}
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto fail;
}
PyConfig_Clear(&config);
return Py_RunMain();
fail:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
.. _init-path-config:
Path Configuration
------------------
Python Path Configuration
=========================
:c:type:`PyConfig` contains multiple fields for the path configuration:
@ -1354,7 +1372,7 @@ The ``__PYVENV_LAUNCHER__`` environment variable is used to set
Py_RunMain()
------------
============
.. c:function:: int Py_RunMain(void)
@ -1374,7 +1392,7 @@ customized Python always running in isolated mode using
Py_GetArgcArgv()
----------------
================
.. c:function:: void Py_GetArgcArgv(int *argc, wchar_t ***argv)
@ -1384,7 +1402,7 @@ Py_GetArgcArgv()
Multi-Phase Initialization Private Provisional API
--------------------------------------------------
==================================================
This section is a private provisional API introducing multi-phase
initialization, the core feature of the :pep:`432`:

View File

@ -326,7 +326,7 @@ when it's no longer needed---or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a *new* reference. When no ownership is transferred,
the caller is said to *borrow* the reference. Nothing needs to be done for a
borrowed reference.
:term:`borrowed reference`.
Conversely, when a calling function passes in a reference to an object, there
are two possibilities: the function *steals* a reference to the object, or it

View File

@ -264,7 +264,7 @@ of the following two module creation functions:
instead; only use this if you are sure you need it.
Before it is returned from in the initialization function, the resulting module
object is typically populated using functions like :c:func:`PyModule_AddObject`.
object is typically populated using functions like :c:func:`PyModule_AddObjectRef`.
.. _multi-phase-initialization:
@ -437,26 +437,102 @@ a function called from a module execution slot (if using multi-phase
initialization), can use the following functions to help initialize the module
state:
.. c:function:: int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Add an object to *module* as *name*. This is a convenience function which
can be used from the module's initialization function.
On success, return ``0``. On error, raise an exception and return ``-1``.
Return ``NULL`` if *value* is ``NULL``. It must be called with an exception
raised in this case.
Example usage::
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}
The example can also be written without checking explicitly if *obj* is
``NULL``::
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_XDECREF(obj);
return res;
}
Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in
this case, since *obj* can be ``NULL``.
.. versionadded:: 3.10
.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
Add an object to *module* as *name*. This is a convenience function which can
be used from the module's initialization function. This steals a reference to
*value* on success. Return ``-1`` on error, ``0`` on success.
Similar to :c:func:`PyModule_AddObjectRef`, but steals a reference to
*value* on success (if it returns ``0``).
The new :c:func:`PyModule_AddObjectRef` function is recommended, since it is
easy to introduce reference leaks by misusing the
:c:func:`PyModule_AddObject` function.
.. note::
Unlike other functions that steal references, ``PyModule_AddObject()`` only
decrements the reference count of *value* **on success**.
Unlike other functions that steal references, ``PyModule_AddObject()``
only decrements the reference count of *value* **on success**.
This means that its return value must be checked, and calling code must
:c:func:`Py_DECREF` *value* manually on error. Example usage::
:c:func:`Py_DECREF` *value* manually on error.
Example usage::
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_DECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
The example can also be written without checking explicitly if *obj* is
``NULL``::
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_XDECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in
this case, since *obj* can be ``NULL``.
Py_INCREF(spam);
if (PyModule_AddObject(module, "spam", spam) < 0) {
Py_DECREF(module);
Py_DECREF(spam);
return NULL;
}
.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)

View File

@ -13,8 +13,14 @@ objects.
.. c:function:: void Py_INCREF(PyObject *o)
Increment the reference count for object *o*. The object must not be ``NULL``; if
you aren't sure that it isn't ``NULL``, use :c:func:`Py_XINCREF`.
Increment the reference count for object *o*.
This function is usually used to convert a :term:`borrowed reference` to a
:term:`strong reference` in-place. The :c:func:`Py_NewRef` function can be
used to create a new :term:`strong reference`.
The object must not be ``NULL``; if you aren't sure that it isn't
``NULL``, use :c:func:`Py_XINCREF`.
.. c:function:: void Py_XINCREF(PyObject *o)
@ -22,13 +28,55 @@ objects.
Increment the reference count for object *o*. The object may be ``NULL``, in
which case the macro has no effect.
See also :c:func:`Py_XNewRef`.
.. c:function:: PyObject* Py_NewRef(PyObject *o)
Create a new :term:`strong reference` to an object: increment the reference
count of the object *o* and return the object *o*.
When the :term:`strong reference` is no longer needed, :c:func:`Py_DECREF`
should be called on it to decrement the object reference count.
The object *o* must not be ``NULL``; use :c:func:`Py_XNewRef` if *o* can be
``NULL``.
For example::
Py_INCREF(obj);
self->attr = obj;
can be written as::
self->attr = Py_NewRef(obj);
See also :c:func:`Py_INCREF`.
.. versionadded:: 3.10
.. c:function:: PyObject* Py_XNewRef(PyObject *o)
Similar to :c:func:`Py_NewRef`, but the object *o* can be NULL.
If the object *o* is ``NULL``, the function just returns ``NULL``.
.. versionadded:: 3.10
.. c:function:: void Py_DECREF(PyObject *o)
Decrement the reference count for object *o*. The object must not be ``NULL``; if
you aren't sure that it isn't ``NULL``, use :c:func:`Py_XDECREF`. If the reference
count reaches zero, the object's type's deallocation function (which must not be
``NULL``) is invoked.
Decrement the reference count for object *o*.
If the reference count reaches zero, the object's type's deallocation
function (which must not be ``NULL``) is invoked.
This function is usually used to delete a :term:`strong reference` before
exiting its scope.
The object must not be ``NULL``; if you aren't sure that it isn't ``NULL``,
use :c:func:`Py_XDECREF`.
.. warning::

View File

@ -35,7 +35,7 @@ Reflection
Get the *frame* next outer frame.
Return a strong reference, or ``NULL`` if *frame* has no outer frame.
Return a :term:`strong reference`, or ``NULL`` if *frame* has no outer frame.
*frame* must not be ``NULL``.
@ -46,7 +46,7 @@ Reflection
Get the *frame* code.
Return a strong reference.
Return a :term:`strong reference`.
*frame* must not be ``NULL``. The result (frame code) cannot be ``NULL``.

View File

@ -66,11 +66,9 @@ the definition of all other Python objects.
Get the type of the Python object *o*.
Return a borrowed reference.
Return a :term:`borrowed reference`.
.. versionchanged:: 3.10
:c:func:`Py_TYPE()` is changed to the inline static function.
Use :c:func:`Py_SET_TYPE()` to set an object type.
The :c:func:`Py_SET_TYPE` function must be used to set an object type.
.. c:function:: int Py_IS_TYPE(PyObject *o, PyTypeObject *type)
@ -108,9 +106,7 @@ the definition of all other Python objects.
Get the size of the Python object *o*.
.. versionchanged:: 3.10
:c:func:`Py_SIZE()` is changed to the inline static function.
Use :c:func:`Py_SET_SIZE()` to set an object size.
The :c:func:`Py_SET_SIZE` function must be used to set an object size.
.. c:function:: void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
@ -263,10 +259,12 @@ There are these calling conventions:
of :c:type:`PyObject*` values indicating the arguments and the third
parameter is the number of arguments (the length of the array).
This is not part of the :ref:`limited API <stable>`.
.. versionadded:: 3.7
.. versionchanged:: 3.10
``METH_FASTCALL`` is now part of the stable ABI.
.. data:: METH_FASTCALL | METH_KEYWORDS

View File

@ -57,7 +57,7 @@ Tuple Objects
.. c:function:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is
out of bounds, return ``NULL`` and set an :exc:`IndexError` exception.
negative or out of bounds, return ``NULL`` and set an :exc:`IndexError` exception.
.. c:function:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)

View File

@ -105,10 +105,12 @@ Type Objects
See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument.
An exception is raised if *type* is not a heap type.
.. versionadded:: 3.4
.. versionchanged:: 3.10
:c:func:`PyType_GetSlot` can now accept all types.
Previously, it was limited to heap types.
.. c:function:: PyObject* PyType_GetModule(PyTypeObject *type)
Return the module object associated with the given type when the type was
@ -152,10 +154,10 @@ The following functions and structs are used to create
Creates and returns a heap type object from the *spec*
(:const:`Py_TPFLAGS_HEAPTYPE`).
If *bases* is a tuple, the created heap type contains all types contained
in it as base types.
If *bases* is ``NULL``, the *Py_tp_base* slot is used instead.
The *bases* argument can be used to specify base classes; it can either
be only one class or a tuple of classes.
If *bases* is ``NULL``, the *Py_tp_bases* slot is used instead.
If that also is ``NULL``, the *Py_tp_base* slot is used instead.
If that also is ``NULL``, the new type derives from :class:`object`.
The *module* argument can be used to record the module in which the new
@ -169,6 +171,11 @@ The following functions and structs are used to create
.. versionadded:: 3.9
.. versionchanged:: 3.10
The function now accepts a single class as the *bases* argument and
``NULL`` as the ``tp_doc`` slot.
.. c:function:: PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Equivalent to ``PyType_FromModuleAndSpec(NULL, spec, bases)``.
@ -247,7 +254,8 @@ The following functions and structs are used to create
* :c:member:`~PyBufferProcs.bf_getbuffer`
* :c:member:`~PyBufferProcs.bf_releasebuffer`
Setting :c:data:`Py_tp_bases` may be problematic on some platforms.
Setting :c:data:`Py_tp_bases` or :c:data:`Py_tp_base` may be
problematic on some platforms.
To avoid issues, use the *bases* argument of
:py:func:`PyType_FromSpecWithBases` instead.
@ -260,4 +268,4 @@ The following functions and structs are used to create
The desired value of the slot. In most cases, this is a pointer
to a function.
May not be ``NULL``.
Slots other than ``Py_tp_doc`` may not be ``NULL``.

View File

@ -199,6 +199,8 @@ sub-slots
+---------------------------------------------------------+-----------------------------------+--------------+
| :c:member:`~PyAsyncMethods.am_anext` | :c:type:`unaryfunc` | __anext__ |
+---------------------------------------------------------+-----------------------------------+--------------+
| :c:member:`~PyAsyncMethods.am_send` | :c:type:`sendfunc` | |
+---------------------------------------------------------+-----------------------------------+--------------+
| |
+---------------------------------------------------------+-----------------------------------+--------------+
| :c:member:`~PyNumberMethods.nb_add` | :c:type:`binaryfunc` | __add__ |
@ -1168,6 +1170,14 @@ and :c:type:`PyType_Type` effectively act as defaults.)
.. versionadded:: 3.9
.. data:: Py_TPFLAGS_HAVE_AM_SEND
This bit is set when the :c:member:`~PyAsyncMethods.am_send` entry is present in the
:c:member:`~PyTypeObject.tp_as_async` slot of type structure.
.. versionadded:: 3.10
.. c:member:: const char* PyTypeObject.tp_doc
An optional pointer to a NUL-terminated C string giving the docstring for this
@ -1213,8 +1223,9 @@ and :c:type:`PyType_Type` effectively act as defaults.)
:func:`~gc.get_referents` function will include it.
.. warning::
When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members
that the instance *owns* (by having strong references to them) must be
When implementing :c:member:`~PyTypeObject.tp_traverse`, only the
members that the instance *owns* (by having :term:`strong references
<strong reference>` to them) must be
visited. For instance, if an object supports weak references via the
:c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
the linked list (what *tp_weaklist* points to) must **not** be
@ -2303,6 +2314,7 @@ Async Object Structures
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
.. c:member:: unaryfunc PyAsyncMethods.am_await
@ -2336,6 +2348,15 @@ Async Object Structures
Must return an :term:`awaitable` object. See :meth:`__anext__` for details.
This slot may be set to ``NULL``.
.. c:member:: sendfunc PyAsyncMethods.am_send
The signature of this function is::
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
See :c:func:`PyIter_Send` for details.
This slot may be set to ``NULL``.
.. _slot-typedefs:
@ -2431,6 +2452,10 @@ Slot Type typedefs
.. c:type:: PyObject *(*binaryfunc)(PyObject *, PyObject *)
.. c:type:: PySendResult (*sendfunc)(PyObject *, PyObject *, PyObject **)
See :c:member:`~PyAsyncMethods.am_send`.
.. c:type:: PyObject *(*ternaryfunc)(PyObject *, PyObject *, PyObject *)
.. c:type:: PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t)

View File

@ -57,10 +57,10 @@ as much as it can.
.. note::
This function returns a **borrowed reference** to the referenced object.
This function returns a :term:`borrowed reference` to the referenced object.
This means that you should always call :c:func:`Py_INCREF` on the object
except if you know that it cannot be destroyed while you are still
using it.
except when it cannot be destroyed before the last usage of the borrowed
reference.
.. c:function:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)

View File

@ -15,8 +15,7 @@ sys.path.append(os.path.abspath('includes'))
extensions = ['sphinx.ext.coverage', 'sphinx.ext.doctest',
'pyspecific', 'c_annotations', 'escape4chm',
'asdl_highlight', 'peg_highlight']
'asdl_highlight', 'peg_highlight', 'glossary_search']
doctest_global_setup = '''
try:

View File

@ -3007,6 +3007,9 @@ Py_GetVersion:const char*:::
Py_INCREF:void:::
Py_INCREF:PyObject*:o:+1:
Py_NewRef:void:::
Py_NewRef:PyObject*:o:+1:
Py_Initialize:void:::
Py_IsInitialized:int:::
@ -3028,6 +3031,9 @@ Py_XDECREF:PyObject*:o:-1:if o is not NULL
Py_XINCREF:void:::
Py_XINCREF:PyObject*:o:+1:if o is not NULL
Py_XNewRef:void:::
Py_XNewRef:PyObject*:o:+1:if o is not NULL
_PyImport_Fini:void:::
_PyObject_New:PyObject*::+1:

780
Doc/data/stable_abi.dat Normal file
View File

@ -0,0 +1,780 @@
# File generated by 'make regen-limited-abi'
# This is NOT an authoritative list of stable ABI symbols
PyArg_Parse
PyArg_ParseTuple
PyArg_ParseTupleAndKeywords
PyArg_UnpackTuple
PyArg_VaParse
PyArg_VaParseTupleAndKeywords
PyArg_ValidateKeywordArguments
PyBaseObject_Type
PyBool_FromLong
PyBool_Type
PyByteArrayIter_Type
PyByteArray_AsString
PyByteArray_Concat
PyByteArray_FromObject
PyByteArray_FromStringAndSize
PyByteArray_Resize
PyByteArray_Size
PyByteArray_Type
PyBytesIter_Type
PyBytes_AsString
PyBytes_AsStringAndSize
PyBytes_Concat
PyBytes_ConcatAndDel
PyBytes_DecodeEscape
PyBytes_FromFormat
PyBytes_FromFormatV
PyBytes_FromObject
PyBytes_FromString
PyBytes_FromStringAndSize
PyBytes_Repr
PyBytes_Size
PyBytes_Type
PyCFunction_Call
PyCFunction_GetFlags
PyCFunction_GetFunction
PyCFunction_GetSelf
PyCFunction_NewEx
PyCFunction_Type
PyCMethod_New
PyCallIter_New
PyCallIter_Type
PyCallable_Check
PyCapsule_GetContext
PyCapsule_GetDestructor
PyCapsule_GetName
PyCapsule_GetPointer
PyCapsule_Import
PyCapsule_IsValid
PyCapsule_New
PyCapsule_SetContext
PyCapsule_SetDestructor
PyCapsule_SetName
PyCapsule_SetPointer
PyCapsule_Type
PyClassMethodDescr_Type
PyCodec_BackslashReplaceErrors
PyCodec_Decode
PyCodec_Decoder
PyCodec_Encode
PyCodec_Encoder
PyCodec_IgnoreErrors
PyCodec_IncrementalDecoder
PyCodec_IncrementalEncoder
PyCodec_KnownEncoding
PyCodec_LookupError
PyCodec_NameReplaceErrors
PyCodec_Register
PyCodec_RegisterError
PyCodec_ReplaceErrors
PyCodec_StreamReader
PyCodec_StreamWriter
PyCodec_StrictErrors
PyCodec_Unregister
PyCodec_XMLCharRefReplaceErrors
PyComplex_FromDoubles
PyComplex_ImagAsDouble
PyComplex_RealAsDouble
PyComplex_Type
PyDescr_NewClassMethod
PyDescr_NewGetSet
PyDescr_NewMember
PyDescr_NewMethod
PyDictItems_Type
PyDictIterItem_Type
PyDictIterKey_Type
PyDictIterValue_Type
PyDictKeys_Type
PyDictProxy_New
PyDictProxy_Type
PyDictRevIterItem_Type
PyDictRevIterKey_Type
PyDictRevIterValue_Type
PyDictValues_Type
PyDict_Clear
PyDict_Contains
PyDict_Copy
PyDict_DelItem
PyDict_DelItemString
PyDict_GetItem
PyDict_GetItemString
PyDict_GetItemWithError
PyDict_Items
PyDict_Keys
PyDict_Merge
PyDict_MergeFromSeq2
PyDict_New
PyDict_Next
PyDict_SetItem
PyDict_SetItemString
PyDict_Size
PyDict_Type
PyDict_Update
PyDict_Values
PyEllipsis_Type
PyEnum_Type
PyErr_BadArgument
PyErr_BadInternalCall
PyErr_CheckSignals
PyErr_Clear
PyErr_Display
PyErr_ExceptionMatches
PyErr_Fetch
PyErr_Format
PyErr_FormatV
PyErr_GetExcInfo
PyErr_GivenExceptionMatches
PyErr_NewException
PyErr_NewExceptionWithDoc
PyErr_NoMemory
PyErr_NormalizeException
PyErr_Occurred
PyErr_Print
PyErr_PrintEx
PyErr_ProgramText
PyErr_ResourceWarning
PyErr_Restore
PyErr_SetExcInfo
PyErr_SetFromErrno
PyErr_SetFromErrnoWithFilename
PyErr_SetFromErrnoWithFilenameObject
PyErr_SetFromErrnoWithFilenameObjects
PyErr_SetImportError
PyErr_SetImportErrorSubclass
PyErr_SetInterrupt
PyErr_SetNone
PyErr_SetObject
PyErr_SetString
PyErr_SyntaxLocation
PyErr_SyntaxLocationEx
PyErr_WarnEx
PyErr_WarnExplicit
PyErr_WarnFormat
PyErr_WriteUnraisable
PyEval_AcquireLock
PyEval_AcquireThread
PyEval_CallFunction
PyEval_CallMethod
PyEval_CallObjectWithKeywords
PyEval_EvalCode
PyEval_EvalCodeEx
PyEval_EvalFrame
PyEval_EvalFrameEx
PyEval_GetBuiltins
PyEval_GetFrame
PyEval_GetFuncDesc
PyEval_GetFuncName
PyEval_GetGlobals
PyEval_GetLocals
PyEval_InitThreads
PyEval_ReleaseLock
PyEval_ReleaseThread
PyEval_RestoreThread
PyEval_SaveThread
PyEval_ThreadsInitialized
PyExc_ArithmeticError
PyExc_AssertionError
PyExc_AttributeError
PyExc_BaseException
PyExc_BlockingIOError
PyExc_BrokenPipeError
PyExc_BufferError
PyExc_BytesWarning
PyExc_ChildProcessError
PyExc_ConnectionAbortedError
PyExc_ConnectionError
PyExc_ConnectionRefusedError
PyExc_ConnectionResetError
PyExc_DeprecationWarning
PyExc_EOFError
PyExc_EnvironmentError
PyExc_Exception
PyExc_FileExistsError
PyExc_FileNotFoundError
PyExc_FloatingPointError
PyExc_FutureWarning
PyExc_GeneratorExit
PyExc_IOError
PyExc_ImportError
PyExc_ImportWarning
PyExc_IndentationError
PyExc_IndexError
PyExc_InterruptedError
PyExc_IsADirectoryError
PyExc_KeyError
PyExc_KeyboardInterrupt
PyExc_LookupError
PyExc_MemoryError
PyExc_ModuleNotFoundError
PyExc_NameError
PyExc_NotADirectoryError
PyExc_NotImplementedError
PyExc_OSError
PyExc_OverflowError
PyExc_PendingDeprecationWarning
PyExc_PermissionError
PyExc_ProcessLookupError
PyExc_RecursionError
PyExc_ReferenceError
PyExc_ResourceWarning
PyExc_RuntimeError
PyExc_RuntimeWarning
PyExc_StopAsyncIteration
PyExc_StopIteration
PyExc_SyntaxError
PyExc_SyntaxWarning
PyExc_SystemError
PyExc_SystemExit
PyExc_TabError
PyExc_TimeoutError
PyExc_TypeError
PyExc_UnboundLocalError
PyExc_UnicodeDecodeError
PyExc_UnicodeEncodeError
PyExc_UnicodeError
PyExc_UnicodeTranslateError
PyExc_UnicodeWarning
PyExc_UserWarning
PyExc_ValueError
PyExc_Warning
PyExc_ZeroDivisionError
PyExceptionClass_Name
PyException_GetCause
PyException_GetContext
PyException_GetTraceback
PyException_SetCause
PyException_SetContext
PyException_SetTraceback
PyFile_FromFd
PyFile_GetLine
PyFile_WriteObject
PyFile_WriteString
PyFilter_Type
PyFloat_AsDouble
PyFloat_FromDouble
PyFloat_FromString
PyFloat_GetInfo
PyFloat_GetMax
PyFloat_GetMin
PyFloat_Type
PyFrame_GetCode
PyFrame_GetLineNumber
PyFrozenSet_New
PyFrozenSet_Type
PyGC_Collect
PyGILState_Ensure
PyGILState_GetThisThreadState
PyGILState_Release
PyGetSetDescr_Type
PyImport_AddModule
PyImport_AddModuleObject
PyImport_AppendInittab
PyImport_ExecCodeModule
PyImport_ExecCodeModuleEx
PyImport_ExecCodeModuleObject
PyImport_ExecCodeModuleWithPathnames
PyImport_GetImporter
PyImport_GetMagicNumber
PyImport_GetMagicTag
PyImport_GetModule
PyImport_GetModuleDict
PyImport_Import
PyImport_ImportFrozenModule
PyImport_ImportFrozenModuleObject
PyImport_ImportModule
PyImport_ImportModuleLevel
PyImport_ImportModuleLevelObject
PyImport_ImportModuleNoBlock
PyImport_ReloadModule
PyIndex_Check
PyInterpreterState_Clear
PyInterpreterState_Delete
PyInterpreterState_Get
PyInterpreterState_GetDict
PyInterpreterState_GetID
PyInterpreterState_New
PyIter_Check
PyIter_Next
PyIter_Send
PyListIter_Type
PyListRevIter_Type
PyList_Append
PyList_AsTuple
PyList_GetItem
PyList_GetSlice
PyList_Insert
PyList_New
PyList_Reverse
PyList_SetItem
PyList_SetSlice
PyList_Size
PyList_Sort
PyList_Type
PyLongRangeIter_Type
PyLong_AsDouble
PyLong_AsLong
PyLong_AsLongAndOverflow
PyLong_AsLongLong
PyLong_AsLongLongAndOverflow
PyLong_AsSize_t
PyLong_AsSsize_t
PyLong_AsUnsignedLong
PyLong_AsUnsignedLongLong
PyLong_AsUnsignedLongLongMask
PyLong_AsUnsignedLongMask
PyLong_AsVoidPtr
PyLong_FromDouble
PyLong_FromLong
PyLong_FromLongLong
PyLong_FromSize_t
PyLong_FromSsize_t
PyLong_FromString
PyLong_FromUnsignedLong
PyLong_FromUnsignedLongLong
PyLong_FromVoidPtr
PyLong_GetInfo
PyLong_Type
PyMap_Type
PyMapping_Check
PyMapping_GetItemString
PyMapping_HasKey
PyMapping_HasKeyString
PyMapping_Items
PyMapping_Keys
PyMapping_Length
PyMapping_SetItemString
PyMapping_Size
PyMapping_Values
PyMarshal_ReadObjectFromString
PyMarshal_WriteLongToFile
PyMarshal_WriteObjectToFile
PyMarshal_WriteObjectToString
PyMem_Free
PyMem_Malloc
PyMem_Realloc
PyMemberDescr_Type
PyMember_GetOne
PyMember_SetOne
PyMemoryView_FromMemory
PyMemoryView_FromObject
PyMemoryView_GetContiguous
PyMemoryView_Type
PyMethodDescr_Type
PyModuleDef_Init
PyModuleDef_Type
PyModule_AddFunctions
PyModule_AddIntConstant
PyModule_AddObject
PyModule_AddObjectRef
PyModule_AddStringConstant
PyModule_AddType
PyModule_Create2
PyModule_ExecDef
PyModule_FromDefAndSpec2
PyModule_GetDef
PyModule_GetDict
PyModule_GetFilename
PyModule_GetFilenameObject
PyModule_GetName
PyModule_GetNameObject
PyModule_GetState
PyModule_New
PyModule_NewObject
PyModule_SetDocString
PyModule_Type
PyNumber_Absolute
PyNumber_Add
PyNumber_And
PyNumber_AsSsize_t
PyNumber_Check
PyNumber_Divmod
PyNumber_Float
PyNumber_FloorDivide
PyNumber_InPlaceAdd
PyNumber_InPlaceAnd
PyNumber_InPlaceFloorDivide
PyNumber_InPlaceLshift
PyNumber_InPlaceMatrixMultiply
PyNumber_InPlaceMultiply
PyNumber_InPlaceOr
PyNumber_InPlacePower
PyNumber_InPlaceRemainder
PyNumber_InPlaceRshift
PyNumber_InPlaceSubtract
PyNumber_InPlaceTrueDivide
PyNumber_InPlaceXor
PyNumber_Index
PyNumber_Invert
PyNumber_Long
PyNumber_Lshift
PyNumber_MatrixMultiply
PyNumber_Multiply
PyNumber_Negative
PyNumber_Or
PyNumber_Positive
PyNumber_Power
PyNumber_Remainder
PyNumber_Rshift
PyNumber_Subtract
PyNumber_ToBase
PyNumber_TrueDivide
PyNumber_Xor
PyOS_AfterFork
PyOS_AfterFork_Child
PyOS_AfterFork_Parent
PyOS_BeforeFork
PyOS_FSPath
PyOS_InterruptOccurred
PyOS_double_to_string
PyOS_getsig
PyOS_mystricmp
PyOS_mystrnicmp
PyOS_setsig
PyOS_snprintf
PyOS_string_to_double
PyOS_strtol
PyOS_strtoul
PyOS_vsnprintf
PyObject_ASCII
PyObject_AsFileDescriptor
PyObject_Bytes
PyObject_Call
PyObject_CallFunction
PyObject_CallFunctionObjArgs
PyObject_CallMethod
PyObject_CallMethodObjArgs
PyObject_CallNoArgs
PyObject_CallObject
PyObject_Calloc
PyObject_ClearWeakRefs
PyObject_DelItem
PyObject_DelItemString
PyObject_Dir
PyObject_Format
PyObject_Free
PyObject_GC_Del
PyObject_GC_IsFinalized
PyObject_GC_IsTracked
PyObject_GC_Track
PyObject_GC_UnTrack
PyObject_GenericGetAttr
PyObject_GenericGetDict
PyObject_GenericSetAttr
PyObject_GenericSetDict
PyObject_GetAttr
PyObject_GetAttrString
PyObject_GetItem
PyObject_GetIter
PyObject_HasAttr
PyObject_HasAttrString
PyObject_Hash
PyObject_HashNotImplemented
PyObject_Init
PyObject_InitVar
PyObject_IsInstance
PyObject_IsSubclass
PyObject_IsTrue
PyObject_Length
PyObject_Malloc
PyObject_Not
PyObject_Realloc
PyObject_Repr
PyObject_RichCompare
PyObject_RichCompareBool
PyObject_SelfIter
PyObject_SetAttr
PyObject_SetAttrString
PyObject_SetItem
PyObject_Size
PyObject_Str
PyObject_Type
PyProperty_Type
PyRangeIter_Type
PyRange_Type
PyReversed_Type
PySeqIter_New
PySeqIter_Type
PySequence_Check
PySequence_Concat
PySequence_Contains
PySequence_Count
PySequence_DelItem
PySequence_DelSlice
PySequence_Fast
PySequence_GetItem
PySequence_GetSlice
PySequence_In
PySequence_InPlaceConcat
PySequence_InPlaceRepeat
PySequence_Index
PySequence_Length
PySequence_List
PySequence_Repeat
PySequence_SetItem
PySequence_SetSlice
PySequence_Size
PySequence_Tuple
PySetIter_Type
PySet_Add
PySet_Clear
PySet_Contains
PySet_Discard
PySet_New
PySet_Pop
PySet_Size
PySet_Type
PySlice_AdjustIndices
PySlice_GetIndices
PySlice_GetIndicesEx
PySlice_New
PySlice_Type
PySlice_Unpack
PyState_AddModule
PyState_FindModule
PyState_RemoveModule
PyStructSequence_GetItem
PyStructSequence_New
PyStructSequence_NewType
PyStructSequence_SetItem
PySuper_Type
PySys_AddWarnOption
PySys_AddWarnOptionUnicode
PySys_AddXOption
PySys_FormatStderr
PySys_FormatStdout
PySys_GetObject
PySys_GetXOptions
PySys_HasWarnOptions
PySys_ResetWarnOptions
PySys_SetArgv
PySys_SetArgvEx
PySys_SetObject
PySys_SetPath
PySys_WriteStderr
PySys_WriteStdout
PyThreadState_Clear
PyThreadState_Delete
PyThreadState_Get
PyThreadState_GetDict
PyThreadState_GetFrame
PyThreadState_GetID
PyThreadState_GetInterpreter
PyThreadState_New
PyThreadState_SetAsyncExc
PyThreadState_Swap
PyThread_GetInfo
PyThread_ReInitTLS
PyThread_acquire_lock
PyThread_acquire_lock_timed
PyThread_allocate_lock
PyThread_create_key
PyThread_delete_key
PyThread_delete_key_value
PyThread_exit_thread
PyThread_free_lock
PyThread_get_key_value
PyThread_get_stacksize
PyThread_get_thread_ident
PyThread_get_thread_native_id
PyThread_init_thread
PyThread_release_lock
PyThread_set_key_value
PyThread_set_stacksize
PyThread_start_new_thread
PyThread_tss_alloc
PyThread_tss_create
PyThread_tss_delete
PyThread_tss_free
PyThread_tss_get
PyThread_tss_is_created
PyThread_tss_set
PyTraceBack_Here
PyTraceBack_Print
PyTraceBack_Type
PyTupleIter_Type
PyTuple_GetItem
PyTuple_GetSlice
PyTuple_New
PyTuple_Pack
PyTuple_SetItem
PyTuple_Size
PyTuple_Type
PyType_ClearCache
PyType_FromModuleAndSpec
PyType_FromSpec
PyType_FromSpecWithBases
PyType_GenericAlloc
PyType_GenericNew
PyType_GetFlags
PyType_GetModule
PyType_GetModuleState
PyType_GetSlot
PyType_IsSubtype
PyType_Modified
PyType_Ready
PyType_Type
PyUnicodeDecodeError_Create
PyUnicodeDecodeError_GetEncoding
PyUnicodeDecodeError_GetEnd
PyUnicodeDecodeError_GetObject
PyUnicodeDecodeError_GetReason
PyUnicodeDecodeError_GetStart
PyUnicodeDecodeError_SetEnd
PyUnicodeDecodeError_SetReason
PyUnicodeDecodeError_SetStart
PyUnicodeEncodeError_GetEncoding
PyUnicodeEncodeError_GetEnd
PyUnicodeEncodeError_GetObject
PyUnicodeEncodeError_GetReason
PyUnicodeEncodeError_GetStart
PyUnicodeEncodeError_SetEnd
PyUnicodeEncodeError_SetReason
PyUnicodeEncodeError_SetStart
PyUnicodeIter_Type
PyUnicodeTranslateError_GetEnd
PyUnicodeTranslateError_GetObject
PyUnicodeTranslateError_GetReason
PyUnicodeTranslateError_GetStart
PyUnicodeTranslateError_SetEnd
PyUnicodeTranslateError_SetReason
PyUnicodeTranslateError_SetStart
PyUnicode_Append
PyUnicode_AppendAndDel
PyUnicode_AsASCIIString
PyUnicode_AsCharmapString
PyUnicode_AsDecodedObject
PyUnicode_AsDecodedUnicode
PyUnicode_AsEncodedObject
PyUnicode_AsEncodedString
PyUnicode_AsEncodedUnicode
PyUnicode_AsLatin1String
PyUnicode_AsRawUnicodeEscapeString
PyUnicode_AsUCS4
PyUnicode_AsUCS4Copy
PyUnicode_AsUTF16String
PyUnicode_AsUTF32String
PyUnicode_AsUTF8AndSize
PyUnicode_AsUTF8String
PyUnicode_AsUnicodeEscapeString
PyUnicode_AsWideChar
PyUnicode_AsWideCharString
PyUnicode_BuildEncodingMap
PyUnicode_Compare
PyUnicode_CompareWithASCIIString
PyUnicode_Concat
PyUnicode_Contains
PyUnicode_Count
PyUnicode_Decode
PyUnicode_DecodeASCII
PyUnicode_DecodeCharmap
PyUnicode_DecodeFSDefault
PyUnicode_DecodeFSDefaultAndSize
PyUnicode_DecodeLatin1
PyUnicode_DecodeLocale
PyUnicode_DecodeLocaleAndSize
PyUnicode_DecodeRawUnicodeEscape
PyUnicode_DecodeUTF16
PyUnicode_DecodeUTF16Stateful
PyUnicode_DecodeUTF32
PyUnicode_DecodeUTF32Stateful
PyUnicode_DecodeUTF7
PyUnicode_DecodeUTF7Stateful
PyUnicode_DecodeUTF8
PyUnicode_DecodeUTF8Stateful
PyUnicode_DecodeUnicodeEscape
PyUnicode_EncodeFSDefault
PyUnicode_EncodeLocale
PyUnicode_FSConverter
PyUnicode_FSDecoder
PyUnicode_Find
PyUnicode_FindChar
PyUnicode_Format
PyUnicode_FromEncodedObject
PyUnicode_FromFormat
PyUnicode_FromFormatV
PyUnicode_FromObject
PyUnicode_FromOrdinal
PyUnicode_FromString
PyUnicode_FromStringAndSize
PyUnicode_FromWideChar
PyUnicode_GetDefaultEncoding
PyUnicode_GetLength
PyUnicode_GetSize
PyUnicode_InternFromString
PyUnicode_InternImmortal
PyUnicode_InternInPlace
PyUnicode_IsIdentifier
PyUnicode_Join
PyUnicode_Partition
PyUnicode_RPartition
PyUnicode_RSplit
PyUnicode_ReadChar
PyUnicode_Replace
PyUnicode_Resize
PyUnicode_RichCompare
PyUnicode_Split
PyUnicode_Splitlines
PyUnicode_Substring
PyUnicode_Tailmatch
PyUnicode_Translate
PyUnicode_Type
PyUnicode_WriteChar
PyWeakref_GetObject
PyWeakref_NewProxy
PyWeakref_NewRef
PyWrapperDescr_Type
PyWrapper_New
PyZip_Type
Py_AddPendingCall
Py_AtExit
Py_BuildValue
Py_BytesMain
Py_CompileString
Py_DecRef
Py_DecodeLocale
Py_EncodeLocale
Py_EndInterpreter
Py_EnterRecursiveCall
Py_Exit
Py_FatalError
Py_FileSystemDefaultEncodeErrors
Py_FileSystemDefaultEncoding
Py_Finalize
Py_FinalizeEx
Py_FrozenMain
Py_GenericAlias
Py_GenericAliasType
Py_GetBuildInfo
Py_GetCompiler
Py_GetCopyright
Py_GetExecPrefix
Py_GetPath
Py_GetPlatform
Py_GetPrefix
Py_GetProgramFullPath
Py_GetProgramName
Py_GetPythonHome
Py_GetRecursionLimit
Py_GetVersion
Py_HasFileSystemDefaultEncoding
Py_IncRef
Py_Initialize
Py_InitializeEx
Py_IsInitialized
Py_LeaveRecursiveCall
Py_Main
Py_MakePendingCalls
Py_NewInterpreter
Py_NewRef
Py_ReprEnter
Py_ReprLeave
Py_SetPath
Py_SetProgramName
Py_SetPythonHome
Py_SetRecursionLimit
Py_SymtableString
Py_UTF8Mode
Py_VaBuildValue
Py_XNewRef

View File

@ -158,6 +158,18 @@ Glossary
See also :term:`text file` for a file object able to read and write
:class:`str` objects.
borrowed reference
In Python's C API, a borrowed reference is a reference to an object.
It does not modify the object reference count. It becomes a dangling
pointer if the object is destroyed. For example, a garbage collection can
remove the last :term:`strong reference` to the object and so destroy it.
Calling :c:func:`Py_INCREF` on the :term:`borrowed reference` is
recommended to convert it to a :term:`strong reference` in-place, except
when the object cannot be destroyed before the last usage of the borrowed
reference. The :c:func:`Py_NewRef` function can be used to create a new
:term:`strong reference`.
bytes-like object
An object that supports the :ref:`bufferobjects` and can
export a C-:term:`contiguous` buffer. This includes all :class:`bytes`,
@ -1100,6 +1112,18 @@ Glossary
an :term:`expression` or one of several constructs with a keyword, such
as :keyword:`if`, :keyword:`while` or :keyword:`for`.
strong reference
In Python's C API, a strong reference is a reference to an object
which increments the object's reference count when it is created and
decrements the object's reference count when it is deleted.
The :c:func:`Py_NewRef` function can be used to create a strong reference
to an object. Usually, the :c:func:`Py_DECREF` function must be called on
the strong reference before exiting the scope of the strong reference, to
avoid leaking one reference.
See also :term:`borrowed reference`.
text encoding
A codec which encodes Unicode strings to bytes.

View File

@ -83,7 +83,7 @@ Following is a result of running the code:
$ python3 prog.py --help
usage: prog.py [-h]
optional arguments:
options:
-h, --help show this help message and exit
$ python3 prog.py --verbose
usage: prog.py [-h]
@ -130,7 +130,7 @@ And running the code:
positional arguments:
echo
optional arguments:
options:
-h, --help show this help message and exit
$ python3 prog.py foo
foo
@ -172,7 +172,7 @@ And we get:
positional arguments:
echo echo the string you use here
optional arguments:
options:
-h, --help show this help message and exit
Now, how about doing something even more useful::
@ -241,7 +241,7 @@ And the output:
$ python3 prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]
optional arguments:
options:
-h, --help show this help message and exit
--verbosity VERBOSITY
increase output verbosity
@ -289,7 +289,7 @@ And the output:
$ python3 prog.py --help
usage: prog.py [-h] [--verbose]
optional arguments:
options:
-h, --help show this help message and exit
--verbose increase output verbosity
@ -332,7 +332,7 @@ And here goes:
$ python3 prog.py --help
usage: prog.py [-h] [-v]
optional arguments:
options:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
@ -440,7 +440,7 @@ And the output:
positional arguments:
square display a square of a given number
optional arguments:
options:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity
@ -468,7 +468,8 @@ verbosity argument (check the output of ``python --help``)::
print(answer)
We have introduced another action, "count",
to count the number of occurrences of a specific optional arguments:
to count the number of occurrences of specific options.
.. code-block:: shell-session
@ -489,7 +490,7 @@ to count the number of occurrences of a specific optional arguments:
positional arguments:
square display a square of a given number
optional arguments:
options:
-h, --help show this help message and exit
-v, --verbosity increase output verbosity
$ python3 prog.py 4 -vvv
@ -626,7 +627,7 @@ Output:
x the base
y the exponent
optional arguments:
options:
-h, --help show this help message and exit
-v, --verbosity
$ python3 prog.py 4 2 -v
@ -750,7 +751,7 @@ but not both at the same time:
x the base
y the exponent
optional arguments:
options:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet

File diff suppressed because it is too large Load Diff

View File

@ -336,6 +336,7 @@ The :mod:`abc` module also provides the following functions:
.. versionadded:: 3.4
.. function:: update_abstractmethods(cls)
A function to recalculate an abstract class's abstraction status. This
function should be called if a class's abstract methods have been
implemented or changed after it was created. Usually, this function should
@ -343,7 +344,7 @@ The :mod:`abc` module also provides the following functions:
Returns *cls*, to allow usage as a class decorator.
If *cls* is not an instance of ABCMeta, does nothing.
If *cls* is not an instance of :class:`ABCMeta`, does nothing.
.. note::

View File

@ -57,7 +57,7 @@ be run at the command line and provides useful help messages:
positional arguments:
N an integer for the accumulator
optional arguments:
options:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
@ -217,14 +217,14 @@ The help for this program will display ``myprogram.py`` as the program name
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO foo help
$ cd ..
$ python subdir/myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO foo help
@ -235,7 +235,7 @@ To change this default behavior, another value can be supplied using the
>>> parser.print_help()
usage: myprogram [-h]
optional arguments:
options:
-h, --help show this help message and exit
Note that the program name, whether determined from ``sys.argv[0]`` or from the
@ -249,7 +249,7 @@ specifier.
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO foo of the myprogram program
@ -269,7 +269,7 @@ arguments it contains::
positional arguments:
bar bar help
optional arguments:
options:
-h, --help show this help message and exit
--foo [FOO] foo help
@ -284,7 +284,7 @@ The default message can be overridden with the ``usage=`` keyword argument::
positional arguments:
bar bar help
optional arguments:
options:
-h, --help show this help message and exit
--foo [FOO] foo help
@ -307,7 +307,7 @@ various arguments::
A foo that bars
optional arguments:
options:
-h, --help show this help message and exit
By default, the description will be line-wrapped so that it fits within the
@ -329,7 +329,7 @@ argument to :class:`ArgumentParser`::
A foo that bars
optional arguments:
options:
-h, --help show this help message and exit
And that's how you'd foo a bar
@ -403,7 +403,7 @@ epilog_ texts in command-line help messages::
this description was indented weird but that is okay
optional arguments:
options:
-h, --help show this help message and exit
likewise for this epilog whose whitespace will be cleaned up and whose words
@ -432,7 +432,7 @@ should not be line-wrapped::
exactly the way
I want it
optional arguments:
options:
-h, --help show this help message and exit
:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
@ -454,7 +454,7 @@ default values to each of the argument help messages::
positional arguments:
bar BAR! (default: [1, 2, 3])
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO FOO! (default: 42)
@ -473,7 +473,7 @@ as the regular formatter does)::
positional arguments:
float
optional arguments:
options:
-h, --help show this help message and exit
--foo int
@ -592,7 +592,7 @@ older arguments with the same option string. To get this behavior, the value
>>> parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]
optional arguments:
options:
-h, --help show this help message and exit
-f FOO old foo help
--foo FOO new foo help
@ -623,7 +623,7 @@ help will be printed:
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO foo help
@ -636,7 +636,7 @@ This can be achieved by passing ``False`` as the ``add_help=`` argument to
>>> parser.print_help()
usage: PROG [--foo FOO]
optional arguments:
options:
--foo FOO foo help
The help option is typically ``-h/--help``. The exception to this is
@ -649,7 +649,7 @@ the help options::
>>> parser.print_help()
usage: PROG [+h]
optional arguments:
options:
+h, ++help show this help message and exit
@ -696,7 +696,7 @@ The add_argument() method
* const_ - A constant value required by some action_ and nargs_ selections.
* default_ - The value produced if the argument is absent from the
command line.
command line and if it is absent from the namespace object.
* type_ - The type to which the command-line argument should be converted.
@ -1006,6 +1006,14 @@ was not present at the command line::
>>> parser.parse_args([])
Namespace(foo=42)
If the target namespace already has an attribute set, the action *default*
will not over write it::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
Namespace(foo=101)
If the ``default`` value is a string, the parser parses the value as if it
were a command-line argument. In particular, the parser applies any type_
conversion argument, if provided, before setting the attribute on the
@ -1042,63 +1050,70 @@ command-line argument was not present::
type
^^^^
By default, :class:`ArgumentParser` objects read command-line arguments in as simple
By default, the parser reads command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, like a :class:`float` or :class:`int`. The
``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
necessary type-checking and type conversions to be performed. Common built-in
types and functions can be used directly as the value of the ``type`` argument::
interpreted as another type, such as a :class:`float` or :class:`int`. The
``type`` keyword for :meth:`~ArgumentParser.add_argument` allows any
necessary type-checking and type conversions to be performed.
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
If the type_ keyword is used with the default_ keyword, the type converter
is only applied if the default is a string.
See the section on the default_ keyword argument for information on when the
``type`` argument is applied to default arguments.
The argument to ``type`` can be any callable that accepts a single string.
If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or
:exc:`ValueError`, the exception is caught and a nicely formatted error
message is displayed. No other exception types are handled.
To ease the use of various types of files, the argparse module provides the
factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
``errors=`` arguments of the :func:`open` function. For example,
``FileType('w')`` can be used to create a writable file::
Common built-in types and functions can be used as type converters:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar', type=argparse.FileType('w'))
>>> parser.parse_args(['out.txt'])
Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
.. testcode::
``type=`` can take any callable that takes a single string argument and returns
the converted value::
import argparse
import pathlib
>>> def perfect_square(string):
... value = int(string)
... sqrt = math.sqrt(value)
... if sqrt != int(sqrt):
... msg = "%r is not a perfect square" % string
... raise argparse.ArgumentTypeError(msg)
... return value
parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
parser.add_argument('datapath', type=pathlib.Path)
User defined functions can be used as well:
.. doctest::
>>> def hyphenated(string):
... return '-'.join([word[:4] for word in string.casefold().split()])
...
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=perfect_square)
>>> parser.parse_args(['9'])
Namespace(foo=9)
>>> parser.parse_args(['7'])
usage: PROG [-h] foo
PROG: error: argument foo: '7' is not a perfect square
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument('short_title', type=hyphenated)
>>> parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')
The choices_ keyword argument may be more convenient for type checkers that
simply check against a range of values::
The :func:`bool` function is not recommended as a type converter. All it does
is convert empty strings to ``False`` and non-empty strings to ``True``.
This is usually not what is desired.
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=int, choices=range(5, 10))
>>> parser.parse_args(['7'])
Namespace(foo=7)
>>> parser.parse_args(['11'])
usage: PROG [-h] {5,6,7,8,9}
PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
In general, the ``type`` keyword is a convenience that should only be used for
simple conversions that can only raise one of the three supported exceptions.
Anything with more interesting error-handling or resource management should be
done downstream after the arguments are parsed.
See the choices_ section for more details.
For example, JSON or YAML conversions have complex error cases that require
better reporting than can be given by the ``type`` keyword. An
:exc:`~json.JSONDecodeError` would not be well formatted and a
:exc:`FileNotFound` exception would not be handled at all.
Even :class:`~argparse.FileType` has its limitations for use with the ``type``
keyword. If one argument uses *FileType* and then a subsequent argument fails,
an error is reported but the file is not automatically closed. In this case, it
would be better to wait until after the parser has run and then use the
:keyword:`with`-statement to manage the files.
For type checkers that simply check against a fixed set of values, consider
using the choices_ keyword instead.
choices
@ -1133,20 +1148,14 @@ container should match the type_ specified::
Any container can be passed as the *choices* value, so :class:`list` objects,
:class:`set` objects, and custom containers are all supported.
This includes :class:`enum.Enum`, which could be used to restrain
argument's choices; if we reuse previous rock/paper/scissors game example,
this could be as follows::
>>> from enum import Enum
>>> class GameMove(Enum):
... ROCK = 'rock'
... PAPER = 'paper'
... SCISSORS = 'scissors'
...
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', type=GameMove, choices=GameMove)
>>> parser.parse_args(['rock'])
Namespace(move=<GameMove.ROCK: 'rock'>)
Use of :class:`enum.Enum` is not recommended because it is difficult to
control its appearance in usage, help, and error messages.
Formatted choices overrides the default *metavar* which is normally derived
from *dest*. This is usually what you want because the user never sees the
*dest* parameter. If this display isn't desirable (perhaps because there are
many choices), just specify an explicit metavar_.
required
@ -1194,7 +1203,7 @@ argument::
positional arguments:
bar one of the bars to be frobbled
optional arguments:
options:
-h, --help show this help message and exit
--foo foo the bars before frobbling
@ -1212,7 +1221,7 @@ specifiers include the program name, ``%(prog)s`` and most keyword arguments to
positional arguments:
bar the bar to frobble (default: 42)
optional arguments:
options:
-h, --help show this help message and exit
As the help string supports %-formatting, if you want a literal ``%`` to appear
@ -1226,7 +1235,7 @@ setting the ``help`` value to ``argparse.SUPPRESS``::
>>> parser.print_help()
usage: frobble [-h]
optional arguments:
options:
-h, --help show this help message and exit
@ -1253,7 +1262,7 @@ will be referred to as ``FOO``. An example::
positional arguments:
bar
optional arguments:
options:
-h, --help show this help message and exit
--foo FOO
@ -1270,7 +1279,7 @@ An alternative name can be specified with ``metavar``::
positional arguments:
XXX
optional arguments:
options:
-h, --help show this help message and exit
--foo YYY
@ -1288,7 +1297,7 @@ arguments::
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]
optional arguments:
options:
-h, --help show this help message and exit
-x X X
--foo bar baz
@ -1692,7 +1701,7 @@ Sub-commands
a a help
b b help
optional arguments:
options:
-h, --help show this help message and exit
--foo foo help
@ -1702,13 +1711,13 @@ Sub-commands
positional arguments:
bar bar help
optional arguments:
options:
-h, --help show this help message and exit
>>> parser.parse_args(['b', '--help'])
usage: PROG b [-h] [--baz {X,Y,Z}]
optional arguments:
options:
-h, --help show this help message and exit
--baz {X,Y,Z} baz help
@ -1725,7 +1734,7 @@ Sub-commands
>>> parser.parse_args(['-h'])
usage: [-h] {foo,bar} ...
optional arguments:
options:
-h, --help show this help message and exit
subcommands:

View File

@ -80,12 +80,13 @@ Node classes
end_col_offset
Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
:attr:`lineno`, :attr:`col_offset`, :attr:`lineno`, and :attr:`col_offset`
attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and
last line numbers of source text span (1-indexed so the first line is line 1)
and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding
UTF-8 byte offsets of the first and last tokens that generated the node.
The UTF-8 offset is recorded because the parser uses UTF-8 internally.
:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, and
:attr:`end_col_offset` attributes. The :attr:`lineno` and :attr:`end_lineno`
are the first and last line numbers of source text span (1-indexed so the
first line is line 1) and the :attr:`col_offset` and :attr:`end_col_offset`
are the corresponding UTF-8 byte offsets of the first and last tokens that
generated the node. The UTF-8 offset is recorded because the parser uses
UTF-8 internally.
Note that the end positions are not required by the compiler and are
therefore optional. The end offset is *after* the last symbol, for example
@ -1575,7 +1576,7 @@ and classes for traversing abstract syntax trees:
Safely evaluate an expression node or a string containing a Python literal or
container display. The string or node provided may only consist of the
following Python literal structures: strings, bytes, numbers, tuples, lists,
dicts, sets, booleans, and ``None``.
dicts, sets, booleans, ``None`` and ``Ellipsis``.
This can be used for safely evaluating strings containing Python values from
untrusted sources without the need to parse the values oneself. It is not
@ -1587,6 +1588,10 @@ and classes for traversing abstract syntax trees:
sufficiently large/complex string due to stack depth limitations
in Python's AST compiler.
It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`,
:exc:`MemoryError` and :exc:`RecursionError` depending on the malformed
input.
.. versionchanged:: 3.2
Now allows bytes and set literals.

View File

@ -321,7 +321,7 @@ Creating Futures and Tasks
.. versionadded:: 3.5.2
.. method:: loop.create_task(coro, \*, name=None)
.. method:: loop.create_task(coro, *, name=None)
Schedule the execution of a :ref:`coroutine`.
Return a :class:`Task` object.
@ -356,7 +356,7 @@ Opening network connections
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. coroutinemethod:: loop.create_connection(protocol_factory, \
host=None, port=None, \*, ssl=None, \
host=None, port=None, *, ssl=None, \
family=0, proto=0, flags=0, sock=None, \
local_addr=None, server_hostname=None, \
ssl_handshake_timeout=None, \
@ -482,7 +482,7 @@ Opening network connections
that can be used directly in async/await code.
.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \
local_addr=None, remote_addr=None, \*, \
local_addr=None, remote_addr=None, *, \
family=0, proto=0, flags=0, \
reuse_address=None, reuse_port=None, \
allow_broadcast=None, sock=None)
@ -559,7 +559,7 @@ Opening network connections
Added support for Windows.
.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \
path=None, \*, ssl=None, sock=None, \
path=None, *, ssl=None, sock=None, \
server_hostname=None, ssl_handshake_timeout=None)
Create a Unix connection.
@ -592,7 +592,7 @@ Creating network servers
^^^^^^^^^^^^^^^^^^^^^^^^
.. coroutinemethod:: loop.create_server(protocol_factory, \
host=None, port=None, \*, \
host=None, port=None, *, \
family=socket.AF_UNSPEC, \
flags=socket.AI_PASSIVE, \
sock=None, backlog=100, ssl=None, \
@ -683,7 +683,7 @@ Creating network servers
.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
\*, sock=None, backlog=100, ssl=None, \
*, sock=None, backlog=100, ssl=None, \
ssl_handshake_timeout=None, start_serving=True)
Similar to :meth:`loop.create_server` but works with the
@ -708,7 +708,7 @@ Creating network servers
The *path* parameter can now be a :class:`~pathlib.Path` object.
.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
sock, \*, ssl=None, ssl_handshake_timeout=None)
sock, *, ssl=None, ssl_handshake_timeout=None)
Wrap an already accepted connection into a transport/protocol pair.
@ -773,7 +773,7 @@ TLS Upgrade
^^^^^^^^^^^
.. coroutinemethod:: loop.start_tls(transport, protocol, \
sslcontext, \*, server_side=False, \
sslcontext, *, server_side=False, \
server_hostname=None, ssl_handshake_timeout=None)
Upgrade an existing transport-based connection to TLS.
@ -806,7 +806,7 @@ TLS Upgrade
Watching file descriptors
^^^^^^^^^^^^^^^^^^^^^^^^^
.. method:: loop.add_reader(fd, callback, \*args)
.. method:: loop.add_reader(fd, callback, *args)
Start monitoring the *fd* file descriptor for read availability and
invoke *callback* with the specified arguments once *fd* is available for
@ -816,7 +816,7 @@ Watching file descriptors
Stop monitoring the *fd* file descriptor for read availability.
.. method:: loop.add_writer(fd, callback, \*args)
.. method:: loop.add_writer(fd, callback, *args)
Start monitoring the *fd* file descriptor for write availability and
invoke *callback* with the specified arguments once *fd* is available for
@ -930,7 +930,7 @@ convenient.
:meth:`loop.create_server` and :func:`start_server`.
.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
\*, fallback=True)
*, fallback=True)
Send a file using high-performance :mod:`os.sendfile` if possible.
Return the total number of bytes sent.
@ -964,7 +964,7 @@ convenient.
DNS
^^^
.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
.. coroutinemethod:: loop.getaddrinfo(host, port, *, family=0, \
type=0, proto=0, flags=0)
Asynchronous version of :meth:`socket.getaddrinfo`.
@ -1029,7 +1029,7 @@ Working with pipes
Unix signals
^^^^^^^^^^^^
.. method:: loop.add_signal_handler(signum, callback, \*args)
.. method:: loop.add_signal_handler(signum, callback, *args)
Set *callback* as the handler for the *signum* signal.
@ -1064,7 +1064,7 @@ Unix signals
Executing code in thread or process pools
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. awaitablemethod:: loop.run_in_executor(executor, func, \*args)
.. awaitablemethod:: loop.run_in_executor(executor, func, *args)
Arrange for *func* to be called in the specified executor.
@ -1184,10 +1184,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 <asyncio-protocol>` instance;
* 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
* 'socket' (optional): :class:`socket.socket` instance.
* 'socket' (optional): :class:`socket.socket` instance;
* 'asyncgen' (optional): Asynchronous generator that caused
the exception.
.. note::
@ -1234,9 +1237,9 @@ async/await code consider using the high-level
subprocesses. See :ref:`Subprocess Support on Windows
<asyncio-windows-subprocess>` for details.
.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
.. coroutinemethod:: loop.subprocess_exec(protocol_factory, *args, \
stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, \*\*kwargs)
stderr=subprocess.PIPE, **kwargs)
Create a subprocess from one or more string arguments specified by
*args*.
@ -1316,9 +1319,9 @@ async/await code consider using the high-level
conforms to the :class:`asyncio.SubprocessTransport` base class and
*protocol* is an object instantiated by the *protocol_factory*.
.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, *, \
stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, \*\*kwargs)
stderr=subprocess.PIPE, **kwargs)
Create a subprocess from *cmd*, which can be a :class:`str` or a
:class:`bytes` string encoded to the

View File

@ -31,7 +31,7 @@ Future Functions
.. versionadded:: 3.5
.. function:: ensure_future(obj, \*, loop=None)
.. function:: ensure_future(obj, *, loop=None)
Return:
@ -58,7 +58,7 @@ Future Functions
The function accepts any :term:`awaitable` object.
.. function:: wrap_future(future, \*, loop=None)
.. function:: wrap_future(future, *, loop=None)
Wrap a :class:`concurrent.futures.Future` object in a
:class:`asyncio.Future` object.
@ -67,7 +67,7 @@ Future Functions
Future Object
=============
.. class:: Future(\*, loop=None)
.. class:: Future(*, loop=None)
A Future represents an eventual result of an asynchronous
operation. Not thread-safe.

View File

@ -159,7 +159,7 @@ implementation used by the asyncio event loop:
.. class:: AbstractChildWatcher
.. method:: add_child_handler(pid, callback, \*args)
.. method:: add_child_handler(pid, callback, *args)
Register a new child handler.
@ -209,7 +209,7 @@ implementation used by the asyncio event loop:
It works reliably even when the asyncio event loop is run in a non-main OS thread.
There is no noticeable overhead when handling a big number of children (*O(1)* each
time a child terminates), but stating a thread per process requires extra memory.
time a child terminates), but starting a thread per process requires extra memory.
This watcher is used by default.

View File

@ -23,7 +23,7 @@ See also the `Examples`_ section below.
Queue
=====
.. class:: Queue(maxsize=0, \*, loop=None)
.. class:: Queue(maxsize=0)
A first in, first out (FIFO) queue.
@ -36,9 +36,6 @@ Queue
the queue is always known and can be returned by calling the
:meth:`qsize` method.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
This class is :ref:`not thread safe <asyncio-multithreading>`.

View File

@ -48,9 +48,9 @@ The following top-level asyncio functions can be used to create
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, \
.. coroutinefunction:: open_connection(host=None, port=None, *, \
limit=None, ssl=None, family=0, proto=0, \
flags=0, sock=None, local_addr=None, \
server_hostname=None, ssl_handshake_timeout=None)
Establish a network connection and return a pair of
@ -59,9 +59,6 @@ and work with streams:
The returned *reader* and *writer* objects are instances of
:class:`StreamReader` and :class:`StreamWriter` classes.
The *loop* argument is optional and can always be determined
automatically when this function is awaited from a coroutine.
*limit* determines the buffer size limit used by the
returned :class:`StreamReader` instance. By default the *limit*
is set to 64 KiB.
@ -74,7 +71,7 @@ and work with streams:
The *ssl_handshake_timeout* parameter.
.. coroutinefunction:: start_server(client_connected_cb, host=None, \
port=None, \*, loop=None, limit=None, \
port=None, *, limit=None, \
family=socket.AF_UNSPEC, \
flags=socket.AI_PASSIVE, sock=None, \
backlog=100, ssl=None, reuse_address=None, \
@ -92,9 +89,6 @@ and work with streams:
:ref:`coroutine function <coroutine>`; if it is a coroutine function,
it will be automatically scheduled as a :class:`Task`.
The *loop* argument is optional and can always be determined
automatically when this method is awaited from a coroutine.
*limit* determines the buffer size limit used by the
returned :class:`StreamReader` instance. By default the *limit*
is set to 64 KiB.
@ -109,9 +103,9 @@ and work with streams:
.. rubric:: Unix Sockets
.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
limit=None, ssl=None, sock=None, \
server_hostname=None, ssl_handshake_timeout=None)
.. coroutinefunction:: open_unix_connection(path=None, *, limit=None, \
ssl=None, sock=None, server_hostname=None, \
ssl_handshake_timeout=None)
Establish a Unix socket connection and return a pair of
``(reader, writer)``.
@ -132,9 +126,8 @@ and work with streams:
.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
\*, loop=None, limit=None, sock=None, \
backlog=100, ssl=None, ssl_handshake_timeout=None, \
start_serving=True)
*, limit=None, sock=None, backlog=100, ssl=None, \
ssl_handshake_timeout=None, start_serving=True)
Start a Unix socket server.
@ -192,7 +185,7 @@ StreamReader
can be read. Use the :attr:`IncompleteReadError.partial`
attribute to get the partially read data.
.. coroutinemethod:: readuntil(separator=b'\\n')
.. coroutinemethod:: readuntil(separator=b'\n')
Read data from the stream until *separator* is found.

View File

@ -61,9 +61,8 @@ See also the `Examples`_ subsection.
Creating Subprocesses
=====================
.. coroutinefunction:: create_subprocess_exec(program, \*args, stdin=None, \
stdout=None, stderr=None, loop=None, \
limit=None, \*\*kwds)
.. coroutinefunction:: create_subprocess_exec(program, *args, stdin=None, \
stdout=None, stderr=None, limit=None, **kwds)
Create a subprocess.
@ -76,13 +75,9 @@ Creating Subprocesses
See the documentation of :meth:`loop.subprocess_exec` for other
parameters.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
stdout=None, stderr=None, loop=None, \
limit=None, \*\*kwds)
stdout=None, stderr=None, limit=None, **kwds)
Run the *cmd* shell command.
@ -104,10 +99,6 @@ Creating Subprocesses
escape whitespace and special shell characters in strings that are going
to be used to construct shell commands.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. note::
Subprocesses are available for Windows if a :class:`ProactorEventLoop` is

View File

@ -36,7 +36,7 @@ asyncio has the following basic synchronization primitives:
Lock
====
.. class:: Lock(\*, loop=None)
.. class:: Lock()
Implements a mutex lock for asyncio tasks. Not thread-safe.
@ -63,9 +63,6 @@ Lock
finally:
lock.release()
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. coroutinemethod:: acquire()
Acquire the lock.
@ -96,7 +93,7 @@ Lock
Event
=====
.. class:: Event(\*, loop=None)
.. class:: Event()
An event object. Not thread-safe.
@ -104,14 +101,10 @@ Event
that some event has happened.
An Event object manages an internal flag that can be set to *true*
with the :meth:`set` method and reset to *false* with the
:meth:`clear` method. The :meth:`wait` method blocks until the
with the :meth:`~Event.set` method and reset to *false* with the
:meth:`clear` method. The :meth:`~Event.wait` method blocks until the
flag is set to *true*. The flag is set to *false* initially.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. _asyncio_example_sync_event:
Example::
@ -142,7 +135,7 @@ Event
Wait until the event is set.
If the event is set, return ``True`` immediately.
Otherwise block until another task calls :meth:`set`.
Otherwise block until another task calls :meth:`~Event.set`.
.. method:: set()
@ -155,8 +148,8 @@ Event
Clear (unset) the event.
Tasks awaiting on :meth:`wait` will now block until the
:meth:`set` method is called again.
Tasks awaiting on :meth:`~Event.wait` will now block until the
:meth:`~Event.set` method is called again.
.. method:: is_set()
@ -166,7 +159,7 @@ Event
Condition
=========
.. class:: Condition(lock=None, \*, loop=None)
.. class:: Condition(lock=None)
A Condition object. Not thread-safe.
@ -184,10 +177,6 @@ Condition
``None``. In the latter case a new Lock object is created
automatically.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
The preferred way to use a Condition is an :keyword:`async with`
statement::
@ -270,7 +259,7 @@ Condition
Semaphore
=========
.. class:: Semaphore(value=1, \*, loop=None)
.. class:: Semaphore(value=1)
A Semaphore object. Not thread-safe.
@ -284,10 +273,6 @@ Semaphore
internal counter (``1`` by default). If the given value is
less than ``0`` a :exc:`ValueError` is raised.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
The preferred way to use a Semaphore is an :keyword:`async with`
statement::
@ -332,7 +317,7 @@ Semaphore
BoundedSemaphore
================
.. class:: BoundedSemaphore(value=1, \*, loop=None)
.. class:: BoundedSemaphore(value=1)
A bounded semaphore object. Not thread-safe.
@ -340,10 +325,6 @@ BoundedSemaphore
a :exc:`ValueError` in :meth:`~Semaphore.release` if it
increases the internal counter above the initial *value*.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
---------

View File

@ -210,7 +210,7 @@ is :meth:`loop.run_in_executor`.
Running an asyncio Program
==========================
.. function:: run(coro, \*, debug=False)
.. function:: run(coro, *, debug=False)
Execute the :term:`coroutine` *coro* and return the result.
@ -247,7 +247,7 @@ Running an asyncio Program
Creating Tasks
==============
.. function:: create_task(coro, \*, name=None)
.. function:: create_task(coro, *, name=None)
Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
and schedule its execution. Return the Task object.
@ -283,7 +283,7 @@ Creating Tasks
Sleeping
========
.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
.. coroutinefunction:: sleep(delay, result=None)
Block for *delay* seconds.
@ -293,9 +293,6 @@ Sleeping
``sleep()`` always suspends the current task, allowing other tasks
to run.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. _asyncio_example_sleep:
Example of coroutine displaying the current date every second
@ -319,7 +316,7 @@ Sleeping
Running Tasks Concurrently
==========================
.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
.. awaitablefunction:: gather(*aws, return_exceptions=False)
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
sequence *concurrently*.
@ -348,9 +345,6 @@ Running Tasks Concurrently
cancellation of one submitted Task/Future to cause other
Tasks/Futures to be cancelled.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. _asyncio_example_gather:
Example::
@ -403,7 +397,7 @@ Running Tasks Concurrently
Shielding From Cancellation
===========================
.. awaitablefunction:: shield(aw, \*, loop=None)
.. awaitablefunction:: shield(aw)
Protect an :ref:`awaitable object <asyncio-awaitables>`
from being :meth:`cancelled <Task.cancel>`.
@ -436,14 +430,11 @@ Shielding From Cancellation
except CancelledError:
res = None
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
Timeouts
========
.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
.. coroutinefunction:: wait_for(aw, timeout)
Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
to complete with a timeout.
@ -466,9 +457,6 @@ Timeouts
If the wait is cancelled, the future *aw* is also cancelled.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. _asyncio_example_waitfor:
Example::
@ -500,8 +488,7 @@ Timeouts
Waiting Primitives
==================
.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
return_when=ALL_COMPLETED)
.. coroutinefunction:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
iterable concurrently and block until the condition specified
@ -553,10 +540,6 @@ Waiting Primitives
``wait()`` directly is deprecated as it leads to
:ref:`confusing behavior <asyncio_example_wait_coroutine>`.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
.. _asyncio_example_wait_coroutine:
.. note::
@ -590,7 +573,7 @@ Waiting Primitives
deprecated.
.. function:: as_completed(aws, \*, loop=None, timeout=None)
.. function:: as_completed(aws, *, timeout=None)
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
iterable concurrently. Return an iterator of coroutines.
@ -600,9 +583,6 @@ Waiting Primitives
Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
all Futures are done.
.. deprecated-removed:: 3.8 3.10
The *loop* parameter.
Example::
for coro in as_completed(aws):
@ -613,12 +593,12 @@ Waiting Primitives
Running in Threads
==================
.. coroutinefunction:: to_thread(func, /, \*args, \*\*kwargs)
.. coroutinefunction:: to_thread(func, /, *args, **kwargs)
Asynchronously run function *func* in a separate thread.
Any \*args and \*\*kwargs supplied for this function are directly passed
to *func*. Also, the current :class:`contextvars.Context` is propogated,
to *func*. Also, the current :class:`contextvars.Context` is propagated,
allowing context variables from the event loop thread to be accessed in the
separate thread.
@ -743,7 +723,7 @@ Introspection
Task Object
===========
.. class:: Task(coro, \*, loop=None, name=None)
.. class:: Task(coro, *, loop=None, name=None)
A :class:`Future-like <Future>` object that runs a Python
:ref:`coroutine <coroutine>`. Not thread-safe.
@ -909,7 +889,7 @@ Task Object
See the documentation of :meth:`Future.remove_done_callback`
for more details.
.. method:: get_stack(\*, limit=None)
.. method:: get_stack(*, limit=None)
Return the list of stack frames for this Task.
@ -930,7 +910,7 @@ Task Object
stack are returned, but the oldest frames of a traceback are
returned. (This matches the behavior of the traceback module.)
.. method:: print_stack(\*, limit=None, file=None)
.. method:: print_stack(*, limit=None, file=None)
Print the stack or traceback for this Task.

View File

@ -199,7 +199,7 @@ The modern interface provides:
.. versionadded:: 3.4
.. function:: a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \\t\\n\\r\\v')
.. function:: a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')
Decode the Ascii85 encoded :term:`bytes-like object` or ASCII string *b* and
return the decoded :class:`bytes`.

View File

@ -266,7 +266,6 @@ Below are some examples of typical usage of the :mod:`bz2` module.
Using :func:`compress` and :func:`decompress` to demonstrate round-trip compression:
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
@ -275,11 +274,9 @@ Using :func:`compress` and :func:`decompress` to demonstrate round-trip compress
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c) # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d # Check equality to original object after round-trip
True
@ -287,7 +284,6 @@ Using :func:`compress` and :func:`decompress` to demonstrate round-trip compress
Using :class:`BZ2Compressor` for incremental compression:
>>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
... """Yield incremental blocks of chunksize bytes."""
... for _ in range(chunks):
@ -310,7 +306,6 @@ while ordered, repetitive data usually yields a high compression ratio.
Writing and reading a bzip2-compressed file in binary mode:
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
@ -319,14 +314,11 @@ Writing and reading a bzip2-compressed file in binary mode:
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
... # Write compressed data to file
... unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
... # Decompress data from file
... content = f.read()
>>> content == data # Check equality to original object after round-trip
True

View File

@ -291,7 +291,7 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
:meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
If the :class:`Set` mixin is being used in a class with a different
constructor signature, you will need to override :meth:`_from_iterable`
with a classmethod that can construct new instances from
with a classmethod or regular method that can construct new instances from
an iterable argument.
(2)

View File

@ -862,6 +862,9 @@ they add the ability to access fields by name instead of position index.
Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.
To support pickling, the named tuple class should be assigned to a variable
that matches *typename*.
.. versionchanged:: 3.1
Added support for *rename*.

View File

@ -148,7 +148,7 @@ runtime.
Public functions
----------------
.. function:: compile_dir(dir, maxlevels=sys.getrecursionlimit(), ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, \*, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)
.. function:: compile_dir(dir, maxlevels=sys.getrecursionlimit(), ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)
Recursively descend the directory tree named by *dir*, compiling all :file:`.py`
files along the way. Return a true value if all the files compiled successfully,
@ -231,7 +231,7 @@ Public functions
Added *stripdir*, *prependdir*, *limit_sl_dest* and *hardlink_dupes* arguments.
Default value of *maxlevels* was changed from ``10`` to ``sys.getrecursionlimit()``
.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=None, \*, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)
.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)
Compile the file with path *fullname*. Return a true value if the file
compiled successfully, and a false value otherwise.

View File

@ -67,7 +67,7 @@ Executor Objects
.. versionchanged:: 3.5
Added the *chunksize* argument.
.. method:: shutdown(wait=True, \*, cancel_futures=False)
.. method:: shutdown(wait=True, *, cancel_futures=False)
Signal the executor that it should free any resources that it is using
when the currently pending futures are done executing. Calls to
@ -236,9 +236,9 @@ to a :class:`ProcessPoolExecutor` will result in deadlock.
An :class:`Executor` subclass that executes calls asynchronously using a pool
of at most *max_workers* processes. If *max_workers* is ``None`` or not
given, it will default to the number of processors on the machine.
If *max_workers* is lower or equal to ``0``, then a :exc:`ValueError`
If *max_workers* is less than or equal to ``0``, then a :exc:`ValueError`
will be raised.
On Windows, *max_workers* must be equal or lower than ``61``. If it is not
On Windows, *max_workers* must be less than or equal to ``61``. If it is not
then :exc:`ValueError` will be raised. If *max_workers* is ``None``, then
the default chosen will be at most ``61``, even if more processors are
available.
@ -250,7 +250,7 @@ to a :class:`ProcessPoolExecutor` will result in deadlock.
each worker process; *initargs* is a tuple of arguments passed to the
initializer. Should *initializer* raise an exception, all currently
pending jobs will raise a :exc:`~concurrent.futures.process.BrokenProcessPool`,
as well any attempt to submit more jobs to the pool.
as well as any attempt to submit more jobs to the pool.
.. versionchanged:: 3.3
When one of the worker processes terminates abruptly, a

View File

@ -126,6 +126,31 @@ Functions and classes provided:
.. versionadded:: 3.7
Context managers defined with :func:`asynccontextmanager` can be used
either as decorators or with :keyword:`async with` statements::
import time
async def timeit():
now = time.monotonic()
try:
yield
finally:
print(f'it took {time.monotonic() - now}s to run')
@timeit()
async def main():
# ... async code ...
When used as a decorator, a new generator instance is implicitly created on
each function call. This allows the otherwise "one-shot" context managers
created by :func:`asynccontextmanager` to meet the requirement that context
managers support multiple invocations in order to be used as decorators.
.. versionchanged:: 3.10
Async context managers created with :func:`asynccontextmanager` can
be used as decorators.
.. function:: closing(thing)
@ -218,8 +243,26 @@ Functions and classes provided:
with cm as file:
# Perform processing on the file
It can also be used as a stand-in for
:ref:`asynchronous context managers <async-context-managers>`::
async def send_http(session=None):
if not session:
# If no http session, create it with aiohttp
cm = aiohttp.ClientSession()
else:
# Caller is responsible for closing the session
cm = nullcontext(session)
async with cm as session:
# Send http requests with session
.. versionadded:: 3.7
.. versionchanged:: 3.10
:term:`asynchronous context manager` support was added.
.. function:: suppress(*exceptions)
@ -384,6 +427,45 @@ Functions and classes provided:
.. versionadded:: 3.2
.. class:: AsyncContextDecorator
Similar to :class:`ContextDecorator` but only for asynchronous functions.
Example of ``AsyncContextDecorator``::
from asyncio import run
from contextlib import AsyncContextDecorator
class mycontext(AsyncContextDecorator):
async def __aenter__(self):
print('Starting')
return self
async def __aexit__(self, *exc):
print('Finishing')
return False
>>> @mycontext()
... async def function():
... print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing
>>> async def function():
... async with mycontext():
... print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing
.. versionadded:: 3.10
.. class:: ExitStack()
A context manager that is designed to make it easy to programmatically

View File

@ -26,7 +26,7 @@ See also :pep:`567` for additional details.
Context Variables
-----------------
.. class:: ContextVar(name, [\*, default])
.. class:: ContextVar(name, [*, default])
This class is used to declare a new Context Variable, e.g.::
@ -146,7 +146,7 @@ Manual Context Management
Context implements the :class:`collections.abc.Mapping` interface.
.. method:: run(callable, \*args, \*\*kwargs)
.. method:: run(callable, *args, **kwargs)
Execute ``callable(*args, **kwargs)`` code in the context object
the *run* method is called on. Return the result of the execution

View File

@ -2508,7 +2508,7 @@ other data types containing pointer type fields.
Arrays and pointers
^^^^^^^^^^^^^^^^^^^
.. class:: Array(\*args)
.. class:: Array(*args)
Abstract base class for arrays.

View File

@ -1219,7 +1219,7 @@ Instance methods:
.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \
hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \
tzinfo=self.tzinfo, * fold=0)
tzinfo=self.tzinfo, *, fold=0)
Return a datetime with the same attributes, except for those attributes given
new values by whichever keyword arguments are specified. Note that
@ -1783,7 +1783,7 @@ Other constructor:
Instance methods:
.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)
Return a :class:`.time` with the same value, except for those attributes given
new values by whichever keyword arguments are specified. Note that

View File

@ -198,7 +198,7 @@ These do not emulate the native look-and-feel of the platform.
A subclass of FileDialog that creates a dialog window for selecting a
destination file.
.. method:: ok_command()
.. method:: ok_command()
Test whether or not the selection points to a valid file that is not a
directory. Confirmation is required if an already existing file is

View File

@ -149,7 +149,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
contains a good example of its use.
.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
generating the delta lines) in context diff format.
@ -279,7 +279,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
emu
.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
generating the delta lines) in unified diff format.
@ -321,7 +321,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
See :ref:`difflib-interface` for a more detailed example.
.. function:: diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\\n')
.. function:: diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')
Compare *a* and *b* (lists of bytes objects) using *dfunc*; yield a
sequence of delta lines (also bytes) in the format returned by *dfunc*.

View File

@ -708,7 +708,8 @@ iterations of the loop.
.. opcode:: RERAISE
Re-raises the exception currently on top of the stack.
Re-raises the exception currently on top of the stack. If oparg is non-zero,
restores ``f_lasti`` of the current frame to its value when the exception was raised.
.. versionadded:: 3.9
@ -861,7 +862,7 @@ All of the following opcodes use their arguments.
.. opcode:: LIST_TO_TUPLE
Pops a list from the stack and pushes a tuple containing the same values.
Pops a list from the stack and pushes a tuple containing the same values.
.. versionadded:: 3.9
@ -889,7 +890,7 @@ All of the following opcodes use their arguments.
.. opcode:: DICT_MERGE
Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys.
Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys.
.. versionadded:: 3.9
@ -907,14 +908,14 @@ All of the following opcodes use their arguments.
.. opcode:: IS_OP (invert)
Performs ``is`` comparison, or ``is not`` if ``invert`` is 1.
Performs ``is`` comparison, or ``is not`` if ``invert`` is 1.
.. versionadded:: 3.9
.. opcode:: CONTAINS_OP (invert)
Performs ``in`` comparison, or ``not in`` if ``invert`` is 1.
Performs ``in`` comparison, or ``not in`` if ``invert`` is 1.
.. versionadded:: 3.9
@ -955,8 +956,8 @@ All of the following opcodes use their arguments.
.. opcode:: JUMP_IF_NOT_EXC_MATCH (target)
Tests whether the second value on the stack is an exception matching TOS,
and jumps if it is not. Pops two values from the stack.
Tests whether the second value on the stack is an exception matching TOS,
and jumps if it is not. Pops two values from the stack.
.. versionadded:: 3.9
@ -1144,11 +1145,13 @@ All of the following opcodes use their arguments.
* ``0x01`` a tuple of default values for positional-only and
positional-or-keyword parameters in positional order
* ``0x02`` a dictionary of keyword-only parameters' default values
* ``0x04`` an annotation dictionary
* ``0x04`` a tuple of strings containing parameters' annotations
* ``0x08`` a tuple containing cells for free variables, making a closure
* the code associated with the function (at TOS1)
* the :term:`qualified name` of the function (at TOS)
.. versionchanged:: 3.10
Flag value ``0x04`` is a tuple of strings instead of dictionary
.. opcode:: BUILD_SLICE (argc)

View File

@ -719,36 +719,51 @@ above.
An example's doctest directives modify doctest's behavior for that single
example. Use ``+`` to enable the named behavior, or ``-`` to disable it.
For example, this test passes::
For example, this test passes:
>>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
.. doctest::
:no-trim-doctest-flags:
>>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Without the directive it would fail, both because the actual output doesn't have
two blanks before the single-digit list elements, and because the actual output
is on a single line. This test also passes, and also requires a directive to do
so::
so:
>>> print(list(range(20))) # doctest: +ELLIPSIS
.. doctest::
:no-trim-doctest-flags:
>>> print(list(range(20))) # doctest: +ELLIPSIS
[0, 1, ..., 18, 19]
Multiple directives can be used on a single physical line, separated by
commas::
commas:
>>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
.. doctest::
:no-trim-doctest-flags:
>>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19]
If multiple directive comments are used for a single example, then they are
combined::
combined:
>>> print(list(range(20))) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
.. doctest::
:no-trim-doctest-flags:
>>> print(list(range(20))) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19]
As the previous example shows, you can add ``...`` lines to your example
containing only directives. This can be useful when an example is too long for
a directive to comfortably fit on the same line::
a directive to comfortably fit on the same line:
.. doctest::
:no-trim-doctest-flags:
>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
... # doctest: +ELLIPSIS
@ -793,18 +808,23 @@ instead. Another is to do ::
There are others, but you get the idea.
Another bad idea is to print things that embed an object address, like ::
Another bad idea is to print things that embed an object address, like
>>> id(1.0) # certain to fail some of the time
.. doctest::
>>> id(1.0) # certain to fail some of the time # doctest: +SKIP
7948648
>>> class C: pass
>>> C() # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>
>>> C() # the default repr() for instances embeds an address # doctest: +SKIP
<C object at 0x00AC18F0>
The :const:`ELLIPSIS` directive gives a nice approach for the last example::
The :const:`ELLIPSIS` directive gives a nice approach for the last example:
>>> C() #doctest: +ELLIPSIS
<__main__.C instance at 0x...>
.. doctest::
:no-trim-doctest-flags:
>>> C() # doctest: +ELLIPSIS
<C object at 0x...>
Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for float formatting,

View File

@ -116,7 +116,7 @@ Currently the email package provides only one concrete content manager,
decoding the payload to unicode. The default error handler is
``replace``.
.. method:: set_content(msg, <'str'>, subtype="plain", charset='utf-8' \
.. method:: set_content(msg, <'str'>, subtype="plain", charset='utf-8', \
cte=None, \
disposition=None, filename=None, cid=None, \
params=None, headers=None)

View File

@ -116,7 +116,7 @@ Here is the :class:`Header` class description:
if *s* is a byte string.
.. method:: encode(splitchars=';, \\t', maxlinelen=None, linesep='\\n')
.. method:: encode(splitchars=';, \t', maxlinelen=None, linesep='\n')
Encode a message header into an RFC-compliant format, possibly wrapping
long lines and encapsulating non-ASCII parts in base64 or quoted-printable

View File

@ -210,7 +210,7 @@ added matters. To illustrate::
:meth:`register_defect` method.
.. attribute:: mangle_from\_
.. attribute:: mangle_from_
If :const:`True`, lines starting with *"From "* in the body are
escaped by putting a ``>`` in front of them. This parameter is used when

View File

@ -61,16 +61,18 @@ helper, :class:`auto`.
the bitwise operations without losing their :class:`Flag` membership.
.. function:: unique
:noindex:
:noindex:
Enum class decorator that ensures only one name is bound to any one value.
.. class:: auto
Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.
Instances are replaced with an appropriate value for Enum members.
:class:`StrEnum` defaults to the lower-cased version of the member name,
while other Enums default to 1 and increase from there.
.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
.. versionadded:: 3.10 ``StrEnum``
Creating an Enum
----------------
@ -1164,6 +1166,15 @@ and raise an error if the two do not match::
In Python 2 code the :attr:`_order_` attribute is necessary as definition
order is lost before it can be recorded.
_Private__names
"""""""""""""""
Private names are not converted to Enum members, but remain normal attributes.
.. versionchanged:: 3.10
``Enum`` member type
""""""""""""""""""""

View File

@ -90,8 +90,13 @@ The following exceptions are used mostly as base classes for other exceptions.
.. method:: with_traceback(tb)
This method sets *tb* as the new traceback for the exception and returns
the exception object. It is usually used in exception handling code like
this::
the exception object. It was more commonly used before the exception
chaining features of :pep:`3134` became available. The following example
shows how we can convert an instance of ``SomeException`` into an
instance of ``OtherException`` while preserving the traceback. Once
raised, the current frame is pushed onto the traceback of the
``OtherException``, as would have happened to the traceback of the
original ``SomeException`` had we allowed it to propagate to the caller.
try:
...

View File

@ -173,7 +173,13 @@ The :class:`dircmp` class
.. attribute:: subdirs
A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp`
objects.
instances (or MyDirCmp instances if this instance is of type MyDirCmp, a
subclass of :class:`dircmp`).
.. versionchanged:: 3.10
Previously entries were always :class:`dircmp` instances. Now entries
are the same type as *self*, if *self* is a subclass of
:class:`dircmp`.
.. attribute:: DEFAULT_IGNORES

View File

@ -75,7 +75,7 @@ patterns.
.. function:: filter(names, pattern)
Return the subset of the list of *names* that match *pattern*. It is the same as
Construct a list from those elements of the iterable *names* that match *pattern*. It is the same as
``[n for n in names if fnmatch(n, pattern)]``, but implemented more efficiently.

View File

@ -1,351 +0,0 @@
:mod:`formatter` --- Generic output formatting
==============================================
.. module:: formatter
:synopsis: Generic output formatter and device interface.
:deprecated:
.. deprecated:: 3.4
Due to lack of usage, the formatter module has been deprecated.
--------------
This module supports two interface definitions, each with multiple
implementations: The *formatter* interface, and the *writer* interface which is
required by the formatter interface.
Formatter objects transform an abstract flow of formatting events into specific
output events on writer objects. Formatters manage several stack structures to
allow various properties of a writer object to be changed and restored; writers
need not be able to handle relative changes nor any sort of "change back"
operation. Specific writer properties which may be controlled via formatter
objects are horizontal alignment, font, and left margin indentations. A
mechanism is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well. Additional interfaces facilitate formatting
events which are not reversible, such as paragraph separation.
Writer objects encapsulate device interfaces. Abstract devices, such as file
formats, are supported as well as physical devices. The provided
implementations all work with abstract devices. The interface makes available
mechanisms for setting the properties which formatter objects manage and
inserting data into the output.
.. _formatter-interface:
The Formatter Interface
-----------------------
Interfaces to create formatters are dependent on the specific formatter class
being instantiated. The interfaces described below are the required interfaces
which all formatters must support once initialized.
One data element is defined at the module level:
.. data:: AS_IS
Value which can be used in the font specification passed to the ``push_font()``
method described below, or as the new value to any other ``push_property()``
method. Pushing the ``AS_IS`` value allows the corresponding ``pop_property()``
method to be called without having to track whether the property was changed.
The following attributes are defined for formatter instance objects:
.. attribute:: formatter.writer
The writer instance with which the formatter interacts.
.. method:: formatter.end_paragraph(blanklines)
Close any open paragraphs and insert at least *blanklines* before the next
paragraph.
.. method:: formatter.add_line_break()
Add a hard line break if one does not already exist. This does not break the
logical paragraph.
.. method:: formatter.add_hor_rule(*args, **kw)
Insert a horizontal rule in the output. A hard break is inserted if there is
data in the current paragraph, but the logical paragraph is not broken. The
arguments and keywords are passed on to the writer's :meth:`send_line_break`
method.
.. method:: formatter.add_flowing_data(data)
Provide data which should be formatted with collapsed whitespace. Whitespace
from preceding and successive calls to :meth:`add_flowing_data` is considered as
well when the whitespace collapse is performed. The data which is passed to
this method is expected to be word-wrapped by the output device. Note that any
word-wrapping still must be performed by the writer object due to the need to
rely on device and font information.
.. method:: formatter.add_literal_data(data)
Provide data which should be passed to the writer unchanged. Whitespace,
including newline and tab characters, are considered legal in the value of
*data*.
.. method:: formatter.add_label_data(format, counter)
Insert a label which should be placed to the left of the current left margin.
This should be used for constructing bulleted or numbered lists. If the
*format* value is a string, it is interpreted as a format specification for
*counter*, which should be an integer. The result of this formatting becomes the
value of the label; if *format* is not a string it is used as the label value
directly. The label value is passed as the only argument to the writer's
:meth:`send_label_data` method. Interpretation of non-string label values is
dependent on the associated writer.
Format specifications are strings which, in combination with a counter value,
are used to compute label values. Each character in the format string is copied
to the label value, with some characters recognized to indicate a transform on
the counter value. Specifically, the character ``'1'`` represents the counter
value formatter as an Arabic number, the characters ``'A'`` and ``'a'``
represent alphabetic representations of the counter value in upper and lower
case, respectively, and ``'I'`` and ``'i'`` represent the counter value in Roman
numerals, in upper and lower case. Note that the alphabetic and roman
transforms require that the counter value be greater than zero.
.. method:: formatter.flush_softspace()
Send any pending whitespace buffered from a previous call to
:meth:`add_flowing_data` to the associated writer object. This should be called
before any direct manipulation of the writer object.
.. method:: formatter.push_alignment(align)
Push a new alignment setting onto the alignment stack. This may be
:const:`AS_IS` if no change is desired. If the alignment value is changed from
the previous setting, the writer's :meth:`new_alignment` method is called with
the *align* value.
.. method:: formatter.pop_alignment()
Restore the previous alignment.
.. method:: formatter.push_font((size, italic, bold, teletype))
Change some or all font properties of the writer object. Properties which are
not set to :const:`AS_IS` are set to the values passed in while others are
maintained at their current settings. The writer's :meth:`new_font` method is
called with the fully resolved font specification.
.. method:: formatter.pop_font()
Restore the previous font.
.. method:: formatter.push_margin(margin)
Increase the number of left margin indentations by one, associating the logical
tag *margin* with the new indentation. The initial margin level is ``0``.
Changed values of the logical tag must be true values; false values other than
:const:`AS_IS` are not sufficient to change the margin.
.. method:: formatter.pop_margin()
Restore the previous margin.
.. method:: formatter.push_style(*styles)
Push any number of arbitrary style specifications. All styles are pushed onto
the styles stack in order. A tuple representing the entire stack, including
:const:`AS_IS` values, is passed to the writer's :meth:`new_styles` method.
.. method:: formatter.pop_style(n=1)
Pop the last *n* style specifications passed to :meth:`push_style`. A tuple
representing the revised stack, including :const:`AS_IS` values, is passed to
the writer's :meth:`new_styles` method.
.. method:: formatter.set_spacing(spacing)
Set the spacing style for the writer.
.. method:: formatter.assert_line_data(flag=1)
Inform the formatter that data has been added to the current paragraph
out-of-band. This should be used when the writer has been manipulated
directly. The optional *flag* argument can be set to false if the writer
manipulations produced a hard line break at the end of the output.
.. _formatter-impls:
Formatter Implementations
-------------------------
Two implementations of formatter objects are provided by this module. Most
applications may use one of these classes without modification or subclassing.
.. class:: NullFormatter(writer=None)
A formatter which does nothing. If *writer* is omitted, a :class:`NullWriter`
instance is created. No methods of the writer are called by
:class:`NullFormatter` instances. Implementations should inherit from this
class if implementing a writer interface but don't need to inherit any
implementation.
.. class:: AbstractFormatter(writer)
The standard formatter. This implementation has demonstrated wide applicability
to many writers, and may be used directly in most circumstances. It has been
used to implement a full-featured World Wide Web browser.
.. _writer-interface:
The Writer Interface
--------------------
Interfaces to create writers are dependent on the specific writer class being
instantiated. The interfaces described below are the required interfaces which
all writers must support once initialized. Note that while most applications can
use the :class:`AbstractFormatter` class as a formatter, the writer must
typically be provided by the application.
.. method:: writer.flush()
Flush any buffered output or device control events.
.. method:: writer.new_alignment(align)
Set the alignment style. The *align* value can be any object, but by convention
is a string or ``None``, where ``None`` indicates that the writer's "preferred"
alignment should be used. Conventional *align* values are ``'left'``,
``'center'``, ``'right'``, and ``'justify'``.
.. method:: writer.new_font(font)
Set the font style. The value of *font* will be ``None``, indicating that the
device's default font should be used, or a tuple of the form ``(size,
italic, bold, teletype)``. Size will be a string indicating the size of
font that should be used; specific strings and their interpretation must be
defined by the application. The *italic*, *bold*, and *teletype* values are
Boolean values specifying which of those font attributes should be used.
.. method:: writer.new_margin(margin, level)
Set the margin level to the integer *level* and the logical tag to *margin*.
Interpretation of the logical tag is at the writer's discretion; the only
restriction on the value of the logical tag is that it not be a false value for
non-zero values of *level*.
.. method:: writer.new_spacing(spacing)
Set the spacing style to *spacing*.
.. method:: writer.new_styles(styles)
Set additional styles. The *styles* value is a tuple of arbitrary values; the
value :const:`AS_IS` should be ignored. The *styles* tuple may be interpreted
either as a set or as a stack depending on the requirements of the application
and writer implementation.
.. method:: writer.send_line_break()
Break the current line.
.. method:: writer.send_paragraph(blankline)
Produce a paragraph separation of at least *blankline* blank lines, or the
equivalent. The *blankline* value will be an integer. Note that the
implementation will receive a call to :meth:`send_line_break` before this call
if a line break is needed; this method should not include ending the last line
of the paragraph. It is only responsible for vertical spacing between
paragraphs.
.. method:: writer.send_hor_rule(*args, **kw)
Display a horizontal rule on the output device. The arguments to this method
are entirely application- and writer-specific, and should be interpreted with
care. The method implementation may assume that a line break has already been
issued via :meth:`send_line_break`.
.. method:: writer.send_flowing_data(data)
Output character data which may be word-wrapped and re-flowed as needed. Within
any sequence of calls to this method, the writer may assume that spans of
multiple whitespace characters have been collapsed to single space characters.
.. method:: writer.send_literal_data(data)
Output character data which has already been formatted for display. Generally,
this should be interpreted to mean that line breaks indicated by newline
characters should be preserved and no new line breaks should be introduced. The
data may contain embedded newline and tab characters, unlike data provided to
the :meth:`send_formatted_data` interface.
.. method:: writer.send_label_data(data)
Set *data* to the left of the current left margin, if possible. The value of
*data* is not restricted; treatment of non-string values is entirely
application- and writer-dependent. This method will only be called at the
beginning of a line.
.. _writer-impls:
Writer Implementations
----------------------
Three implementations of the writer object interface are provided as examples by
this module. Most applications will need to derive new writer classes from the
:class:`NullWriter` class.
.. class:: NullWriter()
A writer which only provides the interface definition; no actions are taken on
any methods. This should be the base class for all writers which do not need to
inherit any implementation methods.
.. class:: AbstractWriter()
A writer which can be used in debugging formatters, but not much else. Each
method simply announces itself by printing its name and arguments on standard
output.
.. class:: DumbWriter(file=None, maxcol=72)
Simple writer class which writes output on the :term:`file object` passed
in as *file* or, if *file* is omitted, on standard output. The output is
simply word-wrapped to the number of columns specified by *maxcol*. This
class is suitable for reflowing a sequence of paragraphs.

View File

@ -478,14 +478,15 @@ are always available. They are listed here in alphabetical order.
dictionaries as global and local namespace. If the *globals* dictionary is
present and does not contain a value for the key ``__builtins__``, a
reference to the dictionary of the built-in module :mod:`builtins` is
inserted under that key before *expression* is parsed. This means that
*expression* normally has full access to the standard :mod:`builtins`
module and restricted environments are propagated. If the *locals*
dictionary is omitted it defaults to the *globals* dictionary. If both
dictionaries are omitted, the expression is executed with the *globals* and
*locals* in the environment where :func:`eval` is called. Note, *eval()*
does not have access to the :term:`nested scopes <nested scope>` (non-locals) in the
enclosing environment.
inserted under that key before *expression* is parsed. That way you can
control what builtins are available to the executed code by inserting your
own ``__builtins__`` dictionary into *globals* before passing it to
:func:`eval`. If the *locals* dictionary is omitted it defaults to the
*globals* dictionary. If both dictionaries are omitted, the expression is
executed with the *globals* and *locals* in the environment where
:func:`eval` is called. Note, *eval()* does not have access to the
:term:`nested scopes <nested scope>` (non-locals) in the enclosing
environment.
The return value is the result of
the evaluated expression. Syntax errors are reported as exceptions. Example:
@ -1333,7 +1334,7 @@ are always available. They are listed here in alphabetical order.
supported.
.. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)
.. function:: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print *objects* to the text stream *file*, separated by *sep* and followed
by *end*. *sep*, *end*, *file* and *flush*, if present, must be given as keyword

View File

@ -99,6 +99,11 @@ The module provides the following classes:
:attr:`ssl.SSLContext.post_handshake_auth` for the default *context* or
when *cert_file* is passed with a custom *context*.
.. versionchanged:: 3.10
This class now sends an ALPN extension with protocol indicator
``http/1.1`` when no *context* is given. Custom *context* should set
ALPN protocols with :meth:`~ssl.SSLContext.set_alpn_protocol`.
.. deprecated:: 3.6
*key_file* and *cert_file* are deprecated in favor of *context*.

View File

@ -93,7 +93,7 @@ Cookie Objects
:meth:`value_decode` are inverses on the range of *value_decode*.
.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')
Return a string representation suitable to be sent as HTTP headers. *attrs* and
*header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used

View File

@ -174,9 +174,9 @@ example of usage.
.. seealso::
Documents describing the protocol, and sources and binaries for servers
implementing it, can all be found at the University of Washington's *IMAP
Information Center* (https://www.washington.edu/imap/).
Documents describing the protocol, sources for servers
implementing it, by the University of Washington's IMAP Information Center
can all be found at (**Source Code**) https://github.com/uw-imap/imap (**Not Maintained**).
.. _imap4-objects:

View File

@ -1138,7 +1138,7 @@ find and load modules.
directory for ``''`` (i.e. the empty string).
.. class:: FileFinder(path, \*loader_details)
.. class:: FileFinder(path, *loader_details)
A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
caches results from the file system.
@ -1181,7 +1181,7 @@ find and load modules.
Clear out the internal cache.
.. classmethod:: path_hook(\*loader_details)
.. classmethod:: path_hook(*loader_details)
A class method which returns a closure for use on :attr:`sys.path_hooks`.
An instance of :class:`FileFinder` is returned by the closure using the

View File

@ -72,7 +72,6 @@ the `Python Package Index <https://pypi.org>`_.
custominterp.rst
modules.rst
language.rst
misc.rst
windows.rst
unix.rst
superseded.rst

View File

@ -556,7 +556,7 @@ The Signature object represents the call signature of a callable object and its
return annotation. To retrieve a Signature object, use the :func:`signature`
function.
.. function:: signature(callable, \*, follow_wrapped=True)
.. function:: signature(callable, *, follow_wrapped=True, globalns=None, localns=None)
Return a :class:`Signature` object for the given ``callable``::
@ -581,6 +581,9 @@ function.
Raises :exc:`ValueError` if no signature can be provided, and
:exc:`TypeError` if that type of object is not supported.
``globalns`` and ``localns`` are passed into
:func:`typing.get_type_hints` when resolving the annotations.
A slash(/) in the signature of a function denotes that the parameters prior
to it are positional-only. For more info, see
:ref:`the FAQ entry on positional-only parameters <faq-positional-only-arguments>`.
@ -590,14 +593,23 @@ function.
``callable`` specifically (``callable.__wrapped__`` will not be used to
unwrap decorated callables.)
.. versionadded:: 3.10
``globalns`` and ``localns`` parameters.
.. note::
Some callables may not be introspectable in certain implementations of
Python. For example, in CPython, some built-in functions defined in
C provide no metadata about their arguments.
.. note::
.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Will first try to resolve the annotations, but when it fails and
encounters with an error while that operation, the annotations will be
returned unchanged (as strings).
.. class:: Signature(parameters=None, *, return_annotation=Signature.empty)
A Signature object represents the call signature of a function and its return
annotation. For each parameter accepted by the function it stores a
@ -668,11 +680,12 @@ function.
>>> str(new_sig)
"(a, b) -> 'new return anno'"
.. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
.. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globalns=None, localns=None)
Return a :class:`Signature` (or its subclass) object for a given callable
``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
without unwrapping its ``__wrapped__`` chain.
without unwrapping its ``__wrapped__`` chain. ``globalns`` and
``localns`` will be used as the namespaces when resolving annotations.
This method simplifies subclassing of :class:`Signature`::
@ -683,8 +696,11 @@ function.
.. versionadded:: 3.5
.. versionadded:: 3.10
``globalns`` and ``localns`` parameters.
.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
.. class:: Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
Parameter objects are *immutable*. Instead of modifying a Parameter object,
you can use :meth:`Parameter.replace` to create a modified copy.

View File

@ -964,7 +964,7 @@ Text I/O
.. versionadded:: 3.7
.. class:: StringIO(initial_value='', newline='\\n')
.. class:: StringIO(initial_value='', newline='\n')
A text stream using an in-memory text buffer. It inherits
:class:`TextIOBase`.

View File

@ -55,6 +55,7 @@ Iterator Arguments Results
:func:`filterfalse` pred, seq elements of seq where pred(elem) is false ``filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8``
:func:`groupby` iterable[, key] sub-iterators grouped by value of key(v)
:func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ``islice('ABCDEFG', 2, None) --> C D E F G``
:func:`pairwise` iterable (p[0], p[1]), (p[1], p[2]) ``pairwise('ABCDEFG') --> AB BC CD DE EF FG``
:func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000``
:func:`takewhile` pred, seq seq[0], seq[1], until pred fails ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4``
:func:`tee` it, n it1, it2, ... itn splits one iterator into n
@ -475,6 +476,22 @@ loops that truncate the stream.
If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
then the step defaults to one.
.. function:: pairwise(iterable)
Return successive overlapping pairs taken from the input *iterable*.
The number of 2-tuples in the output iterator will be one fewer than the
number of inputs. It will be empty if the input iterable has fewer than
two values.
Roughly equivalent to::
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
.. function:: permutations(iterable, r=None)
@ -565,7 +582,7 @@ loops that truncate the stream.
Before :func:`product` runs, it completely consumes the input iterables,
keeping pools of values in memory to generate the products. Accordingly,
it only useful with finite inputs.
it is only useful with finite inputs.
.. function:: repeat(object[, times])
@ -755,7 +772,7 @@ which incur interpreter overhead.
"Count how many times the predicate is true"
return sum(map(pred, iterable))
def padnone(iterable):
def pad_none(iterable):
"""Returns the sequence elements and then returns None indefinitely.
Useful for emulating the behavior of the built-in map() function.
@ -769,6 +786,18 @@ which incur interpreter overhead.
def dotproduct(vec1, vec2):
return sum(map(operator.mul, vec1, vec2))
def convolve(signal, kernel):
# See: https://betterexplained.com/articles/intuitive-convolution/
# convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)
# convolve(data, [1, -1]) --> 1st finite difference (1st derivative)
# convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
kernel = list(reversed(kernel))
n = len(kernel)
window = collections.deque([0] * n, maxlen=n)
for x in chain(signal, repeat(0, n-1)):
window.append(x)
yield sum(map(operator.mul, kernel, window))
def flatten(list_of_lists):
"Flatten one level of nesting"
return chain.from_iterable(list_of_lists)
@ -782,12 +811,6 @@ which incur interpreter overhead.
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
@ -809,7 +832,7 @@ which incur interpreter overhead.
nexts = cycle(islice(nexts, num_active))
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
"Use a predicate to partition entries into false entries and true entries"
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
@ -881,7 +904,7 @@ which incur interpreter overhead.
def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools)
return tuple(map(random.choice, pools))
def random_permutation(iterable, r=None):
"Random selection from itertools.permutations(iterable, r)"
@ -900,11 +923,11 @@ which incur interpreter overhead.
"Random selection from itertools.combinations_with_replacement(iterable, r)"
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.randrange(n) for i in range(r))
indices = sorted(random.choices(range(n), k=r))
return tuple(pool[i] for i in indices)
def nth_combination(iterable, r, index):
'Equivalent to list(combinations(iterable, r))[index]'
"Equivalent to list(combinations(iterable, r))[index]"
pool = tuple(iterable)
n = len(pool)
if r < 0 or r > n:

View File

@ -35,45 +35,45 @@ in :mod:`logging` itself) and defining handlers which are declared either in
.. function:: dictConfig(config)
Takes the logging configuration from a dictionary. The contents of
this dictionary are described in :ref:`logging-config-dictschema`
below.
Takes the logging configuration from a dictionary. The contents of
this dictionary are described in :ref:`logging-config-dictschema`
below.
If an error is encountered during configuration, this function will
raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
or :exc:`ImportError` with a suitably descriptive message. The
following is a (possibly incomplete) list of conditions which will
raise an error:
If an error is encountered during configuration, this function will
raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
or :exc:`ImportError` with a suitably descriptive message. The
following is a (possibly incomplete) list of conditions which will
raise an error:
* A ``level`` which is not a string or which is a string not
corresponding to an actual logging level.
* A ``propagate`` value which is not a boolean.
* An id which does not have a corresponding destination.
* A non-existent handler id found during an incremental call.
* An invalid logger name.
* Inability to resolve to an internal or external object.
* A ``level`` which is not a string or which is a string not
corresponding to an actual logging level.
* A ``propagate`` value which is not a boolean.
* An id which does not have a corresponding destination.
* A non-existent handler id found during an incremental call.
* An invalid logger name.
* Inability to resolve to an internal or external object.
Parsing is performed by the :class:`DictConfigurator` class, whose
constructor is passed the dictionary used for configuration, and
has a :meth:`configure` method. The :mod:`logging.config` module
has a callable attribute :attr:`dictConfigClass`
which is initially set to :class:`DictConfigurator`.
You can replace the value of :attr:`dictConfigClass` with a
suitable implementation of your own.
Parsing is performed by the :class:`DictConfigurator` class, whose
constructor is passed the dictionary used for configuration, and
has a :meth:`configure` method. The :mod:`logging.config` module
has a callable attribute :attr:`dictConfigClass`
which is initially set to :class:`DictConfigurator`.
You can replace the value of :attr:`dictConfigClass` with a
suitable implementation of your own.
:func:`dictConfig` calls :attr:`dictConfigClass` passing
the specified dictionary, and then calls the :meth:`configure` method on
the returned object to put the configuration into effect::
:func:`dictConfig` calls :attr:`dictConfigClass` passing
the specified dictionary, and then calls the :meth:`configure` method on
the returned object to put the configuration into effect::
def dictConfig(config):
dictConfigClass(config).configure()
def dictConfig(config):
dictConfigClass(config).configure()
For example, a subclass of :class:`DictConfigurator` could call
``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
set up custom prefixes which would be usable in the subsequent
:meth:`configure` call. :attr:`dictConfigClass` would be bound to
this new subclass, and then :func:`dictConfig` could be called exactly as
in the default, uncustomized state.
For example, a subclass of :class:`DictConfigurator` could call
``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
set up custom prefixes which would be usable in the subsequent
:meth:`configure` call. :attr:`dictConfigClass` would be bound to
this new subclass, and then :func:`dictConfig` could be called exactly as
in the default, uncustomized state.
.. versionadded:: 3.2

View File

@ -1096,8 +1096,8 @@ functions.
suitable value.
.. versionchanged:: 3.7
The *level* parameter was defaulted to level ``CRITICAL``. See Issue
#28524 for more information about this change.
The *level* parameter was defaulted to level ``CRITICAL``. See
:issue:`28524` for more information about this change.
.. function:: addLevelName(level, levelName)
@ -1174,7 +1174,9 @@ functions.
| | to ``'a'``. |
+--------------+---------------------------------------------+
| *format* | Use the specified format string for the |
| | handler. |
| | handler. Defaults to attributes |
| | ``levelname``, ``name`` and ``message`` |
| | separated by colons. |
+--------------+---------------------------------------------+
| *datefmt* | Use the specified date/time format, as |
| | accepted by :func:`time.strftime`. |

View File

@ -33,7 +33,7 @@ from multiple threads, it is necessary to protect it with a lock.
Reading and writing compressed files
------------------------------------
.. function:: open(filename, mode="rb", \*, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None)
.. function:: open(filename, mode="rb", *, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None)
Open an LZMA-compressed file in binary or text mode, returning a :term:`file
object`.
@ -69,7 +69,7 @@ Reading and writing compressed files
Accepts a :term:`path-like object`.
.. class:: LZMAFile(filename=None, mode="r", \*, format=None, check=-1, preset=None, filters=None)
.. class:: LZMAFile(filename=None, mode="r", *, format=None, check=-1, preset=None, filters=None)
Open an LZMA-compressed file in binary mode.

View File

@ -1,13 +0,0 @@
.. _misc:
**********************
Miscellaneous Services
**********************
The modules described in this chapter provide miscellaneous services that are
available in all Python versions. Here's an overview:
.. toctree::
formatter.rst

View File

@ -337,6 +337,8 @@ MADV_* Constants
MADV_NOCORE
MADV_CORE
MADV_PROTECT
MADV_FREE_REUSABLE
MADV_FREE_REUSE
These options can be passed to :meth:`mmap.madvise`. Not every option will
be present on every system.

View File

@ -98,7 +98,7 @@ to start a process. These *start methods* are
*spawn*
The parent process starts a fresh python interpreter process. The
child process will only inherit those resources necessary to run
the process objects :meth:`~Process.run` method. In particular,
the process object's :meth:`~Process.run` method. In particular,
unnecessary file descriptors and handles from the parent process
will not be inherited. Starting a process using this method is
rather slow compared to using *fork* or *forkserver*.
@ -2569,9 +2569,9 @@ Address Formats
filesystem.
* An ``'AF_PIPE'`` address is a string of the form
:samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
pipe on a remote computer called *ServerName* one should use an address of the
form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
:samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
pipe on a remote computer called *ServerName* one should use an address of the
form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Note that any string beginning with two backslashes is assumed by default to be
an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
@ -2661,6 +2661,46 @@ The :mod:`multiprocessing.dummy` module
:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
no more than a wrapper around the :mod:`threading` module.
.. currentmodule:: multiprocessing.pool
In particular, the ``Pool`` function provided by :mod:`multiprocessing.dummy`
returns an instance of :class:`ThreadPool`, which is a subclass of
:class:`Pool` that supports all the same method calls but uses a pool of
worker threads rather than worker processes.
.. class:: ThreadPool([processes[, initializer[, initargs]]])
A thread pool object which controls a pool of worker threads to which jobs
can be submitted. :class:`ThreadPool` instances are fully interface
compatible with :class:`Pool` instances, and their resources must also be
properly managed, either by using the pool as a context manager or by
calling :meth:`~multiprocessing.pool.Pool.close` and
:meth:`~multiprocessing.pool.Pool.terminate` manually.
*processes* is the number of worker threads to use. If *processes* is
``None`` then the number returned by :func:`os.cpu_count` is used.
If *initializer* is not ``None`` then each worker process will call
``initializer(*initargs)`` when it starts.
Unlike :class:`Pool`, *maxtasksperchild* and *context* cannot be provided.
.. note::
A :class:`ThreadPool` shares the same interface as :class:`Pool`, which
is designed around a pool of processes and predates the introduction of
the :class:`concurrent.futures` module. As such, it inherits some
operations that don't make sense for a pool backed by threads, and it
has its own type for representing the status of asynchronous jobs,
:class:`AsyncResult`, that is not understood by any other libraries.
Users should generally prefer to use
:class:`concurrent.futures.ThreadPoolExecutor`, which has a simpler
interface that was designed around threads from the start, and which
returns :class:`concurrent.futures.Future` instances that are
compatible with many other libraries, including :mod:`asyncio`.
.. _multiprocessing-programming:

View File

@ -32,7 +32,7 @@ Notes on the availability of these functions:
objects, and result in an object of the same type, if a path or file name is
returned.
* On VxWorks, os.fork, os.execv and os.spawn*p* are not supported.
* On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
.. note::
@ -113,6 +113,8 @@ of the UTF-8 encoding:
:ref:`error handler <error-handlers>` being enabled for :data:`sys.stdin`
and :data:`sys.stdout` (:data:`sys.stderr` continues to use
``backslashreplace`` as it does in the default locale-aware mode)
* On Unix, :func:`os.device_encoding` returns ``'UTF-8'``. rather than the
device encoding.
Note that the standard stream settings in UTF-8 mode can be overridden by
:envvar:`PYTHONIOENCODING` (just as they can be in the default locale-aware
@ -808,6 +810,12 @@ as internal buffering of data.
Return a string describing the encoding of the device associated with *fd*
if it is connected to a terminal; else return :const:`None`.
On Unix, if the :ref:`Python UTF-8 Mode <utf8-mode>` is enabled, return
``'UTF-8'`` rather than the device encoding.
.. versionchanged:: 3.10
On Unix, the function now implements the Python UTF-8 Mode.
.. function:: dup(fd)
@ -1315,12 +1323,12 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
.. data:: RWF_APPEND
Provide a per-write equivalent of the :data:`O_APPEND` :func:`os.open`
flag. This flag is meaningful only for :func:`os.pwritev`, and its
effect applies only to the data range written by the system call. The
*offset* argument does not affect the write operation; the data is always
appended to the end of the file. However, if the *offset* argument is
``-1``, the current file *offset* is updated.
Provide a per-write equivalent of the :data:`O_APPEND` :func:`os.open`
flag. This flag is meaningful only for :func:`os.pwritev`, and its
effect applies only to the data range written by the system call. The
*offset* argument does not affect the write operation; the data is always
appended to the end of the file. However, if the *offset* argument is
``-1``, the current file *offset* is updated.
.. availability:: Linux 4.16 and newer.
@ -1411,6 +1419,39 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
.. versionadded:: 3.3
.. function:: splice(src, dst, count, offset_src=None, offset_dst=None)
Transfer *count* bytes from file descriptor *src*, starting from offset
*offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
At least one of the file descriptors must refer to a pipe. If *offset_src*
is None, then *src* is read from the current position; respectively for
*offset_dst*. The offset associated to the file descriptor that refers to a
pipe must be ``None``. The files pointed by *src* and *dst* must reside in
the same filesystem, otherwise an :exc:`OSError` is raised with
:attr:`~OSError.errno` set to :data:`errno.EXDEV`.
This copy is done without the additional cost of transferring data
from the kernel to user space and then back into the kernel. Additionally,
some filesystems could implement extra optimizations. The copy is done as if
both files are opened as binary.
Upon successful completion, returns the number of bytes spliced to or from
the pipe. A return value of 0 means end of input. If *src* refers to a
pipe, then this means that there was no data to transfer, and it would not
make sense to block because there are no writers connected to the write end
of the pipe.
.. availability:: Linux kernel >= 2.6.17 and glibc >= 2.5
.. versionadded:: 3.10
.. data:: SPLICE_F_MOVE
SPLICE_F_NONBLOCK
SPLICE_F_MORE
.. versionadded:: 3.10
.. function:: readv(fd, buffers)
Read from a file descriptor *fd* into a number of mutable :term:`bytes-like
@ -1950,7 +1991,7 @@ features:
Accepts a :term:`path-like object`.
.. function:: lstat(path, \*, dir_fd=None)
.. function:: lstat(path, *, dir_fd=None)
Perform the equivalent of an :c:func:`lstat` system call on the given path.
Similar to :func:`~os.stat`, but does not follow symbolic links. Return a
@ -2457,7 +2498,7 @@ features:
On the first, uncached call, a system call is required on Windows but
not on Unix.
.. method:: is_dir(\*, follow_symlinks=True)
.. method:: is_dir(*, follow_symlinks=True)
Return ``True`` if this entry is a directory or a symbolic link pointing
to a directory; return ``False`` if the entry is or points to any other
@ -2481,7 +2522,7 @@ features:
This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
but :exc:`FileNotFoundError` is caught and not raised.
.. method:: is_file(\*, follow_symlinks=True)
.. method:: is_file(*, follow_symlinks=True)
Return ``True`` if this entry is a file or a symbolic link pointing to a
file; return ``False`` if the entry is or points to a directory or other
@ -2511,7 +2552,7 @@ features:
This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
but :exc:`FileNotFoundError` is caught and not raised.
.. method:: stat(\*, follow_symlinks=True)
.. method:: stat(*, follow_symlinks=True)
Return a :class:`stat_result` object for this entry. This method
follows symbolic links by default; to stat a symbolic link add the
@ -2543,7 +2584,7 @@ features:
for :class:`bytes` paths on Windows.
.. function:: stat(path, \*, dir_fd=None, follow_symlinks=True)
.. function:: stat(path, *, dir_fd=None, follow_symlinks=True)
Get the status of a file or a file descriptor. Perform the equivalent of a
:c:func:`stat` system call on the given path. *path* may be specified as
@ -3268,6 +3309,102 @@ features:
.. versionadded:: 3.8
.. function:: eventfd(initval[, flags=os.EFD_CLOEXEC])
Create and return an event file descriptor. The file descriptors supports
raw :func:`read` and :func:`write` with a buffer size of 8,
:func:`~select.select`, :func:`~select.poll` and similar. See man page
:manpage:`eventfd(2)` for more information. By default, the
new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
*initval* is the initial value of the event counter. The initial value
must be an 32 bit unsigned integer. Please note that the initial value is
limited to a 32 bit unsigned int although the event counter is an unsigned
64 bit integer with a maximum value of 2\ :sup:`64`\ -\ 2.
*flags* can be constructed from :const:`EFD_CLOEXEC`,
:const:`EFD_NONBLOCK`, and :const:`EFD_SEMAPHORE`.
If :const:`EFD_SEMAPHORE` is specified and the event counter is non-zero,
:func:`eventfd_read` returns 1 and decrements the counter by one.
If :const:`EFD_SEMAPHORE` is not specified and the event counter is
non-zero, :func:`eventfd_read` returns the current event counter value and
resets the counter to zero.
If the event counter is zero and :const:`EFD_NONBLOCK` is not
specified, :func:`eventfd_read` blocks.
:func:`eventfd_write` increments the event counter. Write blocks if the
write operation would increment the counter to a value larger than
2\ :sup:`64`\ -\ 2.
Example::
import os
# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
try:
# acquire semaphore
v = os.eventfd_read(fd)
try:
do_work()
finally:
# release semaphore
os.eventfd_write(fd, v)
finally:
os.close(fd)
.. availability:: Linux 2.6.27 or newer with glibc 2.8 or newer.
.. versionadded:: 3.10
.. function:: eventfd_read(fd)
Read value from an :func:`eventfd` file descriptor and return a 64 bit
unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
.. availability:: See :func:`eventfd`
.. versionadded:: 3.10
.. function:: eventfd_write(fd, value)
Add value to an :func:`eventfd` file descriptor. *value* must be a 64 bit
unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
.. availability:: See :func:`eventfd`
.. versionadded:: 3.10
.. data:: EFD_CLOEXEC
Set close-on-exec flag for new :func:`eventfd` file descriptor.
.. availability:: See :func:`eventfd`
.. versionadded:: 3.10
.. data:: EFD_NONBLOCK
Set :const:`O_NONBLOCK` status flag for new :func:`eventfd` file
descriptor.
.. availability:: See :func:`eventfd`
.. versionadded:: 3.10
.. data:: EFD_SEMAPHORE
Provide semaphore-like semantics for reads from a :func:`eventfd` file
descriptor. On read the internal counter is decremented by one.
.. availability:: Linux 2.6.30 or newer with glibc 2.8 or newer.
.. versionadded:: 3.10
Linux extended attributes
~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -336,6 +336,8 @@ Pure paths provide the following methods and properties:
>>> p.parents[2]
PureWindowsPath('c:/')
.. versionchanged:: 3.10
The parents sequence now supports :term:`slices <slice>` and negative index values.
.. data:: PurePath.parent

View File

@ -213,7 +213,7 @@ The :mod:`pickle` module provides the following constants:
The :mod:`pickle` module provides the following functions to make the pickling
process more convenient:
.. function:: dump(obj, file, protocol=None, \*, fix_imports=True, buffer_callback=None)
.. function:: dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
Write the pickled representation of the object *obj* to the open
:term:`file object` *file*. This is equivalent to
@ -225,7 +225,7 @@ process more convenient:
.. versionchanged:: 3.8
The *buffer_callback* argument was added.
.. function:: dumps(obj, protocol=None, \*, fix_imports=True, buffer_callback=None)
.. function:: dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)
Return the pickled representation of the object *obj* as a :class:`bytes` object,
instead of writing it to a file.
@ -236,7 +236,7 @@ process more convenient:
.. versionchanged:: 3.8
The *buffer_callback* argument was added.
.. function:: load(file, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
.. function:: load(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
Read the pickled representation of an object from the open :term:`file object`
*file* and return the reconstituted object hierarchy specified therein.
@ -252,7 +252,7 @@ process more convenient:
.. versionchanged:: 3.8
The *buffers* argument was added.
.. function:: loads(data, /, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
.. function:: loads(data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
Return the reconstituted object hierarchy of the pickled representation
*data* of an object. *data* must be a :term:`bytes-like object`.
@ -296,7 +296,7 @@ The :mod:`pickle` module defines three exceptions:
The :mod:`pickle` module exports three classes, :class:`Pickler`,
:class:`Unpickler` and :class:`PickleBuffer`:
.. class:: Pickler(file, protocol=None, \*, fix_imports=True, buffer_callback=None)
.. class:: Pickler(file, protocol=None, *, fix_imports=True, buffer_callback=None)
This takes a binary file for writing a pickle data stream.
@ -391,7 +391,7 @@ The :mod:`pickle` module exports three classes, :class:`Pickler`,
Use :func:`pickletools.optimize` if you need more compact pickles.
.. class:: Unpickler(file, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
.. class:: Unpickler(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)
This takes a binary file for reading a pickle data stream.

View File

@ -17,6 +17,8 @@ The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
Because the module uses :program:`/bin/sh` command lines, a POSIX or compatible
shell for :func:`os.system` and :func:`os.popen` is required.
.. availability:: Unix. Not available on VxWorks.
The :mod:`pipes` module defines the following class:

View File

@ -209,13 +209,6 @@ Windows Platform
which means the OS version uses debugging code, i.e. code that checks arguments,
ranges, etc.
.. note::
This function works best with Mark Hammond's
:mod:`win32all` package installed, but also on Python 2.3 and
later (support for this was added in Python 2.6). It obviously
only runs on Win32 compatible platforms.
.. function:: win32_edition()
Returns a string representing the current Windows edition. Possible
@ -260,3 +253,41 @@ Unix Platforms
using :program:`gcc`.
The file is read and scanned in chunks of *chunksize* bytes.
Linux Platforms
---------------
.. function:: freedesktop_os_release()
Get operating system identification from ``os-release`` file and return
it as a dict. The ``os-release`` file is a `freedesktop.org standard
<https://www.freedesktop.org/software/systemd/man/os-release.html>`_ and
is available in most Linux distributions. A noticeable exception is
Android and Android-based distributions.
Raises :exc:`OSError` or subclass when neither ``/etc/os-release`` nor
``/usr/lib/os-release`` can be read.
On success, the function returns a dictionary where keys and values are
strings. Values have their special characters like ``"`` and ``$``
unquoted. The fields ``NAME``, ``ID``, and ``PRETTY_NAME`` are always
defined according to the standard. All other fields are optional. Vendors
may include additional fields.
Note that fields like ``NAME``, ``VERSION``, and ``VARIANT`` are strings
suitable for presentation to users. Programs should use fields like
``ID``, ``ID_LIKE``, ``VERSION_ID``, or ``VARIANT_ID`` to identify
Linux distributions.
Example::
def get_like_distro():
info = platform.freedesktop_os_release()
ids = [info["ID"]]
if "ID_LIKE" in info:
# ids are space separated and ordered by precedence
ids.extend(info["ID_LIKE"].split())
return ids
.. versionadded:: 3.10

View File

@ -52,7 +52,7 @@ or :class:`datetime.datetime` objects.
This module defines the following functions:
.. function:: load(fp, \*, fmt=None, dict_type=dict)
.. function:: load(fp, *, fmt=None, dict_type=dict)
Read a plist file. *fp* should be a readable and binary file object.
Return the unpacked root object (which usually is a
@ -80,7 +80,7 @@ This module defines the following functions:
.. versionadded:: 3.4
.. function:: loads(data, \*, fmt=None, dict_type=dict)
.. function:: loads(data, *, fmt=None, dict_type=dict)
Load a plist from a bytes object. See :func:`load` for an explanation of
the keyword arguments.
@ -88,7 +88,7 @@ This module defines the following functions:
.. versionadded:: 3.4
.. function:: dump(value, fp, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False)
.. function:: dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Write *value* to a plist file. *Fp* should be a writable, binary
file object.
@ -116,7 +116,7 @@ This module defines the following functions:
.. versionadded:: 3.4
.. function:: dumps(value, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False)
.. function:: dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Return *value* as a plist-formatted bytes object. See
the documentation for :func:`dump` for an explanation of the keyword

View File

@ -525,16 +525,16 @@ Analysis of the profiler data is done using the :class:`~pstats.Stats` class.
ordering are identical to the :meth:`~pstats.Stats.print_callers` method.
.. method:: get_stats_profile()
.. method:: get_stats_profile()
This method returns an instance of StatsProfile, which contains a mapping
of function names to instances of FunctionProfile. Each FunctionProfile
instance holds information related to the function's profile such as how
long the function took to run, how many times it was called, etc...
.. versionadded:: 3.9
Added the following dataclasses: StatsProfile, FunctionProfile.
Added the following function: get_stats_profile.
.. versionadded:: 3.9
Added the following dataclasses: StatsProfile, FunctionProfile.
Added the following function: get_stats_profile.
.. _deterministic-profiling:

View File

@ -97,6 +97,13 @@ statements. They have the following attributes:
.. versionadded:: 3.7
.. attribute:: Function.is_async
``True`` for functions that are defined with the ``async`` prefix, ``False`` otherwise.
.. versionadded:: 3.10
.. _pyclbr-class-objects:
Class Objects

View File

@ -142,10 +142,11 @@ Functions for integers
.. function:: getrandbits(k)
Returns a Python integer with *k* random bits. This method is supplied with
the MersenneTwister generator and some other generators may also provide it
as an optional part of the API. When available, :meth:`getrandbits` enables
:meth:`randrange` to handle arbitrarily large ranges.
Returns a non-negative Python integer with *k* random bits. This method
is supplied with the MersenneTwister generator and some other generators
may also provide it as an optional part of the API. When available,
:meth:`getrandbits` enables :meth:`randrange` to handle arbitrarily large
ranges.
.. versionchanged:: 3.9
This method now accepts zero for *k*.

View File

@ -61,6 +61,20 @@ The :mod:`shlex` module defines the following functions:
string that can safely be used as one token in a shell command line, for
cases where you cannot use a list.
.. _shlex-quote-warning:
.. warning::
The ``shlex`` module is **only designed for Unix shells**.
The :func:`quote` function is not guaranteed to be correct on non-POSIX
compliant shells or shells from other operating systems such as Windows.
Executing commands quoted by this module on such shells can open up the
possibility of a command injection vulnerability.
Consider using functions that pass command arguments with lists such as
:func:`subprocess.run` with ``shell=False``.
This idiom would be unsafe:
>>> filename = 'somefile; rm -rf ~'

View File

@ -218,7 +218,7 @@ Directory and files operations
copy the file more efficiently. See
:ref:`shutil-platform-dependent-efficient-copy-operations` section.
.. function:: ignore_patterns(\*patterns)
.. function:: ignore_patterns(*patterns)
This factory function creates a function that can be used as a callable for
:func:`copytree`\'s *ignore* argument, ignoring files and directories that

View File

@ -117,7 +117,7 @@ The variables defined in the :mod:`signal` module are:
Child process stopped or terminated.
.. availability:: Windows.
.. availability:: Unix.
.. data:: SIGCLD

View File

@ -32,7 +32,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
than a success code, an :exc:`SMTPConnectError` is raised. The optional
*timeout* parameter specifies a timeout in seconds for blocking operations
like the connection attempt (if not specified, the global default timeout
setting will be used). If the timeout expires, :exc:`socket.timeout` is
setting will be used). If the timeout expires, :exc:`TimeoutError` is
raised. The optional source_address parameter allows binding
to some specific source address in a machine with multiple network
interfaces, and/or to some specific source TCP port. It takes a 2-tuple
@ -115,7 +115,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
If the *timeout* parameter is set to be zero, it will raise a
:class:`ValueError` to prevent the creation of a non-blocking socket
.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None,
.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, \
source_address=None[, timeout])
The LMTP protocol, which is very similar to ESMTP, is heavily based on the

View File

@ -56,12 +56,12 @@ created. Socket addresses are represented as follows:
bytes-like object can be used for either type of address when
passing it as an argument.
.. versionchanged:: 3.3
Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8
encoding.
.. versionchanged:: 3.3
Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8
encoding.
.. versionchanged:: 3.5
Writable :term:`bytes-like object` is now accepted.
.. versionchanged:: 3.5
Writable :term:`bytes-like object` is now accepted.
.. _host_port:
@ -283,6 +283,8 @@ Exceptions
.. exception:: timeout
A deprecated alias of :exc:`TimeoutError`.
A subclass of :exc:`OSError`, this exception is raised when a timeout
occurs on a socket which has had timeouts enabled via a prior call to
:meth:`~socket.settimeout` (or implicitly through
@ -292,6 +294,9 @@ Exceptions
.. versionchanged:: 3.3
This class was made a subclass of :exc:`OSError`.
.. versionchanged:: 3.10
This class was made an alias of :exc:`TimeoutError`.
Constants
^^^^^^^^^
@ -1208,7 +1213,7 @@ to sockets.
address family --- see above.)
If the connection is interrupted by a signal, the method waits until the
connection completes, or raise a :exc:`socket.timeout` on timeout, if the
connection completes, or raise a :exc:`TimeoutError` on timeout, if the
signal handler doesn't raise an exception and the socket is blocking or has
a timeout. For non-blocking sockets, the method raises an
:exc:`InterruptedError` exception if the connection is interrupted by a

View File

@ -198,7 +198,9 @@ Module functions and constants
*detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
type detection on.
type detection on. Due to SQLite behaviour, types can't be detected for generated
fields (for example ``max(data)``), even when *detect_types* parameter is set. In
such case, the returned type is :class:`str`.
By default, *check_same_thread* is :const:`True` and only the creating thread may
use the connection. If set :const:`False`, the returned connection may be shared

View File

@ -156,10 +156,11 @@ However, for reading convenience, most of the examples show sorted sequences.
.. versionadded:: 3.8
.. function:: harmonic_mean(data)
.. function:: harmonic_mean(data, weights=None)
Return the harmonic mean of *data*, a sequence or iterable of
real-valued numbers.
real-valued numbers. If *weights* is omitted or *None*, then
equal weighting is assumed.
The harmonic mean, sometimes called the subcontrary mean, is the
reciprocal of the arithmetic :func:`mean` of the reciprocals of the
@ -179,17 +180,17 @@ However, for reading convenience, most of the examples show sorted sequences.
>>> harmonic_mean([40, 60])
48.0
Suppose an investor purchases an equal value of shares in each of
three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
What is the average P/E ratio for the investor's portfolio?
Suppose a car travels 40 km/hr for 5 km, and when traffic clears,
speeds-up to 60 km/hr for the remaining 30 km of the journey. What
is the average speed?
.. doctest::
>>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
3.6
>>> harmonic_mean([40, 60], weights=[5, 30])
56.0
:exc:`StatisticsError` is raised if *data* is empty, or any element
is less than zero.
:exc:`StatisticsError` is raised if *data* is empty, any element
is less than zero, or if the weighted sum isn't positive.
The current algorithm has an early-out when it encounters a zero
in the input. This means that the subsequent inputs are not tested
@ -197,6 +198,8 @@ However, for reading convenience, most of the examples show sorted sequences.
.. versionadded:: 3.6
.. versionchanged:: 3.8
Added support for *weights*.
.. function:: median(data)

View File

@ -499,7 +499,7 @@ class`. In addition, it provides a few more methods:
.. versionadded:: 3.10
.. method:: int.to_bytes(length, byteorder, \*, signed=False)
.. method:: int.to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
@ -531,7 +531,7 @@ class`. In addition, it provides a few more methods:
.. versionadded:: 3.2
.. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
.. classmethod:: int.from_bytes(bytes, byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
@ -5065,7 +5065,7 @@ instantiated from the type::
>>> class M(type):
... def __or__(self, other):
... return "Hello"
... return "Hello"
...
>>> class C(metaclass=M):
... pass
@ -5353,8 +5353,8 @@ types, where they are relevant. Some of these are not reported by the
.. method:: class.__subclasses__
Each class keeps a list of weak references to its immediate subclasses. This
method returns a list of all those references still alive.
Example::
method returns a list of all those references still alive. The list is in
definition order. Example::
>>> int.__subclasses__()
[<class 'bool'>]

View File

@ -384,10 +384,10 @@ following:
The ``'#'`` option causes the "alternate form" to be used for the
conversion. The alternate form is defined differently for different
types. This option is only valid for integer, float, complex and
Decimal types. For integers, when binary, octal, or hexadecimal output
types. This option is only valid for integer, float and complex
types. For integers, when binary, octal, or hexadecimal output
is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
``'0x'`` to the output value. For floats, complex and Decimal the
``'0x'`` to the output value. For float and complex the
alternate form causes the result of the conversion to always contain a
decimal-point character, even if no digits follow it. Normally, a
decimal-point character appears in the result of these conversions
@ -476,20 +476,36 @@ with the floating point presentation types listed below (except
``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
integer to a floating point number before formatting.
The available presentation types for floating point and decimal values are:
The available presentation types for :class:`float` and
:class:`~decimal.Decimal` values are:
+---------+----------------------------------------------------------+
| Type | Meaning |
+=========+==========================================================+
| ``'e'`` | Exponent notation. Prints the number in scientific |
| | notation using the letter 'e' to indicate the exponent. |
| | The default precision is ``6``. |
| ``'e'`` | Scientific notation. For a given precision ``p``, |
| | formats the number in scientific notation with the |
| | letter 'e' separating the coefficient from the exponent. |
| | The coefficient has one digit before and ``p`` digits |
| | after the decimal point, for a total of ``p + 1`` |
| | significant digits. With no precision given, uses a |
| | precision of ``6`` digits after the decimal point for |
| | :class:`float`, and shows all coefficient digits |
| | for :class:`~decimal.Decimal`. If no digits follow the |
| | decimal point, the decimal point is also removed unless |
| | the ``#`` option is used. |
+---------+----------------------------------------------------------+
| ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
| | upper case 'E' as the separator character. |
| ``'E'`` | Scientific notation. Same as ``'e'`` except it uses |
| | an upper case 'E' as the separator character. |
+---------+----------------------------------------------------------+
| ``'f'`` | Fixed-point notation. Displays the number as a |
| | fixed-point number. The default precision is ``6``. |
| ``'f'`` | Fixed-point notation. For a given precision ``p``, |
| | formats the number as a decimal number with exactly |
| | ``p`` digits following the decimal point. With no |
| | precision given, uses a precision of ``6`` digits after |
| | the decimal point for :class:`float`, and uses a |
| | precision large enough to show all coefficient digits |
| | for :class:`~decimal.Decimal`. If no digits follow the |
| | decimal point, the decimal point is also removed unless |
| | the ``#`` option is used. |
+---------+----------------------------------------------------------+
| ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts |
| | ``nan`` to ``NAN`` and ``inf`` to ``INF``. |
@ -498,6 +514,8 @@ The available presentation types for floating point and decimal values are:
| | this rounds the number to ``p`` significant digits and |
| | then formats the result in either fixed-point format |
| | or in scientific notation, depending on its magnitude. |
| | A precision of ``0`` is treated as equivalent to a |
| | precision of ``1``. |
| | |
| | The precise rules are as follows: suppose that the |
| | result formatted with presentation type ``'e'`` and |
@ -512,13 +530,19 @@ The available presentation types for floating point and decimal values are:
| | removed if there are no remaining digits following it, |
| | unless the ``'#'`` option is used. |
| | |
| | With no precision given, uses a precision of ``6`` |
| | significant digits for :class:`float`. For |
| | :class:`~decimal.Decimal`, the coefficient of the result |
| | is formed from the coefficient digits of the value; |
| | scientific notation is used for values smaller than |
| | ``1e-6`` in absolute value and values where the place |
| | value of the least significant digit is larger than 1, |
| | and fixed-point notation is used otherwise. |
| | |
| | Positive and negative infinity, positive and negative |
| | zero, and nans, are formatted as ``inf``, ``-inf``, |
| | ``0``, ``-0`` and ``nan`` respectively, regardless of |
| | the precision. |
| | |
| | A precision of ``0`` is treated as equivalent to a |
| | precision of ``1``. The default precision is ``6``. |
+---------+----------------------------------------------------------+
| ``'G'`` | General format. Same as ``'g'`` except switches to |
| | ``'E'`` if the number gets too large. The |
@ -531,12 +555,18 @@ The available presentation types for floating point and decimal values are:
| ``'%'`` | Percentage. Multiplies the number by 100 and displays |
| | in fixed (``'f'``) format, followed by a percent sign. |
+---------+----------------------------------------------------------+
| None | Similar to ``'g'``, except that fixed-point notation, |
| | when used, has at least one digit past the decimal point.|
| | The default precision is as high as needed to represent |
| | the particular value. The overall effect is to match the |
| | output of :func:`str` as altered by the other format |
| | modifiers. |
| None | For :class:`float` this is the same as ``'g'``, except |
| | that when fixed-point notation is used to format the |
| | result, it always includes at least one digit past the |
| | decimal point. The precision used is as large as needed |
| | to represent the given value faithfully. |
| | |
| | For :class:`~decimal.Decimal`, this is the same as |
| | either ``'g'`` or ``'G'`` depending on the value of |
| | ``context.capitals`` for the current decimal context. |
| | |
| | The overall effect is to match the output of :func:`str` |
| | as altered by the other format modifiers. |
+---------+----------------------------------------------------------+

View File

@ -339,7 +339,7 @@ functions.
stderr=None, preexec_fn=None, close_fds=True, shell=False, \
cwd=None, env=None, universal_newlines=None, \
startupinfo=None, creationflags=0, restore_signals=True, \
start_new_session=False, pass_fds=(), \*, group=None, \
start_new_session=False, pass_fds=(), *, group=None, \
extra_groups=None, user=None, umask=-1, \
encoding=None, errors=None, text=None, pipesize=-1)
@ -718,11 +718,8 @@ If the shell is invoked explicitly, via ``shell=True``, it is the application's
responsibility to ensure that all whitespace and metacharacters are
quoted appropriately to avoid
`shell injection <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
vulnerabilities.
When using ``shell=True``, the :func:`shlex.quote` function can be
used to properly escape whitespace and shell metacharacters in strings
that are going to be used to construct shell commands.
vulnerabilities. On :ref:`some platforms <shlex-quote-warning>`, it is possible
to use :func:`shlex.quote` for this escaping.
Popen Objects
@ -1190,8 +1187,9 @@ calls these functions.
The arguments shown above are merely some common ones.
The full function signature is largely the same as that of :func:`run` -
most arguments are passed directly through to that interface.
However, explicitly passing ``input=None`` to inherit the parent's
standard input file handle is not supported.
One API deviation from :func:`run` behavior exists: passing ``input=None``
will behave the same as ``input=b''`` (or ``input=''``, depending on other
arguments) rather than using the parent's standard input file handle.
By default, this function will return the data as encoded bytes. The actual
encoding of the output data may depend on the command being invoked, so the
@ -1284,7 +1282,7 @@ be used directly:
becomes::
output=check_output("dmesg | grep hda", shell=True)
output = check_output("dmesg | grep hda", shell=True)
Replacing :func:`os.system`

View File

@ -156,7 +156,7 @@ Examining Symbol Tables
Return ``True`` if the symbol is local to its block.
.. method:: is_annotated()
.. method:: is_annotated()
Return ``True`` if the symbol is annotated.

Some files were not shown because too many files have changed in this diff Show More