Compare commits

..

269 Commits

Author SHA1 Message Date
Cheryl Sabella e40e2a2cc9
bpo-32631: IDLE: Enable zzdummy example extension module (GH-14491)
Make menu items work with formatter, add docstrings, add 100% tests.

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
2021-01-05 02:26:43 -05:00
Serhiy Storchaka 59f9b4e450
bpo-42681: Fix test_curses failures related to color pairs (GH-24089)
On ncurses 6.1 pair numbers are limited by SHORT_MAX-1, even
with extended color support.

Improve error reporting and tests for color functions.
2021-01-05 09:13:15 +02:00
Brandt Bucher 27f9dafc2b
bpo-40636: Remove overly-strict zip pickling tests (GH-24109) 2021-01-04 23:05:29 -08:00
Brandt Bucher cde988e893
Fix broken NEWS markup (GH-24110) 2021-01-04 22:55:14 -08:00
Erlend Egeberg Aasland f7f0ed59bc
bpo-40810: Fix CheckTraceCallbackContent for SQLite pre 3.7.15 (GH-20530)
Ref. [SQLite 3.7.15 changelog](https://sqlite.org/changes.html#version_3_7_15):
_"Avoid invoking the sqlite3_trace() callback multiple times when a statement is automatically reprepared due to SQLITE_SCHEMA errors."_
2021-01-04 15:16:43 -08:00
Erlend Egeberg Aasland 0b858cdd5d
bpo-1635741: Convert _multibytecodec to multi-phase init (GH-24095)
Convert the _multibytecodec extension module (CJK codecs) to multi-phase
initialization (PEP 489).
2021-01-04 22:33:45 +01:00
Pablo Galindo 958acd2da0
Post 3.10.0a4 2021-01-04 21:17:03 +00:00
Pablo Galindo ef2d371dee Python 3.10.0a4
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl/zT6kACgkQ/+h0BBaL
 2EeKVhAAxHzHdp1zZyDgqx0yBoHrB/N7aA5aL8dsrRPPIp+vd6CVanCymd2I2W59
 N8ouYoXFDUbDoWW/E26ggnMtbDtN7HUmMV48v9KIeDHVIR+CcSePcT9cWldmZr+m
 9J7aVoU/MswsLbUpLh5XnXYFbPziv2lsaMWz/j/6EX6VpzVuvmS0sg+xYea6/Kg0
 GyE2Le7p5WZ+5He1OJJOPFJ9/yOzj9fix2DDhRP7ZP8Oi+vPlRsDGMO1E3YKQzP1
 4bWhhoSCTDGIW6l0j41xGZYyW7Ror6FqpJqOGygYsA9LwryPdhqQVIVR7sqoK0sC
 xmLF1XrZhipNi+in7XxtmStor9MGVu5oR4Ieawhd70LEOrfdux2I7vTCEz4YqW0K
 7evxZ4fjfKALkAoJZ6WhUHcJf97n08+lyGo5Ng4miBi0VXYaj45l6pdpEPOZKfx1
 flXYThu4VOfZ7ggi4Y/Mxi4U2sQVbNtXD19KhrxsKe+wdfRQ2I/fkYrz/nCA/bJe
 qt7HO9AuyiqbBWQ88ZrnHsZLiuidXiBEQ5Evxb2aDNx+gOTeoa+W02BflRZ2wQN5
 d9+/THh0LE12OARa8DZvYYWRj/IiKLx5YbVkuhMxwBbWpSO4nlq2OKhX5Cdc3hxd
 Pp4j5oZX0Wg283vIwgfZYa3E0TfjSs+bu2euCMsWe/7oFw4ZNKc=
 =3nPI
 -----END PGP SIGNATURE-----
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEz9yiRbEEPPKl+Xhl/+h0BBaL2EcFAl/zhaAACgkQ/+h0BBaL
 2Ecvow//bxy+jIPxR7IDlnTOxUMBXU/97ed9AozzPUzfov09S5OYP04S1UDC8dqt
 DqLzCBPJrc/+t8t6q2oksfOJGHrPJOQIBDKEST7yxa0k7TbZodJ3QVqHAe2dYF48
 QbACiOphBCXwUBR+Gk6kJxZAPUZelyUxL4ZgZMhFvJD5ONVl3VWeMzodCejYluYM
 Zs6MRMOHvbcaZgrB4M7fn2TS+ZAaFqORsMx/FSzNLmJf+42iTI/ZGICwRFMaiB6V
 Z1A9ajvcm8W37RL1GLAe7fE43WUzmE1QhwGnVv2kRoz5Q5tHJy8Rcp//ZIAUCTXq
 4jCX24T0H7ze/vPEkdX4TYc/3Xzd5vR2WqIyVnNjdM/Ye6ouuHmyf701Ql17qBRU
 fJ3aINJkOnXzmlPMsClrA9VxsBnX7raJHuj3YkCkUZv+jM6oap8IwGCO3uTkGVpa
 SiIuZ/2SmSujT6b67CZrBgmJB30uGzUKiqPZKT2rYgLS8C7PnGg0gaPfrcVIvwxZ
 XRAkDBzlY0mhmj8ss66UJc83faLYI+3ralSoRhR/5F3JLd7bIC/0TUBBTbZP9Jec
 +sxO+RQHG2TbN89mULDqbfsPRTuNIF83s9Zcg2OQG09ClVNEfdUKZ1UgMo+X/nST
 ZShaM3oQ720VN9ZzMJrzglMESs2QT37ERKtehInR1YDBytydD3c=
 =UiJ+
 -----END PGP SIGNATURE-----

Merge tag 'v3.10.0a4'

Python 3.10.0a4
2021-01-04 21:16:13 +00:00
Steve Dower af4cd16479
Do not remove x bit from published directories (GH-24101) 2021-01-04 20:56:32 +00:00
Mark Shannon 127dde5916
bpo-42810: Mark jumps at end of if and try statements as artificial. (GH-24091)
* Mark jumps at end of if and try statements as artificial.

* Update importlib

* Add comment explaining the purpose of ADDOP_JUMP_NOLINE.
2021-01-04 18:06:55 +00:00
Pablo Galindo 445f7f54b1
Python 3.10.0a4 2021-01-04 17:26:00 +00:00
Pablo Galindo de833b6013
Fix 'make suspicious' for the itertools module (GH-24097) 2021-01-04 17:24:22 +00:00
Mohamed Koubaa c8a87addb1
bpo-1635741: Port pyexpat to multi-phase init (PEP 489) (GH-22222) 2021-01-04 15:34:26 +01:00
Mark Shannon bf06b209da
Delete the now unused c_do_not_emit_bytecode field. (#24094) 2021-01-04 13:51:17 +00:00
Joshua Root df21f502fd
bpo-42692: fix __builtin_available check on older compilers (GH-23873)
A compiler that doesn't define `__has_builtin` will error out when it is
used on the same line as the check for it.

Automerge-Triggered-By: GH:ronaldoussoren
2021-01-04 02:36:58 -08:00
Serhiy Storchaka b6fc0c406e
bpo-42789: Enable using /dev/tty in test_curses. (GH-24085)
It was temporary disabled for debugging.
2021-01-04 12:30:20 +02:00
Ned Deily 0f3b96b368
Update Sphinx version for macOS installer build. (GH-24082) 2021-01-04 04:43:53 -05:00
Ned Deily a38e04b566
bpo-42361: Update macOS installer build to use Tcl/Tk 8.6.11 (GH-24081)
As of 2021-01-03, Tcl/Tk 8.6.11rc2 is expected to be the final release.
2021-01-04 04:43:11 -05:00
Ned Deily 14097a2785
bpo-41837: Update macOS installer build to use OpenSSL 1.1.1i. (GH-24080) 2021-01-04 04:39:47 -05:00
Erlend Egeberg Aasland c94ee13ad5
bpo-42584: Update macOS installer to use SQLite 3.34.0 (GH-23674) 2021-01-03 23:48:19 -05:00
Serhiy Storchaka 1470edd613
bpo-42681: Fix range checks for color and pair numbers in curses (GH-23874) 2021-01-03 22:51:11 +02:00
Hai Shi 7c83eaa536
bpo-41798: pyexpat: Allocate the expat_CAPI on the heap memory (GH-24061) 2021-01-03 16:47:44 +01:00
Erlend Egeberg Aasland b8eb376590
bpo-40077: Add traverse/clear/free to arraymodule (GH-24066) 2021-01-03 14:11:15 +01:00
Zackery Spytz 6613676861
bpo-38308: Fix the "versionchanged" for the *weights* of harmonic_mean() (GH-23919) 2021-01-03 14:35:26 +02:00
Zackery Spytz 5d3553b0a8
bpo-42814: Fix undefined behavior in Objects/genericaliasobject.c (GH-24073)
In is_typing_name(), va_end() is not always called before the
function returns.  It is undefined behavior to call va_start()
without also calling va_end().
2021-01-03 13:18:25 +01:00
Pablo Galindo 9e8fe1986c
bpo-42093: Tweak the what's new message about the new LOAD_ATTR opcode cache (GH-24070) 2021-01-03 04:37:46 +00:00
Pablo Galindo bd2728b1e8
bpo-42806: Fix ast locations of f-strings inside parentheses (GH-24067) 2021-01-03 01:11:41 +00:00
Lysandros Nikolaou 2ea320dddd
bpo-40631: Disallow single parenthesized star target (GH-24027) 2021-01-03 01:14:21 +02:00
Raymond Hettinger 8f8de7380c
No need to test "istep==1" twice. (GH-24064) 2021-01-02 12:09:56 -08:00
Raymond Hettinger 768fa145cf
bpo-42772: Step argument ignored when stop is None. (GH-24018) 2021-01-02 10:24:51 -08:00
Serhiy Storchaka 607501abb4
bpo-42789: Don't skip curses tests on non-tty. (GH-24009)
If __stdout__ is not attached to terminal, try to use __stderr__
if it is attached to terminal, or open the terminal device, or
use regular file as terminal, but some functions will be untested
in the latter case.
2021-01-02 19:35:15 +02:00
Serhiy Storchaka a25011be8c
bpo-42809: Improve pickle tests for recursive data. (GH-24060) 2021-01-02 19:32:47 +02:00
Erlend Egeberg Aasland 75bf107c62
bpo-40077: Convert arraymodule to use heap types and establish module state (GH-23124) 2021-01-02 17:38:47 +01:00
Ken Jin 49cd68fb1e
bpo-42195: Disallow isinstance/issubclass for subclasses of genericaliases in Union (GH-24059)
Previously this didn't raise an error. Now it will:
```python
from collections.abc import Callable
isinstance(int, list | Callable[..., str])
```
Also added tests in Union since there were previously none for stuff like ``isinstance(list, list | list[int])`` either.

Backport to 3.9 not required.

Automerge-Triggered-By: GH:gvanrossum
2021-01-02 08:19:15 -08:00
Kurochan d9142831ba
handle empty string in variable executable in platform.libc_ver() (#23140) 2021-01-02 17:03:53 +01:00
Ken Jin 11276cd9c4
bpo-41559: Documentation for PEP 612 (GH-24000) 2021-01-01 16:45:50 -08:00
Ross 3bf05327c2
bpo-42756: Configure LMTP Unix-domain socket to use global default timeout when timeout not provided (GH-23969) 2021-01-02 02:20:25 +09:00
Dong-hee Na de6f20a6de
Bring Python into the new year. (GH-24036) 2021-01-02 00:37:23 +09:00
Dong-hee Na ec3165320e
bpo-42794: Update test_nntplib to use offical group name for testing (GH-24037) 2021-01-01 23:20:33 +09:00
Raymond Hettinger c8a7b8fa1b
bpo-42781: Document the mechanics of cached_property from a user viewpoint (GH-24031) 2020-12-31 17:05:58 -08:00
Jason R. Coombs b5711c940f
bpo-37193: Remove thread objects which finished process its request (GH-23127)
This reverts commit aca67da4fe.
2020-12-31 20:19:30 +00:00
Tao He 3631d6deab
Fixes a typo in importlib.metadata. (#23921)
Signed-off-by: Tao He <sighingnow@gmail.com>
2020-12-31 11:37:53 -08:00
Jason R. Coombs a6fd0f414c
bpo-42163, bpo-42189, bpo-42659: Support uname_tuple._replace (for all but processor) (#23010)
* Add test capturing missed expectation with uname_result._replace.

* bpo-42163: Override uname_result._make to allow uname_result._replace to work (for everything but 'processor'.

* Replace hard-coded length with one derived from the definition.

* Add test capturing missed expectation with copy/deepcopy on namedtuple (bpo-42189).

* bpo-42189: Exclude processor parameter when constructing uname_result.

* In _make, rely on __new__ to strip processor.

* Add blurb.

* iter is not necessary here.

* Rely on num_fields in __new__

* Add test for slices on uname

* Add test for copy and pickle.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>

* import pickle

* Fix equality test after pickling.

* Simply rely on __reduce__ for pickling.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
2020-12-31 14:08:03 -05:00
Jason R. Coombs dfdca85dfa
bpo-42382: In importlib.metadata, `EntryPoint` objects now expose `dist` (#23758)
* bpo-42382: In importlib.metadata, `EntryPoint` objects now expose a `.dist` object referencing the `Distribution` when constructed from a `Distribution`.

Also, sync importlib_metadata 3.3:

- Add support for package discovery under package normalization rules.
- The object returned by `metadata()` now has a formally-defined protocol called `PackageMetadata` with declared support for the `.get_all()` method.

* Add blurb

* Remove latent footnote.
2020-12-31 12:56:43 -05:00
Erlend Egeberg Aasland f4936ad1c4
bpo-42393: Raise OverflowError iso. DeprecationWarning on overflow in socket.ntohs and socket.htons (GH-23980) 2020-12-31 15:16:50 +02:00
Brandon Stansbury 9655434cca
bpo-39068: Fix race condition in base64 (GH-17627)
There was a race condition in base64 in lazy initialization of multiple globals.
2020-12-31 11:44:46 +02:00
Raymond Hettinger f421bfce80
Minor improvements to the convolve() recipe (GH-24012)
* Minor improvement to speed and space efficiency for the convolve() recipe
* Don't require convolve's kernel to be a sequence.
2020-12-30 12:51:19 -08:00
Filipe Laíns 4ac923f275
bpo-42773: fix tests not being run on pushes (GH-24004)
There was a typo, we were checking if the "GITHUB_BASE_REF" string
literal was empty instead of the $GITHUB_BASE_REF value. When
$GITHUB_BASE_REF is empty, the action that triggered the run was not a
pull request, so we always run the full test suite.

Signed-off-by: Filipe Laíns <lains@riseup.net>
2020-12-30 06:53:58 -08:00
pxinwr 277ce3060b
bpo-27640: Add --disable-test-modules configure option (GH-23886)
Added --disable-test-modules option to the configure script:
don't build nor install test modules.

Patch by Xavier de Gaye, Thomas Petazzoni and Peixing Xin.

Co-Authored-By: Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
Co-Authored-By: Xavier de Gaye <xdegaye@gmail.com>
2020-12-30 13:50:39 +01:00
Yurii Karabas c56387f80c
bpo-27794: Add `name` attribute to `property` class (GH-23967) 2020-12-30 01:51:24 -08:00
Victor Stinner ba0e49a464
bpo-40137: Fix refleak in _functools_exec() (GH-24006) 2020-12-30 02:24:43 +01:00
Petr Viktorin 056c08211b
bpo-40052: Fix alignment issue in PyVectorcall_Function() (GH-23999)
```
In file included from /usr/include/python3.8/Python.h:147:
In file included from /usr/include/python3.8/abstract.h:837:
/usr/include/python3.8/cpython/abstract.h:91:11: error: cast from 'char *' to 'vectorcallfunc *'
(aka 'struct _object *(**)(struct _object *, struct _object *const *, unsigned long, struct _object *)')
increases required alignment from 1 to 8 [-Werror,-Wcast-align]

    ptr = (vectorcallfunc*)(((char *)callable) + offset);
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
```
Co-Authored-By: Andreas Schneider <asn@cryptomilk.org>
Co-Authored-By: Antoine Pitrou <antoine@python.org>
2020-12-29 15:32:07 -08:00
Andre Delfino 2edfc86f69
bpo-41224: Add versionadded for Symbol.is_annotated (GH-23861) 2020-12-29 15:32:10 +02:00
Erlend Egeberg Aasland 84d79cfda9
bpo-40956: Convert _sqlite3.Row to Argument Clinic (GH-23964) 2020-12-29 15:22:55 +02:00
Jakub Kulík 0159e5efee
bpo-42655: Fix subprocess extra_groups gid conversion (GH-23762) 2020-12-29 14:58:27 +02:00
Hai Shi dd39123970
bpo-40137: Convert _functools module to use PyType_FromModuleAndSpec. (GH-23405) 2020-12-29 04:45:07 -08:00
Michael Wayne Goodman 84402eb110
bpo-42700: Swap descriptions in pyexpat.errors (GH-23876)
The descriptions of the `codes` and `messages` dictionaries in
`xml.parsers.expat.errors` were swapped, and this commit swaps them
back. For example, `codes` maps string descriptions of errors to numeric
error codes, not the other way around.
2020-12-29 14:33:15 +02:00
Jero Bado a4258e8cd7
Fix minor typo in comments in readline.c (GH-23911) 2020-12-29 14:26:57 +02:00
Senthil Kumaran 030a713183
Allow / character in username,password fields in _PROXY envvars. (#23973) 2020-12-29 04:18:42 -08:00
Ross c1af128f5a
bpo-41781: Fix typo in internal function name in typing (GH-23957) 2020-12-29 13:55:28 +02:00
Zackery Spytz 40c2c83899
Fix typo in NEWS (GH23958) 2020-12-29 13:50:22 +02:00
Serhiy Storchaka 1df56bc059
bpo-42759: Fix equality comparison of Variable and Font in Tkinter (GH-23968)
Objects which belong to different Tcl interpreters are now always
different, even if they have the same name.
2020-12-29 12:56:55 +02:00
Serhiy Storchaka 156b7f7052
bpo-42749: Use dynamic version to test for unsupported bignum in Tk (GH-23966)
Tk can internally support bignum even if Tkinter is built without
support of bignum.
2020-12-29 12:55:55 +02:00
Zackery Spytz c56988b88f
bpo-42770: Fix a typo in the email.headerregistry docs (GH-23982)
Automerge-Triggered-By: GH:zware
2020-12-28 20:12:37 -08:00
Ken Jin efb1f0918f
bpo-42740: Support PEP 604, 612 for typing.py get_args and get_origin (GH-23942) 2020-12-28 18:26:19 -08:00
Pablo Galindo a6d63a20df
Fix compiler warnings regarding loss of data (GH-23983) 2020-12-29 00:28:09 +00:00
Pablo Galindo 290f5ae997
Use Py_NewRef in Modules/_struct.c (GH-23981) 2020-12-28 23:59:16 +00:00
Ken Jin 4140f10a16
bpo-42740: Fix get_args for PEP 585 collections.abc.Callable (GH-23963)
PR 1/2. Needs backport to 3.9.
2020-12-28 12:06:19 -08:00
Raymond Hettinger a9621bb301
bpo-42222: Modernize integer test/conversion in randrange() (#23064) 2020-12-28 11:10:34 -08:00
Ammar Askar 1031f23fc3
[workflow] Use MSVC problem matcher for Windows action build (GH-18532)
This makes warnings and errors from the compiler very prominent so this should help prevent warnings from sneaking into the code base and catch them in review. See https://discuss.python.org/t/using-github-problem-matchers-to-catch-warnings-early/4254 for more details

You can see a demo of this in action here: https://github.com/ammaraskar/cpython/pull/15/files#diff-9ba2eeca0f254ece0a9df4d7cb68e870

GCC and Sphinx matchers have previously been added in GH-18567 and GH-20325, respectively.
2020-12-28 12:28:40 -06:00
Erlend Egeberg Aasland bf108bb21e
bpo-40077: Fix typo in simplequeue_get_state_by_type() (GH-23975)
The typo did no damage, but it looks suspicious and confusing.
Introduced by GH-23136.

Skip news.

Automerge-Triggered-By: GH:pitrou
2020-12-28 09:47:16 -08:00
Erlend Egeberg Aasland 897387d2c8
bpo-1635741: sqlite3: Fix ref leak introduced by commit bf64d90 (GH-23972) 2020-12-28 03:09:26 +01:00
Erlend Egeberg Aasland abba83b4b9
bpo-42755: Fix sqlite3.Connection.backup docs (GH-23965)
The `pages` argument default value now reflects the implementation.
2020-12-27 22:35:17 +00: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
535 changed files with 23514 additions and 12248 deletions

View File

@ -12,7 +12,7 @@ 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') }}:
@ -31,7 +31,7 @@ steps:
- ${{ if eq(parameters.upload, 'true') }}:
- task: PublishBuildArtifacts@1
displayName: 'Publish docs'
inputs:
PathToPublish: '$(build.sourcesDirectory)/Doc/build'
ArtifactName: docs

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"

19
.github/problem-matchers/msvc.json vendored Normal file
View File

@ -0,0 +1,19 @@
{
"__comment": "Taken from vscode's vs/workbench/contrib/tasks/common/problemMatcher.ts msCompile rule",
"problemMatcher": [
{
"owner": "msvc-problem-matcher",
"pattern": [
{
"regexp": "^(?:\\s+\\d+\\>)?([^\\s].*)\\((\\d+),?(\\d+)?(?:,\\d+,\\d+)?\\)\\s*:\\s+(error|warning|info)\\s+(\\w{1,2}\\d+)\\s*:\\s*(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"code": 5,
"message": 6
}
]
}
]
}

View File

@ -28,7 +28,7 @@ jobs:
- name: Check for source changes
id: check
run: |
if [ -z "GITHUB_BASE_REF" ]; then
if [ -z "$GITHUB_BASE_REF" ]; then
echo '::set-output name=run_tests::true'
else
git fetch origin $GITHUB_BASE_REF --depth=1
@ -75,6 +75,8 @@ jobs:
fi
- name: Check exported libpython symbols
run: make smelly
- name: Check limited ABI symbols
run: make check-limited-abi
build_win32:
name: 'Windows (x86)'
@ -97,6 +99,8 @@ jobs:
if: needs.check_source.outputs.run_tests == 'true'
steps:
- uses: actions/checkout@v2
- name: Register MSVC problem matcher
run: echo "::add-matcher::.github/problem-matchers/msvc.json"
- name: Build CPython
run: .\PCbuild\build.bat -e -p x64
- name: Display build info

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

@ -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

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

@ -4,7 +4,7 @@ Copyright
Python and this documentation is:
Copyright © 2001-2020 Python Software Foundation. All rights reserved.
Copyright © 2001-2021 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.

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

@ -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

View File

@ -934,32 +934,42 @@ here is a pure Python equivalent:
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
self._name = ''
def __set_name__(self, owner, name):
self._name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
raise AttributeError(f'unreadable attribute {self._name}')
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
raise AttributeError(f"can't set attribute {self._name}")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
raise AttributeError(f"can't delete attribute {self._name}")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
prop = type(self)(fget, self.fset, self.fdel, self.__doc__)
prop._name = self._name
return prop
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
prop = type(self)(self.fget, fset, self.fdel, self.__doc__)
prop._name = self._name
return prop
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
prop = type(self)(self.fget, self.fset, fdel, self.__doc__)
prop._name = self._name
return prop
.. testcode::
:hide:

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
@ -1137,6 +1152,11 @@ Any container can be passed as the *choices* value, so :class:`list` objects,
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
^^^^^^^^
@ -1183,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
@ -1201,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
@ -1215,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
@ -1242,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
@ -1259,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
@ -1277,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
@ -1681,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
@ -1691,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
@ -1714,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

@ -1576,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
@ -1588,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.
@ -1237,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*.
@ -1319,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.

View File

@ -48,7 +48,7 @@ The following top-level asyncio functions can be used to create
and work with streams:
.. coroutinefunction:: open_connection(host=None, port=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)
@ -71,7 +71,7 @@ and work with streams:
The *ssl_handshake_timeout* parameter.
.. coroutinefunction:: start_server(client_connected_cb, host=None, \
port=None, \*, limit=None, \
port=None, *, limit=None, \
family=socket.AF_UNSPEC, \
flags=socket.AI_PASSIVE, sock=None, \
backlog=100, ssl=None, reuse_address=None, \
@ -103,7 +103,7 @@ and work with streams:
.. rubric:: Unix Sockets
.. coroutinefunction:: open_unix_connection(path=None, \*, limit=None, \
.. coroutinefunction:: open_unix_connection(path=None, *, limit=None, \
ssl=None, sock=None, server_hostname=None, \
ssl_handshake_timeout=None)
@ -126,7 +126,7 @@ and work with streams:
.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
\*, limit=None, sock=None, backlog=100, ssl=None, \
*, limit=None, sock=None, backlog=100, ssl=None, \
ssl_handshake_timeout=None, start_serving=True)
Start a Unix socket server.
@ -185,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,8 +61,8 @@ See also the `Examples`_ subsection.
Creating Subprocesses
=====================
.. coroutinefunction:: create_subprocess_exec(program, \*args, stdin=None, \
stdout=None, stderr=None, limit=None, \*\*kwds)
.. coroutinefunction:: create_subprocess_exec(program, *args, stdin=None, \
stdout=None, stderr=None, limit=None, **kwds)
Create a subprocess.
@ -77,7 +77,7 @@ Creating Subprocesses
.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
stdout=None, stderr=None, limit=None, \*\*kwds)
stdout=None, stderr=None, limit=None, **kwds)
Run the *cmd* shell command.

View File

@ -101,8 +101,8 @@ 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.
.. _asyncio_example_sync_event:
@ -135,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()
@ -148,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()

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.
@ -316,7 +316,7 @@ Sleeping
Running Tasks Concurrently
==========================
.. awaitablefunction:: gather(\*aws, return_exceptions=False)
.. awaitablefunction:: gather(*aws, return_exceptions=False)
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
sequence *concurrently*.
@ -488,7 +488,7 @@ Timeouts
Waiting Primitives
==================
.. coroutinefunction:: wait(aws, \*, 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
@ -573,7 +573,7 @@ Waiting Primitives
deprecated.
.. function:: as_completed(aws, \*, timeout=None)
.. function:: as_completed(aws, *, timeout=None)
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
iterable concurrently. Return an iterator of coroutines.
@ -593,7 +593,7 @@ 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.
@ -723,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.
@ -889,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.
@ -910,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

@ -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

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

@ -112,14 +112,15 @@ The module :mod:`curses` defines the following functions:
.. function:: color_content(color_number)
Return the intensity of the red, green, and blue (RGB) components in the color
*color_number*, which must be between ``0`` and :const:`COLORS`. Return a 3-tuple,
*color_number*, which must be between ``0`` and ``COLORS - 1``. Return a 3-tuple,
containing the R,G,B values for the given color, which will be between
``0`` (no component) and ``1000`` (maximum amount of component).
.. function:: color_pair(color_number)
.. function:: color_pair(pair_number)
Return the attribute value for displaying text in the specified color. This
Return the attribute value for displaying text in the specified color pair.
Only the first 256 color pairs are supported. This
attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`,
and the other :const:`A_\*` attributes. :func:`pair_number` is the counterpart
to this function.
@ -287,7 +288,7 @@ The module :mod:`curses` defines the following functions:
Change the definition of a color, taking the number of the color to be changed
followed by three RGB values (for the amounts of red, green, and blue
components). The value of *color_number* must be between ``0`` and
:const:`COLORS`. Each of *r*, *g*, *b*, must be a value between ``0`` and
`COLORS - 1`. Each of *r*, *g*, *b*, must be a value between ``0`` and
``1000``. When :func:`init_color` is used, all occurrences of that color on the
screen immediately change to the new definition. This function is a no-op on
most terminals; it is active only if :func:`can_change_color` returns ``True``.
@ -300,7 +301,8 @@ The module :mod:`curses` defines the following functions:
color number. The value of *pair_number* must be between ``1`` and
``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot
be changed). The value of *fg* and *bg* arguments must be between ``0`` and
:const:`COLORS`. If the color-pair was previously initialized, the screen is
``COLORS - 1``, or, after calling :func:`use_default_colors`, ``-1``.
If the color-pair was previously initialized, the screen is
refreshed and all occurrences of that color-pair are changed to the new
definition.
@ -450,7 +452,7 @@ The module :mod:`curses` defines the following functions:
.. function:: pair_content(pair_number)
Return a tuple ``(fg, bg)`` containing the colors for the requested color pair.
The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``.
The value of *pair_number* must be between ``0`` and ``COLOR_PAIRS - 1``.
.. function:: pair_number(attr)

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

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

@ -289,7 +289,7 @@ variant, :attr:`~.BaseHeader.max_count` is set to 1.
A :class:`ParameterizedMIMEHeader` class that handles the
:mailheader:`Content-Disposition` header.
.. attribute:: content-disposition
.. attribute:: content_disposition
``inline`` and ``attachment`` are the only valid values in common use.

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

@ -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

@ -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

@ -62,16 +62,26 @@ The :mod:`functools` module defines the following functions:
Example::
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = sequence_of_numbers
self._data = tuple(sequence_of_numbers)
@cached_property
def stdev(self):
return statistics.stdev(self._data)
@cached_property
def variance(self):
return statistics.variance(self._data)
The mechanics of :func:`cached_property` are somewhat different from
:func:`property`. A regular property blocks attribute writes unless a
setter is defined. In contrast, a *cached_property* allows writes.
The *cached_property* decorator only runs on lookups and only when an
attribute of the same name doesn't exist. When it does run, the
*cached_property* writes to the attribute with the same name. Subsequent
attribute reads and writes take precedence over the *cached_property*
method and it works like a normal attribute.
The cached value can be cleared by deleting the attribute. This
allows the *cached_property* method to run again.
Note, this decorator interferes with the operation of :pep:`412`
key-sharing dictionaries. This means that instance dictionaries

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

@ -115,8 +115,9 @@ Every distribution includes some metadata, which you can extract using the
>>> wheel_metadata = metadata('wheel') # doctest: +SKIP
The keys of the returned data structure [#f1]_ name the metadata keywords, and
their values are returned unparsed from the distribution metadata::
The keys of the returned data structure, a ``PackageMetadata``,
name the metadata keywords, and
the values are returned unparsed from the distribution metadata::
>>> wheel_metadata['Requires-Python'] # doctest: +SKIP
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
@ -206,9 +207,9 @@ Thus, an alternative way to get the version number is through the
There are all kinds of additional metadata available on the ``Distribution``
instance::
>>> d.metadata['Requires-Python'] # doctest: +SKIP
>>> dist.metadata['Requires-Python'] # doctest: +SKIP
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
>>> d.metadata['License'] # doctest: +SKIP
>>> dist.metadata['License'] # doctest: +SKIP
'MIT'
The full set of available metadata is not described here. See :pep:`566`
@ -259,9 +260,3 @@ a custom finder, return instances of this derived ``Distribution`` in the
.. rubric:: Footnotes
.. [#f1] Technically, the returned distribution metadata object is an
:class:`email.message.EmailMessage`
instance, but this is an implementation detail, and not part of the
stable API. You should only use dictionary-like methods and syntax
to access the metadata contents.

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

@ -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

@ -582,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])
@ -786,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 = tuple(kernel)[::-1]
n = len(kernel)
window = collections.deque([0], maxlen=n) * 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)

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

@ -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::
@ -1323,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.
@ -1991,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
@ -2498,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
@ -2522,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
@ -2552,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
@ -2584,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

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

@ -290,4 +290,4 @@ Linux Platforms
ids.extend(info["ID_LIKE"].split())
return ids
.. versionadded:: 3.10
.. 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

@ -665,14 +665,14 @@ The ``errors`` module has the following attributes:
.. data:: codes
A dictionary mapping numeric error codes to their string descriptions.
A dictionary mapping string descriptions to their error codes.
.. versionadded:: 3.2
.. data:: messages
A dictionary mapping string descriptions to their error codes.
A dictionary mapping numeric error codes to their string descriptions.
.. versionadded:: 3.2

View File

@ -135,6 +135,15 @@ Functions for integers
values. Formerly it used a style like ``int(random()*n)`` which could produce
slightly uneven distributions.
.. deprecated:: 3.10
The automatic conversion of non-integer types to equivalent integers is
deprecated. Currently ``randrange(10.0)`` is losslessly converted to
``randrange(10)``. In the future, this will raise a :exc:`TypeError`.
.. deprecated:: 3.10
The exception raised for non-integral values such as ``range(10.5)``
will be changed from :exc:`ValueError` to :exc:`TypeError`.
.. function:: randint(a, b)
Return a random integer *N* such that ``a <= N <= b``. Alias for
@ -142,10 +151,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

@ -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

@ -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:
@ -907,11 +907,9 @@ The :mod:`socket` module also offers various network-related services:
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 2-byte swap operation.
.. deprecated:: 3.7
In case *x* does not fit in 16-bit unsigned integer, but does fit in a
positive C int, it is silently truncated to 16-bit unsigned integer.
This silent truncation feature is deprecated, and will raise an
exception in future versions of Python.
.. versionchanged:: 3.10
Raises :exc:`OverflowError` if *x* does not fit in a 16-bit unsigned
integer.
.. function:: htonl(x)
@ -927,11 +925,9 @@ The :mod:`socket` module also offers various network-related services:
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 2-byte swap operation.
.. deprecated:: 3.7
In case *x* does not fit in 16-bit unsigned integer, but does fit in a
positive C int, it is silently truncated to 16-bit unsigned integer.
This silent truncation feature is deprecated, and will raise an
exception in future versions of Python.
.. versionchanged:: 3.10
Raises :exc:`OverflowError` if *x* does not fit in a 16-bit unsigned
integer.
.. function:: inet_aton(ip_string)

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
@ -544,7 +546,7 @@ Connection Objects
con.close()
.. method:: backup(target, *, pages=0, progress=None, name="main", sleep=0.250)
.. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250)
This method makes a backup of a SQLite database even while it's being accessed
by other clients, or concurrently by the same connection. The copy will be

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.10
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.
@ -4959,6 +4959,11 @@ All parameterized generics implement special read-only attributes.
(~T,)
.. note::
A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not
have correct ``__parameters__`` after substitution because
:class:`typing.ParamSpec` is intended primarily for static type checking.
.. seealso::
* :pep:`585` -- "Type Hinting Generics In Standard Collections"
@ -5353,8 +5358,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

@ -514,6 +514,8 @@ The available presentation types for :class:`float` and
| | 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 |
@ -528,16 +530,19 @@ The available presentation types for :class:`float` and
| | 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``. With no precision given, uses a |
| | precision of ``6`` significant digits for |
| | :class:`float`, and shows all coefficient digits |
| | for :class:`~decimal.Decimal`. |
+---------+----------------------------------------------------------+
| ``'G'`` | General format. Same as ``'g'`` except switches to |
| | ``'E'`` if the number gets too large. The |
@ -550,12 +555,18 @@ The available presentation types for :class:`float` and
| ``'%'`` | 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)
@ -1187,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
@ -1281,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,10 +156,12 @@ 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.
.. versionadded:: 3.6
.. method:: is_free()
Return ``True`` if the symbol is referenced in its block, but not assigned

View File

@ -32,7 +32,7 @@ can be accessed using :func:`get_config_vars` or :func:`get_config_var`.
Notice that on Windows, it's a much smaller set.
.. function:: get_config_vars(\*args)
.. function:: get_config_vars(*args)
With no arguments, return a dictionary of all configuration variables
relevant for the current platform.

View File

@ -37,7 +37,7 @@ Some facts and figures:
Added support for :mod:`lzma` compression.
.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)
Return a :class:`TarFile` object for the pathname *name*. For detailed
information on :class:`TarFile` objects and the keyword arguments that are

View File

@ -453,7 +453,7 @@ The :mod:`test.support` module defines the following functions:
Define match test with regular expression *patterns*.
.. function:: run_unittest(\*classes)
.. function:: run_unittest(*classes)
Execute :class:`unittest.TestCase` subclasses passed to the function. The
function scans the classes for methods starting with the prefix ``test_``
@ -1599,7 +1599,7 @@ The :mod:`test.support.warnings_helper` module provides support for warnings tes
.. versionadded:: 3.8
.. function:: check_warnings(\*filters, quiet=True)
.. function:: check_warnings(*filters, quiet=True)
A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
easier to test that a warning was correctly raised. It is approximately

View File

@ -91,6 +91,9 @@ The different font weights and slants are:
Return the names of defined fonts.
.. function:: nametofont(name)
.. function:: nametofont(name, root=None)
Return a :class:`Font` representation of a tk named font.
Return a :class:`Font` representation of a tk named font.
.. versionchanged:: 3.10
The *root* parameter was added.

View File

@ -153,47 +153,47 @@ Programmatic Interface
count information. *timing* enables a timestamp relative to when tracing was
started to be displayed.
.. method:: run(cmd)
.. method:: run(cmd)
Execute the command and gather statistics from the execution with
the current tracing parameters. *cmd* must be a string or code object,
suitable for passing into :func:`exec`.
Execute the command and gather statistics from the execution with
the current tracing parameters. *cmd* must be a string or code object,
suitable for passing into :func:`exec`.
.. method:: runctx(cmd, globals=None, locals=None)
.. method:: runctx(cmd, globals=None, locals=None)
Execute the command and gather statistics from the execution with the
current tracing parameters, in the defined global and local
environments. If not defined, *globals* and *locals* default to empty
dictionaries.
Execute the command and gather statistics from the execution with the
current tracing parameters, in the defined global and local
environments. If not defined, *globals* and *locals* default to empty
dictionaries.
.. method:: runfunc(func, /, *args, **kwds)
.. method:: runfunc(func, /, *args, **kwds)
Call *func* with the given arguments under control of the :class:`Trace`
object with the current tracing parameters.
Call *func* with the given arguments under control of the :class:`Trace`
object with the current tracing parameters.
.. method:: results()
.. method:: results()
Return a :class:`CoverageResults` object that contains the cumulative
results of all previous calls to ``run``, ``runctx`` and ``runfunc``
for the given :class:`Trace` instance. Does not reset the accumulated
trace results.
Return a :class:`CoverageResults` object that contains the cumulative
results of all previous calls to ``run``, ``runctx`` and ``runfunc``
for the given :class:`Trace` instance. Does not reset the accumulated
trace results.
.. class:: CoverageResults
A container for coverage results, created by :meth:`Trace.results`. Should
not be created directly by the user.
.. method:: update(other)
.. method:: update(other)
Merge in data from another :class:`CoverageResults` object.
Merge in data from another :class:`CoverageResults` object.
.. method:: write_results(show_missing=True, summary=False, coverdir=None)
.. method:: write_results(show_missing=True, summary=False, coverdir=None)
Write coverage results. Set *show_missing* to show lines that had no
hits. Set *summary* to include in the output the coverage summary per
module. *coverdir* specifies the directory into which the coverage
result files will be output. If ``None``, the results for each source
file are placed in its directory.
Write coverage results. Set *show_missing* to show lines that had no
hits. Set *summary* to include in the output the coverage summary per
module. *coverdir* specifies the directory into which the coverage
result files will be output. If ``None``, the results for each source
file are placed in its directory.
A simple example demonstrating the use of the programmatic interface::

View File

@ -913,8 +913,8 @@ Color control
Set pencolor to the RGB color represented by *r*, *g*, and *b*. Each of
*r*, *g*, and *b* must be in the range 0..colormode.
If turtleshape is a polygon, the outline of that polygon is drawn with the
newly set pencolor.
If turtleshape is a polygon, the outline of that polygon is drawn with the
newly set pencolor.
.. doctest::
:skipif: _tkinter is None
@ -962,8 +962,8 @@ Color control
Set fillcolor to the RGB color represented by *r*, *g*, and *b*. Each of
*r*, *g*, and *b* must be in the range 0..colormode.
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
.. doctest::
:skipif: _tkinter is None
@ -1001,8 +1001,8 @@ Color control
Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
and analogously if the other input format is used.
If turtleshape is a polygon, outline and interior of that polygon is drawn
with the newly set colors.
If turtleshape is a polygon, outline and interior of that polygon is drawn
with the newly set colors.
.. doctest::
:skipif: _tkinter is None

View File

@ -280,6 +280,10 @@ Standard names are defined for the following types:
.. versionadded:: 3.9
.. versionchanged:: 3.9.2
This type can now be subclassed.
.. data:: Union
The type of :ref:`union type expressions<types-union>`.

View File

@ -18,7 +18,8 @@
--------------
This module provides runtime support for type hints as specified by
:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, :pep:`591`, and :pep:`613`.
:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, :pep:`591`,
:pep:`612` and :pep:`613`.
The most fundamental support consists of the types :data:`Any`, :data:`Union`,
:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and
:class:`Generic`. For full specification please see :pep:`484`. For
@ -171,6 +172,22 @@ It is possible to declare the return type of a callable without specifying
the call signature by substituting a literal ellipsis
for the list of arguments in the type hint: ``Callable[..., ReturnType]``.
Callables which take other callables as arguments may indicate that their
parameter types are dependent on each other using :class:`ParamSpec`.
Additionally, if that callable adds or removes arguments from other
callables, the :data:`Concatenate` operator may be used. They
take the form ``Callable[ParamSpecVariable, ReturnType]`` and
``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]``
respectively.
.. versionchanged:: 3.10
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
See :pep:`612` for more information.
.. seealso::
The documentation for :class:`ParamSpec` and :class:`Concatenate` provide
examples of usage in ``Callable``.
.. _generics:
Generics
@ -316,6 +333,43 @@ User defined generic type aliases are also supported. Examples::
.. versionchanged:: 3.7
:class:`Generic` no longer has a custom metaclass.
User-defined generics for parameter expressions are also supported via parameter
specification variables in the form ``Generic[P]``. The behavior is consistent
with type variables' described above as parameter specification variables are
treated by the typing module as a specialized type variable. The one exception
to this is that a list of types can be used to substitute a :class:`ParamSpec`::
>>> from typing import Generic, ParamSpec, TypeVar
>>> T = TypeVar('T')
>>> P = ParamSpec('P')
>>> class Z(Generic[T, P]): ...
...
>>> Z[int, [dict, float]]
__main__.Z[int, (<class 'dict'>, <class 'float'>)]
Furthermore, a generic with only one parameter specification variable will accept
parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also
``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted
to the former and are thus equivalent::
>>> class X(Generic[P]): ...
...
>>> X[int, str]
__main__.X[(<class 'int'>, <class 'str'>)]
>>> X[[int, str]]
__main__.X[(<class 'int'>, <class 'str'>)]
Do note that generics with :class:`ParamSpec` may not have correct
``__parameters__`` after substitution in some cases because they
are intended primarily for static type checking.
.. versionchanged:: 3.10
:class:`Generic` can now be parameterized over parameter expressions.
See :class:`ParamSpec` and :pep:`612` for more details.
A user-defined generic class can have ABCs as base classes without a metaclass
conflict. Generic metaclasses are not supported. The outcome of parameterizing
generics is cached, and most types in the typing module are hashable and
@ -602,10 +656,80 @@ These can be used as types in annotations using ``[]``, each having a unique syn
``Callable[..., Any]``, and in turn to
:class:`collections.abc.Callable`.
Callables which take other callables as arguments may indicate that their
parameter types are dependent on each other using :class:`ParamSpec`.
Additionally, if that callable adds or removes arguments from other
callables, the :data:`Concatenate` operator may be used. They
take the form ``Callable[ParamSpecVariable, ReturnType]`` and
``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]``
respectively.
.. deprecated:: 3.9
:class:`collections.abc.Callable` now supports ``[]``. See :pep:`585` and
:ref:`types-genericalias`.
.. versionchanged:: 3.10
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
See :pep:`612` for more information.
.. seealso::
The documentation for :class:`ParamSpec` and :class:`Concatenate` provide
examples of usage with ``Callable``.
.. data:: Concatenate
Used with :data:`Callable` and :class:`ParamSpec` to type annotate a higher
order callable which adds, removes, or transforms parameters of another
callable. Usage is in the form
``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate``
is currently only valid when used as the first argument to a :data:`Callable`.
The last parameter to ``Concatenate`` must be a :class:`ParamSpec`.
For example, to annotate a decorator ``with_lock`` which provides a
:class:`threading.Lock` to the decorated function, ``Concatenate`` can be
used to indicate that ``with_lock`` expects a callable which takes in a
``Lock`` as the first argument, and returns a callable with a different type
signature. In this case, the :class:`ParamSpec` indicates that the returned
callable's parameter types are dependent on the parameter types of the
callable being passed in::
from collections.abc import Callable
from threading import Lock
from typing import Any, Concatenate, ParamSpec
P = ParamSpec('P')
R = ParamSpec('R')
# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()
def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
'''A type-safe decorator which provides a lock.'''
global my_lock
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
# Provide the lock as the first argument.
return f(my_lock, *args, **kwargs)
return inner
@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
'''Add a list of numbers together in a thread-safe manner.'''
with lock:
return sum(numbers)
# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])
.. versionadded:: 3.10
.. seealso::
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
``ParamSpec`` and ``Concatenate``).
* :class:`ParamSpec` and :class:`Callable`.
.. class:: Type(Generic[CT_co])
A variable annotated with ``C`` may accept a value of type ``C``. In
@ -876,6 +1000,84 @@ These are not used in annotations. They are building blocks for creating generic
for the type variable must be a subclass of the boundary type,
see :pep:`484`.
.. class:: ParamSpec(name, *, bound=None, covariant=False, contravariant=False)
Parameter specification variable. A specialized version of
:class:`type variables <TypeVar>`.
Usage::
P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static
type checkers. They are used to forward the parameter types of one
callable to another callable -- a pattern commonly found in higher order
functions and decorators. They are only valid when used in ``Concatenate``,
or as the first argument to ``Callable``, or as parameters for user-defined
Generics. See :class:`Generic` for more information on generic types.
For example, to add basic logging to a function, one can create a decorator
``add_logging`` to log function calls. The parameter specification variable
tells the type checker that the callable passed into the decorator and the
new callable returned by it have inter-dependent type parameters::
from collections.abc import Callable
from typing import TypeVar, ParamSpec
import logging
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Without ``ParamSpec``, the simplest way to annotate this previously was to
use a :class:`TypeVar` with bound ``Callable[..., Any]``. However this
causes two problems:
1. The type checker can't type check the ``inner`` function because
``*args`` and ``**kwargs`` have to be typed :data:`Any`.
2. :func:`~cast` may be required in the body of the ``add_logging``
decorator when returning the ``inner`` function, or the static type
checker must be told to ignore the ``return inner``.
.. attribute:: args
.. attribute:: kwargs
Since ``ParamSpec`` captures both positional and keyword parameters,
``P.args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its
components. ``P.args`` represents the tuple of positional parameters in a
given call and should only be used to annotate ``*args``. ``P.kwargs``
represents the mapping of keyword parameters to their values in a given call,
and should be only be used to annotate ``**kwargs`` or ``**kwds``. Both
attributes require the annotated parameter to be in scope.
Parameter specification variables created with ``covariant=True`` or
``contravariant=True`` can be used to declare covariant or contravariant
generic types. The ``bound`` argument is also accepted, similar to
:class:`TypeVar`. However the actual semantics of these keywords are yet to
be decided.
.. versionadded:: 3.10
.. note::
Only parameter specification variables defined in global scope can
be pickled.
.. seealso::
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
``ParamSpec`` and ``Concatenate``).
* :class:`Callable` and :class:`Concatenate`.
.. data:: AnyStr
``AnyStr`` is a type variable defined as

View File

@ -262,9 +262,10 @@ the *new_callable* argument to :func:`patch`.
this is a new Mock (created on first access). See the
:attr:`return_value` attribute.
* *unsafe*: By default if any attribute starts with *assert* or
*assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
will allow access to these attributes.
* *unsafe*: By default, accessing any attribute with name starting with
*assert*, *assret*, *asert*, *aseert* or *assrt* will raise an
:exc:`AttributeError`. Passing ``unsafe=True`` will allow access to
these attributes.
.. versionadded:: 3.5

View File

@ -491,7 +491,7 @@ Available Functions
Available Context Managers
--------------------------
.. class:: catch_warnings(\*, record=False, module=None)
.. class:: catch_warnings(*, record=False, module=None)
A context manager that copies and, upon exit, restores the warnings filter
and the :func:`showwarning` function.

View File

@ -791,7 +791,7 @@ integer handle, and also disconnect the Windows handle from the handle object.
.. method:: PyHKEY.__enter__()
PyHKEY.__exit__(\*exc_info)
PyHKEY.__exit__(*exc_info)
The HKEY object implements :meth:`~object.__enter__` and
:meth:`~object.__exit__` and thus supports the context protocol for the

View File

@ -174,7 +174,7 @@ module documentation. This section lists the differences between the API and
The :meth:`toxml` method now preserves the attribute order specified
by the user.
.. method:: Node.toprettyxml(indent="\\t", newl="\\n", encoding=None, \
.. method:: Node.toprettyxml(indent="\t", newl="\n", encoding=None, \
standalone=None)
Return a pretty-printed version of the document. *indent* specifies the

View File

@ -483,7 +483,7 @@ Path Objects
Path objects expose the following features of :mod:`pathlib.Path`
objects:
Path objects are traversable using the ``/`` operator.
Path objects are traversable using the ``/`` operator or ``joinpath``.
.. attribute:: Path.name
@ -532,6 +532,19 @@ Path objects are traversable using the ``/`` operator.
Read the current file as bytes.
.. method:: Path.joinpath(*other)
Return a new Path object with each of the *other* arguments
joined. The following are equivalent::
>>> Path(...).joinpath('child').joinpath('grandchild')
>>> Path(...).joinpath('child', 'grandchild')
>>> Path(...) / 'child' / 'grandchild'
.. versionchanged:: 3.10
Prior to 3.10, ``joinpath`` was undocumented and accepted
exactly one parameter.
.. _pyzipfile-objects:

View File

@ -121,7 +121,7 @@ zipimporter Objects
.. method:: get_code(fullname)
Return the code object for the specified module. Raise
:exc:`ZipImportError` if the module couldn't be found.
:exc:`ZipImportError` if the module couldn't be imported.
.. method:: get_data(pathname)
@ -137,7 +137,7 @@ zipimporter Objects
Return the value ``__file__`` would be set to if the specified module
was imported. Raise :exc:`ZipImportError` if the module couldn't be
found.
imported.
.. versionadded:: 3.1
@ -159,14 +159,13 @@ zipimporter Objects
.. method:: load_module(fullname)
Load the module specified by *fullname*. *fullname* must be the fully
qualified (dotted) module name. It returns the imported module, or raises
:exc:`ZipImportError` if it wasn't found.
qualified (dotted) module name. Returns the imported module on success,
raises :exc:`ZipImportError` on failure.
.. deprecated:: 3.10
Use :meth:`exec_module` instead.
.. attribute:: archive
The file name of the importer's associated ZIP file, without a possible

View File

@ -100,7 +100,7 @@ PSF LICENSE AGREEMENT FOR PYTHON |release|
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python |release| alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i.e., "Copyright © 2001-2020 Python Software Foundation; All Rights
copyright, i.e., "Copyright © 2001-2021 Python Software Foundation; All Rights
Reserved" are retained in Python |release| alone or in any derivative version
prepared by Licensee.

View File

@ -254,7 +254,8 @@ present, must be last; it matches any exception. For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is "compatible" with the exception. An object is
compatible with an exception if it is the class or a base class of the exception
object or a tuple containing an item compatible with the exception.
object, or a tuple containing an item that is the class or a base class of
the exception object.
If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack. [#]_
@ -301,9 +302,27 @@ Before an except clause's suite is executed, details about the exception are
stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`.
:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section :ref:`types`) identifying
the point in the program where the exception occurred. :func:`sys.exc_info`
values are restored to their previous values (before the call) when returning
from a function that handled an exception.
the point in the program where the exception occurred. The details about the
exception accessed via :func:`sys.exc_info` are restored to their previous values
when leaving an exception handler::
>>> print(sys.exc_info())
(None, None, None)
>>> try:
... raise TypeError
... except:
... print(sys.exc_info())
... try:
... raise ValueError
... except:
... print(sys.exc_info())
... print(sys.exc_info())
...
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
(<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>)
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
>>> print(sys.exc_info())
(None, None, None)
.. index::
keyword: else
@ -796,12 +815,12 @@ The :keyword:`!async for` statement
.. productionlist:: python-grammar
async_for_stmt: "async" `for_stmt`
An :term:`asynchronous iterable` is able to call asynchronous code in its
*iter* implementation, and :term:`asynchronous iterator` can call asynchronous
code in its *next* method.
An :term:`asynchronous iterable` provides an ``__aiter__`` method that directly
returns an :term:`asynchronous iterator`, which can call asynchronous code in
its ``__anext__`` method.
The ``async for`` statement allows convenient iteration over asynchronous
iterators.
iterables.
The following code::

View File

@ -217,7 +217,6 @@ Ellipsis
There are two types of integers:
Integers (:class:`int`)
These represent numbers in an unlimited range, subject to available (virtual)
memory only. For the purpose of shift and mask operations, a binary
representation is assumed, and negative numbers are represented in a variant of

View File

@ -950,7 +950,7 @@ Names listed in a :keyword:`global` statement must not be used in the same code
block textually preceding that :keyword:`!global` statement.
Names listed in a :keyword:`global` statement must not be defined as formal
parameters or in a :keyword:`for` loop control target, :keyword:`class`
parameters, or as targets in :keyword:`with` statements or :keyword:`except` clauses, or in a :keyword:`for` target list, :keyword:`class`
definition, function definition, :keyword:`import` statement, or variable
annotation.

View File

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""
glossary_search.py
~~~~~~~~~~~~~~~~
Feature search results for glossary items prominently.
:license: Python license.
"""
from os import path
from sphinx.addnodes import glossary
from sphinx.util import logging
from docutils.nodes import definition_list_item
import json
logger = logging.getLogger(__name__)
def process_glossary_nodes(app, doctree, fromdocname):
if app.builder.format != 'html':
return
terms = {}
for node in doctree.traverse(glossary):
for glossary_item in node.traverse(definition_list_item):
term = glossary_item[0].astext().lower()
definition = glossary_item[1]
rendered = app.builder.render_partial(definition)
terms[term] = {
'title': glossary_item[0].astext(),
'body': rendered['html_body']
}
if hasattr(app.env, 'glossary_terms'):
app.env.glossary_terms.update(terms)
else:
app.env.glossary_terms = terms
def on_build_finish(app, exc):
if not hasattr(app.env, 'glossary_terms'):
return
if not app.env.glossary_terms:
return
logger.info('Writing glossary.json', color='green')
with open(path.join(app.outdir, '_static', 'glossary.json'), 'w') as f:
json.dump(app.env.glossary_terms, f)
def setup(app):
app.connect('doctree-resolved', process_glossary_nodes)
app.connect('build-finished', on_build_finish)
return {'version': '0.1', 'parallel_read_safe': True}

View File

@ -394,7 +394,12 @@ class DeprecatedRemoved(Directive):
translatable=False)
node.append(para)
env = self.state.document.settings.env
env.get_domain('changeset').note_changeset(node)
# deprecated pre-Sphinx-2 method
if hasattr(env, 'note_versionchange'):
env.note_versionchange('deprecated', version[0], node, self.lineno)
# new method
else:
env.get_domain('changeset').note_changeset(node)
return [node] + messages

View File

@ -13,6 +13,7 @@ import os
import re
import sys
import getopt
from string import ascii_letters
from os.path import join, splitext, abspath, exists
from collections import defaultdict
@ -128,6 +129,81 @@ def check_leaked_markup(fn, lines):
yield lno+1, 'possibly leaked markup: %r' % line
def hide_literal_blocks(lines):
"""Tool to remove literal blocks from given lines.
It yields empty lines in place of blocks, so line numbers are
still meaningful.
"""
in_block = False
for line in lines:
if line.endswith("::\n"):
in_block = True
elif in_block:
if line == "\n" or line.startswith(" "):
line = "\n"
else:
in_block = False
yield line
def type_of_explicit_markup(line):
if re.match(fr'\.\. {all_directives}::', line):
return 'directive'
if re.match(r'\.\. \[[0-9]+\] ', line):
return 'footnote'
if re.match(r'\.\. \[[^\]]+\] ', line):
return 'citation'
if re.match(r'\.\. _.*[^_]: ', line):
return 'target'
if re.match(r'\.\. \|[^\|]*\| ', line):
return 'substitution_definition'
return 'comment'
def hide_comments(lines):
"""Tool to remove comments from given lines.
It yields empty lines in place of comments, so line numbers are
still meaningfull.
"""
in_multiline_comment = False
for line in lines:
if line == "..\n":
in_multiline_comment = True
elif in_multiline_comment:
if line == "\n" or line.startswith(" "):
line = "\n"
else:
in_multiline_comment = False
if line.startswith(".. ") and type_of_explicit_markup(line) == 'comment':
line = "\n"
yield line
@checker(".rst", severity=2)
def check_missing_surrogate_space_on_plural(fn, lines):
r"""Check for missing 'backslash-space' between a code sample a letter.
Good: ``Point``\ s
Bad: ``Point``s
"""
in_code_sample = False
check_next_one = False
for lno, line in enumerate(hide_comments(hide_literal_blocks(lines))):
tokens = line.split("``")
for token_no, token in enumerate(tokens):
if check_next_one:
if token[0] in ascii_letters:
yield lno + 1, f"Missing backslash-space between code sample and {token!r}."
check_next_one = False
if token_no == len(tokens) - 1:
continue
if in_code_sample:
check_next_one = True
in_code_sample = not in_code_sample
def main(argv):
usage = '''\
Usage: %s [-v] [-f] [-s sev] [-i path]* [path]

View File

@ -168,6 +168,7 @@ library/ipaddress,,::,2001:db00::0/24
library/ipaddress,,:db00,2001:db00::0/ffff:ff00::
library/ipaddress,,::,2001:db00::0/ffff:ff00::
library/itertools,,:step,elements from seq[start:stop:step]
library/itertools,,::,kernel = tuple(kernel)[::-1]
library/itertools,,:stop,elements from seq[start:stop:step]
library/logging.handlers,,:port,host:port
library/mmap,,:i2,obj[i1:i2]

1 c-api/arg :ref PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
168 library/ipaddress :db00 2001:db00::0/ffff:ff00::
169 library/ipaddress :: 2001:db00::0/ffff:ff00::
170 library/itertools :step elements from seq[start:stop:step]
171 library/itertools :: kernel = tuple(kernel)[::-1]
172 library/itertools :stop elements from seq[start:stop:step]
173 library/logging.handlers :port host:port
174 library/mmap :i2 obj[i1:i2]

View File

@ -0,0 +1,48 @@
{% extends "!search.html" %}
{% block extrahead %}
{{ super() }}
<script type="text/javascript">
var GLOSSARY_PAGE = 'glossary.html';
jQuery(function() {
$.getJSON("_static/glossary.json", function(glossary) {
var RESULT_TEMPLATE = '<div style="display: none" class="admonition seealso" id="glossary-result">' +
' <p class="topic-title">' +
' <a class="glossary-title" href="#"></a>' +
' </p>' +
' <div class="glossary-body"></div>' +
'</div>';
$("#search-results").prepend(RESULT_TEMPLATE);
var params = $.getQueryParameters();
if (params.q) {
var search_param = params.q[0].toLowerCase();
var glossary_item = glossary[search_param];
if (glossary_item) {
var resultDiv = $("#glossary-result");
// set up the title text with a link to the glossary page
resultDiv.find(".glossary-title").text('Glossary: ' + glossary_item.title);
var link_target = search_param.replace(/ /g, '-');
resultDiv.find(".glossary-title").attr(
'href', GLOSSARY_PAGE + '#term-' + link_target
);
// rewrite any anchor links (to other glossary terms)
// to have a full reference to the glossary page
var body = $(glossary_item.body).children();
body.find("a[href^='#']").each(function() {
var current_url = $(this).attr('href');
$(this).attr('href', GLOSSARY_PAGE + current_url);
});
resultDiv.find(".glossary-body").html(body);
resultDiv.show();
} else {
$("#glossary-result").hide('');
}
}
});
});
</script>
{% endblock %}

View File

@ -281,17 +281,17 @@ chaining exceptions. For example::
This can be useful when you are transforming exceptions. For example::
>>> def func():
... raise IOError
... raise ConnectionError
...
>>> try:
... func()
... except IOError as exc:
... except ConnectionError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
OSError
ConnectionError
<BLANKLINE>
The above exception was the direct cause of the following exception:
<BLANKLINE>
@ -300,7 +300,7 @@ This can be useful when you are transforming exceptions. For example::
RuntimeError: Failed to open database
Exception chaining happens automatically when an exception is raised inside an
:keyword:`except` or :keyword:`finally` section. Exception chaining can be
:keyword:`except` or :keyword:`finally` section. This can be
disabled by using ``from None`` idiom:
>>> try:

View File

@ -23,8 +23,8 @@ available for application-local distributions.
As specified in :pep:`11`, a Python release only supports a Windows platform
while Microsoft considers the platform under extended support. This means that
Python |version| supports Windows Vista and newer. If you require Windows XP
support then please install Python 3.4.
Python |version| supports Windows 8.1 and newer. If you require Windows 7
support, please install Python 3.8.
There are a number of different installers available for Windows, each with
certain benefits and downsides.

View File

@ -144,6 +144,28 @@ See :pep:`604` for more details.
(Contributed by Maggie Moss and Philippe Prados in :issue:`41428`.)
PEP 612: Parameter Specification Variables
------------------------------------------
Two new options to improve the information provided to static type checkers for
:pep:`484`\ 's ``Callable`` have been added to the :mod:`typing` module.
The first is the parameter specification variable. They are used to forward the
parameter types of one callable to another callable -- a pattern commonly
found in higher order functions and decorators. Examples of usage can be found
in :class:`typing.ParamSpec`. Previously, there was no easy way to type annotate
dependency of parameter types in such a precise manner.
The second option is the new ``Concatenate`` operator. It's used in conjunction
with parameter specification variables to type annotate a higher order callable
which adds or removes parameters of another callable. Examples of usage can
be found in :class:`typing.Concatenate`.
See :class:`typing.Callable`, :class:`typing.ParamSpec`,
:class:`typing.Concatenate` and :pep:`612` for more details.
(Contributed by Ken Jin in :issue:`41559`.)
Other Language Changes
======================
@ -179,6 +201,21 @@ codecs
Add a :func:`codecs.unregister` function to unregister a codec search function.
(Contributed by Hai Shi in :issue:`41842`.)
collections.abc
---------------
The ``__args__`` of the :ref:`parameterized generic <types-genericalias>` for
:class:`collections.abc.Callable` are now consistent with :data:`typing.Callable`.
:class:`collections.abc.Callable` generic now flattens type parameters, similar
to what :data:`typing.Callable` currently does. This means that
``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
``(int, str, str)``; previously this was ``([int, str], str)``. To allow this
change, :class:`types.GenericAlias` can now be subclassed, and a subclass will
be returned when subscripting the :class:`collections.abc.Callable` type. Note
that a :exc:`TypeError` may be raised for invalid forms of parameterizing
:class:`collections.abc.Callable` which may have passed silently in Python 3.9.
(Contributed by Ken Jin in :issue:`42195`.)
contextlib
----------
@ -223,6 +260,11 @@ inspect
When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
(Contributed by Brett Cannon in :issue:`42133`.)
Added *globalns* and *localns* parameters in :func:`~inspect.signature` and
:meth:`inspect.Signature.from_callable` to retrieve the annotations in given
local and global namespaces.
(Contributed by Batuhan Taskaya in :issue:`41960`.)
linecache
---------
@ -384,9 +426,11 @@ Optimizations
average.
(Contributed by Victor Stinner in :issue:`41006`.)
* The ``LOAD_ATTR`` instruction now uses new "per opcode cache" mechanism.
It is about 36% faster now. (Contributed by Pablo Galindo and Yury Selivanov
in :issue:`42093`, based on ideas implemented originally in PyPy and MicroPython.)
* The ``LOAD_ATTR`` instruction now uses new "per opcode cache" mechanism. It
is about 36% faster now. This makes optimized ``LOAD_ATTR`` instructions the
current most performance attribute access method (faster than slots).
(Contributed by Pablo Galindo and Yury Selivanov in :issue:`42093`, based on
ideas implemented originally in PyPy and MicroPython.)
* When building Python with ``--enable-optimizations`` now
``-fno-semantic-interposition`` is added to both the compile and link line.
@ -394,7 +438,8 @@ Optimizations
with ``gcc`` by up to 30%. See `this article
<https://developers.redhat.com/blog/2020/06/25/red-hat-enterprise-linux-8-2-brings-faster-python-3-8-run-speeds/>`_
for more details. (Contributed by Victor Stinner and Pablo Galindo in
:issue:`38980`)
:issue:`38980`.)
* Function parameters and their annotations are no longer computed at runtime,
but rather at compilation time. They are stored as a tuple of strings at the
@ -421,6 +466,21 @@ Deprecated
as appropriate to help identify code which needs updating during
this transition.
* The various ``load_module()`` methods of :mod:`importlib` have been
documented as deprecated since Python 3.6, but will now also trigger
a :exc:`DeprecationWarning`. Use
:meth:`~importlib.abc.Loader.exec_module` instead.
(Contributed by Brett Cannon in :issue:`26131`.)
* :meth:`zimport.zipimporter.load_module` has been deprecated in
preference for :meth:`~zipimport.zipimporter.exec_module`.
(Contributed by Brett Cannon in :issue:`26131`.)
* The use of :meth:`~importlib.abc.Loader.load_module` by the import
system now triggers an :exc:`ImportWarning` as
:meth:`~importlib.abc.Loader.exec_module` is preferred.
(Contributed by Brett Cannon in :issue:`26131`.)
* ``sqlite3.OptimizedUnicode`` has been undocumented and obsolete since Python
3.3, when it was made an alias to :class:`str`. It is now deprecated,
scheduled for removal in Python 3.12.
@ -464,6 +524,11 @@ Removed
into their code.
(Contributed by Dong-hee Na and Terry J. Reedy in :issue:`42299`.)
* Removed the :c:func:`PyModule_GetWarningsModule` function that was useless
now due to the _warnings module was converted to a builtin module in 2.6.
(Contributed by Hai Shi in :issue:`42599`.)
Porting to Python 3.10
======================
@ -480,6 +545,28 @@ Changes in the Python API
have been renamed to *exc*.
(Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.)
* :mod:`atexit`: At Python exit, if a callback registered with
:func:`atexit.register` fails, its exception is now logged. Previously, only
some exceptions were logged, and the last exception was always silently
ignored.
(Contributed by Victor Stinner in :issue:`42639`.)
* :class:`collections.abc.Callable` generic now flattens type parameters, similar
to what :data:`typing.Callable` currently does. This means that
``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
``(int, str, str)``; previously this was ``([int, str], str)``. Code which
accesses the arguments via :func:`typing.get_args` or ``__args__`` need to account
for this change. Furthermore, :exc:`TypeError` may be raised for invalid forms
of parameterizing :class:`collections.abc.Callable` which may have passed
silently in Python 3.9.
(Contributed by Ken Jin in :issue:`42195`.)
* :meth:`socket.htons` and :meth:`socket.ntohs` now raise :exc:`OverflowError`
instead of :exc:`DeprecationWarning` if the given parameter will not fit in
a 16-bit unsigned integer.
(Contributed by Erlend E. Aasland in :issue:`42393`.)
CPython bytecode changes
========================
@ -498,6 +585,12 @@ Build Changes
* :mod:`sqlite3` requires SQLite 3.7.3 or higher.
(Contributed by Sergey Fedoseev and Erlend E. Aasland :issue:`40744`.)
* The :mod:`atexit` module must now always be built as a built-in module.
(Contributed by Victor Stinner in :issue:`42639`.)
* Added ``--disable-test-modules`` option to the ``configure`` script:
don't build nor install test modules.
(Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in :issue:`27640`.)
C API Changes
@ -595,6 +688,13 @@ Porting to Python 3.10
:ref:`Python Path Configuration. <init-path-config>`.
(Contributed by Victor Stinner in :issue:`42260`.)
* :c:func:`PyList_SET_ITEM`, :c:func:`PyTuple_SET_ITEM` and
:c:func:`PyCell_SET` macros can no longer be used as l-value or r-value.
For example, ``x = PyList_SET_ITEM(a, b, c)`` and
``PyList_SET_ITEM(a, b, c) = x`` now fail with a compiler error. It prevents
bugs like ``if (PyList_SET_ITEM (a, b, c) < 0) ...`` test.
(Contributed by Zackery Spytz and Victor Stinner in :issue:`30459`.)
Deprecated
----------

View File

@ -1482,4 +1482,37 @@ and to match the behavior of static type checkers specified in the PEP.
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
(Contributed by Yurii Karabas in :issue:`42345`.)
(Contributed by Yurii Karabas in :issue:`42345`.)
macOS 11.0 (Big Sur) and Apple Silicon Mac support
--------------------------------------------------
As of 3.9.1, Python now fully supports building and running on macOS 11.0
(Big Sur) and on Apple Silicon Macs (based on the ``ARM64`` architecture).
A new universal build variant, ``universal2``, is now available to natively
support both ``ARM64`` and ``Intel 64`` in one set of executables. Binaries
can also now be built on current versions of macOS to be deployed on a range
of older macOS versions (tested to 10.9) while making some newer OS
functions and options conditionally available based on the operating system
version in use at runtime ("weaklinking").
(Contributed by Ronald Oussoren and Lawrence D'Anna in :issue:`41100`.)
Notable changes in Python 3.9.2
===============================
collections.abc
---------------
:class:`collections.abc.Callable` generic now flattens type parameters, similar
to what :data:`typing.Callable` currently does. This means that
``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
``(int, str, str)``; previously this was ``([int, str], str)``. To allow this
change, :class:`types.GenericAlias` can now be subclassed, and a subclass will
be returned when subscripting the :class:`collections.abc.Callable` type.
Code which accesses the arguments via :func:`typing.get_args` or ``__args__``
need to account for this change. A :exc:`DeprecationWarning` may be emitted for
invalid forms of parameterizing :class:`collections.abc.Callable` which may have
passed silently in Python 3.9.1. This :exc:`DeprecationWarning` will
become a :exc:`TypeError` in Python 3.10.
(Contributed by Ken Jin in :issue:`42195`.)

View File

@ -580,18 +580,23 @@ star_targets[expr_ty]:
| a=star_target !',' { a }
| a=star_target b=(',' c=star_target { c })* [','] {
_Py_Tuple(CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)), Store, EXTRA) }
star_targets_seq[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_target+ [','] { a }
star_targets_list_seq[asdl_expr_seq*]: a[asdl_expr_seq*]=','.star_target+ [','] { a }
star_targets_tuple_seq[asdl_expr_seq*]:
| a=star_target b=(',' c=star_target { c })+ [','] { (asdl_expr_seq*) _PyPegen_seq_insert_in_front(p, a, b) }
| a=star_target ',' { (asdl_expr_seq*) _PyPegen_singleton_seq(p, a) }
star_target[expr_ty] (memo):
| '*' a=(!'*' star_target) {
_Py_Starred(CHECK(expr_ty, _PyPegen_set_expr_context(p, a, Store)), Store, EXTRA) }
| target_with_star_atom
target_with_star_atom[expr_ty] (memo):
| a=t_primary '.' b=NAME !t_lookahead { _Py_Attribute(a, b->v.Name.id, Store, EXTRA) }
| a=t_primary '[' b=slices ']' !t_lookahead { _Py_Subscript(a, b, Store, EXTRA) }
| star_atom
star_atom[expr_ty]:
| a=NAME { _PyPegen_set_expr_context(p, a, Store) }
| '(' a=star_target ')' { _PyPegen_set_expr_context(p, a, Store) }
| '(' a=[star_targets_seq] ')' { _Py_Tuple(a, Store, EXTRA) }
| '[' a=[star_targets_seq] ']' { _Py_List(a, Store, EXTRA) }
| '(' a=target_with_star_atom ')' { _PyPegen_set_expr_context(p, a, Store) }
| '(' a=[star_targets_tuple_seq] ')' { _Py_Tuple(a, Store, EXTRA) }
| '[' a=[star_targets_list_seq] ']' { _Py_List(a, Store, EXTRA) }
single_target[expr_ty]:
| single_subscript_attribute_target
@ -646,7 +651,7 @@ invalid_arguments:
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "Generator expression must be parenthesized") }
| a=args ',' args { _PyPegen_arguments_parsing_error(p, a) }
invalid_kwarg:
| a=expression '=' {
| expression a='=' {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
a, "expression cannot contain assignment, perhaps you meant \"==\"?") }
invalid_named_expression:

View File

@ -1,5 +1,5 @@
/* Bytes (String) object interface */
/* Bytes object interface */
#ifndef Py_BYTESOBJECT_H
#define Py_BYTESOBJECT_H
@ -10,23 +10,20 @@ extern "C" {
#include <stdarg.h>
/*
Type PyBytesObject represents a character string. An extra zero byte is
Type PyBytesObject represents a byte string. An extra zero byte is
reserved at the end to ensure it is zero-terminated, but a size is
present so strings with null bytes in them can be represented. This
is an immutable object type.
There are functions to create new string objects, to test
an object for string-ness, and to get the
string value. The latter function returns a null pointer
There are functions to create new bytes objects, to test
an object for bytes-ness, and to get the
byte string value. The latter function returns a null pointer
if the object is not of the proper type.
There is a variant that takes an explicit size as well as a
variant that assumes a zero-terminated string. Note that none of the
functions should be applied to nil objects.
functions should be applied to NULL pointer.
*/
/* Caching the hash (ob_shash) saves recalculation of a string's hash value.
This significantly speeds up dict lookups. */
PyAPI_DATA(PyTypeObject) PyBytes_Type;
PyAPI_DATA(PyTypeObject) PyBytesIter_Type;
@ -50,26 +47,16 @@ PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t,
const char *, Py_ssize_t,
const char *);
/* Provides access to the internal data buffer and size of a string
object or the default encoded version of a Unicode object. Passing
NULL as *len parameter will force the string buffer to be
0-terminated (passing a string with embedded NULL characters will
/* Provides access to the internal data buffer and size of a bytes object.
Passing NULL as len parameter will force the string buffer to be
0-terminated (passing a string with embedded NUL characters will
cause an exception). */
PyAPI_FUNC(int) PyBytes_AsStringAndSize(
PyObject *obj, /* string or Unicode object */
PyObject *obj, /* bytes object */
char **s, /* pointer to buffer variable */
Py_ssize_t *len /* pointer to length variable or NULL
(only possible for 0-terminated
strings) */
Py_ssize_t *len /* pointer to length variable or NULL */
);
/* Flags used by string formatting */
#define F_LJUST (1<<0)
#define F_SIGN (1<<1)
#define F_BLANK (1<<2)
#define F_ALT (1<<3)
#define F_ZERO (1<<4)
#ifndef Py_LIMITED_API
# define Py_CPYTHON_BYTESOBJECT_H
# include "cpython/bytesobject.h"

View File

@ -20,7 +20,7 @@ PyAPI_FUNC(PyObject *) PyCell_Get(PyObject *);
PyAPI_FUNC(int) PyCell_Set(PyObject *, PyObject *);
#define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref)
#define PyCell_SET(op, v) (((PyCellObject *)(op))->ob_ref = v)
#define PyCell_SET(op, v) ((void)(((PyCellObject *)(op))->ob_ref = v))
#ifdef __cplusplus
}

View File

@ -63,7 +63,7 @@ PyVectorcall_Function(PyObject *callable)
{
PyTypeObject *tp;
Py_ssize_t offset;
vectorcallfunc *ptr;
vectorcallfunc ptr;
assert(callable != NULL);
tp = Py_TYPE(callable);
@ -73,8 +73,8 @@ PyVectorcall_Function(PyObject *callable)
assert(PyCallable_Check(callable));
offset = tp->tp_vectorcall_offset;
assert(offset > 0);
ptr = (vectorcallfunc *)(((char *)callable) + offset);
return *ptr;
memcpy(&ptr, (char *) callable + offset, sizeof(ptr));
return ptr;
}
/* Call the callable object 'callable' with the "vectorcall" calling

View File

@ -10,7 +10,7 @@ typedef struct {
/* Invariants:
* ob_sval contains space for 'ob_size+1' elements.
* ob_sval[ob_size] == 0.
* ob_shash is the hash of the string or -1 if not computed yet.
* ob_shash is the hash of the byte string or -1 if not computed yet.
*/
} PyBytesObject;

View File

@ -95,10 +95,6 @@ PyAPI_FUNC(FILE *) _Py_wfopen(
const wchar_t *path,
const wchar_t *mode);
PyAPI_FUNC(FILE*) _Py_fopen(
const char *pathname,
const char *mode);
PyAPI_FUNC(FILE*) _Py_fopen_obj(
PyObject *path,
const char *mode);

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