summaryrefslogtreecommitdiffstats
path: root/doc/src/snippets/code/src_network_kernel_qhostaddress.cpp
blob: 0db5e806984bbb4b43974510760df30ae3a4abe3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
Q_IPV6ADDR addr = hostAddr.toIPv6Address();
// addr contains 16 unsigned characters

for (int i = 0; i < 16; ++i) {
    // process addr[i]
}
//! [0]
class='right'>113
-rw-r--r--Doc/c-api/structures.rst5
-rw-r--r--Doc/c-api/sys.rst25
-rw-r--r--Doc/c-api/unicode.rst53
-rw-r--r--Doc/data/refcounts.dat3
-rw-r--r--Doc/extending/embedding.rst6
-rw-r--r--Doc/faq/design.rst32
-rw-r--r--Doc/faq/programming.rst3
-rw-r--r--Doc/glossary.rst54
-rw-r--r--Doc/howto/argparse.rst3
-rw-r--r--Doc/howto/clinic.rst4
-rw-r--r--Doc/howto/index.rst1
-rw-r--r--Doc/howto/instrumentation.rst408
-rw-r--r--Doc/includes/email-alternative-new-api.py56
-rw-r--r--[-rwxr-xr-x]Doc/includes/email-alternative.py76
-rw-r--r--Doc/includes/email-dir.py55
-rw-r--r--Doc/includes/email-headers.py22
-rw-r--r--Doc/includes/email-mime.py29
-rw-r--r--Doc/includes/email-read-alternative.py (renamed from Doc/includes/email-read-alternative-new-api.py)0
-rw-r--r--Doc/includes/email-simple.py8
-rw-r--r--Doc/includes/email-unpack.py8
-rw-r--r--Doc/includes/run-func.c4
-rw-r--r--Doc/includes/test.py2
-rw-r--r--Doc/includes/tzinfo-examples.py130
-rw-r--r--Doc/installing/index.rst61
-rw-r--r--Doc/library/asynchat.rst19
-rw-r--r--Doc/library/asyncio-eventloop.rst23
-rw-r--r--Doc/library/asyncio-protocol.rst3
-rw-r--r--Doc/library/asyncio.rst7
-rw-r--r--Doc/library/asyncore.rst3
-rw-r--r--Doc/library/binascii.rst11
-rw-r--r--Doc/library/bz2.rst6
-rw-r--r--Doc/library/cmath.rst36
-rw-r--r--Doc/library/code.rst19
-rw-r--r--Doc/library/codecs.rst10
-rw-r--r--Doc/library/collections.abc.rst42
-rw-r--r--Doc/library/collections.rst31
-rw-r--r--Doc/library/compileall.rst18
-rw-r--r--Doc/library/concurrent.futures.rst6
-rw-r--r--Doc/library/constants.rst22
-rw-r--r--Doc/library/contextlib.rst20
-rw-r--r--Doc/library/crypt.rst2
-rw-r--r--Doc/library/crypto.rst2
-rw-r--r--Doc/library/csv.rst49
-rw-r--r--Doc/library/ctypes.rst17
-rw-r--r--Doc/library/datetime.rst305
-rw-r--r--Doc/library/dbm.rst4
-rw-r--r--Doc/library/decimal.rst23
-rw-r--r--Doc/library/dis.rst86
-rw-r--r--Doc/library/email.charset.rst5
-rw-r--r--Doc/library/email.compat32-message.rst754
-rw-r--r--Doc/library/email.contentmanager.rst304
-rw-r--r--Doc/library/email.encoders.rst6
-rw-r--r--Doc/library/email.errors.rst38
-rw-r--r--Doc/library/email.examples.rst (renamed from Doc/library/email-examples.rst)33
-rw-r--r--Doc/library/email.generator.rst376
-rw-r--r--Doc/library/email.header.rst8
-rw-r--r--Doc/library/email.headerregistry.rst49
-rw-r--r--Doc/library/email.message.rst719
-rw-r--r--Doc/library/email.mime.rst58
-rw-r--r--Doc/library/email.parser.rst358
-rw-r--r--Doc/library/email.policy.rst280
-rw-r--r--Doc/library/email.rst464
-rw-r--r--Doc/library/email.util.rst68
-rw-r--r--Doc/library/enum.rst623
-rw-r--r--Doc/library/exceptions.rst38
-rw-r--r--Doc/library/faulthandler.rst3
-rw-r--r--Doc/library/fileinput.rst19
-rw-r--r--Doc/library/fnmatch.rst2
-rw-r--r--Doc/library/ftplib.rst7
-rw-r--r--Doc/library/functions.rst68
-rw-r--r--Doc/library/glob.rst2
-rw-r--r--Doc/library/grp.rst3
-rw-r--r--Doc/library/gzip.rst5
-rw-r--r--Doc/library/hashlib-blake2-tree.pngbin0 -> 11148 bytes-rw-r--r--Doc/library/hashlib-blake2.rst444
-rw-r--r--Doc/library/hashlib.rst79
-rw-r--r--Doc/library/http.client.rst115
-rw-r--r--Doc/library/http.server.rst14
-rw-r--r--Doc/library/imaplib.rst19
-rw-r--r--Doc/library/imghdr.rst3
-rw-r--r--Doc/library/imp.rst15
-rw-r--r--Doc/library/importlib.rst199
-rw-r--r--Doc/library/inspect.rst132
-rw-r--r--Doc/library/itertools.rst8
-rw-r--r--Doc/library/json.rst29
-rw-r--r--Doc/library/logging.handlers.rst104
-rw-r--r--Doc/library/lzma.rst18
-rw-r--r--Doc/library/math.rst9
-rw-r--r--Doc/library/mmap.rst9
-rw-r--r--Doc/library/multiprocessing.rst97
-rw-r--r--Doc/library/os.path.rst87
-rw-r--r--Doc/library/os.rst385
-rw-r--r--Doc/library/pathlib.rst37
-rw-r--r--Doc/library/pdb.rst8
-rw-r--r--Doc/library/pickle.rst19
-rw-r--r--Doc/library/pkgutil.rst9
-rw-r--r--Doc/library/poplib.rst7
-rw-r--r--Doc/library/queue.rst11
-rw-r--r--Doc/library/random.rst263
-rw-r--r--Doc/library/re.rst65
-rw-r--r--Doc/library/readline.rst14
-rw-r--r--Doc/library/secrets.rst198
-rw-r--r--Doc/library/select.rst69
-rw-r--r--Doc/library/shlex.rst111
-rw-r--r--Doc/library/shutil.rst2
-rw-r--r--Doc/library/site.rst3
-rw-r--r--Doc/library/smtpd.rst50
-rw-r--r--Doc/library/smtplib.rst8
-rw-r--r--Doc/library/socket.rst76
-rw-r--r--Doc/library/socketserver.rst68
-rw-r--r--Doc/library/spwd.rst3
-rw-r--r--Doc/library/sqlite3.rst20
-rw-r--r--Doc/library/ssl.rst275
-rw-r--r--Doc/library/statistics.rst43
-rw-r--r--Doc/library/stdtypes.rst27
-rw-r--r--Doc/library/string.rst23
-rw-r--r--Doc/library/struct.rst27
-rw-r--r--Doc/library/subprocess.rst107
-rw-r--r--Doc/library/sys.rst123
-rw-r--r--Doc/library/sysconfig.rst2
-rw-r--r--Doc/library/telnetlib.rst11
-rw-r--r--Doc/library/test.rst42
-rw-r--r--Doc/library/time.rst12
-rw-r--r--Doc/library/timeit.rst21
-rw-r--r--Doc/library/tkinter.tix.rst4
-rw-r--r--Doc/library/traceback.rst14
-rw-r--r--Doc/library/tracemalloc.rst45
-rw-r--r--Doc/library/types.rst14
-rw-r--r--Doc/library/typing.rst43
-rw-r--r--Doc/library/undoc.rst2
-rw-r--r--Doc/library/unicodedata.rst8
-rw-r--r--Doc/library/unittest.mock.rst40
-rw-r--r--Doc/library/unittest.rst6
-rw-r--r--Doc/library/urllib.parse.rst18
-rw-r--r--Doc/library/urllib.request.rst65
-rw-r--r--Doc/library/urllib.robotparser.rst30
-rw-r--r--Doc/library/venv.rst134
-rw-r--r--Doc/library/warnings.rst16
-rw-r--r--Doc/library/winreg.rst14
-rw-r--r--Doc/library/winsound.rst8
-rw-r--r--Doc/library/wsgiref.rst32
-rw-r--r--Doc/library/xmlrpc.client.rst17
-rw-r--r--Doc/library/xmlrpc.server.rst59
-rw-r--r--Doc/library/zipfile.rst129
-rw-r--r--Doc/library/zlib.rst31
-rw-r--r--Doc/make.bat2
-rw-r--r--Doc/reference/compound_stmts.rst26
-rw-r--r--Doc/reference/datamodel.rst182
-rw-r--r--Doc/reference/expressions.rst166
-rw-r--r--Doc/reference/import.rst37
-rw-r--r--Doc/reference/lexical_analysis.rst163
-rw-r--r--Doc/reference/simple_stmts.rst56
-rw-r--r--Doc/tools/extensions/pyspecific.py2
-rwxr-xr-xDoc/tools/rstlint.py2
-rw-r--r--Doc/tools/susp-ignored.csv63
-rw-r--r--Doc/tools/templates/indexsidebar.html2
-rw-r--r--Doc/tutorial/controlflow.rst3
-rw-r--r--Doc/tutorial/datastructures.rst53
-rw-r--r--Doc/tutorial/errors.rst2
-rw-r--r--Doc/tutorial/inputoutput.rst3
-rw-r--r--Doc/tutorial/interpreter.rst12
-rw-r--r--Doc/tutorial/introduction.rst3
-rw-r--r--Doc/tutorial/stdlib.rst2
-rw-r--r--Doc/tutorial/stdlib2.rst2
-rw-r--r--Doc/tutorial/venv.rst111
-rw-r--r--Doc/using/cmdline.rst99
-rw-r--r--Doc/using/index.rst1
-rw-r--r--Doc/using/mac.rst6
-rw-r--r--Doc/using/scripts.rst12
-rw-r--r--Doc/using/venv-create.inc95
-rw-r--r--Doc/using/windows.rst143
-rw-r--r--Doc/whatsnew/2.1.rst2
-rw-r--r--Doc/whatsnew/3.2.rst4
-rw-r--r--Doc/whatsnew/3.3.rst2
-rw-r--r--Doc/whatsnew/3.4.rst10
-rw-r--r--Doc/whatsnew/3.5.rst6
-rw-r--r--Doc/whatsnew/3.6.rst2310
-rw-r--r--Doc/whatsnew/index.rst1
-rw-r--r--Grammar/Grammar24
-rw-r--r--Include/Python-ast.h56
-rw-r--r--Include/Python.h1
-rw-r--r--Include/abstract.h98
-rw-r--r--Include/asdl.h1
-rw-r--r--Include/bytes_methods.h27
-rw-r--r--Include/bytesobject.h97
-rw-r--r--Include/ceval.h23
-rw-r--r--Include/code.h32
-rw-r--r--Include/codecs.h4
-rw-r--r--Include/datetime.h17
-rw-r--r--Include/descrobject.h2
-rw-r--r--Include/dictobject.h27
-rw-r--r--Include/fileobject.h3
-rw-r--r--Include/fileutils.h22
-rw-r--r--Include/floatobject.h10
-rw-r--r--Include/funcobject.h14
-rw-r--r--Include/genobject.h33
-rw-r--r--Include/graminit.h137
-rw-r--r--Include/grammar.h1
-rw-r--r--Include/import.h10
-rw-r--r--Include/intrcheck.h3
-rw-r--r--Include/longintrepr.h12
-rw-r--r--Include/longobject.h26
-rw-r--r--Include/memoryobject.h2
-rw-r--r--Include/methodobject.h16
-rw-r--r--Include/modsupport.h30
-rw-r--r--Include/moduleobject.h4
-rw-r--r--Include/namespaceobject.h2
-rw-r--r--Include/object.h22
-rw-r--r--Include/objimpl.h9
-rw-r--r--Include/odictobject.h9
-rw-r--r--Include/opcode.h10
-rw-r--r--Include/osmodule.h17
-rw-r--r--Include/patchlevel.h6
-rw-r--r--Include/pgenheaders.h1
-rw-r--r--Include/py_curses.h4
-rw-r--r--Include/pyatomic.h4
-rw-r--r--Include/pydebug.h4
-rw-r--r--Include/pydtrace.d19
-rw-r--r--Include/pydtrace.h53
-rw-r--r--Include/pyerrors.h34
-rw-r--r--Include/pygetopt.h2
-rw-r--r--Include/pyhash.h16
-rw-r--r--Include/pylifecycle.h7
-rw-r--r--Include/pymacro.h15
-rw-r--r--Include/pymath.h8
-rw-r--r--Include/pymem.h45
-rw-r--r--Include/pyport.h190
-rw-r--r--Include/pystate.h49
-rw-r--r--Include/pystrhex.h2
-rw-r--r--Include/pystrtod.h4
-rw-r--r--Include/pythonrun.h10
-rw-r--r--Include/pythread.h13
-rw-r--r--Include/pytime.h21
-rw-r--r--Include/setobject.h11
-rw-r--r--Include/structmember.h2
-rw-r--r--Include/symtable.h2
-rw-r--r--Include/sysmodule.h4
-rw-r--r--Include/traceback.h52
-rw-r--r--Include/unicodeobject.h138
-rw-r--r--Include/warnings.h9
-rw-r--r--Lib/_collections_abc.py170
-rw-r--r--Lib/_compat_pickle.py7
-rw-r--r--Lib/_osx_support.py10
-rw-r--r--Lib/_pydecimal.py62
-rw-r--r--Lib/_pyio.py9
-rw-r--r--Lib/_strptime.py83
-rw-r--r--Lib/aifc.py9
-rw-r--r--Lib/argparse.py10
-rw-r--r--Lib/ast.py52
-rw-r--r--Lib/asynchat.py29
-rw-r--r--Lib/asyncio/base_events.py5
-rw-r--r--Lib/asyncio/base_futures.py71
-rw-r--r--Lib/asyncio/base_subprocess.py3
-rw-r--r--Lib/asyncio/base_tasks.py76
-rw-r--r--Lib/asyncio/coroutines.py4
-rw-r--r--Lib/asyncio/futures.py92
-rw-r--r--Lib/asyncio/proactor_events.py3
-rw-r--r--Lib/asyncio/selector_events.py3
-rw-r--r--Lib/asyncio/sslproto.py3
-rw-r--r--Lib/asyncio/tasks.py80
-rw-r--r--Lib/asyncio/test_utils.py8
-rw-r--r--Lib/asyncio/unix_events.py6
-rw-r--r--Lib/asyncio/windows_events.py9
-rw-r--r--Lib/asyncio/windows_utils.py3
-rw-r--r--Lib/asyncore.py5
-rwxr-xr-xLib/base64.py5
-rw-r--r--Lib/bz2.py16
-rw-r--r--Lib/calendar.py85
-rwxr-xr-xLib/cgi.py2
-rw-r--r--Lib/code.py16
-rw-r--r--Lib/collections/__init__.py22
-rw-r--r--Lib/collections/__main__.py38
-rw-r--r--Lib/compileall.py20
-rw-r--r--Lib/concurrent/futures/thread.py11
-rw-r--r--Lib/contextlib.py42
-rw-r--r--Lib/copy.py115
-rw-r--r--Lib/crypt.py3
-rw-r--r--Lib/csv.py24
-rw-r--r--Lib/ctypes/__init__.py17
-rw-r--r--Lib/ctypes/test/test_bitfields.py5
-rw-r--r--Lib/ctypes/test/test_find.py43
-rw-r--r--Lib/ctypes/test/test_funcptr.py4
-rw-r--r--Lib/ctypes/test/test_loading.py17
-rw-r--r--Lib/ctypes/test/test_objects.py2
-rw-r--r--Lib/ctypes/test/test_parameters.py8
-rw-r--r--Lib/ctypes/test/test_pep3118.py2
-rw-r--r--Lib/ctypes/test/test_returnfuncptrs.py1
-rw-r--r--Lib/ctypes/test/test_sizes.py1
-rw-r--r--Lib/ctypes/test/test_structures.py7
-rw-r--r--Lib/ctypes/test/test_values.py6
-rw-r--r--Lib/ctypes/util.py40
-rw-r--r--Lib/datetime.py312
-rw-r--r--Lib/dbm/dumb.py17
-rw-r--r--Lib/difflib.py2
-rw-r--r--Lib/dis.py61
-rw-r--r--Lib/distutils/archive_util.py2
-rw-r--r--Lib/distutils/cmd.py5
-rw-r--r--Lib/distutils/command/bdist_dumb.py2
-rw-r--r--Lib/distutils/command/bdist_msi.py6
-rw-r--r--Lib/distutils/command/bdist_wininst.py2
-rw-r--r--Lib/distutils/command/build.py4
-rw-r--r--Lib/distutils/command/build_ext.py6
-rw-r--r--Lib/distutils/command/build_scripts.py2
-rw-r--r--Lib/distutils/command/config.py4
-rw-r--r--Lib/distutils/command/install.py12
-rw-r--r--Lib/distutils/command/install_egg_info.py4
-rw-r--r--Lib/distutils/command/register.py8
-rw-r--r--Lib/distutils/command/sdist.py15
-rw-r--r--Lib/distutils/core.py5
-rw-r--r--Lib/distutils/cygwinccompiler.py2
-rw-r--r--Lib/distutils/dist.py3
-rw-r--r--Lib/distutils/extension.py1
-rw-r--r--Lib/distutils/filelist.py15
-rw-r--r--Lib/distutils/msvc9compiler.py2
-rw-r--r--Lib/distutils/sysconfig.py48
-rw-r--r--Lib/distutils/tests/test_bdist_rpm.py2
-rw-r--r--Lib/distutils/tests/test_build.py5
-rw-r--r--Lib/distutils/tests/test_build_clib.py20
-rw-r--r--Lib/distutils/tests/test_build_ext.py7
-rw-r--r--Lib/distutils/tests/test_build_py.py3
-rw-r--r--Lib/distutils/tests/test_clean.py2
-rw-r--r--Lib/distutils/tests/test_config.py2
-rw-r--r--Lib/distutils/tests/test_config_cmd.py5
-rw-r--r--Lib/distutils/tests/test_core.py30
-rw-r--r--Lib/distutils/tests/test_cygwinccompiler.py3
-rw-r--r--Lib/distutils/tests/test_dep_util.py1
-rw-r--r--Lib/distutils/tests/test_file_util.py1
-rw-r--r--Lib/distutils/tests/test_filelist.py14
-rw-r--r--Lib/distutils/tests/test_install.py4
-rw-r--r--Lib/distutils/tests/test_install_data.py2
-rw-r--r--Lib/distutils/tests/test_install_headers.py2
-rw-r--r--Lib/distutils/tests/test_install_lib.py3
-rw-r--r--Lib/distutils/tests/test_spawn.py14
-rw-r--r--Lib/distutils/tests/test_sysconfig.py9
-rw-r--r--Lib/distutils/tests/test_unixccompiler.py1
-rw-r--r--Lib/distutils/text_file.py2
-rw-r--r--Lib/distutils/util.py15
-rw-r--r--Lib/distutils/versionpredicate.py2
-rw-r--r--Lib/doctest.py25
-rw-r--r--Lib/email/_header_value_parser.py16
-rw-r--r--Lib/email/_policybase.py4
-rw-r--r--Lib/email/contentmanager.py6
-rw-r--r--Lib/email/feedparser.py19
-rw-r--r--Lib/email/generator.py6
-rw-r--r--Lib/email/header.py4
-rw-r--r--Lib/email/message.py25
-rw-r--r--Lib/email/mime/application.py5
-rw-r--r--Lib/email/mime/audio.py5
-rw-r--r--Lib/email/mime/base.py8
-rw-r--r--Lib/email/mime/image.py5
-rw-r--r--Lib/email/mime/message.py4
-rw-r--r--Lib/email/mime/multipart.py3
-rw-r--r--Lib/email/mime/text.py4
-rw-r--r--Lib/email/policy.py2
-rw-r--r--Lib/encodings/__init__.py17
-rw-r--r--Lib/encodings/aliases.py1
-rw-r--r--Lib/encodings/oem.py41
-rw-r--r--Lib/ensurepip/__init__.py20
-rw-r--r--Lib/enum.py328
-rw-r--r--Lib/fileinput.py14
-rw-r--r--Lib/fnmatch.py2
-rw-r--r--Lib/fractions.py34
-rw-r--r--Lib/ftplib.py11
-rw-r--r--Lib/functools.py92
-rw-r--r--Lib/genericpath.py6
-rw-r--r--Lib/glob.py70
-rw-r--r--Lib/gzip.py8
-rw-r--r--Lib/hashlib.py54
-rw-r--r--Lib/hmac.py2
-rw-r--r--Lib/html/parser.py4
-rw-r--r--Lib/http/client.py241
-rw-r--r--Lib/http/cookiejar.py6
-rw-r--r--Lib/http/cookies.py5
-rw-r--r--Lib/http/server.py66
-rw-r--r--Lib/idlelib/NEWS.txt96
-rw-r--r--Lib/idlelib/README.txt287
-rw-r--r--Lib/idlelib/__init__.py2
-rw-r--r--Lib/idlelib/__main__.py4
-rw-r--r--Lib/idlelib/autocomplete.py (renamed from Lib/idlelib/AutoComplete.py)67
-rw-r--r--Lib/idlelib/autocomplete_w.py (renamed from Lib/idlelib/AutoCompleteWindow.py)41
-rw-r--r--Lib/idlelib/autoexpand.py (renamed from Lib/idlelib/AutoExpand.py)7
-rw-r--r--Lib/idlelib/browser.py (renamed from Lib/idlelib/ClassBrowser.py)18
-rw-r--r--Lib/idlelib/calltip_w.py (renamed from Lib/idlelib/CallTipWindow.py)8
-rw-r--r--Lib/idlelib/calltips.py (renamed from Lib/idlelib/CallTips.py)12
-rw-r--r--Lib/idlelib/codecontext.py (renamed from Lib/idlelib/CodeContext.py)12
-rw-r--r--Lib/idlelib/colorizer.py (renamed from Lib/idlelib/ColorDelegator.py)40
-rw-r--r--Lib/idlelib/config-keys.def51
-rw-r--r--Lib/idlelib/config-main.def74
-rw-r--r--Lib/idlelib/config.py (renamed from Lib/idlelib/configHandler.py)185
-rw-r--r--Lib/idlelib/configHelpSourceEdit.py170
-rw-r--r--Lib/idlelib/configSectionNameDialog.py98
-rw-r--r--Lib/idlelib/config_key.py (renamed from Lib/idlelib/keybindingDialog.py)21
-rw-r--r--Lib/idlelib/configdialog.py (renamed from Lib/idlelib/configDialog.py)163
-rw-r--r--Lib/idlelib/debugger.py (renamed from Lib/idlelib/Debugger.py)21
-rw-r--r--Lib/idlelib/debugger_r.py (renamed from Lib/idlelib/RemoteDebugger.py)8
-rw-r--r--Lib/idlelib/debugobj.py (renamed from Lib/idlelib/ObjectBrowser.py)26
-rw-r--r--Lib/idlelib/debugobj_r.py (renamed from Lib/idlelib/RemoteObjectBrowser.py)0
-rw-r--r--Lib/idlelib/delegator.py (renamed from Lib/idlelib/Delegator.py)0
-rw-r--r--Lib/idlelib/dynoption.py (renamed from Lib/idlelib/dynOptionMenuWidget.py)9
-rw-r--r--Lib/idlelib/editor.py (renamed from Lib/idlelib/EditorWindow.py)276
-rw-r--r--Lib/idlelib/filelist.py (renamed from Lib/idlelib/FileList.py)5
-rw-r--r--Lib/idlelib/grep.py (renamed from Lib/idlelib/GrepDialog.py)48
-rw-r--r--Lib/idlelib/help.py26
-rw-r--r--Lib/idlelib/help.txt372
-rw-r--r--Lib/idlelib/help_about.py (renamed from Lib/idlelib/aboutDialog.py)13
-rw-r--r--Lib/idlelib/history.py (renamed from Lib/idlelib/IdleHistory.py)8
-rw-r--r--Lib/idlelib/hyperparser.py (renamed from Lib/idlelib/HyperParser.py)7
-rw-r--r--Lib/idlelib/idle.py3
-rw-r--r--Lib/idlelib/idle.pyw12
-rw-r--r--Lib/idlelib/idle_test/__init__.py2
-rw-r--r--Lib/idlelib/idle_test/htest.py145
-rw-r--r--Lib/idlelib/idle_test/mock_idle.py4
-rw-r--r--Lib/idlelib/idle_test/test_autocomplete.py13
-rw-r--r--Lib/idlelib/idle_test/test_autoexpand.py6
-rw-r--r--Lib/idlelib/idle_test/test_calltips.py2
-rw-r--r--Lib/idlelib/idle_test/test_colorizer.py56
-rw-r--r--Lib/idlelib/idle_test/test_config.py160
-rw-r--r--Lib/idlelib/idle_test/test_config_help.py106
-rw-r--r--Lib/idlelib/idle_test/test_config_key.py33
-rw-r--r--Lib/idlelib/idle_test/test_config_name.py75
-rw-r--r--Lib/idlelib/idle_test/test_configdialog.py135
-rw-r--r--Lib/idlelib/idle_test/test_debugger.py29
-rw-r--r--Lib/idlelib/idle_test/test_delegator.py2
-rw-r--r--Lib/idlelib/idle_test/test_editmenu.py30
-rw-r--r--Lib/idlelib/idle_test/test_editor.py2
-rw-r--r--Lib/idlelib/idle_test/test_grep.py6
-rw-r--r--Lib/idlelib/idle_test/test_help.py34
-rw-r--r--Lib/idlelib/idle_test/test_help_about.py24
-rw-r--r--Lib/idlelib/idle_test/test_history.py (renamed from Lib/idlelib/idle_test/test_idlehistory.py)4
-rw-r--r--Lib/idlelib/idle_test/test_hyperparser.py6
-rw-r--r--Lib/idlelib/idle_test/test_iomenu.py (renamed from Lib/idlelib/idle_test/test_io.py)5
-rw-r--r--Lib/idlelib/idle_test/test_macosx.py103
-rw-r--r--Lib/idlelib/idle_test/test_paragraph.py (renamed from Lib/idlelib/idle_test/test_formatparagraph.py)8
-rw-r--r--Lib/idlelib/idle_test/test_parenmatch.py17
-rw-r--r--Lib/idlelib/idle_test/test_pathbrowser.py8
-rw-r--r--Lib/idlelib/idle_test/test_percolator.py4
-rw-r--r--Lib/idlelib/idle_test/test_query.py353
-rw-r--r--Lib/idlelib/idle_test/test_redirector.py (renamed from Lib/idlelib/idle_test/test_widgetredir.py)5
-rw-r--r--Lib/idlelib/idle_test/test_replace.py (renamed from Lib/idlelib/idle_test/test_replacedialog.py)16
-rw-r--r--Lib/idlelib/idle_test/test_rstrip.py4
-rw-r--r--Lib/idlelib/idle_test/test_scrolledlist.py29
-rw-r--r--Lib/idlelib/idle_test/test_search.py (renamed from Lib/idlelib/idle_test/test_searchdialog.py)8
-rw-r--r--Lib/idlelib/idle_test/test_searchbase.py (renamed from Lib/idlelib/idle_test/test_searchdialogbase.py)27
-rw-r--r--Lib/idlelib/idle_test/test_searchengine.py16
-rw-r--r--Lib/idlelib/idle_test/test_text.py21
-rw-r--r--Lib/idlelib/idle_test/test_textview.py20
-rw-r--r--Lib/idlelib/idle_test/test_tree.py36
-rw-r--r--Lib/idlelib/idle_test/test_undo.py (renamed from Lib/idlelib/idle_test/test_undodelegator.py)8
-rw-r--r--Lib/idlelib/idle_test/test_warning.py6
-rw-r--r--Lib/idlelib/idlever.py12
-rw-r--r--Lib/idlelib/iomenu.py (renamed from Lib/idlelib/IOBinding.py)95
-rw-r--r--Lib/idlelib/macosx.py (renamed from Lib/idlelib/macosxSupport.py)99
-rw-r--r--Lib/idlelib/mainmenu.py (renamed from Lib/idlelib/Bindings.py)4
-rw-r--r--Lib/idlelib/multicall.py (renamed from Lib/idlelib/MultiCall.py)17
-rw-r--r--Lib/idlelib/outwin.py (renamed from Lib/idlelib/OutputWindow.py)11
-rw-r--r--Lib/idlelib/paragraph.py (renamed from Lib/idlelib/FormatParagraph.py)10
-rw-r--r--Lib/idlelib/parenmatch.py (renamed from Lib/idlelib/ParenMatch.py)14
-rw-r--r--Lib/idlelib/pathbrowser.py (renamed from Lib/idlelib/PathBrowser.py)11
-rw-r--r--Lib/idlelib/percolator.py (renamed from Lib/idlelib/Percolator.py)13
-rw-r--r--Lib/idlelib/pyparse.py (renamed from Lib/idlelib/PyParse.py)2
-rwxr-xr-xLib/idlelib/pyshell.py (renamed from Lib/idlelib/PyShell.py)220
-rw-r--r--Lib/idlelib/query.py308
-rw-r--r--Lib/idlelib/redirector.py (renamed from Lib/idlelib/WidgetRedirector.py)21
-rw-r--r--Lib/idlelib/replace.py (renamed from Lib/idlelib/ReplaceDialog.py)26
-rw-r--r--Lib/idlelib/rpc.py26
-rw-r--r--Lib/idlelib/rstrip.py (renamed from Lib/idlelib/RstripExtension.py)0
-rw-r--r--Lib/idlelib/run.py159
-rw-r--r--Lib/idlelib/runscript.py (renamed from Lib/idlelib/ScriptBinding.py)17
-rw-r--r--Lib/idlelib/scrolledlist.py (renamed from Lib/idlelib/ScrolledList.py)21
-rw-r--r--Lib/idlelib/search.py (renamed from Lib/idlelib/SearchDialog.py)29
-rw-r--r--Lib/idlelib/searchbase.py (renamed from Lib/idlelib/SearchDialogBase.py)40
-rw-r--r--Lib/idlelib/searchengine.py (renamed from Lib/idlelib/SearchEngine.py)5
-rw-r--r--Lib/idlelib/stackviewer.py (renamed from Lib/idlelib/StackViewer.py)30
-rw-r--r--Lib/idlelib/statusbar.py (renamed from Lib/idlelib/MultiStatusBar.py)35
-rw-r--r--Lib/idlelib/tabbedpages.py26
-rw-r--r--Lib/idlelib/textview.py (renamed from Lib/idlelib/textView.py)34
-rw-r--r--Lib/idlelib/tooltip.py (renamed from Lib/idlelib/ToolTip.py)19
-rw-r--r--Lib/idlelib/tree.py (renamed from Lib/idlelib/TreeWidget.py)23
-rw-r--r--Lib/idlelib/undo.py (renamed from Lib/idlelib/UndoDelegator.py)26
-rw-r--r--Lib/idlelib/windows.py (renamed from Lib/idlelib/WindowList.py)2
-rw-r--r--Lib/idlelib/zoomheight.py (renamed from Lib/idlelib/ZoomHeight.py)6
-rw-r--r--Lib/imaplib.py19
-rw-r--r--Lib/imghdr.py4
-rw-r--r--Lib/imp.py2
-rw-r--r--Lib/importlib/_bootstrap.py70
-rw-r--r--Lib/importlib/_bootstrap_external.py102
-rw-r--r--Lib/importlib/util.py28
-rw-r--r--Lib/inspect.py96
-rw-r--r--Lib/io.py7
-rw-r--r--Lib/ipaddress.py4
-rw-r--r--Lib/json/__init__.py59
-rw-r--r--Lib/json/decoder.py2
-rw-r--r--Lib/json/encoder.py5
-rw-r--r--Lib/lib2to3/Grammar.txt7
-rw-r--r--Lib/lib2to3/fixer_util.py2
-rw-r--r--Lib/lib2to3/fixes/fix_dict.py3
-rw-r--r--Lib/lib2to3/fixes/fix_exec.py1
-rw-r--r--Lib/lib2to3/fixes/fix_filter.py1
-rw-r--r--Lib/lib2to3/fixes/fix_has_key.py1
-rw-r--r--Lib/lib2to3/fixes/fix_metaclass.py2
-rw-r--r--Lib/lib2to3/fixes/fix_nonzero.py2
-rw-r--r--Lib/lib2to3/fixes/fix_print.py2
-rw-r--r--Lib/lib2to3/fixes/fix_types.py3
-rw-r--r--Lib/lib2to3/fixes/fix_urllib.py1
-rw-r--r--Lib/lib2to3/refactor.py3
-rw-r--r--Lib/lib2to3/tests/data/py3_test_grammar.py2
-rw-r--r--Lib/lib2to3/tests/support.py2
-rw-r--r--Lib/lib2to3/tests/test_all_fixers.py1
-rw-r--r--Lib/lib2to3/tests/test_fixers.py7
-rw-r--r--Lib/lib2to3/tests/test_parser.py50
-rw-r--r--Lib/lib2to3/tests/test_pytree.py5
-rw-r--r--Lib/lib2to3/tests/test_refactor.py6
-rw-r--r--Lib/lib2to3/tests/test_util.py3
-rw-r--r--Lib/locale.py8
-rw-r--r--Lib/logging/__init__.py35
-rw-r--r--Lib/logging/handlers.py34
-rw-r--r--Lib/lzma.py18
-rw-r--r--Lib/mailbox.py28
-rw-r--r--Lib/mimetypes.py6
-rw-r--r--Lib/modulefinder.py7
-rw-r--r--Lib/msilib/__init__.py12
-rw-r--r--Lib/multiprocessing/connection.py8
-rw-r--r--Lib/multiprocessing/context.py13
-rw-r--r--Lib/multiprocessing/forkserver.py2
-rw-r--r--Lib/multiprocessing/heap.py5
-rw-r--r--Lib/multiprocessing/managers.py100
-rw-r--r--Lib/multiprocessing/pool.py20
-rw-r--r--Lib/multiprocessing/popen_forkserver.py7
-rw-r--r--Lib/multiprocessing/popen_spawn_posix.py7
-rw-r--r--Lib/multiprocessing/popen_spawn_win32.py9
-rw-r--r--Lib/multiprocessing/queues.py10
-rw-r--r--Lib/multiprocessing/reduction.py34
-rw-r--r--Lib/multiprocessing/resource_sharer.py2
-rw-r--r--Lib/multiprocessing/sharedctypes.py6
-rw-r--r--Lib/multiprocessing/spawn.py9
-rw-r--r--Lib/ntpath.py20
-rw-r--r--Lib/opcode.py32
-rw-r--r--Lib/optparse.py3
-rw-r--r--Lib/os.py253
-rw-r--r--Lib/pathlib.py147
-rwxr-xr-xLib/pdb.py22
-rw-r--r--Lib/pickle.py105
-rw-r--r--Lib/pickletools.py3
-rw-r--r--Lib/pkgutil.py31
-rw-r--r--Lib/plat-aix4/IN.py165
-rwxr-xr-xLib/plat-aix4/regen8
-rw-r--r--Lib/plat-darwin/IN.py662
-rwxr-xr-xLib/plat-darwin/regen3
-rw-r--r--Lib/plat-freebsd4/IN.py355
-rwxr-xr-xLib/plat-freebsd4/regen3
-rw-r--r--Lib/plat-freebsd5/IN.py355
-rwxr-xr-xLib/plat-freebsd5/regen3
-rw-r--r--Lib/plat-freebsd6/IN.py551
-rwxr-xr-xLib/plat-freebsd6/regen3
-rw-r--r--Lib/plat-freebsd7/IN.py571
-rwxr-xr-xLib/plat-freebsd7/regen3
-rw-r--r--Lib/plat-freebsd8/IN.py571
-rwxr-xr-xLib/plat-freebsd8/regen3
-rwxr-xr-xLib/plat-generic/regen3
-rw-r--r--Lib/plat-linux/CDROM.py207
-rw-r--r--Lib/plat-linux/DLFCN.py83
-rw-r--r--Lib/plat-linux/IN.py615
-rw-r--r--Lib/plat-linux/TYPES.py170
-rwxr-xr-xLib/plat-linux/regen8
-rw-r--r--Lib/plat-netbsd1/IN.py56
-rwxr-xr-xLib/plat-netbsd1/regen3
-rwxr-xr-xLib/plat-next3/regen6
-rw-r--r--Lib/plat-sunos5/CDIO.py73
-rw-r--r--Lib/plat-sunos5/DLFCN.py27
-rw-r--r--Lib/plat-sunos5/IN.py1421
-rw-r--r--Lib/plat-sunos5/STROPTS.py1813
-rw-r--r--Lib/plat-sunos5/TYPES.py313
-rwxr-xr-xLib/plat-sunos5/regen9
-rw-r--r--Lib/plat-unixware7/IN.py836
-rw-r--r--Lib/plat-unixware7/STROPTS.py328
-rwxr-xr-xLib/plat-unixware7/regen9
-rwxr-xr-xLib/platform.py37
-rw-r--r--Lib/plistlib.py2
-rw-r--r--Lib/poplib.py4
-rw-r--r--Lib/posixpath.py19
-rw-r--r--Lib/pyclbr.py3
-rw-r--r--[-rwxr-xr-x]Lib/pydoc.py36
-rw-r--r--Lib/pydoc_data/topics.py13059
-rw-r--r--Lib/random.py56
-rw-r--r--Lib/re.py51
-rw-r--r--Lib/rlcompleter.py38
-rw-r--r--Lib/sched.py17
-rw-r--r--Lib/secrets.py73
-rw-r--r--Lib/shlex.py72
-rw-r--r--Lib/shutil.py3
-rw-r--r--Lib/site-packages/README.txt2
-rw-r--r--Lib/site.py93
-rwxr-xr-xLib/smtpd.py42
-rwxr-xr-xLib/smtplib.py8
-rw-r--r--Lib/sndhdr.py12
-rw-r--r--Lib/socket.py12
-rw-r--r--Lib/socketserver.py210
-rw-r--r--Lib/sqlite3/test/dbapi.py43
-rw-r--r--Lib/sqlite3/test/transactions.py36
-rw-r--r--Lib/sre_compile.py140
-rw-r--r--Lib/sre_parse.py191
-rw-r--r--Lib/ssl.py179
-rw-r--r--Lib/statistics.py151
-rw-r--r--Lib/string.py11
-rw-r--r--Lib/subprocess.py113
-rwxr-xr-xLib/symbol.py137
-rw-r--r--Lib/symtable.py5
-rw-r--r--Lib/sysconfig.py28
-rwxr-xr-xLib/tarfile.py139
-rw-r--r--Lib/telnetlib.py15
-rw-r--r--Lib/tempfile.py1
-rw-r--r--Lib/test/__main__.py5
-rw-r--r--Lib/test/_test_multiprocessing.py96
-rw-r--r--Lib/test/ann_module.py53
-rw-r--r--Lib/test/ann_module2.py36
-rw-r--r--Lib/test/ann_module3.py18
-rw-r--r--Lib/test/audiotests.py3
-rw-r--r--Lib/test/autotest.py5
-rw-r--r--Lib/test/badsyntax_async1.py2
-rw-r--r--Lib/test/badsyntax_async2.py2
-rw-r--r--Lib/test/badsyntax_async3.py2
-rw-r--r--Lib/test/badsyntax_async4.py2
-rw-r--r--Lib/test/badsyntax_async5.py2
-rw-r--r--Lib/test/badsyntax_async6.py2
-rw-r--r--Lib/test/badsyntax_async7.py2
-rw-r--r--Lib/test/badsyntax_async8.py2
-rw-r--r--Lib/test/capath/0e4015b9.016
-rw-r--r--Lib/test/capath/b1930218.021
-rw-r--r--Lib/test/capath/ce7b8643.016
-rw-r--r--Lib/test/capath/ceff1710.021
-rw-r--r--Lib/test/cmath_testcases.txt141
-rw-r--r--Lib/test/datetimetester.py900
-rw-r--r--Lib/test/dtracedata/assert_usable.d5
-rw-r--r--Lib/test/dtracedata/assert_usable.stp5
-rw-r--r--Lib/test/dtracedata/call_stack.d31
-rw-r--r--Lib/test/dtracedata/call_stack.d.expected18
-rw-r--r--Lib/test/dtracedata/call_stack.py30
-rw-r--r--Lib/test/dtracedata/call_stack.stp41
-rw-r--r--Lib/test/dtracedata/call_stack.stp.expected14
-rw-r--r--Lib/test/dtracedata/gc.d18
-rw-r--r--Lib/test/dtracedata/gc.d.expected8
-rw-r--r--Lib/test/dtracedata/gc.py13
-rw-r--r--Lib/test/dtracedata/gc.stp26
-rw-r--r--Lib/test/dtracedata/gc.stp.expected8
-rw-r--r--Lib/test/dtracedata/instance.py24
-rw-r--r--Lib/test/dtracedata/line.d7
-rw-r--r--Lib/test/dtracedata/line.d.expected20
-rw-r--r--Lib/test/dtracedata/line.py17
-rw-r--r--Lib/test/eintrdata/eintr_tester.py15
-rw-r--r--Lib/test/exception_hierarchy.txt1
-rw-r--r--Lib/test/libregrtest/__init__.py5
-rw-r--r--Lib/test/libregrtest/cmdline.py347
-rw-r--r--Lib/test/libregrtest/main.py532
-rw-r--r--Lib/test/libregrtest/refleak.py269
-rw-r--r--Lib/test/libregrtest/runtest.py245
-rw-r--r--Lib/test/libregrtest/runtest_mp.py245
-rw-r--r--Lib/test/libregrtest/save_env.py285
-rw-r--r--Lib/test/libregrtest/setup.py121
-rw-r--r--Lib/test/list_tests.py14
-rw-r--r--Lib/test/lock_tests.py12
-rw-r--r--Lib/test/make_ssl_certs.py1
-rw-r--r--Lib/test/pickletester.py23
-rw-r--r--Lib/test/pydoc_mod.py2
-rwxr-xr-xLib/test/re_tests.py12
-rwxr-xr-xLib/test/regrtest.py1659
-rw-r--r--Lib/test/seq_tests.py1
-rw-r--r--Lib/test/signalinterproctester.py84
-rw-r--r--Lib/test/sortperf.py2
-rw-r--r--Lib/test/support/__init__.py146
-rw-r--r--Lib/test/test___all__.py2
-rw-r--r--Lib/test/test__locale.py1
-rw-r--r--Lib/test/test__osx_support.py1
-rw-r--r--Lib/test/test_aifc.py1
-rw-r--r--Lib/test/test_argparse.py15
-rw-r--r--Lib/test/test_array.py23
-rw-r--r--Lib/test/test_ast.py177
-rw-r--r--Lib/test/test_asyncgen.py1044
-rw-r--r--Lib/test/test_asynchat.py32
-rw-r--r--Lib/test/test_asyncio/test_futures.py186
-rw-r--r--Lib/test/test_asyncio/test_tasks.py454
-rw-r--r--Lib/test/test_asyncore.py7
-rw-r--r--Lib/test/test_augassign.py8
-rw-r--r--Lib/test/test_baseexception.py (renamed from Lib/test/test_pep352.py)1
-rw-r--r--Lib/test/test_bigmem.py1
-rw-r--r--Lib/test/test_binascii.py26
-rw-r--r--Lib/test/test_binhex.py1
-rw-r--r--Lib/test/test_binop.py50
-rw-r--r--Lib/test/test_bool.py18
-rw-r--r--Lib/test/test_buffer.py1
-rw-r--r--Lib/test/test_bufio.py2
-rw-r--r--Lib/test/test_builtin.py24
-rw-r--r--Lib/test/test_bytes.py230
-rw-r--r--Lib/test/test_bz2.py12
-rw-r--r--Lib/test/test_calendar.py17
-rw-r--r--Lib/test/test_capi.py120
-rw-r--r--Lib/test/test_cgi.py8
-rw-r--r--Lib/test/test_charmapcodec.py2
-rw-r--r--Lib/test/test_cmath.py37
-rw-r--r--Lib/test/test_cmd_line.py14
-rw-r--r--Lib/test/test_cmd_line_script.py7
-rw-r--r--Lib/test/test_code_module.py30
-rw-r--r--Lib/test/test_codeccallbacks.py5
-rw-r--r--Lib/test/test_codecencodings_cn.py1
-rw-r--r--Lib/test/test_codecencodings_hk.py1
-rw-r--r--Lib/test/test_codecencodings_iso2022.py1
-rw-r--r--Lib/test/test_codecencodings_jp.py1
-rw-r--r--Lib/test/test_codecencodings_kr.py1
-rw-r--r--Lib/test/test_codecencodings_tw.py1
-rw-r--r--Lib/test/test_codecmaps_cn.py1
-rw-r--r--Lib/test/test_codecmaps_hk.py1
-rw-r--r--Lib/test/test_codecmaps_jp.py1
-rw-r--r--Lib/test/test_codecmaps_kr.py1
-rw-r--r--Lib/test/test_codecmaps_tw.py1
-rw-r--r--Lib/test/test_codecs.py255
-rw-r--r--Lib/test/test_codeop.py1
-rw-r--r--Lib/test/test_collections.py299
-rw-r--r--Lib/test/test_compile.py17
-rw-r--r--Lib/test/test_compileall.py57
-rw-r--r--Lib/test/test_complex.py14
-rw-r--r--Lib/test/test_concurrent_futures.py24
-rw-r--r--Lib/test/test_configparser.py6
-rw-r--r--Lib/test/test_contains.py25
-rw-r--r--Lib/test/test_contextlib.py35
-rw-r--r--Lib/test/test_copy.py2
-rw-r--r--Lib/test/test_coroutines.py489
-rw-r--r--Lib/test/test_cprofile.py2
-rw-r--r--Lib/test/test_csv.py101
-rw-r--r--Lib/test/test_datetime.py10
-rw-r--r--Lib/test/test_dbm.py1
-rw-r--r--Lib/test/test_dbm_dumb.py27
-rw-r--r--Lib/test/test_dbm_gnu.py2
-rw-r--r--Lib/test/test_dbm_ndbm.py2
-rw-r--r--Lib/test/test_decimal.py43
-rw-r--r--Lib/test/test_deque.py79
-rw-r--r--Lib/test/test_descr.py15
-rw-r--r--Lib/test/test_descrtut.py1
-rw-r--r--Lib/test/test_devpoll.py3
-rw-r--r--Lib/test/test_dict.py157
-rw-r--r--Lib/test/test_dict_version.py186
-rw-r--r--Lib/test/test_dictcomps.py2
-rw-r--r--Lib/test/test_dictviews.py22
-rw-r--r--Lib/test/test_difflib.py12
-rw-r--r--Lib/test/test_difflib_expect.html12
-rw-r--r--Lib/test/test_dis.py589
-rw-r--r--Lib/test/test_doctest.py9
-rw-r--r--Lib/test/test_dtrace.py178
-rw-r--r--Lib/test/test_dynamic.py1
-rw-r--r--Lib/test/test_eintr.py12
-rw-r--r--Lib/test/test_email/__init__.py1
-rw-r--r--Lib/test/test_email/test__header_value_parser.py4
-rw-r--r--Lib/test/test_email/test_asian_codecs.py1
-rw-r--r--Lib/test/test_email/test_email.py44
-rw-r--r--Lib/test/test_email/test_generator.py2
-rw-r--r--Lib/test/test_email/test_headerregistry.py1
-rw-r--r--Lib/test/test_email/test_message.py20
-rw-r--r--Lib/test/test_email/test_parser.py91
-rw-r--r--Lib/test/test_email/test_policy.py42
-rw-r--r--Lib/test/test_ensurepip.py65
-rw-r--r--Lib/test/test_enum.py777
-rw-r--r--Lib/test/test_enumerate.py9
-rw-r--r--Lib/test/test_epoll.py1
-rw-r--r--Lib/test/test_exception_hierarchy.py (renamed from Lib/test/test_pep3151.py)1
-rw-r--r--Lib/test/test_exceptions.py1
-rw-r--r--Lib/test/test_extcall.py5
-rw-r--r--Lib/test/test_faulthandler.py112
-rw-r--r--Lib/test/test_file.py4
-rw-r--r--Lib/test/test_fileinput.py36
-rw-r--r--Lib/test/test_float.py46
-rw-r--r--Lib/test/test_fnmatch.py16
-rw-r--r--Lib/test/test_format.py4
-rw-r--r--Lib/test/test_fractions.py15
-rw-r--r--Lib/test/test_fstring.py760
-rw-r--r--Lib/test/test_ftplib.py21
-rw-r--r--Lib/test/test_functools.py194
-rw-r--r--Lib/test/test_future.py2
-rw-r--r--Lib/test/test_gc.py2
-rw-r--r--Lib/test/test_gdb.py59
-rw-r--r--Lib/test/test_generator_stop.py (renamed from Lib/test/test_pep479.py)0
-rw-r--r--Lib/test/test_generators.py6
-rw-r--r--Lib/test/test_genericpath.py342
-rw-r--r--Lib/test/test_getargs2.py64
-rw-r--r--Lib/test/test_gettext.py7
-rw-r--r--Lib/test/test_global.py6
-rw-r--r--Lib/test/test_grammar.py316
-rw-r--r--Lib/test/test_grp.py10
-rw-r--r--Lib/test/test_gzip.py26
-rw-r--r--Lib/test/test_hashlib.py428
-rw-r--r--Lib/test/test_heapq.py1
-rw-r--r--Lib/test/test_hmac.py1
-rw-r--r--Lib/test/test_htmlparser.py3
-rw-r--r--Lib/test/test_http_cookiejar.py6
-rw-r--r--Lib/test/test_httplib.py198
-rw-r--r--Lib/test/test_httpservers.py50
-rw-r--r--Lib/test/test_idle.py23
-rw-r--r--Lib/test/test_imaplib.py61
-rw-r--r--Lib/test/test_imghdr.py7
-rw-r--r--Lib/test/test_imp.py3
-rw-r--r--Lib/test/test_import/__init__.py12
-rw-r--r--Lib/test/test_importlib/extension/test_case_sensitivity.py3
-rw-r--r--Lib/test/test_importlib/extension/test_finder.py1
-rw-r--r--Lib/test/test_importlib/extension/test_path_hook.py2
-rw-r--r--Lib/test/test_importlib/frozen/test_loader.py2
-rw-r--r--Lib/test/test_importlib/import_/test___package__.py55
-rw-r--r--Lib/test/test_importlib/import_/test_api.py4
-rw-r--r--Lib/test/test_importlib/import_/test_fromlist.py10
-rw-r--r--Lib/test/test_importlib/import_/test_packages.py1
-rw-r--r--Lib/test/test_importlib/import_/test_path.py68
-rw-r--r--Lib/test/test_importlib/import_/test_relative_imports.py24
-rw-r--r--Lib/test/test_importlib/regrtest.py17
-rw-r--r--Lib/test/test_importlib/source/test_case_sensitivity.py1
-rw-r--r--Lib/test/test_importlib/source/test_file_loader.py9
-rw-r--r--Lib/test/test_importlib/source/test_path_hook.py11
-rw-r--r--Lib/test/test_importlib/source/test_source_encoding.py1
-rw-r--r--Lib/test/test_importlib/test_abc.py22
-rw-r--r--Lib/test/test_importlib/test_api.py31
-rw-r--r--Lib/test/test_importlib/test_lazy.py2
-rw-r--r--Lib/test/test_importlib/test_locks.py3
-rw-r--r--Lib/test/test_importlib/test_namespace_pkgs.py38
-rw-r--r--Lib/test/test_importlib/test_spec.py6
-rw-r--r--Lib/test/test_importlib/test_util.py27
-rw-r--r--Lib/test/test_importlib/test_windows.py2
-rw-r--r--Lib/test/test_inspect.py49
-rw-r--r--Lib/test/test_int.py26
-rw-r--r--Lib/test/test_io.py42
-rw-r--r--Lib/test/test_ipaddress.py11
-rw-r--r--Lib/test/test_iter.py12
-rw-r--r--Lib/test/test_iterlen.py1
-rw-r--r--Lib/test/test_itertools.py65
-rw-r--r--Lib/test/test_json/__init__.py1
-rw-r--r--Lib/test/test_json/test_decode.py4
-rw-r--r--Lib/test/test_json/test_fail.py1
-rw-r--r--Lib/test/test_json/test_unicode.py29
-rw-r--r--Lib/test/test_kqueue.py1
-rw-r--r--Lib/test/test_linecache.py75
-rw-r--r--Lib/test/test_list.py2
-rw-r--r--Lib/test/test_locale.py4
-rw-r--r--Lib/test/test_logging.py72
-rw-r--r--Lib/test/test_long.py76
-rw-r--r--Lib/test/test_lzma.py26
-rw-r--r--Lib/test/test_macpath.py2
-rw-r--r--Lib/test/test_mailbox.py17
-rw-r--r--Lib/test/test_mailcap.py3
-rw-r--r--Lib/test/test_marshal.py7
-rw-r--r--Lib/test/test_math.py310
-rw-r--r--Lib/test/test_mimetypes.py6
-rw-r--r--Lib/test/test_mmap.py7
-rw-r--r--Lib/test/test_msilib.py1
-rw-r--r--Lib/test/test_multibytecodec.py2
-rw-r--r--Lib/test/test_multiprocessing_fork.py6
-rw-r--r--Lib/test/test_multiprocessing_forkserver.py5
-rw-r--r--Lib/test/test_multiprocessing_main_handling.py6
-rw-r--r--Lib/test/test_multiprocessing_spawn.py5
-rw-r--r--Lib/test/test_nis.py1
-rw-r--r--Lib/test/test_nntplib.py6
-rw-r--r--Lib/test/test_normalization.py1
-rw-r--r--Lib/test/test_ntpath.py83
-rw-r--r--Lib/test/test_opcodes.py27
-rw-r--r--Lib/test/test_operator.py50
-rw-r--r--Lib/test/test_optparse.py7
-rw-r--r--Lib/test/test_ordered_dict.py59
-rw-r--r--Lib/test/test_os.py747
-rw-r--r--Lib/test/test_parser.py50
-rw-r--r--Lib/test/test_pathlib.py78
-rw-r--r--Lib/test/test_pdb.py70
-rw-r--r--Lib/test/test_peepholer.py20
-rw-r--r--Lib/test/test_pep247.py66
-rw-r--r--Lib/test/test_pickle.py16
-rw-r--r--Lib/test/test_pickletools.py34
-rw-r--r--Lib/test/test_pipes.py7
-rw-r--r--Lib/test/test_pkgutil.py6
-rw-r--r--Lib/test/test_platform.py5
-rw-r--r--Lib/test/test_plistlib.py9
-rw-r--r--Lib/test/test_poplib.py11
-rw-r--r--Lib/test/test_posix.py40
-rw-r--r--Lib/test/test_posixpath.py80
-rw-r--r--Lib/test/test_pow.py2
-rw-r--r--Lib/test/test_pty.py1
-rw-r--r--Lib/test/test_pulldom.py1
-rw-r--r--Lib/test/test_pwd.py26
-rw-r--r--Lib/test/test_pyclbr.py4
-rw-r--r--Lib/test/test_pydoc.py25
-rw-r--r--Lib/test/test_quopri.py2
-rw-r--r--Lib/test/test_random.py112
-rw-r--r--Lib/test/test_range.py52
-rw-r--r--Lib/test/test_re.py465
-rw-r--r--Lib/test/test_readline.py15
-rw-r--r--Lib/test/test_regrtest.py630
-rw-r--r--Lib/test/test_richcmp.py25
-rw-r--r--Lib/test/test_rlcompleter.py55
-rw-r--r--Lib/test/test_robotparser.py396
-rw-r--r--Lib/test/test_runpy.py11
-rw-r--r--Lib/test/test_sched.py21
-rw-r--r--Lib/test/test_secrets.py124
-rw-r--r--Lib/test/test_set.py22
-rw-r--r--Lib/test/test_shlex.py110
-rw-r--r--Lib/test/test_shutil.py17
-rw-r--r--Lib/test/test_signal.py171
-rw-r--r--Lib/test/test_site.py112
-rw-r--r--Lib/test/test_smtpd.py52
-rw-r--r--Lib/test/test_socket.py253
-rw-r--r--Lib/test/test_socketserver.py183
-rw-r--r--Lib/test/test_sort.py1
-rw-r--r--Lib/test/test_spwd.py15
-rw-r--r--Lib/test/test_ssl.py997
-rw-r--r--Lib/test/test_stat.py3
-rw-r--r--Lib/test/test_statistics.py200
-rw-r--r--Lib/test/test_strftime.py6
-rw-r--r--Lib/test/test_string_literals.py (renamed from Lib/test/test_strlit.py)51
-rw-r--r--Lib/test/test_strptime.py89
-rw-r--r--Lib/test/test_struct.py128
-rw-r--r--Lib/test/test_subclassinit.py284
-rw-r--r--Lib/test/test_subprocess.py247
-rw-r--r--Lib/test/test_sunau.py1
-rw-r--r--Lib/test/test_super.py164
-rw-r--r--Lib/test/test_support.py27
-rw-r--r--Lib/test/test_symbol.py54
-rw-r--r--Lib/test/test_symtable.py17
-rw-r--r--Lib/test/test_syntax.py32
-rw-r--r--Lib/test/test_sys.py47
-rw-r--r--Lib/test/test_sys_settrace.py4
-rw-r--r--Lib/test/test_sysconfig.py8
-rw-r--r--Lib/test/test_tarfile.py18
-rw-r--r--Lib/test/test_telnetlib.py6
-rw-r--r--Lib/test/test_threading.py11
-rw-r--r--Lib/test/test_time.py598
-rw-r--r--Lib/test/test_timeit.py22
-rw-r--r--Lib/test/test_tokenize.py76
-rw-r--r--Lib/test/test_tools/__init__.py1
-rw-r--r--Lib/test/test_tools/test_gprof2html.py3
-rw-r--r--Lib/test/test_tools/test_md5sum.py3
-rw-r--r--Lib/test/test_tools/test_pdeps.py4
-rw-r--r--Lib/test/test_tools/test_unparse.py19
-rw-r--r--Lib/test/test_trace.py66
-rw-r--r--Lib/test/test_traceback.py147
-rw-r--r--Lib/test/test_tracemalloc.py219
-rw-r--r--Lib/test/test_ttk_guionly.py1
-rw-r--r--Lib/test/test_ttk_textonly.py1
-rw-r--r--Lib/test/test_types.py19
-rw-r--r--Lib/test/test_unicode.py29
-rw-r--r--Lib/test/test_unicode_file_functions.py (renamed from Lib/test/test_pep277.py)0
-rw-r--r--Lib/test/test_unicode_identifiers.py (renamed from Lib/test/test_pep3131.py)0
-rw-r--r--Lib/test/test_unicodedata.py8
-rw-r--r--Lib/test/test_unpack.py21
-rw-r--r--Lib/test/test_unpack_ex.py1
-rw-r--r--Lib/test/test_urllib.py13
-rw-r--r--Lib/test/test_urllib2.py121
-rw-r--r--Lib/test/test_urllib2_localnet.py34
-rw-r--r--Lib/test/test_urllibnet.py1
-rw-r--r--Lib/test/test_urlparse.py36
-rw-r--r--Lib/test/test_userdict.py6
-rw-r--r--Lib/test/test_userlist.py2
-rw-r--r--Lib/test/test_userstring.py3
-rw-r--r--Lib/test/test_utf8source.py (renamed from Lib/test/test_pep3120.py)0
-rw-r--r--Lib/test/test_uu.py1
-rw-r--r--Lib/test/test_venv.py41
-rw-r--r--Lib/test/test_warnings/__init__.py90
-rw-r--r--Lib/test/test_wave.py8
-rw-r--r--Lib/test/test_weakref.py9
-rw-r--r--Lib/test/test_weakset.py9
-rw-r--r--Lib/test/test_winconsoleio.py147
-rw-r--r--Lib/test/test_winreg.py15
-rw-r--r--Lib/test/test_winsound.py26
-rw-r--r--Lib/test/test_with.py24
-rw-r--r--Lib/test/test_wsgiref.py2
-rw-r--r--Lib/test/test_xml_etree.py16
-rw-r--r--Lib/test/test_xml_etree_c.py4
-rw-r--r--Lib/test/test_xmlrpc.py53
-rw-r--r--Lib/test/test_xmlrpc_net.py3
-rw-r--r--Lib/test/test_yield_from.py (renamed from Lib/test/test_pep380.py)93
-rw-r--r--Lib/test/test_zipfile.py288
-rw-r--r--Lib/test/test_zipimport.py27
-rw-r--r--Lib/test/test_zipimport_support.py1
-rw-r--r--Lib/test/test_zlib.py35
-rw-r--r--Lib/threading.py8
-rw-r--r--[-rwxr-xr-x]Lib/timeit.py73
-rw-r--r--Lib/tkinter/__init__.py218
-rw-r--r--Lib/tkinter/commondialog.py5
-rw-r--r--Lib/tkinter/dialog.py5
-rw-r--r--Lib/tkinter/test/runtktests.py2
-rw-r--r--Lib/tkinter/test/test_tkinter/test_misc.py8
-rw-r--r--Lib/tkinter/test/test_tkinter/test_variables.py52
-rw-r--r--Lib/tkinter/test/test_tkinter/test_widgets.py7
-rw-r--r--Lib/tkinter/test/test_ttk/test_functions.py1
-rw-r--r--Lib/tkinter/test/test_ttk/test_widgets.py49
-rw-r--r--Lib/tkinter/tix.py36
-rw-r--r--Lib/tkinter/ttk.py66
-rw-r--r--Lib/tokenize.py135
-rwxr-xr-xLib/trace.py382
-rw-r--r--Lib/traceback.py28
-rw-r--r--Lib/tracemalloc.py73
-rw-r--r--Lib/turtledemo/__main__.py7
-rwxr-xr-xLib/turtledemo/bytedesign.py1
-rwxr-xr-xLib/turtledemo/planet_and_moon.py1
-rw-r--r--Lib/types.py5
-rw-r--r--Lib/unittest/mock.py48
-rw-r--r--Lib/unittest/runner.py2
-rw-r--r--Lib/unittest/test/test_assertions.py18
-rw-r--r--Lib/unittest/test/test_loader.py8
-rw-r--r--Lib/unittest/test/testmock/support.py2
-rw-r--r--Lib/unittest/test/testmock/testmagicmethods.py1
-rw-r--r--Lib/unittest/test/testmock/testmock.py39
-rw-r--r--Lib/unittest/test/testmock/testpatch.py10
-rw-r--r--Lib/urllib/parse.py70
-rw-r--r--Lib/urllib/request.py90
-rw-r--r--Lib/urllib/robotparser.py43
-rw-r--r--Lib/uuid.py1
-rw-r--r--Lib/venv/__init__.py58
-rw-r--r--Lib/warnings.py127
-rw-r--r--Lib/wave.py2
-rw-r--r--Lib/wsgiref/simple_server.py30
-rw-r--r--Lib/xml/dom/xmlbuilder.py6
-rw-r--r--Lib/xml/etree/ElementPath.py22
-rw-r--r--Lib/xml/etree/ElementTree.py98
-rw-r--r--Lib/xmlrpc/client.py34
-rw-r--r--Lib/xmlrpc/server.py25
-rw-r--r--Lib/zipfile.py444
-rwxr-xr-xMac/BuildScript/build-installer.py121
-rw-r--r--Mac/BuildScript/resources/ReadMe.rtf108
-rw-r--r--Mac/BuildScript/resources/Welcome.rtf13
-rwxr-xr-xMac/BuildScript/resources/install_certificates.command48
-rw-r--r--Mac/IDLE/IDLE.app/Contents/Resources/idlemain.py2
-rw-r--r--Makefile.pre.in143
-rw-r--r--Misc/ACKS33
-rw-r--r--Misc/HISTORY4301
-rw-r--r--Misc/NEWS7000
-rw-r--r--Misc/README.valgrind3
-rw-r--r--Misc/SpecialBuilds.txt34
-rw-r--r--Misc/coverity_model.c5
-rw-r--r--Misc/python.man3
-rw-r--r--Modules/Setup.config.in3
-rw-r--r--Modules/Setup.dist4
-rw-r--r--Modules/_asynciomodule.c2469
-rw-r--r--Modules/_bisectmodule.c6
-rwxr-xr-xModules/_blake2/blake2b2s.py49
-rw-r--r--Modules/_blake2/blake2b_impl.c460
-rw-r--r--Modules/_blake2/blake2module.c105
-rw-r--r--Modules/_blake2/blake2ns.h32
-rw-r--r--Modules/_blake2/blake2s_impl.c460
-rw-r--r--Modules/_blake2/clinic/blake2b_impl.c.h125
-rw-r--r--Modules/_blake2/clinic/blake2s_impl.c.h125
-rw-r--r--Modules/_blake2/impl/blake2-config.h74
-rw-r--r--Modules/_blake2/impl/blake2-impl.h139
-rw-r--r--Modules/_blake2/impl/blake2.h161
-rw-r--r--Modules/_blake2/impl/blake2b-load-sse2.h70
-rw-r--r--Modules/_blake2/impl/blake2b-load-sse41.h404
-rw-r--r--Modules/_blake2/impl/blake2b-ref.c420
-rw-r--r--Modules/_blake2/impl/blake2b-round.h159
-rw-r--r--Modules/_blake2/impl/blake2b.c453
-rw-r--r--Modules/_blake2/impl/blake2s-load-sse2.h61
-rw-r--r--Modules/_blake2/impl/blake2s-load-sse41.h231
-rw-r--r--Modules/_blake2/impl/blake2s-load-xop.h191
-rw-r--r--Modules/_blake2/impl/blake2s-ref.c411
-rw-r--r--Modules/_blake2/impl/blake2s-round.h90
-rw-r--r--Modules/_blake2/impl/blake2s.c435
-rw-r--r--Modules/_bz2module.c3
-rw-r--r--Modules/_codecsmodule.c303
-rw-r--r--Modules/_collectionsmodule.c651
-rw-r--r--Modules/_csv.c24
-rw-r--r--Modules/_ctypes/_ctypes.c48
-rw-r--r--Modules/_ctypes/_ctypes_test.c43
-rw-r--r--Modules/_ctypes/callbacks.c2
-rw-r--r--Modules/_ctypes/callproc.c28
-rw-r--r--Modules/_ctypes/cfield.c76
-rw-r--r--Modules/_ctypes/ctypes.h10
-rw-r--r--Modules/_ctypes/libffi/src/dlmalloc.c2
-rw-r--r--Modules/_ctypes/libffi_arm_wince/debug.c59
-rw-r--r--Modules/_ctypes/libffi_arm_wince/ffi.c310
-rw-r--r--Modules/_ctypes/libffi_arm_wince/ffi.h317
-rw-r--r--Modules/_ctypes/libffi_arm_wince/ffi_common.h111
-rw-r--r--Modules/_ctypes/libffi_arm_wince/fficonfig.h152
-rw-r--r--Modules/_ctypes/libffi_arm_wince/ffitarget.h49
-rw-r--r--Modules/_ctypes/libffi_arm_wince/prep_cif.c175
-rw-r--r--Modules/_ctypes/libffi_arm_wince/sysv.asm228
-rw-r--r--Modules/_ctypes/stgdict.c2
-rw-r--r--Modules/_curses_panel.c4
-rw-r--r--Modules/_cursesmodule.c2
-rw-r--r--Modules/_datetimemodule.c1075
-rw-r--r--Modules/_dbmmodule.c8
-rw-r--r--Modules/_decimal/_decimal.c113
-rw-r--r--Modules/_decimal/docstrings.h9
-rw-r--r--Modules/_decimal/libmpdec/basearith.c1
-rw-r--r--Modules/_decimal/libmpdec/io.c1
-rw-r--r--Modules/_decimal/libmpdec/memory.c7
-rw-r--r--Modules/_decimal/libmpdec/mpalloc.h (renamed from Modules/_decimal/libmpdec/memory.h)4
-rw-r--r--Modules/_decimal/libmpdec/mpdecimal.c2
-rw-r--r--Modules/_decimal/libmpdec/mpdecimal.h12
-rw-r--r--Modules/_decimal/libmpdec/vccompat.h5
-rw-r--r--Modules/_decimal/tests/deccheck.py6
-rw-r--r--Modules/_elementtree.c585
-rw-r--r--Modules/_functoolsmodule.c60
-rw-r--r--Modules/_gdbmmodule.c2
-rw-r--r--Modules/_hashopenssl.c129
-rw-r--r--Modules/_heapqmodule.c10
-rw-r--r--Modules/_io/_iomodule.c83
-rw-r--r--Modules/_io/_iomodule.h29
-rw-r--r--Modules/_io/bufferedio.c2
-rw-r--r--Modules/_io/bytesio.c6
-rw-r--r--Modules/_io/clinic/_iomodule.c.h14
-rw-r--r--Modules/_io/clinic/bufferedio.c.h80
-rw-r--r--Modules/_io/clinic/bytesio.c.h31
-rw-r--r--Modules/_io/clinic/fileio.c.h31
-rw-r--r--Modules/_io/clinic/iobase.c.h11
-rw-r--r--Modules/_io/clinic/stringio.c.h22
-rw-r--r--Modules/_io/clinic/textio.c.h45
-rw-r--r--Modules/_io/clinic/winconsoleio.c.h331
-rw-r--r--Modules/_io/fileio.c49
-rw-r--r--Modules/_io/iobase.c2
-rw-r--r--Modules/_io/stringio.c4
-rw-r--r--Modules/_io/textio.c34
-rw-r--r--Modules/_io/winconsoleio.c1154
-rw-r--r--Modules/_json.c4
-rw-r--r--Modules/_localemodule.c56
-rw-r--r--Modules/_lsprof.c41
-rw-r--r--Modules/_lzmamodule.c30
-rw-r--r--Modules/_multiprocessing/multiprocessing.c2
-rw-r--r--Modules/_multiprocessing/multiprocessing.h2
-rw-r--r--Modules/_operator.c18
-rw-r--r--Modules/_pickle.c412
-rw-r--r--Modules/_posixsubprocess.c5
-rw-r--r--Modules/_randommodule.c101
-rw-r--r--Modules/_scproxy.c16
-rw-r--r--Modules/_sha3/README.txt11
-rwxr-xr-xModules/_sha3/cleanup.py50
-rw-r--r--Modules/_sha3/clinic/sha3module.c.h154
-rw-r--r--Modules/_sha3/kcp/KeccakHash.c82
-rw-r--r--Modules/_sha3/kcp/KeccakHash.h114
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-64.macros2208
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-SnP-opt32.h37
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-SnP-opt64.h49
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-SnP.h7
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-inplace32BI.c1162
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-opt64-config.h3
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-opt64.c474
-rw-r--r--Modules/_sha3/kcp/KeccakP-1600-unrolling.macros185
-rw-r--r--Modules/_sha3/kcp/KeccakSponge.c92
-rw-r--r--Modules/_sha3/kcp/KeccakSponge.h172
-rw-r--r--Modules/_sha3/kcp/KeccakSponge.inc332
-rw-r--r--Modules/_sha3/kcp/PlSnP-Fallback.inc257
-rw-r--r--Modules/_sha3/kcp/SnP-Relaned.h134
-rw-r--r--Modules/_sha3/kcp/align.h35
-rw-r--r--Modules/_sha3/sha3module.c757
-rw-r--r--Modules/_sqlite/cache.c3
-rw-r--r--Modules/_sqlite/connection.c95
-rw-r--r--Modules/_sqlite/connection.h4
-rw-r--r--Modules/_sqlite/cursor.c154
-rw-r--r--Modules/_sqlite/cursor.h6
-rw-r--r--Modules/_sqlite/module.c15
-rw-r--r--Modules/_sqlite/row.c4
-rw-r--r--Modules/_sqlite/statement.c24
-rw-r--r--Modules/_sqlite/statement.h1
-rw-r--r--Modules/_sqlite/util.c21
-rw-r--r--Modules/_sre.c129
-rw-r--r--Modules/_ssl.c601
-rw-r--r--Modules/_struct.c198
-rw-r--r--Modules/_testbuffer.c2
-rw-r--r--Modules/_testcapimodule.c314
-rw-r--r--Modules/_testmultiphase.c2
-rw-r--r--Modules/_tkinter.c77
-rw-r--r--Modules/_tracemalloc.c586
-rw-r--r--Modules/_winapi.c16
-rw-r--r--Modules/addrinfo.h12
-rw-r--r--Modules/arraymodule.c136
-rw-r--r--Modules/audioop.c76
-rw-r--r--Modules/binascii.c287
-rw-r--r--Modules/cjkcodecs/cjkcodecs.h2
-rw-r--r--Modules/cjkcodecs/clinic/multibytecodec.c.h65
-rw-r--r--Modules/cjkcodecs/multibytecodec.c4
-rw-r--r--Modules/clinic/_asynciomodule.c.h520
-rw-r--r--Modules/clinic/_bz2module.c.h35
-rw-r--r--Modules/clinic/_codecsmodule.c.h334
-rw-r--r--Modules/clinic/_cryptmodule.c.h5
-rw-r--r--Modules/clinic/_cursesmodule.c.h14
-rw-r--r--Modules/clinic/_datetimemodule.c.h14
-rw-r--r--Modules/clinic/_dbmmodule.c.h11
-rw-r--r--Modules/clinic/_elementtree.c.h120
-rw-r--r--Modules/clinic/_gdbmmodule.c.h14
-rw-r--r--Modules/clinic/_hashopenssl.c.h60
-rw-r--r--Modules/clinic/_lzmamodule.c.h43
-rw-r--r--Modules/clinic/_opcode.c.h8
-rw-r--r--Modules/clinic/_pickle.c.h75
-rw-r--r--Modules/clinic/_sre.c.h206
-rw-r--r--Modules/clinic/_ssl.c.h198
-rw-r--r--Modules/clinic/_tkinter.c.h53
-rw-r--r--Modules/clinic/_weakref.c.h8
-rw-r--r--Modules/clinic/_winapi.c.h143
-rw-r--r--Modules/clinic/arraymodule.c.h29
-rw-r--r--Modules/clinic/audioop.c.h167
-rw-r--r--Modules/clinic/binascii.c.h118
-rw-r--r--Modules/clinic/cmathmodule.c.h83
-rw-r--r--Modules/clinic/fcntlmodule.c.h14
-rw-r--r--Modules/clinic/grpmodule.c.h26
-rw-r--r--Modules/clinic/md5module.c.h14
-rw-r--r--Modules/clinic/posixmodule.c.h1216
-rw-r--r--Modules/clinic/pwdmodule.c.h5
-rw-r--r--Modules/clinic/pyexpat.c.h32
-rw-r--r--Modules/clinic/sha1module.c.h14
-rw-r--r--Modules/clinic/sha256module.c.h26
-rw-r--r--Modules/clinic/sha512module.c.h74
-rw-r--r--Modules/clinic/signalmodule.c.h32
-rw-r--r--Modules/clinic/spwdmodule.c.h5
-rw-r--r--Modules/clinic/unicodedata.c.h44
-rw-r--r--Modules/clinic/zlibmodule.c.h115
-rw-r--r--Modules/cmathmodule.c55
-rw-r--r--Modules/faulthandler.c316
-rw-r--r--Modules/gcmodule.c20
-rw-r--r--Modules/getaddrinfo.c4
-rw-r--r--Modules/getpath.c4
-rw-r--r--Modules/grpmodule.c21
-rw-r--r--Modules/hashlib.h19
-rw-r--r--Modules/hashtable.c196
-rw-r--r--Modules/hashtable.h181
-rw-r--r--Modules/itertoolsmodule.c387
-rw-r--r--Modules/main.c59
-rw-r--r--Modules/mathmodule.c5
-rw-r--r--Modules/md5module.c2
-rw-r--r--Modules/mmapmodule.c19
-rw-r--r--Modules/nismodule.c6
-rw-r--r--Modules/ossaudiodev.c6
-rw-r--r--Modules/overlapped.c10
-rw-r--r--Modules/parsermodule.c2559
-rw-r--r--Modules/posixmodule.c1856
-rw-r--r--Modules/pwdmodule.c8
-rw-r--r--Modules/pyexpat.c38
-rw-r--r--Modules/readline.c27
-rw-r--r--Modules/resource.c10
-rw-r--r--Modules/selectmodule.c42
-rw-r--r--Modules/sha1module.c2
-rw-r--r--Modules/sha512module.c172
-rw-r--r--Modules/signalmodule.c226
-rw-r--r--Modules/socketmodule.c725
-rw-r--r--Modules/spwdmodule.c5
-rw-r--r--Modules/sre_lib.h61
-rw-r--r--Modules/symtablemodule.c1
-rw-r--r--Modules/syslogmodule.c4
-rw-r--r--Modules/timemodule.c180
-rw-r--r--Modules/unicodedata.c7
-rw-r--r--Modules/unicodedata_db.h3239
-rw-r--r--Modules/unicodename_db.h45498
-rw-r--r--Modules/winreparse.h17
-rw-r--r--Modules/xxlimited.c2
-rw-r--r--Modules/xxmodule.c2
-rw-r--r--Modules/zipimport.c6
-rw-r--r--Modules/zlibmodule.c30
-rw-r--r--Objects/abstract.c653
-rw-r--r--Objects/bytearrayobject.c1034
-rw-r--r--Objects/bytes_methods.c431
-rw-r--r--Objects/bytesobject.c2326
-rw-r--r--Objects/classobject.c29
-rw-r--r--Objects/clinic/bytearrayobject.c.h134
-rw-r--r--Objects/clinic/bytesobject.c.h137
-rw-r--r--Objects/clinic/dictobject.c.h5
-rw-r--r--Objects/clinic/unicodeobject.c.h5
-rw-r--r--Objects/codeobject.c116
-rw-r--r--Objects/complexobject.c63
-rw-r--r--Objects/descrobject.c38
-rw-r--r--Objects/dict-common.h60
-rw-r--r--Objects/dictobject.c1862
-rw-r--r--Objects/enumobject.c12
-rw-r--r--Objects/exceptions.c40
-rw-r--r--Objects/fileobject.c11
-rw-r--r--Objects/floatobject.c352
-rw-r--r--Objects/frameobject.c14
-rw-r--r--Objects/funcobject.c35
-rw-r--r--Objects/genobject.c1065
-rw-r--r--Objects/iterobject.c40
-rw-r--r--Objects/listobject.c66
-rw-r--r--Objects/listsort.txt2
-rw-r--r--Objects/lnotab_notes.txt47
-rw-r--r--Objects/longobject.c542
-rw-r--r--Objects/memoryobject.c100
-rw-r--r--Objects/methodobject.c152
-rw-r--r--Objects/moduleobject.c13
-rw-r--r--Objects/namespaceobject.c8
-rw-r--r--Objects/object.c85
-rw-r--r--Objects/obmalloc.c432
-rw-r--r--Objects/odictobject.c73
-rw-r--r--Objects/rangeobject.c34
-rw-r--r--Objects/setobject.c625
-rw-r--r--Objects/stringlib/codecs.h220
-rw-r--r--Objects/stringlib/ctype.h5
-rw-r--r--Objects/stringlib/fastsearch.h150
-rw-r--r--Objects/stringlib/find.h82
-rw-r--r--Objects/stringlib/find_max_char.h5
-rw-r--r--Objects/stringlib/join.h8
-rw-r--r--Objects/stringlib/localeutil.h4
-rw-r--r--Objects/stringlib/transmogrify.h615
-rw-r--r--Objects/stringlib/unicode_format.h2
-rw-r--r--Objects/structseq.c32
-rw-r--r--Objects/tupleobject.c19
-rw-r--r--Objects/typeobject.c544
-rw-r--r--Objects/unicodeobject.c2486
-rw-r--r--Objects/unicodetype_db.h1573
-rw-r--r--Objects/weakrefobject.c4
-rw-r--r--PC/_msi.c12
-rw-r--r--PC/_testconsole.c131
-rw-r--r--PC/bdist_wininst/install.c18
-rw-r--r--PC/clinic/_testconsole.c.h82
-rw-r--r--PC/clinic/msvcrtmodule.c.h67
-rw-r--r--PC/clinic/winreg.c.h135
-rw-r--r--PC/clinic/winsound.c.h51
-rw-r--r--PC/config.c4
-rw-r--r--PC/getpathp.c276
-rw-r--r--PC/icons/launcher.icnsbin0 -> 264476 bytes-rw-r--r--PC/icons/launcher.icobin0 -> 87263 bytes-rw-r--r--PC/icons/launcher.svg1
-rw-r--r--PC/icons/py.icnsbin0 -> 195977 bytes-rw-r--r--PC/icons/py.icobin0 -> 75809 bytes-rw-r--r--PC/icons/py.svg1
-rw-r--r--PC/icons/pyc.icnsbin0 -> 212125 bytes-rw-r--r--PC/icons/pyc.icobin0 -> 78396 bytes-rw-r--r--PC/icons/pyc.svg1
-rw-r--r--PC/icons/pyd.icnsbin0 -> 223199 bytes-rw-r--r--PC/icons/pyd.icobin0 -> 83351 bytes-rw-r--r--PC/icons/pyd.svg1
-rw-r--r--PC/icons/python.icnsbin0 -> 201868 bytes-rw-r--r--PC/icons/python.icobin0 -> 77671 bytes-rw-r--r--PC/icons/python.svg1
-rw-r--r--PC/icons/pythonw.icnsbin0 -> 193222 bytes-rw-r--r--PC/icons/pythonw.icobin0 -> 76102 bytes-rw-r--r--PC/icons/pythonw.svg1
-rw-r--r--PC/icons/setup.icnsbin0 -> 220699 bytes-rw-r--r--PC/icons/setup.icobin0 -> 78328 bytes-rw-r--r--PC/icons/setup.svg1
-rw-r--r--PC/launcher.c33
-rw-r--r--PC/launcher.icobin19790 -> 0 bytes-rw-r--r--PC/msvcrtmodule.c34
-rw-r--r--PC/py.icobin19790 -> 0 bytes-rw-r--r--PC/pyc.icobin19790 -> 0 bytes-rw-r--r--PC/pycon.icobin19790 -> 0 bytes-rw-r--r--PC/pyconfig.h92
-rw-r--r--PC/pylauncher.rc10
-rw-r--r--PC/python.manifest7
-rw-r--r--PC/python3.def1562
-rw-r--r--PC/python_exe.rc2
-rw-r--r--PC/pythonw_exe.rc49
-rw-r--r--PC/testpy.py4
-rw-r--r--PC/winreg.c53
-rw-r--r--PC/winsound.c74
-rw-r--r--PCbuild/_asyncio.vcxproj77
-rw-r--r--PCbuild/_asyncio.vcxproj.filters16
-rw-r--r--PCbuild/_freeze_importlib.vcxproj37
-rw-r--r--PCbuild/_lzma.vcxproj12
-rw-r--r--PCbuild/_testconsole.vcxproj83
-rw-r--r--PCbuild/_testconsole.vcxproj.filters22
-rw-r--r--PCbuild/build.bat2
-rw-r--r--PCbuild/build_pgo.bat6
-rw-r--r--PCbuild/get_externals.bat8
-rw-r--r--PCbuild/liblzma.vcxproj216
-rw-r--r--PCbuild/openssl.props2
-rw-r--r--PCbuild/pcbuild.proj14
-rw-r--r--PCbuild/pcbuild.sln20
-rw-r--r--PCbuild/prepare_ssl.bat4
-rw-r--r--PCbuild/pyproject.props13
-rw-r--r--PCbuild/python.props5
-rw-r--r--PCbuild/pythoncore.vcxproj14
-rw-r--r--PCbuild/pythoncore.vcxproj.filters28
-rw-r--r--PCbuild/pythonw.vcxproj2
-rw-r--r--PCbuild/readme.txt6
-rw-r--r--PCbuild/rt.bat5
-rw-r--r--PCbuild/sqlite3.vcxproj4
-rw-r--r--PCbuild/tcltk.props6
-rw-r--r--PCbuild/xxlimited.vcxproj2
-rw-r--r--Parser/Python.asdl13
-rw-r--r--Parser/asdl.py3
-rw-r--r--[-rwxr-xr-x]Parser/asdl_c.py16
-rw-r--r--Parser/grammar.c27
-rw-r--r--Parser/myreadline.c139
-rw-r--r--Parser/node.c2
-rw-r--r--Parser/parser.c9
-rw-r--r--Parser/parsetok.c6
-rw-r--r--Parser/pgen.c24
-rw-r--r--Parser/pgenmain.c14
-rw-r--r--Parser/tokenizer.c248
-rw-r--r--Programs/_freeze_importlib.c2
-rw-r--r--Programs/_testembed.c2
-rw-r--r--Programs/python.c9
-rw-r--r--Python/Python-ast.c394
-rw-r--r--Python/_warnings.c221
-rw-r--r--Python/asdl.c8
-rw-r--r--Python/ast.c1460
-rw-r--r--Python/bltinmodule.c163
-rw-r--r--Python/ceval.c1947
-rw-r--r--Python/ceval_gil.h4
-rw-r--r--Python/clinic/bltinmodule.c.h53
-rw-r--r--Python/clinic/import.c.h29
-rw-r--r--Python/compile.c1322
-rw-r--r--Python/condvar.h6
-rw-r--r--Python/dtoa.c125
-rw-r--r--Python/dynload_win.c8
-rw-r--r--Python/errors.c144
-rw-r--r--Python/fileutils.c189
-rw-r--r--Python/formatter_unicode.c107
-rw-r--r--Python/frozen.c20
-rw-r--r--Python/frozenmain.c4
-rw-r--r--Python/future.c7
-rw-r--r--Python/getargs.c867
-rw-r--r--Python/graminit.c1924
-rw-r--r--Python/import.c423
-rw-r--r--Python/importdl.c4
-rw-r--r--Python/importlib.h3688
-rw-r--r--Python/importlib_external.h4724
-rwxr-xr-xPython/makeopcodetargets.py48
-rw-r--r--Python/marshal.c122
-rw-r--r--Python/modsupport.c25
-rw-r--r--Python/mystrtoul.c6
-rw-r--r--Python/opcode_targets.h18
-rw-r--r--Python/peephole.c661
-rw-r--r--Python/pyhash.c53
-rw-r--r--Python/pylifecycle.c176
-rw-r--r--Python/pystate.c50
-rw-r--r--Python/pystrtod.c75
-rw-r--r--Python/pythonrun.c44
-rw-r--r--Python/pytime.c348
-rw-r--r--Python/random.c340
-rw-r--r--Python/structmember.c22
-rw-r--r--Python/symtable.c155
-rw-r--r--Python/sysmodule.c297
-rw-r--r--Python/thread_nt.h24
-rw-r--r--Python/traceback.c225
-rw-r--r--Python/wordcode_helpers.h41
-rw-r--r--README53
-rw-r--r--Tools/buildbot/build-amd64.bat5
-rw-r--r--Tools/buildbot/clean-amd64.bat5
-rw-r--r--Tools/buildbot/clean.bat1
-rw-r--r--Tools/buildbot/external-amd64.bat3
-rw-r--r--Tools/buildbot/external.bat3
-rw-r--r--Tools/buildbot/test-amd64.bat6
-rw-r--r--Tools/buildbot/test.bat4
-rwxr-xr-xTools/clinic/clinic.py128
-rwxr-xr-xTools/demo/ss1.py2
-rwxr-xr-xTools/freeze/freeze.py6
-rw-r--r--Tools/freeze/winmakemakefile.py6
-rwxr-xr-xTools/gdb/libpython.py81
-rw-r--r--Tools/hg/hgtouch.py1
-rwxr-xr-xTools/i18n/pygettext.py51
-rw-r--r--Tools/msi/buildrelease.bat87
-rw-r--r--Tools/msi/bundle/Default.thm7
-rw-r--r--Tools/msi/bundle/Default.wxl3
-rw-r--r--Tools/msi/bundle/bootstrap/PythonBootstrapperApplication.cpp155
-rw-r--r--Tools/msi/bundle/bundle.icobin19790 -> 0 bytes-rw-r--r--Tools/msi/bundle/bundle.wxs2
-rw-r--r--Tools/msi/common.wxs12
-rw-r--r--Tools/msi/common_en-US.wxl_template1
-rw-r--r--Tools/msi/exe/exe.wixproj1
-rw-r--r--Tools/msi/exe/exe.wxs2
-rw-r--r--Tools/msi/exe/exe_d.wixproj1
-rw-r--r--Tools/msi/exe/exe_en-US.wxl_template1
-rw-r--r--Tools/msi/exe/exe_files.wxs10
-rw-r--r--Tools/msi/exe/exe_pdb.wixproj1
-rw-r--r--Tools/msi/exe/exe_reg.wxs25
-rw-r--r--Tools/msi/launcher/launcher.wixproj2
-rw-r--r--Tools/msi/launcher/launcher.wxs16
-rw-r--r--Tools/msi/launcher/launcher_en-US.wxl1
-rw-r--r--Tools/msi/launcher/launcher_reg.wxs8
-rw-r--r--Tools/msi/lib/lib.wixproj1
-rw-r--r--Tools/msi/lib/lib.wxs1
-rw-r--r--Tools/msi/lib/lib_files.wxs15
-rw-r--r--Tools/msi/make_zip.proj2
-rw-r--r--Tools/msi/make_zip.py54
-rw-r--r--Tools/msi/msi.props11
-rw-r--r--Tools/msi/msi.targets33
-rw-r--r--Tools/msi/test/test_files.wxs77
-rw-r--r--Tools/msi/tools/tools.wixproj1
-rw-r--r--Tools/msi/tools/tools.wxs1
-rw-r--r--Tools/msi/tools/tools_files.wxs7
-rw-r--r--Tools/nuget/make_pkg.proj2
-rw-r--r--Tools/parser/unparse.py86
-rw-r--r--Tools/pybench/CommandLine.py4
-rw-r--r--Tools/pybench/With.py1
-rw-r--r--Tools/pynche/ColorDB.py6
-rwxr-xr-xTools/scripts/combinerefs.py4
-rwxr-xr-xTools/scripts/diff.py2
-rwxr-xr-xTools/scripts/fixdiv.py4
-rw-r--r--Tools/scripts/generate_opcode_h.py2
-rwxr-xr-xTools/scripts/h2py.py8
-rwxr-xr-xTools/scripts/highlight.py16
-rwxr-xr-xTools/scripts/idle32
-rwxr-xr-xTools/scripts/mailerdaemon.py2
-rwxr-xr-xTools/scripts/nm2def.py4
-rwxr-xr-xTools/scripts/parseentities.py4
-rwxr-xr-xTools/scripts/pathfix.py2
-rwxr-xr-xTools/scripts/ptags.py2
-rwxr-xr-xTools/scripts/pyvenv6
-rwxr-xr-xTools/scripts/svneol.py2
-rwxr-xr-xTools/scripts/texi2html.py10
-rw-r--r--Tools/ssl/test_multiple_versions.py6
-rw-r--r--Tools/tz/zdump.py81
-rw-r--r--Tools/unicode/gencodec.py10
-rw-r--r--Tools/unicode/makeunicodedata.py11
-rw-r--r--aclocal.m44
-rwxr-xr-xconfig.guess174
-rwxr-xr-xconfig.sub75
-rwxr-xr-xconfigure1309
-rw-r--r--configure.ac459
-rw-r--r--pyconfig.h.in109
-rw-r--r--setup.py71
1507 files changed, 135295 insertions, 81416 deletions
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..4ce80d8
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,9 @@
+## CPython Mirror
+
+https://github.com/python/cpython is a cpython mirror repository. Pull requests
+are not accepted on this repo and will be automatically closed.
+
+### Submit patches at https://bugs.python.org
+
+For additional information about contributing to CPython, see the
+[developer's guide](https://docs.python.org/devguide/#contributing).
diff --git a/.gitignore b/.gitignore
index d267d15..ed4ebfb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,8 +21,6 @@ Doc/venv/
Lib/distutils/command/*.pdb
Lib/lib2to3/*.pickle
Lib/test/data/*
-Lib/_sysconfigdata.py
-Lib/plat-mac/errors.rsrc.df.rsrc
Makefile
Makefile.pre
Misc/python.pc
@@ -73,6 +71,7 @@ db_home
ipch/
libpython*.a
libpython*.so*
+libpython*.dylib
platform
pybuilddir.txt
pyconfig.h
diff --git a/.hgignore b/.hgignore
index cf9453a..92896b7 100644
--- a/.hgignore
+++ b/.hgignore
@@ -2,6 +2,7 @@
.purify
.svn/
^.idea/
+^.vscode/
.DS_Store
Makefile$
Makefile.pre$
@@ -25,7 +26,6 @@ python-config$
python-config.py$
reflog.txt$
tags$
-Lib/plat-mac/errors.rsrc.df.rsrc
Misc/python.pc
Misc/python-config.sh$
Modules/Setup$
@@ -43,6 +43,7 @@ Parser/pgen$
syntax: glob
libpython*.a
libpython*.so*
+libpython*.dylib
*.swp
*.o
*.pyc
@@ -54,6 +55,7 @@ libpython*.so*
*.profclang?
*.profraw
*.dyn
+Include/pydtrace_probes.h
Lib/distutils/command/*.pdb
Lib/lib2to3/*.pickle
Lib/test/data/*
diff --git a/.hgtags b/.hgtags
index ed4fc92..8df6239 100644
--- a/.hgtags
+++ b/.hgtags
@@ -148,6 +148,7 @@ b4cbecbc0781e89a309d03b60a1f75f8499250e6 v3.4.3
737efcadf5a678b184e0fa431aae11276bf06648 v3.4.4
3631bb4a2490292ebf81d3e947ae36da145da564 v3.4.5rc1
619b61e505d0e2ccc8516b366e4ddd1971b46a6f v3.4.5
+3631bb4a2490292ebf81d3e947ae36da145da564 v3.4.5rc1
5d4b6a57d5fd7564bf73f3db0e46fe5eeb00bcd8 v3.5.0a1
0337bd7ebcb6559d69679bc7025059ad1ce4f432 v3.5.0a2
82656e28b5e5c4ae48d8dd8b5f0d7968908a82b6 v3.5.0a3
@@ -165,3 +166,14 @@ cc15d736d860303b9da90d43cd32db39bab048df v3.5.0rc2
37a07cee5969e6d3672583187a73cf636ff28e1b v3.5.1
68feec6488b26327a85a634605dd28eca4daa5f1 v3.5.2rc1
4def2a2901a5618ea45bcc8f2a1411ef33af18ad v3.5.2
+5896da372fb044e38595fb74495de1e1e7c8fb3c v3.6.0a1
+37889342355223e2fc1438de3dc7ffcd625c60f7 v3.6.0a2
+f3edf13dc339b8942ae6b309771ab197dd8ce6fa v3.6.0a3
+017cf260936b444788c9b671d195b7bfd83dbd25 v3.6.0a4
+5b0ca4ed5e2f0669d76ece7ef975c544580f12b4 v3.6.0b1
+b9fadc7d1c3f9c3c77f32f35afbe1a1cc38070e6 v3.6.0b2
+8345e066c0ed713c3e510cbc8fafc1c38d6d306b v3.6.0b3
+18496abdb3d5c2730a659b747a89261b2219fecf v3.6.0b4
+29a273eee9a523ee178f6a66c4ac9d317c8fc84f v3.6.0rc1
+800a67f7806de45a7abd5273359e704bf147c079 v3.6.0rc2
+41df79263a11f2429d1dd0cfe12553de3dcb5508 v3.6.0
diff --git a/Doc/Makefile b/Doc/Makefile
index 10c3288..91f937f 100644
--- a/Doc/Makefile
+++ b/Doc/Makefile
@@ -153,7 +153,7 @@ dist:
cp -pPR build/epub/Python.epub dist/python-$(DISTVERSION)-docs.epub
check:
- $(PYTHON) tools/rstlint.py -i tools
+ $(PYTHON) tools/rstlint.py -i tools -i venv
serve:
../Tools/scripts/serve.py build/html
diff --git a/Doc/c-api/arg.rst b/Doc/c-api/arg.rst
index 1123972..e8e7e0d 100644
--- a/Doc/c-api/arg.rst
+++ b/Doc/c-api/arg.rst
@@ -223,8 +223,7 @@ which disallows mutable objects such as :class:`bytearray`.
:c:func:`PyArg_ParseTuple` will use this location as the buffer and interpret the
initial value of *\*buffer_length* as the buffer size. It will then copy the
encoded data into the buffer and NUL-terminate it. If the buffer is not large
- enough, a :exc:`TypeError` will be set.
- Note: starting from Python 3.6 a :exc:`ValueError` will be set.
+ enough, a :exc:`ValueError` will be set.
In both cases, *\*buffer_length* is set to the length of the encoded data
without the trailing NUL byte.
@@ -266,15 +265,12 @@ Numbers
Convert a Python integer to a C :c:type:`unsigned long` without
overflow checking.
-``L`` (:class:`int`) [PY_LONG_LONG]
- Convert a Python integer to a C :c:type:`long long`. This format is only
- available on platforms that support :c:type:`long long` (or :c:type:`_int64` on
- Windows).
+``L`` (:class:`int`) [long long]
+ Convert a Python integer to a C :c:type:`long long`.
-``K`` (:class:`int`) [unsigned PY_LONG_LONG]
+``K`` (:class:`int`) [unsigned long long]
Convert a Python integer to a C :c:type:`unsigned long long`
- without overflow checking. This format is only available on platforms that
- support :c:type:`unsigned long long` (or :c:type:`unsigned _int64` on Windows).
+ without overflow checking.
``n`` (:class:`int`) [Py_ssize_t]
Convert a Python integer to a C :c:type:`Py_ssize_t`.
@@ -424,8 +420,15 @@ API Functions
.. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
Parse the parameters of a function that takes both positional and keyword
- parameters into local variables. Returns true on success; on failure, it
- returns false and raises the appropriate exception.
+ parameters into local variables. The *keywords* argument is a
+ *NULL*-terminated array of keyword parameter names. Empty names denote
+ :ref:`positional-only parameters <positional-only_parameter>`.
+ Returns true on success; on failure, it returns false and raises the
+ appropriate exception.
+
+ .. versionchanged:: 3.6
+ Added support for :ref:`positional-only parameters
+ <positional-only_parameter>`.
.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
@@ -588,15 +591,11 @@ Building values
``k`` (:class:`int`) [unsigned long]
Convert a C :c:type:`unsigned long` to a Python integer object.
- ``L`` (:class:`int`) [PY_LONG_LONG]
- Convert a C :c:type:`long long` to a Python integer object. Only available
- on platforms that support :c:type:`long long` (or :c:type:`_int64` on
- Windows).
+ ``L`` (:class:`int`) [long long]
+ Convert a C :c:type:`long long` to a Python integer object.
- ``K`` (:class:`int`) [unsigned PY_LONG_LONG]
- Convert a C :c:type:`unsigned long long` to a Python integer object. Only
- available on platforms that support :c:type:`unsigned long long` (or
- :c:type:`unsigned _int64` on Windows).
+ ``K`` (:class:`int`) [unsigned long long]
+ Convert a C :c:type:`unsigned long long` to a Python integer object.
``n`` (:class:`int`) [Py_ssize_t]
Convert a C :c:type:`Py_ssize_t` to a Python integer.
diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst
index c389888..037b85c 100644
--- a/Doc/c-api/exceptions.rst
+++ b/Doc/c-api/exceptions.rst
@@ -306,6 +306,13 @@ an error value).
:mod:`warnings` module and the :option:`-W` option in the command line
documentation. There is no C API for warning control.
+.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *msg, PyObject *name, PyObject *path)
+
+ Much like :c:func:`PyErr_SetImportError` but this function allows for
+ specifying a subclass of :exc:`ImportError` to raise.
+
+ .. versionadded:: 3.6
+
.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
@@ -334,6 +341,14 @@ an error value).
.. versionadded:: 3.2
+.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
+
+ Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
+ :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
+
+ .. versionadded:: 3.6
+
+
Querying the error indicator
============================
@@ -774,6 +789,8 @@ the variables:
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ImportError` | :exc:`ImportError` | |
+-----------------------------------------+---------------------------------+----------+
+| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | |
++-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_IndexError` | :exc:`IndexError` | |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | |
diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
index 70b98ae..2965bc9 100644
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -25,7 +25,7 @@ Initializing and finalizing the interpreter
triple: module; search; path
single: PySys_SetArgv()
single: PySys_SetArgvEx()
- single: Py_Finalize()
+ single: Py_FinalizeEx()
Initialize the Python interpreter. In an application embedding Python, this
should be called before using any other Python/C API functions; with the
@@ -34,7 +34,7 @@ Initializing and finalizing the interpreter
modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes
the module search path (``sys.path``). It does not set ``sys.argv``; use
:c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time
- (without calling :c:func:`Py_Finalize` first). There is no return value; it is a
+ (without calling :c:func:`Py_FinalizeEx` first). There is no return value; it is a
fatal error if the initialization fails.
.. note::
@@ -52,19 +52,20 @@ Initializing and finalizing the interpreter
.. c:function:: int Py_IsInitialized()
Return true (nonzero) when the Python interpreter has been initialized, false
- (zero) if not. After :c:func:`Py_Finalize` is called, this returns false until
+ (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
:c:func:`Py_Initialize` is called again.
-.. c:function:: void Py_Finalize()
+.. c:function:: int Py_FinalizeEx()
Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
Python/C API functions, and destroy all sub-interpreters (see
:c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory
allocated by the Python interpreter. This is a no-op when called for a second
- time (without calling :c:func:`Py_Initialize` again first). There is no return
- value; errors during finalization are ignored.
+ time (without calling :c:func:`Py_Initialize` again first). Normally the
+ return value is 0. If there were errors during finalization
+ (flushing buffered data), -1 is returned.
This function is provided for a number of reasons. An embedding application
might want to restart Python without having to restart the application itself.
@@ -83,7 +84,15 @@ Initializing and finalizing the interpreter
freed. Some memory allocated by extension modules may not be freed. Some
extensions may not work properly if their initialization routine is called more
than once; this can happen if an application calls :c:func:`Py_Initialize` and
- :c:func:`Py_Finalize` more than once.
+ :c:func:`Py_FinalizeEx` more than once.
+
+ .. versionadded:: 3.6
+
+
+.. c:function:: void Py_Finalize()
+
+ This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
+ disregards the return value.
Process-wide parameters
@@ -111,7 +120,7 @@ Process-wide parameters
Note that :data:`sys.stderr` always uses the "backslashreplace" error
handler, regardless of this (or any other) setting.
- If :c:func:`Py_Finalize` is called, this function will need to be called
+ If :c:func:`Py_FinalizeEx` is called, this function will need to be called
again in order to affect subsequent calls to :c:func:`Py_Initialize`.
Returns ``0`` if successful, a nonzero value on error (e.g. calling after the
@@ -922,7 +931,7 @@ using the following functions:
entry.)
.. index::
- single: Py_Finalize()
+ single: Py_FinalizeEx()
single: Py_Initialize()
Extension modules are shared between (sub-)interpreters as follows: the first
@@ -932,7 +941,7 @@ using the following functions:
and filled with the contents of this copy; the extension's ``init`` function is
not called. Note that this is different from what happens when an extension is
imported after the interpreter has been completely re-initialized by calling
- :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's
+ :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that case, the extension's
``initmodule`` function *is* called again.
.. index:: single: close() (in module os)
@@ -940,14 +949,14 @@ using the following functions:
.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
- .. index:: single: Py_Finalize()
+ .. index:: single: Py_FinalizeEx()
Destroy the (sub-)interpreter represented by the given thread state. The given
thread state must be the current thread state. See the discussion of thread
states below. When the call returns, the current thread state is *NULL*. All
thread states associated with this interpreter are destroyed. (The global
interpreter lock must be held before calling this function and is still held
- when it returns.) :c:func:`Py_Finalize` will destroy all sub-interpreters that
+ when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
haven't been explicitly destroyed at that point.
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index bc3a752..74681d2 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -64,9 +64,10 @@ The header files are typically installed with Python. On Unix, these are
located in the directories :file:`{prefix}/include/pythonversion/` and
:file:`{exec_prefix}/include/pythonversion/`, where :envvar:`prefix` and
:envvar:`exec_prefix` are defined by the corresponding parameters to Python's
-:program:`configure` script and *version* is ``sys.version[:3]``. On Windows,
-the headers are installed in :file:`{prefix}/include`, where :envvar:`prefix` is
-the installation directory specified to the installer.
+:program:`configure` script and *version* is
+``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed
+in :file:`{prefix}/include`, where :envvar:`prefix` is the installation
+directory specified to the installer.
To include the headers, place both directories (if different) on your compiler's
search path for includes. Do *not* place the parent directories on the search
@@ -578,9 +579,9 @@ Sometimes, it is desirable to "uninitialize" Python. For instance, the
application may want to start over (make another call to
:c:func:`Py_Initialize`) or the application is simply done with its use of
Python and wants to free memory allocated by Python. This can be accomplished
-by calling :c:func:`Py_Finalize`. The function :c:func:`Py_IsInitialized` returns
+by calling :c:func:`Py_FinalizeEx`. The function :c:func:`Py_IsInitialized` returns
true if Python is currently in the initialized state. More information about
-these functions is given in a later chapter. Notice that :c:func:`Py_Finalize`
+these functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx`
does *not* free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.
diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst
index 68f6a8e..f592cb6 100644
--- a/Doc/c-api/long.rst
+++ b/Doc/c-api/long.rst
@@ -62,13 +62,13 @@ All integers are implemented as "long" integer objects of arbitrary size.
*NULL* on failure.
-.. c:function:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v)
+.. c:function:: PyObject* PyLong_FromLongLong(long long v)
Return a new :c:type:`PyLongObject` object from a C :c:type:`long long`, or *NULL*
on failure.
-.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v)
+.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned long long v)
Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long long`,
or *NULL* on failure.
@@ -148,7 +148,7 @@ All integers are implemented as "long" integer objects of arbitrary size.
occurs set *\*overflow* to ``0`` and return ``-1`` as usual.
-.. c:function:: PY_LONG_LONG PyLong_AsLongLong(PyObject *obj)
+.. c:function:: long long PyLong_AsLongLong(PyObject *obj)
.. index::
single: OverflowError (built-in exception)
@@ -161,7 +161,7 @@ All integers are implemented as "long" integer objects of arbitrary size.
:c:type:`long`.
-.. c:function:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
+.. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
Return a C :c:type:`long long` representation of *obj*. If *obj* is not an
instance of :c:type:`PyLongObject`, first call its :meth:`__int__` method
@@ -210,16 +210,16 @@ All integers are implemented as "long" integer objects of arbitrary size.
:c:type:`size_t`.
-.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong)
+.. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
.. index::
single: OverflowError (built-in exception)
- Return a C :c:type:`unsigned PY_LONG_LONG` representation of *pylong*.
- *pylong* must be an instance of :c:type:`PyLongObject`.
+ Return a C :c:type:`unsigned long long` representation of *pylong*. *pylong*
+ must be an instance of :c:type:`PyLongObject`.
Raise :exc:`OverflowError` if the value of *pylong* is out of range for an
- :c:type:`unsigned PY_LONG_LONG`.
+ :c:type:`unsigned long long`.
.. versionchanged:: 3.1
A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`.
@@ -235,7 +235,7 @@ All integers are implemented as "long" integer objects of arbitrary size.
return the reduction of that value modulo ``ULONG_MAX + 1``.
-.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *obj)
+.. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
Return a C :c:type:`unsigned long long` representation of *obj*. If *obj*
is not an instance of :c:type:`PyLongObject`, first call its :meth:`__int__`
diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst
index 290ef09..3ff5452 100644
--- a/Doc/c-api/memory.rst
+++ b/Doc/c-api/memory.rst
@@ -85,9 +85,12 @@ for the I/O buffer escapes completely the Python memory manager.
.. seealso::
+ The :envvar:`PYTHONMALLOC` environment variable can be used to configure
+ the memory allocators used by Python.
+
The :envvar:`PYTHONMALLOCSTATS` environment variable can be used to print
- memory allocation statistics every time a new object arena is created, and
- on shutdown.
+ statistics of the :ref:`pymalloc memory allocator <pymalloc>` every time a
+ new pymalloc object arena is created, and on shutdown.
Raw Memory Interface
@@ -162,15 +165,17 @@ The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap.
-The default memory block allocator uses the following functions:
-:c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`; call
-``malloc(1)`` (or ``calloc(1, 1)``) when requesting zero bytes.
+By default, these functions use :ref:`pymalloc memory allocator <pymalloc>`.
.. warning::
The :term:`GIL <global interpreter lock>` must be held when using these
functions.
+.. versionchanged:: 3.6
+
+ The default allocator is now pymalloc instead of system :c:func:`malloc`.
+
.. c:function:: void* PyMem_Malloc(size_t n)
Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the
@@ -292,15 +297,32 @@ Customize Memory Allocators
Enum used to identify an allocator domain. Domains:
- * :c:data:`PYMEM_DOMAIN_RAW`: functions :c:func:`PyMem_RawMalloc`,
- :c:func:`PyMem_RawRealloc`, :c:func:`PyMem_RawCalloc` and
- :c:func:`PyMem_RawFree`
- * :c:data:`PYMEM_DOMAIN_MEM`: functions :c:func:`PyMem_Malloc`,
- :c:func:`PyMem_Realloc`, :c:func:`PyMem_Calloc` and :c:func:`PyMem_Free`
- * :c:data:`PYMEM_DOMAIN_OBJ`: functions :c:func:`PyObject_Malloc`,
- :c:func:`PyObject_Realloc`, :c:func:`PyObject_Calloc` and
- :c:func:`PyObject_Free`
+ .. c:var:: PYMEM_DOMAIN_RAW
+
+ Functions:
+
+ * :c:func:`PyMem_RawMalloc`
+ * :c:func:`PyMem_RawRealloc`
+ * :c:func:`PyMem_RawCalloc`
+ * :c:func:`PyMem_RawFree`
+
+ .. c:var:: PYMEM_DOMAIN_MEM
+
+ Functions:
+
+ * :c:func:`PyMem_Malloc`,
+ * :c:func:`PyMem_Realloc`
+ * :c:func:`PyMem_Calloc`
+ * :c:func:`PyMem_Free`
+ .. c:var:: PYMEM_DOMAIN_OBJ
+
+ Functions:
+
+ * :c:func:`PyObject_Malloc`
+ * :c:func:`PyObject_Realloc`
+ * :c:func:`PyObject_Calloc`
+ * :c:func:`PyObject_Free`
.. c:function:: void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
@@ -325,43 +347,62 @@ Customize Memory Allocators
.. c:function:: void PyMem_SetupDebugHooks(void)
- Setup hooks to detect bugs in the following Python memory allocator
- functions:
-
- - :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc`,
- :c:func:`PyMem_RawCalloc`, :c:func:`PyMem_RawFree`
- - :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc`, :c:func:`PyMem_Calloc`,
- :c:func:`PyMem_Free`
- - :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`,
- :c:func:`PyObject_Calloc`, :c:func:`PyObject_Free`
+ Setup hooks to detect bugs in the Python memory allocator functions.
Newly allocated memory is filled with the byte ``0xCB``, freed memory is
- filled with the byte ``0xDB``. Additional checks:
+ filled with the byte ``0xDB``.
- - detect API violations, ex: :c:func:`PyObject_Free` called on a buffer
+ Runtime checks:
+
+ - Detect API violations, ex: :c:func:`PyObject_Free` called on a buffer
allocated by :c:func:`PyMem_Malloc`
- - detect write before the start of the buffer (buffer underflow)
- - detect write after the end of the buffer (buffer overflow)
+ - Detect write before the start of the buffer (buffer underflow)
+ - Detect write after the end of the buffer (buffer overflow)
+ - Check that the :term:`GIL <global interpreter lock>` is held when
+ allocator functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex:
+ :c:func:`PyObject_Malloc`) and :c:data:`PYMEM_DOMAIN_MEM` (ex:
+ :c:func:`PyMem_Malloc`) domains are called
+
+ On error, the debug hooks use the :mod:`tracemalloc` module to get the
+ traceback where a memory block was allocated. The traceback is only
+ displayed if :mod:`tracemalloc` is tracing Python memory allocations and the
+ memory block was traced.
- The function does nothing if Python is not compiled is debug mode.
+ These hooks are installed by default if Python is compiled in debug
+ mode. The :envvar:`PYTHONMALLOC` environment variable can be used to install
+ debug hooks on a Python compiled in release mode.
+ .. versionchanged:: 3.6
+ This function now also works on Python compiled in release mode.
+ On error, the debug hooks now use :mod:`tracemalloc` to get the traceback
+ where a memory block was allocated. The debug hooks now also check
+ if the GIL is held when functions of :c:data:`PYMEM_DOMAIN_OBJ` and
+ :c:data:`PYMEM_DOMAIN_MEM` domains are called.
-Customize PyObject Arena Allocator
-==================================
-Python has a *pymalloc* allocator for allocations smaller than 512 bytes. This
-allocator is optimized for small objects with a short lifetime. It uses memory
-mappings called "arenas" with a fixed size of 256 KB. It falls back to
-:c:func:`PyMem_RawMalloc` and :c:func:`PyMem_RawRealloc` for allocations larger
-than 512 bytes. *pymalloc* is the default allocator used by
-:c:func:`PyObject_Malloc`.
+.. _pymalloc:
-The default arena allocator uses the following functions:
+The pymalloc allocator
+======================
+
+Python has a *pymalloc* allocator optimized for small objects (smaller or equal
+to 512 bytes) with a short lifetime. It uses memory mappings called "arenas"
+with a fixed size of 256 KB. It falls back to :c:func:`PyMem_RawMalloc` and
+:c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes.
+
+*pymalloc* is the default allocator of the :c:data:`PYMEM_DOMAIN_MEM` (ex:
+:c:func:`PyObject_Malloc`) and :c:data:`PYMEM_DOMAIN_OBJ` (ex:
+:c:func:`PyObject_Malloc`) domains.
+
+The arena allocator uses the following functions:
* :c:func:`VirtualAlloc` and :c:func:`VirtualFree` on Windows,
* :c:func:`mmap` and :c:func:`munmap` if available,
* :c:func:`malloc` and :c:func:`free` otherwise.
+Customize pymalloc Arena Allocator
+----------------------------------
+
.. versionadded:: 3.4
.. c:type:: PyObjectArenaAllocator
diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst
index 3e8a90c..837ac7d 100644
--- a/Doc/c-api/structures.rst
+++ b/Doc/c-api/structures.rst
@@ -150,8 +150,9 @@ specific C type of the *self* object.
The :attr:`ml_flags` field is a bitfield which can include the following flags.
The individual flags indicate either a calling convention or a binding
convention. Of the calling convention flags, only :const:`METH_VARARGS` and
-:const:`METH_KEYWORDS` can be combined. Any of the calling convention flags
-can be combined with a binding flag.
+:const:`METH_KEYWORDS` can be combined (but note that :const:`METH_KEYWORDS`
+alone is equivalent to ``METH_VARARGS | METH_KEYWORDS``). Any of the calling
+convention flags can be combined with a binding flag.
.. data:: METH_VARARGS
diff --git a/Doc/c-api/sys.rst b/Doc/c-api/sys.rst
index 3d83b27..035cdc1 100644
--- a/Doc/c-api/sys.rst
+++ b/Doc/c-api/sys.rst
@@ -5,6 +5,17 @@
Operating System Utilities
==========================
+.. c:function:: PyObject* PyOS_FSPath(PyObject *path)
+
+ Return the file system representation for *path*. If the object is a
+ :class:`str` or :class:`bytes` object, then its reference count is
+ incremented. If the object implements the :class:`os.PathLike` interface,
+ then :meth:`~os.PathLike.__fspath__` is returned as long as it is a
+ :class:`str` or :class:`bytes` object. Otherwise :exc:`TypeError` is raised
+ and ``NULL`` is returned.
+
+ .. versionadded:: 3.6
+
.. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename)
@@ -212,20 +223,24 @@ Process Control
.. c:function:: void Py_Exit(int status)
.. index::
- single: Py_Finalize()
+ single: Py_FinalizeEx()
single: exit()
- Exit the current process. This calls :c:func:`Py_Finalize` and then calls the
- standard C library function ``exit(status)``.
+ Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the
+ standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx`
+ indicates an error, the exit status is set to 120.
+
+ .. versionchanged:: 3.6
+ Errors from finalization no longer ignored.
.. c:function:: int Py_AtExit(void (*func) ())
.. index::
- single: Py_Finalize()
+ single: Py_FinalizeEx()
single: cleanup functions
- Register a cleanup function to be called by :c:func:`Py_Finalize`. The cleanup
+ Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. The cleanup
function will be called with no arguments and should return no value. At most
32 cleanup functions can be registered. When the registration is successful,
:c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup
diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst
index 256fef3..02f7ada 100644
--- a/Doc/c-api/unicode.rst
+++ b/Doc/c-api/unicode.rst
@@ -440,7 +440,6 @@ APIs:
.. % because not all compilers support the %z width modifier -- we fake it
.. % when necessary via interpolating PY_FORMAT_SIZE_T.
.. % Similar comments apply to the %ll width modifier and
- .. % PY_FORMAT_LONG_LONG.
.. tabularcolumns:: |l|l|L|
@@ -525,11 +524,6 @@ APIs:
copied as-is to the result string, and any extra arguments discarded.
.. note::
-
- The `"%lld"` and `"%llu"` format specifiers are only available
- when :const:`HAVE_LONG_LONG` is defined.
-
- .. note::
The width formatter unit is number of characters rather than bytes.
The precision formatter unit is number of bytes for ``"%s"`` and
``"%V"`` (if the ``PyObject*`` argument is NULL), and a number of
@@ -811,38 +805,47 @@ File System Encoding
""""""""""""""""""""
To encode and decode file names and other environment strings,
-:c:data:`Py_FileSystemEncoding` should be used as the encoding, and
-``"surrogateescape"`` should be used as the error handler (:pep:`383`). To
-encode file names during argument parsing, the ``"O&"`` converter should be
-used, passing :c:func:`PyUnicode_FSConverter` as the conversion function:
+:c:data:`Py_FileSystemDefaultEncoding` should be used as the encoding, and
+:c:data:`Py_FileSystemDefaultEncodeErrors` should be used as the error handler
+(:pep:`383` and :pep:`529`). To encode file names to :class:`bytes` during
+argument parsing, the ``"O&"`` converter should be used, passing
+:c:func:`PyUnicode_FSConverter` as the conversion function:
.. c:function:: int PyUnicode_FSConverter(PyObject* obj, void* result)
- ParseTuple converter: encode :class:`str` objects to :class:`bytes` using
+ ParseTuple converter: encode :class:`str` objects -- obtained directly or
+ through the :class:`os.PathLike` interface -- to :class:`bytes` using
:c:func:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is.
*result* must be a :c:type:`PyBytesObject*` which must be released when it is
no longer used.
.. versionadded:: 3.1
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
-To decode file names during argument parsing, the ``"O&"`` converter should be
-used, passing :c:func:`PyUnicode_FSDecoder` as the conversion function:
+To decode file names to :class:`str` during argument parsing, the ``"O&"``
+converter should be used, passing :c:func:`PyUnicode_FSDecoder` as the
+conversion function:
.. c:function:: int PyUnicode_FSDecoder(PyObject* obj, void* result)
- ParseTuple converter: decode :class:`bytes` objects to :class:`str` using
- :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` objects are output
- as-is. *result* must be a :c:type:`PyUnicodeObject*` which must be released
- when it is no longer used.
+ ParseTuple converter: decode :class:`bytes` objects -- obtained either
+ directly or indirectly through the :class:`os.PathLike` interface -- to
+ :class:`str` using :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str`
+ objects are output as-is. *result* must be a :c:type:`PyUnicodeObject*` which
+ must be released when it is no longer used.
.. versionadded:: 3.2
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
Decode a string using :c:data:`Py_FileSystemDefaultEncoding` and the
- ``"surrogateescape"`` error handler, or ``"strict"`` on Windows.
+ :c:data:`Py_FileSystemDefaultEncodeErrors` error handler.
If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the
locale encoding.
@@ -856,28 +859,28 @@ used, passing :c:func:`PyUnicode_FSDecoder` as the conversion function:
The :c:func:`Py_DecodeLocale` function.
- .. versionchanged:: 3.2
- Use ``"strict"`` error handler on Windows.
+ .. versionchanged:: 3.6
+ Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler.
.. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *s)
Decode a null-terminated string using :c:data:`Py_FileSystemDefaultEncoding`
- and the ``"surrogateescape"`` error handler, or ``"strict"`` on Windows.
+ and the :c:data:`Py_FileSystemDefaultEncodeErrors` error handler.
If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the
locale encoding.
Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length.
- .. versionchanged:: 3.2
- Use ``"strict"`` error handler on Windows.
+ .. versionchanged:: 3.6
+ Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler.
.. c:function:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode)
Encode a Unicode object to :c:data:`Py_FileSystemDefaultEncoding` with the
- ``"surrogateescape"`` error handler, or ``"strict"`` on Windows, and return
+ :c:data:`Py_FileSystemDefaultEncodeErrors` error handler, and return
:class:`bytes`. Note that the resulting :class:`bytes` object may contain
null bytes.
@@ -894,6 +897,8 @@ used, passing :c:func:`PyUnicode_FSDecoder` as the conversion function:
.. versionadded:: 3.2
+ .. versionchanged:: 3.6
+ Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler.
wchar_t Support
"""""""""""""""
diff --git a/Doc/data/refcounts.dat b/Doc/data/refcounts.dat
index e388195..8b469f4 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -921,6 +921,9 @@ PyNumber_Xor:PyObject*:o2:0:
PyObject_AsFileDescriptor:int:::
PyObject_AsFileDescriptor:PyObject*:o:0:
+PyOS_FSPath:PyObject*::+1:
+PyOS_FSPath:PyObject*:path:0:
+
PyObject_Call:PyObject*::+1:
PyObject_Call:PyObject*:callable_object:0:
PyObject_Call:PyObject*:args:0:
diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst
index 64033dc..ab2f616 100644
--- a/Doc/extending/embedding.rst
+++ b/Doc/extending/embedding.rst
@@ -67,7 +67,9 @@ perform some operation on a file. ::
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
- Py_Finalize();
+ if (Py_FinalizeEx() < 0) {
+ exit(120);
+ }
PyMem_RawFree(program);
return 0;
}
@@ -76,7 +78,7 @@ The :c:func:`Py_SetProgramName` function should be called before
:c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time
libraries. Next, the Python interpreter is initialized with
:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script
-that prints the date and time. Afterwards, the :c:func:`Py_Finalize` call shuts
+that prints the date and time. Afterwards, the :c:func:`Py_FinalizeEx` call shuts
the interpreter down, followed by the end of the program. In a real program,
you may want to get the Python script from another source, perhaps a text-editor
routine, a file, or a database. Getting the Python code from a file can better
diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst
index 108df6d..1bd800b 100644
--- a/Doc/faq/design.rst
+++ b/Doc/faq/design.rst
@@ -366,33 +366,11 @@ is exactly the same type of object that a lambda expression yields) is assigned!
Can Python be compiled to machine code, C or some other language?
-----------------------------------------------------------------
-Practical answer:
-
-`Cython <http://cython.org/>`_ and `Pyrex <https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_
-compile a modified version of Python with optional annotations into C
-extensions. `Weave <https://scipy.github.io/devdocs/tutorial/weave.html>`_ makes it easy to
-intermingle Python and C code in various ways to increase performance.
-`Nuitka <http://www.nuitka.net/>`_ is an up-and-coming compiler of Python
-into C++ code, aiming to support the full Python language.
-
-Theoretical answer:
-
- .. XXX not sure what to make of this
-
-Not trivially. Python's high level data types, dynamic typing of objects and
-run-time invocation of the interpreter (using :func:`eval` or :func:`exec`)
-together mean that a naïvely "compiled" Python program would probably consist
-mostly of calls into the Python run-time system, even for seemingly simple
-operations like ``x+1``.
-
-Several projects described in the Python newsgroup or at past `Python
-conferences <https://www.python.org/community/workshops/>`_ have shown that this
-approach is feasible, although the speedups reached so far are only modest
-(e.g. 2x). Jython uses the same strategy for compiling to Java bytecode. (Jim
-Hugunin has demonstrated that in combination with whole-program analysis,
-speedups of 1000x are feasible for small demo programs. See the proceedings
-from the `1997 Python conference
-<http://legacy.python.org/workshops/1997-10/proceedings/>`_ for more information.)
+`Cython <http://cython.org/>`_ compiles a modified version of Python with
+optional annotations into C extensions. `Nuitka <http://www.nuitka.net/>`_ is
+an up-and-coming compiler of Python into C++ code, aiming to support the full
+Python language. For compiling to Java you can consider
+`VOC <https://voc.readthedocs.io>`_.
How does Python manage memory?
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index 694753e..9c5e20d 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -838,7 +838,8 @@ How do I convert a number to a string?
To convert, e.g., the number 144 to the string '144', use the built-in type
constructor :func:`str`. If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
-the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
+the :ref:`f-strings` and :ref:`formatstrings` sections,
+e.g. ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
diff --git a/Doc/glossary.rst b/Doc/glossary.rst
index 45b794f..41ee3d8 100644
--- a/Doc/glossary.rst
+++ b/Doc/glossary.rst
@@ -74,6 +74,34 @@ Glossary
:keyword:`async with` statement by defining :meth:`__aenter__` and
:meth:`__aexit__` methods. Introduced by :pep:`492`.
+ asynchronous generator
+ A function which returns an :term:`asynchronous generator iterator`. It
+ looks like a coroutine function defined with :keyword:`async def` except
+ that it contains :keyword:`yield` expressions for producing a series of
+ values usable in an :keyword:`async for` loop.
+
+ Usually refers to a asynchronous generator function, but may refer to an
+ *asynchronous generator iterator* in some contexts. In cases where the
+ intended meaning isn't clear, using the full terms avoids ambiguity.
+
+ An asynchronous generator function may contain :keyword:`await`
+ expressions as well as :keyword:`async for`, and :keyword:`async with`
+ statements.
+
+ asynchronous generator iterator
+ An object created by a :term:`asynchronous generator` function.
+
+ This is an :term:`asynchronous iterator` which when called using the
+ :meth:`__anext__` method returns an awaitable object which will execute
+ that the body of the asynchronous generator function until the
+ next :keyword:`yield` expression.
+
+ Each :keyword:`yield` temporarily suspends processing, remembering the
+ location execution state (including local variables and pending
+ try-statements). When the *asynchronous generator iterator* effectively
+ resumes with another awaitable returned by :meth:`__anext__`, it
+ picks-up where it left-off. See :pep:`492` and :pep:`525`.
+
asynchronous iterable
An object, that can be used in an :keyword:`async for` statement.
Must return an :term:`asynchronous iterator` from its
@@ -718,6 +746,8 @@ Glossary
def func(foo, bar=None): ...
+ .. _positional-only_parameter:
+
* :dfn:`positional-only`: specifies an argument that can be supplied only
by position. Python has no syntax for defining positional-only
parameters. However, some built-in functions have positional-only
@@ -776,6 +806,16 @@ Glossary
One of the default :term:`meta path finders <meta path finder>` which
searches an :term:`import path` for modules.
+ path-like object
+ An object representing a file system path. A path-like object is either
+ a :class:`str` or :class:`bytes` object representing a path, or an object
+ implementing the :class:`os.PathLike` protocol. An object that supports
+ the :class:`os.PathLike` protocol can be converted to a :class:`str` or
+ :class:`bytes` file system path by calling the :func:`os.fspath` function;
+ :func:`os.fsdecode` and :func:`os.fsencode` can be used to guarantee a
+ :class:`str` or :class:`bytes` result instead, respectively. Introduced
+ by :pep:`519`.
+
portion
A set of files in a single directory (possibly stored in a zip file)
that contribute to a namespace package, as defined in :pep:`420`.
@@ -952,13 +992,25 @@ Glossary
``'\r'``. See :pep:`278` and :pep:`3116`, as well as
:func:`bytes.splitlines` for an additional use.
+ variable annotation
+ A type metadata value associated with a module global variable or
+ a class attribute. Its syntax is explained in section :ref:`annassign`.
+ Annotations are stored in the :attr:`__annotations__` special
+ attribute of a class or module object and can be accessed using
+ :func:`typing.get_type_hints`.
+
+ Python itself does not assign any particular meaning to variable
+ annotations. They are intended to be interpreted by third-party libraries
+ or type checking tools. See :pep:`526`, :pep:`484` which describe
+ some of their potential uses.
+
virtual environment
A cooperatively isolated runtime environment that allows Python users
and applications to install and upgrade Python distribution packages
without interfering with the behaviour of other Python applications
running on the same system.
- See also :ref:`scripts-pyvenv`.
+ See also :mod:`venv`.
virtual machine
A computer defined entirely in software. Python's virtual machine
diff --git a/Doc/howto/argparse.rst b/Doc/howto/argparse.rst
index 3b79b92..7e161a5 100644
--- a/Doc/howto/argparse.rst
+++ b/Doc/howto/argparse.rst
@@ -547,7 +547,8 @@ And this is what it gives:
Traceback (most recent call last):
File "prog.py", line 11, in <module>
if args.verbosity >= 2:
- TypeError: unorderable types: NoneType() >= int()
+ TypeError: '>=' not supported between instances of 'NoneType' and 'int'
+
* First output went well, and fixes the bug we had before.
That is, we want any value >= 2 to be as verbose as possible.
diff --git a/Doc/howto/clinic.rst b/Doc/howto/clinic.rst
index 491c5a2..eaab20a 100644
--- a/Doc/howto/clinic.rst
+++ b/Doc/howto/clinic.rst
@@ -834,9 +834,9 @@ on the right is the text you'd replace it with.
``'i'`` ``int``
``'I'`` ``unsigned_int(bitwise=True)``
``'k'`` ``unsigned_long(bitwise=True)``
-``'K'`` ``unsigned_PY_LONG_LONG(bitwise=True)``
+``'K'`` ``unsigned_long_long(bitwise=True)``
``'l'`` ``long``
-``'L'`` ``PY_LONG_LONG``
+``'L'`` ``long long``
``'n'`` ``Py_ssize_t``
``'O'`` ``object``
``'O!'`` ``object(subclass_of='&PySomething_Type')``
diff --git a/Doc/howto/index.rst b/Doc/howto/index.rst
index de65950..593341c 100644
--- a/Doc/howto/index.rst
+++ b/Doc/howto/index.rst
@@ -28,4 +28,5 @@ Currently, the HOWTOs are:
argparse.rst
ipaddress.rst
clinic.rst
+ instrumentation.rst
diff --git a/Doc/howto/instrumentation.rst b/Doc/howto/instrumentation.rst
new file mode 100644
index 0000000..7fca9aa
--- /dev/null
+++ b/Doc/howto/instrumentation.rst
@@ -0,0 +1,408 @@
+.. highlight:: shell-session
+
+.. _instrumentation:
+
+===============================================
+Instrumenting CPython with DTrace and SystemTap
+===============================================
+
+:author: David Malcolm
+:author: Łukasz Langa
+
+DTrace and SystemTap are monitoring tools, each providing a way to inspect
+what the processes on a computer system are doing. They both use
+domain-specific languages allowing a user to write scripts which:
+
+ - filter which processes are to be observed
+ - gather data from the processes of interest
+ - generate reports on the data
+
+As of Python 3.6, CPython can be built with embedded "markers", also
+known as "probes", that can be observed by a DTrace or SystemTap script,
+making it easier to monitor what the CPython processes on a system are
+doing.
+
+.. impl-detail::
+
+ DTrace markers are implementation details of the CPython interpreter.
+ No guarantees are made about probe compatibility between versions of
+ CPython. DTrace scripts can stop working or work incorrectly without
+ warning when changing CPython versions.
+
+
+Enabling the static markers
+---------------------------
+
+macOS comes with built-in support for DTrace. On Linux, in order to
+build CPython with the embedded markers for SystemTap, the SystemTap
+development tools must be installed.
+
+On a Linux machine, this can be done via::
+
+ $ yum install systemtap-sdt-devel
+
+or::
+
+ $ sudo apt-get install systemtap-sdt-dev
+
+
+CPython must then be configured ``--with-dtrace``:
+
+.. code-block:: none
+
+ checking for --with-dtrace... yes
+
+On macOS, you can list available DTrace probes by running a Python
+process in the background and listing all probes made available by the
+Python provider::
+
+ $ python3.6 -q &
+ $ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6
+
+ ID PROVIDER MODULE FUNCTION NAME
+ 29564 python18035 python3.6 _PyEval_EvalFrameDefault function-entry
+ 29565 python18035 python3.6 dtrace_function_entry function-entry
+ 29566 python18035 python3.6 _PyEval_EvalFrameDefault function-return
+ 29567 python18035 python3.6 dtrace_function_return function-return
+ 29568 python18035 python3.6 collect gc-done
+ 29569 python18035 python3.6 collect gc-start
+ 29570 python18035 python3.6 _PyEval_EvalFrameDefault line
+ 29571 python18035 python3.6 maybe_dtrace_line line
+
+On Linux, you can verify if the SystemTap static markers are present in
+the built binary by seeing if it contains a ".note.stapsdt" section.
+
+::
+
+ $ readelf -S ./python | grep .note.stapsdt
+ [30] .note.stapsdt NOTE 0000000000000000 00308d78
+
+If you've built Python as a shared library (with --enable-shared), you
+need to look instead within the shared library. For example::
+
+ $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
+ [29] .note.stapsdt NOTE 0000000000000000 00365b68
+
+Sufficiently modern readelf can print the metadata::
+
+ $ readelf -n ./python
+
+ Displaying notes found at file offset 0x00000254 with length 0x00000020:
+ Owner Data size Description
+ GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag)
+ OS: Linux, ABI: 2.6.32
+
+ Displaying notes found at file offset 0x00000274 with length 0x00000024:
+ Owner Data size Description
+ GNU 0x00000014 NT_GNU_BUILD_ID (unique build ID bitstring)
+ Build ID: df924a2b08a7e89f6e11251d4602022977af2670
+
+ Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
+ Owner Data size Description
+ stapsdt 0x00000031 NT_STAPSDT (SystemTap probe descriptors)
+ Provider: python
+ Name: gc__start
+ Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
+ Arguments: -4@%ebx
+ stapsdt 0x00000030 NT_STAPSDT (SystemTap probe descriptors)
+ Provider: python
+ Name: gc__done
+ Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
+ Arguments: -8@%rax
+ stapsdt 0x00000045 NT_STAPSDT (SystemTap probe descriptors)
+ Provider: python
+ Name: function__entry
+ Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
+ Arguments: 8@%rbp 8@%r12 -4@%eax
+ stapsdt 0x00000046 NT_STAPSDT (SystemTap probe descriptors)
+ Provider: python
+ Name: function__return
+ Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
+ Arguments: 8@%rbp 8@%r12 -4@%eax
+
+The above metadata contains information for SystemTap describing how it
+can patch strategically-placed machine code instructions to enable the
+tracing hooks used by a SystemTap script.
+
+
+Static DTrace probes
+--------------------
+
+The following example DTrace script can be used to show the call/return
+hierarchy of a Python script, only tracing within the invocation of
+a function called "start". In other words, import-time function
+invocations are not going to be listed:
+
+.. code-block:: none
+
+ self int indent;
+
+ python$target:::function-entry
+ /copyinstr(arg1) == "start"/
+ {
+ self->trace = 1;
+ }
+
+ python$target:::function-entry
+ /self->trace/
+ {
+ printf("%d\t%*s:", timestamp, 15, probename);
+ printf("%*s", self->indent, "");
+ printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
+ self->indent++;
+ }
+
+ python$target:::function-return
+ /self->trace/
+ {
+ self->indent--;
+ printf("%d\t%*s:", timestamp, 15, probename);
+ printf("%*s", self->indent, "");
+ printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
+ }
+
+ python$target:::function-return
+ /copyinstr(arg1) == "start"/
+ {
+ self->trace = 0;
+ }
+
+It can be invoked like this::
+
+ $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"
+
+The output looks like this:
+
+.. code-block:: none
+
+ 156641360502280 function-entry:call_stack.py:start:23
+ 156641360518804 function-entry: call_stack.py:function_1:1
+ 156641360532797 function-entry: call_stack.py:function_3:9
+ 156641360546807 function-return: call_stack.py:function_3:10
+ 156641360563367 function-return: call_stack.py:function_1:2
+ 156641360578365 function-entry: call_stack.py:function_2:5
+ 156641360591757 function-entry: call_stack.py:function_1:1
+ 156641360605556 function-entry: call_stack.py:function_3:9
+ 156641360617482 function-return: call_stack.py:function_3:10
+ 156641360629814 function-return: call_stack.py:function_1:2
+ 156641360642285 function-return: call_stack.py:function_2:6
+ 156641360656770 function-entry: call_stack.py:function_3:9
+ 156641360669707 function-return: call_stack.py:function_3:10
+ 156641360687853 function-entry: call_stack.py:function_4:13
+ 156641360700719 function-return: call_stack.py:function_4:14
+ 156641360719640 function-entry: call_stack.py:function_5:18
+ 156641360732567 function-return: call_stack.py:function_5:21
+ 156641360747370 function-return:call_stack.py:start:28
+
+
+Static SystemTap markers
+------------------------
+
+The low-level way to use the SystemTap integration is to use the static
+markers directly. This requires you to explicitly state the binary file
+containing them.
+
+For example, this SystemTap script can be used to show the call/return
+hierarchy of a Python script:
+
+.. code-block:: none
+
+ probe process("python").mark("function__entry") {
+ filename = user_string($arg1);
+ funcname = user_string($arg2);
+ lineno = $arg3;
+
+ printf("%s => %s in %s:%d\\n",
+ thread_indent(1), funcname, filename, lineno);
+ }
+
+ probe process("python").mark("function__return") {
+ filename = user_string($arg1);
+ funcname = user_string($arg2);
+ lineno = $arg3;
+
+ printf("%s <= %s in %s:%d\\n",
+ thread_indent(-1), funcname, filename, lineno);
+ }
+
+It can be invoked like this::
+
+ $ stap \
+ show-call-hierarchy.stp \
+ -c "./python test.py"
+
+The output looks like this:
+
+.. code-block:: none
+
+ 11408 python(8274): => __contains__ in Lib/_abcoll.py:362
+ 11414 python(8274): => __getitem__ in Lib/os.py:425
+ 11418 python(8274): => encode in Lib/os.py:490
+ 11424 python(8274): <= encode in Lib/os.py:493
+ 11428 python(8274): <= __getitem__ in Lib/os.py:426
+ 11433 python(8274): <= __contains__ in Lib/_abcoll.py:366
+
+where the columns are:
+
+ - time in microseconds since start of script
+
+ - name of executable
+
+ - PID of process
+
+and the remainder indicates the call/return hierarchy as the script executes.
+
+For a `--enable-shared` build of CPython, the markers are contained within the
+libpython shared library, and the probe's dotted path needs to reflect this. For
+example, this line from the above example::
+
+ probe process("python").mark("function__entry") {
+
+should instead read::
+
+ probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") {
+
+(assuming a debug build of CPython 3.6)
+
+
+Available static markers
+------------------------
+
+.. I'm reusing the "c:function" type for markers
+
+.. c:function:: function__entry(str filename, str funcname, int lineno)
+
+ This marker indicates that execution of a Python function has begun.
+ It is only triggered for pure-Python (bytecode) functions.
+
+ The filename, function name, and line number are provided back to the
+ tracing script as positional arguments, which must be accessed using
+ ``$arg1``, ``$arg2``, ``$arg3``:
+
+ * ``$arg1`` : ``(const char *)`` filename, accessible using ``user_string($arg1)``
+
+ * ``$arg2`` : ``(const char *)`` function name, accessible using
+ ``user_string($arg2)``
+
+ * ``$arg3`` : ``int`` line number
+
+.. c:function:: function__return(str filename, str funcname, int lineno)
+
+ This marker is the converse of :c:func:`function__entry`, and indicates that
+ execution of a Python function has ended (either via ``return``, or via an
+ exception). It is only triggered for pure-Python (bytecode) functions.
+
+ The arguments are the same as for :c:func:`function__entry`
+
+.. c:function:: line(str filename, str funcname, int lineno)
+
+ This marker indicates a Python line is about to be executed. It is
+ the equivalent of line-by-line tracing with a Python profiler. It is
+ not triggered within C functions.
+
+ The arguments are the same as for :c:func:`function__entry`.
+
+.. c:function:: gc__start(int generation)
+
+ Fires when the Python interpreter starts a garbage collection cycle.
+ ``arg0`` is the generation to scan, like :func:`gc.collect()`.
+
+.. c:function:: gc__done(long collected)
+
+ Fires when the Python interpreter finishes a garbage collection
+ cycle. ``arg0`` is the number of collected objects.
+
+
+SystemTap Tapsets
+-----------------
+
+The higher-level way to use the SystemTap integration is to use a "tapset":
+SystemTap's equivalent of a library, which hides some of the lower-level
+details of the static markers.
+
+Here is a tapset file, based on a non-shared build of CPython:
+
+.. code-block:: none
+
+ /*
+ Provide a higher-level wrapping around the function__entry and
+ function__return markers:
+ \*/
+ probe python.function.entry = process("python").mark("function__entry")
+ {
+ filename = user_string($arg1);
+ funcname = user_string($arg2);
+ lineno = $arg3;
+ frameptr = $arg4
+ }
+ probe python.function.return = process("python").mark("function__return")
+ {
+ filename = user_string($arg1);
+ funcname = user_string($arg2);
+ lineno = $arg3;
+ frameptr = $arg4
+ }
+
+If this file is installed in SystemTap's tapset directory (e.g.
+``/usr/share/systemtap/tapset``), then these additional probepoints become
+available:
+
+.. c:function:: python.function.entry(str filename, str funcname, int lineno, frameptr)
+
+ This probe point indicates that execution of a Python function has begun.
+ It is only triggered for pure-python (bytecode) functions.
+
+.. c:function:: python.function.return(str filename, str funcname, int lineno, frameptr)
+
+ This probe point is the converse of :c:func:`python.function.return`, and
+ indicates that execution of a Python function has ended (either via
+ ``return``, or via an exception). It is only triggered for pure-python
+ (bytecode) functions.
+
+
+Examples
+--------
+This SystemTap script uses the tapset above to more cleanly implement the
+example given above of tracing the Python function-call hierarchy, without
+needing to directly name the static markers:
+
+.. code-block:: none
+
+ probe python.function.entry
+ {
+ printf("%s => %s in %s:%d\n",
+ thread_indent(1), funcname, filename, lineno);
+ }
+
+ probe python.function.return
+ {
+ printf("%s <= %s in %s:%d\n",
+ thread_indent(-1), funcname, filename, lineno);
+ }
+
+
+The following script uses the tapset above to provide a top-like view of all
+running CPython code, showing the top 20 most frequently-entered bytecode
+frames, each second, across the whole system:
+
+.. code-block:: none
+
+ global fn_calls;
+
+ probe python.function.entry
+ {
+ fn_calls[pid(), filename, funcname, lineno] += 1;
+ }
+
+ probe timer.ms(1000) {
+ printf("\033[2J\033[1;1H") /* clear screen \*/
+ printf("%6s %80s %6s %30s %6s\n",
+ "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
+ foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {
+ printf("%6d %80s %6d %30s %6d\n",
+ pid, filename, lineno, funcname,
+ fn_calls[pid, filename, funcname, lineno]);
+ }
+ delete fn_calls;
+ }
+
diff --git a/Doc/includes/email-alternative-new-api.py b/Doc/includes/email-alternative-new-api.py
deleted file mode 100644
index 321f727..0000000
--- a/Doc/includes/email-alternative-new-api.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python3
-
-import smtplib
-
-from email.message import EmailMessage
-from email.headerregistry import Address
-from email.utils import make_msgid
-
-# Create the base text message.
-msg = EmailMessage()
-msg['Subject'] = "Ayons asperges pour le déjeuner"
-msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
-msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
- Address("Fabrette Pussycat", "fabrette", "example.com"))
-msg.set_content("""\
-Salut!
-
-Cela ressemble à un excellent recipie[1] déjeuner.
-
-[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
-
---Pepé
-""")
-
-# Add the html version. This converts the message into a multipart/alternative
-# container, with the original text message as the first part and the new html
-# message as the second part.
-asparagus_cid = make_msgid()
-msg.add_alternative("""\
-<html>
- <head></head>
- <body>
- <p>Salut!<\p>
- <p>Cela ressemble à un excellent
- <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
- recipie
- </a> déjeuner.
- </p>
- <img src="cid:{asparagus_cid}" \>
- </body>
-</html>
-""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
-# note that we needed to peel the <> off the msgid for use in the html.
-
-# Now add the related image to the html part.
-with open("roasted-asparagus.jpg", 'rb') as img:
- msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
- cid=asparagus_cid)
-
-# Make a local copy of what we are going to send.
-with open('outgoing.msg', 'wb') as f:
- f.write(bytes(msg))
-
-# Send the message via local SMTP server.
-with smtplib.SMTP('localhost') as s:
- s.send_message(msg)
diff --git a/Doc/includes/email-alternative.py b/Doc/includes/email-alternative.py
index 85070f3..2e142b1 100755..100644
--- a/Doc/includes/email-alternative.py
+++ b/Doc/includes/email-alternative.py
@@ -2,47 +2,55 @@
import smtplib
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-
-# me == my email address
-# you == recipient's email address
-me = "my@email.com"
-you = "your@email.com"
-
-# Create message container - the correct MIME type is multipart/alternative.
-msg = MIMEMultipart('alternative')
-msg['Subject'] = "Link"
-msg['From'] = me
-msg['To'] = you
-
-# Create the body of the message (a plain-text and an HTML version).
-text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
-html = """\
+from email.message import EmailMessage
+from email.headerregistry import Address
+from email.utils import make_msgid
+
+# Create the base text message.
+msg = EmailMessage()
+msg['Subject'] = "Ayons asperges pour le déjeuner"
+msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
+msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
+ Address("Fabrette Pussycat", "fabrette", "example.com"))
+msg.set_content("""\
+Salut!
+
+Cela ressemble à un excellent recipie[1] déjeuner.
+
+[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
+
+--Pepé
+""")
+
+# Add the html version. This converts the message into a multipart/alternative
+# container, with the original text message as the first part and the new html
+# message as the second part.
+asparagus_cid = make_msgid()
+msg.add_alternative("""\
<html>
<head></head>
<body>
- <p>Hi!<br>
- How are you?<br>
- Here is the <a href="https://www.python.org">link</a> you wanted.
+ <p>Salut!</p>
+ <p>Cela ressemble à un excellent
+ <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
+ recipie
+ </a> déjeuner.
</p>
+ <img src="cid:{asparagus_cid}" />
</body>
</html>
-"""
+""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
+# note that we needed to peel the <> off the msgid for use in the html.
-# Record the MIME types of both parts - text/plain and text/html.
-part1 = MIMEText(text, 'plain')
-part2 = MIMEText(html, 'html')
+# Now add the related image to the html part.
+with open("roasted-asparagus.jpg", 'rb') as img:
+ msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
+ cid=asparagus_cid)
-# Attach parts into message container.
-# According to RFC 2046, the last part of a multipart message, in this case
-# the HTML message, is best and preferred.
-msg.attach(part1)
-msg.attach(part2)
+# Make a local copy of what we are going to send.
+with open('outgoing.msg', 'wb') as f:
+ f.write(bytes(msg))
# Send the message via local SMTP server.
-s = smtplib.SMTP('localhost')
-# sendmail function takes 3 arguments: sender's address, recipient's address
-# and message to send - here it is sent as one string.
-s.sendmail(me, you, msg.as_string())
-s.quit()
+with smtplib.SMTP('localhost') as s:
+ s.send_message(msg)
diff --git a/Doc/includes/email-dir.py b/Doc/includes/email-dir.py
index 3c7c770..0dcfbfb 100644
--- a/Doc/includes/email-dir.py
+++ b/Doc/includes/email-dir.py
@@ -3,22 +3,14 @@
"""Send the contents of a directory as a MIME message."""
import os
-import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from argparse import ArgumentParser
-from email import encoders
-from email.message import Message
-from email.mime.audio import MIMEAudio
-from email.mime.base import MIMEBase
-from email.mime.image import MIMEImage
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-
-COMMASPACE = ', '
+from email.message import EmailMessage
+from email.policy import SMTP
def main():
@@ -47,12 +39,12 @@ must be running an SMTP server.
directory = args.directory
if not directory:
directory = '.'
- # Create the enclosing (outer) message
- outer = MIMEMultipart()
- outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
- outer['To'] = COMMASPACE.join(args.recipients)
- outer['From'] = args.sender
- outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
+ # Create the message
+ msg = EmailMessage()
+ msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
+ msg['To'] = ', '.join(args.recipients)
+ msg['From'] = args.sender
+ msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
@@ -67,33 +59,18 @@ must be running an SMTP server.
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
- if maintype == 'text':
- with open(path) as fp:
- # Note: we should handle calculating the charset
- msg = MIMEText(fp.read(), _subtype=subtype)
- elif maintype == 'image':
- with open(path, 'rb') as fp:
- msg = MIMEImage(fp.read(), _subtype=subtype)
- elif maintype == 'audio':
- with open(path, 'rb') as fp:
- msg = MIMEAudio(fp.read(), _subtype=subtype)
- else:
- with open(path, 'rb') as fp:
- msg = MIMEBase(maintype, subtype)
- msg.set_payload(fp.read())
- # Encode the payload using Base64
- encoders.encode_base64(msg)
- # Set the filename parameter
- msg.add_header('Content-Disposition', 'attachment', filename=filename)
- outer.attach(msg)
+ with open(path, 'rb') as fp:
+ msg.add_attachment(fp.read(),
+ maintype=maintype,
+ subtype=subtype,
+ filename=filename)
# Now send or store the message
- composed = outer.as_string()
if args.output:
- with open(args.output, 'w') as fp:
- fp.write(composed)
+ with open(args.output, 'wb') as fp:
+ fp.write(msg.as_bytes(policy=SMTP))
else:
with smtplib.SMTP('localhost') as s:
- s.sendmail(args.sender, args.recipients, composed)
+ s.send_message(msg)
if __name__ == '__main__':
diff --git a/Doc/includes/email-headers.py b/Doc/includes/email-headers.py
index 89c8f3a..2c42145 100644
--- a/Doc/includes/email-headers.py
+++ b/Doc/includes/email-headers.py
@@ -1,18 +1,24 @@
# Import the email modules we'll need
-from email.parser import Parser
+from email.parser import BytesParser, Parser
+from email.policy import default
# If the e-mail headers are in a file, uncomment these two lines:
-# with open(messagefile) as fp:
-# headers = Parser().parse(fp)
+# with open(messagefile, 'rb') as fp:
+# headers = BytesParser(policy=default).parse(fp)
-# Or for parsing headers in a string, use:
-headers = Parser().parsestr('From: <user@example.com>\n'
+# Or for parsing headers in a string (this is an uncommon operation), use:
+headers = Parser(policy=default).parsestr(
+ 'From: Foo Bar <user@example.com>\n'
'To: <someone_else@example.com>\n'
'Subject: Test message\n'
'\n'
'Body would go here\n')
# Now the header items can be accessed as a dictionary:
-print('To: %s' % headers['to'])
-print('From: %s' % headers['from'])
-print('Subject: %s' % headers['subject'])
+print('To: {}'.format(headers['to']))
+print('From: {}'.format(headers['from']))
+print('Subject: {}'.format(headers['subject']))
+
+# You can also access the parts of the addresses:
+print('Recipient username: {}'.format(headers['to'].addresses[0].username))
+print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
diff --git a/Doc/includes/email-mime.py b/Doc/includes/email-mime.py
index 61d0830..c610242 100644
--- a/Doc/includes/email-mime.py
+++ b/Doc/includes/email-mime.py
@@ -1,30 +1,29 @@
# Import smtplib for the actual sending function
import smtplib
-# Here are the email package modules we'll need
-from email.mime.image import MIMEImage
-from email.mime.multipart import MIMEMultipart
+# And imghdr to find the types of our images
+import imghdr
-COMMASPACE = ', '
+# Here are the email package modules we'll need
+from email.message import EmailMessage
-# Create the container (outer) email message.
-msg = MIMEMultipart()
+# Create the container email message.
+msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
-msg['To'] = COMMASPACE.join(family)
+msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
-# Assume we know that the image files are all in PNG format
+# Open the files in binary mode. Use imghdr to figure out the
+# MIME subtype for each specific image.
for file in pngfiles:
- # Open the files in binary mode. Let the MIMEImage class automatically
- # guess the specific image type.
with open(file, 'rb') as fp:
- img = MIMEImage(fp.read())
- msg.attach(img)
+ img_data = fp.read()
+ msg.add_attachment(img_data, maintype='image',
+ subtype=imghdr.what(None, img_data))
# Send the email via our own SMTP server.
-s = smtplib.SMTP('localhost')
-s.send_message(msg)
-s.quit()
+with smtplib.SMTP('localhost') as s:
+ s.send_message(msg)
diff --git a/Doc/includes/email-read-alternative-new-api.py b/Doc/includes/email-read-alternative.py
index 3f5ab24..3f5ab24 100644
--- a/Doc/includes/email-read-alternative-new-api.py
+++ b/Doc/includes/email-read-alternative.py
diff --git a/Doc/includes/email-simple.py b/Doc/includes/email-simple.py
index b9b8b41..f69ef40 100644
--- a/Doc/includes/email-simple.py
+++ b/Doc/includes/email-simple.py
@@ -2,13 +2,13 @@
import smtplib
# Import the email modules we'll need
-from email.mime.text import MIMEText
+from email.message import EmailMessage
-# Open a plain text file for reading. For this example, assume that
-# the text file contains only ASCII characters.
+# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
- msg = MIMEText(fp.read())
+ msg = EmailMessage()
+ msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
diff --git a/Doc/includes/email-unpack.py b/Doc/includes/email-unpack.py
index 574a0b6..e0a7f01 100644
--- a/Doc/includes/email-unpack.py
+++ b/Doc/includes/email-unpack.py
@@ -3,11 +3,11 @@
"""Unpack a MIME message into a directory of files."""
import os
-import sys
import email
-import errno
import mimetypes
+from email.policy import default
+
from argparse import ArgumentParser
@@ -22,8 +22,8 @@ Unpack a MIME message into a directory of files.
parser.add_argument('msgfile')
args = parser.parse_args()
- with open(args.msgfile) as fp:
- msg = email.message_from_file(fp)
+ with open(args.msgfile, 'rb') as fp:
+ msg = email.message_from_binary_file(fp, policy=default)
try:
os.mkdir(args.directory)
diff --git a/Doc/includes/run-func.c b/Doc/includes/run-func.c
index 986d670..ead7bdd 100644
--- a/Doc/includes/run-func.c
+++ b/Doc/includes/run-func.c
@@ -63,6 +63,8 @@ main(int argc, char *argv[])
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
- Py_Finalize();
+ if (Py_FinalizeEx() < 0) {
+ return 120;
+ }
return 0;
}
diff --git a/Doc/includes/test.py b/Doc/includes/test.py
index 7ebf46a..9e9d4a6 100644
--- a/Doc/includes/test.py
+++ b/Doc/includes/test.py
@@ -204,7 +204,7 @@ Test cyclic gc(?)
import os
import sys
from distutils.util import get_platform
-PLAT_SPEC = "%s-%s" % (get_platform(), sys.version[0:3])
+PLAT_SPEC = "%s-%d.%d" % (get_platform(), *sys.version_info[:2])
src = os.path.join("build", "lib.%s" % PLAT_SPEC)
sys.path.append(src)
diff --git a/Doc/includes/tzinfo-examples.py b/Doc/includes/tzinfo-examples.py
index 3a8cf47..ae5a509 100644
--- a/Doc/includes/tzinfo-examples.py
+++ b/Doc/includes/tzinfo-examples.py
@@ -1,46 +1,13 @@
-from datetime import tzinfo, timedelta, datetime
+from datetime import tzinfo, timedelta, datetime, timezone
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
-
-# A UTC class.
-
-class UTC(tzinfo):
- """UTC"""
-
- def utcoffset(self, dt):
- return ZERO
-
- def tzname(self, dt):
- return "UTC"
-
- def dst(self, dt):
- return ZERO
-
-utc = UTC()
-
-# A class building tzinfo objects for fixed-offset time zones.
-# Note that FixedOffset(0, "UTC") is a different way to build a
-# UTC tzinfo object.
-
-class FixedOffset(tzinfo):
- """Fixed offset in minutes east from UTC."""
-
- def __init__(self, offset, name):
- self.__offset = timedelta(minutes=offset)
- self.__name = name
-
- def utcoffset(self, dt):
- return self.__offset
-
- def tzname(self, dt):
- return self.__name
-
- def dst(self, dt):
- return ZERO
+SECOND = timedelta(seconds=1)
# A class capturing the platform's idea of local time.
-
+# (May result in wrong values on historical times in
+# timezones where UTC offset and/or the DST rules had
+# changed in the past.)
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
@@ -53,6 +20,16 @@ DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
+ def fromutc(self, dt):
+ assert dt.tzinfo is self
+ stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
+ args = _time.localtime(stamp)[:6]
+ dst_diff = DSTDIFF // SECOND
+ # Detect fold
+ fold = (args == _time.localtime(stamp - dst_diff))
+ return datetime(*args, microsecond=dt.microsecond,
+ tzinfo=self, fold=fold)
+
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
@@ -99,20 +76,37 @@ def first_sunday_on_or_after(dt):
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
-# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov.
-DSTEND_2007 = datetime(1, 11, 1, 1)
+# and ends at 2am (DST time) on the first Sunday of Nov.
+DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
-# Sunday in April and to end at 2am (DST time; 1am standard time) on the last
+# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
-DSTEND_1987_2006 = datetime(1, 10, 25, 1)
+DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
-# Sunday in April (the one on or after April 24) and to end at 2am (DST time;
-# 1am standard time) on the last Sunday of October, which is the first Sunday
+# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
+# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006
+def us_dst_range(year):
+ # Find start and end times for US DST. For years before 1967, return
+ # start = end for no DST.
+ if 2006 < year:
+ dststart, dstend = DSTSTART_2007, DSTEND_2007
+ elif 1986 < year < 2007:
+ dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
+ elif 1966 < year < 1987:
+ dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
+ else:
+ return (datetime(year, 1, 1), ) * 2
+
+ start = first_sunday_on_or_after(dststart.replace(year=year))
+ end = first_sunday_on_or_after(dstend.replace(year=year))
+ return start, end
+
+
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
@@ -141,27 +135,39 @@ class USTimeZone(tzinfo):
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
-
- # Find start and end times for US DST. For years before 1967, return
- # ZERO for no DST.
- if 2006 < dt.year:
- dststart, dstend = DSTSTART_2007, DSTEND_2007
- elif 1986 < dt.year < 2007:
- dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
- elif 1966 < dt.year < 1987:
- dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
- else:
- return ZERO
-
- start = first_sunday_on_or_after(dststart.replace(year=dt.year))
- end = first_sunday_on_or_after(dstend.replace(year=dt.year))
-
+ start, end = us_dst_range(dt.year)
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
- if start <= dt.replace(tzinfo=None) < end:
+ dt = dt.replace(tzinfo=None)
+ if start + HOUR <= dt < end - HOUR:
+ # DST is in effect.
return HOUR
- else:
- return ZERO
+ if end - HOUR <= dt < end:
+ # Fold (an ambiguous hour): use dt.fold to disambiguate.
+ return ZERO if dt.fold else HOUR
+ if start <= dt < start + HOUR:
+ # Gap (a non-existent hour): reverse the fold rule.
+ return HOUR if dt.fold else ZERO
+ # DST is off.
+ return ZERO
+
+ def fromutc(self, dt):
+ assert dt.tzinfo is self
+ start, end = us_dst_range(dt.year)
+ start = start.replace(tzinfo=self)
+ end = end.replace(tzinfo=self)
+ std_time = dt + self.stdoffset
+ dst_time = std_time + HOUR
+ if end <= dst_time < end + HOUR:
+ # Repeated hour
+ return std_time.replace(fold=1)
+ if std_time < start or dst_time >= end:
+ # Standard time
+ return std_time
+ if start <= std_time < end - HOUR:
+ # Daylight saving time
+ return dst_time
+
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT")
diff --git a/Doc/installing/index.rst b/Doc/installing/index.rst
index 1ef3149..b22465d 100644
--- a/Doc/installing/index.rst
+++ b/Doc/installing/index.rst
@@ -2,9 +2,9 @@
.. _installing-index:
-*****************************
- Installing Python Modules
-*****************************
+*************************
+Installing Python Modules
+*************************
:Email: distutils-sig@python.org
@@ -34,24 +34,24 @@ Key terms
* ``pip`` is the preferred installer program. Starting with Python 3.4, it
is included by default with the Python binary installers.
-* a virtual environment is a semi-isolated Python environment that allows
+* A *virtual environment* is a semi-isolated Python environment that allows
packages to be installed for use by a particular application, rather than
- being installed system wide
-* ``pyvenv`` is the standard tool for creating virtual environments, and has
+ being installed system wide.
+* ``venv`` is the standard tool for creating virtual environments, and has
been part of Python since Python 3.3. Starting with Python 3.4, it
- defaults to installing ``pip`` into all created virtual environments
+ defaults to installing ``pip`` into all created virtual environments.
* ``virtualenv`` is a third party alternative (and predecessor) to
- ``pyvenv``. It allows virtual environments to be used on versions of
- Python prior to 3.4, which either don't provide ``pyvenv`` at all, or
+ ``venv``. It allows virtual environments to be used on versions of
+ Python prior to 3.4, which either don't provide ``venv`` at all, or
aren't able to automatically install ``pip`` into created environments.
-* the `Python Packaging Index <https://pypi.python.org/pypi>`__ is a public
+* The `Python Packaging Index <https://pypi.python.org/pypi>`__ is a public
repository of open source licensed packages made available for use by
- other Python users
+ other Python users.
* the `Python Packaging Authority
<https://www.pypa.io/en/latest/>`__ are the group of
developers and documentation authors responsible for the maintenance and
evolution of the standard packaging tools and the associated metadata and
- file format standards. They maintain a variety of tools, documentation
+ file format standards. They maintain a variety of tools, documentation,
and issue trackers on both `GitHub <https://github.com/pypa>`__ and
`BitBucket <https://bitbucket.org/pypa/>`__.
* ``distutils`` is the original build and distribution system first added to
@@ -62,6 +62,19 @@ Key terms
of the mailing list used to coordinate Python packaging standards
development).
+.. deprecated:: 3.6
+ ``pyvenv`` was the recommended tool for creating virtual environments for
+ Python 3.3 and 3.4, and is `deprecated in Python 3.6
+ <https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features>`_.
+
+.. versionchanged:: 3.5
+ The use of ``venv`` is now recommended for creating virtual environments.
+
+.. seealso::
+
+ `Python Packaging User Guide: Creating and using virtual environments
+ <https://packaging.python.org/installing/#creating-virtual-environments>`__
+
Basic usage
===========
@@ -100,13 +113,14 @@ explicitly::
More information and resources regarding ``pip`` and its capabilities can be
found in the `Python Packaging User Guide <https://packaging.python.org>`__.
-``pyvenv`` has its own documentation at :ref:`scripts-pyvenv`. Installing
-into an active virtual environment uses the commands shown above.
+Creation of virtual environments is done through the :mod:`venv` module.
+Installing packages into an active virtual environment uses the commands shown
+above.
.. seealso::
`Python Packaging User Guide: Installing Python Distribution Packages
- <https://packaging.python.org/en/latest/installing/>`__
+ <https://packaging.python.org/installing/>`__
How do I ...?
@@ -124,7 +138,7 @@ User Guide.
.. seealso::
`Python Packaging User Guide: Requirements for Installing Packages
- <https://packaging.python.org/en/latest/installing/#requirements-for-installing-packages>`__
+ <https://packaging.python.org/installing/#requirements-for-installing-packages>`__
.. installing-per-user-installation:
@@ -142,20 +156,19 @@ package just for the current user, rather than for all users of the system.
A number of scientific Python packages have complex binary dependencies, and
aren't currently easy to install using ``pip`` directly. At this point in
time, it will often be easier for users to install these packages by
-`other means
-<https://packaging.python.org/en/latest/science/>`__
+`other means <https://packaging.python.org/science/>`__
rather than attempting to install them with ``pip``.
.. seealso::
`Python Packaging User Guide: Installing Scientific Packages
- <https://packaging.python.org/en/latest/science/>`__
+ <https://packaging.python.org/science/>`__
... work with multiple versions of Python installed in parallel?
----------------------------------------------------------------
-On Linux, Mac OS X and other POSIX systems, use the versioned Python commands
+On Linux, Mac OS X, and other POSIX systems, use the versioned Python commands
in combination with the ``-m`` switch to run the appropriate copy of
``pip``::
@@ -164,7 +177,7 @@ in combination with the ``-m`` switch to run the appropriate copy of
python3 -m pip install SomePackage # default Python 3
python3.4 -m pip install SomePackage # specifically Python 3.4
-(appropriately versioned ``pip`` commands may also be available)
+Appropriately versioned ``pip`` commands may also be available.
On Windows, use the ``py`` Python launcher in combination with the ``-m``
switch::
@@ -212,11 +225,11 @@ as users are more regularly able to install pre-built extensions rather
than needing to build them themselves.
Some of the solutions for installing `scientific software
-<https://packaging.python.org/en/latest/science/>`__
-that is not yet available as pre-built ``wheel`` files may also help with
+<https://packaging.python.org/science/>`__
+that are not yet available as pre-built ``wheel`` files may also help with
obtaining other binary extensions without needing to build them locally.
.. seealso::
`Python Packaging User Guide: Binary Extensions
- <https://packaging.python.org/en/latest/extensions/>`__
+ <https://packaging.python.org/extensions/>`__
diff --git a/Doc/library/asynchat.rst b/Doc/library/asynchat.rst
index ae72d26..9e51416 100644
--- a/Doc/library/asynchat.rst
+++ b/Doc/library/asynchat.rst
@@ -9,6 +9,9 @@
**Source code:** :source:`Lib/asynchat.py`
+.. deprecated:: 3.6
+ Please use :mod:`asyncio` instead.
+
--------------
.. note::
@@ -58,13 +61,13 @@ connection requests.
The asynchronous output buffer size (default ``4096``).
Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to
- define a first-in-first-out queue (fifo) of *producers*. A producer need
+ define a :abbr:`FIFO (first-in, first-out)` queue of *producers*. A producer need
have only one method, :meth:`more`, which should return data to be
transmitted on the channel.
The producer indicates exhaustion (*i.e.* that it contains no more data) by
having its :meth:`more` method return the empty bytes object. At this point
- the :class:`async_chat` object removes the producer from the fifo and starts
- using the next producer, if any. When the producer fifo is empty the
+ the :class:`async_chat` object removes the producer from the queue and starts
+ using the next producer, if any. When the producer queue is empty the
:meth:`handle_write` method does nothing. You use the channel object's
:meth:`set_terminator` method to describe how to recognize the end of, or
an important breakpoint in, an incoming transmission from the remote
@@ -78,8 +81,8 @@ connection requests.
.. method:: async_chat.close_when_done()
- Pushes a ``None`` on to the producer fifo. When this producer is popped off
- the fifo it causes the channel to be closed.
+ Pushes a ``None`` on to the producer queue. When this producer is popped off
+ the queue it causes the channel to be closed.
.. method:: async_chat.collect_incoming_data(data)
@@ -92,7 +95,7 @@ connection requests.
.. method:: async_chat.discard_buffers()
In emergencies this method will discard any data held in the input and/or
- output buffers and the producer fifo.
+ output buffers and the producer queue.
.. method:: async_chat.found_terminator()
@@ -110,7 +113,7 @@ connection requests.
.. method:: async_chat.push(data)
- Pushes data on to the channel's fifo to ensure its transmission.
+ Pushes data on to the channel's queue to ensure its transmission.
This is all you need to do to have the channel write the data out to the
network, although it is possible to use your own producers in more complex
schemes to implement encryption and chunking, for example.
@@ -118,7 +121,7 @@ connection requests.
.. method:: async_chat.push_with_producer(producer)
- Takes a producer object and adds it to the producer fifo associated with
+ Takes a producer object and adds it to the producer queue associated with
the channel. When all currently-pushed producers have been exhausted the
channel will consume this producer's data by calling its :meth:`more`
method and send the data to the remote endpoint.
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index d720160..fa6a296 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -88,6 +88,24 @@ Run an event loop
This is idempotent and irreversible. No other methods should be called after
this one.
+
+.. coroutinemethod:: AbstractEventLoop.shutdown_asyncgens()
+
+ Schedule all currently open :term:`asynchronous generator` objects to
+ close with an :meth:`~agen.aclose()` call. After calling this method,
+ the event loop will issue a warning whenever a new asynchronous generator
+ is iterated. Should be used to finalize all scheduled asynchronous
+ generators reliably. Example::
+
+ try:
+ loop.run_forever()
+ finally:
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ loop.close()
+
+ .. versionadded:: 3.6
+
+
.. _asyncio-pass-keywords:
Calls
@@ -110,8 +128,9 @@ keywords to your callback, use :func:`functools.partial`. For example,
called after :meth:`call_soon` returns, when control returns to the event
loop.
- This operates as a FIFO queue, callbacks are called in the order in
- which they are registered. Each callback will be called exactly once.
+ This operates as a :abbr:`FIFO (first-in, first-out)` queue, callbacks
+ are called in the order in which they are registered. Each callback
+ will be called exactly once.
Any positional arguments after the callback will be passed to the
callback when it is called.
diff --git a/Doc/library/asyncio-protocol.rst b/Doc/library/asyncio-protocol.rst
index c0342f7..3fbf510 100644
--- a/Doc/library/asyncio-protocol.rst
+++ b/Doc/library/asyncio-protocol.rst
@@ -25,6 +25,9 @@ the transport's kind.
The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
+.. versionchanged:: 3.6
+ The socket option ``TCP_NODELAY`` is now set by default.
+
BaseTransport
-------------
diff --git a/Doc/library/asyncio.rst b/Doc/library/asyncio.rst
index 76bd9e9..b076b7d 100644
--- a/Doc/library/asyncio.rst
+++ b/Doc/library/asyncio.rst
@@ -8,13 +8,6 @@
**Source code:** :source:`Lib/asyncio/`
-.. note::
-
- The asyncio package has been included in the standard library on a
- :term:`provisional basis <provisional package>`. Backwards incompatible
- changes (up to and including removal of the module) may occur if deemed
- necessary by the core developers.
-
--------------
This module provides infrastructure for writing single-threaded concurrent
diff --git a/Doc/library/asyncore.rst b/Doc/library/asyncore.rst
index c838be7..11d3616 100644
--- a/Doc/library/asyncore.rst
+++ b/Doc/library/asyncore.rst
@@ -12,6 +12,9 @@
**Source code:** :source:`Lib/asyncore.py`
+.. deprecated:: 3.6
+ Please use :mod:`asyncio` instead.
+
--------------
.. note::
diff --git a/Doc/library/binascii.rst b/Doc/library/binascii.rst
index 49da59a..0476f50 100644
--- a/Doc/library/binascii.rst
+++ b/Doc/library/binascii.rst
@@ -53,13 +53,14 @@ The :mod:`binascii` module defines the following functions:
than one line may be passed at a time.
-.. function:: b2a_base64(data)
+.. function:: b2a_base64(data, \*, newline=True)
Convert binary data to a line of ASCII characters in base64 coding. The return
- value is the converted line, including a newline char. The newline is
- added because the original use case for this function was to feed it a
- series of 57 byte input lines to get output lines that conform to the
- MIME-base64 standard. Otherwise the output conforms to :rfc:`3548`.
+ value is the converted line, including a newline char if *newline* is
+ true. The output of this function conforms to :rfc:`3548`.
+
+ .. versionchanged:: 3.6
+ Added the *newline* parameter.
.. function:: a2b_qp(data, header=False)
diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst
index 6c49d9f..d5f6225 100644
--- a/Doc/library/bz2.rst
+++ b/Doc/library/bz2.rst
@@ -61,6 +61,9 @@ All of the classes in this module may safely be accessed from multiple threads.
.. versionchanged:: 3.4
The ``'x'`` (exclusive creation) mode was added.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. class:: BZ2File(filename, mode='r', buffering=None, compresslevel=9)
@@ -128,6 +131,9 @@ All of the classes in this module may safely be accessed from multiple threads.
The :meth:`~io.BufferedIOBase.read` method now accepts an argument of
``None``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
Incremental (de)compression
---------------------------
diff --git a/Doc/library/cmath.rst b/Doc/library/cmath.rst
index e113ffc..c819a66 100644
--- a/Doc/library/cmath.rst
+++ b/Doc/library/cmath.rst
@@ -253,6 +253,40 @@ Constants
The mathematical constant *e*, as a float.
+.. data:: tau
+
+ The mathematical constant *τ*, as a float.
+
+ .. versionadded:: 3.6
+
+.. data:: inf
+
+ Floating-point positive infinity. Equivalent to ``float('inf')``.
+
+ .. versionadded:: 3.6
+
+.. data:: infj
+
+ Complex number with zero real part and positive infinity imaginary
+ part. Equivalent to ``complex(0.0, float('inf'))``.
+
+ .. versionadded:: 3.6
+
+.. data:: nan
+
+ A floating-point "not a number" (NaN) value. Equivalent to
+ ``float('nan')``.
+
+ .. versionadded:: 3.6
+
+.. data:: nanj
+
+ Complex number with zero real part and NaN imaginary part. Equivalent to
+ ``complex(0.0, float('nan'))``.
+
+ .. versionadded:: 3.6
+
+
.. index:: module: math
Note that the selection of functions is similar, but not identical, to that in
@@ -276,5 +310,3 @@ cuts for numerical purposes, a good reference should be the following:
Kahan, W: Branch cuts for complex elementary functions; or, Much ado about
nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art
in numerical analysis. Clarendon Press (1987) pp165--211.
-
-
diff --git a/Doc/library/code.rst b/Doc/library/code.rst
index 443af69..e2c47ba 100644
--- a/Doc/library/code.rst
+++ b/Doc/library/code.rst
@@ -30,15 +30,19 @@ build applications which provide an interactive interpreter prompt.
``sys.ps1`` and ``sys.ps2``, and input buffering.
-.. function:: interact(banner=None, readfunc=None, local=None)
+.. function:: interact(banner=None, readfunc=None, local=None, exitmsg=None)
Convenience function to run a read-eval-print loop. This creates a new
instance of :class:`InteractiveConsole` and sets *readfunc* to be used as
the :meth:`InteractiveConsole.raw_input` method, if provided. If *local* is
provided, it is passed to the :class:`InteractiveConsole` constructor for
use as the default namespace for the interpreter loop. The :meth:`interact`
- method of the instance is then run with *banner* passed as the banner to
- use, if provided. The console object is discarded after use.
+ method of the instance is then run with *banner* and *exitmsg* passed as the
+ banner and exit message to use, if provided. The console object is discarded
+ after use.
+
+ .. versionchanged:: 3.6
+ Added *exitmsg* parameter.
.. function:: compile_command(source, filename="<input>", symbol="single")
@@ -136,7 +140,7 @@ The :class:`InteractiveConsole` class is a subclass of
interpreter objects as well as the following additions.
-.. method:: InteractiveConsole.interact(banner=None)
+.. method:: InteractiveConsole.interact(banner=None, exitmsg=None)
Closely emulate the interactive Python console. The optional *banner* argument
specify the banner to print before the first interaction; by default it prints a
@@ -144,9 +148,16 @@ interpreter objects as well as the following additions.
by the class name of the console object in parentheses (so as not to confuse
this with the real interpreter -- since it's so close!).
+ The optional *exitmsg* argument specifies an exit message printed when exiting.
+ Pass the empty string to suppress the exit message. If *exitmsg* is not given or
+ ``None``, a default message is printed.
+
.. versionchanged:: 3.4
To suppress printing any banner, pass an empty string.
+ .. versionchanged:: 3.6
+ Print an exit message when exiting.
+
.. method:: InteractiveConsole.push(line)
diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst
index f38e41b..0ecd89b 100644
--- a/Doc/library/codecs.rst
+++ b/Doc/library/codecs.rst
@@ -1263,10 +1263,16 @@ encodings.
| | | Only ``errors='strict'`` |
| | | is supported. |
+--------------------+---------+---------------------------+
-| mbcs | dbcs | Windows only: Encode |
-| | | operand according to the |
+| mbcs | ansi, | Windows only: Encode |
+| | dbcs | operand according to the |
| | | ANSI codepage (CP_ACP) |
+--------------------+---------+---------------------------+
+| oem | | Windows only: Encode |
+| | | operand according to the |
+| | | OEM codepage (CP_OEMCP) |
+| | | |
+| | | .. versionadded:: 3.6 |
++--------------------+---------+---------------------------+
| palmos | | Encoding of PalmOS 3.5 |
+--------------------+---------+---------------------------+
| punycode | | Implements :rfc:`3492`. |
diff --git a/Doc/library/collections.abc.rst b/Doc/library/collections.abc.rst
index aeb6a73..58b03b9 100644
--- a/Doc/library/collections.abc.rst
+++ b/Doc/library/collections.abc.rst
@@ -41,13 +41,16 @@ ABC Inherits from Abstract Methods Mixin
:class:`Hashable` ``__hash__``
:class:`Iterable` ``__iter__``
:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
+:class:`Reversible` :class:`Iterable` ``__reversed__``
:class:`Generator` :class:`Iterator` ``send``, ``throw`` ``close``, ``__iter__``, ``__next__``
:class:`Sized` ``__len__``
:class:`Callable` ``__call__``
+:class:`Collection` :class:`Sized`, ``__contains__``,
+ :class:`Iterable`, ``__iter__``,
+ :class:`Container` ``__len__``
-:class:`Sequence` :class:`Sized`, ``__getitem__``, ``__contains__``, ``__iter__``, ``__reversed__``,
- :class:`Iterable`, ``__len__`` ``index``, and ``count``
- :class:`Container`
+:class:`Sequence` :class:`Reversible`, ``__getitem__``, ``__contains__``, ``__iter__``, ``__reversed__``,
+ :class:`Collection` ``__len__`` ``index``, and ``count``
:class:`MutableSequence` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods and
``__setitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
@@ -58,9 +61,9 @@ ABC Inherits from Abstract Methods Mixin
:class:`ByteString` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods
``__len__``
-:class:`Set` :class:`Sized`, ``__contains__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
- :class:`Iterable`, ``__iter__``, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``,
- :class:`Container` ``__len__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
+:class:`Set` :class:`Collection` ``__contains__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
+ ``__iter__``, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``,
+ ``__len__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
:class:`MutableSet` :class:`Set` ``__contains__``, Inherited :class:`Set` methods and
``__iter__``, ``clear``, ``pop``, ``remove``, ``__ior__``,
@@ -68,9 +71,9 @@ ABC Inherits from Abstract Methods Mixin
``add``,
``discard``
-:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
- :class:`Iterable`, ``__iter__``, ``get``, ``__eq__``, and ``__ne__``
- :class:`Container` ``__len__``
+:class:`Mapping` :class:`Collection` ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
+ ``__iter__``, ``get``, ``__eq__``, and ``__ne__``
+ ``__len__``
:class:`MutableMapping` :class:`Mapping` ``__getitem__``, Inherited :class:`Mapping` methods and
``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
@@ -89,6 +92,7 @@ ABC Inherits from Abstract Methods Mixin
:class:`Coroutine` :class:`Awaitable` ``send``, ``throw`` ``close``
:class:`AsyncIterable` ``__aiter__``
:class:`AsyncIterator` :class:`AsyncIterable` ``__anext__`` ``__aiter__``
+:class:`AsyncGenerator` :class:`AsyncIterator` ``asend``, ``athrow`` ``aclose``, ``__aiter__``, ``__anext__``
========================== ====================== ======================= ====================================================
@@ -105,12 +109,25 @@ ABC Inherits from Abstract Methods Mixin
ABC for classes that provide the :meth:`__iter__` method.
See also the definition of :term:`iterable`.
+.. class:: Collection
+
+ ABC for sized iterable container classes.
+
+ .. versionadded:: 3.6
+
.. class:: Iterator
ABC for classes that provide the :meth:`~iterator.__iter__` and
:meth:`~iterator.__next__` methods. See also the definition of
:term:`iterator`.
+.. class:: Reversible
+
+ ABC for iterable classes that also provide the :meth:`__reversed__`
+ method.
+
+ .. versionadded:: 3.6
+
.. class:: Generator
ABC for generator classes that implement the protocol defined in
@@ -206,6 +223,13 @@ ABC Inherits from Abstract Methods Mixin
.. versionadded:: 3.5
+.. class:: AsyncGenerator
+
+ ABC for asynchronous generator classes that implement the protocol
+ defined in :pep:`525` and :pep:`492`.
+
+ .. versionadded:: 3.6
+
These ABCs allow us to ask classes or instances if they provide
particular functionality, for example::
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index d0aa62e..9f3f5dc 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -763,7 +763,7 @@ Named tuples assign meaning to each position in a tuple and allow for more reada
self-documenting code. They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.
-.. function:: namedtuple(typename, field_names, verbose=False, rename=False)
+.. function:: namedtuple(typename, field_names, *, verbose=False, rename=False, module=None)
Returns a new tuple subclass named *typename*. The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
@@ -790,12 +790,21 @@ they add the ability to access fields by name instead of position index.
built. This option is outdated; instead, it is simpler to print the
:attr:`_source` attribute.
+ If *module* is defined, the ``__module__`` attribute of the named tuple is
+ set to that value.
+
Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.
.. versionchanged:: 3.1
- Added support for *rename*.
+ Added support for *rename*.
+
+ .. versionchanged:: 3.6
+ The *verbose* and *rename* parameters became
+ :ref:`keyword-only arguments <keyword-only_parameter>`.
+ .. versionchanged:: 3.6
+ Added the *module* parameter.
.. doctest::
:options: +NORMALIZE_WHITESPACE
@@ -846,7 +855,9 @@ field names, the method and attribute names start with an underscore.
.. method:: somenamedtuple._asdict()
Return a new :class:`OrderedDict` which maps field names to their corresponding
- values::
+ values:
+
+ .. doctest::
>>> p = Point(x=11, y=22)
>>> p._asdict()
@@ -908,7 +919,9 @@ Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass. Here is how to add a calculated field and
a fixed-width print format:
- >>> class Point(namedtuple('Point', 'x y')):
+.. doctest::
+
+ >>> class Point(namedtuple('Point', ['x', 'y'])):
... __slots__ = ()
... @property
... def hypot(self):
@@ -959,6 +972,11 @@ customize a prototype instance:
constructor that is convenient for use cases where named tuples are being
subclassed.
+ * See :meth:`types.SimpleNamespace` for a mutable namespace based on an
+ underlying dictionary instead of a tuple.
+
+ * See :meth:`typing.NamedTuple` for a way to add type hints for named tuples.
+
:class:`OrderedDict` objects
----------------------------
@@ -980,8 +998,9 @@ the items are returned in the order their keys were first added.
.. method:: popitem(last=True)
The :meth:`popitem` method for ordered dictionaries returns and removes a
- (key, value) pair. The pairs are returned in LIFO order if *last* is true
- or FIFO order if false.
+ (key, value) pair. The pairs are returned in
+ :abbr:`LIFO (last-in, first-out)` order if *last* is true
+ or :abbr:`FIFO (first-in, first-out)` order if false.
.. method:: move_to_end(key, last=True)
diff --git a/Doc/library/compileall.rst b/Doc/library/compileall.rst
index 511c581..c1af02b 100644
--- a/Doc/library/compileall.rst
+++ b/Doc/library/compileall.rst
@@ -102,7 +102,8 @@ Public functions
.. function:: compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1)
Recursively descend the directory tree named by *dir*, compiling all :file:`.py`
- files along the way.
+ files along the way. Return a true value if all the files compiled successfully,
+ and a false value otherwise.
The *maxlevels* parameter is used to limit the depth of the recursion; it
defaults to ``10``.
@@ -152,9 +153,13 @@ Public functions
The *legacy* parameter only writes out ``.pyc`` files, not ``.pyo`` files
no matter what the value of *optimize* is.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1)
- Compile the file with path *fullname*.
+ Compile the file with path *fullname*. Return a true value if the file
+ compiled successfully, and a false value otherwise.
If *ddir* is given, it is prepended to the path to the file being compiled
for use in compilation time tracebacks, and is also compiled in to the
@@ -190,8 +195,10 @@ Public functions
.. function:: compile_path(skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1)
- Byte-compile all the :file:`.py` files found along ``sys.path``. If
- *skip_curdir* is true (the default), the current directory is not included
+ Byte-compile all the :file:`.py` files found along ``sys.path``. Return a
+ true value if all the files compiled successfully, and a false value otherwise.
+
+ If *skip_curdir* is true (the default), the current directory is not included
in the search. All other parameters are passed to the :func:`compile_dir`
function. Note that unlike the other compile functions, ``maxlevels``
defaults to ``0``.
@@ -217,6 +224,9 @@ subdirectory and all its subdirectories::
import re
compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)
+ # pathlib.Path objects can also be used.
+ import pathlib
+ compileall.compile_dir(pathlib.Path('Lib/'), force=True)
.. seealso::
diff --git a/Doc/library/concurrent.futures.rst b/Doc/library/concurrent.futures.rst
index ae03f4b..d85576b 100644
--- a/Doc/library/concurrent.futures.rst
+++ b/Doc/library/concurrent.futures.rst
@@ -124,7 +124,7 @@ And::
executor.submit(wait_on_future)
-.. class:: ThreadPoolExecutor(max_workers=None)
+.. class:: ThreadPoolExecutor(max_workers=None, thread_name_prefix='')
An :class:`Executor` subclass that uses a pool of at most *max_workers*
threads to execute calls asynchronously.
@@ -137,6 +137,10 @@ And::
should be higher than the number of workers
for :class:`ProcessPoolExecutor`.
+ .. versionadded:: 3.6
+ The *thread_name_prefix* argument was added to allow users to
+ control the threading.Thread names for worker threads created by
+ the pool for easier debugging.
.. _threadpoolexecutor-example:
diff --git a/Doc/library/constants.rst b/Doc/library/constants.rst
index d5a0f09..f0742ce 100644
--- a/Doc/library/constants.rst
+++ b/Doc/library/constants.rst
@@ -33,16 +33,22 @@ A small number of constants live in the built-in namespace. They are:
(e.g. :meth:`__imul__`, :meth:`__iand__`, etc.) for the same purpose.
Its truth value is true.
-.. note::
+ .. note::
+
+ When a binary (or in-place) method returns ``NotImplemented`` the
+ interpreter will try the reflected operation on the other type (or some
+ other fallback, depending on the operator). If all attempts return
+ ``NotImplemented``, the interpreter will raise an appropriate exception.
+ Incorrectly returning ``NotImplemented`` will result in a misleading
+ error message or the ``NotImplemented`` value being returned to Python code.
+
+ See :ref:`implementing-the-arithmetic-operations` for examples.
- When ``NotImplemented`` is returned, the interpreter will then try the
- reflected operation on the other type, or some other fallback, depending
- on the operator. If all attempted operations return ``NotImplemented``, the
- interpreter will raise an appropriate exception.
+ .. note::
- See
- :ref:`implementing-the-arithmetic-operations`
- for more details.
+ ``NotImplentedError`` and ``NotImplemented`` are not interchangeable,
+ even though they have similar names and purposes.
+ See :exc:`NotImplementedError` for details on when to use it.
.. data:: Ellipsis
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst
index cf85fcd..dd34c96 100644
--- a/Doc/library/contextlib.rst
+++ b/Doc/library/contextlib.rst
@@ -18,6 +18,18 @@ Utilities
Functions and classes provided:
+.. class:: AbstractContextManager
+
+ An :term:`abstract base class` for classes that implement
+ :meth:`object.__enter__` and :meth:`object.__exit__`. A default
+ implementation for :meth:`object.__enter__` is provided which returns
+ ``self`` while :meth:`object.__exit__` is an abstract method which by default
+ returns ``None``. See also the definition of :ref:`typecontextmanager`.
+
+ .. versionadded:: 3.6
+
+
+
.. decorator:: contextmanager
This function is a :term:`decorator` that can be used to define a factory
@@ -447,9 +459,9 @@ Here's an example of doing this for a context manager that accepts resource
acquisition and release functions, along with an optional validation function,
and maps them to the context management protocol::
- from contextlib import contextmanager, ExitStack
+ from contextlib import contextmanager, AbstractContextManager, ExitStack
- class ResourceManager:
+ class ResourceManager(AbstractContextManager):
def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
self.acquire_resource = acquire_resource
@@ -578,10 +590,10 @@ single definition::
self.name = name
def __enter__(self):
- logging.info('Entering: {}'.format(self.name))
+ logging.info('Entering: %s', self.name)
def __exit__(self, exc_type, exc, exc_tb):
- logging.info('Exiting: {}'.format(self.name))
+ logging.info('Exiting: %s', self.name)
Instances of this class can be used as both a context manager::
diff --git a/Doc/library/crypt.rst b/Doc/library/crypt.rst
index a21c1e7..dbd4274 100644
--- a/Doc/library/crypt.rst
+++ b/Doc/library/crypt.rst
@@ -68,7 +68,7 @@ Module Attributes
A list of available password hashing algorithms, as
``crypt.METHOD_*`` objects. This list is sorted from strongest to
- weakest, and is guaranteed to have at least ``crypt.METHOD_CRYPT``.
+ weakest.
Module Functions
diff --git a/Doc/library/crypto.rst b/Doc/library/crypto.rst
index 1eddfdc..8eb4b81 100644
--- a/Doc/library/crypto.rst
+++ b/Doc/library/crypto.rst
@@ -15,4 +15,6 @@ Here's an overview:
.. toctree::
hashlib.rst
+ hashlib-blake2.rst
hmac.rst
+ secrets.rst
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 7fb4fc8..f916572 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -149,18 +149,25 @@ The :mod:`csv` module defines the following classes:
.. class:: DictReader(csvfile, fieldnames=None, restkey=None, restval=None, \
dialect='excel', *args, **kwds)
- Create an object which operates like a regular reader but maps the
- information read into a dict whose keys are given by the optional
- *fieldnames* parameter. The *fieldnames* parameter is a :mod:`sequence
- <collections.abc>` whose elements are associated with the fields of the
- input data in order. These elements become the keys of the resulting
- dictionary. If the *fieldnames* parameter is omitted, the values in the
- first row of the *csvfile* will be used as the fieldnames. If the row read
- has more fields than the fieldnames sequence, the remaining data is added as
- a sequence keyed by the value of *restkey*. If the row read has fewer
- fields than the fieldnames sequence, the remaining keys take the value of
- the optional *restval* parameter. Any other optional or keyword arguments
- are passed to the underlying :class:`reader` instance.
+ Create an object that operates like a regular reader but maps the
+ information in each row to an :mod:`OrderedDict <collections.OrderedDict>`
+ whose keys are given by the optional *fieldnames* parameter.
+
+ The *fieldnames* parameter is a :term:`sequence`. If *fieldnames* is
+ omitted, the values in the first row of the *csvfile* will be used as the
+ fieldnames. Regardless of how the fieldnames are determined, the ordered
+ dictionary preserves their original ordering.
+
+ If a row has more fields than fieldnames, the remaining data is put in a
+ list and stored with the fieldname specified by *restkey* (which defaults
+ to ``None``). If a non-blank row has fewer fields than fieldnames, the
+ missing values are filled-in with ``None``.
+
+ All other optional or keyword arguments are passed to the underlying
+ :class:`reader` instance.
+
+ .. versionchanged:: 3.6
+ Returned rows are now of type :class:`OrderedDict`.
A short usage example::
@@ -170,9 +177,11 @@ The :mod:`csv` module defines the following classes:
... for row in reader:
... print(row['first_name'], row['last_name'])
...
- Baked Beans
- Lovely Spam
- Wonderful Spam
+ Eric Idle
+ John Cleese
+
+ >>> print(row)
+ OrderedDict([('first_name', 'John'), ('last_name', 'Cleese')])
.. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \
@@ -186,10 +195,12 @@ The :mod:`csv` module defines the following classes:
written if the dictionary is missing a key in *fieldnames*. If the
dictionary passed to the :meth:`writerow` method contains a key not found in
*fieldnames*, the optional *extrasaction* parameter indicates what action to
- take. If it is set to ``'raise'`` a :exc:`ValueError` is raised. If it is
- set to ``'ignore'``, extra values in the dictionary are ignored. Any other
- optional or keyword arguments are passed to the underlying :class:`writer`
- instance.
+ take.
+ If it is set to ``'raise'``, the default value, a :exc:`ValueError`
+ is raised.
+ If it is set to ``'ignore'``, extra values in the dictionary are ignored.
+ Any other optional or keyword arguments are passed to the underlying
+ :class:`writer` instance.
Note that unlike the :class:`DictReader` class, the *fieldnames* parameter
of the :class:`DictWriter` is not optional. Since Python's :class:`dict`
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index b25fbbb..3840935 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -1239,9 +1239,10 @@ When programming in a compiled language, shared libraries are accessed when
compiling/linking a program, and when the program is run.
The purpose of the :func:`find_library` function is to locate a library in a way
-similar to what the compiler does (on platforms with several versions of a
-shared library the most recent should be loaded), while the ctypes library
-loaders act like when a program is run, and call the runtime loader directly.
+similar to what the compiler or runtime loader does (on platforms with several
+versions of a shared library the most recent should be loaded), while the ctypes
+library loaders act like when a program is run, and call the runtime loader
+directly.
The :mod:`ctypes.util` module provides a function which can help to determine
the library to load.
@@ -1259,8 +1260,14 @@ the library to load.
The exact functionality is system dependent.
On Linux, :func:`find_library` tries to run external programs
-(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
-returns the filename of the library file. Here are some examples::
+(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file.
+It returns the filename of the library file.
+
+.. versionchanged:: 3.6
+ On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used
+ when searching for libraries, if a library cannot be found by any other means.
+
+Here are some examples::
>>> from ctypes.util import find_library
>>> find_library("m")
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 4f3cfe3..c931855 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -522,7 +522,7 @@ objects are considered to be true.
Instance methods:
-.. method:: date.replace(year, month, day)
+.. method:: date.replace(year=self.year, month=self.month, day=self.day)
Return a date with the same value, except for those parameters given new
values by whichever keyword arguments are specified. For example, if ``d ==
@@ -610,7 +610,8 @@ Instance methods:
.. method:: date.__format__(format)
Same as :meth:`.date.strftime`. This makes it possible to specify a format
- string for a :class:`.date` object when using :meth:`str.format`. For a
+ string for a :class:`.date` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -682,22 +683,26 @@ both directions; like a time object, :class:`.datetime` assumes there are exactl
Constructor:
-.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
+.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
The year, month and day arguments are required. *tzinfo* may be ``None``, or an
instance of a :class:`tzinfo` subclass. The remaining arguments may be integers,
in the following ranges:
- * ``MINYEAR <= year <= MAXYEAR``
- * ``1 <= month <= 12``
- * ``1 <= day <= number of days in the given month and year``
- * ``0 <= hour < 24``
- * ``0 <= minute < 60``
- * ``0 <= second < 60``
- * ``0 <= microsecond < 1000000``
+ * ``MINYEAR <= year <= MAXYEAR``,
+ * ``1 <= month <= 12``,
+ * ``1 <= day <= number of days in the given month and year``,
+ * ``0 <= hour < 24``,
+ * ``0 <= minute < 60``,
+ * ``0 <= second < 60``,
+ * ``0 <= microsecond < 1000000``,
+ * ``fold in [0, 1]``.
If an argument outside those ranges is given, :exc:`ValueError` is raised.
+ .. versionadded:: 3.6
+ Added the ``fold`` argument.
+
Other constructors, all class methods:
.. classmethod:: datetime.today()
@@ -757,6 +762,8 @@ Other constructors, all class methods:
instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime`
failure.
+ .. versionchanged:: 3.6
+ :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1.
.. classmethod:: datetime.utcfromtimestamp(timestamp)
@@ -793,16 +800,23 @@ Other constructors, all class methods:
microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
-.. classmethod:: datetime.combine(date, time)
+.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo)
Return a new :class:`.datetime` object whose date components are equal to the
- given :class:`date` object's, and whose time components and :attr:`.tzinfo`
- attributes are equal to the given :class:`.time` object's. For any
- :class:`.datetime` object *d*,
- ``d == datetime.combine(d.date(), d.timetz())``. If date is a
+ given :class:`date` object's, and whose time components
+ are equal to the given :class:`.time` object's. If the *tzinfo*
+ argument is provided, its value is used to set the :attr:`.tzinfo` attribute
+ of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument
+ is used.
+
+ For any :class:`.datetime` object *d*,
+ ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a
:class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
are ignored.
+ .. versionchanged:: 3.6
+ Added the *tzinfo* argument.
+
.. classmethod:: datetime.strptime(date_string, format)
@@ -878,6 +892,16 @@ Instance attributes (read-only):
or ``None`` if none was passed.
+.. attribute:: datetime.fold
+
+ In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
+ repeated interval occurs when clocks are rolled back at the end of daylight saving
+ time or when the UTC offset for the current zone is decreased for political reasons.)
+ The value 0 (1) represents the earlier (later) of the two moments with the same wall
+ time representation.
+
+ .. versionadded:: 3.6
+
Supported operations:
+---------------------------------------+--------------------------------+
@@ -966,23 +990,34 @@ Instance methods:
.. method:: datetime.time()
- Return :class:`.time` object with same hour, minute, second and microsecond.
+ Return :class:`.time` object with same hour, minute, second, microsecond and fold.
:attr:`.tzinfo` is ``None``. See also method :meth:`timetz`.
+ .. versionchanged:: 3.6
+ The fold value is copied to the returned :class:`.time` object.
+
.. method:: datetime.timetz()
- Return :class:`.time` object with same hour, minute, second, microsecond, and
+ Return :class:`.time` object with same hour, minute, second, microsecond, fold, and
tzinfo attributes. See also method :meth:`time`.
+ .. versionchanged:: 3.6
+ The fold value is copied to the returned :class:`.time` object.
-.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
+
+.. 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)
Return a datetime with the same attributes, except for those attributes given
new values by whichever keyword arguments are specified. Note that
``tzinfo=None`` can be specified to create a naive datetime from an aware
datetime with no conversion of date and time data.
+ .. versionadded:: 3.6
+ Added the ``fold`` argument.
+
.. method:: datetime.astimezone(tz=None)
@@ -991,23 +1026,20 @@ Instance methods:
*self*, but in *tz*'s local time.
If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its
- :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
- be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
- not return ``None``).
+ :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self*
+ is naive (``self.tzinfo is None``), it is presumed to represent time in the
+ system timezone.
If called without arguments (or with ``tz=None``) the system local
- timezone is assumed. The ``.tzinfo`` attribute of the converted
+ timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted
datetime instance will be set to an instance of :class:`timezone`
with the zone name and offset obtained from the OS.
If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
adjustment of date or time data is performed. Else the result is local
- time in time zone *tz*, representing the same UTC time as *self*: after
- ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
- the same date and time data as ``dt - dt.utcoffset()``. The discussion
- of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
- boundaries where this cannot be achieved (an issue only if *tz* models both
- standard and daylight time).
+ time in the timezone *tz*, representing the same UTC time as *self*: after
+ ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have
+ the same date and time data as ``dt - dt.utcoffset()``.
If you merely want to attach a time zone object *tz* to a datetime *dt* without
adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
@@ -1029,6 +1061,10 @@ Instance methods:
.. versionchanged:: 3.3
*tz* now can be omitted.
+ .. versionchanged:: 3.6
+ The :meth:`astimezone` method can now be called on naive instances that
+ are presumed to represent system local time.
+
.. method:: datetime.utcoffset()
@@ -1105,6 +1141,10 @@ Instance methods:
.. versionadded:: 3.3
+ .. versionchanged:: 3.6
+ The :meth:`timestamp` method uses the :attr:`.fold` attribute to
+ disambiguate the times during a repeated interval.
+
.. note::
There is no method to obtain the POSIX timestamp directly from a
@@ -1138,7 +1178,7 @@ Instance methods:
``self.date().isocalendar()``.
-.. method:: datetime.isoformat(sep='T')
+.. method:: datetime.isoformat(sep='T', timespec='auto')
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
@@ -1159,6 +1199,37 @@ Instance methods:
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
+ The optional argument *timespec* specifies the number of additional
+ components of the time to include (the default is ``'auto'``).
+ It can be one of the following:
+
+ - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
+ same as ``'microseconds'`` otherwise.
+ - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
+ - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
+ - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
+ in HH:MM:SS format.
+ - ``'milliseconds'``: Include full time, but truncate fractional second
+ part to milliseconds. HH:MM:SS.sss format.
+ - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
+
+ .. note::
+
+ Excluded time components are truncated, not rounded.
+
+ :exc:`ValueError` will be raised on an invalid *timespec* argument.
+
+
+ >>> from datetime import datetime
+ >>> datetime.now().isoformat(timespec='minutes')
+ '2002-12-25T00:00'
+ >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
+ >>> dt.isoformat(timespec='microseconds')
+ '2015-01-01T12:30:59.000000'
+
+ .. versionadded:: 3.6
+ Added the *timespec* argument.
+
.. method:: datetime.__str__()
@@ -1185,7 +1256,8 @@ Instance methods:
.. method:: datetime.__format__(format)
Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
- string for a :class:`.datetime` object when using :meth:`str.format`. For a
+ string for a :class:`.datetime` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -1302,16 +1374,17 @@ Using datetime with tzinfo:
A time object represents a (local) time of day, independent of any particular
day, and subject to adjustment via a :class:`tzinfo` object.
-.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
+.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
All arguments are optional. *tzinfo* may be ``None``, or an instance of a
:class:`tzinfo` subclass. The remaining arguments may be integers, in the
following ranges:
- * ``0 <= hour < 24``
- * ``0 <= minute < 60``
- * ``0 <= second < 60``
- * ``0 <= microsecond < 1000000``.
+ * ``0 <= hour < 24``,
+ * ``0 <= minute < 60``,
+ * ``0 <= second < 60``,
+ * ``0 <= microsecond < 1000000``,
+ * ``fold in [0, 1]``.
If an argument outside those ranges is given, :exc:`ValueError` is raised. All
default to ``0`` except *tzinfo*, which defaults to :const:`None`.
@@ -1364,6 +1437,17 @@ Instance attributes (read-only):
``None`` if none was passed.
+.. attribute:: time.fold
+
+ In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A
+ repeated interval occurs when clocks are rolled back at the end of daylight saving
+ time or when the UTC offset for the current zone is decreased for political reasons.)
+ The value 0 (1) represents the earlier (later) of the two moments with the same wall
+ time representation.
+
+ .. versionadded:: 3.6
+
+
Supported operations:
* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
@@ -1399,21 +1483,58 @@ In boolean contexts, a :class:`.time` object is always considered to be true.
Instance methods:
-.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
+.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \
+ 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
``tzinfo=None`` can be specified to create a naive :class:`.time` from an
aware :class:`.time`, without conversion of the time data.
+ .. versionadded:: 3.6
+ Added the ``fold`` argument.
+
-.. method:: time.isoformat()
+.. method:: time.isoformat(timespec='auto')
Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
- self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
+ :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
6-character string is appended, giving the UTC offset in (signed) hours and
minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
+ The optional argument *timespec* specifies the number of additional
+ components of the time to include (the default is ``'auto'``).
+ It can be one of the following:
+
+ - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
+ same as ``'microseconds'`` otherwise.
+ - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
+ - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
+ - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
+ in HH:MM:SS format.
+ - ``'milliseconds'``: Include full time, but truncate fractional second
+ part to milliseconds. HH:MM:SS.sss format.
+ - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
+
+ .. note::
+
+ Excluded time components are truncated, not rounded.
+
+ :exc:`ValueError` will be raised on an invalid *timespec* argument.
+
+
+ >>> from datetime import time
+ >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
+ '12:34'
+ >>> dt = time(hour=12, minute=34, second=56, microsecond=0)
+ >>> dt.isoformat(timespec='microseconds')
+ '12:34:56.000000'
+ >>> dt.isoformat(timespec='auto')
+ '12:34:56'
+
+ .. versionadded:: 3.6
+ Added the *timespec* argument.
+
.. method:: time.__str__()
@@ -1430,7 +1551,8 @@ Instance methods:
.. method:: time.__format__(format)
Same as :meth:`.time.strftime`. This makes it possible to specify a format string
- for a :class:`.time` object when using :meth:`str.format`. For a
+ for a :class:`.time` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -1680,9 +1802,19 @@ minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
When DST starts (the "start" line), the local wall clock leaps from 1:59 to
3:00. A wall time of the form 2:MM doesn't really make sense on that day, so
``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
-begins. In order for :meth:`astimezone` to make this guarantee, the
-:meth:`tzinfo.dst` method must consider times in the "missing hour" (2:MM for
-Eastern) to be in daylight time.
+begins. For example, at the Spring forward transition of 2016, we get
+
+ >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
+ >>> for i in range(4):
+ ... u = u0 + i*HOUR
+ ... t = u.astimezone(Eastern)
+ ... print(u.time(), 'UTC =', t.time(), t.tzname())
+ ...
+ 05:00:00 UTC = 00:00:00 EST
+ 06:00:00 UTC = 01:00:00 EST
+ 07:00:00 UTC = 03:00:00 EDT
+ 08:00:00 UTC = 04:00:00 EDT
+
When DST ends (the "end" line), there's a potentially worse problem: there's an
hour that can't be spelled unambiguously in local wall time: the last hour of
@@ -1691,28 +1823,41 @@ daylight time ends. The local wall clock leaps from 1:59 (daylight time) back
to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
hours into the same local hour then. In the Eastern example, UTC times of the
-form 5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for
-:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
-consider times in the "repeated hour" to be in standard time. This is easily
-arranged, as in the example, by expressing DST switch times in the time zone's
-standard local time.
+form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times
+have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1.
+For example, at the Fall back transition of 2016, we get
+
+ >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
+ >>> for i in range(4):
+ ... u = u0 + i*HOUR
+ ... t = u.astimezone(Eastern)
+ ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
+ ...
+ 04:00:00 UTC = 00:00:00 EDT 0
+ 05:00:00 UTC = 01:00:00 EDT 0
+ 06:00:00 UTC = 01:00:00 EST 1
+ 07:00:00 UTC = 02:00:00 EST 0
+
+Note that the :class:`datetime` instances that differ only by the value of the
+:attr:`~datetime.fold` attribute are considered equal in comparisons.
-Applications that can't bear such ambiguities should avoid using hybrid
+Applications that can't bear wall-time ambiguities should explicitly check the
+value of the :attr:`~datetime.fold` attribute or avoid using hybrid
:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
.. seealso::
- `pytz <https://pypi.python.org/pypi/pytz/>`_
+ `datetuil.tz <https://dateutil.readthedocs.io/en/stable/tz.html>`_
The standard library has :class:`timezone` class for handling arbitrary
fixed offsets from UTC and :attr:`timezone.utc` as UTC timezone instance.
- *pytz* library brings the *IANA timezone database* (also known as the
+ *datetuil.tz* library brings the *IANA timezone database* (also known as the
Olson database) to Python and its usage is recommended.
`IANA timezone database <https://www.iana.org/time-zones>`_
- The Time Zone Database (often called tz or zoneinfo) contains code and
+ The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and
data that represent the history of local time for many representative
locations around the globe. It is updated periodically to reflect changes
made by political bodies to time zone boundaries, UTC offsets, and
@@ -1732,7 +1877,7 @@ in different days of the year or where historical changes have been
made to civil time.
-.. class:: timezone(offset[, name])
+.. class:: timezone(offset, name=None)
The *offset* argument must be specified as a :class:`timedelta`
object representing the difference between the local time and UTC. It must
@@ -1741,10 +1886,7 @@ made to civil time.
otherwise :exc:`ValueError` is raised.
The *name* argument is optional. If specified it must be a string that
- is used as the value returned by the ``tzname(dt)`` method. Otherwise,
- ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
- *offset*, HH and MM are two digits of ``offset.hours`` and
- ``offset.minutes`` respectively.
+ will be used as the value returned by the :meth:`datetime.tzname` method.
.. versionadded:: 3.2
@@ -1757,11 +1899,19 @@ made to civil time.
.. method:: timezone.tzname(dt)
- Return the fixed value specified when the :class:`timezone` instance is
- constructed or a string 'UTCsHH:MM', where s is the sign of
- *offset*, HH and MM are two digits of ``offset.hours`` and
+ Return the fixed value specified when the :class:`timezone` instance
+ is constructed. If *name* is not provided in the constructor, the
+ name returned by ``tzname(dt)`` is generated from the value of the
+ ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
+ is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
+ of ``offset``, HH and MM are two digits of ``offset.hours`` and
``offset.minutes`` respectively.
+ .. versionchanged:: 3.6
+ Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
+ 'UTC+00:00'.
+
+
.. method:: timezone.dst(dt)
Always returns ``None``.
@@ -1911,6 +2061,34 @@ format codes.
| ``%%`` | A literal ``'%'`` character. | % | |
+-----------+--------------------------------+------------------------+-------+
+Several additional directives not required by the C89 standard are included for
+convenience. These parameters all correspond to ISO 8601 date values. These
+may not be available on all platforms when used with the :meth:`strftime`
+method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
+with the year and week number directives above. Calling :meth:`strptime` with
+incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
+
++-----------+--------------------------------+------------------------+-------+
+| Directive | Meaning | Example | Notes |
++===========+================================+========================+=======+
+| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
+| | representing the year that | 2014, ..., 9998, 9999 | |
+| | contains the greater part of | | |
+| | the ISO week (``%V``). | | |
++-----------+--------------------------------+------------------------+-------+
+| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
+| | number where 1 is Monday. | | |
++-----------+--------------------------------+------------------------+-------+
+| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
+| | number with Monday as | | |
+| | the first day of the week. | | |
+| | Week 01 is the week containing | | |
+| | Jan 4. | | |
++-----------+--------------------------------+------------------------+-------+
+
+.. versionadded:: 3.6
+ ``%G``, ``%u`` and ``%V`` were added.
+
Notes:
(1)
@@ -1975,7 +2153,14 @@ Notes:
(7)
When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
- in calculations when the day of the week and the year are specified.
+ in calculations when the day of the week and the calendar year (``%Y``)
+ are specified.
+
+(8)
+ Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
+ day of the week and the ISO year (``%G``) are specified in a
+ :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
+ interchangeable.
.. rubric:: Footnotes
diff --git a/Doc/library/dbm.rst b/Doc/library/dbm.rst
index 2a1db91..32e80b2 100644
--- a/Doc/library/dbm.rst
+++ b/Doc/library/dbm.rst
@@ -351,6 +351,10 @@ The module defines the following:
:func:`.open` always creates a new database when the flag has the value
``'n'``.
+ .. deprecated-removed:: 3.6 3.8
+ Creating database in ``'r'`` and ``'w'`` modes. Modifying database in
+ ``'r'`` mode.
+
In addition to the methods provided by the
:class:`collections.abc.MutableMapping` class, :class:`dumbdbm` objects
provide the following methods:
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index b5ce0b1..e984edc 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -345,7 +345,7 @@ Decimal objects
*value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
string, it should conform to the decimal numeric string syntax after leading
- and trailing whitespace characters are removed::
+ and trailing whitespace characters, as well as underscores throughout, are removed::
sign ::= '+' | '-'
digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
@@ -394,6 +394,10 @@ Decimal objects
:class:`float` arguments raise an exception if the :exc:`FloatOperation`
trap is set. By default the trap is off.
+ .. versionchanged:: 3.6
+ Underscores are allowed for grouping, as with integral and floating-point
+ literals in code.
+
Decimal floating point objects share many properties with the other built-in
numeric types such as :class:`float` and :class:`int`. All of the usual math
operations and special methods apply. Likewise, decimal objects can be
@@ -447,6 +451,19 @@ Decimal objects
``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
position of the most significant digit with respect to the decimal point.
+ .. method:: as_integer_ratio()
+
+ Return a pair ``(n, d)`` of integers that represent the given
+ :class:`Decimal` instance as a fraction, in lowest terms and
+ with a positive denominator::
+
+ >>> Decimal('-3.14').as_integer_ratio()
+ (-157, 50)
+
+ The conversion is exact. Raise OverflowError on infinities and ValueError
+ on NaNs.
+
+ .. versionadded:: 3.6
.. method:: as_tuple()
@@ -1062,8 +1079,8 @@ In addition to the three supplied contexts, new contexts can be created with the
Decimal('4.44')
This method implements the to-number operation of the IBM specification.
- If the argument is a string, no leading or trailing whitespace is
- permitted.
+ If the argument is a string, no leading or trailing whitespace or
+ underscores are permitted.
.. method:: create_decimal_from_float(f)
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index f86725b..a15690b 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -31,9 +31,9 @@ the following command can be used to display the disassembly of
>>> dis.dis(myfunc)
2 0 LOAD_GLOBAL 0 (len)
- 3 LOAD_FAST 0 (alist)
- 6 CALL_FUNCTION 1
- 9 RETURN_VALUE
+ 2 LOAD_FAST 0 (alist)
+ 4 CALL_FUNCTION 1
+ 6 RETURN_VALUE
(The "2" is a line number).
@@ -607,6 +607,14 @@ iterations of the loop.
.. versionadded:: 3.3
+.. opcode:: SETUP_ANNOTATIONS
+
+ Checks whether ``__annotations__`` is defined in ``locals()``, if not it is
+ set up to an empty ``dict``. This opcode is only emitted if a class
+ or module body contains :term:`variable annotations <variable annotation>`
+ statically.
+
+ .. versionadded:: 3.6
.. opcode:: IMPORT_STAR
@@ -682,8 +690,7 @@ iterations of the loop.
.. XXX explain the WHY stuff!
-All of the following opcodes expect arguments. An argument is two bytes, with
-the more significant byte last.
+All of the following opcodes use their arguments.
.. opcode:: STORE_NAME (namei)
@@ -769,6 +776,23 @@ the more significant byte last.
to hold *count* entries.
+.. opcode:: BUILD_CONST_KEY_MAP (count)
+
+ The version of :opcode:`BUILD_MAP` specialized for constant keys. *count*
+ values are consumed from the stack. The top element on the stack contains
+ a tuple of keys.
+
+ .. versionadded:: 3.6
+
+
+.. opcode:: BUILD_STRING (count)
+
+ Concatenates *count* strings from the stack and pushes the resulting string
+ onto the stack.
+
+ .. versionadded:: 3.6
+
+
.. opcode:: LOAD_ATTR (namei)
Replaces TOS with ``getattr(TOS, co_names[namei])``.
@@ -874,6 +898,13 @@ the more significant byte last.
Deletes local ``co_varnames[var_num]``.
+.. opcode:: STORE_ANNOTATION (namei)
+
+ Stores TOS as ``locals()['__annotations__'][co_names[namei]] = TOS``.
+
+ .. versionadded:: 3.6
+
+
.. opcode:: LOAD_CLOSURE (i)
Pushes a reference to the cell contained in slot *i* of the cell and free
@@ -929,27 +960,16 @@ the more significant byte last.
.. opcode:: MAKE_FUNCTION (argc)
Pushes a new function object on the stack. From bottom to top, the consumed
- stack must consist of
-
- * ``argc & 0xFF`` default argument objects in positional order
- * ``(argc >> 8) & 0xFF`` pairs of name and default argument, with the name
- just below the object on the stack, for keyword-only parameters
- * ``(argc >> 16) & 0x7FFF`` parameter annotation objects
- * a tuple listing the parameter names for the annotations (only if there are
- ony annotation objects)
+ stack must consist of values if the argument carries a specified flag value
+
+ * ``0x01`` a tuple of default argument objects in positional order
+ * ``0x02`` a dictionary of keyword-only parameters' default values
+ * ``0x04`` an annotation dictionary
+ * ``0x08`` a tuple containing cells for free variables, making a closure
* the code associated with the function (at TOS1)
* the :term:`qualified name` of the function (at TOS)
-.. opcode:: MAKE_CLOSURE (argc)
-
- Creates a new function object, sets its *__closure__* slot, and pushes it on
- the stack. TOS is the :term:`qualified name` of the function, TOS1 is the
- code associated with the function, and TOS2 is the tuple containing cells for
- the closure's free variables. *argc* is interpreted as in ``MAKE_FUNCTION``;
- the annotations and defaults are also in the same order below TOS2.
-
-
.. opcode:: BUILD_SLICE (argc)
.. index:: builtin: slice
@@ -989,6 +1009,28 @@ the more significant byte last.
arguments.
+.. opcode:: FORMAT_VALUE (flags)
+
+ Used for implementing formatted literal strings (f-strings). Pops
+ an optional *fmt_spec* from the stack, then a required *value*.
+ *flags* is interpreted as follows:
+
+ * ``(flags & 0x03) == 0x00``: *value* is formatted as-is.
+ * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before
+ formatting it.
+ * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before
+ formatting it.
+ * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before
+ formatting it.
+ * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use
+ it, else use an empty *fmt_spec*.
+
+ Formatting is performed using :c:func:`PyObject_Format`. The
+ result is pushed on the stack.
+
+ .. versionadded:: 3.6
+
+
.. opcode:: HAVE_ARGUMENT
This is not really an opcode. It identifies the dividing line between
diff --git a/Doc/library/email.charset.rst b/Doc/library/email.charset.rst
index 161d86a..053463f 100644
--- a/Doc/library/email.charset.rst
+++ b/Doc/library/email.charset.rst
@@ -8,6 +8,11 @@
--------------
+This module is part of the legacy (``Compat32``) email API. In the new
+API only the aliases table is used.
+
+The remaining text in this section is the original documentation of the module.
+
This module provides a class :class:`Charset` for representing character sets
and character set conversions in email messages, as well as a character set
registry and several convenience methods for manipulating this registry.
diff --git a/Doc/library/email.compat32-message.rst b/Doc/library/email.compat32-message.rst
new file mode 100644
index 0000000..2c65079
--- /dev/null
+++ b/Doc/library/email.compat32-message.rst
@@ -0,0 +1,754 @@
+.. _compat32_message:
+
+:mod:`email.message.Message`: Representing an email message using the :data:`~email.policy.compat32` API
+--------------------------------------------------------------------------------------------------------
+
+.. module:: email.message
+ :synopsis: The base class representing email messages in a fashion
+ backward compatible with python3.2
+
+
+The :class:`Message` class is very similar to the
+:class:`~email.message.EmailMessage` class, without the methods added by that
+class, and with the default behavior of certain other methods being slightly
+different. We also document here some methods that, while supported by the
+:class:`~email.message.EmailMessage` class, are not recommended unless you are
+dealing with legacy code.
+
+The philosophy and structure of the two classes is otherwise the same.
+
+This document describes the behavior under the default (for :class:`Message`)
+policy :attr:`~email.policy.Compat32`. If you are going to use another policy,
+you should be using the :class:`~email.message.EmailMessage` class instead.
+
+An email message consists of *headers* and a *payload*. Headers must be
+:rfc:`5233` style names and values, where the field name and value are
+separated by a colon. The colon is not part of either the field name or the
+field value. The payload may be a simple text message, or a binary object, or
+a structured sequence of sub-messages each with their own set of headers and
+their own payload. The latter type of payload is indicated by the message
+having a MIME type such as :mimetype:`multipart/\*` or
+:mimetype:`message/rfc822`.
+
+The conceptual model provided by a :class:`Message` object is that of an
+ordered dictionary of headers with additional methods for accessing both
+specialized information from the headers, for accessing the payload, for
+generating a serialized version of the mssage, and for recursively walking over
+the object tree. Note that duplicate headers are supported but special methods
+must be used to access them.
+
+The :class:`Message` psuedo-dictionary is indexed by the header names, which
+must be ASCII values. The values of the dictionary are strings that are
+supposed to contain only ASCII characters; there is some special handling for
+non-ASCII input, but it doesn't always produce the correct results. Headers
+are stored and returned in case-preserving form, but field names are matched
+case-insensitively. There may also be a single envelope header, also known as
+the *Unix-From* header or the ``From_`` header. The *payload* is either a
+string or bytes, in the case of simple message objects, or a list of
+:class:`Message` objects, for MIME container documents (e.g.
+:mimetype:`multipart/\*` and :mimetype:`message/rfc822`).
+
+Here are the methods of the :class:`Message` class:
+
+
+.. class:: Message(policy=compat32)
+
+ If *policy* is specified (it must be an instance of a :mod:`~email.policy`
+ class) use the rules it specifies to update and serialize the representation
+ of the message. If *policy* is not set, use the :class:`compat32
+ <email.policy.Compat32>` policy, which maintains backward compatibility with
+ the Python 3.2 version of the email package. For more information see the
+ :mod:`~email.policy` documentation.
+
+ .. versionchanged:: 3.3 The *policy* keyword argument was added.
+
+
+ .. method:: as_string(unixfrom=False, maxheaderlen=0, policy=None)
+
+ Return the entire message flattened as a string. When optional *unixfrom*
+ is true, the envelope header is included in the returned string.
+ *unixfrom* defaults to ``False``. For backward compabitility reasons,
+ *maxheaderlen* defaults to ``0``, so if you want a different value you
+ must override it explicitly (the value specified for *max_line_length* in
+ the policy will be ignored by this method). The *policy* argument may be
+ used to override the default policy obtained from the message instance.
+ This can be used to control some of the formatting produced by the
+ method, since the specified *policy* will be passed to the ``Generator``.
+
+ Flattening the message may trigger changes to the :class:`Message` if
+ defaults need to be filled in to complete the transformation to a string
+ (for example, MIME boundaries may be generated or modified).
+
+ Note that this method is provided as a convenience and may not always
+ format the message the way you want. For example, by default it does
+ not do the mangling of lines that begin with ``From`` that is
+ required by the unix mbox format. For more flexibility, instantiate a
+ :class:`~email.generator.Generator` instance and use its
+ :meth:`~email.generator.Generator.flatten` method directly. For example::
+
+ from io import StringIO
+ from email.generator import Generator
+ fp = StringIO()
+ g = Generator(fp, mangle_from_=True, maxheaderlen=60)
+ g.flatten(msg)
+ text = fp.getvalue()
+
+ If the message object contains binary data that is not encoded according
+ to RFC standards, the non-compliant data will be replaced by unicode
+ "unknown character" code points. (See also :meth:`.as_bytes` and
+ :class:`~email.generator.BytesGenerator`.)
+
+ .. versionchanged:: 3.4 the *policy* keyword argument was added.
+
+
+ .. method:: __str__()
+
+ Equivalent to :meth:`.as_string()`. Allows ``str(msg)`` to produce a
+ string containing the formatted message.
+
+
+ .. method:: as_bytes(unixfrom=False, policy=None)
+
+ Return the entire message flattened as a bytes object. When optional
+ *unixfrom* is true, the envelope header is included in the returned
+ string. *unixfrom* defaults to ``False``. The *policy* argument may be
+ used to override the default policy obtained from the message instance.
+ This can be used to control some of the formatting produced by the
+ method, since the specified *policy* will be passed to the
+ ``BytesGenerator``.
+
+ Flattening the message may trigger changes to the :class:`Message` if
+ defaults need to be filled in to complete the transformation to a string
+ (for example, MIME boundaries may be generated or modified).
+
+ Note that this method is provided as a convenience and may not always
+ format the message the way you want. For example, by default it does
+ not do the mangling of lines that begin with ``From`` that is
+ required by the unix mbox format. For more flexibility, instantiate a
+ :class:`~email.generator.BytesGenerator` instance and use its
+ :meth:`~email.generator.BytesGenerator.flatten` method directly.
+ For example::
+
+ from io import BytesIO
+ from email.generator import BytesGenerator
+ fp = BytesIO()
+ g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
+ g.flatten(msg)
+ text = fp.getvalue()
+
+ .. versionadded:: 3.4
+
+
+ .. method:: __bytes__()
+
+ Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a
+ bytes object containing the formatted message.
+
+ .. versionadded:: 3.4
+
+
+ .. method:: is_multipart()
+
+ Return ``True`` if the message's payload is a list of sub-\
+ :class:`Message` objects, otherwise return ``False``. When
+ :meth:`is_multipart` returns ``False``, the payload should be a string
+ object (which might be a CTE encoded binary payload. (Note that
+ :meth:`is_multipart` returning ``True`` does not necessarily mean that
+ "msg.get_content_maintype() == 'multipart'" will return the ``True``.
+ For example, ``is_multipart`` will return ``True`` when the
+ :class:`Message` is of type ``message/rfc822``.)
+
+
+ .. method:: set_unixfrom(unixfrom)
+
+ Set the message's envelope header to *unixfrom*, which should be a string.
+
+
+ .. method:: get_unixfrom()
+
+ Return the message's envelope header. Defaults to ``None`` if the
+ envelope header was never set.
+
+
+ .. method:: attach(payload)
+
+ Add the given *payload* to the current payload, which must be ``None`` or
+ a list of :class:`Message` objects before the call. After the call, the
+ payload will always be a list of :class:`Message` objects. If you want to
+ set the payload to a scalar object (e.g. a string), use
+ :meth:`set_payload` instead.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by :meth:`~email.message.EmailMessage.set_content` and the
+ realted ``make`` and ``add`` methods.
+
+
+ .. method:: get_payload(i=None, decode=False)
+
+ Return the current payload, which will be a list of
+ :class:`Message` objects when :meth:`is_multipart` is ``True``, or a
+ string when :meth:`is_multipart` is ``False``. If the payload is a list
+ and you mutate the list object, you modify the message's payload in place.
+
+ With optional argument *i*, :meth:`get_payload` will return the *i*-th
+ element of the payload, counting from zero, if :meth:`is_multipart` is
+ ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or
+ greater than or equal to the number of items in the payload. If the
+ payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is
+ given, a :exc:`TypeError` is raised.
+
+ Optional *decode* is a flag indicating whether the payload should be
+ decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
+ header. When ``True`` and the message is not a multipart, the payload will
+ be decoded if this header's value is ``quoted-printable`` or ``base64``.
+ If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
+ header is missing, the payload is
+ returned as-is (undecoded). In all cases the returned value is binary
+ data. If the message is a multipart and the *decode* flag is ``True``,
+ then ``None`` is returned. If the payload is base64 and it was not
+ perfectly formed (missing padding, characters outside the base64
+ alphabet), then an appropriate defect will be added to the message's
+ defect property (:class:`~email.errors.InvalidBase64PaddingDefect` or
+ :class:`~email.errors.InvalidBase64CharactersDefect`, respectively).
+
+ When *decode* is ``False`` (the default) the body is returned as a string
+ without decoding the :mailheader:`Content-Transfer-Encoding`. However,
+ for a :mailheader:`Content-Transfer-Encoding` of 8bit, an attempt is made
+ to decode the original bytes using the ``charset`` specified by the
+ :mailheader:`Content-Type` header, using the ``replace`` error handler.
+ If no ``charset`` is specified, or if the ``charset`` given is not
+ recognized by the email package, the body is decoded using the default
+ ASCII charset.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by :meth:`~email.message.EmailMessage.get_content` and
+ :meth:`~email.message.EmailMessage.iter_parts`.
+
+
+ .. method:: set_payload(payload, charset=None)
+
+ Set the entire message object's payload to *payload*. It is the client's
+ responsibility to ensure the payload invariants. Optional *charset* sets
+ the message's default character set; see :meth:`set_charset` for details.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by :meth:`~email.message.EmailMessage.set_content`.
+
+
+ .. method:: set_charset(charset)
+
+ Set the character set of the payload to *charset*, which can either be a
+ :class:`~email.charset.Charset` instance (see :mod:`email.charset`), a
+ string naming a character set, or ``None``. If it is a string, it will
+ be converted to a :class:`~email.charset.Charset` instance. If *charset*
+ is ``None``, the ``charset`` parameter will be removed from the
+ :mailheader:`Content-Type` header (the message will not be otherwise
+ modified). Anything else will generate a :exc:`TypeError`.
+
+ If there is no existing :mailheader:`MIME-Version` header one will be
+ added. If there is no existing :mailheader:`Content-Type` header, one
+ will be added with a value of :mimetype:`text/plain`. Whether the
+ :mailheader:`Content-Type` header already exists or not, its ``charset``
+ parameter will be set to *charset.output_charset*. If
+ *charset.input_charset* and *charset.output_charset* differ, the payload
+ will be re-encoded to the *output_charset*. If there is no existing
+ :mailheader:`Content-Transfer-Encoding` header, then the payload will be
+ transfer-encoded, if needed, using the specified
+ :class:`~email.charset.Charset`, and a header with the appropriate value
+ will be added. If a :mailheader:`Content-Transfer-Encoding` header
+ already exists, the payload is assumed to already be correctly encoded
+ using that :mailheader:`Content-Transfer-Encoding` and is not modified.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by the *charset* parameter of the
+ :meth:`email.emailmessage.EmailMessage.set_content` method.
+
+
+ .. method:: get_charset()
+
+ Return the :class:`~email.charset.Charset` instance associated with the
+ message's payload.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class it always returns
+ ``None``.
+
+
+ The following methods implement a mapping-like interface for accessing the
+ message's :rfc:`2822` headers. Note that there are some semantic differences
+ between these methods and a normal mapping (i.e. dictionary) interface. For
+ example, in a dictionary there are no duplicate keys, but here there may be
+ duplicate message headers. Also, in dictionaries there is no guaranteed
+ order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
+ headers are always returned in the order they appeared in the original
+ message, or were added to the message later. Any header deleted and then
+ re-added are always appended to the end of the header list.
+
+ These semantic differences are intentional and are biased toward maximal
+ convenience.
+
+ Note that in all cases, any envelope header present in the message is not
+ included in the mapping interface.
+
+ In a model generated from bytes, any header values that (in contravention of
+ the RFCs) contain non-ASCII bytes will, when retrieved through this
+ interface, be represented as :class:`~email.header.Header` objects with
+ a charset of `unknown-8bit`.
+
+
+ .. method:: __len__()
+
+ Return the total number of headers, including duplicates.
+
+
+ .. method:: __contains__(name)
+
+ Return true if the message object has a field named *name*. Matching is
+ done case-insensitively and *name* should not include the trailing colon.
+ Used for the ``in`` operator, e.g.::
+
+ if 'message-id' in myMessage:
+ print('Message-ID:', myMessage['message-id'])
+
+
+ .. method:: __getitem__(name)
+
+ Return the value of the named header field. *name* should not include the
+ colon field separator. If the header is missing, ``None`` is returned; a
+ :exc:`KeyError` is never raised.
+
+ Note that if the named field appears more than once in the message's
+ headers, exactly which of those field values will be returned is
+ undefined. Use the :meth:`get_all` method to get the values of all the
+ extant named headers.
+
+
+ .. method:: __setitem__(name, val)
+
+ Add a header to the message with field name *name* and value *val*. The
+ field is appended to the end of the message's existing fields.
+
+ Note that this does *not* overwrite or delete any existing header with the same
+ name. If you want to ensure that the new header is the only one present in the
+ message with field name *name*, delete the field first, e.g.::
+
+ del msg['subject']
+ msg['subject'] = 'Python roolz!'
+
+
+ .. method:: __delitem__(name)
+
+ Delete all occurrences of the field with name *name* from the message's
+ headers. No exception is raised if the named field isn't present in the
+ headers.
+
+
+ .. method:: keys()
+
+ Return a list of all the message's header field names.
+
+
+ .. method:: values()
+
+ Return a list of all the message's field values.
+
+
+ .. method:: items()
+
+ Return a list of 2-tuples containing all the message's field headers and
+ values.
+
+
+ .. method:: get(name, failobj=None)
+
+ Return the value of the named header field. This is identical to
+ :meth:`__getitem__` except that optional *failobj* is returned if the
+ named header is missing (defaults to ``None``).
+
+ Here are some additional useful methods:
+
+
+ .. method:: get_all(name, failobj=None)
+
+ Return a list of all the values for the field named *name*. If there are
+ no such named headers in the message, *failobj* is returned (defaults to
+ ``None``).
+
+
+ .. method:: add_header(_name, _value, **_params)
+
+ Extended header setting. This method is similar to :meth:`__setitem__`
+ except that additional header parameters can be provided as keyword
+ arguments. *_name* is the header field to add and *_value* is the
+ *primary* value for the header.
+
+ For each item in the keyword argument dictionary *_params*, the key is
+ taken as the parameter name, with underscores converted to dashes (since
+ dashes are illegal in Python identifiers). Normally, the parameter will
+ be added as ``key="value"`` unless the value is ``None``, in which case
+ only the key will be added. If the value contains non-ASCII characters,
+ it can be specified as a three tuple in the format
+ ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the
+ charset to be used to encode the value, ``LANGUAGE`` can usually be set
+ to ``None`` or the empty string (see :rfc:`2231` for other possibilities),
+ and ``VALUE`` is the string value containing non-ASCII code points. If
+ a three tuple is not passed and the value contains non-ASCII characters,
+ it is automatically encoded in :rfc:`2231` format using a ``CHARSET``
+ of ``utf-8`` and a ``LANGUAGE`` of ``None``.
+
+ Here's an example::
+
+ msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
+
+ This will add a header that looks like ::
+
+ Content-Disposition: attachment; filename="bud.gif"
+
+ An example with non-ASCII characters::
+
+ msg.add_header('Content-Disposition', 'attachment',
+ filename=('iso-8859-1', '', 'Fußballer.ppt'))
+
+ Which produces ::
+
+ Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"
+
+
+ .. method:: replace_header(_name, _value)
+
+ Replace a header. Replace the first header found in the message that
+ matches *_name*, retaining header order and field name case. If no
+ matching header was found, a :exc:`KeyError` is raised.
+
+
+ .. method:: get_content_type()
+
+ Return the message's content type. The returned string is coerced to
+ lower case of the form :mimetype:`maintype/subtype`. If there was no
+ :mailheader:`Content-Type` header in the message the default type as given
+ by :meth:`get_default_type` will be returned. Since according to
+ :rfc:`2045`, messages always have a default type, :meth:`get_content_type`
+ will always return a value.
+
+ :rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
+ unless it appears inside a :mimetype:`multipart/digest` container, in
+ which case it would be :mimetype:`message/rfc822`. If the
+ :mailheader:`Content-Type` header has an invalid type specification,
+ :rfc:`2045` mandates that the default type be :mimetype:`text/plain`.
+
+
+ .. method:: get_content_maintype()
+
+ Return the message's main content type. This is the :mimetype:`maintype`
+ part of the string returned by :meth:`get_content_type`.
+
+
+ .. method:: get_content_subtype()
+
+ Return the message's sub-content type. This is the :mimetype:`subtype`
+ part of the string returned by :meth:`get_content_type`.
+
+
+ .. method:: get_default_type()
+
+ Return the default content type. Most messages have a default content
+ type of :mimetype:`text/plain`, except for messages that are subparts of
+ :mimetype:`multipart/digest` containers. Such subparts have a default
+ content type of :mimetype:`message/rfc822`.
+
+
+ .. method:: set_default_type(ctype)
+
+ Set the default content type. *ctype* should either be
+ :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
+ enforced. The default content type is not stored in the
+ :mailheader:`Content-Type` header.
+
+
+ .. method:: get_params(failobj=None, header='content-type', unquote=True)
+
+ Return the message's :mailheader:`Content-Type` parameters, as a list.
+ The elements of the returned list are 2-tuples of key/value pairs, as
+ split on the ``'='`` sign. The left hand side of the ``'='`` is the key,
+ while the right hand side is the value. If there is no ``'='`` sign in
+ the parameter the value is the empty string, otherwise the value is as
+ described in :meth:`get_param` and is unquoted if optional *unquote* is
+ ``True`` (the default).
+
+ Optional *failobj* is the object to return if there is no
+ :mailheader:`Content-Type` header. Optional *header* is the header to
+ search instead of :mailheader:`Content-Type`.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by the *params* property of the individual header objects
+ returned by the header access methods.
+
+
+ .. method:: get_param(param, failobj=None, header='content-type', unquote=True)
+
+ Return the value of the :mailheader:`Content-Type` header's parameter
+ *param* as a string. If the message has no :mailheader:`Content-Type`
+ header or if there is no such parameter, then *failobj* is returned
+ (defaults to ``None``).
+
+ Optional *header* if given, specifies the message header to use instead of
+ :mailheader:`Content-Type`.
+
+ Parameter keys are always compared case insensitively. The return value
+ can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
+ encoded. When it's a 3-tuple, the elements of the value are of the form
+ ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and
+ ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
+ to be encoded in the ``us-ascii`` charset. You can usually ignore
+ ``LANGUAGE``.
+
+ If your application doesn't care whether the parameter was encoded as in
+ :rfc:`2231`, you can collapse the parameter value by calling
+ :func:`email.utils.collapse_rfc2231_value`, passing in the return value
+ from :meth:`get_param`. This will return a suitably decoded Unicode
+ string when the value is a tuple, or the original string unquoted if it
+ isn't. For example::
+
+ rawparam = msg.get_param('foo')
+ param = email.utils.collapse_rfc2231_value(rawparam)
+
+ In any case, the parameter value (either the returned string, or the
+ ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
+ to ``False``.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by the *params* property of the individual header objects
+ returned by the header access methods.
+
+
+ .. method:: set_param(param, value, header='Content-Type', requote=True, \
+ charset=None, language='', replace=False)
+
+ Set a parameter in the :mailheader:`Content-Type` header. If the
+ parameter already exists in the header, its value will be replaced with
+ *value*. If the :mailheader:`Content-Type` header as not yet been defined
+ for this message, it will be set to :mimetype:`text/plain` and the new
+ parameter value will be appended as per :rfc:`2045`.
+
+ Optional *header* specifies an alternative header to
+ :mailheader:`Content-Type`, and all parameters will be quoted as necessary
+ unless optional *requote* is ``False`` (the default is ``True``).
+
+ If optional *charset* is specified, the parameter will be encoded
+ according to :rfc:`2231`. Optional *language* specifies the RFC 2231
+ language, defaulting to the empty string. Both *charset* and *language*
+ should be strings.
+
+ If *replace* is ``False`` (the default) the header is moved to the
+ end of the list of headers. If *replace* is ``True``, the header
+ will be updated in place.
+
+ .. versionchanged:: 3.4 ``replace`` keyword was added.
+
+
+ .. method:: del_param(param, header='content-type', requote=True)
+
+ Remove the given parameter completely from the :mailheader:`Content-Type`
+ header. The header will be re-written in place without the parameter or
+ its value. All values will be quoted as necessary unless *requote* is
+ ``False`` (the default is ``True``). Optional *header* specifies an
+ alternative to :mailheader:`Content-Type`.
+
+
+ .. method:: set_type(type, header='Content-Type', requote=True)
+
+ Set the main type and subtype for the :mailheader:`Content-Type`
+ header. *type* must be a string in the form :mimetype:`maintype/subtype`,
+ otherwise a :exc:`ValueError` is raised.
+
+ This method replaces the :mailheader:`Content-Type` header, keeping all
+ the parameters in place. If *requote* is ``False``, this leaves the
+ existing header's quoting as is, otherwise the parameters will be quoted
+ (the default).
+
+ An alternative header can be specified in the *header* argument. When the
+ :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
+ header is also added.
+
+ This is a legacy method. On the
+ :class:`~email.emailmessage.EmailMessage` class its functionality is
+ replaced by the ``make_`` and ``add_`` methods.
+
+
+ .. method:: get_filename(failobj=None)
+
+ Return the value of the ``filename`` parameter of the
+ :mailheader:`Content-Disposition` header of the message. If the header
+ does not have a ``filename`` parameter, this method falls back to looking
+ for the ``name`` parameter on the :mailheader:`Content-Type` header. If
+ neither is found, or the header is missing, then *failobj* is returned.
+ The returned string will always be unquoted as per
+ :func:`email.utils.unquote`.
+
+
+ .. method:: get_boundary(failobj=None)
+
+ Return the value of the ``boundary`` parameter of the
+ :mailheader:`Content-Type` header of the message, or *failobj* if either
+ the header is missing, or has no ``boundary`` parameter. The returned
+ string will always be unquoted as per :func:`email.utils.unquote`.
+
+
+ .. method:: set_boundary(boundary)
+
+ Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to
+ *boundary*. :meth:`set_boundary` will always quote *boundary* if
+ necessary. A :exc:`~email.errors.HeaderParseError` is raised if the
+ message object has no :mailheader:`Content-Type` header.
+
+ Note that using this method is subtly different than deleting the old
+ :mailheader:`Content-Type` header and adding a new one with the new
+ boundary via :meth:`add_header`, because :meth:`set_boundary` preserves
+ the order of the :mailheader:`Content-Type` header in the list of
+ headers. However, it does *not* preserve any continuation lines which may
+ have been present in the original :mailheader:`Content-Type` header.
+
+
+ .. method:: get_content_charset(failobj=None)
+
+ Return the ``charset`` parameter of the :mailheader:`Content-Type` header,
+ coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
+ that header has no ``charset`` parameter, *failobj* is returned.
+
+ Note that this method differs from :meth:`get_charset` which returns the
+ :class:`~email.charset.Charset` instance for the default encoding of the message body.
+
+
+ .. method:: get_charsets(failobj=None)
+
+ Return a list containing the character set names in the message. If the
+ message is a :mimetype:`multipart`, then the list will contain one element
+ for each subpart in the payload, otherwise, it will be a list of length 1.
+
+ Each item in the list will be a string which is the value of the
+ ``charset`` parameter in the :mailheader:`Content-Type` header for the
+ represented subpart. However, if the subpart has no
+ :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
+ the :mimetype:`text` main MIME type, then that item in the returned list
+ will be *failobj*.
+
+
+ .. method:: get_content_disposition()
+
+ Return the lowercased value (without parameters) of the message's
+ :mailheader:`Content-Disposition` header if it has one, or ``None``. The
+ possible values for this method are *inline*, *attachment* or ``None``
+ if the message follows :rfc:`2183`.
+
+ .. versionadded:: 3.5
+
+ .. method:: walk()
+
+ The :meth:`walk` method is an all-purpose generator which can be used to
+ iterate over all the parts and subparts of a message object tree, in
+ depth-first traversal order. You will typically use :meth:`walk` as the
+ iterator in a ``for`` loop; each iteration returns the next subpart.
+
+ Here's an example that prints the MIME type of every part of a multipart
+ message structure:
+
+ .. testsetup::
+
+ >>> from email import message_from_binary_file
+ >>> with open('Lib/test/test_email/data/msg_16.txt', 'rb') as f:
+ ... msg = message_from_binary_file(f)
+ >>> from email.iterators import _structure
+
+ .. doctest::
+
+ >>> for part in msg.walk():
+ ... print(part.get_content_type())
+ multipart/report
+ text/plain
+ message/delivery-status
+ text/plain
+ text/plain
+ message/rfc822
+ text/plain
+
+ ``walk`` iterates over the subparts of any part where
+ :meth:`is_multipart` returns ``True``, even though
+ ``msg.get_content_maintype() == 'multipart'`` may return ``False``. We
+ can see this in our example by making use of the ``_structure`` debug
+ helper function:
+
+ .. doctest::
+
+ >>> for part in msg.walk():
+ ... print(part.get_content_maintype() == 'multipart'),
+ ... part.is_multipart())
+ True True
+ False False
+ False True
+ False False
+ False False
+ False True
+ False False
+ >>> _structure(msg)
+ multipart/report
+ text/plain
+ message/delivery-status
+ text/plain
+ text/plain
+ message/rfc822
+ text/plain
+
+ Here the ``message`` parts are not ``multiparts``, but they do contain
+ subparts. ``is_multipart()`` returns ``True`` and ``walk`` descends
+ into the subparts.
+
+
+ :class:`Message` objects can also optionally contain two instance attributes,
+ which can be used when generating the plain text of a MIME message.
+
+
+ .. attribute:: preamble
+
+ The format of a MIME document allows for some text between the blank line
+ following the headers, and the first multipart boundary string. Normally,
+ this text is never visible in a MIME-aware mail reader because it falls
+ outside the standard MIME armor. However, when viewing the raw text of
+ the message, or when viewing the message in a non-MIME aware reader, this
+ text can become visible.
+
+ The *preamble* attribute contains this leading extra-armor text for MIME
+ documents. When the :class:`~email.parser.Parser` discovers some text
+ after the headers but before the first boundary string, it assigns this
+ text to the message's *preamble* attribute. When the
+ :class:`~email.generator.Generator` is writing out the plain text
+ representation of a MIME message, and it finds the
+ message has a *preamble* attribute, it will write this text in the area
+ between the headers and the first boundary. See :mod:`email.parser` and
+ :mod:`email.generator` for details.
+
+ Note that if the message object has no preamble, the *preamble* attribute
+ will be ``None``.
+
+
+ .. attribute:: epilogue
+
+ The *epilogue* attribute acts the same way as the *preamble* attribute,
+ except that it contains text that appears between the last boundary and
+ the end of the message.
+
+ You do not need to set the epilogue to the empty string in order for the
+ :class:`~email.generator.Generator` to print a newline at the end of the
+ file.
+
+
+ .. attribute:: defects
+
+ The *defects* attribute contains a list of all the problems found when
+ parsing this message. See :mod:`email.errors` for a detailed description
+ of the possible parsing defects.
diff --git a/Doc/library/email.contentmanager.rst b/Doc/library/email.contentmanager.rst
index a9c078b..57743d5 100644
--- a/Doc/library/email.contentmanager.rst
+++ b/Doc/library/email.contentmanager.rst
@@ -7,251 +7,12 @@
.. moduleauthor:: R. David Murray <rdmurray@bitdance.com>
.. sectionauthor:: R. David Murray <rdmurray@bitdance.com>
-.. versionadded:: 3.4
- as a :term:`provisional module <provisional package>`.
-
**Source code:** :source:`Lib/email/contentmanager.py`
-.. note::
-
- The contentmanager module has been included in the standard library on a
- :term:`provisional basis <provisional package>`. Backwards incompatible
- changes (up to and including removal of the module) may occur if deemed
- necessary by the core developers.
-
---------------
-
-The :mod:`~email.message` module provides a class that can represent an
-arbitrary email message. That basic message model has a useful and flexible
-API, but it provides only a lower-level API for interacting with the generic
-parts of a message (the headers, generic header parameters, and the payload,
-which may be a list of sub-parts). This module provides classes and tools
-that provide an enhanced and extensible API for dealing with various specific
-types of content, including the ability to retrieve the content of the message
-as a specialized object type rather than as a simple bytes object. The module
-automatically takes care of the RFC-specified MIME details (required headers
-and parameters, etc.) for the certain common content types content properties,
-and support for additional types can be added by an application using the
-extension mechanisms.
-
-This module defines the eponymous "Content Manager" classes. The base
-:class:`.ContentManager` class defines an API for registering content
-management functions which extract data from ``Message`` objects or insert data
-and headers into ``Message`` objects, thus providing a way of converting
-between ``Message`` objects containing data and other representations of that
-data (Python data types, specialized Python objects, external files, etc). The
-module also defines one concrete content manager: :data:`raw_data_manager`
-converts between MIME content types and ``str`` or ``bytes`` data. It also
-provides a convenient API for managing the MIME parameters when inserting
-content into ``Message``\ s. It also handles inserting and extracting
-``Message`` objects when dealing with the ``message/rfc822`` content type.
-
-Another part of the enhanced interface is subclasses of
-:class:`~email.message.Message` that provide new convenience API functions,
-including convenience methods for calling the Content Managers derived from
-this module.
-
-.. note::
-
- Although :class:`.EmailMessage` and :class:`.MIMEPart` are currently
- documented in this module because of the provisional nature of the code, the
- implementation lives in the :mod:`email.message` module.
-
-.. currentmodule:: email.message
-
-.. class:: EmailMessage(policy=default)
-
- If *policy* is specified (it must be an instance of a :mod:`~email.policy`
- class) use the rules it specifies to udpate and serialize the representation
- of the message. If *policy* is not set, use the
- :class:`~email.policy.default` policy, which follows the rules of the email
- RFCs except for line endings (instead of the RFC mandated ``\r\n``, it uses
- the Python standard ``\n`` line endings). For more information see the
- :mod:`~email.policy` documentation.
-
- This class is a subclass of :class:`~email.message.Message`. It adds
- the following methods:
-
-
- .. method:: is_attachment
-
- Return ``True`` if there is a :mailheader:`Content-Disposition` header
- and its (case insensitive) value is ``attachment``, ``False`` otherwise.
-
- .. versionchanged:: 3.4.2
- is_attachment is now a method instead of a property, for consistency
- with :meth:`~email.message.Message.is_multipart`.
-
-
- .. method:: get_body(preferencelist=('related', 'html', 'plain'))
-
- Return the MIME part that is the best candidate to be the "body" of the
- message.
-
- *preferencelist* must be a sequence of strings from the set ``related``,
- ``html``, and ``plain``, and indicates the order of preference for the
- content type of the part returned.
-
- Start looking for candidate matches with the object on which the
- ``get_body`` method is called.
-
- If ``related`` is not included in *preferencelist*, consider the root
- part (or subpart of the root part) of any related encountered as a
- candidate if the (sub-)part matches a preference.
-
- When encountering a ``multipart/related``, check the ``start`` parameter
- and if a part with a matching :mailheader:`Content-ID` is found, consider
- only it when looking for candidate matches. Otherwise consider only the
- first (default root) part of the ``multipart/related``.
-
- If a part has a :mailheader:`Content-Disposition` header, only consider
- the part a candidate match if the value of the header is ``inline``.
-
- If none of the candidates matches any of the preferences in
- *preferneclist*, return ``None``.
-
- Notes: (1) For most applications the only *preferencelist* combinations
- that really make sense are ``('plain',)``, ``('html', 'plain')``, and the
- default, ``('related', 'html', 'plain')``. (2) Because matching starts
- with the object on which ``get_body`` is called, calling ``get_body`` on
- a ``multipart/related`` will return the object itself unless
- *preferencelist* has a non-default value. (3) Messages (or message parts)
- that do not specify a :mailheader:`Content-Type` or whose
- :mailheader:`Content-Type` header is invalid will be treated as if they
- are of type ``text/plain``, which may occasionally cause ``get_body`` to
- return unexpected results.
-
-
- .. method:: iter_attachments()
-
- Return an iterator over all of the parts of the message that are not
- candidate "body" parts. That is, skip the first occurrence of each of
- ``text/plain``, ``text/html``, ``multipart/related``, or
- ``multipart/alternative`` (unless they are explicitly marked as
- attachments via :mailheader:`Content-Disposition: attachment`), and
- return all remaining parts. When applied directly to a
- ``multipart/related``, return an iterator over the all the related parts
- except the root part (ie: the part pointed to by the ``start`` parameter,
- or the first part if there is no ``start`` parameter or the ``start``
- parameter doesn't match the :mailheader:`Content-ID` of any of the
- parts). When applied directly to a ``multipart/alternative`` or a
- non-``multipart``, return an empty iterator.
-
-
- .. method:: iter_parts()
-
- Return an iterator over all of the immediate sub-parts of the message,
- which will be empty for a non-``multipart``. (See also
- :meth:`~email.message.walk`.)
-
-
- .. method:: get_content(*args, content_manager=None, **kw)
-
- Call the ``get_content`` method of the *content_manager*, passing self
- as the message object, and passing along any other arguments or keywords
- as additional arguments. If *content_manager* is not specified, use
- the ``content_manager`` specified by the current :mod:`~email.policy`.
+------------
+.. versionadded:: 3.6 [1]_
- .. method:: set_content(*args, content_manager=None, **kw)
-
- Call the ``set_content`` method of the *content_manager*, passing self
- as the message object, and passing along any other arguments or keywords
- as additional arguments. If *content_manager* is not specified, use
- the ``content_manager`` specified by the current :mod:`~email.policy`.
-
-
- .. method:: make_related(boundary=None)
-
- Convert a non-``multipart`` message into a ``multipart/related`` message,
- moving any existing :mailheader:`Content-` headers and payload into a
- (new) first part of the ``multipart``. If *boundary* is specified, use
- it as the boundary string in the multipart, otherwise leave the boundary
- to be automatically created when it is needed (for example, when the
- message is serialized).
-
-
- .. method:: make_alternative(boundary=None)
-
- Convert a non-``multipart`` or a ``multipart/related`` into a
- ``multipart/alternative``, moving any existing :mailheader:`Content-`
- headers and payload into a (new) first part of the ``multipart``. If
- *boundary* is specified, use it as the boundary string in the multipart,
- otherwise leave the boundary to be automatically created when it is
- needed (for example, when the message is serialized).
-
-
- .. method:: make_mixed(boundary=None)
-
- Convert a non-``multipart``, a ``multipart/related``, or a
- ``multipart-alternative`` into a ``multipart/mixed``, moving any existing
- :mailheader:`Content-` headers and payload into a (new) first part of the
- ``multipart``. If *boundary* is specified, use it as the boundary string
- in the multipart, otherwise leave the boundary to be automatically
- created when it is needed (for example, when the message is serialized).
-
-
- .. method:: add_related(*args, content_manager=None, **kw)
-
- If the message is a ``multipart/related``, create a new message
- object, pass all of the arguments to its :meth:`set_content` method,
- and :meth:`~email.message.Message.attach` it to the ``multipart``. If
- the message is a non-``multipart``, call :meth:`make_related` and then
- proceed as above. If the message is any other type of ``multipart``,
- raise a :exc:`TypeError`. If *content_manager* is not specified, use
- the ``content_manager`` specified by the current :mod:`~email.policy`.
- If the added part has no :mailheader:`Content-Disposition` header,
- add one with the value ``inline``.
-
-
- .. method:: add_alternative(*args, content_manager=None, **kw)
-
- If the message is a ``multipart/alternative``, create a new message
- object, pass all of the arguments to its :meth:`set_content` method, and
- :meth:`~email.message.Message.attach` it to the ``multipart``. If the
- message is a non-``multipart`` or ``multipart/related``, call
- :meth:`make_alternative` and then proceed as above. If the message is
- any other type of ``multipart``, raise a :exc:`TypeError`. If
- *content_manager* is not specified, use the ``content_manager`` specified
- by the current :mod:`~email.policy`.
-
-
- .. method:: add_attachment(*args, content_manager=None, **kw)
-
- If the message is a ``multipart/mixed``, create a new message object,
- pass all of the arguments to its :meth:`set_content` method, and
- :meth:`~email.message.Message.attach` it to the ``multipart``. If the
- message is a non-``multipart``, ``multipart/related``, or
- ``multipart/alternative``, call :meth:`make_mixed` and then proceed as
- above. If *content_manager* is not specified, use the ``content_manager``
- specified by the current :mod:`~email.policy`. If the added part
- has no :mailheader:`Content-Disposition` header, add one with the value
- ``attachment``. This method can be used both for explicit attachments
- (:mailheader:`Content-Disposition: attachment` and ``inline`` attachments
- (:mailheader:`Content-Disposition: inline`), by passing appropriate
- options to the ``content_manager``.
-
-
- .. method:: clear()
-
- Remove the payload and all of the headers.
-
-
- .. method:: clear_content()
-
- Remove the payload and all of the :exc:`Content-` headers, leaving
- all other headers intact and in their original order.
-
-
-.. class:: MIMEPart(policy=default)
-
- This class represents a subpart of a MIME message. It is identical to
- :class:`EmailMessage`, except that no :mailheader:`MIME-Version` headers are
- added when :meth:`~EmailMessage.set_content` is called, since sub-parts do
- not need their own :mailheader:`MIME-Version` headers.
-
-
-.. currentmodule:: email.contentmanager
.. class:: ContentManager()
@@ -362,7 +123,7 @@ Currently the email package provides only one concrete content manager,
set_content(msg, <'bytes'>, maintype, subtype, cte="base64", \
disposition=None, filename=None, cid=None, \
params=None, headers=None)
- set_content(msg, <'Message'>, cte=None, \
+ set_content(msg, <'EmailMessage'>, cte=None, \
disposition=None, filename=None, cid=None, \
params=None, headers=None)
set_content(msg, <'list'>, subtype='mixed', \
@@ -378,14 +139,14 @@ Currently the email package provides only one concrete content manager,
subtype to *subtype* if it is specified, or ``plain`` if it is not.
* For ``bytes``, use the specified *maintype* and *subtype*, or
raise a :exc:`TypeError` if they are not specified.
- * For :class:`~email.message.Message` objects, set the maintype to
- ``message``, and set the subtype to *subtype* if it is specified
- or ``rfc822`` if it is not. If *subtype* is ``partial``, raise an
- error (``bytes`` objects must be used to construct
- ``message/partial`` parts).
+ * For :class:`~email.message.EmailMessage` objects, set the maintype
+ to ``message``, and set the subtype to *subtype* if it is
+ specified or ``rfc822`` if it is not. If *subtype* is
+ ``partial``, raise an error (``bytes`` objects must be used to
+ construct ``message/partial`` parts).
* For *<'list'>*, which should be a list of
- :class:`~email.message.Message` objects, set the ``maintype`` to
- ``multipart``, and the ``subtype`` to *subtype* if it is
+ :class:`~email.message.EmailMessage` objects, set the ``maintype``
+ to ``multipart``, and the ``subtype`` to *subtype* if it is
specified, and ``mixed`` if it is not. If the message parts in
the *<'list'>* have :mailheader:`MIME-Version` headers, remove
them.
@@ -397,32 +158,35 @@ Currently the email package provides only one concrete content manager,
If *cte* is set, encode the payload using the specified content transfer
encoding, and set the :mailheader:`Content-Transfer-Endcoding` header to
- that value. For ``str`` objects, if it is not set use heuristics to
- determine the most compact encoding. Possible values for *cte* are
- ``quoted-printable``, ``base64``, ``7bit``, ``8bit``, and ``binary``.
- If the input cannot be encoded in the specified encoding (eg: ``7bit``),
- raise a :exc:`ValueError`. For :class:`~email.message.Message`, per
- :rfc:`2046`, raise an error if a *cte* of ``quoted-printable`` or
- ``base64`` is requested for *subtype* ``rfc822``, and for any *cte*
- other than ``7bit`` for *subtype* ``external-body``. For
- ``message/rfc822``, use ``8bit`` if *cte* is not specified. For all
- other values of *subtype*, use ``7bit``.
+ that value. Possible values for *cte* are ``quoted-printable``,
+ ``base64``, ``7bit``, ``8bit``, and ``binary``. If the input cannot be
+ encoded in the specified encoding (for example, specifying a *cte* of
+ ``7bit`` for an input that contains non-ASCII values), raise a
+ :exc:`ValueError`.
+
+ * For ``str`` objects, if *cte* is not set use heuristics to
+ determine the most compact encoding.
+ * For :class:`~email.message.EmailMessage`, per :rfc:`2046`, raise
+ an error if a *cte* of ``quoted-printable`` or ``base64`` is
+ requested for *subtype* ``rfc822``, and for any *cte* other than
+ ``7bit`` for *subtype* ``external-body``. For
+ ``message/rfc822``, use ``8bit`` if *cte* is not specified. For
+ all other values of *subtype*, use ``7bit``.
.. note:: A *cte* of ``binary`` does not actually work correctly yet.
- The ``Message`` object as modified by ``set_content`` is correct, but
- :class:`~email.generator.BytesGenerator` does not serialize it
- correctly.
+ The ``EmailMessage`` object as modified by ``set_content`` is
+ correct, but :class:`~email.generator.BytesGenerator` does not
+ serialize it correctly.
If *disposition* is set, use it as the value of the
:mailheader:`Content-Disposition` header. If not specified, and
*filename* is specified, add the header with the value ``attachment``.
- If it is not specified and *filename* is also not specified, do not add
- the header. The only valid values for *disposition* are ``attachment``
- and ``inline``.
+ If *disposition* is not specified and *filename* is also not specified,
+ do not add the header. The only valid values for *disposition* are
+ ``attachment`` and ``inline``.
If *filename* is specified, use it as the value of the ``filename``
- parameter of the :mailheader:`Content-Disposition` header. There is no
- default.
+ parameter of the :mailheader:`Content-Disposition` header.
If *cid* is specified, add a :mailheader:`Content-ID` header with
*cid* as its value.
@@ -435,3 +199,9 @@ Currently the email package provides only one concrete content manager,
``headername: headervalue`` or a list of ``header`` objects
(distinguished from strings by having a ``name`` attribute), add the
headers to *msg*.
+
+
+.. rubric:: Footnotes
+
+.. [1] Oringally added in 3.4 as a :term:`provisional module <provisional
+ package>`
diff --git a/Doc/library/email.encoders.rst b/Doc/library/email.encoders.rst
index 9d7f9bf..e24ac7b 100644
--- a/Doc/library/email.encoders.rst
+++ b/Doc/library/email.encoders.rst
@@ -8,6 +8,12 @@
--------------
+This module is part of the legacy (``Compat32``) email API. In the
+new API the functionality is provided by the *cte* parameter of
+the :meth:`~email.message.EmailMessage.set_content` method.
+
+The remaining text in this section is the original documentation of the module.
+
When creating :class:`~email.message.Message` objects from scratch, you often
need to encode the payloads for transport through compliant mail servers. This
is especially true for :mimetype:`image/\*` and :mimetype:`text/\*` type messages
diff --git a/Doc/library/email.errors.rst b/Doc/library/email.errors.rst
index 8470783..2d0d192 100644
--- a/Doc/library/email.errors.rst
+++ b/Doc/library/email.errors.rst
@@ -20,33 +20,27 @@ The following exception classes are defined in the :mod:`email.errors` module:
.. exception:: MessageParseError()
- This is the base class for exceptions raised by the :class:`~email.parser.Parser`
- class. It is derived from :exc:`MessageError`.
+ This is the base class for exceptions raised by the
+ :class:`~email.parser.Parser` class. It is derived from
+ :exc:`MessageError`. This class is also used internally by the parser used
+ by :mod:`~email.headerregistry`.
.. exception:: HeaderParseError()
- Raised under some error conditions when parsing the :rfc:`2822` headers of a
- message, this class is derived from :exc:`MessageParseError`. It can be raised
- from the :meth:`Parser.parse <email.parser.Parser.parse>` or
- :meth:`Parser.parsestr <email.parser.Parser.parsestr>` methods.
-
- Situations where it can be raised include finding an envelope header after the
- first :rfc:`2822` header of the message, finding a continuation line before the
- first :rfc:`2822` header is found, or finding a line in the headers which is
- neither a header or a continuation line.
+ Raised under some error conditions when parsing the :rfc:`5322` headers of a
+ message, this class is derived from :exc:`MessageParseError`. The
+ :meth:`~email.message.EmailMessage.set_boundary` method will raise this
+ error if the content type is unknown when the method is called.
+ :class:`~email.header.Header` may raise this error for certain base64
+ decoding errors, and when an attempt is made to create a header that appears
+ to contain an embedded header (that is, there is what is supposed to be a
+ continuation line that has no leading whitespace and looks like a header).
.. exception:: BoundaryError()
- Raised under some error conditions when parsing the :rfc:`2822` headers of a
- message, this class is derived from :exc:`MessageParseError`. It can be raised
- from the :meth:`Parser.parse <email.parser.Parser.parse>` or
- :meth:`Parser.parsestr <email.parser.Parser.parsestr>` methods.
-
- Situations where it can be raised include not being able to find the starting or
- terminating boundary in a :mimetype:`multipart/\*` message when strict parsing
- is used.
+ Deprecated and no longer used.
.. exception:: MultipartConversionError()
@@ -64,14 +58,14 @@ The following exception classes are defined in the :mod:`email.errors` module:
:class:`~email.mime.nonmultipart.MIMENonMultipart` (e.g.
:class:`~email.mime.image.MIMEImage`).
-Here's the list of the defects that the :class:`~email.parser.FeedParser`
+
+Here is the list of the defects that the :class:`~email.parser.FeedParser`
can find while parsing messages. Note that the defects are added to the message
where the problem was found, so for example, if a message nested inside a
:mimetype:`multipart/alternative` had a malformed header, that nested message
object would have a defect, but the containing messages would not.
-All defect classes are subclassed from :class:`email.errors.MessageDefect`, but
-this class is *not* an exception!
+All defect classes are subclassed from :class:`email.errors.MessageDefect`.
* :class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart,
but had no :mimetype:`boundary` parameter.
diff --git a/Doc/library/email-examples.rst b/Doc/library/email.examples.rst
index ad93b5c..84e9aee 100644
--- a/Doc/library/email-examples.rst
+++ b/Doc/library/email.examples.rst
@@ -6,13 +6,14 @@
Here are a few examples of how to use the :mod:`email` package to read, write,
and send simple email messages, as well as more complex MIME messages.
-First, let's see how to create and send a simple text message:
+First, let's see how to create and send a simple text message (both the
+text content and the addresses may contain unicode characters):
.. literalinclude:: ../includes/email-simple.py
-And parsing RFC822 headers can easily be done by the parse(filename) or
-parsestr(message_as_string) methods of the Parser() class:
+Parsing RFC822 headers can easily be done by the using the classes
+from the :mod:`~email.parser` module:
.. literalinclude:: ../includes/email-headers.py
@@ -34,30 +35,19 @@ above, into a directory of files:
.. literalinclude:: ../includes/email-unpack.py
+
Here's an example of how to create an HTML message with an alternative plain
-text version: [2]_
+text version. To make things a bit more interesting, we include a related
+image in the html part, and we save a copy of what we are going to send to
+disk, as well as sending it.
.. literalinclude:: ../includes/email-alternative.py
-.. _email-contentmanager-api-examples:
-
-Examples using the Provisional API
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Here is a reworking of the last example using the provisional API. To make
-things a bit more interesting, we include a related image in the html part, and
-we save a copy of what we are going to send to disk, as well as sending it.
-
-This example also shows how easy it is to include non-ASCII, and simplifies the
-sending of the message using the :meth:`.send_message` method of the
-:mod:`smtplib` module.
-
-.. literalinclude:: ../includes/email-alternative-new-api.py
-
-If we were instead sent the message from the last example, here is one
-way we could process it:
+If we were sent the message from the last example, here is one way we could
+process it:
-.. literalinclude:: ../includes/email-read-alternative-new-api.py
+.. literalinclude:: ../includes/email-read-alternative.py
Up to the prompt, the output from the above is:
@@ -75,4 +65,3 @@ Up to the prompt, the output from the above is:
.. rubric:: Footnotes
.. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples.
-.. [2] Contributed by Martin Matejek.
diff --git a/Doc/library/email.generator.rst b/Doc/library/email.generator.rst
index d596ed8..ab0fbc2 100644
--- a/Doc/library/email.generator.rst
+++ b/Doc/library/email.generator.rst
@@ -8,210 +8,244 @@
--------------
-One of the most common tasks is to generate the flat text of the email message
-represented by a message object structure. You will need to do this if you want
-to send your message via the :mod:`smtplib` module or the :mod:`nntplib` module,
-or print the message on the console. Taking a message object structure and
-producing a flat text document is the job of the :class:`Generator` class.
-
-Again, as with the :mod:`email.parser` module, you aren't limited to the
-functionality of the bundled generator; you could write one from scratch
-yourself. However the bundled generator knows how to generate most email in a
-standards-compliant way, should handle MIME and non-MIME email messages just
-fine, and is designed so that the transformation from flat text, to a message
-structure via the :class:`~email.parser.Parser` class, and back to flat text,
-is idempotent (the input is identical to the output) [#]_. On the other hand,
-using the Generator on a :class:`~email.message.Message` constructed by program
-may result in changes to the :class:`~email.message.Message` object as defaults
-are filled in.
-
-:class:`bytes` output can be generated using the :class:`BytesGenerator` class.
-If the message object structure contains non-ASCII bytes, this generator's
-:meth:`~BytesGenerator.flatten` method will emit the original bytes. Parsing a
-binary message and then flattening it with :class:`BytesGenerator` should be
-idempotent for standards compliant messages.
-
-Here are the public methods of the :class:`Generator` class, imported from the
-:mod:`email.generator` module:
-
-
-.. class:: Generator(outfp, mangle_from_=True, maxheaderlen=78, *, policy=None)
-
- The constructor for the :class:`Generator` class takes a :term:`file-like object`
- called *outfp* for an argument. *outfp* must support the :meth:`write` method
- and be usable as the output file for the :func:`print` function.
-
- Optional *mangle_from_* is a flag that, when ``True``, puts a ``>`` character in
- front of any line in the body that starts exactly as ``From``, i.e. ``From``
- followed by a space at the beginning of the line. This is the only guaranteed
- portable way to avoid having such lines be mistaken for a Unix mailbox format
- envelope header separator (see `WHY THE CONTENT-LENGTH FORMAT IS BAD
- <https://www.jwz.org/doc/content-length.html>`_ for details). *mangle_from_*
- defaults to ``True``, but you might want to set this to ``False`` if you are not
- writing Unix mailbox format files.
-
- Optional *maxheaderlen* specifies the longest length for a non-continued header.
- When a header line is longer than *maxheaderlen* (in characters, with tabs
- expanded to 8 spaces), the header will be split as defined in the
- :class:`~email.header.Header` class. Set to zero to disable header wrapping.
- The default is 78, as recommended (but not required) by :rfc:`2822`.
-
- The *policy* keyword specifies a :mod:`~email.policy` object that controls a
- number of aspects of the generator's operation. If no *policy* is specified,
- then the *policy* attached to the message object passed to :attr:`flatten`
- is used.
+One of the most common tasks is to generate the flat (serialized) version of
+the email message represented by a message object structure. You will need to
+do this if you want to send your message via :meth:`smtplib.SMTP.sendmail` or
+the :mod:`nntplib` module, or print the message on the console. Taking a
+message object structure and producing a serialized representation is the job
+of the generator classes.
+
+As with the :mod:`email.parser` module, you aren't limited to the functionality
+of the bundled generator; you could write one from scratch yourself. However
+the bundled generator knows how to generate most email in a standards-compliant
+way, should handle MIME and non-MIME email messages just fine, and is designed
+so that the bytes-oriented parsing and generation operations are inverses,
+assuming the same non-transforming :mod:`~email.policy` is used for both. That
+is, parsing the serialized byte stream via the
+:class:`~email.parser.BytesParser` class and then regenerating the serialized
+byte stream using :class:`BytesGenerator` should produce output identical to
+the input [#]_. (On the other hand, using the generator on an
+:class:`~email.message.EmailMessage` constructed by program may result in
+changes to the :class:`~email.message.EmailMessage` object as defaults are
+filled in.)
+
+The :class:`Generator` class can be used to flatten a message into a text (as
+opposed to binary) serialized representation, but since Unicode cannot
+represent binary data directly, the message is of necessity transformed into
+something that contains only ASCII characters, using the standard email RFC
+Content Transfer Encoding techniques for encoding email messages for transport
+over channels that are not "8 bit clean".
+
+
+.. class:: BytesGenerator(outfp, mangle_from_=None, maxheaderlen=None, *, \
+ policy=None)
- .. versionchanged:: 3.3 Added the *policy* keyword.
+ Return a :class:`BytesGenerator` object that will write any message provided
+ to the :meth:`flatten` method, or any surrogateescape encoded text provided
+ to the :meth:`write` method, to the :term:`file-like object` *outfp*.
+ *outfp* must support a ``write`` method that accepts binary data.
+
+ If optional *mangle_from_* is ``True``, put a ``>`` character in front of
+ any line in the body that starts with the exact string ``"From "``, that is
+ ``From`` followed by a space at the beginning of a line. *mangle_from_*
+ defaults to the value of the :attr:`~email.policy.Policy.mangle_from_`
+ setting of the *policy* (which is ``True`` for the
+ :data:`~email.policy.compat32` policy and ``False`` for all others).
+ *mangle_from_* is intended for use when messages are stored in unix mbox
+ format (see :mod:`mailbox` and `WHY THE CONTENT-LENGTH FORMAT IS BAD
+ <http://www.jwz.org/doc/content-length.html>`_).
+
+ If *maxheaderlen* is not ``None``, refold any header lines that are longer
+ than *maxheaderlen*, or if ``0``, do not rewrap any headers. If
+ *manheaderlen* is ``None`` (the default), wrap headers and other message
+ lines according to the *policy* settings.
+
+ If *policy* is specified, use that policy to control message generation. If
+ *policy* is ``None`` (the default), use the policy associated with the
+ :class:`~email.message.Message` or :class:`~email.message.EmailMessage`
+ object passed to ``flatten`` to control the message generation. See
+ :mod:`email.policy` for details on what *policy* controls.
- The other public :class:`Generator` methods are:
+ .. versionadded:: 3.2
+ .. versionchanged:: 3.3 Added the *policy* keyword.
- .. method:: flatten(msg, unixfrom=False, linesep=None)
+ .. versionchanged:: 3.6 The default behavior of the *mangle_from_*
+ and *maxheaderlen* parameters is to follow the policy.
- Print the textual representation of the message object structure rooted at
- *msg* to the output file specified when the :class:`Generator` instance
- was created. Subparts are visited depth-first and the resulting text will
- be properly MIME encoded.
- Optional *unixfrom* is a flag that forces the printing of the envelope
- header delimiter before the first :rfc:`2822` header of the root message
- object. If the root object has no envelope header, a standard one is
- crafted. By default, this is set to ``False`` to inhibit the printing of
- the envelope delimiter.
+ .. method:: flatten(msg, unixfrom=False, linesep=None)
+ Print the textual representation of the message object structure rooted
+ at *msg* to the output file specified when the :class:`BytesGenerator`
+ instance was created.
+
+ If the :mod:`~email.policy` option :attr:`~email.policy.Policy.cte_type`
+ is ``8bit`` (the default), copy any headers in the original parsed
+ message that have not been modified to the output with any bytes with the
+ high bit set reproduced as in the original, and preserve the non-ASCII
+ :mailheader:`Content-Transfer-Encoding` of any body parts that have them.
+ If ``cte_type`` is ``7bit``, convert the bytes with the high bit set as
+ needed using an ASCII-compatible :mailheader:`Content-Transfer-Encoding`.
+ That is, transform parts with non-ASCII
+ :mailheader:`Cotnent-Transfer-Encoding`
+ (:mailheader:`Content-Transfer-Encoding: 8bit`) to an ASCII compatibile
+ :mailheader:`Content-Transfer-Encoding`, and encode RFC-invalid non-ASCII
+ bytes in headers using the MIME ``unknown-8bit`` character set, thus
+ rendering them RFC-compliant.
+
+ .. XXX: There should be an option that just does the RFC
+ compliance transformation on headers but leaves CTE 8bit parts alone.
+
+ If *unixfrom* is ``True``, print the envelope header delimiter used by
+ the Unix mailbox format (see :mod:`mailbox`) before the first of the
+ :rfc:`5322` headers of the root message object. If the root object has
+ no envelope header, craft a standard one. The default is ``False``.
Note that for subparts, no envelope header is ever printed.
- Optional *linesep* specifies the line separator character used to
- terminate lines in the output. If specified it overrides the value
- specified by the *msg*\'s or ``Generator``\'s ``policy``.
+ If *linesep* is not ``None``, use it as the separator character between
+ all the lines of the flattened message. If *linesep* is ``None`` (the
+ default), use the value specified in the *policy*.
- Because strings cannot represent non-ASCII bytes, if the policy that
- applies when ``flatten`` is run has :attr:`~email.policy.Policy.cte_type`
- set to ``8bit``, ``Generator`` will operate as if it were set to
- ``7bit``. This means that messages parsed with a Bytes parser that have
- a :mailheader:`Content-Transfer-Encoding` of ``8bit`` will be converted
- to a use a ``7bit`` Content-Transfer-Encoding. Non-ASCII bytes in the
- headers will be :rfc:`2047` encoded with a charset of ``unknown-8bit``.
+ .. XXX: flatten should take a *policy* keyword.
- .. versionchanged:: 3.2
- Added support for re-encoding ``8bit`` message bodies, and the
- *linesep* argument.
.. method:: clone(fp)
- Return an independent clone of this :class:`Generator` instance with the
- exact same options.
-
- .. method:: write(s)
-
- Write the string *s* to the underlying file object, i.e. *outfp* passed to
- :class:`Generator`'s constructor. This provides just enough file-like API
- for :class:`Generator` instances to be used in the :func:`print` function.
+ Return an independent clone of this :class:`BytesGenerator` instance with
+ the exact same option settings, and *fp* as the new *outfp*.
-As a convenience, see the :class:`~email.message.Message` methods
-:meth:`~email.message.Message.as_string` and ``str(aMessage)``, a.k.a.
-:meth:`~email.message.Message.__str__`, which simplify the generation of a
-formatted string representation of a message object. For more detail, see
-:mod:`email.message`.
-.. class:: BytesGenerator(outfp, mangle_from_=True, maxheaderlen=78, *, \
- policy=None)
+ .. method:: write(s)
- The constructor for the :class:`BytesGenerator` class takes a binary
- :term:`file-like object` called *outfp* for an argument. *outfp* must
- support a :meth:`write` method that accepts binary data.
+ Encode *s* using the ``ASCII`` codec and the ``surrogateescape`` error
+ handler, and pass it to the *write* method of the *outfp* passed to the
+ :class:`BytesGenerator`'s constructor.
- Optional *mangle_from_* is a flag that, when ``True``, puts a ``>``
- character in front of any line in the body that starts exactly as ``From``,
- i.e. ``From`` followed by a space at the beginning of the line. This is the
- only guaranteed portable way to avoid having such lines be mistaken for a
- Unix mailbox format envelope header separator (see `WHY THE CONTENT-LENGTH
- FORMAT IS BAD <https://www.jwz.org/doc/content-length.html>`_ for details).
- *mangle_from_* defaults to ``True``, but you might want to set this to
- ``False`` if you are not writing Unix mailbox format files.
- Optional *maxheaderlen* specifies the longest length for a non-continued
- header. When a header line is longer than *maxheaderlen* (in characters,
- with tabs expanded to 8 spaces), the header will be split as defined in the
- :class:`~email.header.Header` class. Set to zero to disable header
- wrapping. The default is 78, as recommended (but not required) by
- :rfc:`2822`.
+As a convenience, :class:`~email.message.EmailMessage` provides the methods
+:meth:`~email.message.EmailMessage.as_bytes` and ``bytes(aMessage)`` (a.k.a.
+:meth:`~email.message.EmailMessage.__bytes__`), which simplify the generation of
+a serialized binary representation of a message object. For more detail, see
+:mod:`email.message`.
- The *policy* keyword specifies a :mod:`~email.policy` object that controls a
- number of aspects of the generator's operation. If no *policy* is specified,
- then the *policy* attached to the message object passed to :attr:`flatten`
- is used.
+Because strings cannot represent binary data, the :class:`Generator` class must
+convert any binary data in any message it flattens to an ASCII compatible
+format, by converting them to an ASCII compatible
+:mailheader:`Content-Transfer_Encoding`. Using the terminology of the email
+RFCs, you can think of this as :class:`Generator` serializing to an I/O stream
+that is not "8 bit clean". In other words, most applications will want
+to be using :class:`BytesGenerator`, and not :class:`Generator`.
+
+.. class:: Generator(outfp, mangle_from_=None, maxheaderlen=None, *, \
+ policy=None)
+
+ Return a :class:`Generator` object that will write any message provided
+ to the :meth:`flatten` method, or any text provided to the :meth:`write`
+ method, to the :term:`file-like object` *outfp*. *outfp* must support a
+ ``write`` method that accepts string data.
+
+ If optional *mangle_from_* is ``True``, put a ``>`` character in front of
+ any line in the body that starts with the exact string ``"From "``, that is
+ ``From`` followed by a space at the beginning of a line. *mangle_from_*
+ defaults to the value of the :attr:`~email.policy.Policy.mangle_from_`
+ setting of the *policy* (which is ``True`` for the
+ :data:`~email.policy.compat32` policy and ``False`` for all others).
+ *mangle_from_* is intended for use when messages are stored in unix mbox
+ format (see :mod:`mailbox` and `WHY THE CONTENT-LENGTH FORMAT IS BAD
+ <http://www.jwz.org/doc/content-length.html>`_).
+
+ If *maxheaderlen* is not ``None``, refold any header lines that are longer
+ than *maxheaderlen*, or if ``0``, do not rewrap any headers. If
+ *manheaderlen* is ``None`` (the default), wrap headers and other message
+ lines according to the *policy* settings.
+
+ If *policy* is specified, use that policy to control message generation. If
+ *policy* is ``None`` (the default), use the policy associated with the
+ :class:`~email.message.Message` or :class:`~email.message.EmailMessage`
+ object passed to ``flatten`` to control the message generation. See
+ :mod:`email.policy` for details on what *policy* controls.
.. versionchanged:: 3.3 Added the *policy* keyword.
- The other public :class:`BytesGenerator` methods are:
+ .. versionchanged:: 3.6 The default behavior of the *mangle_from_*
+ and *maxheaderlen* parameters is to follow the policy.
.. method:: flatten(msg, unixfrom=False, linesep=None)
Print the textual representation of the message object structure rooted
- at *msg* to the output file specified when the :class:`BytesGenerator`
- instance was created. Subparts are visited depth-first and the resulting
- text will be properly MIME encoded. If the :mod:`~email.policy` option
- :attr:`~email.policy.Policy.cte_type` is ``8bit`` (the default),
- then any bytes with the high bit set in the original parsed message that
- have not been modified will be copied faithfully to the output. If
- ``cte_type`` is ``7bit``, the bytes will be converted as needed
- using an ASCII-compatible Content-Transfer-Encoding. In particular,
- RFC-invalid non-ASCII bytes in headers will be encoded using the MIME
- ``unknown-8bit`` character set, thus rendering them RFC-compliant.
-
- .. XXX: There should be a complementary option that just does the RFC
- compliance transformation but leaves CTE 8bit parts alone.
-
- Messages parsed with a Bytes parser that have a
- :mailheader:`Content-Transfer-Encoding` of 8bit will be reconstructed
- as 8bit if they have not been modified.
-
- Optional *unixfrom* is a flag that forces the printing of the envelope
- header delimiter before the first :rfc:`2822` header of the root message
- object. If the root object has no envelope header, a standard one is
- crafted. By default, this is set to ``False`` to inhibit the printing of
- the envelope delimiter.
-
+ at *msg* to the output file specified when the :class:`Generator`
+ instance was created.
+
+ If the :mod:`~email.policy` option :attr:`~email.policy.Policy.cte_type`
+ is ``8bit``, generate the message as if the option were set to ``7bit``.
+ (This is required because strings cannot represent non-ASCII bytes.)
+ Convert any bytes with the high bit set as needed using an
+ ASCII-compatible :mailheader:`Content-Transfer-Encoding`. That is,
+ transform parts with non-ASCII :mailheader:`Cotnent-Transfer-Encoding`
+ (:mailheader:`Content-Transfer-Encoding: 8bit`) to an ASCII compatibile
+ :mailheader:`Content-Transfer-Encoding`, and encode RFC-invalid non-ASCII
+ bytes in headers using the MIME ``unknown-8bit`` character set, thus
+ rendering them RFC-compliant.
+
+ If *unixfrom* is ``True``, print the envelope header delimiter used by
+ the Unix mailbox format (see :mod:`mailbox`) before the first of the
+ :rfc:`5322` headers of the root message object. If the root object has
+ no envelope header, craft a standard one. The default is ``False``.
Note that for subparts, no envelope header is ever printed.
- Optional *linesep* specifies the line separator character used to
- terminate lines in the output. If specified it overrides the value
- specified by the ``Generator``\ or *msg*\ 's ``policy``.
+ If *linesep* is not ``None``, use it as the separator character between
+ all the lines of the flattened message. If *linesep* is ``None`` (the
+ default), use the value specified in the *policy*.
+
+ .. XXX: flatten should take a *policy* keyword.
+
+ .. versionchanged:: 3.2
+ Added support for re-encoding ``8bit`` message bodies, and the
+ *linesep* argument.
+
.. method:: clone(fp)
- Return an independent clone of this :class:`BytesGenerator` instance with
- the exact same options.
+ Return an independent clone of this :class:`Generator` instance with the
+ exact same options, and *fp* as the new *outfp*.
+
.. method:: write(s)
- Write the string *s* to the underlying file object. *s* is encoded using
- the ``ASCII`` codec and written to the *write* method of the *outfp*
- *outfp* passed to the :class:`BytesGenerator`'s constructor. This
- provides just enough file-like API for :class:`BytesGenerator` instances
- to be used in the :func:`print` function.
+ Write *s* to the *write* method of the *outfp* passed to the
+ :class:`Generator`'s constructor. This provides just enough file-like
+ API for :class:`Generator` instances to be used in the :func:`print`
+ function.
- .. versionadded:: 3.2
-The :mod:`email.generator` module also provides a derived class, called
-:class:`DecodedGenerator` which is like the :class:`Generator` base class,
-except that non-\ :mimetype:`text` parts are substituted with a format string
-representing the part.
+As a convenience, :class:`~email.message.EmailMessage` provides the methods
+:meth:`~email.message.EmailMessage.as_string` and ``str(aMessage)`` (a.k.a.
+:meth:`~email.message.EmailMessage.__str__`), which simplify the generation of
+a formatted string representation of a message object. For more detail, see
+:mod:`email.message`.
+
+The :mod:`email.generator` module also provides a derived class,
+:class:`DecodedGenerator`, which is like the :class:`Generator` base class,
+except that non-\ :mimetype:`text` parts are not serialized, but are instead
+represented in the output stream by a string derived from a template filled
+in with information about the part.
-.. class:: DecodedGenerator(outfp, mangle_from_=True, maxheaderlen=78, fmt=None)
+.. class:: DecodedGenerator(outfp, mangle_from_=None, maxheaderlen=None, \
+ fmt=None, *, policy=None)
- This class, derived from :class:`Generator` walks through all the subparts of a
- message. If the subpart is of main type :mimetype:`text`, then it prints the
- decoded payload of the subpart. Optional *_mangle_from_* and *maxheaderlen* are
- as with the :class:`Generator` base class.
+ Act like :class:`Generator`, except that for any subpart of the message
+ passed to :meth:`Generator.flatten`, if the subpart is of main type
+ :mimetype:`text`, print the decoded payload of the subpart, and if the main
+ type is not :mimetype:`text`, instead of printing it fill in the string
+ *fmt* using information from the part and print the resulting
+ filled-in string.
- If the subpart is not of main type :mimetype:`text`, optional *fmt* is a format
- string that is used instead of the message payload. *fmt* is expanded with the
- following keywords, ``%(keyword)s`` format:
+ To fill in *fmt*, execute ``fmt % part_info``, where ``part_info``
+ is a dictionary composed of the following keys and values:
* ``type`` -- Full MIME type of the non-\ :mimetype:`text` part
@@ -225,15 +259,21 @@ representing the part.
* ``encoding`` -- Content transfer encoding of the non-\ :mimetype:`text` part
- The default value for *fmt* is ``None``, meaning ::
+ If *fmt* is ``None``, use the following default *fmt*:
+
+ "[Non-text (%(type)s) part of message omitted, filename %(filename)s]"
- [Non-text (%(type)s) part of message omitted, filename %(filename)s]
+ Optional *_mangle_from_* and *maxheaderlen* are as with the
+ :class:`Generator` base class.
.. rubric:: Footnotes
-.. [#] This statement assumes that you use the appropriate setting for the
- ``unixfrom`` argument, and that you set maxheaderlen=0 (which will
- preserve whatever the input line lengths were). It is also not strictly
- true, since in many cases runs of whitespace in headers are collapsed
- into single blanks. The latter is a bug that will eventually be fixed.
+.. [#] This statement assumes that you use the appropriate setting for
+ ``unixfrom``, and that there are no :mod:`policy` settings calling for
+ automatic adjustments (for example,
+ :attr:`~email.policy.Policy.refold_source` must be ``none``, which is
+ *not* the default). It is also not 100% true, since if the message
+ does not conform to the RFC standards occasionally information about the
+ exact original text is lost during parsing error recovery. It is a goal
+ to fix these latter edge cases when possible.
diff --git a/Doc/library/email.header.rst b/Doc/library/email.header.rst
index e94837c..07152c2 100644
--- a/Doc/library/email.header.rst
+++ b/Doc/library/email.header.rst
@@ -8,6 +8,14 @@
--------------
+This module is part of the legacy (``Compat32``) email API. In the current API
+encoding and decoding of headers is handled transparently by the
+dictionary-like API of the :class:`~email.message.EmailMessage` class. In
+addition to uses in legacy code, this module can be useful in applications that
+need to completely control the character sets used when encoding headers.
+
+The remaining text in this section is the original documentation of the module.
+
:rfc:`2822` is the base standard that describes the format of email messages.
It derives from the older :rfc:`822` standard which came into widespread use at
a time when most email was composed of ASCII characters only. :rfc:`2822` is a
diff --git a/Doc/library/email.headerregistry.rst b/Doc/library/email.headerregistry.rst
index 0707bd8..2c830cf 100644
--- a/Doc/library/email.headerregistry.rst
+++ b/Doc/library/email.headerregistry.rst
@@ -7,20 +7,12 @@
.. moduleauthor:: R. David Murray <rdmurray@bitdance.com>
.. sectionauthor:: R. David Murray <rdmurray@bitdance.com>
-.. versionadded:: 3.3
- as a :term:`provisional module <provisional package>`.
-
**Source code:** :source:`Lib/email/headerregistry.py`
-.. note::
-
- The headerregistry module has been included in the standard library on a
- :term:`provisional basis <provisional package>`. Backwards incompatible
- changes (up to and including removal of the module) may occur if deemed
- necessary by the core developers.
-
--------------
+.. versionadded:: 3.6 [1]_
+
Headers are represented by customized subclasses of :class:`str`. The
particular class used to represent a given header is determined by the
:attr:`~email.policy.EmailPolicy.header_factory` of the :mod:`~email.policy` in
@@ -86,10 +78,11 @@ headers.
.. method:: fold(*, policy)
Return a string containing :attr:`~email.policy.Policy.linesep`
- characters as required to correctly fold the header according
- to *policy*. A :attr:`~email.policy.Policy.cte_type` of
- ``8bit`` will be treated as if it were ``7bit``, since strings
- may not contain binary data.
+ characters as required to correctly fold the header according to
+ *policy*. A :attr:`~email.policy.Policy.cte_type` of ``8bit`` will be
+ treated as if it were ``7bit``, since headers may not contain arbitrary
+ binary data. If :attr:`~email.policy.EmailPolicy.utf8` is ``False``,
+ non-ASCII data will be :rfc:`2047` encoded.
``BaseHeader`` by itself cannot be used to create a header object. It
@@ -106,7 +99,7 @@ headers.
values for at least the keys ``decoded`` and ``defects``. ``decoded``
should be the string value for the header (that is, the header value fully
decoded to unicode). The parse method should assume that *string* may
- contain transport encoded parts, but should correctly handle all valid
+ contain content-transfer-encoded parts, but should correctly handle all valid
unicode characters as well so that it can parse un-encoded header values.
``BaseHeader``'s ``__new__`` then creates the header instance, and calls its
@@ -135,11 +128,10 @@ headers.
mechanism for encoding non-ASCII text as ASCII characters within a header
value. When a *value* containing encoded words is passed to the
constructor, the ``UnstructuredHeader`` parser converts such encoded words
- back in to the original unicode, following the :rfc:`2047` rules for
- unstructured text. The parser uses heuristics to attempt to decode certain
- non-compliant encoded words. Defects are registered in such cases, as well
- as defects for issues such as invalid characters within the encoded words or
- the non-encoded text.
+ into unicode, following the :rfc:`2047` rules for unstructured text. The
+ parser uses heuristics to attempt to decode certain non-compliant encoded
+ words. Defects are registered in such cases, as well as defects for issues
+ such as invalid characters within the encoded words or the non-encoded text.
This header type provides no additional attributes.
@@ -213,15 +205,16 @@ headers.
the list of addresses is "flattened" into a one dimensional list).
The ``decoded`` value of the header will have all encoded words decoded to
- unicode. :class:`~encodings.idna` encoded domain names are also decoded to unicode. The
- ``decoded`` value is set by :attr:`~str.join`\ ing the :class:`str` value of
- the elements of the ``groups`` attribute with ``', '``.
+ unicode. :class:`~encodings.idna` encoded domain names are also decoded to
+ unicode. The ``decoded`` value is set by :attr:`~str.join`\ ing the
+ :class:`str` value of the elements of the ``groups`` attribute with ``',
+ '``.
A list of :class:`.Address` and :class:`.Group` objects in any combination
may be used to set the value of an address header. ``Group`` objects whose
``display_name`` is ``None`` will be interpreted as single addresses, which
allows an address list to be copied with groups intact by using the list
- obtained ``groups`` attribute of the source header.
+ obtained from the ``groups`` attribute of the source header.
.. class:: SingleAddressHeader
@@ -267,7 +260,7 @@ variant, :attr:`~.BaseHeader.max_count` is set to 1.
.. class:: ParameterizedMIMEHeader
- MOME headers all start with the prefix 'Content-'. Each specific header has
+ MIME headers all start with the prefix 'Content-'. Each specific header has
a certain value, described under the class for that header. Some can
also take a list of supplemental parameters, which have a common format.
This class serves as a base for all the MIME headers that take parameters.
@@ -454,3 +447,9 @@ construct structured values to assign to specific headers.
``display_name`` is none and there is a single ``Address`` in the
``addresses`` list, the ``str`` value will be the same as the ``str`` of
that single ``Address``.
+
+
+.. rubric:: Footnotes
+
+.. [1] Oringally added in 3.3 as a :term:`provisional module <provisional
+ package>`
diff --git a/Doc/library/email.message.rst b/Doc/library/email.message.rst
index 2907975..32852e7 100644
--- a/Doc/library/email.message.rst
+++ b/Doc/library/email.message.rst
@@ -3,91 +3,102 @@
.. module:: email.message
:synopsis: The base class representing email messages.
+.. moduleauthor:: R. David Murray <rdmurray@bitdance.com>
+.. sectionauthor:: R. David Murray <rdmurray@bitdance.com>,
+ Barry A. Warsaw <barry@python.org>
**Source code:** :source:`Lib/email/message.py`
--------------
-The central class in the :mod:`email` package is the :class:`Message` class,
-imported from the :mod:`email.message` module. It is the base class for the
-:mod:`email` object model. :class:`Message` provides the core functionality for
-setting and querying header fields, and for accessing message bodies.
-
-Conceptually, a :class:`Message` object consists of *headers* and *payloads*.
-Headers are :rfc:`2822` style field names and values where the field name and
-value are separated by a colon. The colon is not part of either the field name
-or the field value.
-
-Headers are stored and returned in case-preserving form but are matched
-case-insensitively. There may also be a single envelope header, also known as
-the *Unix-From* header or the ``From_`` header. The payload is either a string
-in the case of simple message objects or a list of :class:`Message` objects for
-MIME container documents (e.g. :mimetype:`multipart/\*` and
-:mimetype:`message/rfc822`).
-
-:class:`Message` objects provide a mapping style interface for accessing the
-message headers, and an explicit interface for accessing both the headers and
-the payload. It provides convenience methods for generating a flat text
-representation of the message object tree, for accessing commonly used header
-parameters, and for recursively walking over the object tree.
-
-Here are the methods of the :class:`Message` class:
-
-
-.. class:: Message(policy=compat32)
-
- If *policy* is specified (it must be an instance of a :mod:`~email.policy`
- class) use the rules it specifies to update and serialize the representation
- of the message. If *policy* is not set, use the :class:`compat32
- <email.policy.Compat32>` policy, which maintains backward compatibility with
- the Python 3.2 version of the email package. For more information see the
+.. versionadded:: 3.6 [1]_
+
+The central class in the :mod:`email` package is the :class:`EmailMessage`
+class, imported from the :mod:`email.message` module. It is the base class for
+the :mod:`email` object model. :class:`EmailMessage` provides the core
+functionality for setting and querying header fields, for accessing message
+bodies, and for creating or modifying structured messages.
+
+An email message consists of *headers* and a *payload* (which is also referred
+to as the *content*). Headers are :rfc:`5322` or :rfc:`6532` style field names
+and values, where the field name and value are separated by a colon. The colon
+is not part of either the field name or the field value. The payload may be a
+simple text message, or a binary object, or a structured sequence of
+sub-messages each with their own set of headers and their own payload. The
+latter type of payload is indicated by the message having a MIME type such as
+:mimetype:`multipart/\*` or :mimetype:`message/rfc822`.
+
+The conceptual model provided by an :class:`EmailMessage` object is that of an
+ordered dictionary of headers coupled with a *payload* that represents the
+:rfc:`5322` body of the message, which might be a list of sub-``EmailMessage``
+objects. In addition to the normal dictionary methods for accessing the header
+names and values, there are methods for accessing specialized information from
+the headers (for example the MIME content type), for operating on the payload,
+for generating a serialized version of the message, and for recursively walking
+over the object tree.
+
+The :class:`EmailMessage` dictionary-like interface is indexed by the header
+names, which must be ASCII values. The values of the dictionary are strings
+with some extra methods. Headers are stored and returned in case-preserving
+form, but field names are matched case-insensitively. Unlike a real dict,
+there is an ordering to the keys, and there can be duplicate keys. Additional
+methods are provided for working with headers that have duplicate keys.
+
+The *payload* is either a string or bytes object, in the case of simple message
+objects, or a list of :class:`EmailMessage` objects, for MIME container
+documents such as :mimetype:`multipart/\*` and :mimetype:`message/rfc822`
+message objects.
+
+
+.. class:: EmailMessage(policy=default)
+
+ If *policy* is specified use the rules it specifies to udpate and serialize
+ the representation of the message. If *policy* is not set, use the
+ :class:`~email.policy.default` policy, which follows the rules of the email
+ RFCs except for line endings (instead of the RFC mandated ``\r\n``, it uses
+ the Python standard ``\n`` line endings). For more information see the
:mod:`~email.policy` documentation.
- .. versionchanged:: 3.3 The *policy* keyword argument was added.
-
-
- .. method:: as_string(unixfrom=False, maxheaderlen=0, policy=None)
-
- Return the entire message flattened as a string. When optional *unixfrom*
- is true, the envelope header is included in the returned string.
- *unixfrom* defaults to ``False``. For backward compabitility reasons,
- *maxheaderlen* defaults to ``0``, so if you want a different value you
- must override it explicitly (the value specified for *max_line_length* in
- the policy will be ignored by this method). The *policy* argument may be
- used to override the default policy obtained from the message instance.
- This can be used to control some of the formatting produced by the
- method, since the specified *policy* will be passed to the ``Generator``.
-
- Flattening the message may trigger changes to the :class:`Message` if
- defaults need to be filled in to complete the transformation to a string
- (for example, MIME boundaries may be generated or modified).
-
- Note that this method is provided as a convenience and may not always
- format the message the way you want. For example, by default it does
- not do the mangling of lines that begin with ``From`` that is
- required by the unix mbox format. For more flexibility, instantiate a
- :class:`~email.generator.Generator` instance and use its
- :meth:`~email.generator.Generator.flatten` method directly. For example::
-
- from io import StringIO
- from email.generator import Generator
- fp = StringIO()
- g = Generator(fp, mangle_from_=True, maxheaderlen=60)
- g.flatten(msg)
- text = fp.getvalue()
+ .. method:: as_string(unixfrom=False, maxheaderlen=None, policy=None)
- If the message object contains binary data that is not encoded according
- to RFC standards, the non-compliant data will be replaced by unicode
- "unknown character" code points. (See also :meth:`.as_bytes` and
- :class:`~email.generator.BytesGenerator`.)
-
- .. versionchanged:: 3.4 the *policy* keyword argument was added.
+ Return the entire message flattened as a string. When optional
+ *unixfrom* is true, the envelope header is included in the returned
+ string. *unixfrom* defaults to ``False``. For backward compabitility
+ with the base :class:`~email.message.Message` class *maxheaderlen* is
+ accepted, but defaults to ``None``, which means that by default the line
+ length is controlled by the
+ :attr:`~email.policy.EmailPolicy.max_line_length` of the policy. The
+ *policy* argument may be used to override the default policy obtained
+ from the message instance. This can be used to control some of the
+ formatting produced by the method, since the specified *policy* will be
+ passed to the :class:`~email.generator.Generator`.
+
+ Flattening the message may trigger changes to the :class:`EmailMessage`
+ if defaults need to be filled in to complete the transformation to a
+ string (for example, MIME boundaries may be generated or modified).
+
+ Note that this method is provided as a convenience and may not be the
+ most useful way to serialize messages in your application, especially if
+ you are dealing with multiple messages. See
+ :class:`email.generator.Generator` for a more flexible API for
+ serializing messages. Note also that this method is restricted to
+ producing messages serialized as "7 bit clean" when
+ :attr:`~email.policy.EmailPolicy.utf8` is ``False``, which is the default.
+
+ .. versionchanged:: 3.6 the default behavior when *maxheaderlen*
+ is not specified was changed from defaulting to 0 to defaulting
+ to the value of *max_line_length* from the policy.
.. method:: __str__()
- Equivalent to :meth:`.as_string()`. Allows ``str(msg)`` to produce a
- string containing the formatted message.
+ Equivalent to `as_string(policy=self.policy.clone(utf8=True)`. Allows
+ ``str(msg)`` to produce a string containing the serialized message in a
+ readable format.
+
+ .. versionchanged:: 3.4 the method was changed to use ``utf8=True``,
+ thus producing an :rfc:`6531`-like message representation, instead of
+ being a direct alias for :meth:`as_string`.
.. method:: as_bytes(unixfrom=False, policy=None)
@@ -98,52 +109,42 @@ Here are the methods of the :class:`Message` class:
used to override the default policy obtained from the message instance.
This can be used to control some of the formatting produced by the
method, since the specified *policy* will be passed to the
- ``BytesGenerator``.
-
- Flattening the message may trigger changes to the :class:`Message` if
- defaults need to be filled in to complete the transformation to a string
- (for example, MIME boundaries may be generated or modified).
+ :class:`~email.generator.BytesGenerator`.
- Note that this method is provided as a convenience and may not always
- format the message the way you want. For example, by default it does
- not do the mangling of lines that begin with ``From`` that is
- required by the unix mbox format. For more flexibility, instantiate a
- :class:`~email.generator.BytesGenerator` instance and use its
- :meth:`~email.generator.BytesGenerator.flatten` method directly.
- For example::
+ Flattening the message may trigger changes to the :class:`EmailMessage`
+ if defaults need to be filled in to complete the transformation to a
+ string (for example, MIME boundaries may be generated or modified).
- from io import BytesIO
- from email.generator import BytesGenerator
- fp = BytesIO()
- g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
- g.flatten(msg)
- text = fp.getvalue()
-
- .. versionadded:: 3.4
+ Note that this method is provided as a convenience and may not be the
+ most useful way to serialize messages in your application, especially if
+ you are dealing with multiple messages. See
+ :class:`email.generator.BytesGenerator` for a more flexible API for
+ serializing messages.
.. method:: __bytes__()
Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a
- bytes object containing the formatted message.
-
- .. versionadded:: 3.4
+ bytes object containing the serialized message.
.. method:: is_multipart()
Return ``True`` if the message's payload is a list of sub-\
- :class:`Message` objects, otherwise return ``False``. When
+ :class:`EmailMessage` objects, otherwise return ``False``. When
:meth:`is_multipart` returns ``False``, the payload should be a string
- object. (Note that :meth:`is_multipart` returning ``True`` does not
- necessarily mean that "msg.get_content_maintype() == 'multipart'" will
- return the ``True``. For example, ``is_multipart`` will return ``True``
- when the :class:`Message` is of type ``message/rfc822``.)
+ object (which might be a CTE encoded binary payload). Note that
+ :meth:`is_multipart` returning ``True`` does not necessarily mean that
+ "msg.get_content_maintype() == 'multipart'" will return the ``True``.
+ For example, ``is_multipart`` will return ``True`` when the
+ :class:`EmailMessage` is of type ``message/rfc822``.
.. method:: set_unixfrom(unixfrom)
- Set the message's envelope header to *unixfrom*, which should be a string.
+ Set the message's envelope header to *unixfrom*, which should be a
+ string. (See :class:`~mailbox.mboxMessage` for a brief description of
+ this header.)
.. method:: get_unixfrom()
@@ -152,109 +153,23 @@ Here are the methods of the :class:`Message` class:
envelope header was never set.
- .. method:: attach(payload)
-
- Add the given *payload* to the current payload, which must be ``None`` or
- a list of :class:`Message` objects before the call. After the call, the
- payload will always be a list of :class:`Message` objects. If you want to
- set the payload to a scalar object (e.g. a string), use
- :meth:`set_payload` instead.
-
-
- .. method:: get_payload(i=None, decode=False)
-
- Return the current payload, which will be a list of
- :class:`Message` objects when :meth:`is_multipart` is ``True``, or a
- string when :meth:`is_multipart` is ``False``. If the payload is a list
- and you mutate the list object, you modify the message's payload in place.
-
- With optional argument *i*, :meth:`get_payload` will return the *i*-th
- element of the payload, counting from zero, if :meth:`is_multipart` is
- ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or
- greater than or equal to the number of items in the payload. If the
- payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is
- given, a :exc:`TypeError` is raised.
-
- Optional *decode* is a flag indicating whether the payload should be
- decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
- header. When ``True`` and the message is not a multipart, the payload will
- be decoded if this header's value is ``quoted-printable`` or ``base64``.
- If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
- header is missing, the payload is
- returned as-is (undecoded). In all cases the returned value is binary
- data. If the message is a multipart and the *decode* flag is ``True``,
- then ``None`` is returned. If the payload is base64 and it was not
- perfectly formed (missing padding, characters outside the base64
- alphabet), then an appropriate defect will be added to the message's
- defect property (:class:`~email.errors.InvalidBase64PaddingDefect` or
- :class:`~email.errors.InvalidBase64CharactersDefect`, respectively).
-
- When *decode* is ``False`` (the default) the body is returned as a string
- without decoding the :mailheader:`Content-Transfer-Encoding`. However,
- for a :mailheader:`Content-Transfer-Encoding` of 8bit, an attempt is made
- to decode the original bytes using the ``charset`` specified by the
- :mailheader:`Content-Type` header, using the ``replace`` error handler.
- If no ``charset`` is specified, or if the ``charset`` given is not
- recognized by the email package, the body is decoded using the default
- ASCII charset.
-
-
- .. method:: set_payload(payload, charset=None)
-
- Set the entire message object's payload to *payload*. It is the client's
- responsibility to ensure the payload invariants. Optional *charset* sets
- the message's default character set; see :meth:`set_charset` for details.
-
- .. method:: set_charset(charset)
-
- Set the character set of the payload to *charset*, which can either be a
- :class:`~email.charset.Charset` instance (see :mod:`email.charset`), a
- string naming a character set, or ``None``. If it is a string, it will
- be converted to a :class:`~email.charset.Charset` instance. If *charset*
- is ``None``, the ``charset`` parameter will be removed from the
- :mailheader:`Content-Type` header (the message will not be otherwise
- modified). Anything else will generate a :exc:`TypeError`.
-
- If there is no existing :mailheader:`MIME-Version` header one will be
- added. If there is no existing :mailheader:`Content-Type` header, one
- will be added with a value of :mimetype:`text/plain`. Whether the
- :mailheader:`Content-Type` header already exists or not, its ``charset``
- parameter will be set to *charset.output_charset*. If
- *charset.input_charset* and *charset.output_charset* differ, the payload
- will be re-encoded to the *output_charset*. If there is no existing
- :mailheader:`Content-Transfer-Encoding` header, then the payload will be
- transfer-encoded, if needed, using the specified
- :class:`~email.charset.Charset`, and a header with the appropriate value
- will be added. If a :mailheader:`Content-Transfer-Encoding` header
- already exists, the payload is assumed to already be correctly encoded
- using that :mailheader:`Content-Transfer-Encoding` and is not modified.
-
- .. method:: get_charset()
-
- Return the :class:`~email.charset.Charset` instance associated with the
- message's payload.
-
- The following methods implement a mapping-like interface for accessing the
- message's :rfc:`2822` headers. Note that there are some semantic differences
+ The following methods implement the mapping-like interface for accessing the
+ message's headers. Note that there are some semantic differences
between these methods and a normal mapping (i.e. dictionary) interface. For
example, in a dictionary there are no duplicate keys, but here there may be
duplicate message headers. Also, in dictionaries there is no guaranteed
- order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
- headers are always returned in the order they appeared in the original
- message, or were added to the message later. Any header deleted and then
- re-added are always appended to the end of the header list.
+ order to the keys returned by :meth:`keys`, but in an :class:`EmailMessage`
+ object, headers are always returned in the order they appeared in the
+ original message, or in which they were added to the message later. Any
+ header deleted and then re-added is always appended to the end of the
+ header list.
- These semantic differences are intentional and are biased toward maximal
- convenience.
+ These semantic differences are intentional and are biased toward
+ convenience in the most common use cases.
Note that in all cases, any envelope header present in the message is not
included in the mapping interface.
- In a model generated from bytes, any header values that (in contravention of
- the RFCs) contain non-ASCII bytes will, when retrieved through this
- interface, be represented as :class:`~email.header.Header` objects with
- a charset of `unknown-8bit`.
-
.. method:: __len__()
@@ -264,8 +179,8 @@ Here are the methods of the :class:`Message` class:
.. method:: __contains__(name)
Return true if the message object has a field named *name*. Matching is
- done case-insensitively and *name* should not include the trailing colon.
- Used for the ``in`` operator, e.g.::
+ done without regard to case and *name* does not include the trailing
+ colon. Used for the ``in`` operator. For example::
if 'message-id' in myMessage:
print('Message-ID:', myMessage['message-id'])
@@ -273,20 +188,23 @@ Here are the methods of the :class:`Message` class:
.. method:: __getitem__(name)
- Return the value of the named header field. *name* should not include the
+ Return the value of the named header field. *name* does not include the
colon field separator. If the header is missing, ``None`` is returned; a
:exc:`KeyError` is never raised.
Note that if the named field appears more than once in the message's
headers, exactly which of those field values will be returned is
undefined. Use the :meth:`get_all` method to get the values of all the
- extant named headers.
+ extant headers named *name*.
+
+ Using the standard (non-``compat32``) policies, the returned value is an
+ instance of a subclass of :class:`email.headerregistry.BaseHeader`.
.. method:: __setitem__(name, val)
Add a header to the message with field name *name* and value *val*. The
- field is appended to the end of the message's existing fields.
+ field is appended to the end of the message's existing headers.
Note that this does *not* overwrite or delete any existing header with the same
name. If you want to ensure that the new header is the only one present in the
@@ -295,6 +213,13 @@ Here are the methods of the :class:`Message` class:
del msg['subject']
msg['subject'] = 'Python roolz!'
+ If the :mod:`policy` defines certain haders to be unique (as the standard
+ policies do), this method may raise a :exc:`ValueError` when an attempt
+ is made to assign a value to such a header when one already exists. This
+ behavior is intentional for consistency's sake, but do not depend on it
+ as we may choose to make such assignments do an automatic deletion of the
+ existing header in the future.
+
.. method:: __delitem__(name)
@@ -323,9 +248,10 @@ Here are the methods of the :class:`Message` class:
Return the value of the named header field. This is identical to
:meth:`__getitem__` except that optional *failobj* is returned if the
- named header is missing (defaults to ``None``).
+ named header is missing (*failobj* defaults to ``None``).
- Here are some additional useful methods:
+
+ Here are some additional useful header related methods:
.. method:: get_all(name, failobj=None)
@@ -346,17 +272,19 @@ Here are the methods of the :class:`Message` class:
taken as the parameter name, with underscores converted to dashes (since
dashes are illegal in Python identifiers). Normally, the parameter will
be added as ``key="value"`` unless the value is ``None``, in which case
- only the key will be added. If the value contains non-ASCII characters,
- it can be specified as a three tuple in the format
- ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the
- charset to be used to encode the value, ``LANGUAGE`` can usually be set
- to ``None`` or the empty string (see :rfc:`2231` for other possibilities),
- and ``VALUE`` is the string value containing non-ASCII code points. If
- a three tuple is not passed and the value contains non-ASCII characters,
- it is automatically encoded in :rfc:`2231` format using a ``CHARSET``
- of ``utf-8`` and a ``LANGUAGE`` of ``None``.
-
- Here's an example::
+ only the key will be added.
+
+ If the value contains non-ASCII characters, the charset and language may
+ be explicitly controlled by specifying the value as a three tuple in the
+ format ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string
+ naming the charset to be used to encode the value, ``LANGUAGE`` can
+ usually be set to ``None`` or the empty string (see :rfc:`2231` for other
+ possibilities), and ``VALUE`` is the string value containing non-ASCII
+ code points. If a three tuple is not passed and the value contains
+ non-ASCII characters, it is automatically encoded in :rfc:`2231` format
+ using a ``CHARSET`` of ``utf-8`` and a ``LANGUAGE`` of ``None``.
+
+ Here is an example::
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
@@ -364,37 +292,35 @@ Here are the methods of the :class:`Message` class:
Content-Disposition: attachment; filename="bud.gif"
- An example with non-ASCII characters::
+ An example of the extended interface with non-ASCII characters::
msg.add_header('Content-Disposition', 'attachment',
filename=('iso-8859-1', '', 'Fußballer.ppt'))
- Which produces ::
-
- Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"
-
.. method:: replace_header(_name, _value)
Replace a header. Replace the first header found in the message that
- matches *_name*, retaining header order and field name case. If no
- matching header was found, a :exc:`KeyError` is raised.
+ matches *_name*, retaining header order and field name case of the
+ original header. If no matching header is found, raise a
+ :exc:`KeyError`.
.. method:: get_content_type()
- Return the message's content type. The returned string is coerced to
- lower case of the form :mimetype:`maintype/subtype`. If there was no
- :mailheader:`Content-Type` header in the message the default type as given
- by :meth:`get_default_type` will be returned. Since according to
- :rfc:`2045`, messages always have a default type, :meth:`get_content_type`
- will always return a value.
+ Return the message's content type, coerced to lower case of the form
+ :mimetype:`maintype/subtype`. If there is no :mailheader:`Content-Type`
+ header in the message return the value returned by
+ :meth:`get_default_type`. If the :mailheader:`Content-Type` header is
+ invalid, return ``text/plain``.
- :rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
- unless it appears inside a :mimetype:`multipart/digest` container, in
- which case it would be :mimetype:`message/rfc822`. If the
- :mailheader:`Content-Type` header has an invalid type specification,
- :rfc:`2045` mandates that the default type be :mimetype:`text/plain`.
+ (According to :rfc:`2045`, messages always have a default type,
+ :meth:`get_content_type` will always return a value. :rfc:`2045` defines
+ a message's default type to be :mimetype:`text/plain` unless it appears
+ inside a :mimetype:`multipart/digest` container, in which case it would
+ be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header
+ has an invalid type specification, :rfc:`2045` mandates that the default
+ type be :mimetype:`text/plain`.)
.. method:: get_content_maintype()
@@ -420,81 +346,41 @@ Here are the methods of the :class:`Message` class:
.. method:: set_default_type(ctype)
Set the default content type. *ctype* should either be
- :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
- enforced. The default content type is not stored in the
- :mailheader:`Content-Type` header.
-
-
- .. method:: get_params(failobj=None, header='content-type', unquote=True)
-
- Return the message's :mailheader:`Content-Type` parameters, as a list.
- The elements of the returned list are 2-tuples of key/value pairs, as
- split on the ``'='`` sign. The left hand side of the ``'='`` is the key,
- while the right hand side is the value. If there is no ``'='`` sign in
- the parameter the value is the empty string, otherwise the value is as
- described in :meth:`get_param` and is unquoted if optional *unquote* is
- ``True`` (the default).
-
- Optional *failobj* is the object to return if there is no
- :mailheader:`Content-Type` header. Optional *header* is the header to
- search instead of :mailheader:`Content-Type`.
-
-
- .. method:: get_param(param, failobj=None, header='content-type', unquote=True)
-
- Return the value of the :mailheader:`Content-Type` header's parameter
- *param* as a string. If the message has no :mailheader:`Content-Type`
- header or if there is no such parameter, then *failobj* is returned
- (defaults to ``None``).
-
- Optional *header* if given, specifies the message header to use instead of
- :mailheader:`Content-Type`.
-
- Parameter keys are always compared case insensitively. The return value
- can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
- encoded. When it's a 3-tuple, the elements of the value are of the form
- ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and
- ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
- to be encoded in the ``us-ascii`` charset. You can usually ignore
- ``LANGUAGE``.
-
- If your application doesn't care whether the parameter was encoded as in
- :rfc:`2231`, you can collapse the parameter value by calling
- :func:`email.utils.collapse_rfc2231_value`, passing in the return value
- from :meth:`get_param`. This will return a suitably decoded Unicode
- string when the value is a tuple, or the original string unquoted if it
- isn't. For example::
-
- rawparam = msg.get_param('foo')
- param = email.utils.collapse_rfc2231_value(rawparam)
-
- In any case, the parameter value (either the returned string, or the
- ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
- to ``False``.
+ :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is
+ not enforced. The default content type is not stored in the
+ :mailheader:`Content-Type` header, so it only affects the return value of
+ the ``get_content_type`` methods when no :mailheader:`Content-Type`
+ header is present in the message.
.. method:: set_param(param, value, header='Content-Type', requote=True, \
charset=None, language='', replace=False)
Set a parameter in the :mailheader:`Content-Type` header. If the
- parameter already exists in the header, its value will be replaced with
- *value*. If the :mailheader:`Content-Type` header as not yet been defined
- for this message, it will be set to :mimetype:`text/plain` and the new
- parameter value will be appended as per :rfc:`2045`.
-
- Optional *header* specifies an alternative header to
- :mailheader:`Content-Type`, and all parameters will be quoted as necessary
- unless optional *requote* is ``False`` (the default is ``True``).
-
- If optional *charset* is specified, the parameter will be encoded
- according to :rfc:`2231`. Optional *language* specifies the RFC 2231
- language, defaulting to the empty string. Both *charset* and *language*
- should be strings.
+ parameter already exists in the header, replace its value with *value*.
+ When *header* is ``Content-Type`` (the default) and the header does not
+ yet exist in the message, add it, set its value to
+ :mimetype:`text/plain`, and append the new parameter value. Optional
+ *header* specifies an alternative header to :mailheader:`Content-Type`.
+
+ If the value contains non-ASCII characters, the charset and language may
+ be explicity specified using the optional *charset* and *language*
+ parameters. Optional *language* specifies the :rfc:`2231` language,
+ defaulting to the empty string. Both *charset* and *language* should be
+ strings. The default is to use the ``utf8`` *charset* and ``None`` for
+ the *language*.
If *replace* is ``False`` (the default) the header is moved to the
end of the list of headers. If *replace* is ``True``, the header
will be updated in place.
+ Use of the *requote* parameter with :class:`EmailMessage` objects is
+ deprecated.
+
+ Note that existing parameter values of headers may be accessed through
+ the :attr:`~email.headerregistry.BaseHeader.params` attribute of the
+ header value (for example, ``msg['Content-Type'].params['charset']``.
+
.. versionchanged:: 3.4 ``replace`` keyword was added.
@@ -502,25 +388,11 @@ Here are the methods of the :class:`Message` class:
Remove the given parameter completely from the :mailheader:`Content-Type`
header. The header will be re-written in place without the parameter or
- its value. All values will be quoted as necessary unless *requote* is
- ``False`` (the default is ``True``). Optional *header* specifies an
- alternative to :mailheader:`Content-Type`.
-
-
- .. method:: set_type(type, header='Content-Type', requote=True)
-
- Set the main type and subtype for the :mailheader:`Content-Type`
- header. *type* must be a string in the form :mimetype:`maintype/subtype`,
- otherwise a :exc:`ValueError` is raised.
-
- This method replaces the :mailheader:`Content-Type` header, keeping all
- the parameters in place. If *requote* is ``False``, this leaves the
- existing header's quoting as is, otherwise the parameters will be quoted
- (the default).
+ its value. Optional *header* specifies an alternative to
+ :mailheader:`Content-Type`.
- An alternative header can be specified in the *header* argument. When the
- :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
- header is also added.
+ Use of the *requote* parameter with :class:`EmailMessage` objects is
+ deprecated.
.. method:: get_filename(failobj=None)
@@ -549,12 +421,11 @@ Here are the methods of the :class:`Message` class:
necessary. A :exc:`~email.errors.HeaderParseError` is raised if the
message object has no :mailheader:`Content-Type` header.
- Note that using this method is subtly different than deleting the old
+ Note that using this method is subtly different from deleting the old
:mailheader:`Content-Type` header and adding a new one with the new
boundary via :meth:`add_header`, because :meth:`set_boundary` preserves
the order of the :mailheader:`Content-Type` header in the list of
- headers. However, it does *not* preserve any continuation lines which may
- have been present in the original :mailheader:`Content-Type` header.
+ headers.
.. method:: get_content_charset(failobj=None)
@@ -563,9 +434,6 @@ Here are the methods of the :class:`Message` class:
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
that header has no ``charset`` parameter, *failobj* is returned.
- Note that this method differs from :meth:`get_charset` which returns the
- :class:`~email.charset.Charset` instance for the default encoding of the message body.
-
.. method:: get_charsets(failobj=None)
@@ -575,10 +443,19 @@ Here are the methods of the :class:`Message` class:
Each item in the list will be a string which is the value of the
``charset`` parameter in the :mailheader:`Content-Type` header for the
- represented subpart. However, if the subpart has no
- :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
- the :mimetype:`text` main MIME type, then that item in the returned list
- will be *failobj*.
+ represented subpart. If the subpart has no :mailheader:`Content-Type`
+ header, no ``charset`` parameter, or is not of the :mimetype:`text` main
+ MIME type, then that item in the returned list will be *failobj*.
+
+
+ .. method:: is_attachment
+
+ Return ``True`` if there is a :mailheader:`Content-Disposition` header
+ and its (case insensitive) value is ``attachment``, ``False`` otherwise.
+
+ .. versionchanged:: 3.4.2
+ is_attachment is now a method instead of a property, for consistency
+ with :meth:`~email.message.Message.is_multipart`.
.. method:: get_content_disposition()
@@ -590,6 +467,11 @@ Here are the methods of the :class:`Message` class:
.. versionadded:: 3.5
+
+ The following methods relate to interrogating and manipulating the content
+ (payload) of the message.
+
+
.. method:: walk()
The :meth:`walk` method is an all-purpose generator which can be used to
@@ -651,8 +533,169 @@ Here are the methods of the :class:`Message` class:
into the subparts.
- :class:`Message` objects can also optionally contain two instance attributes,
- which can be used when generating the plain text of a MIME message.
+ .. method:: get_body(preferencelist=('related', 'html', 'plain'))
+
+ Return the MIME part that is the best candidate to be the "body" of the
+ message.
+
+ *preferencelist* must be a sequence of strings from the set ``related``,
+ ``html``, and ``plain``, and indicates the order of preference for the
+ content type of the part returned.
+
+ Start looking for candidate matches with the object on which the
+ ``get_body`` method is called.
+
+ If ``related`` is not included in *preferencelist*, consider the root
+ part (or subpart of the root part) of any related encountered as a
+ candidate if the (sub-)part matches a preference.
+
+ When encountering a ``multipart/related``, check the ``start`` parameter
+ and if a part with a matching :mailheader:`Content-ID` is found, consider
+ only it when looking for candidate matches. Otherwise consider only the
+ first (default root) part of the ``multipart/related``.
+
+ If a part has a :mailheader:`Content-Disposition` header, only consider
+ the part a candidate match if the value of the header is ``inline``.
+
+ If none of the candidates matches any of the preferences in
+ *preferneclist*, return ``None``.
+
+ Notes: (1) For most applications the only *preferencelist* combinations
+ that really make sense are ``('plain',)``, ``('html', 'plain')``, and the
+ default ``('related', 'html', 'plain')``. (2) Because matching starts
+ with the object on which ``get_body`` is called, calling ``get_body`` on
+ a ``multipart/related`` will return the object itself unless
+ *preferencelist* has a non-default value. (3) Messages (or message parts)
+ that do not specify a :mailheader:`Content-Type` or whose
+ :mailheader:`Content-Type` header is invalid will be treated as if they
+ are of type ``text/plain``, which may occasionally cause ``get_body`` to
+ return unexpected results.
+
+
+ .. method:: iter_attachments()
+
+ Return an iterator over all of the immediate sub-parts of the message
+ that are not candidate "body" parts. That is, skip the first occurrence
+ of each of ``text/plain``, ``text/html``, ``multipart/related``, or
+ ``multipart/alternative`` (unless they are explicitly marked as
+ attachments via :mailheader:`Content-Disposition: attachment`), and
+ return all remaining parts. When applied directly to a
+ ``multipart/related``, return an iterator over the all the related parts
+ except the root part (ie: the part pointed to by the ``start`` parameter,
+ or the first part if there is no ``start`` parameter or the ``start``
+ parameter doesn't match the :mailheader:`Content-ID` of any of the
+ parts). When applied directly to a ``multipart/alternative`` or a
+ non-``multipart``, return an empty iterator.
+
+
+ .. method:: iter_parts()
+
+ Return an iterator over all of the immediate sub-parts of the message,
+ which will be empty for a non-``multipart``. (See also
+ :meth:`~email.message.EmailMessage.walk`.)
+
+
+ .. method:: get_content(*args, content_manager=None, **kw)
+
+ Call the :meth:`~email.contentmanager.ContentManager.get_content` method
+ of the *content_manager*, passing self as the message object, and passing
+ along any other arguments or keywords as additional arguments. If
+ *content_manager* is not specified, use the ``content_manager`` specified
+ by the current :mod:`~email.policy`.
+
+
+ .. method:: set_content(*args, content_manager=None, **kw)
+
+ Call the :meth:`~email.contentmanager.ContentManager.set_content` method
+ of the *content_manager*, passing self as the message object, and passing
+ along any other arguments or keywords as additional arguments. If
+ *content_manager* is not specified, use the ``content_manager`` specified
+ by the current :mod:`~email.policy`.
+
+
+ .. method:: make_related(boundary=None)
+
+ Convert a non-``multipart`` message into a ``multipart/related`` message,
+ moving any existing :mailheader:`Content-` headers and payload into a
+ (new) first part of the ``multipart``. If *boundary* is specified, use
+ it as the boundary string in the multipart, otherwise leave the boundary
+ to be automatically created when it is needed (for example, when the
+ message is serialized).
+
+
+ .. method:: make_alternative(boundary=None)
+
+ Convert a non-``multipart`` or a ``multipart/related`` into a
+ ``multipart/alternative``, moving any existing :mailheader:`Content-`
+ headers and payload into a (new) first part of the ``multipart``. If
+ *boundary* is specified, use it as the boundary string in the multipart,
+ otherwise leave the boundary to be automatically created when it is
+ needed (for example, when the message is serialized).
+
+
+ .. method:: make_mixed(boundary=None)
+
+ Convert a non-``multipart``, a ``multipart/related``, or a
+ ``multipart-alternative`` into a ``multipart/mixed``, moving any existing
+ :mailheader:`Content-` headers and payload into a (new) first part of the
+ ``multipart``. If *boundary* is specified, use it as the boundary string
+ in the multipart, otherwise leave the boundary to be automatically
+ created when it is needed (for example, when the message is serialized).
+
+
+ .. method:: add_related(*args, content_manager=None, **kw)
+
+ If the message is a ``multipart/related``, create a new message
+ object, pass all of the arguments to its :meth:`set_content` method,
+ and :meth:`~email.message.Message.attach` it to the ``multipart``. If
+ the message is a non-``multipart``, call :meth:`make_related` and then
+ proceed as above. If the message is any other type of ``multipart``,
+ raise a :exc:`TypeError`. If *content_manager* is not specified, use
+ the ``content_manager`` specified by the current :mod:`~email.policy`.
+ If the added part has no :mailheader:`Content-Disposition` header,
+ add one with the value ``inline``.
+
+
+ .. method:: add_alternative(*args, content_manager=None, **kw)
+
+ If the message is a ``multipart/alternative``, create a new message
+ object, pass all of the arguments to its :meth:`set_content` method, and
+ :meth:`~email.message.Message.attach` it to the ``multipart``. If the
+ message is a non-``multipart`` or ``multipart/related``, call
+ :meth:`make_alternative` and then proceed as above. If the message is
+ any other type of ``multipart``, raise a :exc:`TypeError`. If
+ *content_manager* is not specified, use the ``content_manager`` specified
+ by the current :mod:`~email.policy`.
+
+
+ .. method:: add_attachment(*args, content_manager=None, **kw)
+
+ If the message is a ``multipart/mixed``, create a new message object,
+ pass all of the arguments to its :meth:`set_content` method, and
+ :meth:`~email.message.Message.attach` it to the ``multipart``. If the
+ message is a non-``multipart``, ``multipart/related``, or
+ ``multipart/alternative``, call :meth:`make_mixed` and then proceed as
+ above. If *content_manager* is not specified, use the ``content_manager``
+ specified by the current :mod:`~email.policy`. If the added part
+ has no :mailheader:`Content-Disposition` header, add one with the value
+ ``attachment``. This method can be used both for explicit attachments
+ (:mailheader:`Content-Disposition: attachment` and ``inline`` attachments
+ (:mailheader:`Content-Disposition: inline`), by passing appropriate
+ options to the ``content_manager``.
+
+
+ .. method:: clear()
+
+ Remove the payload and all of the headers.
+
+
+ .. method:: clear_content()
+
+ Remove the payload and all of the :exc:`Content-` headers, leaving
+ all other headers intact and in their original order.
+
+
+ :class:`EmailMessage` objects have the following instance attributes:
.. attribute:: preamble
@@ -682,11 +725,8 @@ Here are the methods of the :class:`Message` class:
The *epilogue* attribute acts the same way as the *preamble* attribute,
except that it contains text that appears between the last boundary and
- the end of the message.
-
- You do not need to set the epilogue to the empty string in order for the
- :class:`~email.generator.Generator` to print a newline at the end of the
- file.
+ the end of the message. As with the :attr:`~EmailMessage.preamble`,
+ if there is no epilog text this attribute will be ``None``.
.. attribute:: defects
@@ -694,3 +734,18 @@ Here are the methods of the :class:`Message` class:
The *defects* attribute contains a list of all the problems found when
parsing this message. See :mod:`email.errors` for a detailed description
of the possible parsing defects.
+
+
+.. class:: MIMEPart(policy=default)
+
+ This class represents a subpart of a MIME message. It is identical to
+ :class:`EmailMessage`, except that no :mailheader:`MIME-Version` headers are
+ added when :meth:`~EmailMessage.set_content` is called, since sub-parts do
+ not need their own :mailheader:`MIME-Version` headers.
+
+
+.. rubric:: Footnotes
+
+.. [1] Oringally added in 3.4 as a :term:`provisional module <provisional
+ package>`. Docs for legacy message class moved to
+ :ref:`compat32_message`.
diff --git a/Doc/library/email.mime.rst b/Doc/library/email.mime.rst
index 8297dea..d9dae9f 100644
--- a/Doc/library/email.mime.rst
+++ b/Doc/library/email.mime.rst
@@ -8,6 +8,11 @@
--------------
+This module is part of the legacy (``Compat32``) email API. Its functionality
+is partially replaced by the :mod:`~email.contentmanager` in the new API, but
+in certain applications these classes may still be useful, even in non-legacy
+code.
+
Ordinarily, you get a message object structure by passing a file or some text to
a parser, which parses the text and returns the root message object. However
you can also build a complete message structure from scratch, or even individual
@@ -25,7 +30,7 @@ Here are the classes:
.. currentmodule:: email.mime.base
-.. class:: MIMEBase(_maintype, _subtype, **_params)
+.. class:: MIMEBase(_maintype, _subtype, *, policy=compat32, **_params)
Module: :mod:`email.mime.base`
@@ -41,10 +46,17 @@ Here are the classes:
key/value dictionary and is passed directly to :meth:`Message.add_header
<email.message.Message.add_header>`.
+ If *policy* is specified, (defaults to the
+ :class:`compat32 <email.policy.Compat32>` policy) it will be passed to
+ :class:`~email.message.Message`.
+
The :class:`MIMEBase` class always adds a :mailheader:`Content-Type` header
(based on *_maintype*, *_subtype*, and *_params*), and a
:mailheader:`MIME-Version` header (always set to ``1.0``).
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
+
.. currentmodule:: email.mime.nonmultipart
@@ -62,7 +74,8 @@ Here are the classes:
.. currentmodule:: email.mime.multipart
-.. class:: MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None, **_params)
+.. class:: MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None, \
+ *, policy=compat32, **_params)
Module: :mod:`email.mime.multipart`
@@ -82,14 +95,20 @@ Here are the classes:
to the message by using the :meth:`Message.attach
<email.message.Message.attach>` method.
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
Additional parameters for the :mailheader:`Content-Type` header are taken from
the keyword arguments, or passed into the *_params* argument, which is a keyword
dictionary.
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
.. currentmodule:: email.mime.application
-.. class:: MIMEApplication(_data, _subtype='octet-stream', _encoder=email.encoders.encode_base64, **_params)
+.. class:: MIMEApplication(_data, _subtype='octet-stream', \
+ _encoder=email.encoders.encode_base64, \
+ *, policy=compat32, **_params)
Module: :mod:`email.mime.application`
@@ -109,12 +128,18 @@ Here are the classes:
object as necessary. The default encoding is base64. See the
:mod:`email.encoders` module for a list of the built-in encoders.
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
*_params* are passed straight through to the base class constructor.
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
.. currentmodule:: email.mime.audio
-.. class:: MIMEAudio(_audiodata, _subtype=None, _encoder=email.encoders.encode_base64, **_params)
+.. class:: MIMEAudio(_audiodata, _subtype=None, \
+ _encoder=email.encoders.encode_base64, \
+ *, policy=compat32, **_params)
Module: :mod:`email.mime.audio`
@@ -137,12 +162,18 @@ Here are the classes:
object as necessary. The default encoding is base64. See the
:mod:`email.encoders` module for a list of the built-in encoders.
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
*_params* are passed straight through to the base class constructor.
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
.. currentmodule:: email.mime.image
-.. class:: MIMEImage(_imagedata, _subtype=None, _encoder=email.encoders.encode_base64, **_params)
+.. class:: MIMEImage(_imagedata, _subtype=None, \
+ _encoder=email.encoders.encode_base64, \
+ *, policy=compat32, **_params)
Module: :mod:`email.mime.image`
@@ -165,13 +196,17 @@ Here are the classes:
object as necessary. The default encoding is base64. See the
:mod:`email.encoders` module for a list of the built-in encoders.
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
*_params* are passed straight through to the :class:`~email.mime.base.MIMEBase`
constructor.
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
.. currentmodule:: email.mime.message
-.. class:: MIMEMessage(_msg, _subtype='rfc822')
+.. class:: MIMEMessage(_msg, _subtype='rfc822', *, policy=compat32)
Module: :mod:`email.mime.message`
@@ -184,10 +219,14 @@ Here are the classes:
Optional *_subtype* sets the subtype of the message; it defaults to
:mimetype:`rfc822`.
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
.. currentmodule:: email.mime.text
-.. class:: MIMEText(_text, _subtype='plain', _charset=None)
+.. class:: MIMEText(_text, _subtype='plain', _charset=None, *, policy=compat32)
Module: :mod:`email.mime.text`
@@ -211,5 +250,10 @@ Here are the classes:
will automatically encode the new payload (and add a new
:mailheader:`Content-Transfer-Encoding` header).
+ Optional *policy* argument defaults to :class:`compat32 <email.policy.Compat32>`.
+
.. versionchanged:: 3.5
*_charset* also accepts :class:`~email.charset.Charset` instances.
+
+ .. versionchanged:: 3.6
+ Added *policy* keyword-only parameter.
diff --git a/Doc/library/email.parser.rst b/Doc/library/email.parser.rst
index b8eb7c5..c323ebc 100644
--- a/Doc/library/email.parser.rst
+++ b/Doc/library/email.parser.rst
@@ -8,210 +8,223 @@
--------------
-Message object structures can be created in one of two ways: they can be created
-from whole cloth by instantiating :class:`~email.message.Message` objects and
-stringing them together via :meth:`~email.message.Message.attach` and
-:meth:`~email.message.Message.set_payload` calls, or they
-can be created by parsing a flat text representation of the email message.
+Message object structures can be created in one of two ways: they can be
+created from whole cloth by creating an :class:`~email.message.EmailMessage`
+object, adding headers using the dictionary interface, and adding payload(s)
+using :meth:`~email.message.EmailMessage.set_content` and related methods, or
+they can be created by parsing a serialized representation of the email
+message.
The :mod:`email` package provides a standard parser that understands most email
-document structures, including MIME documents. You can pass the parser a string
-or a file object, and the parser will return to you the root
-:class:`~email.message.Message` instance of the object structure. For simple,
-non-MIME messages the payload of this root object will likely be a string
-containing the text of the message. For MIME messages, the root object will
-return ``True`` from its :meth:`~email.message.Message.is_multipart` method, and
-the subparts can be accessed via the :meth:`~email.message.Message.get_payload`
-and :meth:`~email.message.Message.walk` methods.
-
-There are actually two parser interfaces available for use, the classic
-:class:`Parser` API and the incremental :class:`FeedParser` API. The classic
-:class:`Parser` API is fine if you have the entire text of the message in memory
-as a string, or if the entire message lives in a file on the file system.
-:class:`FeedParser` is more appropriate for when you're reading the message from
-a stream which might block waiting for more input (e.g. reading an email message
-from a socket). The :class:`FeedParser` can consume and parse the message
-incrementally, and only returns the root object when you close the parser [#]_.
+document structures, including MIME documents. You can pass the parser a
+bytes, string or file object, and the parser will return to you the root
+:class:`~email.message.EmailMessage` instance of the object structure. For
+simple, non-MIME messages the payload of this root object will likely be a
+string containing the text of the message. For MIME messages, the root object
+will return ``True`` from its :meth:`~email.message.EmailMessage.is_multipart`
+method, and the subparts can be accessed via the payload manipulation methods,
+such as :meth:`~email.message.EmailMessage.get_body`,
+:meth:`~email.message.EmailMessage.iter_parts`, and
+:meth:`~email.message.EmailMessage.walk`.
+
+There are actually two parser interfaces available for use, the :class:`Parser`
+API and the incremental :class:`FeedParser` API. The :class:`Parser` API is
+most useful if you have the entire text of the message in memory, or if the
+entire message lives in a file on the file system. :class:`FeedParser` is more
+appropriate when you are reading the message from a stream which might block
+waiting for more input (such as reading an email message from a socket). The
+:class:`FeedParser` can consume and parse the message incrementally, and only
+returns the root object when you close the parser.
Note that the parser can be extended in limited ways, and of course you can
-implement your own parser completely from scratch. There is no magical
-connection between the :mod:`email` package's bundled parser and the
-:class:`~email.message.Message` class, so your custom parser can create message
-object trees any way it finds necessary.
+implement your own parser completely from scratch. All of the logic that
+connects the :mod:`email` package's bundled parser and the
+:class:`~email.message.EmailMessage` class is embodied in the :mod:`policy`
+class, so a custom parser can create message object trees any way it finds
+necessary by implementing custom versions of the appropriate :mod:`policy`
+methods.
FeedParser API
^^^^^^^^^^^^^^
-The :class:`FeedParser`, imported from the :mod:`email.feedparser` module,
-provides an API that is conducive to incremental parsing of email messages, such
-as would be necessary when reading the text of an email message from a source
-that can block (e.g. a socket). The :class:`FeedParser` can of course be used
-to parse an email message fully contained in a string or a file, but the classic
-:class:`Parser` API may be more convenient for such use cases. The semantics
-and results of the two parser APIs are identical.
-
-The :class:`FeedParser`'s API is simple; you create an instance, feed it a bunch
-of text until there's no more to feed it, then close the parser to retrieve the
-root message object. The :class:`FeedParser` is extremely accurate when parsing
-standards-compliant messages, and it does a very good job of parsing
-non-compliant messages, providing information about how a message was deemed
-broken. It will populate a message object's *defects* attribute with a list of
-any problems it found in a message. See the :mod:`email.errors` module for the
+The :class:`BytesFeedParser`, imported from the :mod:`email.feedparser` module,
+provides an API that is conducive to incremental parsing of email messages,
+such as would be necessary when reading the text of an email message from a
+source that can block (such as a socket). The :class:`BytesFeedParser` can of
+course be used to parse an email message fully contained in a :term:`bytes-like
+object`, string, or file, but the :class:`BytesParser` API may be more
+convenient for such use cases. The semantics and results of the two parser
+APIs are identical.
+
+The :class:`BytesFeedParser`'s API is simple; you create an instance, feed it a
+bunch of bytes until there's no more to feed it, then close the parser to
+retrieve the root message object. The :class:`BytesFeedParser` is extremely
+accurate when parsing standards-compliant messages, and it does a very good job
+of parsing non-compliant messages, providing information about how a message
+was deemed broken. It will populate a message object's
+:attr:`~email.message.EmailMessage.defects` attribute with a list of any
+problems it found in a message. See the :mod:`email.errors` module for the
list of defects that it can find.
-Here is the API for the :class:`FeedParser`:
+Here is the API for the :class:`BytesFeedParser`:
-.. class:: FeedParser(_factory=email.message.Message, *, policy=policy.compat32)
+.. class:: BytesFeedParser(_factory=None, *, policy=policy.compat32)
- Create a :class:`FeedParser` instance. Optional *_factory* is a no-argument
- callable that will be called whenever a new message object is needed. It
- defaults to the :class:`email.message.Message` class.
+ Create a :class:`BytesFeedParser` instance. Optional *_factory* is a
+ no-argument callable; if not specified use the
+ :attr:`~email.policy.Policy.message_factory` from the *policy*. Call
+ *_factory* whenever a new message object is needed.
- If *policy* is specified (it must be an instance of a :mod:`~email.policy`
- class) use the rules it specifies to update the representation of the
- message. If *policy* is not set, use the :class:`compat32
- <email.policy.Compat32>` policy, which maintains backward compatibility with
- the Python 3.2 version of the email package. For more information see the
+ If *policy* is specified use the rules it specifies to update the
+ representation of the message. If *policy* is not set, use the
+ :class:`compat32 <email.policy.Compat32>` policy, which maintains backward
+ compatibility with the Python 3.2 version of the email package and provides
+ :class:`~email.message.Message` as the default factory. All other policies
+ provide :class:`~email.message.EmailMessage` as the default *_factory*. For
+ more information on what else *policy* controls, see the
:mod:`~email.policy` documentation.
+ Note: **The policy keyword should always be specified**; The default will
+ change to :data:`email.policy.default` in a future version of Python.
+
+ .. versionadded:: 3.2
+
.. versionchanged:: 3.3 Added the *policy* keyword.
+ .. versionchanged:: 3.6 *_factory* defaults to the policy ``message_factory``.
+
.. method:: feed(data)
- Feed the :class:`FeedParser` some more data. *data* should be a string
- containing one or more lines. The lines can be partial and the
- :class:`FeedParser` will stitch such partial lines together properly. The
- lines in the string can have any of the common three line endings,
- carriage return, newline, or carriage return and newline (they can even be
- mixed).
+ Feed the parser some more data. *data* should be a :term:`bytes-like
+ object` containing one or more lines. The lines can be partial and the
+ parser will stitch such partial lines together properly. The lines can
+ have any of the three common line endings: carriage return, newline, or
+ carriage return and newline (they can even be mixed).
+
.. method:: close()
- Closing a :class:`FeedParser` completes the parsing of all previously fed
- data, and returns the root message object. It is undefined what happens
- if you feed more data to a closed :class:`FeedParser`.
+ Complete the parsing of all previously fed data and return the root
+ message object. It is undefined what happens if :meth:`~feed` is called
+ after this method has been called.
-.. class:: BytesFeedParser(_factory=email.message.Message)
+.. class:: FeedParser(_factory=None, *, policy=policy.compat32)
- Works exactly like :class:`FeedParser` except that the input to the
- :meth:`~FeedParser.feed` method must be bytes and not string.
+ Works like :class:`BytesFeedParser` except that the input to the
+ :meth:`~BytesFeedParser.feed` method must be a string. This is of limited
+ utility, since the only way for such a message to be valid is for it to
+ contain only ASCII text or, if :attr:`~email.policy.Policy.utf8` is
+ ``True``, no binary attachments.
- .. versionadded:: 3.2
+ .. versionchanged:: 3.3 Added the *policy* keyword.
-Parser class API
-^^^^^^^^^^^^^^^^
+Parser API
+^^^^^^^^^^
-The :class:`Parser` class, imported from the :mod:`email.parser` module,
+The :class:`BytesParser` class, imported from the :mod:`email.parser` module,
provides an API that can be used to parse a message when the complete contents
-of the message are available in a string or file. The :mod:`email.parser`
-module also provides header-only parsers, called :class:`HeaderParser` and
-:class:`BytesHeaderParser`, which can be used if you're only interested in the
-headers of the message. :class:`HeaderParser` and :class:`BytesHeaderParser`
+of the message are available in a :term:`bytes-like object` or file. The
+:mod:`email.parser` module also provides :class:`Parser` for parsing strings,
+and header-only parsers, :class:`BytesHeaderParser` and
+:class:`HeaderParser`, which can be used if you're only interested in the
+headers of the message. :class:`BytesHeaderParser` and :class:`HeaderParser`
can be much faster in these situations, since they do not attempt to parse the
-message body, instead setting the payload to the raw body as a string. They
-have the same API as the :class:`Parser` and :class:`BytesParser` classes.
+message body, instead setting the payload to the raw body.
-.. versionadded:: 3.3
- The BytesHeaderParser class.
+.. class:: BytesParser(_class=None, *, policy=policy.compat32)
-.. class:: Parser(_class=email.message.Message, *, policy=policy.compat32)
+ Create a :class:`BytesParser` instance. The *_class* and *policy*
+ arguments have the same meaning and sematnics as the *_factory*
+ and *policy* arguments of :class:`BytesFeedParser`.
- The constructor for the :class:`Parser` class takes an optional argument
- *_class*. This must be a callable factory (such as a function or a class), and
- it is used whenever a sub-message object needs to be created. It defaults to
- :class:`~email.message.Message` (see :mod:`email.message`). The factory will
- be called without arguments.
-
- If *policy* is specified (it must be an instance of a :mod:`~email.policy`
- class) use the rules it specifies to update the representation of the
- message. If *policy* is not set, use the :class:`compat32
- <email.policy.Compat32>` policy, which maintains backward compatibility with
- the Python 3.2 version of the email package. For more information see the
- :mod:`~email.policy` documentation.
+ Note: **The policy keyword should always be specified**; The default will
+ change to :data:`email.policy.default` in a future version of Python.
.. versionchanged:: 3.3
Removed the *strict* argument that was deprecated in 2.4. Added the
*policy* keyword.
-
- The other public :class:`Parser` methods are:
+ .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``.
.. method:: parse(fp, headersonly=False)
- Read all the data from the file-like object *fp*, parse the resulting
- text, and return the root message object. *fp* must support both the
- :meth:`~io.TextIOBase.readline` and the :meth:`~io.TextIOBase.read`
- methods on file-like objects.
+ Read all the data from the binary file-like object *fp*, parse the
+ resulting bytes, and return the message object. *fp* must support
+ both the :meth:`~io.IOBase.readline` and the :meth:`~io.IOBase.read`
+ methods.
- The text contained in *fp* must be formatted as a block of :rfc:`2822`
+ The bytes contained in *fp* must be formatted as a block of :rfc:`5322`
+ (or, if :attr:`~email.policy.Policy.utf8` is ``True``, :rfc:`6532`)
style headers and header continuation lines, optionally preceded by an
envelope header. The header block is terminated either by the end of the
data or by a blank line. Following the header block is the body of the
- message (which may contain MIME-encoded subparts).
+ message (which may contain MIME-encoded subparts, including subparts
+ with a :mailheader:`Content-Transfer-Encoding` of ``8bit``.
Optional *headersonly* is a flag specifying whether to stop parsing after
reading the headers or not. The default is ``False``, meaning it parses
the entire contents of the file.
- .. method:: parsestr(text, headersonly=False)
- Similar to the :meth:`parse` method, except it takes a string object
- instead of a file-like object. Calling this method on a string is exactly
- equivalent to wrapping *text* in a :class:`~io.StringIO` instance first and
- calling :meth:`parse`.
+ .. method:: parsebytes(bytes, headersonly=False)
+
+ Similar to the :meth:`parse` method, except it takes a :term:`bytes-like
+ object` instead of a file-like object. Calling this method on a
+ :term:`bytes-like object` is equivalent to wrapping *bytes* in a
+ :class:`~io.BytesIO` instance first and calling :meth:`parse`.
Optional *headersonly* is as with the :meth:`parse` method.
+ .. versionadded:: 3.2
-.. class:: BytesParser(_class=email.message.Message, *, policy=policy.compat32)
- This class is exactly parallel to :class:`Parser`, but handles bytes input.
- The *_class* and *strict* arguments are interpreted in the same way as for
- the :class:`Parser` constructor.
+.. class:: BytesHeaderParser(_class=None, *, policy=policy.compat32)
- If *policy* is specified (it must be an instance of a :mod:`~email.policy`
- class) use the rules it specifies to update the representation of the
- message. If *policy* is not set, use the :class:`compat32
- <email.policy.Compat32>` policy, which maintains backward compatibility with
- the Python 3.2 version of the email package. For more information see the
- :mod:`~email.policy` documentation.
+ Exactly like :class:`BytesParser`, except that *headersonly*
+ defaults to ``True``.
+
+ .. versionadded:: 3.3
+
+
+.. class:: Parser(_class=None, *, policy=policy.compat32)
+
+ This class is parallel to :class:`BytesParser`, but handles string input.
.. versionchanged:: 3.3
Removed the *strict* argument. Added the *policy* keyword.
+ .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``.
+
.. method:: parse(fp, headersonly=False)
- Read all the data from the binary file-like object *fp*, parse the
- resulting bytes, and return the message object. *fp* must support
- both the :meth:`~io.IOBase.readline` and the :meth:`~io.IOBase.read`
- methods on file-like objects.
+ Read all the data from the text-mode file-like object *fp*, parse the
+ resulting text, and return the root message object. *fp* must support
+ both the :meth:`~io.TextIOBase.readline` and the
+ :meth:`~io.TextIOBase.read` methods on file-like objects.
- The bytes contained in *fp* must be formatted as a block of :rfc:`2822`
- style headers and header continuation lines, optionally preceded by an
- envelope header. The header block is terminated either by the end of the
- data or by a blank line. Following the header block is the body of the
- message (which may contain MIME-encoded subparts, including subparts
- with a :mailheader:`Content-Transfer-Encoding` of ``8bit``.
+ Other than the text mode requirement, this method operates like
+ :meth:`BytesParser.parse`.
- Optional *headersonly* is a flag specifying whether to stop parsing after
- reading the headers or not. The default is ``False``, meaning it parses
- the entire contents of the file.
- .. method:: parsebytes(text, headersonly=False)
+ .. method:: parsestr(text, headersonly=False)
- Similar to the :meth:`parse` method, except it takes a :term:`bytes-like
- object` instead of a file-like object. Calling this method is equivalent
- to wrapping *text* in a :class:`~io.BytesIO` instance first and calling
- :meth:`parse`.
+ Similar to the :meth:`parse` method, except it takes a string object
+ instead of a file-like object. Calling this method on a string is
+ equivalent to wrapping *text* in a :class:`~io.StringIO` instance first
+ and calling :meth:`parse`.
Optional *headersonly* is as with the :meth:`parse` method.
- .. versionadded:: 3.2
+
+.. class:: HeaderParser(_class=None, *, policy=policy.compat32)
+
+ Exactly like :class:`Parser`, except that *headersonly*
+ defaults to ``True``.
Since creating a message object structure from a string or a file object is such
@@ -220,55 +233,58 @@ in the top-level :mod:`email` package namespace.
.. currentmodule:: email
-.. function:: message_from_string(s, _class=email.message.Message, *, \
- policy=policy.compat32)
- Return a message object structure from a string. This is exactly equivalent to
- ``Parser().parsestr(s)``. *_class* and *policy* are interpreted as
- with the :class:`~email.parser.Parser` class constructor.
+.. function:: message_from_bytes(s, _class=None, *, policy=policy.compat32)
+
+ Return a message object structure from a :term:`bytes-like object`. This is
+ equivalent to ``BytesParser().parsebytes(s)``. Optional *_class* and
+ *strict* are interpreted as with the :class:`~email.parser.BytesParser` class
+ constructor.
+ .. versionadded:: 3.2
.. versionchanged:: 3.3
Removed the *strict* argument. Added the *policy* keyword.
-.. function:: message_from_bytes(s, _class=email.message.Message, *, \
- policy=policy.compat32)
- Return a message object structure from a :term:`bytes-like object`. This is exactly
- equivalent to ``BytesParser().parsebytes(s)``. Optional *_class* and
- *strict* are interpreted as with the :class:`~email.parser.Parser` class
+.. function:: message_from_binary_file(fp, _class=None, *,
+ policy=policy.compat32)
+
+ Return a message object structure tree from an open binary :term:`file
+ object`. This is equivalent to ``BytesParser().parse(fp)``. *_class* and
+ *policy* are interpreted as with the :class:`~email.parser.BytesParser` class
constructor.
.. versionadded:: 3.2
.. versionchanged:: 3.3
Removed the *strict* argument. Added the *policy* keyword.
-.. function:: message_from_file(fp, _class=email.message.Message, *, \
- policy=policy.compat32)
- Return a message object structure tree from an open :term:`file object`.
- This is exactly equivalent to ``Parser().parse(fp)``. *_class*
- and *policy* are interpreted as with the :class:`~email.parser.Parser` class
- constructor.
+.. function:: message_from_string(s, _class=None, *, policy=policy.compat32)
+
+ Return a message object structure from a string. This is equivalent to
+ ``Parser().parsestr(s)``. *_class* and *policy* are interpreted as
+ with the :class:`~email.parser.Parser` class constructor.
.. versionchanged:: 3.3
Removed the *strict* argument. Added the *policy* keyword.
-.. function:: message_from_binary_file(fp, _class=email.message.Message, *, \
- policy=policy.compat32)
- Return a message object structure tree from an open binary :term:`file
- object`. This is exactly equivalent to ``BytesParser().parse(fp)``.
- *_class* and *policy* are interpreted as with the
- :class:`~email.parser.Parser` class constructor.
+.. function:: message_from_file(fp, _class=None, *, policy=policy.compat32)
+
+ Return a message object structure tree from an open :term:`file object`.
+ This is equivalent to ``Parser().parse(fp)``. *_class* and *policy* are
+ interpreted as with the :class:`~email.parser.Parser` class constructor.
- .. versionadded:: 3.2
.. versionchanged:: 3.3
Removed the *strict* argument. Added the *policy* keyword.
+ .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``.
-Here's an example of how you might use this at an interactive Python prompt::
+
+Here's an example of how you might use :func:`message_from_bytes` at an
+interactive Python prompt::
>>> import email
- >>> msg = email.message_from_string(myString) # doctest: +SKIP
+ >>> msg = email.message_from_bytes(myBytes) # doctest: +SKIP
Additional notes
@@ -278,35 +294,27 @@ Here are some notes on the parsing semantics:
* Most non-\ :mimetype:`multipart` type messages are parsed as a single message
object with a string payload. These objects will return ``False`` for
- :meth:`~email.message.Message.is_multipart`. Their
- :meth:`~email.message.Message.get_payload` method will return a string object.
+ :meth:`~email.message.EmailMessage.is_multipart`, and
+ :meth:`~email.message.EmailMessage.iter_parts` will yield an empty list.
* All :mimetype:`multipart` type messages will be parsed as a container message
object with a list of sub-message objects for their payload. The outer
container message will return ``True`` for
- :meth:`~email.message.Message.is_multipart` and their
- :meth:`~email.message.Message.get_payload` method will return the list of
- :class:`~email.message.Message` subparts.
+ :meth:`~email.message.EmailMessage.is_multipart`, and
+ :meth:`~email.message.EmailMessage.iter_parts` will yield a list of subparts.
-* Most messages with a content type of :mimetype:`message/\*` (e.g.
- :mimetype:`message/delivery-status` and :mimetype:`message/rfc822`) will also be
- parsed as container object containing a list payload of length 1. Their
- :meth:`~email.message.Message.is_multipart` method will return ``True``.
- The single element in the list payload will be a sub-message object.
+* Most messages with a content type of :mimetype:`message/\*` (such as
+ :mimetype:`message/delivery-status` and :mimetype:`message/rfc822`) will also
+ be parsed as container object containing a list payload of length 1. Their
+ :meth:`~email.message.EmailMessage.is_multipart` method will return ``True``.
+ The single element yielded by :meth:`~email.message.EmailMessage.iter_parts`
+ will be a sub-message object.
-* Some non-standards compliant messages may not be internally consistent about
+* Some non-standards-compliant messages may not be internally consistent about
their :mimetype:`multipart`\ -edness. Such messages may have a
:mailheader:`Content-Type` header of type :mimetype:`multipart`, but their
- :meth:`~email.message.Message.is_multipart` method may return ``False``.
+ :meth:`~email.message.EmailMessage.is_multipart` method may return ``False``.
If such messages were parsed with the :class:`~email.parser.FeedParser`,
they will have an instance of the
:class:`~email.errors.MultipartInvariantViolationDefect` class in their
*defects* attribute list. See :mod:`email.errors` for details.
-
-.. rubric:: Footnotes
-
-.. [#] As of email package version 3.0, introduced in Python 2.4, the classic
- :class:`~email.parser.Parser` was re-implemented in terms of the
- :class:`~email.parser.FeedParser`, so the semantics and results are
- identical between the two parsers.
-
diff --git a/Doc/library/email.policy.rst b/Doc/library/email.policy.rst
index 2a6047d..8a41877 100644
--- a/Doc/library/email.policy.rst
+++ b/Doc/library/email.policy.rst
@@ -18,9 +18,12 @@ described by the various email and MIME RFCs. However, the general format of
email messages (a block of header fields each consisting of a name followed by
a colon followed by a value, the whole block followed by a blank line and an
arbitrary 'body'), is a format that has found utility outside of the realm of
-email. Some of these uses conform fairly closely to the main RFCs, some do
-not. And even when working with email, there are times when it is desirable to
-break strict compliance with the RFCs.
+email. Some of these uses conform fairly closely to the main email RFCs, some
+do not. Even when working with email, there are times when it is desirable to
+break strict compliance with the RFCs, such as generating emails that
+interoperate with email servers that do not themselves follow the standards, or
+that implement extensions you want to use in ways that violate the
+standards.
Policy objects give the email package the flexibility to handle all these
disparate use cases.
@@ -31,27 +34,40 @@ control the behavior of various components of the email package during use.
email package to alter the default behavior. The settable values and their
defaults are described below.
-There is a default policy used by all classes in the email package. This
-policy is named :class:`Compat32`, with a corresponding pre-defined instance
-named :const:`compat32`. It provides for complete backward compatibility (in
-some cases, including bug compatibility) with the pre-Python3.3 version of the
-email package.
+There is a default policy used by all classes in the email package. For all of
+the :mod:`~email.parser` classes and the related convenience functions, and for
+the :class:`~email.message.Message` class, this is the :class:`Compat32`
+policy, via its corresponding pre-defined instance :const:`compat32`. This
+policy provides for complete backward compatibility (in some cases, including
+bug compatibility) with the pre-Python3.3 version of the email package.
+
+This default value for the *policy* keyword to
+:class:`~email.message.EmailMessage` is the :class:`EmailPolicy` policy, via
+its pre-defined instance :data:`~default`.
+
+When a :class:`~email.message.Message` or :class:`~email.message.EmailMessage`
+object is created, it acquires a policy. If the message is created by a
+:mod:`~email.parser`, a policy passed to the parser will be the policy used by
+the message it creates. If the message is created by the program, then the
+policy can be specified when it is created. When a message is passed to a
+:mod:`~email.generator`, the generator uses the policy from the message by
+default, but you can also pass a specific policy to the generator that will
+override the one stored on the message object.
+
+The default value for the *policy* keyword for the :mod:`email.parser` classes
+and the parser convenience functions **will be changing** in a future version of
+Python. Therefore you should **always specify explicitly which policy you want
+to use** when calling any of the classes and functions described in the
+:mod:`~email.parser` module.
The first part of this documentation covers the features of :class:`Policy`, an
-:term:`abstract base class` that defines the features that are common to all
+:term:`abstract base class` that defines the features that are common to all
policy objects, including :const:`compat32`. This includes certain hook
methods that are called internally by the email package, which a custom policy
-could override to obtain different behavior.
-
-When a :class:`~email.message.Message` object is created, it acquires a policy.
-By default this will be :const:`compat32`, but a different policy can be
-specified. If the ``Message`` is created by a :mod:`~email.parser`, a policy
-passed to the parser will be the policy used by the ``Message`` it creates. If
-the ``Message`` is created by the program, then the policy can be specified
-when it is created. When a ``Message`` is passed to a :mod:`~email.generator`,
-the generator uses the policy from the ``Message`` by default, but you can also
-pass a specific policy to the generator that will override the one stored on
-the ``Message`` object.
+could override to obtain different behavior. The second part describes the
+concrete classes :class:`EmailPolicy` and :class:`Compat32`, which implement
+the hooks that provide the standard behavior and the backward compatible
+behavior and features, respectively.
:class:`Policy` instances are immutable, but they can be cloned, accepting the
same keyword arguments as the class constructor and returning a new
@@ -147,6 +163,7 @@ added matters. To illustrate::
This class defines the following properties, and thus values for the
following may be passed in the constructor of any policy class:
+
.. attribute:: max_line_length
The maximum length of any line in the serialized output, not counting the
@@ -154,12 +171,14 @@ added matters. To illustrate::
``0`` or :const:`None` indicates that no line wrapping should be
done at all.
+
.. attribute:: linesep
The string to be used to terminate lines in serialized output. The
default is ``\n`` because that's the internal end-of-line discipline used
by Python, though ``\r\n`` is required by the RFCs.
+
.. attribute:: cte_type
Controls the type of Content Transfer Encodings that may be or are
@@ -174,8 +193,8 @@ added matters. To illustrate::
``8bit`` data is not constrained to be 7 bit clean. Data in headers is
still required to be ASCII-only and so will be encoded (see
- 'binary_fold' below for an exception), but body parts may use
- the ``8bit`` CTE.
+ :meth:`fold_binary` and :attr:`~EmailPolicy.utf8` below for
+ exceptions), but body parts may use the ``8bit`` CTE.
======== ===============================================================
A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not
@@ -183,6 +202,7 @@ added matters. To illustrate::
``Generator`` is operating under a policy that specifies
``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``.
+
.. attribute:: raise_on_defect
If :const:`True`, any defects encountered will be raised as errors. If
@@ -190,7 +210,6 @@ added matters. To illustrate::
:meth:`register_defect` method.
-
.. attribute:: mangle_from\_
If :const:`True`, lines starting with *"From "* in the body are
@@ -201,19 +220,31 @@ added matters. To illustrate::
.. versionadded:: 3.5
The *mangle_from_* parameter.
+
+ .. attribute:: message_factory
+
+ A factory function for constructing a new empty message object. Used
+ by the parser when building messages. Defaults to ``None``, in
+ which case :class:`~email.message.Message` is used.
+
+ .. versionadded:: 3.6
+
The following :class:`Policy` method is intended to be called by code using
the email library to create policy instances with custom settings:
+
.. method:: clone(**kw)
Return a new :class:`Policy` instance whose attributes have the same
values as the current instance, except where those attributes are
given new values by the keyword arguments.
+
The remaining :class:`Policy` methods are called by the email package code,
and are not intended to be called by an application using the email package.
A custom policy must implement all of these methods.
+
.. method:: handle_defect(obj, defect)
Handle a *defect* found on *obj*. When the email package calls this
@@ -224,6 +255,7 @@ added matters. To illustrate::
it is ``True``, *defect* is raised as an exception. If it is ``False``
(the default), *obj* and *defect* are passed to :meth:`register_defect`.
+
.. method:: register_defect(obj, defect)
Register a *defect* on *obj*. In the email package, *defect* will always
@@ -236,14 +268,16 @@ added matters. To illustrate::
custom ``Message`` objects) should also provide such an attribute,
otherwise defects in parsed messages will raise unexpected errors.
+
.. method:: header_max_count(name)
Return the maximum allowed number of headers named *name*.
- Called when a header is added to a :class:`~email.message.Message`
- object. If the returned value is not ``0`` or ``None``, and there are
- already a number of headers with the name *name* equal to the value
- returned, a :exc:`ValueError` is raised.
+ Called when a header is added to an :class:`~email.message.EmailMessage`
+ or :class:`~email.message.Message` object. If the returned value is not
+ ``0`` or ``None``, and there are already a number of headers with the
+ name *name* greather than or equal to the value returned, a
+ :exc:`ValueError` is raised.
Because the default behavior of ``Message.__setitem__`` is to append the
value to the list of headers, it is easy to create duplicate headers
@@ -255,6 +289,7 @@ added matters. To illustrate::
The default implementation returns ``None`` for all header names.
+
.. method:: header_source_parse(sourcelines)
The email package calls this method with a list of strings, each string
@@ -274,6 +309,7 @@ added matters. To illustrate::
There is no default implementation
+
.. method:: header_store_parse(name, value)
The email package calls this method with the name and value provided by
@@ -289,6 +325,7 @@ added matters. To illustrate::
There is no default implementation
+
.. method:: header_fetch_parse(name, value)
The email package calls this method with the *name* and *value* currently
@@ -304,6 +341,7 @@ added matters. To illustrate::
There is no default implementation
+
.. method:: fold(name, value)
The email package calls this method with the *name* and *value* currently
@@ -316,6 +354,7 @@ added matters. To illustrate::
*value* may contain surrogateescaped binary data. There should be no
surrogateescaped binary data in the string returned by the method.
+
.. method:: fold_binary(name, value)
The same as :meth:`fold`, except that the returned value should be a
@@ -325,73 +364,6 @@ added matters. To illustrate::
converted back into binary data in the returned bytes object.
-.. class:: Compat32(**kw)
-
- This concrete :class:`Policy` is the backward compatibility policy. It
- replicates the behavior of the email package in Python 3.2. The
- :mod:`~email.policy` module also defines an instance of this class,
- :const:`compat32`, that is used as the default policy. Thus the default
- behavior of the email package is to maintain compatibility with Python 3.2.
-
- The following attributes have values that are different from the
- :class:`Policy` default:
-
- .. attribute:: mangle_from_
-
- The default is ``True``.
-
- The class provides the following concrete implementations of the
- abstract methods of :class:`Policy`:
-
- .. method:: header_source_parse(sourcelines)
-
- The name is parsed as everything up to the '``:``' and returned
- unmodified. The value is determined by stripping leading whitespace off
- the remainder of the first line, joining all subsequent lines together,
- and stripping any trailing carriage return or linefeed characters.
-
- .. method:: header_store_parse(name, value)
-
- The name and value are returned unmodified.
-
- .. method:: header_fetch_parse(name, value)
-
- If the value contains binary data, it is converted into a
- :class:`~email.header.Header` object using the ``unknown-8bit`` charset.
- Otherwise it is returned unmodified.
-
- .. method:: fold(name, value)
-
- Headers are folded using the :class:`~email.header.Header` folding
- algorithm, which preserves existing line breaks in the value, and wraps
- each resulting line to the ``max_line_length``. Non-ASCII binary data are
- CTE encoded using the ``unknown-8bit`` charset.
-
- .. method:: fold_binary(name, value)
-
- Headers are folded using the :class:`~email.header.Header` folding
- algorithm, which preserves existing line breaks in the value, and wraps
- each resulting line to the ``max_line_length``. If ``cte_type`` is
- ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit``
- charset. Otherwise the original source header is used, with its existing
- line breaks and any (RFC invalid) binary data it may contain.
-
-
-An instance of :class:`Compat32` is provided as a module constant:
-
-.. data:: compat32
-
- An instance of :class:`Compat32`, providing backward compatibility with the
- behavior of the email package in Python 3.2.
-
-
-.. note::
-
- The documentation below describes new policies that are included in the
- standard library on a :term:`provisional basis <provisional package>`.
- Backwards incompatible changes (up to and including removal of the feature)
- may occur if deemed necessary by the core developers.
-
.. class:: EmailPolicy(**kw)
@@ -404,9 +376,15 @@ An instance of :class:`Compat32` is provided as a module constant:
on the type of the field. The parsing and folding algorithm fully implement
:rfc:`2047` and :rfc:`5322`.
+ The default value for the :attr:`~email.policy.Policy.message_factory`
+ attribute is :class:`~email.message.EmailMessage`.
+
In addition to the settable attributes listed above that apply to all
policies, this policy adds the following additional attributes:
+ .. versionadded:: 3.6 [1]_
+
+
.. attribute:: utf8
If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in
@@ -415,13 +393,14 @@ An instance of :class:`Compat32` is provided as a module constant:
formatted in this way may be passed to SMTP servers that support
the ``SMTPUTF8`` extension (:rfc:`6531`).
+
.. attribute:: refold_source
If the value for a header in the ``Message`` object originated from a
:mod:`~email.parser` (as opposed to being set by a program), this
attribute indicates whether or not a generator should refold that value
- when transforming the message back into stream form. The possible values
- are:
+ when transforming the message back into serialized form. The possible
+ values are:
======== ===============================================================
``none`` all source values use original folding
@@ -434,23 +413,24 @@ An instance of :class:`Compat32` is provided as a module constant:
The default is ``long``.
+
.. attribute:: header_factory
A callable that takes two arguments, ``name`` and ``value``, where
``name`` is a header field name and ``value`` is an unfolded header field
value, and returns a string subclass that represents that header. A
default ``header_factory`` (see :mod:`~email.headerregistry`) is provided
- that understands some of the :RFC:`5322` header field types. (Currently
- address fields and date fields have special treatment, while all other
- fields are treated as unstructured. This list will be completed before
- the extension is marked stable.)
+ that supports custom parsing for the various address and date :RFC:`5322`
+ header field types, and the major MIME header field stypes. Support for
+ additional custom parsing will be added in the future.
+
.. attribute:: content_manager
An object with at least two methods: get_content and set_content. When
- the :meth:`~email.message.Message.get_content` or
- :meth:`~email.message.Message.set_content` method of a
- :class:`~email.message.Message` object is called, it calls the
+ the :meth:`~email.message.EmailMessage.get_content` or
+ :meth:`~email.message.EmailMessage.set_content` method of an
+ :class:`~email.message.EmailMessage` object is called, it calls the
corresponding method of this object, passing it the message object as its
first argument, and any arguments or keywords that were passed to it as
additional arguments. By default ``content_manager`` is set to
@@ -462,16 +442,22 @@ An instance of :class:`Compat32` is provided as a module constant:
The class provides the following concrete implementations of the abstract
methods of :class:`Policy`:
+
.. method:: header_max_count(name)
Returns the value of the
:attr:`~email.headerregistry.BaseHeader.max_count` attribute of the
specialized class used to represent the header with the given name.
+
.. method:: header_source_parse(sourcelines)
- The implementation of this method is the same as that for the
- :class:`Compat32` policy.
+
+ The name is parsed as everything up to the '``:``' and returned
+ unmodified. The value is determined by stripping leading whitespace off
+ the remainder of the first line, joining all subsequent lines together,
+ and stripping any trailing carriage return or linefeed characters.
+
.. method:: header_store_parse(name, value)
@@ -482,6 +468,7 @@ An instance of :class:`Compat32` is provided as a module constant:
the value. In this case a ``ValueError`` is raised if the input value
contains CR or LF characters.
+
.. method:: header_fetch_parse(name, value)
If the value has a ``name`` attribute, it is returned to unmodified.
@@ -490,6 +477,7 @@ An instance of :class:`Compat32` is provided as a module constant:
header object is returned. Any surrogateescaped bytes get turned into
the unicode unknown-character glyph.
+
.. method:: fold(name, value)
Header folding is controlled by the :attr:`refold_source` policy setting.
@@ -508,6 +496,7 @@ An instance of :class:`Compat32` is provided as a module constant:
regardless of the ``refold_source`` setting, which causes the binary data
to be CTE encoded using the ``unknown-8bit`` charset.
+
.. method:: fold_binary(name, value)
The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except
@@ -519,23 +508,27 @@ An instance of :class:`Compat32` is provided as a module constant:
``refold_header`` setting, since there is no way to know whether the
binary data consists of single byte characters or multibyte characters.
+
The following instances of :class:`EmailPolicy` provide defaults suitable for
specific application domains. Note that in the future the behavior of these
instances (in particular the ``HTTP`` instance) may be adjusted to conform even
more closely to the RFCs relevant to their domains.
+
.. data:: default
An instance of ``EmailPolicy`` with all defaults unchanged. This policy
uses the standard Python ``\n`` line endings rather than the RFC-correct
``\r\n``.
+
.. data:: SMTP
Suitable for serializing messages in conformance with the email RFCs.
Like ``default``, but with ``linesep`` set to ``\r\n``, which is RFC
compliant.
+
.. data:: SMTPUTF8
The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``.
@@ -544,11 +537,13 @@ more closely to the RFCs relevant to their domains.
sender or recipient addresses have non-ASCII characters (the
:meth:`smtplib.SMTP.send_message` method handles this automatically).
+
.. data:: HTTP
Suitable for serializing headers with for use in HTTP traffic. Like
``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited).
+
.. data:: strict
Convenience instance. The same as ``default`` except that
@@ -557,6 +552,7 @@ more closely to the RFCs relevant to their domains.
somepolicy + policy.strict
+
With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API of
the email package is changed from the Python 3.2 API in the following ways:
@@ -573,7 +569,7 @@ the email package is changed from the Python 3.2 API in the following ways:
and allowed.
From the application view, this means that any header obtained through the
-:class:`~email.message.Message` is a header object with extra
+:class:`~email.message.EmailMessage` is a header object with extra
attributes, whose string value is the fully decoded unicode value of the
header. Likewise, a header may be assigned a new value, or a new header
created, using a unicode string, and the policy will take care of converting
@@ -581,3 +577,75 @@ the unicode string into the correct RFC encoded form.
The header objects and their attributes are described in
:mod:`~email.headerregistry`.
+
+
+
+.. class:: Compat32(**kw)
+
+ This concrete :class:`Policy` is the backward compatibility policy. It
+ replicates the behavior of the email package in Python 3.2. The
+ :mod:`~email.policy` module also defines an instance of this class,
+ :const:`compat32`, that is used as the default policy. Thus the default
+ behavior of the email package is to maintain compatibility with Python 3.2.
+
+ The following attributes have values that are different from the
+ :class:`Policy` default:
+
+
+ .. attribute:: mangle_from_
+
+ The default is ``True``.
+
+
+ The class provides the following concrete implementations of the
+ abstract methods of :class:`Policy`:
+
+
+ .. method:: header_source_parse(sourcelines)
+
+ The name is parsed as everything up to the '``:``' and returned
+ unmodified. The value is determined by stripping leading whitespace off
+ the remainder of the first line, joining all subsequent lines together,
+ and stripping any trailing carriage return or linefeed characters.
+
+
+ .. method:: header_store_parse(name, value)
+
+ The name and value are returned unmodified.
+
+
+ .. method:: header_fetch_parse(name, value)
+
+ If the value contains binary data, it is converted into a
+ :class:`~email.header.Header` object using the ``unknown-8bit`` charset.
+ Otherwise it is returned unmodified.
+
+
+ .. method:: fold(name, value)
+
+ Headers are folded using the :class:`~email.header.Header` folding
+ algorithm, which preserves existing line breaks in the value, and wraps
+ each resulting line to the ``max_line_length``. Non-ASCII binary data are
+ CTE encoded using the ``unknown-8bit`` charset.
+
+
+ .. method:: fold_binary(name, value)
+
+ Headers are folded using the :class:`~email.header.Header` folding
+ algorithm, which preserves existing line breaks in the value, and wraps
+ each resulting line to the ``max_line_length``. If ``cte_type`` is
+ ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit``
+ charset. Otherwise the original source header is used, with its existing
+ line breaks and any (RFC invalid) binary data it may contain.
+
+
+.. data:: compat32
+
+ An instance of :class:`Compat32`, providing backward compatibility with the
+ behavior of the email package in Python 3.2.
+
+
+.. rubric:: Footnotes
+
+.. [1] Oringally added in 3.3 as a :term:`provisional feature <provisional
+ package>`.
diff --git a/Doc/library/email.rst b/Doc/library/email.rst
index e8bb02b..c4187dd 100644
--- a/Doc/library/email.rst
+++ b/Doc/library/email.rst
@@ -3,50 +3,104 @@
.. module:: email
:synopsis: Package supporting the parsing, manipulating, and generating
- email messages, including MIME documents.
-
-.. moduleauthor:: Barry A. Warsaw <barry@python.org>
-.. sectionauthor:: Barry A. Warsaw <barry@python.org>
-.. Copyright (C) 2001-2010 Python Software Foundation
+ email messages.
+.. moduleauthor:: Barry A. Warsaw <barry@python.org>,
+ R. David Murray <rdmurray@bitdance.com>
+.. sectionauthor:: R. David Murray <rdmurray@bitdance.com>
**Source code:** :source:`Lib/email/__init__.py`
--------------
-The :mod:`email` package is a library for managing email messages, including
-MIME and other :rfc:`2822`\ -based message documents. It is specifically *not*
-designed to do any sending of email messages to SMTP (:rfc:`2821`), NNTP, or
-other servers; those are functions of modules such as :mod:`smtplib` and
-:mod:`nntplib`. The :mod:`email` package attempts to be as RFC-compliant as
-possible, supporting in addition to :rfc:`2822`, such MIME-related RFCs as
-:rfc:`2045`, :rfc:`2046`, :rfc:`2047`, and :rfc:`2231`.
-
-The primary distinguishing feature of the :mod:`email` package is that it splits
-the parsing and generating of email messages from the internal *object model*
-representation of email. Applications using the :mod:`email` package deal
-primarily with objects; you can add sub-objects to messages, remove sub-objects
-from messages, completely re-arrange the contents, etc. There is a separate
-parser and a separate generator which handles the transformation from flat text
-to the object model, and then back to flat text again. There are also handy
-subclasses for some common MIME object types, and a few miscellaneous utilities
-that help with such common tasks as extracting and parsing message field values,
-creating RFC-compliant dates, etc.
+The :mod:`email` package is a library for managing email messages. It is
+specifically *not* designed to do any sending of email messages to SMTP
+(:rfc:`2821`), NNTP, or other servers; those are functions of modules such as
+:mod:`smtplib` and :mod:`nntplib`. The :mod:`email` package attempts to be as
+RFC-compliant as possible, supporting :rfc:`5233` and :rfc:`6532`, as well as
+such MIME-related RFCs as :rfc:`2045`, :rfc:`2046`, :rfc:`2047`, :rfc:`2183`,
+and :rfc:`2231`.
+
+The overall structure of the email package can be divided into three major
+components, plus a fourth component that controls the behavior of the other
+components.
+
+The central component of the package is an "object model" that represents email
+messages. An application interacts with the package primarily through the
+object model interface defined in the :mod:`~email.message` sub-module. The
+application can use this API to ask questions about an existing email, to
+construct a new email, or to add or remove email subcomponents that themselves
+use the same object model interface. That is, following the nature of email
+messages and their MIME subcomponents, the email object model is a tree
+structure of objects that all provide the :class:`~email.message.EmailMessage`
+API.
+
+The other two major components of the package are the :mod:`~email.parser` and
+the :mod:`~email.generator`. The parser takes the serialized version of an
+email message (a stream of bytes) and converts it into a tree of
+:class:`~email.message.EmailMessage` objects. The generator takes an
+:class:`~email.message.EmailMessage` and turns it back into a serialized byte
+stream. (The parser and generator also handle streams of text characters, but
+this usage is discouraged as it is too easy to end up with messages that are
+not valid in one way or another.)
+
+The control component is the :mod:`~email.policy` module. Every
+:class:`~email.message.EmailMessage`, every :mod:`~email.generator`, and every
+:mod:`~email.parser` has an associated :mod:`~email.policy` object that
+controls its behavior. Usually an application only needs to specify the policy
+when an :class:`~email.message.EmailMessage` is created, either by directly
+instantiating an :class:`~email.message.EmailMessage` to create a new email,
+or by parsing an input stream using a :mod:`~email.parser`. But the policy can
+be changed when the message is serialized using a :mod:`~email.generator`.
+This allows, for example, a generic email message to be parsed from disk, but
+to serialize it using standard SMTP settings when sending it to an email
+server.
+
+The email package does its best to hide the details of the various governing
+RFCs from the application. Conceptually the application should be able to
+treat the email message as a structured tree of unicode text and binary
+attachments, without having to worry about how these are represented when
+serialized. In practice, however, it is often necessary to be aware of at
+least some of the rules governing MIME messages and their structure,
+specifically the names and nature of the MIME "content types" and how they
+identify multipart documents. For the most part this knowledge should only be
+required for more complex applications, and even then it should only be the
+high level structure in question, and not the details of how those structures
+are represented. Since MIME content types are used widely in modern internet
+software (not just email), this will be a familiar concept to many programmers.
The following sections describe the functionality of the :mod:`email` package.
-The ordering follows a progression that should be common in applications: an
-email message is read as flat text from a file or other source, the text is
-parsed to produce the object structure of the email message, this structure is
-manipulated, and finally, the object tree is rendered back into flat text.
-
-It is perfectly feasible to create the object structure out of whole cloth ---
-i.e. completely from scratch. From there, a similar progression can be taken as
-above.
-
-Also included are detailed specifications of all the classes and modules that
-the :mod:`email` package provides, the exception classes you might encounter
-while using the :mod:`email` package, some auxiliary utilities, and a few
-examples. For users of the older :mod:`mimelib` package, or previous versions
-of the :mod:`email` package, a section on differences and porting is provided.
+We start with the :mod:`~email.message` object model, which is the primary
+interface an application will use, and follow that with the
+:mod:`~email.parser` and :mod:`~email.generator` components. Then we cover the
+:mod:`~email.policy` controls, which completes the treatment of the main
+components of the library.
+
+The next three sections cover the exceptions the package may raise and the
+defects (non-compliance with the RFCs) that the :mod:`~email.parser` may
+detect. Then we cover the :mod:`~email.headerregistry` and the
+:mod:`~email.contentmanager` sub-components, which provide tools for doing more
+detailed manipulation of headers and payloads, respectively. Both of these
+components contain features relevant to consuming and producing non-trivial
+messages, but also document their extensibility APIs, which will be of interest
+to advanced applications.
+
+Following those is a set of examples of using the fundamental parts of the APIs
+covered in the preceding sections.
+
+The forgoing represent the modern (unicode friendly) API of the email package.
+The remaining sections, starting with the :class:`~email.message.Message`
+class, cover the legacy :data:`~email.policy.compat32` API that deals much more
+directly with the details of how email messages are represented. The
+:data:`~email.policy.compat32` API does *not* hide the details of the RFCs from
+the application, but for applications that need to operate at that level, they
+can be useful tools. This documentation is also relevant for applications that
+are still using the :mod:`~email.policy.compat32` API for backward
+compatibility reasons.
+
+.. versionchanged:: 3.6
+ Docs reorganized and rewritten to promote the new
+ :class:`~email.message.EmailMessage`/:class:`~email.policy.EmailPolicy`
+ API.
Contents of the :mod:`email` package documentation:
@@ -56,335 +110,43 @@ Contents of the :mod:`email` package documentation:
email.parser.rst
email.generator.rst
email.policy.rst
+
+ email.errors.rst
email.headerregistry.rst
email.contentmanager.rst
+
+ email.examples.rst
+
+Legacy API:
+
+.. toctree::
+
+ email.compat32-message.rst
email.mime.rst
email.header.rst
email.charset.rst
email.encoders.rst
- email.errors.rst
email.util.rst
email.iterators.rst
- email-examples.rst
.. seealso::
Module :mod:`smtplib`
- SMTP protocol client
-
- Module :mod:`nntplib`
- NNTP protocol client
-
-
-.. _email-pkg-history:
-
-Package History
----------------
-
-This table describes the release history of the email package, corresponding to
-the version of Python that the package was released with. For purposes of this
-document, when you see a note about change or added versions, these refer to the
-Python version the change was made in, *not* the email package version. This
-table also describes the Python compatibility of each version of the package.
-
-+---------------+------------------------------+-----------------------+
-| email version | distributed with | compatible with |
-+===============+==============================+=======================+
-| :const:`1.x` | Python 2.2.0 to Python 2.2.1 | *no longer supported* |
-+---------------+------------------------------+-----------------------+
-| :const:`2.5` | Python 2.2.2+ and Python 2.3 | Python 2.1 to 2.5 |
-+---------------+------------------------------+-----------------------+
-| :const:`3.0` | Python 2.4 and Python 2.5 | Python 2.3 to 2.6 |
-+---------------+------------------------------+-----------------------+
-| :const:`4.0` | Python 2.5 to Python 2.7 | Python 2.3 to 2.7 |
-+---------------+------------------------------+-----------------------+
-| :const:`5.0` | Python 3.0 and Python 3.1 | Python 3.0 to 3.2 |
-+---------------+------------------------------+-----------------------+
-| :const:`5.1` | Python 3.2 | Python 3.2 |
-+---------------+------------------------------+-----------------------+
-
-After Version 5.1 (Python 3.2), the email package no longer has a version that
-is separate from the Python version. (See the :ref:`whatsnew-index` documents
-for the respective Python versions for details on changes.)
-
-Here are the major differences between :mod:`email` version 5.1 and
-version 5.0:
-
-* It is once again possible to parse messages containing non-ASCII bytes,
- and to reproduce such messages if the data containing the non-ASCII
- bytes is not modified.
-
-* New functions :func:`message_from_bytes` and :func:`message_from_binary_file`,
- and new classes :class:`~email.parser.BytesFeedParser` and
- :class:`~email.parser.BytesParser` allow binary message data to be parsed
- into model objects.
-
-* Given bytes input to the model, :meth:`~email.message.Message.get_payload`
- will by default decode a message body that has a
- :mailheader:`Content-Transfer-Encoding` of ``8bit`` using the charset
- specified in the MIME headers and return the resulting string.
-
-* Given bytes input to the model, :class:`~email.generator.Generator` will
- convert message bodies that have a :mailheader:`Content-Transfer-Encoding` of
- 8bit to instead have a 7bit Content-Transfer-Encoding.
-
-* New class :class:`~email.generator.BytesGenerator` produces bytes
- as output, preserving any unchanged non-ASCII data that was
- present in the input used to build the model, including message bodies
- with a :mailheader:`Content-Transfer-Encoding` of 8bit.
-
-Here are the major differences between :mod:`email` version 5.0 and version 4:
-
-* All operations are on unicode strings. Text inputs must be strings,
- text outputs are strings. Outputs are limited to the ASCII character
- set and so can be encoded to ASCII for transmission. Inputs are also
- limited to ASCII; this is an acknowledged limitation of email 5.0 and
- means it can only be used to parse email that is 7bit clean.
-
-Here are the major differences between :mod:`email` version 4 and version 3:
-
-* All modules have been renamed according to :pep:`8` standards. For example,
- the version 3 module :mod:`email.Message` was renamed to :mod:`email.message` in
- version 4.
-
-* A new subpackage :mod:`email.mime` was added and all the version 3
- :mod:`email.MIME\*` modules were renamed and situated into the :mod:`email.mime`
- subpackage. For example, the version 3 module :mod:`email.MIMEText` was renamed
- to :mod:`email.mime.text`.
-
- *Note that the version 3 names will continue to work until Python 2.6*.
-
-* The :mod:`email.mime.application` module was added, which contains the
- :class:`~email.mime.application.MIMEApplication` class.
-
-* Methods that were deprecated in version 3 have been removed. These include
- :meth:`Generator.__call__`, :meth:`Message.get_type`,
- :meth:`Message.get_main_type`, :meth:`Message.get_subtype`.
-
-* Fixes have been added for :rfc:`2231` support which can change some of the
- return types for :func:`Message.get_param <email.message.Message.get_param>`
- and friends. Under some
- circumstances, values which used to return a 3-tuple now return simple strings
- (specifically, if all extended parameter segments were unencoded, there is no
- language and charset designation expected, so the return type is now a simple
- string). Also, %-decoding used to be done for both encoded and unencoded
- segments; this decoding is now done only for encoded segments.
-
-Here are the major differences between :mod:`email` version 3 and version 2:
-
-* The :class:`~email.parser.FeedParser` class was introduced, and the
- :class:`~email.parser.Parser` class was implemented in terms of the
- :class:`~email.parser.FeedParser`. All parsing therefore is
- non-strict, and parsing will make a best effort never to raise an exception.
- Problems found while parsing messages are stored in the message's *defect*
- attribute.
-
-* All aspects of the API which raised :exc:`DeprecationWarning`\ s in version 2
- have been removed. These include the *_encoder* argument to the
- :class:`~email.mime.text.MIMEText` constructor, the
- :meth:`Message.add_payload` method, the :func:`Utils.dump_address_pair`
- function, and the functions :func:`Utils.decode` and :func:`Utils.encode`.
-
-* New :exc:`DeprecationWarning`\ s have been added to:
- :meth:`Generator.__call__`, :meth:`Message.get_type`,
- :meth:`Message.get_main_type`, :meth:`Message.get_subtype`, and the *strict*
- argument to the :class:`~email.parser.Parser` class. These are expected to
- be removed in future versions.
-
-* Support for Pythons earlier than 2.3 has been removed.
-
-Here are the differences between :mod:`email` version 2 and version 1:
-
-* The :mod:`email.Header` and :mod:`email.Charset` modules have been added.
-
-* The pickle format for :class:`~email.message.Message` instances has changed.
- Since this was never (and still isn't) formally defined, this isn't
- considered a backward incompatibility. However if your application pickles
- and unpickles :class:`~email.message.Message` instances, be aware that in
- :mod:`email` version 2, :class:`~email.message.Message` instances now have
- private variables *_charset* and *_default_type*.
-
-* Several methods in the :class:`~email.message.Message` class have been
- deprecated, or their signatures changed. Also, many new methods have been
- added. See the documentation for the :class:`~email.message.Message` class
- for details. The changes should be completely backward compatible.
+ SMTP (Simple Mail Transport Protcol) client
-* The object structure has changed in the face of :mimetype:`message/rfc822`
- content types. In :mod:`email` version 1, such a type would be represented
- by a scalar payload, i.e. the container message's
- :meth:`~email.message.Message.is_multipart` returned false,
- :meth:`~email.message.Message.get_payload` was not a list object, but a
- single :class:`~email.message.Message` instance.
+ Module :mod:`poplib`
+ POP (Post Office Protocol) client
- This structure was inconsistent with the rest of the package, so the object
- representation for :mimetype:`message/rfc822` content types was changed. In
- :mod:`email` version 2, the container *does* return ``True`` from
- :meth:`~email.message.Message.is_multipart`, and
- :meth:`~email.message.Message.get_payload` returns a list containing a single
- :class:`~email.message.Message` item.
+ Module :mod:`imaplib`
+ IMAP (Internet Message Access Protocol) client
- Note that this is one place that backward compatibility could not be
- completely maintained. However, if you're already testing the return type of
- :meth:`~email.message.Message.get_payload`, you should be fine. You just need
- to make sure your code doesn't do a :meth:`~email.message.Message.set_payload`
- with a :class:`~email.message.Message` instance on a container with a content
- type of :mimetype:`message/rfc822`.
-
-* The :class:`~email.parser.Parser` constructor's *strict* argument was added,
- and its :meth:`~email.parser.Parser.parse` and
- :meth:`~email.parser.Parser.parsestr` methods grew a *headersonly* argument.
- The *strict* flag was also added to functions :func:`email.message_from_file`
- and :func:`email.message_from_string`.
-
-* :meth:`Generator.__call__` is deprecated; use :meth:`Generator.flatten
- <email.generator.Generator.flatten>` instead. The
- :class:`~email.generator.Generator` class has also grown the
- :meth:`~email.generator.Generator.clone` method.
-
-* The :class:`~email.generator.DecodedGenerator` class in the
- :mod:`email.generator` module was added.
-
-* The intermediate base classes
- :class:`~email.mime.nonmultipart.MIMENonMultipart` and
- :class:`~email.mime.multipart.MIMEMultipart` have been added, and interposed
- in the class hierarchy for most of the other MIME-related derived classes.
-
-* The *_encoder* argument to the :class:`~email.mime.text.MIMEText` constructor
- has been deprecated. Encoding now happens implicitly based on the
- *_charset* argument.
-
-* The following functions in the :mod:`email.Utils` module have been deprecated:
- :func:`dump_address_pairs`, :func:`decode`, and :func:`encode`. The following
- functions have been added to the module: :func:`make_msgid`,
- :func:`decode_rfc2231`, :func:`encode_rfc2231`, and :func:`decode_params`.
-
-* The non-public function :func:`email.Iterators._structure` was added.
-
-
-Differences from :mod:`mimelib`
--------------------------------
-
-The :mod:`email` package was originally prototyped as a separate library called
-`mimelib <http://mimelib.sourceforge.net/>`_. Changes have been made so that method names
-are more consistent, and some methods or modules have either been added or
-removed. The semantics of some of the methods have also changed. For the most
-part, any functionality available in :mod:`mimelib` is still available in the
-:mod:`email` package, albeit often in a different way. Backward compatibility
-between the :mod:`mimelib` package and the :mod:`email` package was not a
-priority.
-
-Here is a brief description of the differences between the :mod:`mimelib` and
-the :mod:`email` packages, along with hints on how to port your applications.
-
-Of course, the most visible difference between the two packages is that the
-package name has been changed to :mod:`email`. In addition, the top-level
-package has the following differences:
-
-* :func:`messageFromString` has been renamed to :func:`message_from_string`.
-
-* :func:`messageFromFile` has been renamed to :func:`message_from_file`.
-
-The :class:`~email.message.Message` class has the following differences:
-
-* The method :meth:`asString` was renamed to
- :meth:`~email.message.Message.as_string`.
-
-* The method :meth:`ismultipart` was renamed to
- :meth:`~email.message.Message.is_multipart`.
-
-* The :meth:`~email.message.Message.get_payload` method has grown a *decode*
- optional argument.
-
-* The method :meth:`getall` was renamed to
- :meth:`~email.message.Message.get_all`.
-
-* The method :meth:`addheader` was renamed to
- :meth:`~email.message.Message.add_header`.
-
-* The method :meth:`gettype` was renamed to :meth:`get_type`.
-
-* The method :meth:`getmaintype` was renamed to :meth:`get_main_type`.
-
-* The method :meth:`getsubtype` was renamed to :meth:`get_subtype`.
-
-* The method :meth:`getparams` was renamed to
- :meth:`~email.message.Message.get_params`. Also, whereas :meth:`getparams`
- returned a list of strings, :meth:`~email.message.Message.get_params` returns
- a list of 2-tuples, effectively the key/value pairs of the parameters, split
- on the ``'='`` sign.
-
-* The method :meth:`getparam` was renamed to
- :meth:`~email.message.Message.get_param`.
-
-* The method :meth:`getcharsets` was renamed to
- :meth:`~email.message.Message.get_charsets`.
-
-* The method :meth:`getfilename` was renamed to
- :meth:`~email.message.Message.get_filename`.
-
-* The method :meth:`getboundary` was renamed to
- :meth:`~email.message.Message.get_boundary`.
-
-* The method :meth:`setboundary` was renamed to
- :meth:`~email.message.Message.set_boundary`.
-
-* The method :meth:`getdecodedpayload` was removed. To get similar
- functionality, pass the value 1 to the *decode* flag of the
- :meth:`~email.message.Message.get_payload` method.
-
-* The method :meth:`getpayloadastext` was removed. Similar functionality is
- supported by the :class:`~email.generator.DecodedGenerator` class in the
- :mod:`email.generator` module.
-
-* The method :meth:`getbodyastext` was removed. You can get similar
- functionality by creating an iterator with
- :func:`~email.iterators.typed_subpart_iterator` in the :mod:`email.iterators`
- module.
-
-The :class:`~email.parser.Parser` class has no differences in its public
-interface. It does have some additional smarts to recognize
-:mimetype:`message/delivery-status` type messages, which it represents as a
-:class:`~email.message.Message` instance containing separate
-:class:`~email.message.Message` subparts for each header block in the delivery
-status notification [#]_.
-
-The :class:`~email.generator.Generator` class has no differences in its public
-interface. There is a new class in the :mod:`email.generator` module though,
-called :class:`~email.generator.DecodedGenerator` which provides most of the
-functionality previously available in the :meth:`Message.getpayloadastext`
-method.
-
-The following modules and classes have been changed:
-
-* The :class:`~email.mime.base.MIMEBase` class constructor arguments *_major*
- and *_minor* have changed to *_maintype* and *_subtype* respectively.
-
-* The ``Image`` class/module has been renamed to ``MIMEImage``. The *_minor*
- argument has been renamed to *_subtype*.
-
-* The ``Text`` class/module has been renamed to ``MIMEText``. The *_minor*
- argument has been renamed to *_subtype*.
-
-* The ``MessageRFC822`` class/module has been renamed to ``MIMEMessage``. Note
- that an earlier version of :mod:`mimelib` called this class/module ``RFC822``,
- but that clashed with the Python standard library module :mod:`rfc822` on some
- case-insensitive file systems.
-
- Also, the :class:`~email.mime.message.MIMEMessage` class now represents any
- kind of MIME message
- with main type :mimetype:`message`. It takes an optional argument *_subtype*
- which is used to set the MIME subtype. *_subtype* defaults to
- :mimetype:`rfc822`.
-
-:mod:`mimelib` provided some utility functions in its :mod:`address` and
-:mod:`date` modules. All of these functions have been moved to the
-:mod:`email.utils` module.
-
-The ``MsgReader`` class/module has been removed. Its functionality is most
-closely supported in the :func:`~email.iterators.body_line_iterator` function
-in the :mod:`email.iterators` module.
+ Module :mod:`nntplib`
+ NNTP (Net News Transport Protocol) client
-.. rubric:: Footnotes
+ Module :mod:`mailbox`
+ Tools for creating, reading, and managing collections of messages on disk
+ using a variety standard formats.
-.. [#] Delivery Status Notifications (DSN) are defined in :rfc:`1894`.
+ Module :mod:`smtpd`
+ SMTP server framework (primarily useful for testing)
diff --git a/Doc/library/email.util.rst b/Doc/library/email.util.rst
index 5cff746..63fae2a 100644
--- a/Doc/library/email.util.rst
+++ b/Doc/library/email.util.rst
@@ -8,7 +8,43 @@
--------------
-There are several useful utilities provided in the :mod:`email.utils` module:
+There are a couple of useful utilities provided in the :mod:`email.utils`
+module:
+
+.. function:: localtime(dt=None)
+
+ Return local time as an aware datetime object. If called without
+ arguments, return current time. Otherwise *dt* argument should be a
+ :class:`~datetime.datetime` instance, and it is converted to the local time
+ zone according to the system time zone database. If *dt* is naive (that
+ is, ``dt.tzinfo`` is ``None``), it is assumed to be in local time. In this
+ case, a positive or zero value for *isdst* causes ``localtime`` to presume
+ initially that summer time (for example, Daylight Saving Time) is or is not
+ (respectively) in effect for the specified time. A negative value for
+ *isdst* causes the ``localtime`` to attempt to divine whether summer time
+ is in effect for the specified time.
+
+ .. versionadded:: 3.3
+
+
+.. function:: make_msgid(idstring=None, domain=None)
+
+ Returns a string suitable for an :rfc:`2822`\ -compliant
+ :mailheader:`Message-ID` header. Optional *idstring* if given, is a string
+ used to strengthen the uniqueness of the message id. Optional *domain* if
+ given provides the portion of the msgid after the '@'. The default is the
+ local hostname. It is not normally necessary to override this default, but
+ may be useful certain cases, such as a constructing distributed system that
+ uses a consistent domain name across multiple hosts.
+
+ .. versionchanged:: 3.2
+ Added the *domain* keyword.
+
+
+The remaining functions are part of the legacy (``Compat32``) email API. There
+is no need to directly use these with the new API, since the parsing and
+formatting they provide is done automatically by the header parsing machinery
+of the new API.
.. function:: quote(str)
@@ -141,36 +177,6 @@ There are several useful utilities provided in the :mod:`email.utils` module:
.. versionadded:: 3.3
-.. function:: localtime(dt=None)
-
- Return local time as an aware datetime object. If called without
- arguments, return current time. Otherwise *dt* argument should be a
- :class:`~datetime.datetime` instance, and it is converted to the local time
- zone according to the system time zone database. If *dt* is naive (that
- is, ``dt.tzinfo`` is ``None``), it is assumed to be in local time. In this
- case, a positive or zero value for *isdst* causes ``localtime`` to presume
- initially that summer time (for example, Daylight Saving Time) is or is not
- (respectively) in effect for the specified time. A negative value for
- *isdst* causes the ``localtime`` to attempt to divine whether summer time
- is in effect for the specified time.
-
- .. versionadded:: 3.3
-
-
-.. function:: make_msgid(idstring=None, domain=None)
-
- Returns a string suitable for an :rfc:`2822`\ -compliant
- :mailheader:`Message-ID` header. Optional *idstring* if given, is a string
- used to strengthen the uniqueness of the message id. Optional *domain* if
- given provides the portion of the msgid after the '@'. The default is the
- local hostname. It is not normally necessary to override this default, but
- may be useful certain cases, such as a constructing distributed system that
- uses a consistent domain name across multiple hosts.
-
- .. versionchanged:: 3.2
- Added the *domain* keyword.
-
-
.. function:: decode_rfc2231(s)
Decode the string *s* according to :rfc:`2231`.
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index a3d5afc..ddcc286 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -23,9 +23,10 @@ by identity, and the enumeration itself can be iterated over.
Module Contents
---------------
-This module defines two enumeration classes that can be used to define unique
-sets of names and values: :class:`Enum` and :class:`IntEnum`. It also defines
-one decorator, :func:`unique`.
+This module defines four enumeration classes that can be used to define unique
+sets of names and values: :class:`Enum`, :class:`IntEnum`, and
+:class:`IntFlags`. It also defines one decorator, :func:`unique`, and one
+helper, :class:`auto`.
.. class:: Enum
@@ -37,10 +38,27 @@ one decorator, :func:`unique`.
Base class for creating enumerated constants that are also
subclasses of :class:`int`.
+.. class:: IntFlag
+
+ Base class for creating enumerated constants that can be combined using
+ the bitwise operators without losing their :class:`IntFlag` membership.
+ :class:`IntFlag` members are also subclasses of :class:`int`.
+
+.. class:: Flag
+
+ Base class for creating enumerated constants that can be combined using
+ the bitwise operations without losing their :class:`Flag` membership.
+
.. function:: unique
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.
+
+.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto``
+
Creating an Enum
----------------
@@ -52,18 +70,25 @@ follows::
>>> from enum import Enum
>>> class Color(Enum):
- ... red = 1
- ... green = 2
- ... blue = 3
+ ... RED = 1
+ ... GREEN = 2
+ ... BLUE = 3
...
+.. note:: Enum member values
+
+ Member values can be anything: :class:`int`, :class:`str`, etc.. If
+ the exact value is unimportant you may use :class:`auto` instances and an
+ appropriate value will be chosen for you. Care must be taken if you mix
+ :class:`auto` with other values.
+
.. note:: Nomenclature
- The class :class:`Color` is an *enumeration* (or *enum*)
- - The attributes :attr:`Color.red`, :attr:`Color.green`, etc., are
- *enumeration members* (or *enum members*).
+ - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are
+ *enumeration members* (or *enum members*) and are functionally constants.
- The enum members have *names* and *values* (the name of
- :attr:`Color.red` is ``red``, the value of :attr:`Color.blue` is
+ :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is
``3``, etc.)
.. note::
@@ -74,49 +99,49 @@ follows::
Enumeration members have human readable string representations::
- >>> print(Color.red)
- Color.red
+ >>> print(Color.RED)
+ Color.RED
...while their ``repr`` has more information::
- >>> print(repr(Color.red))
- <Color.red: 1>
+ >>> print(repr(Color.RED))
+ <Color.RED: 1>
The *type* of an enumeration member is the enumeration it belongs to::
- >>> type(Color.red)
+ >>> type(Color.RED)
<enum 'Color'>
- >>> isinstance(Color.green, Color)
+ >>> isinstance(Color.GREEN, Color)
True
>>>
Enum members also have a property that contains just their item name::
- >>> print(Color.red.name)
- red
+ >>> print(Color.RED.name)
+ RED
Enumerations support iteration, in definition order::
>>> class Shake(Enum):
- ... vanilla = 7
- ... chocolate = 4
- ... cookies = 9
- ... mint = 3
+ ... VANILLA = 7
+ ... CHOCOLATE = 4
+ ... COOKIES = 9
+ ... MINT = 3
...
>>> for shake in Shake:
... print(shake)
...
- Shake.vanilla
- Shake.chocolate
- Shake.cookies
- Shake.mint
+ Shake.VANILLA
+ Shake.CHOCOLATE
+ Shake.COOKIES
+ Shake.MINT
Enumeration members are hashable, so they can be used in dictionaries and sets::
>>> apples = {}
- >>> apples[Color.red] = 'red delicious'
- >>> apples[Color.green] = 'granny smith'
- >>> apples == {Color.red: 'red delicious', Color.green: 'granny smith'}
+ >>> apples[Color.RED] = 'red delicious'
+ >>> apples[Color.GREEN] = 'granny smith'
+ >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
True
@@ -124,26 +149,26 @@ Programmatic access to enumeration members and their attributes
---------------------------------------------------------------
Sometimes it's useful to access members in enumerations programmatically (i.e.
-situations where ``Color.red`` won't do because the exact color is not known
+situations where ``Color.RED`` won't do because the exact color is not known
at program-writing time). ``Enum`` allows such access::
>>> Color(1)
- <Color.red: 1>
+ <Color.RED: 1>
>>> Color(3)
- <Color.blue: 3>
+ <Color.BLUE: 3>
If you want to access enum members by *name*, use item access::
- >>> Color['red']
- <Color.red: 1>
- >>> Color['green']
- <Color.green: 2>
+ >>> Color['RED']
+ <Color.RED: 1>
+ >>> Color['GREEN']
+ <Color.GREEN: 2>
If you have an enum member and need its :attr:`name` or :attr:`value`::
- >>> member = Color.red
+ >>> member = Color.RED
>>> member.name
- 'red'
+ 'RED'
>>> member.value
1
@@ -154,12 +179,12 @@ Duplicating enum members and values
Having two enum members with the same name is invalid::
>>> class Shape(Enum):
- ... square = 2
- ... square = 3
+ ... SQUARE = 2
+ ... SQUARE = 3
...
Traceback (most recent call last):
...
- TypeError: Attempted to reuse key: 'square'
+ TypeError: Attempted to reuse key: 'SQUARE'
However, two enum members are allowed to have the same value. Given two members
A and B with the same value (and A defined first), B is an alias to A. By-value
@@ -167,17 +192,17 @@ lookup of the value of A and B will return A. By-name lookup of B will also
return A::
>>> class Shape(Enum):
- ... square = 2
- ... diamond = 1
- ... circle = 3
- ... alias_for_square = 2
- ...
- >>> Shape.square
- <Shape.square: 2>
- >>> Shape.alias_for_square
- <Shape.square: 2>
+ ... SQUARE = 2
+ ... DIAMOND = 1
+ ... CIRCLE = 3
+ ... ALIAS_FOR_SQUARE = 2
+ ...
+ >>> Shape.SQUARE
+ <Shape.SQUARE: 2>
+ >>> Shape.ALIAS_FOR_SQUARE
+ <Shape.SQUARE: 2>
>>> Shape(2)
- <Shape.square: 2>
+ <Shape.SQUARE: 2>
.. note::
@@ -202,15 +227,51 @@ found :exc:`ValueError` is raised with the details::
>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
- ... one = 1
- ... two = 2
- ... three = 3
- ... four = 3
+ ... ONE = 1
+ ... TWO = 2
+ ... THREE = 3
+ ... FOUR = 3
...
Traceback (most recent call last):
...
- ValueError: duplicate values found in <enum 'Mistake'>: four -> three
+ ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
+
+
+Using automatic values
+----------------------
+
+If the exact value is unimportant you can use :class:`auto`::
+
+ >>> from enum import Enum, auto
+ >>> class Color(Enum):
+ ... RED = auto()
+ ... BLUE = auto()
+ ... GREEN = auto()
+ ...
+ >>> list(Color)
+ [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
+
+The values are chosen by :func:`_generate_next_value_`, which can be
+overridden::
+
+ >>> class AutoName(Enum):
+ ... def _generate_next_value_(name, start, count, last_values):
+ ... return name
+ ...
+ >>> class Ordinal(AutoName):
+ ... NORTH = auto()
+ ... SOUTH = auto()
+ ... EAST = auto()
+ ... WEST = auto()
+ ...
+ >>> list(Ordinal)
+ [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
+
+.. note::
+ The goal of the default :meth:`_generate_next_value_` methods is to provide
+ the next :class:`int` in sequence with the last :class:`int` provided, but
+ the way it does this is an implementation detail and may change.
Iteration
---------
@@ -218,7 +279,7 @@ Iteration
Iterating over the members of an enum does not provide the aliases::
>>> list(Shape)
- [<Shape.square: 2>, <Shape.diamond: 1>, <Shape.circle: 3>]
+ [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
The special attribute ``__members__`` is an ordered dictionary mapping names
to members. It includes all names defined in the enumeration, including the
@@ -227,16 +288,16 @@ aliases::
>>> for name, member in Shape.__members__.items():
... name, member
...
- ('square', <Shape.square: 2>)
- ('diamond', <Shape.diamond: 1>)
- ('circle', <Shape.circle: 3>)
- ('alias_for_square', <Shape.square: 2>)
+ ('SQUARE', <Shape.SQUARE: 2>)
+ ('DIAMOND', <Shape.DIAMOND: 1>)
+ ('CIRCLE', <Shape.CIRCLE: 3>)
+ ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
The ``__members__`` attribute can be used for detailed programmatic access to
the enumeration members. For example, finding all the aliases::
>>> [name for name, member in Shape.__members__.items() if member.name != name]
- ['alias_for_square']
+ ['ALIAS_FOR_SQUARE']
Comparisons
@@ -244,35 +305,35 @@ Comparisons
Enumeration members are compared by identity::
- >>> Color.red is Color.red
+ >>> Color.RED is Color.RED
True
- >>> Color.red is Color.blue
+ >>> Color.RED is Color.BLUE
False
- >>> Color.red is not Color.blue
+ >>> Color.RED is not Color.BLUE
True
Ordered comparisons between enumeration values are *not* supported. Enum
members are not integers (but see `IntEnum`_ below)::
- >>> Color.red < Color.blue
+ >>> Color.RED < Color.BLUE
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- TypeError: unorderable types: Color() < Color()
+ TypeError: '<' not supported between instances of 'Color' and 'Color'
Equality comparisons are defined though::
- >>> Color.blue == Color.red
+ >>> Color.BLUE == Color.RED
False
- >>> Color.blue != Color.red
+ >>> Color.BLUE != Color.RED
True
- >>> Color.blue == Color.blue
+ >>> Color.BLUE == Color.BLUE
True
Comparisons against non-enumeration values will always compare not equal
(again, :class:`IntEnum` was explicitly designed to behave differently, see
below)::
- >>> Color.blue == 2
+ >>> Color.BLUE == 2
False
@@ -289,8 +350,8 @@ Enumerations are Python classes, and can have methods and special methods as
usual. If we have this enumeration::
>>> class Mood(Enum):
- ... funky = 1
- ... happy = 3
+ ... FUNKY = 1
+ ... HAPPY = 3
...
... def describe(self):
... # self is the member here
@@ -302,16 +363,16 @@ usual. If we have this enumeration::
... @classmethod
... def favorite_mood(cls):
... # cls here is the enumeration
- ... return cls.happy
+ ... return cls.HAPPY
...
Then::
>>> Mood.favorite_mood()
- <Mood.happy: 3>
- >>> Mood.happy.describe()
- ('happy', 3)
- >>> str(Mood.funky)
+ <Mood.HAPPY: 3>
+ >>> Mood.HAPPY.describe()
+ ('HAPPY', 3)
+ >>> str(Mood.FUNKY)
'my custom str! 1'
The rules for what is allowed are as follows: names that start and end with
@@ -332,7 +393,7 @@ Subclassing an enumeration is allowed only if the enumeration does not define
any members. So this is forbidden::
>>> class MoreColor(Color):
- ... pink = 17
+ ... PINK = 17
...
Traceback (most recent call last):
...
@@ -345,8 +406,8 @@ But this is allowed::
... pass
...
>>> class Bar(Foo):
- ... happy = 1
- ... sad = 2
+ ... HAPPY = 1
+ ... SAD = 2
...
Allowing subclassing of enums that define members would lead to a violation of
@@ -362,7 +423,7 @@ Enumerations can be pickled and unpickled::
>>> from test.test_enum import Fruit
>>> from pickle import dumps, loads
- >>> Fruit.tomato is loads(dumps(Fruit.tomato))
+ >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
True
The usual restrictions for pickling apply: picklable enums must be defined in
@@ -383,15 +444,15 @@ Functional API
The :class:`Enum` class is callable, providing the following functional API::
- >>> Animal = Enum('Animal', 'ant bee cat dog')
+ >>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
>>> Animal
<enum 'Animal'>
- >>> Animal.ant
- <Animal.ant: 1>
- >>> Animal.ant.value
+ >>> Animal.ANT
+ <Animal.ANT: 1>
+ >>> Animal.ANT.value
1
>>> list(Animal)
- [<Animal.ant: 1>, <Animal.bee: 2>, <Animal.cat: 3>, <Animal.dog: 4>]
+ [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
The semantics of this API resemble :class:`~collections.namedtuple`. The first
argument of the call to :class:`Enum` is the name of the enumeration.
@@ -406,10 +467,10 @@ new class derived from :class:`Enum` is returned. In other words, the above
assignment to :class:`Animal` is equivalent to::
>>> class Animal(Enum):
- ... ant = 1
- ... bee = 2
- ... cat = 3
- ... dog = 4
+ ... ANT = 1
+ ... BEE = 2
+ ... CAT = 3
+ ... DOG = 4
...
The reason for defaulting to ``1`` as the starting number and not ``0`` is
@@ -422,7 +483,7 @@ enumeration is being created in (e.g. it will fail if you use a utility
function in separate module, and also may not work on IronPython or Jython).
The solution is to specify the module name explicitly as follows::
- >>> Animal = Enum('Animal', 'ant bee cat dog', module=__name__)
+ >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
.. warning::
@@ -435,7 +496,7 @@ The new pickle protocol 4 also, in some circumstances, relies on
to find the class. For example, if the class was made available in class
SomeData in the global scope::
- >>> Animal = Enum('Animal', 'ant bee cat dog', qualname='SomeData.Animal')
+ >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
The complete signature is::
@@ -446,19 +507,19 @@ The complete signature is::
:names: The Enum members. This can be a whitespace or comma separated string
(values will start at 1 unless otherwise specified)::
- 'red green blue' | 'red,green,blue' | 'red, green, blue'
+ 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
or an iterator of names::
- ['red', 'green', 'blue']
+ ['RED', 'GREEN', 'BLUE']
or an iterator of (name, value) pairs::
- [('cyan', 4), ('magenta', 5), ('yellow', 6)]
+ [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
or a mapping::
- {'chartreuse': 7, 'sea_green': 11, 'rosemary': 42}
+ {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
:module: name of module where new Enum class can be found.
@@ -478,56 +539,167 @@ Derived Enumerations
IntEnum
^^^^^^^
-A variation of :class:`Enum` is provided which is also a subclass of
+The first variation of :class:`Enum` that is provided is also a subclass of
:class:`int`. Members of an :class:`IntEnum` can be compared to integers;
by extension, integer enumerations of different types can also be compared
to each other::
>>> from enum import IntEnum
>>> class Shape(IntEnum):
- ... circle = 1
- ... square = 2
+ ... CIRCLE = 1
+ ... SQUARE = 2
...
>>> class Request(IntEnum):
- ... post = 1
- ... get = 2
+ ... POST = 1
+ ... GET = 2
...
>>> Shape == 1
False
- >>> Shape.circle == 1
+ >>> Shape.CIRCLE == 1
True
- >>> Shape.circle == Request.post
+ >>> Shape.CIRCLE == Request.POST
True
However, they still can't be compared to standard :class:`Enum` enumerations::
>>> class Shape(IntEnum):
- ... circle = 1
- ... square = 2
+ ... CIRCLE = 1
+ ... SQUARE = 2
...
>>> class Color(Enum):
- ... red = 1
- ... green = 2
+ ... RED = 1
+ ... GREEN = 2
...
- >>> Shape.circle == Color.red
+ >>> Shape.CIRCLE == Color.RED
False
:class:`IntEnum` values behave like integers in other ways you'd expect::
- >>> int(Shape.circle)
+ >>> int(Shape.CIRCLE)
1
- >>> ['a', 'b', 'c'][Shape.circle]
+ >>> ['a', 'b', 'c'][Shape.CIRCLE]
'b'
- >>> [i for i in range(Shape.square)]
+ >>> [i for i in range(Shape.SQUARE)]
[0, 1]
-For the vast majority of code, :class:`Enum` is strongly recommended,
-since :class:`IntEnum` breaks some semantic promises of an enumeration (by
-being comparable to integers, and thus by transitivity to other
-unrelated enumerations). It should be used only in special cases where
-there's no other choice; for example, when integer constants are
-replaced with enumerations and backwards compatibility is required with code
-that still expects integers.
+
+IntFlag
+^^^^^^^
+
+The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based
+on :class:`int`. The difference being :class:`IntFlag` members can be combined
+using the bitwise operators (&, \|, ^, ~) and the result is still an
+:class:`IntFlag` member. However, as the name implies, :class:`IntFlag`
+members also subclass :class:`int` and can be used wherever an :class:`int` is
+used. Any operation on an :class:`IntFlag` member besides the bit-wise
+operations will lose the :class:`IntFlag` membership.
+
+.. versionadded:: 3.6
+
+Sample :class:`IntFlag` class::
+
+ >>> from enum import IntFlag
+ >>> class Perm(IntFlag):
+ ... R = 4
+ ... W = 2
+ ... X = 1
+ ...
+ >>> Perm.R | Perm.W
+ <Perm.R|W: 6>
+ >>> Perm.R + Perm.W
+ 6
+ >>> RW = Perm.R | Perm.W
+ >>> Perm.R in RW
+ True
+
+It is also possible to name the combinations::
+
+ >>> class Perm(IntFlag):
+ ... R = 4
+ ... W = 2
+ ... X = 1
+ ... RWX = 7
+ >>> Perm.RWX
+ <Perm.RWX: 7>
+ >>> ~Perm.RWX
+ <Perm.-8: -8>
+
+Another important difference between :class:`IntFlag` and :class:`Enum` is that
+if no flags are set (the value is 0), its boolean evaluation is :data:`False`::
+
+ >>> Perm.R & Perm.X
+ <Perm.0: 0>
+ >>> bool(Perm.R & Perm.X)
+ False
+
+Because :class:`IntFlag` members are also subclasses of :class:`int` they can
+be combined with them::
+
+ >>> Perm.X | 8
+ <Perm.8|X: 9>
+
+
+Flag
+^^^^
+
+The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag`
+members can be combined using the bitwise operators (&, \|, ^, ~). Unlike
+:class:`IntFlag`, they cannot be combined with, nor compared against, any
+other :class:`Flag` enumeration, nor :class:`int`. While it is possible to
+specify the values directly it is recommended to use :class:`auto` as the
+value and let :class:`Flag` select an appropriate value.
+
+.. versionadded:: 3.6
+
+Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no
+flags being set, the boolean evaluation is :data:`False`::
+
+ >>> from enum import Flag
+ >>> class Color(Flag):
+ ... RED = auto()
+ ... BLUE = auto()
+ ... GREEN = auto()
+ ...
+ >>> Color.RED & Color.GREEN
+ <Color.0: 0>
+ >>> bool(Color.RED & Color.GREEN)
+ False
+
+Individual flags should have values that are powers of two (1, 2, 4, 8, ...),
+while combinations of flags won't::
+
+ >>> class Color(Flag):
+ ... RED = auto()
+ ... BLUE = auto()
+ ... GREEN = auto()
+ ... WHITE = RED | BLUE | GREEN
+ ...
+ >>> Color.WHITE
+ <Color.WHITE: 7>
+
+Giving a name to the "no flags set" condition does not change its boolean
+value::
+
+ >>> class Color(Flag):
+ ... BLACK = 0
+ ... RED = auto()
+ ... BLUE = auto()
+ ... GREEN = auto()
+ ...
+ >>> Color.BLACK
+ <Color.BLACK: 0>
+ >>> bool(Color.BLACK)
+ False
+
+.. note::
+
+ For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
+ recommended, since :class:`IntEnum` and :class:`IntFlag` break some
+ semantic promises of an enumeration (by being comparable to integers, and
+ thus by transitivity to other unrelated enumerations). :class:`IntEnum`
+ and :class:`IntFlag` should be used only in cases where :class:`Enum` and
+ :class:`Flag` will not do; for example, when integer constants are replaced
+ with enumerations, or for interoperability with other systems.
Others
@@ -558,7 +730,8 @@ Some rules:
4. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
:meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
`%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
-5. :meth:`str.format` (or :func:`format`) will use the mixed-in
+5. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
+ and :func:`format` will use the mixed-in
type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
:func:`repr` is desired, use the `!s` or `!r` format codes.
@@ -566,18 +739,87 @@ Some rules:
Interesting examples
--------------------
-While :class:`Enum` and :class:`IntEnum` are expected to cover the majority of
-use-cases, they cannot cover them all. Here are recipes for some different
-types of enumerations that can be used directly, or as examples for creating
-one's own.
+While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are
+expected to cover the majority of use-cases, they cannot cover them all. Here
+are recipes for some different types of enumerations that can be used directly,
+or as examples for creating one's own.
-AutoNumber
-^^^^^^^^^^
+Omitting values
+^^^^^^^^^^^^^^^
-Avoids having to specify the value for each enumeration member::
+In many use-cases one doesn't care what the actual value of an enumeration
+is. There are several ways to define this type of simple enumeration:
- >>> class AutoNumber(Enum):
+- use instances of :class:`auto` for the value
+- use instances of :class:`object` as the value
+- use a descriptive string as the value
+- use a tuple as the value and a custom :meth:`__new__` to replace the
+ tuple with an :class:`int` value
+
+Using any of these methods signifies to the user that these values are not
+important, and also enables one to add, remove, or reorder members without
+having to renumber the remaining members.
+
+Whichever method you choose, you should provide a :meth:`repr` that also hides
+the (unimportant) value::
+
+ >>> class NoValue(Enum):
+ ... def __repr__(self):
+ ... return '<%s.%s>' % (self.__class__.__name__, self.name)
+ ...
+
+
+Using :class:`auto`
+"""""""""""""""""""
+
+Using :class:`object` would look like::
+
+ >>> class Color(NoValue):
+ ... RED = auto()
+ ... BLUE = auto()
+ ... GREEN = auto()
+ ...
+ >>> Color.GREEN
+ <Color.GREEN>
+
+
+Using :class:`object`
+"""""""""""""""""""""
+
+Using :class:`object` would look like::
+
+ >>> class Color(NoValue):
+ ... RED = object()
+ ... GREEN = object()
+ ... BLUE = object()
+ ...
+ >>> Color.GREEN
+ <Color.GREEN>
+
+
+Using a descriptive string
+""""""""""""""""""""""""""
+
+Using a string as the value would look like::
+
+ >>> class Color(NoValue):
+ ... RED = 'stop'
+ ... GREEN = 'go'
+ ... BLUE = 'too fast!'
+ ...
+ >>> Color.GREEN
+ <Color.GREEN>
+ >>> Color.GREEN.value
+ 'go'
+
+
+Using a custom :meth:`__new__`
+""""""""""""""""""""""""""""""
+
+Using an auto-numbering :meth:`__new__` would look like::
+
+ >>> class AutoNumber(NoValue):
... def __new__(cls):
... value = len(cls.__members__) + 1
... obj = object.__new__(cls)
@@ -585,12 +827,15 @@ Avoids having to specify the value for each enumeration member::
... return obj
...
>>> class Color(AutoNumber):
- ... red = ()
- ... green = ()
- ... blue = ()
+ ... RED = ()
+ ... GREEN = ()
+ ... BLUE = ()
...
- >>> Color.green.value == 2
- True
+ >>> Color.GREEN
+ <Color.GREEN>
+ >>> Color.GREEN.value
+ 2
+
.. note::
@@ -652,14 +897,14 @@ alias::
... % (a, e))
...
>>> class Color(DuplicateFreeEnum):
- ... red = 1
- ... green = 2
- ... blue = 3
- ... grene = 2
+ ... RED = 1
+ ... GREEN = 2
+ ... BLUE = 3
+ ... GRENE = 2
...
Traceback (most recent call last):
...
- ValueError: aliases not allowed in DuplicateFreeEnum: 'grene' --> 'green'
+ ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'
.. note::
@@ -730,10 +975,61 @@ member instances.
Finer Points
^^^^^^^^^^^^
-:class:`Enum` members are instances of an :class:`Enum` class, and even
-though they are accessible as `EnumClass.member`, they should not be accessed
-directly from the member as that lookup may fail or, worse, return something
-besides the :class:`Enum` member you looking for::
+Supported ``__dunder__`` names
+""""""""""""""""""""""""""""""
+
+:attr:`__members__` is an :class:`OrderedDict` of ``member_name``:``member``
+items. It is only available on the class.
+
+:meth:`__new__`, if specified, must create and return the enum members; it is
+also a very good idea to set the member's :attr:`_value_` appropriately. Once
+all the members are created it is no longer used.
+
+
+Supported ``_sunder_`` names
+""""""""""""""""""""""""""""
+
+- ``_name_`` -- name of the member
+- ``_value_`` -- value of the member; can be set / modified in ``__new__``
+
+- ``_missing_`` -- a lookup function used when a value is not found; may be
+ overridden
+- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent
+ (class attribute, removed during class creation)
+- ``_generate_next_value_`` -- used by the `Functional API`_ and by
+ :class:`auto` to get an appropriate value for an enum member; may be
+ overridden
+
+.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
+
+To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can
+be provided. It will be checked against the actual order of the enumeration
+and raise an error if the two do not match::
+
+ >>> class Color(Enum):
+ ... _order_ = 'RED GREEN BLUE'
+ ... RED = 1
+ ... BLUE = 3
+ ... GREEN = 2
+ ...
+ Traceback (most recent call last):
+ ...
+ TypeError: member order does not match _order_
+
+.. note::
+
+ In Python 2 code the :attr:`_order_` attribute is necessary as definition
+ order is lost before it can be recorded.
+
+``Enum`` member type
+""""""""""""""""""""
+
+:class:`Enum` members are instances of their :class:`Enum` class, and are
+normally accessed as ``EnumClass.member``. Under certain circumstances they
+can also be accessed as ``EnumClass.member.member``, but you should never do
+this as that lookup may fail or, worse, return something besides the
+:class:`Enum` member you are looking for (this is another good reason to use
+all-uppercase names for members)::
>>> class FieldTypes(Enum):
... name = 0
@@ -747,7 +1043,24 @@ besides the :class:`Enum` member you looking for::
.. versionchanged:: 3.5
-The :attr:`__members__` attribute is only available on the class.
+
+Boolean value of ``Enum`` classes and members
+"""""""""""""""""""""""""""""""""""""""""""""
+
+:class:`Enum` members that are mixed with non-:class:`Enum` types (such as
+:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
+type's rules; otherwise, all members evaluate as :data:`True`. To make your
+own Enum's boolean evaluation depend on the member's value add the following to
+your class::
+
+ def __bool__(self):
+ return bool(self.value)
+
+:class:`Enum` classes always evaluate as :data:`True`.
+
+
+``Enum`` classes with methods
+"""""""""""""""""""""""""""""
If you give your :class:`Enum` subclass extra methods, like the `Planet`_
class above, those methods will show up in a :func:`dir` of the member,
@@ -758,11 +1071,23 @@ but not of the class::
>>> dir(Planet.EARTH)
['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
-The :meth:`__new__` method will only be used for the creation of the
-:class:`Enum` members -- after that it is replaced. Any custom :meth:`__new__`
-method must create the object and set the :attr:`_value_` attribute
-appropriately.
-If you wish to change how :class:`Enum` members are looked up you should either
-write a helper function or a :func:`classmethod` for the :class:`Enum`
-subclass.
+Combining members of ``Flag``
+"""""""""""""""""""""""""""""
+
+If a combination of Flag members is not named, the :func:`repr` will include
+all named flags and all named combinations of flags that are in the value::
+
+ >>> class Color(Flag):
+ ... RED = auto()
+ ... GREEN = auto()
+ ... BLUE = auto()
+ ... MAGENTA = RED | BLUE
+ ... YELLOW = RED | GREEN
+ ... CYAN = GREEN | BLUE
+ ...
+ >>> Color(3) # named combination
+ <Color.YELLOW: 3>
+ >>> Color(7) # not named combination
+ <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
+
diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst
index 5a71933..a428f51 100644
--- a/Doc/library/exceptions.rst
+++ b/Doc/library/exceptions.rst
@@ -170,8 +170,9 @@ The following exceptions are the exceptions that are usually raised.
.. exception:: ImportError
- Raised when an :keyword:`import` statement fails to find the module definition
- or when a ``from ... import`` fails to find a name that is to be imported.
+ Raised when the :keyword:`import` statement has troubles trying to
+ load a module. Also raised when the "from list" in ``from ... import``
+ has a name that cannot be found.
The :attr:`name` and :attr:`path` attributes can be set using keyword-only
arguments to the constructor. When set they represent the name of the module
@@ -181,6 +182,14 @@ The following exceptions are the exceptions that are usually raised.
.. versionchanged:: 3.3
Added the :attr:`name` and :attr:`path` attributes.
+.. exception:: ModuleNotFoundError
+
+ A subclass of :exc:`ImportError` which is raised by :keyword:`import`
+ when a module could not be located. It is also raised when ``None``
+ is found in :data:`sys.modules`.
+
+ .. versionadded:: 3.6
+
.. exception:: IndexError
@@ -228,9 +237,21 @@ The following exceptions are the exceptions that are usually raised.
.. exception:: NotImplementedError
This exception is derived from :exc:`RuntimeError`. In user defined base
- classes, abstract methods should raise this exception when they require derived
- classes to override the method.
+ classes, abstract methods should raise this exception when they require
+ derived classes to override the method, or while the class is being
+ developed to indicate that the real implementation still needs to be added.
+
+ .. note::
+ It should not be used to indicate that an operater or method is not
+ meant to be supported at all -- in that case either leave the operator /
+ method undefined or, if a subclass, set it to :data:`None`.
+
+ .. note::
+
+ ``NotImplementedError`` and ``NotImplemented`` are not interchangeable,
+ even though they have similar names and purposes. See
+ :data:`NotImplemented` for details on when to use it.
.. exception:: OSError([arg])
OSError(errno, strerror[, filename[, winerror[, filename2]]])
@@ -436,6 +457,15 @@ The following exceptions are the exceptions that are usually raised.
Raised when an operation or function is applied to an object of inappropriate
type. The associated value is a string giving details about the type mismatch.
+ This exception may be raised by user code to indicate that an attempted
+ operation on an object is not supported, and is not meant to be. If an object
+ is meant to support a given operation but has not yet provided an
+ implementation, :exc:`NotImplementedError` is the proper exception to raise.
+
+ Passing arguments of the wrong type (e.g. passing a :class:`list` when an
+ :class:`int` is expected) should result in a :exc:`TypeError`, but passing
+ arguments with the wrong value (e.g. a number outside expected boundaries)
+ should result in a :exc:`ValueError`.
.. exception:: UnboundLocalError
diff --git a/Doc/library/faulthandler.rst b/Doc/library/faulthandler.rst
index deedea1..d0c4cd0 100644
--- a/Doc/library/faulthandler.rst
+++ b/Doc/library/faulthandler.rst
@@ -70,6 +70,9 @@ Fault handler state
.. versionchanged:: 3.5
Added support for passing file descriptor to this function.
+ .. versionchanged:: 3.6
+ On Windows, a handler for Windows exception is also installed.
+
.. function:: disable()
Disable the fault handler: uninstall the signal handlers installed by
diff --git a/Doc/library/fileinput.rst b/Doc/library/fileinput.rst
index aa4c529..5881fef 100644
--- a/Doc/library/fileinput.rst
+++ b/Doc/library/fileinput.rst
@@ -72,9 +72,8 @@ The following function is the primary interface of this module:
.. versionchanged:: 3.2
Can be used as a context manager.
- .. versionchanged:: 3.5.2
- The *bufsize* parameter is no longer used.
-
+ .. deprecated-removed:: 3.6 3.8
+ The *bufsize* parameter.
The following functions use the global state created by :func:`fileinput.input`;
if there is no active state, :exc:`RuntimeError` is raised.
@@ -167,8 +166,8 @@ available for subclassing as well:
.. deprecated:: 3.4
The ``'rU'`` and ``'U'`` modes.
- .. versionchanged:: 3.5.2
- The *bufsize* parameter is no longer used.
+ .. deprecated-removed:: 3.6 3.8
+ The *bufsize* parameter.
**Optional in-place filtering:** if the keyword argument ``inplace=True`` is
@@ -195,10 +194,14 @@ The two following opening hooks are provided by this module:
Usage example: ``fi = fileinput.FileInput(openhook=fileinput.hook_compressed)``
-.. function:: hook_encoded(encoding)
+.. function:: hook_encoded(encoding, errors=None)
Returns a hook which opens each file with :func:`open`, using the given
- *encoding* to read the file.
+ *encoding* and *errors* to read the file.
Usage example: ``fi =
- fileinput.FileInput(openhook=fileinput.hook_encoded("iso-8859-1"))``
+ fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8",
+ "surrogateescape"))``
+
+ .. versionchanged:: 3.6
+ Added the optional *errors* parameter.
diff --git a/Doc/library/fnmatch.rst b/Doc/library/fnmatch.rst
index 9fc9c7c..c03a9d3 100644
--- a/Doc/library/fnmatch.rst
+++ b/Doc/library/fnmatch.rst
@@ -83,7 +83,7 @@ patterns.
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
- '.*\\.txt\\Z(?ms)'
+ '(?s:.*\\.txt)\\Z'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<_sre.SRE_Match object; span=(0, 10), match='foobar.txt'>
diff --git a/Doc/library/ftplib.rst b/Doc/library/ftplib.rst
index 1e35f37..b8c1dcf 100644
--- a/Doc/library/ftplib.rst
+++ b/Doc/library/ftplib.rst
@@ -97,6 +97,13 @@ The module defines the following items:
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
:data:`ssl.HAS_SNI`).
+ .. deprecated:: 3.6
+
+ *keyfile* and *certfile* are deprecated in favor of *context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
+
Here's a sample session using the :class:`FTP_TLS` class::
>>> ftps = FTP_TLS('ftp.pureftpd.org')
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index 2f14949..c26037b 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -271,6 +271,9 @@ are always available. They are listed here in alphabetical order.
The complex type is described in :ref:`typesnumeric`.
+ .. versionchanged:: 3.6
+ Grouping digits with underscores as in code literals is allowed.
+
.. function:: delattr(object, name)
@@ -531,11 +534,14 @@ are always available. They are listed here in alphabetical order.
The float type is described in :ref:`typesnumeric`.
- .. index::
- single: __format__
- single: string; format() (built-in function)
+ .. versionchanged:: 3.6
+ Grouping digits with underscores as in code literals is allowed.
+.. index::
+ single: __format__
+ single: string; format() (built-in function)
+
.. function:: format(value[, format_spec])
Convert a *value* to a "formatted" representation, as controlled by
@@ -702,6 +708,10 @@ are always available. They are listed here in alphabetical order.
:meth:`base.__int__ <object.__int__>` instead of :meth:`base.__index__
<object.__index__>`.
+ .. versionchanged:: 3.6
+ Grouping digits with underscores as in code literals is allowed.
+
+
.. function:: isinstance(object, classinfo)
Return true if the *object* argument is an instance of the *classinfo*
@@ -878,11 +888,11 @@ are always available. They are listed here in alphabetical order.
Open *file* and return a corresponding :term:`file object`. If the file
cannot be opened, an :exc:`OSError` is raised.
- *file* is either a string or bytes object giving the pathname (absolute or
- relative to the current working directory) of the file to be opened or
- an integer file descriptor of the file to be wrapped. (If a file descriptor
- is given, it is closed when the returned I/O object is closed, unless
- *closefd* is set to ``False``.)
+ *file* is a :term:`path-like object` giving the pathname (absolute or
+ relative to the current working directory) of the file to be opened or an
+ integer file descriptor of the file to be wrapped. (If a file descriptor is
+ given, it is closed when the returned I/O object is closed, unless *closefd*
+ is set to ``False``.)
*mode* is an optional string that specifies the mode in which the file is
opened. It defaults to ``'r'`` which means open for reading in text mode.
@@ -1055,27 +1065,38 @@ are always available. They are listed here in alphabetical order.
(where :func:`open` is declared), :mod:`os`, :mod:`os.path`, :mod:`tempfile`,
and :mod:`shutil`.
- .. versionchanged:: 3.3
- The *opener* parameter was added.
- The ``'x'`` mode was added.
- :exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`.
- :exc:`FileExistsError` is now raised if the file opened in exclusive
- creation mode (``'x'``) already exists.
+ .. versionchanged::
+ 3.3
- .. versionchanged:: 3.4
- The file is now non-inheritable.
+ * The *opener* parameter was added.
+ * The ``'x'`` mode was added.
+ * :exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`.
+ * :exc:`FileExistsError` is now raised if the file opened in exclusive
+ * creation mode (``'x'``) already exists.
+
+ .. versionchanged::
+ 3.4
+
+ * The file is now non-inheritable.
.. deprecated-removed:: 3.4 4.0
The ``'U'`` mode.
- .. versionchanged:: 3.5
- If the system call is interrupted and the signal handler does not raise an
- exception, the function now retries the system call instead of raising an
- :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
+ .. versionchanged::
+ 3.5
- .. versionchanged:: 3.5
- The ``'namereplace'`` error handler was added.
+ * If the system call is interrupted and the signal handler does not raise an
+ exception, the function now retries the system call instead of raising an
+ :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
+ * The ``'namereplace'`` error handler was added.
+
+ .. versionchanged::
+ 3.6
+
+ * Support added to accept objects implementing :class:`os.PathLike`.
+ * On Windows, opening a console buffer may return a subclass of
+ :class:`io.RawIOBase` other than :class:`io.FileIO`.
.. function:: ord(c)
@@ -1460,6 +1481,9 @@ are always available. They are listed here in alphabetical order.
See also :ref:`bltin-type-objects`.
+ .. versionchanged:: 3.6
+ Subclasses of :class:`type` which don't override ``type.__new__`` may no
+ longer use the one-argument form to get the type of an object.
.. function:: vars([object])
diff --git a/Doc/library/glob.rst b/Doc/library/glob.rst
index 328eef3..a8a5a50 100644
--- a/Doc/library/glob.rst
+++ b/Doc/library/glob.rst
@@ -14,7 +14,7 @@ The :mod:`glob` module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell, although results are returned in
arbitrary order. No tilde expansion is done, but ``*``, ``?``, and character
ranges expressed with ``[]`` will be correctly matched. This is done by using
-the :func:`os.listdir` and :func:`fnmatch.fnmatch` functions in concert, and
+the :func:`os.scandir` and :func:`fnmatch.fnmatch` functions in concert, and
not by actually invoking a subshell. Note that unlike :func:`fnmatch.fnmatch`,
:mod:`glob` treats filenames beginning with a dot (``.``) as special cases.
(For tilde and shell variable expansion, use :func:`os.path.expanduser` and
diff --git a/Doc/library/grp.rst b/Doc/library/grp.rst
index a30e622..74de3f9 100644
--- a/Doc/library/grp.rst
+++ b/Doc/library/grp.rst
@@ -43,6 +43,9 @@ It defines the following items:
Return the group database entry for the given numeric group ID. :exc:`KeyError`
is raised if the entry asked for cannot be found.
+ .. deprecated:: 3.6
+ Since Python 3.6 the support of non-integer arguments like floats or
+ strings in :func:`getgrgid` is deprecated.
.. function:: getgrnam(name)
diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst
index 792d57a..9c6b722 100644
--- a/Doc/library/gzip.rst
+++ b/Doc/library/gzip.rst
@@ -56,6 +56,8 @@ The module defines the following items:
.. versionchanged:: 3.4
Added support for the ``'x'``, ``'xb'`` and ``'xt'`` modes.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
.. class:: GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)
@@ -151,6 +153,9 @@ The module defines the following items:
The :meth:`~io.BufferedIOBase.read` method now accepts an argument of
``None``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: compress(data, compresslevel=9)
diff --git a/Doc/library/hashlib-blake2-tree.png b/Doc/library/hashlib-blake2-tree.png
new file mode 100644
index 0000000..010dcba
--- /dev/null
+++ b/Doc/library/hashlib-blake2-tree.png
Binary files differ
diff --git a/Doc/library/hashlib-blake2.rst b/Doc/library/hashlib-blake2.rst
new file mode 100644
index 0000000..436aa4f
--- /dev/null
+++ b/Doc/library/hashlib-blake2.rst
@@ -0,0 +1,444 @@
+.. _hashlib-blake2:
+
+:mod:`hashlib` --- BLAKE2 hash functions
+========================================
+
+.. module:: hashlib
+ :synopsis: BLAKE2 hash function for Python
+.. sectionauthor:: Dmitry Chestnykh
+
+.. index::
+ single: blake2b, blake2s
+
+BLAKE2_ is a cryptographic hash function defined in RFC-7693_ that comes in two
+flavors:
+
+* **BLAKE2b**, optimized for 64-bit platforms and produces digests of any size
+ between 1 and 64 bytes,
+
+* **BLAKE2s**, optimized for 8- to 32-bit platforms and produces digests of any
+ size between 1 and 32 bytes.
+
+BLAKE2 supports **keyed mode** (a faster and simpler replacement for HMAC_),
+**salted hashing**, **personalization**, and **tree hashing**.
+
+Hash objects from this module follow the API of standard library's
+:mod:`hashlib` objects.
+
+
+Module
+======
+
+Creating hash objects
+---------------------
+
+New hash objects are created by calling constructor functions:
+
+
+.. function:: blake2b(data=b'', digest_size=64, key=b'', salt=b'', \
+ person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
+ node_depth=0, inner_size=0, last_node=False)
+
+.. function:: blake2s(data=b'', digest_size=32, key=b'', salt=b'', \
+ person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
+ node_depth=0, inner_size=0, last_node=False)
+
+
+These functions return the corresponding hash objects for calculating
+BLAKE2b or BLAKE2s. They optionally take these general parameters:
+
+* *data*: initial chunk of data to hash, which must be interpretable as buffer
+ of bytes.
+
+* *digest_size*: size of output digest in bytes.
+
+* *key*: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for
+ BLAKE2s).
+
+* *salt*: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8
+ bytes for BLAKE2s).
+
+* *person*: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes
+ for BLAKE2s).
+
+The following table shows limits for general parameters (in bytes):
+
+======= =========== ======== ========= ===========
+Hash digest_size len(key) len(salt) len(person)
+======= =========== ======== ========= ===========
+BLAKE2b 64 64 16 16
+BLAKE2s 32 32 8 8
+======= =========== ======== ========= ===========
+
+.. note::
+
+ BLAKE2 specification defines constant lengths for salt and personalization
+ parameters, however, for convenience, this implementation accepts byte
+ strings of any size up to the specified length. If the length of the
+ parameter is less than specified, it is padded with zeros, thus, for
+ example, ``b'salt'`` and ``b'salt\x00'`` is the same value. (This is not
+ the case for *key*.)
+
+These sizes are available as module `constants`_ described below.
+
+Constructor functions also accept the following tree hashing parameters:
+
+* *fanout*: fanout (0 to 255, 0 if unlimited, 1 in sequential mode).
+
+* *depth*: maximal depth of tree (1 to 255, 255 if unlimited, 1 in
+ sequential mode).
+
+* *leaf_size*: maximal byte length of leaf (0 to 2**32-1, 0 if unlimited or in
+ sequential mode).
+
+* *node_offset*: node offset (0 to 2**64-1 for BLAKE2b, 0 to 2**48-1 for
+ BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode).
+
+* *node_depth*: node depth (0 to 255, 0 for leaves, or in sequential mode).
+
+* *inner_size*: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for
+ BLAKE2s, 0 in sequential mode).
+
+* *last_node*: boolean indicating whether the processed node is the last
+ one (`False` for sequential mode).
+
+.. figure:: hashlib-blake2-tree.png
+ :alt: Explanation of tree mode parameters.
+
+See section 2.10 in `BLAKE2 specification
+<https://blake2.net/blake2_20130129.pdf>`_ for comprehensive review of tree
+hashing.
+
+
+Constants
+---------
+
+.. data:: blake2b.SALT_SIZE
+.. data:: blake2s.SALT_SIZE
+
+Salt length (maximum length accepted by constructors).
+
+
+.. data:: blake2b.PERSON_SIZE
+.. data:: blake2s.PERSON_SIZE
+
+Personalization string length (maximum length accepted by constructors).
+
+
+.. data:: blake2b.MAX_KEY_SIZE
+.. data:: blake2s.MAX_KEY_SIZE
+
+Maximum key size.
+
+
+.. data:: blake2b.MAX_DIGEST_SIZE
+.. data:: blake2s.MAX_DIGEST_SIZE
+
+Maximum digest size that the hash function can output.
+
+
+Examples
+========
+
+Simple hashing
+--------------
+
+To calculate hash of some data, you should first construct a hash object by
+calling the appropriate constructor function (:func:`blake2b` or
+:func:`blake2s`), then update it with the data by calling :meth:`update` on the
+object, and, finally, get the digest out of the object by calling
+:meth:`digest` (or :meth:`hexdigest` for hex-encoded string).
+
+ >>> from hashlib import blake2b
+ >>> h = blake2b()
+ >>> h.update(b'Hello world')
+ >>> h.hexdigest()
+ '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
+
+
+As a shortcut, you can pass the first chunk of data to update directly to the
+constructor as the first argument (or as *data* keyword argument):
+
+ >>> from hashlib import blake2b
+ >>> blake2b(b'Hello world').hexdigest()
+ '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
+
+You can call :meth:`hash.update` as many times as you need to iteratively
+update the hash:
+
+ >>> from hashlib import blake2b
+ >>> items = [b'Hello', b' ', b'world']
+ >>> h = blake2b()
+ >>> for item in items:
+ ... h.update(item)
+ >>> h.hexdigest()
+ '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
+
+
+Using different digest sizes
+----------------------------
+
+BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32
+bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing
+the size of output, we can tell BLAKE2b to produce 20-byte digests:
+
+ >>> from hashlib import blake2b
+ >>> h = blake2b(digest_size=20)
+ >>> h.update(b'Replacing SHA1 with the more secure function')
+ >>> h.hexdigest()
+ 'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c'
+ >>> h.digest_size
+ 20
+ >>> len(h.digest())
+ 20
+
+Hash objects with different digest sizes have completely different outputs
+(shorter hashes are *not* prefixes of longer hashes); BLAKE2b and BLAKE2s
+produce different outputs even if the output length is the same:
+
+ >>> from hashlib import blake2b, blake2s
+ >>> blake2b(digest_size=10).hexdigest()
+ '6fa1d8fcfd719046d762'
+ >>> blake2b(digest_size=11).hexdigest()
+ 'eb6ec15daf9546254f0809'
+ >>> blake2s(digest_size=10).hexdigest()
+ '1bf21a98c78a1c376ae9'
+ >>> blake2s(digest_size=11).hexdigest()
+ '567004bf96e4a25773ebf4'
+
+
+Keyed hashing
+-------------
+
+Keyed hashing can be used for authentication as a faster and simpler
+replacement for `Hash-based message authentication code
+<http://en.wikipedia.org/wiki/Hash-based_message_authentication_code>`_ (HMAC).
+BLAKE2 can be securely used in prefix-MAC mode thanks to the
+indifferentiability property inherited from BLAKE.
+
+This example shows how to get a (hex-encoded) 128-bit authentication code for
+message ``b'message data'`` with key ``b'pseudorandom key'``::
+
+ >>> from hashlib import blake2b
+ >>> h = blake2b(key=b'pseudorandom key', digest_size=16)
+ >>> h.update(b'message data')
+ >>> h.hexdigest()
+ '3d363ff7401e02026f4a4687d4863ced'
+
+
+As a practical example, a web application can symmetrically sign cookies sent
+to users and later verify them to make sure they weren't tampered with::
+
+ >>> from hashlib import blake2b
+ >>> from hmac import compare_digest
+ >>>
+ >>> SECRET_KEY = b'pseudorandomly generated server secret key'
+ >>> AUTH_SIZE = 16
+ >>>
+ >>> def sign(cookie):
+ ... h = blake2b(data=cookie, digest_size=AUTH_SIZE, key=SECRET_KEY)
+ ... return h.hexdigest()
+ >>>
+ >>> cookie = b'user:vatrogasac'
+ >>> sig = sign(cookie)
+ >>> print("{0},{1}".format(cookie.decode('utf-8'), sig))
+ user:vatrogasac,349cf904533767ed2d755279a8df84d0
+ >>> compare_digest(cookie, sig)
+ True
+ >>> compare_digest(b'user:policajac', sig)
+ False
+ >>> compare_digesty(cookie, '0102030405060708090a0b0c0d0e0f00')
+ False
+
+Even though there's a native keyed hashing mode, BLAKE2 can, of course, be used
+in HMAC construction with :mod:`hmac` module::
+
+ >>> import hmac, hashlib
+ >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
+ >>> m.update(b'message')
+ >>> m.hexdigest()
+ 'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'
+
+
+Randomized hashing
+------------------
+
+By setting *salt* parameter users can introduce randomization to the hash
+function. Randomized hashing is useful for protecting against collision attacks
+on the hash function used in digital signatures.
+
+ Randomized hashing is designed for situations where one party, the message
+ preparer, generates all or part of a message to be signed by a second
+ party, the message signer. If the message preparer is able to find
+ cryptographic hash function collisions (i.e., two messages producing the
+ same hash value), then she might prepare meaningful versions of the message
+ that would produce the same hash value and digital signature, but with
+ different results (e.g., transferring $1,000,000 to an account, rather than
+ $10). Cryptographic hash functions have been designed with collision
+ resistance as a major goal, but the current concentration on attacking
+ cryptographic hash functions may result in a given cryptographic hash
+ function providing less collision resistance than expected. Randomized
+ hashing offers the signer additional protection by reducing the likelihood
+ that a preparer can generate two or more messages that ultimately yield the
+ same hash value during the digital signature generation process --- even if
+ it is practical to find collisions for the hash function. However, the use
+ of randomized hashing may reduce the amount of security provided by a
+ digital signature when all portions of the message are prepared
+ by the signer.
+
+ (`NIST SP-800-106 "Randomized Hashing for Digital Signatures"
+ <http://csrc.nist.gov/publications/nistpubs/800-106/NIST-SP-800-106.pdf>`_)
+
+In BLAKE2 the salt is processed as a one-time input to the hash function during
+initialization, rather than as an input to each compression function.
+
+.. warning::
+
+ *Salted hashing* (or just hashing) with BLAKE2 or any other general-purpose
+ cryptographic hash function, such as SHA-256, is not suitable for hashing
+ passwords. See `BLAKE2 FAQ <https://blake2.net/#qa>`_ for more
+ information.
+..
+
+ >>> import os
+ >>> from hashlib import blake2b
+ >>> msg = b'some message'
+ >>> # Calculate the first hash with a random salt.
+ >>> salt1 = os.urandom(blake2b.SALT_SIZE)
+ >>> h1 = blake2b(salt=salt1)
+ >>> h1.update(msg)
+ >>> # Calculate the second hash with a different random salt.
+ >>> salt2 = os.urandom(blake2b.SALT_SIZE)
+ >>> h2 = blake2b(salt=salt2)
+ >>> h2.update(msg)
+ >>> # The digests are different.
+ >>> h1.digest() != h2.digest()
+ True
+
+
+Personalization
+---------------
+
+Sometimes it is useful to force hash function to produce different digests for
+the same input for different purposes. Quoting the authors of the Skein hash
+function:
+
+ We recommend that all application designers seriously consider doing this;
+ we have seen many protocols where a hash that is computed in one part of
+ the protocol can be used in an entirely different part because two hash
+ computations were done on similar or related data, and the attacker can
+ force the application to make the hash inputs the same. Personalizing each
+ hash function used in the protocol summarily stops this type of attack.
+
+ (`The Skein Hash Function Family
+ <http://www.skein-hash.info/sites/default/files/skein1.3.pdf>`_,
+ p. 21)
+
+BLAKE2 can be personalized by passing bytes to the *person* argument::
+
+ >>> from hashlib import blake2b
+ >>> FILES_HASH_PERSON = b'MyApp Files Hash'
+ >>> BLOCK_HASH_PERSON = b'MyApp Block Hash'
+ >>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)
+ >>> h.update(b'the same content')
+ >>> h.hexdigest()
+ '20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'
+ >>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)
+ >>> h.update(b'the same content')
+ >>> h.hexdigest()
+ 'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'
+
+Personalization together with the keyed mode can also be used to derive different
+keys from a single one.
+
+ >>> from hashlib import blake2s
+ >>> from base64 import b64decode, b64encode
+ >>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=')
+ >>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest()
+ >>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest()
+ >>> print(b64encode(enc_key).decode('utf-8'))
+ rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=
+ >>> print(b64encode(mac_key).decode('utf-8'))
+ G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=
+
+Tree mode
+---------
+
+Here's an example of hashing a minimal tree with two leaf nodes::
+
+ 10
+ / \
+ 00 01
+
+This example uses 64-byte internal digests, and returns the 32-byte final
+digest::
+
+ >>> from hashlib import blake2b
+ >>>
+ >>> FANOUT = 2
+ >>> DEPTH = 2
+ >>> LEAF_SIZE = 4096
+ >>> INNER_SIZE = 64
+ >>>
+ >>> buf = bytearray(6000)
+ >>>
+ >>> # Left leaf
+ ... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,
+ ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
+ ... node_offset=0, node_depth=0, last_node=False)
+ >>> # Right leaf
+ ... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,
+ ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
+ ... node_offset=1, node_depth=0, last_node=True)
+ >>> # Root node
+ ... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,
+ ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
+ ... node_offset=0, node_depth=1, last_node=True)
+ >>> h10.update(h00.digest())
+ >>> h10.update(h01.digest())
+ >>> h10.hexdigest()
+ '3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'
+
+Credits
+=======
+
+BLAKE2_ was designed by *Jean-Philippe Aumasson*, *Samuel Neves*, *Zooko
+Wilcox-O'Hearn*, and *Christian Winnerlein* based on SHA-3_ finalist BLAKE_
+created by *Jean-Philippe Aumasson*, *Luca Henzen*, *Willi Meier*, and
+*Raphael C.-W. Phan*.
+
+It uses core algorithm from ChaCha_ cipher designed by *Daniel J. Bernstein*.
+
+The stdlib implementation is based on pyblake2_ module. It was written by
+*Dmitry Chestnykh* based on C implementation written by *Samuel Neves*. The
+documentation was copied from pyblake2_ and written by *Dmitry Chestnykh*.
+
+The C code was partly rewritten for Python by *Christian Heimes*.
+
+The following public domain dedication applies for both C hash function
+implementation, extension code, and this documentation:
+
+ To the extent possible under law, the author(s) have dedicated all copyright
+ and related and neighboring rights to this software to the public domain
+ worldwide. This software is distributed without any warranty.
+
+ You should have received a copy of the CC0 Public Domain Dedication along
+ with this software. If not, see
+ http://creativecommons.org/publicdomain/zero/1.0/.
+
+The following people have helped with development or contributed their changes
+to the project and the public domain according to the Creative Commons Public
+Domain Dedication 1.0 Universal:
+
+* *Alexandr Sokolovskiy*
+
+.. seealso:: Official BLAKE2 website: https://blake2.net
+
+.. _RFC-7693: https://tools.ietf.org/html/rfc7693
+.. _BLAKE2: https://blake2.net
+.. _HMAC: https://en.wikipedia.org/wiki/Hash-based_message_authentication_code
+.. _BLAKE: https://131002.net/blake/
+.. _SHA-3: https://en.wikipedia.org/wiki/NIST_hash_function_competition
+.. _ChaCha: https://cr.yp.to/chacha.html
+.. _pyblake2: https://pythonhosted.org/pyblake2/
+
diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst
index a2e96ca..2cb3c78 100644
--- a/Doc/library/hashlib.rst
+++ b/Doc/library/hashlib.rst
@@ -44,8 +44,8 @@ Hash algorithms
---------------
There is one constructor method named for each type of :dfn:`hash`. All return
-a hash object with the same simple interface. For example: use :func:`sha1` to
-create a SHA1 hash object. You can now feed this object with :term:`bytes-like
+a hash object with the same simple interface. For example: use :func:`sha256` to
+create a SHA-256 hash object. You can now feed this object with :term:`bytes-like
objects <bytes-like object>` (normally :class:`bytes`) using the :meth:`update` method.
At any point you can ask it for the :dfn:`digest` of the
concatenation of the data fed to it so far using the :meth:`digest` or
@@ -64,21 +64,33 @@ concatenation of the data fed to it so far using the :meth:`digest` or
.. index:: single: OpenSSL; (use in module hashlib)
Constructors for hash algorithms that are always present in this module are
-:func:`md5`, :func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`,
-and :func:`sha512`. Additional algorithms may also be available depending upon
-the OpenSSL library that Python uses on your platform.
+:func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`,
+:func:`sha512`, :func:`blake2b`, and :func:`blake2s`.
+:func:`md5` is normally available as well, though it
+may be missing if you are using a rare "FIPS compliant" build of Python.
+Additional algorithms may also be available depending upon the OpenSSL
+library that Python uses on your platform. On most platforms the
+:func:`sha3_224`, :func:`sha3_256`, :func:`sha3_384`, :func:`sha3_512`,
+:func:`shake_128`, :func:`shake_256` are also available.
+
+.. versionadded:: 3.6
+ SHA3 (Keccak) and SHAKE constructors :func:`sha3_224`, :func:`sha3_256`,
+ :func:`sha3_384`, :func:`sha3_512`, :func:`shake_128`, :func:`shake_256`.
+
+.. versionadded:: 3.6
+ :func:`blake2b` and :func:`blake2s` were added.
For example, to obtain the digest of the byte string ``b'Nobody inspects the
spammish repetition'``::
>>> import hashlib
- >>> m = hashlib.md5()
+ >>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
- b'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
+ b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
>>> m.digest_size
- 16
+ 32
>>> m.block_size
64
@@ -107,7 +119,9 @@ Hashlib provides the following constant attributes:
.. data:: algorithms_guaranteed
A set containing the names of the hash algorithms guaranteed to be supported
- by this module on all platforms.
+ by this module on all platforms. Note that 'md5' is in this list despite
+ some upstream vendors offering an odd "FIPS compliant" Python build that
+ excludes it.
.. versionadded:: 3.2
@@ -181,6 +195,28 @@ A hash object has the following methods:
compute the digests of data sharing a common initial substring.
+SHAKE variable length digests
+-----------------------------
+
+The :func:`shake_128` and :func:`shake_256` algorithms provide variable
+length digests with length_in_bits//2 up to 128 or 256 bits of security.
+As such, their digest methods require a length. Maximum length is not limited
+by the SHAKE algorithm.
+
+.. method:: shake.digest(length)
+
+ Return the digest of the data passed to the :meth:`update` method so far.
+ This is a bytes object of size ``length`` which may contain bytes in
+ the whole range from 0 to 255.
+
+
+.. method:: shake.hexdigest(length)
+
+ Like :meth:`digest` except the digest is returned as a string object of
+ double length, containing only hexadecimal digits. This may be used to
+ exchange the value safely in email or other non-binary environments.
+
+
Key derivation
--------------
@@ -221,6 +257,29 @@ include a `salt <https://en.wikipedia.org/wiki/Salt_%28cryptography%29>`_.
Python implementation uses an inline version of :mod:`hmac`. It is about
three times slower and doesn't release the GIL.
+.. function:: scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64)
+
+ The function provides scrypt password-based key derivation function as
+ defined in :rfc:`7914`.
+
+ *password* and *salt* must be bytes-like objects. Applications and
+ libraries should limit *password* to a sensible length (e.g. 1024). *salt*
+ should be about 16 or more bytes from a proper source, e.g. :func:`os.urandom`.
+
+ *n* is the CPU/Memory cost factor, *r* the block size, *p* parallelization
+ factor and *maxmem* limits memory (OpenSSL 1.1.0 defaults to 32 MB).
+ *dklen* is the length of the derived key.
+
+ Availability: OpenSSL 1.1+
+
+ .. versionadded:: 3.6
+
+
+BLAKE2
+------
+
+BLAKE2 takes additional arguments, see :ref:`hashlib-blake2`.
+
.. seealso::
@@ -230,6 +289,8 @@ include a `salt <https://en.wikipedia.org/wiki/Salt_%28cryptography%29>`_.
Module :mod:`base64`
Another way to encode binary hashes for non-binary environments.
+ See :ref:`hashlib-blake2`.
+
http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
The FIPS 180-2 publication on Secure Hash Algorithms.
diff --git a/Doc/library/http.client.rst b/Doc/library/http.client.rst
index e1acf92..2f59ece 100644
--- a/Doc/library/http.client.rst
+++ b/Doc/library/http.client.rst
@@ -69,13 +69,6 @@ The module provides the following classes:
must be a :class:`ssl.SSLContext` instance describing the various SSL
options.
- *key_file* and *cert_file* are deprecated, please use
- :meth:`ssl.SSLContext.load_cert_chain` instead, or let
- :func:`ssl.create_default_context` select the system's trusted CA
- certificates for you. The *check_hostname* parameter is also deprecated; the
- :attr:`ssl.SSLContext.check_hostname` attribute of *context* should be used
- instead.
-
Please read :ref:`ssl-security` for more information on best practices.
.. versionchanged:: 3.2
@@ -95,6 +88,17 @@ The module provides the following classes:
:func:`ssl._create_unverified_context` can be passed to the *context*
parameter.
+ .. deprecated:: 3.6
+
+ *key_file* and *cert_file* are deprecated in favor of *context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
+
+ The *check_hostname* parameter is also deprecated; the
+ :attr:`ssl.SSLContext.check_hostname` attribute of *context* should
+ be used instead.
+
.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None)
@@ -217,39 +221,61 @@ HTTPConnection Objects
:class:`HTTPConnection` instances have the following methods:
-.. method:: HTTPConnection.request(method, url, body=None, headers={})
+.. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \
+ encode_chunked=False)
This will send a request to the server using the HTTP request
method *method* and the selector *url*.
If *body* is specified, the specified data is sent after the headers are
- finished. It may be a string, a :term:`bytes-like object`, an open
- :term:`file object`, or an iterable of :term:`bytes-like object`\s. If
- *body* is a string, it is encoded as ISO-8859-1, the default for HTTP. If
- it is a bytes-like object the bytes are sent as is. If it is a :term:`file
- object`, the contents of the file is sent; this file object should support
- at least the ``read()`` method. If the file object has a ``mode``
- attribute, the data returned by the ``read()`` method will be encoded as
- ISO-8859-1 unless the ``mode`` attribute contains the substring ``b``,
- otherwise the data returned by ``read()`` is sent as is. If *body* is an
- iterable, the elements of the iterable are sent as is until the iterable is
- exhausted.
-
- The *headers* argument should be a mapping of extra HTTP
- headers to send with the request.
-
- If *headers* does not contain a Content-Length item, one is added
- automatically if possible. If *body* is ``None``, the Content-Length header
- is set to ``0`` for methods that expect a body (``PUT``, ``POST``, and
- ``PATCH``). If *body* is a string or bytes object, the Content-Length
- header is set to its length. If *body* is a :term:`file object` and it
- works to call :func:`~os.fstat` on the result of its ``fileno()`` method,
- then the Content-Length header is set to the ``st_size`` reported by the
- ``fstat`` call. Otherwise no Content-Length header is added.
+ finished. It may be a :class:`str`, a :term:`bytes-like object`, an
+ open :term:`file object`, or an iterable of :class:`bytes`. If *body*
+ is a string, it is encoded as ISO-8859-1, the default for HTTP. If it
+ is a bytes-like object, the bytes are sent as is. If it is a :term:`file
+ object`, the contents of the file is sent; this file object should
+ support at least the ``read()`` method. If the file object is an
+ instance of :class:`io.TextIOBase`, the data returned by the ``read()``
+ method will be encoded as ISO-8859-1, otherwise the data returned by
+ ``read()`` is sent as is. If *body* is an iterable, the elements of the
+ iterable are sent as is until the iterable is exhausted.
+
+ The *headers* argument should be a mapping of extra HTTP headers to send
+ with the request.
+
+ If *headers* contains neither Content-Length nor Transfer-Encoding,
+ but there is a request body, one of those
+ header fields will be added automatically. If
+ *body* is ``None``, the Content-Length header is set to ``0`` for
+ methods that expect a body (``PUT``, ``POST``, and ``PATCH``). If
+ *body* is a string or a bytes-like object that is not also a
+ :term:`file <file object>`, the Content-Length header is
+ set to its length. Any other type of *body* (files
+ and iterables in general) will be chunk-encoded, and the
+ Transfer-Encoding header will automatically be set instead of
+ Content-Length.
+
+ The *encode_chunked* argument is only relevant if Transfer-Encoding is
+ specified in *headers*. If *encode_chunked* is ``False``, the
+ HTTPConnection object assumes that all encoding is handled by the
+ calling code. If it is ``True``, the body will be chunk-encoded.
+
+ .. note::
+ Chunked transfer encoding has been added to the HTTP protocol
+ version 1.1. Unless the HTTP server is known to handle HTTP 1.1,
+ the caller must either specify the Content-Length, or must pass a
+ :class:`str` or bytes-like object that is not also a file as the
+ body representation.
.. versionadded:: 3.2
*body* can now be an iterable.
+ .. versionchanged:: 3.6
+ If neither Content-Length nor Transfer-Encoding are set in
+ *headers*, file and iterable *body* objects are now chunk-encoded.
+ The *encode_chunked* argument was added.
+ No attempt is made to determine the Content-Length for file
+ objects.
+
.. method:: HTTPConnection.getresponse()
Should be called after a request is sent to get the response from the server.
@@ -335,13 +361,32 @@ also send your request step by step, by using the four functions below.
an argument.
-.. method:: HTTPConnection.endheaders(message_body=None)
+.. method:: HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)
Send a blank line to the server, signalling the end of the headers. The
optional *message_body* argument can be used to pass a message body
- associated with the request. The message body will be sent in the same
- packet as the message headers if it is string, otherwise it is sent in a
- separate packet.
+ associated with the request.
+
+ If *encode_chunked* is ``True``, the result of each iteration of
+ *message_body* will be chunk-encoded as specified in :rfc:`7230`,
+ Section 3.3.1. How the data is encoded is dependent on the type of
+ *message_body*. If *message_body* implements the :ref:`buffer interface
+ <bufferobjects>` the encoding will result in a single chunk.
+ If *message_body* is a :class:`collections.Iterable`, each iteration
+ of *message_body* will result in a chunk. If *message_body* is a
+ :term:`file object`, each call to ``.read()`` will result in a chunk.
+ The method automatically signals the end of the chunk-encoded data
+ immediately after *message_body*.
+
+ .. note:: Due to the chunked encoding specification, empty chunks
+ yielded by an iterator body will be ignored by the chunk-encoder.
+ This is to avoid premature termination of the read of the request by
+ the target server due to malformed encoding.
+
+ .. versionadded:: 3.6
+ Chunked encoding support. The *encode_chunked* parameter was
+ added.
+
.. method:: HTTPConnection.send(data)
diff --git a/Doc/library/http.server.rst b/Doc/library/http.server.rst
index ae7fb97..fb5c1df 100644
--- a/Doc/library/http.server.rst
+++ b/Doc/library/http.server.rst
@@ -98,8 +98,8 @@ of which this module provides three different variants:
.. attribute:: rfile
- Contains an input stream, positioned at the start of the optional input
- data.
+ An :class:`io.BufferedIOBase` input stream, ready to read from
+ the start of the optional input data.
.. attribute:: wfile
@@ -107,6 +107,9 @@ of which this module provides three different variants:
client. Proper adherence to the HTTP protocol must be used when writing to
this stream.
+ .. versionchanged:: 3.6
+ This is an :class:`io.BufferedIOBase` stream.
+
:class:`BaseHTTPRequestHandler` has the following attributes:
.. attribute:: server_version
@@ -369,10 +372,9 @@ the current directory::
Handler = http.server.SimpleHTTPRequestHandler
- httpd = socketserver.TCPServer(("", PORT), Handler)
-
- print("serving at port", PORT)
- httpd.serve_forever()
+ with socketserver.TCPServer(("", PORT), Handler) as httpd:
+ print("serving at port", PORT)
+ httpd.serve_forever()
.. _http-server-cli:
diff --git a/Doc/library/imaplib.rst b/Doc/library/imaplib.rst
index 771ca43..1632eb7 100644
--- a/Doc/library/imaplib.rst
+++ b/Doc/library/imaplib.rst
@@ -103,6 +103,14 @@ There's also a subclass for secure connections:
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
:data:`ssl.HAS_SNI`).
+ .. deprecated:: 3.6
+
+ *keyfile* and *certfile* are deprecated in favor of *ssl_context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
+
+
The second subclass allows for connections created by a child process:
@@ -500,6 +508,17 @@ An :class:`IMAP4` instance has the following methods:
M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
+ .. note::
+
+ Creating flags containing ']' (for example: "[test]") violates
+ :rfc:`3501` (the IMAP protocol). However, imaplib has historically
+ allowed creation of such tags, and popular IMAP servers, such as Gmail,
+ accept and produce such flags. There are non-Python programs which also
+ create such tags. Although it is an RFC violation and IMAP clients and
+ servers are supposed to be strict, imaplib nonetheless continues to allow
+ such tags to be created for backward compatibility reasons, and as of
+ python 3.6, handles them if they are sent from the server, since this
+ improves real-world compatibility.
.. method:: IMAP4.subscribe(mailbox)
diff --git a/Doc/library/imghdr.rst b/Doc/library/imghdr.rst
index f11f6dc..800e919 100644
--- a/Doc/library/imghdr.rst
+++ b/Doc/library/imghdr.rst
@@ -20,6 +20,9 @@ The :mod:`imghdr` module defines the following function:
string describing the image type. If optional *h* is provided, the *filename*
is ignored and *h* is assumed to contain the byte stream to test.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
The following image types are recognized, as listed below with the return value
from :func:`what`:
diff --git a/Doc/library/imp.rst b/Doc/library/imp.rst
index 9828ba6..ccf5f92 100644
--- a/Doc/library/imp.rst
+++ b/Doc/library/imp.rst
@@ -85,7 +85,9 @@ This module provides an interface to the mechanisms used to implement the
.. deprecated:: 3.3
Use :func:`importlib.util.find_spec` instead unless Python 3.3
compatibility is required, in which case use
- :func:`importlib.find_loader`.
+ :func:`importlib.find_loader`. For example usage of the former case,
+ see the :ref:`importlib-examples` section of the :mod:`importlib`
+ documentation.
.. function:: load_module(name, file, pathname, description)
@@ -112,9 +114,12 @@ This module provides an interface to the mechanisms used to implement the
If previously used in conjunction with :func:`imp.find_module` then
consider using :func:`importlib.import_module`, otherwise use the loader
returned by the replacement you chose for :func:`imp.find_module`. If you
- called :func:`imp.load_module` and related functions directly then use the
- classes in :mod:`importlib.machinery`, e.g.
- ``importlib.machinery.SourceFileLoader(name, path).load_module()``.
+ called :func:`imp.load_module` and related functions directly with file
+ path arguments then use a combination of
+ :func:`importlib.util.spec_from_file_location` and
+ :func:`importlib.util.module_from_spec`. See the :ref:`importlib-examples`
+ section of the :mod:`importlib` documentation for details of the various
+ approaches.
.. function:: new_module(name)
@@ -123,7 +128,7 @@ This module provides an interface to the mechanisms used to implement the
in ``sys.modules``.
.. deprecated:: 3.4
- Use :class:`types.ModuleType` instead.
+ Use :func:`importlib.util.module_from_spec` instead.
.. function:: reload(module)
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index 526c9f3..1fd5698 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -267,7 +267,7 @@ ABC hierarchy::
module and *path* will be the value of :attr:`__path__` from the
parent package. If a spec cannot be found, ``None`` is returned.
When passed in, ``target`` is a module object that the finder may
- use to make a more educated about what spec to return.
+ use to make a more educated guess about what spec to return.
.. versionadded:: 3.4
@@ -317,7 +317,7 @@ ABC hierarchy::
within the :term:`path entry` to which it is assigned. If a spec
cannot be found, ``None`` is returned. When passed in, ``target``
is a module object that the finder may use to make a more educated
- about what spec to return.
+ guess about what spec to return.
.. versionadded:: 3.4
@@ -379,10 +379,14 @@ ABC hierarchy::
An abstract method that executes the module in its own namespace
when a module is imported or reloaded. The module should already
- be initialized when exec_module() is called.
+ be initialized when ``exec_module()`` is called. When this method exists,
+ :meth:`~importlib.abc.Loader.create_module` must be defined.
.. versionadded:: 3.4
+ .. versionchanged:: 3.6
+ :meth:`~importlib.abc.Loader.create_module` must also be defined.
+
.. method:: load_module(fullname)
A legacy method for loading a module. If the module cannot be
@@ -802,6 +806,10 @@ find and load modules.
.. versionadded:: 3.3
+ .. deprecated:: 3.6
+ Use :mod:`site` configuration instead. Future versions of Python may
+ not enable this finder by default.
+
.. class:: PathFinder
@@ -936,6 +944,10 @@ find and load modules.
Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
specifying the name of the module to load is optional.
+ .. deprecated:: 3.6
+
+ Use :meth:`importlib.abc.Loader.exec_module` instead.
+
.. class:: SourcelessFileLoader(fullname, path)
@@ -975,6 +987,10 @@ find and load modules.
Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
specifying the name of the module to load is optional.
+ .. deprecated:: 3.6
+
+ Use :meth:`importlib.abc.Loader.exec_module` instead.
+
.. class:: ExtensionFileLoader(fullname, path)
@@ -1137,6 +1153,9 @@ an :term:`importer`.
The *optimization* parameter was added and the *debug_override* parameter
was deprecated.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: source_from_cache(path)
@@ -1150,6 +1169,9 @@ an :term:`importer`.
.. versionadded:: 3.4
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: decode_source(source_bytes)
Decode the given bytes representing source code and return it as a string
@@ -1192,12 +1214,13 @@ an :term:`importer`.
.. function:: module_from_spec(spec)
- Create a new module based on **spec** and ``spec.loader.create_module()``.
+ Create a new module based on **spec** and
+ :meth:`spec.loader.create_module <importlib.abc.Loader.create_module>`.
- If ``spec.loader.create_module()`` does not return ``None``, then any
- pre-existing attributes will not be reset. Also, no :exc:`AttributeError`
- will be raised if triggered while accessing **spec** or setting an attribute
- on the module.
+ If :meth:`spec.loader.create_module <importlib.abc.Loader.create_module>`
+ does not return ``None``, then any pre-existing attributes will not be reset.
+ Also, no :exc:`AttributeError` will be raised if triggered while accessing
+ **spec** or setting an attribute on the module.
This function is preferred over using :class:`types.ModuleType` to create a
new module as **spec** is used to set as many import-controlled attributes on
@@ -1259,7 +1282,8 @@ an :term:`importer`.
.. decorator:: set_package
- A :term:`decorator` for :meth:`importlib.abc.Loader.load_module` to set the :attr:`__package__` attribute on the returned module. If :attr:`__package__`
+ A :term:`decorator` for :meth:`importlib.abc.Loader.load_module` to set the
+ :attr:`__package__` attribute on the returned module. If :attr:`__package__`
is set and has a value other than ``None`` it will not be changed.
.. deprecated:: 3.4
@@ -1284,6 +1308,9 @@ an :term:`importer`.
.. versionadded:: 3.4
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. class:: LazyLoader(loader)
A class which postpones the execution of the loader of a module until the
@@ -1292,13 +1319,12 @@ an :term:`importer`.
This class **only** works with loaders that define
:meth:`~importlib.abc.Loader.exec_module` as control over what module type
is used for the module is required. For those same reasons, the loader's
- :meth:`~importlib.abc.Loader.create_module` method will be ignored (i.e., the
- loader's method should only return ``None``; this excludes
- :class:`BuiltinImporter` and :class:`ExtensionFileLoader`). Finally,
- modules which substitute the object placed into :attr:`sys.modules` will
- not work as there is no way to properly replace the module references
- throughout the interpreter safely; :exc:`ValueError` is raised if such a
- substitution is detected.
+ :meth:`~importlib.abc.Loader.create_module` method must return ``None`` or a
+ type for which its ``__class__`` attribute can be mutated along with not
+ using :term:`slots <__slots__>`. Finally, modules which substitute the object
+ placed into :attr:`sys.modules` will not work as there is no way to properly
+ replace the module references throughout the interpreter safely;
+ :exc:`ValueError` is raised if such a substitution is detected.
.. note::
For projects where startup time is critical, this class allows for
@@ -1309,6 +1335,11 @@ an :term:`importer`.
.. versionadded:: 3.5
+ .. versionchanged:: 3.6
+ Began calling :meth:`~importlib.abc.Loader.create_module`, removing the
+ compatibility warning for :class:`importlib.machinery.BuiltinImporter` and
+ :class:`importlib.machinery.ExtensionFileLoader`.
+
.. classmethod:: factory(loader)
A static method which returns a callable that creates a lazy loader. This
@@ -1320,3 +1351,139 @@ an :term:`importer`.
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
+
+.. _importlib-examples:
+
+Examples
+--------
+
+Importing programmatically
+''''''''''''''''''''''''''
+
+To programmatically import a module, use :func:`importlib.import_module`.
+::
+
+ import importlib
+
+ itertools = importlib.import_module('itertools')
+
+
+Checking if a module can be imported
+''''''''''''''''''''''''''''''''''''
+
+If you need to find out if a module can be imported without actually doing the
+import, then you should use :func:`importlib.util.find_spec`.
+::
+
+ import importlib.util
+ import sys
+
+ # For illustrative purposes.
+ name = 'itertools'
+
+ spec = importlib.util.find_spec(name)
+ if spec is None:
+ print("can't find the itertools module")
+ else:
+ # If you chose to perform the actual import ...
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ # Adding the module to sys.modules is optional.
+ sys.modules[name] = module
+
+
+Importing a source file directly
+''''''''''''''''''''''''''''''''
+
+To import a Python source file directly, use the following recipe
+(Python 3.4 and newer only)::
+
+ import importlib.util
+ import sys
+
+ # For illustrative purposes.
+ import tokenize
+ file_path = tokenize.__file__
+ module_name = tokenize.__name__
+
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ # Optional; only necessary if you want to be able to import the module
+ # by name later.
+ sys.modules[module_name] = module
+
+
+Setting up an importer
+''''''''''''''''''''''
+
+For deep customizations of import, you typically want to implement an
+:term:`importer`. This means managing both the :term:`finder` and :term:`loader`
+side of things. For finders there are two flavours to choose from depending on
+your needs: a :term:`meta path finder` or a :term:`path entry finder`. The
+former is what you would put on :attr:`sys.meta_path` while the latter is what
+you create using a :term:`path entry hook` on :attr:`sys.path_hooks` which works
+with :attr:`sys.path` entries to potentially create a finder. This example will
+show you how to register your own importers so that import will use them (for
+creating an importer for yourself, read the documentation for the appropriate
+classes defined within this package)::
+
+ import importlib.machinery
+ import sys
+
+ # For illustrative purposes only.
+ SpamMetaPathFinder = importlib.machinery.PathFinder
+ SpamPathEntryFinder = importlib.machinery.FileFinder
+ loader_details = (importlib.machinery.SourceFileLoader,
+ importlib.machinery.SOURCE_SUFFIXES)
+
+ # Setting up a meta path finder.
+ # Make sure to put the finder in the proper location in the list in terms of
+ # priority.
+ sys.meta_path.append(SpamMetaPathFinder)
+
+ # Setting up a path entry finder.
+ # Make sure to put the path hook in the proper location in the list in terms
+ # of priority.
+ sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
+
+
+Approximating :func:`importlib.import_module`
+'''''''''''''''''''''''''''''''''''''''''''''
+
+Import itself is implemented in Python code, making it possible to
+expose most of the import machinery through importlib. The following
+helps illustrate the various APIs that importlib exposes by providing an
+approximate implementation of
+:func:`importlib.import_module` (Python 3.4 and newer for the importlib usage,
+Python 3.6 and newer for other parts of the code).
+::
+
+ import importlib.util
+ import sys
+
+ def import_module(name, package=None):
+ """An approximate implementation of import."""
+ absolute_name = importlib.util.resolve_name(name, package)
+ try:
+ return sys.modules[absolute_name]
+ except KeyError:
+ pass
+
+ path = None
+ if '.' in absolute_name:
+ parent_name, _, child_name = absolute_name.rpartition('.')
+ parent_module = import_module(parent_name)
+ path = parent_module.spec.submodule_search_locations
+ for finder in sys.meta_path:
+ spec = finder.find_spec(absolute_name, path)
+ if spec is not None:
+ break
+ else:
+ raise ImportError(f'No module named {absolute_name!r}')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ sys.modules[absolute_name] = module
+ if path is not None:
+ setattr(parent_module, child_name, module)
+ return module
diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst
index 62a3988..41a784d 100644
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -235,24 +235,6 @@ attributes:
listed in the metaclass' custom :meth:`__dir__`.
-.. function:: getmoduleinfo(path)
-
- Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
- of values that describe how Python will interpret the file identified by
- *path* if it is a module, or ``None`` if it would not be identified as a
- module. In that tuple, *name* is the name of the module without the name of
- any enclosing package, *suffix* is the trailing part of the file name (which
- may not be a dot-delimited extension), *mode* is the :func:`open` mode that
- would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
- the type of the module. *module_type* will have a value which can be
- compared to the constants defined in the :mod:`imp` module; see the
- documentation for that module for more information on module types.
-
- .. deprecated:: 3.3
- You may check the file path's suffix against the supported suffixes
- listed in :mod:`importlib.machinery` to infer the same information.
-
-
.. function:: getmodulename(path)
Return the name of the module named by the file *path*, without including the
@@ -266,8 +248,7 @@ attributes:
still return ``None``.
.. versionchanged:: 3.3
- This function is now based directly on :mod:`importlib` rather than the
- deprecated :func:`getmoduleinfo`.
+ The function is based directly on :mod:`importlib`.
.. function:: ismodule(object)
@@ -337,6 +318,27 @@ attributes:
.. versionadded:: 3.5
+.. function:: isasyncgenfunction(object)
+
+ Return true if the object is an :term:`asynchronous generator` function,
+ for example::
+
+ >>> async def agen():
+ ... yield 1
+ ...
+ >>> inspect.isasyncgenfunction(agen)
+ True
+
+ .. versionadded:: 3.6
+
+
+.. function:: isasyncgen(object)
+
+ Return true if the object is an :term:`asynchronous generator iterator`
+ created by an :term:`asynchronous generator` function.
+
+ .. versionadded:: 3.6
+
.. function:: istraceback(object)
Return true if the object is a traceback.
@@ -646,6 +648,16 @@ function.
The name of the parameter as a string. The name must be a valid
Python identifier.
+ .. impl-detail::
+
+ CPython generates implicit parameter names of the form ``.0`` on the
+ code objects used to implement comprehensions and generator
+ expressions.
+
+ .. versionchanged:: 3.6
+ These parameter names are exposed by this module as names like
+ ``implicit0``.
+
.. attribute:: Parameter.default
The default value for the parameter. If the parameter has no default
@@ -824,47 +836,65 @@ Classes and functions
.. function:: getargspec(func)
- Get the names and default values of a Python function's arguments. A
+ Get the names and default values of a Python function's parameters. A
:term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
- returned. *args* is a list of the argument names. *varargs* and *keywords*
- are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
+ returned. *args* is a list of the parameter names. *varargs* and *keywords*
+ are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a
tuple of default argument values or ``None`` if there are no default
arguments; if this tuple has *n* elements, they correspond to the last
*n* elements listed in *args*.
.. deprecated:: 3.0
- Use :func:`signature` and
+ Use :func:`getfullargspec` for an updated API that is usually a drop-in
+ replacement, but also correctly handles function annotations and
+ keyword-only parameters.
+
+ Alternatively, use :func:`signature` and
:ref:`Signature Object <inspect-signature-object>`, which provide a
- better introspecting API for callables.
+ more structured introspection API for callables.
.. function:: getfullargspec(func)
- Get the names and default values of a Python function's arguments. A
+ Get the names and default values of a Python function's parameters. A
:term:`named tuple` is returned:
``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
annotations)``
- *args* is a list of the argument names. *varargs* and *varkw* are the names
- of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
- of the default values of the last *n* arguments, or ``None`` if there are no
- default arguments. *kwonlyargs* is a list of
- keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
- from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
- names to annotations.
-
- The first four items in the tuple correspond to :func:`getargspec`.
+ *args* is a list of the positional parameter names.
+ *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
+ positional arguments are not accepted.
+ *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
+ keyword arguments are not accepted.
+ *defaults* is an *n*-tuple of default argument values corresponding to the
+ last *n* positional parameters, or ``None`` if there are no such defaults
+ defined.
+ *kwonlyargs* is a list of keyword-only parameter names.
+ *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
+ to the default values used if no argument is supplied.
+ *annotations* is a dictionary mapping parameter names to annotations.
+ The special key ``"return"`` is used to report the function return value
+ annotation (if any).
+
+ Note that :func:`signature` and
+ :ref:`Signature Object <inspect-signature-object>` provide the recommended
+ API for callable introspection, and support additional behaviours (like
+ positional-only arguments) that are sometimes encountered in extension module
+ APIs. This function is retained primarily for use in code that needs to
+ maintain compatibility with the Python 2 ``inspect`` module API.
.. versionchanged:: 3.4
This function is now based on :func:`signature`, but still ignores
``__wrapped__`` attributes and includes the already bound first
parameter in the signature output for bound methods.
- .. deprecated:: 3.5
- Use :func:`signature` and
- :ref:`Signature Object <inspect-signature-object>`, which provide a
- better introspecting API for callables.
+ .. versionchanged:: 3.6
+ This method was previously documented as deprecated in favour of
+ :func:`signature` in Python 3.5, but that decision has been reversed
+ in order to restore a clearly supported standard interface for
+ single-source Python 2/3 code migrating away from the legacy
+ :func:`getargspec` API.
.. function:: getargvalues(frame)
@@ -884,7 +914,7 @@ Classes and functions
.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Format a pretty argument spec from the values returned by
- :func:`getargspec` or :func:`getfullargspec`.
+ :func:`getfullargspec`.
The first seven arguments are (``args``, ``varargs``, ``varkw``,
``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
@@ -1264,20 +1294,29 @@ the following flags:
.. data:: CO_COROUTINE
- The flag is set when the code object is a coroutine function, i.e.
- a coroutine object is returned when the code object is executed. See
- :pep:`492` for more details.
+ The flag is set when the code object is a coroutine function.
+ When the code object is executed it returns a coroutine object.
+ See :pep:`492` for more details.
.. versionadded:: 3.5
.. data:: CO_ITERABLE_COROUTINE
- Used to turn generators into generator-based coroutines. Generator
- objects with this flag can be used in ``await`` expression, and can
- ``yield from`` coroutine objects. See :pep:`492` for more details.
+ The flag is used to transform generators into generator-based
+ coroutines. Generator objects with this flag can be used in
+ ``await`` expression, and can ``yield from`` coroutine objects.
+ See :pep:`492` for more details.
.. versionadded:: 3.5
+.. data:: CO_ASYNC_GENERATOR
+
+ The flag is set when the code object is an asynchronous generator
+ function. When the code object is executed it returns an
+ asynchronous generator object. See :pep:`525` for more details.
+
+ .. versionadded:: 3.6
+
.. note::
The flags are specific to CPython, and may not be defined in other
Python implementations. Furthermore, the flags are an implementation
@@ -1286,7 +1325,6 @@ the following flags:
for any introspection needs.
-
.. _inspect-module-cli:
Command Line Interface
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index dfc1ddc..b0d0a8c 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -591,7 +591,13 @@ loops that truncate the stream.
.. function:: tee(iterable, n=2)
- Return *n* independent iterators from a single iterable. Roughly equivalent to::
+ Return *n* independent iterators from a single iterable.
+
+ The following Python code helps explain what *tee* does (although the actual
+ implementation is more complex and uses only a single underlying
+ :abbr:`FIFO (first-in, first-out)` queue).
+
+ Roughly equivalent to::
def tee(iterable, n=2):
it = iter(iterable)
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
index f487535..76e936f 100644
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -126,7 +126,7 @@ See :ref:`json-commandline` for detailed documentation.
Basic Usage
-----------
-.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
+.. function:: dump(obj, fp, *, skipkeys=False, ensure_ascii=True, \
check_circular=True, allow_nan=True, cls=None, \
indent=None, separators=None, default=None, \
sort_keys=False, **kw)
@@ -187,8 +187,11 @@ Basic Usage
:meth:`default` method to serialize additional types), specify it with the
*cls* kwarg; otherwise :class:`JSONEncoder` is used.
+ .. versionchanged:: 3.6
+ All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
-.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
+
+.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \
check_circular=True, allow_nan=True, cls=None, \
indent=None, separators=None, default=None, \
sort_keys=False, **kw)
@@ -212,7 +215,7 @@ Basic Usage
the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
keys.
-.. function:: load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
+.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
containing a JSON document) to a Python object using this :ref:`conversion
@@ -260,10 +263,14 @@ Basic Usage
If the data being deserialized is not a valid JSON document, a
:exc:`JSONDecodeError` will be raised.
-.. function:: loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
+ .. versionchanged:: 3.6
+ All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
+
+.. function:: loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
- Deserialize *s* (a :class:`str` instance containing a JSON document) to a
- Python object using this :ref:`conversion table <json-to-py-table>`.
+ Deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray`
+ instance containing a JSON document) to a Python object using this
+ :ref:`conversion table <json-to-py-table>`.
The other arguments have the same meaning as in :func:`load`, except
*encoding* which is ignored and deprecated.
@@ -274,7 +281,7 @@ Basic Usage
Encoders and Decoders
---------------------
-.. class:: JSONDecoder(object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
+.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
Simple JSON decoder.
@@ -344,6 +351,9 @@ Encoders and Decoders
If the data being deserialized is not a valid JSON document, a
:exc:`JSONDecodeError` will be raised.
+ .. versionchanged:: 3.6
+ All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
+
.. method:: decode(s)
Return the Python representation of *s* (a :class:`str` instance
@@ -362,7 +372,7 @@ Encoders and Decoders
extraneous data at the end.
-.. class:: JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
+.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Extensible JSON encoder for Python data structures.
@@ -443,6 +453,9 @@ Encoders and Decoders
the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError`
is raised.
+ .. versionchanged:: 3.6
+ All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
+
.. method:: default(o)
diff --git a/Doc/library/logging.handlers.rst b/Doc/library/logging.handlers.rst
index 0c02d3d..5fc32d1 100644
--- a/Doc/library/logging.handlers.rst
+++ b/Doc/library/logging.handlers.rst
@@ -84,6 +84,9 @@ sends logging output to a disk file. It inherits the output functionality from
with that encoding. If *delay* is true, then file opening is deferred until the
first call to :meth:`emit`. By default, the file grows indefinitely.
+ .. versionchanged:: 3.6
+ As well as string values, :class:`~pathlib.Path` objects are also accepted
+ for the *filename* argument.
.. method:: close()
@@ -160,12 +163,23 @@ for this value.
with that encoding. If *delay* is true, then file opening is deferred until the
first call to :meth:`emit`. By default, the file grows indefinitely.
+ .. versionchanged:: 3.6
+ As well as string values, :class:`~pathlib.Path` objects are also accepted
+ for the *filename* argument.
+
+ .. method:: reopenIfNeeded()
+
+ Checks to see if the file has changed. If it has, the existing stream is
+ flushed and closed and the file opened again, typically as a precursor to
+ outputting the record to the file.
+
+ .. versionadded:: 3.6
+
.. method:: emit(record)
- Outputs the record to the file, but first checks to see if the file has
- changed. If it has, the existing stream is flushed and closed and the
- file opened again, before outputting the record to the file.
+ Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to
+ reopen the file if it has changed.
.. _base-rotating-handler:
@@ -268,17 +282,21 @@ module, supports rotation of disk log files.
You can use the *maxBytes* and *backupCount* values to allow the file to
:dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
the file is closed and a new file is silently opened for output. Rollover occurs
- whenever the current log file is nearly *maxBytes* in length; if either of
- *maxBytes* or *backupCount* is zero, rollover never occurs. If *backupCount*
- is non-zero, the system will save old log files by appending the extensions
- '.1', '.2' etc., to the filename. For example, with a *backupCount* of 5 and
- a base file name of :file:`app.log`, you would get :file:`app.log`,
+ whenever the current log file is nearly *maxBytes* in length; but if either of
+ *maxBytes* or *backupCount* is zero, rollover never occurs, so you generally want
+ to set *backupCount* to at least 1, and have a non-zero *maxBytes*.
+ When *backupCount* is non-zero, the system will save old log files by appending
+ the extensions '.1', '.2' etc., to the filename. For example, with a *backupCount*
+ of 5 and a base file name of :file:`app.log`, you would get :file:`app.log`,
:file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being
written to is always :file:`app.log`. When this file is filled, it is closed
and renamed to :file:`app.log.1`, and if files :file:`app.log.1`,
- :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`,
- :file:`app.log.3` etc. respectively.
+ :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`,
+ :file:`app.log.3` etc. respectively.
+ .. versionchanged:: 3.6
+ As well as string values, :class:`~pathlib.Path` objects are also accepted
+ for the *filename* argument.
.. method:: doRollover()
@@ -310,21 +328,24 @@ timed intervals.
You can use the *when* to specify the type of *interval*. The list of possible
values is below. Note that they are not case sensitive.
- +----------------+-----------------------+
- | Value | Type of interval |
- +================+=======================+
- | ``'S'`` | Seconds |
- +----------------+-----------------------+
- | ``'M'`` | Minutes |
- +----------------+-----------------------+
- | ``'H'`` | Hours |
- +----------------+-----------------------+
- | ``'D'`` | Days |
- +----------------+-----------------------+
- | ``'W0'-'W6'`` | Weekday (0=Monday) |
- +----------------+-----------------------+
- | ``'midnight'`` | Roll over at midnight |
- +----------------+-----------------------+
+ +----------------+----------------------------+-------------------------+
+ | Value | Type of interval | If/how *atTime* is used |
+ +================+============================+=========================+
+ | ``'S'`` | Seconds | Ignored |
+ +----------------+----------------------------+-------------------------+
+ | ``'M'`` | Minutes | Ignored |
+ +----------------+----------------------------+-------------------------+
+ | ``'H'`` | Hours | Ignored |
+ +----------------+----------------------------+-------------------------+
+ | ``'D'`` | Days | Ignored |
+ +----------------+----------------------------+-------------------------+
+ | ``'W0'-'W6'`` | Weekday (0=Monday) | Used to compute initial |
+ | | | rollover time |
+ +----------------+----------------------------+-------------------------+
+ | ``'midnight'`` | Roll over at midnight, if | Used to compute initial |
+ | | *atTime* not specified, | rollover time |
+ | | else at time *atTime* | |
+ +----------------+----------------------------+-------------------------+
When using weekday-based rotation, specify 'W0' for Monday, 'W1' for
Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for
@@ -352,16 +373,35 @@ timed intervals.
If *atTime* is not ``None``, it must be a ``datetime.time`` instance which
specifies the time of day when rollover occurs, for the cases where rollover
- is set to happen "at midnight" or "on a particular weekday".
+ is set to happen "at midnight" or "on a particular weekday". Note that in
+ these cases, the *atTime* value is effectively used to compute the *initial*
+ rollover, and subsequent rollovers would be calculated via the normal
+ interval calculation.
+
+ .. note:: Calculation of the initial rollover time is done when the handler
+ is initialised. Calculation of subsequent rollover times is done only
+ when rollover occurs, and rollover occurs only when emitting output. If
+ this is not kept in mind, it might lead to some confusion. For example,
+ if an interval of "every minute" is set, that does not mean you will
+ always see log files with times (in the filename) separated by a minute;
+ if, during application execution, logging output is generated more
+ frequently than once a minute, *then* you can expect to see log files
+ with times separated by a minute. If, on the other hand, logging messages
+ are only output once every five minutes (say), then there will be gaps in
+ the file times corresponding to the minutes where no output (and hence no
+ rollover) occurred.
.. versionchanged:: 3.4
*atTime* parameter was added.
+ .. versionchanged:: 3.6
+ As well as string values, :class:`~pathlib.Path` objects are also accepted
+ for the *filename* argument.
+
.. method:: doRollover()
Does a rollover, as described above.
-
.. method:: emit(record)
Outputs the record to the file, catering for rollover as described above.
@@ -798,12 +838,18 @@ should, then :meth:`flush` is expected to do the flushing.
overridden to implement custom flushing strategies.
-.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
+.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)
Returns a new instance of the :class:`MemoryHandler` class. The instance is
initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
:const:`ERROR` is used. If no *target* is specified, the target will need to be
- set using :meth:`setTarget` before this handler does anything useful.
+ set using :meth:`setTarget` before this handler does anything useful. If
+ *flushOnClose* is specified as ``False``, then the buffer is *not* flushed when
+ the handler is closed. If not specified or specified as ``True``, the previous
+ behaviour of flushing the buffer will occur when the handler is closed.
+
+ .. versionchanged:: 3.6
+ The *flushOnClose* parameter was added.
.. method:: close()
diff --git a/Doc/library/lzma.rst b/Doc/library/lzma.rst
index 61b3ba3..5edb23d 100644
--- a/Doc/library/lzma.rst
+++ b/Doc/library/lzma.rst
@@ -39,8 +39,9 @@ Reading and writing compressed files
object`.
The *filename* argument can be either an actual file name (given as a
- :class:`str` or :class:`bytes` object), in which case the named file is
- opened, or it can be an existing file object to read from or write to.
+ :class:`str`, :class:`bytes` or :term:`path-like object` object), in
+ which case the named file is opened, or it can be an existing file object
+ to read from or write to.
The *mode* argument can be any of ``"r"``, ``"rb"``, ``"w"``, ``"wb"``,
``"x"``, ``"xb"``, ``"a"`` or ``"ab"`` for binary mode, or ``"rt"``,
@@ -64,6 +65,9 @@ Reading and writing compressed files
.. versionchanged:: 3.4
Added support for the ``"x"``, ``"xb"`` and ``"xt"`` modes.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. class:: LZMAFile(filename=None, mode="r", \*, format=None, check=-1, preset=None, filters=None)
@@ -71,9 +75,10 @@ Reading and writing compressed files
An :class:`LZMAFile` can wrap an already-open :term:`file object`, or operate
directly on a named file. The *filename* argument specifies either the file
- object to wrap, or the name of the file to open (as a :class:`str` or
- :class:`bytes` object). When wrapping an existing file object, the wrapped
- file will not be closed when the :class:`LZMAFile` is closed.
+ object to wrap, or the name of the file to open (as a :class:`str`,
+ :class:`bytes` or :term:`path-like object` object). When wrapping an
+ existing file object, the wrapped file will not be closed when the
+ :class:`LZMAFile` is closed.
The *mode* argument can be either ``"r"`` for reading (default), ``"w"`` for
overwriting, ``"x"`` for exclusive creation, or ``"a"`` for appending. These
@@ -118,6 +123,9 @@ Reading and writing compressed files
The :meth:`~io.BufferedIOBase.read` method now accepts an argument of
``None``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
Compressing and decompressing data in memory
--------------------------------------------
diff --git a/Doc/library/math.rst b/Doc/library/math.rst
index 3fdea18..da2b8cc 100644
--- a/Doc/library/math.rst
+++ b/Doc/library/math.rst
@@ -426,6 +426,15 @@ Constants
The mathematical constant e = 2.718281..., to available precision.
+.. data:: tau
+
+ The mathematical constant τ = 6.283185..., to available precision.
+ Tau is a circle constant equal to 2π, the ratio of a circle's circumference to
+ its radius. To learn more about Tau, check out Vi Hart's video `Pi is (still)
+ Wrong <https://www.youtube.com/watch?v=jG7vhMMXagQ>`_, and start celebrating
+ `Tau day <http://tauday.com/>`_ by eating twice as much pie!
+
+ .. versionadded:: 3.6
.. data:: inf
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index 2f2945f..f46bf66 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -264,13 +264,18 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
.. method:: write(bytes)
Write the bytes in *bytes* into memory at the current position of the
- file pointer; the file position is updated to point after the bytes that
- were written. If the mmap was created with :const:`ACCESS_READ`, then
+ file pointer and return the number of bytes written (never less than
+ ``len(bytes)``, since if the write fails, a :exc:`ValueError` will be
+ raised). The file position is updated to point after the bytes that
+ were written. If the mmap was created with :const:`ACCESS_READ`, then
writing to it will raise a :exc:`TypeError` exception.
.. versionchanged:: 3.5
Writable :term:`bytes-like object` is now accepted.
+ .. versionchanged:: 3.6
+ The number of bytes written is now returned.
+
.. method:: write_byte(byte)
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index d45bc20..96d1424 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -650,8 +650,9 @@ primitives like locks.
For passing messages one can use :func:`Pipe` (for a connection between two
processes) or a queue (which allows multiple producers and consumers).
-The :class:`Queue`, :class:`SimpleQueue` and :class:`JoinableQueue` types are multi-producer,
-multi-consumer FIFO queues modelled on the :class:`queue.Queue` class in the
+The :class:`Queue`, :class:`SimpleQueue` and :class:`JoinableQueue` types
+are multi-producer, multi-consumer :abbr:`FIFO (first-in, first-out)`
+queues modelled on the :class:`queue.Queue` class in the
standard library. They differ in that :class:`Queue` lacks the
:meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced
into Python 2.5's :class:`queue.Queue` class.
@@ -889,8 +890,13 @@ Miscellaneous
.. function:: cpu_count()
- Return the number of CPUs in the system. May raise
- :exc:`NotImplementedError`.
+ Return the number of CPUs in the system.
+
+ This number is not equivalent to the number of CPUs the current process can
+ use. The number of usable CPUs can be obtained with
+ ``len(os.sched_getaffinity(0))``
+
+ May raise :exc:`NotImplementedError`.
.. seealso::
:func:`os.cpu_count`
@@ -1679,7 +1685,9 @@ their parent process exits. The manager classes are defined in the
of processes. Objects of this type are returned by
:func:`multiprocessing.Manager`.
- It also supports creation of shared lists and dictionaries.
+ Its methods create and return :ref:`multiprocessing-proxy_objects` for a
+ number of commonly used data types to be synchronized across processes.
+ This notably includes shared lists and dictionaries.
.. method:: Barrier(parties[, action[, timeout]])
@@ -1742,31 +1750,17 @@ their parent process exits. The manager classes are defined in the
dict(mapping)
dict(sequence)
- Create a shared ``dict`` object and return a proxy for it.
+ Create a shared :class:`dict` object and return a proxy for it.
.. method:: list()
list(sequence)
- Create a shared ``list`` object and return a proxy for it.
-
- .. note::
-
- Modifications to mutable values or items in dict and list proxies will not
- be propagated through the manager, because the proxy has no way of knowing
- when its values or items are modified. To modify such an item, you can
- re-assign the modified object to the container proxy::
-
- # create a list proxy and append a mutable object (a dictionary)
- lproxy = manager.list()
- lproxy.append({})
- # now mutate the dictionary
- d = lproxy[0]
- d['a'] = 1
- d['b'] = 2
- # at this point, the changes to d are not yet synced, but by
- # reassigning the dictionary, the proxy is notified of the change
- lproxy[0] = d
+ Create a shared :class:`list` object and return a proxy for it.
+ .. versionchanged:: 3.6
+ Shared objects are capable of being nested. For example, a shared
+ container object such as a shared list can contain other shared objects
+ which will all be managed and synchronized by the :class:`SyncManager`.
.. class:: Namespace
@@ -1878,6 +1872,8 @@ client to access it remotely::
>>> s = m.get_server()
>>> s.serve_forever()
+.. _multiprocessing-proxy_objects:
+
Proxy Objects
~~~~~~~~~~~~~
@@ -1887,8 +1883,7 @@ proxy. Multiple proxy objects may have the same referent.
A proxy object has methods which invoke corresponding methods of its referent
(although not every method of the referent will necessarily be available through
-the proxy). A proxy can usually be used in most of the same ways that its
-referent can:
+the proxy). In this way, a proxy can be used just like its referent can:
.. doctest::
@@ -1909,9 +1904,9 @@ the referent, whereas applying :func:`repr` will return the representation of
the proxy.
An important feature of proxy objects is that they are picklable so they can be
-passed between processes. Note, however, that if a proxy is sent to the
-corresponding manager's process then unpickling it will produce the referent
-itself. This means, for example, that one shared object can contain a second:
+passed between processes. As such, a referent can contain
+:ref:`multiprocessing-proxy_objects`. This permits nesting of these managed
+lists, dicts, and other :ref:`multiprocessing-proxy_objects`:
.. doctest::
@@ -1919,10 +1914,46 @@ itself. This means, for example, that one shared object can contain a second:
>>> b = manager.list()
>>> a.append(b) # referent of a now contains referent of b
>>> print(a, b)
- [[]] []
+ [<ListProxy object, typeid 'list' at ...>] []
>>> b.append('hello')
- >>> print(a, b)
- [['hello']] ['hello']
+ >>> print(a[0], b)
+ ['hello'] ['hello']
+
+Similarly, dict and list proxies may be nested inside one another::
+
+ >>> l_outer = manager.list([ manager.dict() for i in range(2) ])
+ >>> d_first_inner = l_outer[0]
+ >>> d_first_inner['a'] = 1
+ >>> d_first_inner['b'] = 2
+ >>> l_outer[1]['c'] = 3
+ >>> l_outer[1]['z'] = 26
+ >>> print(l_outer[0])
+ {'a': 1, 'b': 2}
+ >>> print(l_outer[1])
+ {'c': 3, 'z': 26}
+
+If standard (non-proxy) :class:`list` or :class:`dict` objects are contained
+in a referent, modifications to those mutable values will not be propagated
+through the manager because the proxy has no way of knowing when the values
+contained within are modified. However, storing a value in a container proxy
+(which triggers a ``__setitem__`` on the proxy object) does propagate through
+the manager and so to effectively modify such an item, one could re-assign the
+modified value to the container proxy::
+
+ # create a list proxy and append a mutable object (a dictionary)
+ lproxy = manager.list()
+ lproxy.append({})
+ # now mutate the dictionary
+ d = lproxy[0]
+ d['a'] = 1
+ d['b'] = 2
+ # at this point, the changes to d are not yet synced, but by
+ # updating the dictionary, the proxy is notified of the change
+ lproxy[0] = d
+
+This approach is perhaps less convenient than employing nested
+:ref:`multiprocessing-proxy_objects` for most use cases but also
+demonstrates a level of control over the synchronization.
.. note::
diff --git a/Doc/library/os.path.rst b/Doc/library/os.path.rst
index bf0dfac..406054e 100644
--- a/Doc/library/os.path.rst
+++ b/Doc/library/os.path.rst
@@ -61,6 +61,9 @@ the :mod:`glob` module.)
platforms, this is equivalent to calling the function :func:`normpath` as
follows: ``normpath(join(os.getcwd(), path))``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: basename(path)
@@ -71,6 +74,9 @@ the :mod:`glob` module.)
``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
empty string (``''``).
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: commonpath(paths)
@@ -83,6 +89,9 @@ the :mod:`glob` module.)
.. versionadded:: 3.5
+ .. versionchanged:: 3.6
+ Accepts a sequence of :term:`path-like objects <path-like object>`.
+
.. function:: commonprefix(list)
@@ -104,12 +113,18 @@ the :mod:`glob` module.)
>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: dirname(path)
Return the directory name of pathname *path*. This is the first element of
the pair returned by passing *path* to the function :func:`split`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: exists(path)
@@ -123,6 +138,9 @@ the :mod:`glob` module.)
*path* can now be an integer: ``True`` is returned if it is an
open file descriptor, ``False`` otherwise.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: lexists(path)
@@ -130,6 +148,9 @@ the :mod:`glob` module.)
broken symbolic links. Equivalent to :func:`exists` on platforms lacking
:func:`os.lstat`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: expanduser(path)
@@ -151,6 +172,9 @@ the :mod:`glob` module.)
If the expansion fails or if the path does not begin with a tilde, the path is
returned unchanged.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: expandvars(path)
@@ -162,6 +186,9 @@ the :mod:`glob` module.)
On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
``${name}``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: getatime(path)
@@ -182,6 +209,9 @@ the :mod:`glob` module.)
If :func:`os.stat_float_times` returns ``True``, the result is a floating point
number.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: getctime(path)
@@ -191,12 +221,18 @@ the :mod:`glob` module.)
the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or
is inaccessible.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: getsize(path)
Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
not exist or is inaccessible.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: isabs(path)
@@ -204,24 +240,36 @@ the :mod:`glob` module.)
begins with a slash, on Windows that it begins with a (back)slash after chopping
off a potential drive letter.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: isfile(path)
Return ``True`` if *path* is an existing regular file. This follows symbolic
links, so both :func:`islink` and :func:`isfile` can be true for the same path.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: isdir(path)
Return ``True`` if *path* is an existing directory. This follows symbolic
links, so both :func:`islink` and :func:`isdir` can be true for the same path.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: islink(path)
Return ``True`` if *path* refers to a directory entry that is a symbolic link.
Always ``False`` if symbolic links are not supported by the Python runtime.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: ismount(path)
@@ -237,6 +285,9 @@ the :mod:`glob` module.)
.. versionadded:: 3.4
Support for detecting non-root mount points on Windows.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: join(path, *paths)
@@ -255,13 +306,20 @@ the :mod:`glob` module.)
``os.path.join("c:", "foo")`` represents a path relative to the current
directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *path* and *paths*.
+
.. function:: normcase(path)
Normalize the case of a pathname. On Unix and Mac OS X, this returns the
path unchanged; on case-insensitive filesystems, it converts the path to
lowercase. On Windows, it also converts forward slashes to backward slashes.
- Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
+ Raise a TypeError if the type of *path* is not ``str`` or ``bytes`` (directly
+ or indirectly through the :class:`os.PathLike` interface).
+
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
.. function:: normpath(path)
@@ -272,12 +330,18 @@ the :mod:`glob` module.)
that contains symbolic links. On Windows, it converts forward slashes to
backward slashes. To normalize case, use :func:`normcase`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: realpath(path)
Return the canonical path of the specified filename, eliminating any symbolic
links encountered in the path (if they are supported by the operating system).
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: relpath(path, start=os.curdir)
@@ -290,6 +354,9 @@ the :mod:`glob` module.)
Availability: Unix, Windows.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: samefile(path1, path2)
@@ -305,6 +372,9 @@ the :mod:`glob` module.)
.. versionchanged:: 3.4
Windows now uses the same implementation as all other platforms.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: sameopenfile(fp1, fp2)
@@ -315,6 +385,9 @@ the :mod:`glob` module.)
.. versionchanged:: 3.2
Added Windows support.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: samestat(stat1, stat2)
@@ -328,6 +401,9 @@ the :mod:`glob` module.)
.. versionchanged:: 3.4
Added Windows support.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: split(path)
@@ -341,6 +417,9 @@ the :mod:`glob` module.)
(but the strings may differ). Also see the functions :func:`dirname` and
:func:`basename`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: splitdrive(path)
@@ -359,6 +438,9 @@ the :mod:`glob` module.)
and share, up to but not including the fourth separator.
e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")``
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: splitext(path)
@@ -367,6 +449,9 @@ the :mod:`glob` module.)
period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
returns ``('.cshrc', '')``.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: splitunc(path)
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index 5a67f93..988cb7c 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -57,7 +57,7 @@ Notes on the availability of these functions:
The name of the operating system dependent module imported. The following
names have currently been registered: ``'posix'``, ``'nt'``,
- ``'ce'``, ``'java'``.
+ ``'java'``.
.. seealso::
:attr:`sys.platform` has a finer granularity. :func:`os.uname` gives
@@ -171,23 +171,60 @@ process and user.
.. function:: fsencode(filename)
- Encode *filename* to the filesystem encoding with ``'surrogateescape'``
- error handler, or ``'strict'`` on Windows; return :class:`bytes` unchanged.
+ Encode :term:`path-like <path-like object>` *filename* to the filesystem
+ encoding with ``'surrogateescape'`` error handler, or ``'strict'`` on
+ Windows; return :class:`bytes` unchanged.
:func:`fsdecode` is the reverse function.
.. versionadded:: 3.2
+ .. versionchanged:: 3.6
+ Support added to accept objects implementing the :class:`os.PathLike`
+ interface.
+
.. function:: fsdecode(filename)
- Decode *filename* from the filesystem encoding with ``'surrogateescape'``
- error handler, or ``'strict'`` on Windows; return :class:`str` unchanged.
+ Decode the :term:`path-like <path-like object>` *filename* from the
+ filesystem encoding with ``'surrogateescape'`` error handler, or ``'strict'``
+ on Windows; return :class:`str` unchanged.
:func:`fsencode` is the reverse function.
.. versionadded:: 3.2
+ .. versionchanged:: 3.6
+ Support added to accept objects implementing the :class:`os.PathLike`
+ interface.
+
+
+.. function:: fspath(path)
+
+ Return the file system representation of the path.
+
+ If :class:`str` or :class:`bytes` is passed in, it is returned unchanged.
+ Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is
+ returned as long as it is a :class:`str` or :class:`bytes` object.
+ In all other cases, :exc:`TypeError` is raised.
+
+ .. versionadded:: 3.6
+
+
+.. class:: PathLike
+
+ An :term:`abstract base class` for objects representing a file system path,
+ e.g. :class:`pathlib.PurePath`.
+
+ .. versionadded:: 3.6
+
+ .. abstractmethod:: __fspath__()
+
+ Return the file system path representation of the object.
+
+ The method should only return a :class:`str` or :class:`bytes` object,
+ with the preference being for :class:`str`.
+
.. function:: getenv(key, default=None)
@@ -896,6 +933,9 @@ as internal buffering of data.
exception, the function now retries the system call instead of raising an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
The following constants are options for the *flags* parameter to the
:func:`~os.open` function. They can be combined using the bitwise OR operator
``|``. Some of them are not available on all platforms. For descriptions of
@@ -1392,6 +1432,9 @@ features:
.. versionchanged:: 3.3
Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. data:: F_OK
R_OK
@@ -1416,6 +1459,9 @@ features:
Added support for specifying *path* as a file descriptor
on some platforms.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: chflags(path, flags, *, follow_symlinks=True)
@@ -1442,6 +1488,9 @@ features:
.. versionadded:: 3.3
The *follow_symlinks* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
@@ -1483,6 +1532,9 @@ features:
Added support for specifying *path* as an open file descriptor,
and the *dir_fd* and *follow_symlinks* arguments.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
@@ -1502,6 +1554,9 @@ features:
Added support for specifying an open file descriptor for *path*,
and the *dir_fd* and *follow_symlinks* arguments.
+ .. versionchanged:: 3.6
+ Supports a :term:`path-like object`.
+
.. function:: chroot(path)
@@ -1509,6 +1564,9 @@ features:
Availability: Unix.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: fchdir(fd)
@@ -1537,6 +1595,9 @@ features:
Availability: Unix.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: lchmod(path, mode)
@@ -1547,6 +1608,8 @@ features:
Availability: Unix.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
.. function:: lchown(path, uid, gid)
@@ -1556,6 +1619,9 @@ features:
Availability: Unix.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
@@ -1573,6 +1639,9 @@ features:
.. versionadded:: 3.3
Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* arguments.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *src* and *dst*.
+
.. function:: listdir(path='.')
@@ -1580,8 +1649,9 @@ features:
*path*. The list is in arbitrary order, and does not include the special
entries ``'.'`` and ``'..'`` even if they are present in the directory.
- *path* may be either of type ``str`` or of type ``bytes``. If *path*
- is of type ``bytes``, the filenames returned will also be of type ``bytes``;
+ *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
+ (directly or indirectly through the :class:`PathLike` interface),
+ the filenames returned will also be of type ``bytes``;
in all other circumstances, they will be of type ``str``.
This function can also support :ref:`specifying a file descriptor
@@ -1602,6 +1672,9 @@ features:
.. versionadded:: 3.3
Added support for specifying an open file descriptor for *path*.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: lstat(path, \*, dir_fd=None)
@@ -1628,6 +1701,9 @@ features:
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *src* and *dst*.
+
.. function:: mkdir(path, mode=0o777, *, dir_fd=None)
@@ -1652,6 +1728,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: makedirs(name, mode=0o777, exist_ok=False)
@@ -1685,6 +1764,9 @@ features:
mode of the existing directory. Since this behavior was impossible to
implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
@@ -1705,6 +1787,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None)
@@ -1724,6 +1809,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: major(device)
@@ -1762,6 +1850,9 @@ features:
Availability: Unix.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. data:: pathconf_names
@@ -1779,9 +1870,10 @@ features:
may be converted to an absolute pathname using
``os.path.join(os.path.dirname(path), result)``.
- If the *path* is a string object, the result will also be a string object,
+ If the *path* is a string object (directly or indirectly through a
+ :class:`PathLike` interface), the result will also be a string object,
and the call may raise a UnicodeDecodeError. If the *path* is a bytes
- object, the result will be a bytes object.
+ object (direct or indirectly), the result will be a bytes object.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
@@ -1794,6 +1886,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: remove(path, *, dir_fd=None)
@@ -1812,6 +1907,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* argument.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: removedirs(name)
@@ -1826,6 +1924,9 @@ features:
they are empty. Raises :exc:`OSError` if the leaf directory could not be
successfully removed.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
@@ -1845,6 +1946,9 @@ features:
.. versionadded:: 3.3
The *src_dir_fd* and *dst_dir_fd* arguments.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *src* and *dst*.
+
.. function:: renames(old, new)
@@ -1858,6 +1962,9 @@ features:
This function can fail with the new directory structure made if you lack
permissions needed to remove the leaf directory or file.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *old* and *new*.
+
.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
@@ -1872,6 +1979,9 @@ features:
.. versionadded:: 3.3
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *src* and *dst*.
+
.. function:: rmdir(path, *, dir_fd=None)
@@ -1885,38 +1995,56 @@ features:
.. versionadded:: 3.3
The *dir_fd* parameter.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: scandir(path='.')
- Return an iterator of :class:`DirEntry` objects corresponding to the entries
- in the directory given by *path*. The entries are yielded in arbitrary
- order, and the special entries ``'.'`` and ``'..'`` are not included.
+ Return an iterator of :class:`os.DirEntry` objects corresponding to the
+ entries in the directory given by *path*. The entries are yielded in
+ arbitrary order, and the special entries ``'.'`` and ``'..'`` are not
+ included.
Using :func:`scandir` instead of :func:`listdir` can significantly
increase the performance of code that also needs file type or file
- attribute information, because :class:`DirEntry` objects expose this
+ attribute information, because :class:`os.DirEntry` objects expose this
information if the operating system provides it when scanning a directory.
- All :class:`DirEntry` methods may perform a system call, but
- :func:`~DirEntry.is_dir` and :func:`~DirEntry.is_file` usually only
- require a system call for symbolic links; :func:`DirEntry.stat`
+ All :class:`os.DirEntry` methods may perform a system call, but
+ :func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only
+ require a system call for symbolic links; :func:`os.DirEntry.stat`
always requires a system call on Unix but only requires one for
symbolic links on Windows.
- On Unix, *path* can be of type :class:`str` or :class:`bytes` (use
- :func:`~os.fsencode` and :func:`~os.fsdecode` to encode and decode
- :class:`bytes` paths). On Windows, *path* must be of type :class:`str`.
- On both systems, the type of the :attr:`~DirEntry.name` and
- :attr:`~DirEntry.path` attributes of each :class:`DirEntry` will be of
- the same type as *path*.
+ *path* may be a :term:`path-like object`. If *path* is of type ``bytes``
+ (directly or indirectly through the :class:`PathLike` interface),
+ the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path`
+ attributes of each :class:`os.DirEntry` will be ``bytes``; in all other
+ circumstances, they will be of type ``str``.
+
+ The :func:`scandir` iterator supports the :term:`context manager` protocol
+ and has the following method:
+
+ .. method:: scandir.close()
+
+ Close the iterator and free acquired resources.
+
+ This is called automatically when the iterator is exhausted or garbage
+ collected, or when an error happens during iterating. However it
+ is advisable to call it explicitly or use the :keyword:`with`
+ statement.
+
+ .. versionadded:: 3.6
The following example shows a simple use of :func:`scandir` to display all
the files (excluding directories) in the given *path* that don't start with
``'.'``. The ``entry.is_file()`` call will generally not make an additional
system call::
- for entry in os.scandir(path):
- if not entry.name.startswith('.') and entry.is_file():
- print(entry.name)
+ with os.scandir(path) as it:
+ for entry in it:
+ if not entry.name.startswith('.') and entry.is_file():
+ print(entry.name)
.. note::
@@ -1932,6 +2060,14 @@ features:
.. versionadded:: 3.5
+ .. versionadded:: 3.6
+ Added support for the :term:`context manager` protocol and the
+ :func:`~scandir.close()` method. If a :func:`scandir` iterator is neither
+ exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
+ in its destructor.
+
+ The function accepts a :term:`path-like object`.
+
.. class:: DirEntry
@@ -1940,27 +2076,30 @@ features:
:func:`scandir` will provide as much of this information as possible without
making additional system calls. When a ``stat()`` or ``lstat()`` system call
- is made, the ``DirEntry`` object will cache the result.
+ is made, the ``os.DirEntry`` object will cache the result.
- ``DirEntry`` instances are not intended to be stored in long-lived data
+ ``os.DirEntry`` instances are not intended to be stored in long-lived data
structures; if you know the file metadata has changed or if a long time has
elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
up-to-date information.
- Because the ``DirEntry`` methods can make operating system calls, they may
+ Because the ``os.DirEntry`` methods can make operating system calls, they may
also raise :exc:`OSError`. If you need very fine-grained
control over errors, you can catch :exc:`OSError` when calling one of the
- ``DirEntry`` methods and handle as appropriate.
+ ``os.DirEntry`` methods and handle as appropriate.
- Attributes and methods on a ``DirEntry`` instance are as follows:
+ To be directly usable as a :term:`path-like object`, ``os.DirEntry``
+ implements the :class:`PathLike` interface.
+
+ Attributes and methods on a ``os.DirEntry`` instance are as follows:
.. attribute:: name
The entry's base filename, relative to the :func:`scandir` *path*
argument.
- The :attr:`name` attribute will be of the same type (``str`` or
- ``bytes``) as the :func:`scandir` *path* argument. Use
+ The :attr:`name` attribute will be ``bytes`` if the :func:`scandir`
+ *path* argument is of type ``bytes`` and ``str`` otherwise. Use
:func:`~os.fsdecode` to decode byte filenames.
.. attribute:: path
@@ -1970,16 +2109,17 @@ features:
argument. The path is only absolute if the :func:`scandir` *path*
argument was absolute.
- The :attr:`path` attribute will be of the same type (``str`` or
- ``bytes``) as the :func:`scandir` *path* argument. Use
+ The :attr:`path` attribute will be ``bytes`` if the :func:`scandir`
+ *path* argument is of type ``bytes`` and ``str`` otherwise. Use
:func:`~os.fsdecode` to decode byte filenames.
.. method:: inode()
Return the inode number of the entry.
- The result is cached on the ``DirEntry`` object. Use ``os.stat(entry.path,
- follow_symlinks=False).st_ino`` to fetch up-to-date information.
+ The result is cached on the ``os.DirEntry`` object. Use
+ ``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date
+ information.
On the first, uncached call, a system call is required on Windows but
not on Unix.
@@ -1994,7 +2134,7 @@ features:
is a directory (without following symlinks); return ``False`` if the
entry is any other kind of file or if it doesn't exist anymore.
- The result is cached on the ``DirEntry`` object, with a separate cache
+ The result is cached on the ``os.DirEntry`` object, with a separate cache
for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
with :func:`stat.S_ISDIR` to fetch up-to-date information.
@@ -2018,8 +2158,8 @@ features:
is a file (without following symlinks); return ``False`` if the entry is
a directory or other non-file entry, or if it doesn't exist anymore.
- The result is cached on the ``DirEntry`` object. Caching, system calls
- made, and exceptions raised are as per :func:`~DirEntry.is_dir`.
+ The result is cached on the ``os.DirEntry`` object. Caching, system calls
+ made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`.
.. method:: is_symlink()
@@ -2027,7 +2167,7 @@ features:
return ``False`` if the entry points to a directory or any kind of file,
or if it doesn't exist anymore.
- The result is cached on the ``DirEntry`` object. Call
+ The result is cached on the ``os.DirEntry`` object. Call
:func:`os.path.islink` to fetch up-to-date information.
On the first, uncached call, no system call is required in most cases.
@@ -2052,23 +2192,29 @@ features:
:class:`stat_result` are always set to zero. Call :func:`os.stat` to
get these attributes.
- The result is cached on the ``DirEntry`` object, with a separate cache
+ The result is cached on the ``os.DirEntry`` object, with a separate cache
for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
fetch up-to-date information.
Note that there is a nice correspondence between several attributes
- and methods of ``DirEntry`` and of :class:`pathlib.Path`. In
- particular, the ``name`` attribute has the same meaning, as do the
- ``is_dir()``, ``is_file()``, ``is_symlink()`` and ``stat()`` methods.
+ and methods of ``os.DirEntry`` and of :class:`pathlib.Path`. In
+ particular, the ``name`` attribute has the same
+ meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``
+ and ``stat()`` methods.
.. versionadded:: 3.5
+ .. versionchanged:: 3.6
+ Added support for the :class:`~os.PathLike` interface. Added support
+ for :class:`bytes` paths on Windows.
+
.. 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
- either a string or as an open file descriptor. Return a :class:`stat_result`
+ either a string -- directly or indirectly through the :class:`PathLike`
+ interface -- or as an open file descriptor. Return a :class:`stat_result`
object.
This function normally follows symlinks; to stat a symlink add the argument
@@ -2098,6 +2244,9 @@ features:
Added the *dir_fd* and *follow_symlinks* arguments, specifying a file
descriptor instead of a path.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. class:: stat_result
@@ -2319,19 +2468,22 @@ features:
This function can support :ref:`specifying a file descriptor <path_fd>`.
+ Availability: Unix.
+
.. versionchanged:: 3.2
The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
+ .. versionadded:: 3.3
+ Added support for specifying an open file descriptor for *path*.
+
.. versionchanged:: 3.4
The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
:const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
:const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
and :const:`ST_RELATIME` constants were added.
- Availability: Unix.
-
- .. versionadded:: 3.3
- Added support for specifying an open file descriptor for *path*.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
.. data:: supports_dir_fd
@@ -2452,6 +2604,9 @@ features:
Added the *dir_fd* argument, and now allow *target_is_directory*
on non-Windows platforms.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *src* and *dst*.
+
.. function:: sync()
@@ -2476,6 +2631,10 @@ features:
.. versionchanged:: 3.5
Added support for Windows
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
+
.. function:: unlink(path, *, dir_fd=None)
Remove (delete) the file *path*. This function is semantically
@@ -2486,6 +2645,9 @@ features:
.. versionadded:: 3.3
The *dir_fd* parameter.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)
@@ -2523,6 +2685,9 @@ features:
Added support for specifying an open file descriptor for *path*,
and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
@@ -2613,6 +2778,9 @@ features:
This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
making it faster by reducing the number of calls to :func:`os.stat`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
@@ -2669,6 +2837,9 @@ features:
.. versionadded:: 3.3
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
Linux extended attributes
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2680,12 +2851,16 @@ These functions are all available on Linux only.
.. function:: getxattr(path, attribute, *, follow_symlinks=True)
Return the value of the extended filesystem attribute *attribute* for
- *path*. *attribute* can be bytes or str. If it is str, it is encoded
- with the filesystem encoding.
+ *path*. *attribute* can be bytes or str (directly or indirectly through the
+ :class:`PathLike` interface). If it is str, it is encoded with the filesystem
+ encoding.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` fpr *path* and *attribute*.
+
.. function:: listxattr(path=None, *, follow_symlinks=True)
@@ -2697,21 +2872,29 @@ These functions are all available on Linux only.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: removexattr(path, attribute, *, follow_symlinks=True)
Removes the extended filesystem attribute *attribute* from *path*.
- *attribute* should be bytes or str. If it is a string, it is encoded
+ *attribute* should be bytes or str (directly or indirectly through the
+ :class:`PathLike` interface). If it is a string, it is encoded
with the filesystem encoding.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *path* and *attribute*.
+
.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
Set the extended filesystem attribute *attribute* on *path* to *value*.
- *attribute* must be a bytes or str with no embedded NULs. If it is a str,
+ *attribute* must be a bytes or str with no embedded NULs (directly or
+ indirectly through the :class:`PathLike` interface). If it is a str,
it is encoded with the filesystem encoding. *flags* may be
:data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
given and the attribute does not exist, ``EEXISTS`` will be raised.
@@ -2726,6 +2909,9 @@ These functions are all available on Linux only.
A bug in Linux kernel versions less than 2.6.39 caused the flags argument
to be ignored on some filesystems.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object` for *path* and *attribute*.
+
.. data:: XATTR_SIZE_MAX
@@ -2827,6 +3013,9 @@ to be ignored.
Added support for specifying an open file descriptor for *path*
for :func:`execve`.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. function:: _exit(n)
Exit the process with status *n*, without calling cleanup handlers, flushing
@@ -3137,6 +3326,9 @@ written in Python, such as a mail server's external command delivery program.
:func:`spawnve` are not thread-safe on Windows; we advise you to use the
:mod:`subprocess` module instead.
+ .. versionchanged:: 3.6
+ Accepts a :term:`path-like object`.
+
.. data:: P_NOWAIT
P_NOWAITO
@@ -3623,6 +3815,11 @@ Miscellaneous System Information
Return the number of CPUs in the system. Returns ``None`` if undetermined.
+ This number is not equivalent to the number of CPUs the current process can
+ use. The number of usable CPUs can be obtained with
+ ``len(os.sched_getaffinity(0))``
+
+
.. versionadded:: 3.4
@@ -3738,35 +3935,89 @@ Higher-level operations on pathnames are defined in the :mod:`os.path` module.
.. versionadded:: 3.3
-.. _os-miscfunc:
-Miscellaneous Functions
------------------------
+Random numbers
+--------------
+
+
+.. function:: getrandom(size, flags=0)
+
+ Get up to *size* random bytes. The function can return less bytes than
+ requested.
+
+ These bytes can be used to seed user-space random number generators or for
+ cryptographic purposes.
+
+ ``getrandom()`` relies on entropy gathered from device drivers and other
+ sources of environmental noise. Unnecessarily reading large quantities of
+ data will have a negative impact on other users of the ``/dev/random`` and
+ ``/dev/urandom`` devices.
+
+ The flags argument is a bit mask that can contain zero or more of the
+ following values ORed together: :py:data:`os.GRND_RANDOM` and
+ :py:data:`GRND_NONBLOCK`.
+
+ See also the `Linux getrandom() manual page
+ <http://man7.org/linux/man-pages/man2/getrandom.2.html>`_.
+
+ Availability: Linux 3.17 and newer.
+ .. versionadded:: 3.6
-.. function:: urandom(n)
+.. function:: urandom(size)
- Return a string of *n* random bytes suitable for cryptographic use.
+ Return a string of *size* random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The
returned data should be unpredictable enough for cryptographic applications,
though its exact quality depends on the OS implementation.
- On Linux, ``getrandom()`` syscall is used if available and the urandom
- entropy pool is initialized (``getrandom()`` does not block).
- On a Unix-like system this will query ``/dev/urandom``. On Windows, it
- will use ``CryptGenRandom()``. If a randomness source is not found,
- :exc:`NotImplementedError` will be raised.
+ On Linux, if the ``getrandom()`` syscall is available, it is used in
+ blocking mode: block until the system urandom entropy pool is initialized
+ (128 bits of entropy are collected by the kernel). See the :pep:`524` for
+ the rationale. On Linux, the :func:`getrandom` function can be used to get
+ random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or
+ to poll until the system urandom entropy pool is initialized.
- For an easy-to-use interface to the random number generator
- provided by your platform, please see :class:`random.SystemRandom`.
+ On a Unix-like system, random bytes are read from the ``/dev/urandom``
+ device. If the ``/dev/urandom`` device is not available or not readable, the
+ :exc:`NotImplementedError` exception is raised.
+
+ On Windows, it will use ``CryptGenRandom()``.
+
+ .. seealso::
+ The :mod:`secrets` module provides higher level functions. For an
+ easy-to-use interface to the random number generator provided by your
+ platform, please see :class:`random.SystemRandom`.
+
+ .. versionchanged:: 3.6.0
+ On Linux, ``getrandom()`` is now used in blocking mode to increase the
+ security.
.. versionchanged:: 3.5.2
- On Linux, if ``getrandom()`` blocks (the urandom entropy pool is not
- initialized yet), fall back on reading ``/dev/urandom``.
+ On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool
+ is not initialized yet), fall back on reading ``/dev/urandom``.
.. versionchanged:: 3.5
On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
when available. On OpenBSD 5.6 and newer, the C ``getentropy()``
function is now used. These functions avoid the usage of an internal file
descriptor.
+
+.. data:: GRND_NONBLOCK
+
+ By default, when reading from ``/dev/random``, :func:`getrandom` blocks if
+ no random bytes are available, and when reading from ``/dev/urandom``, it blocks
+ if the entropy pool has not yet been initialized.
+
+ If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not
+ block in these cases, but instead immediately raises :exc:`BlockingIOError`.
+
+ .. versionadded:: 3.6
+
+.. data:: GRND_RANDOM
+
+ If this bit is set, then random bytes are drawn from the
+ ``/dev/random`` pool instead of the ``/dev/urandom`` pool.
+
+ .. versionadded:: 3.6
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst
index 7b90a1f..34ab3b8 100644
--- a/Doc/library/pathlib.rst
+++ b/Doc/library/pathlib.rst
@@ -35,12 +35,6 @@ Pure paths are useful in some special cases; for example:
accessing the OS. In this case, instantiating one of the pure classes may be
useful since those simply don't have any OS-accessing operations.
-.. note::
- This module has been included in the standard library on a
- :term:`provisional basis <provisional package>`. Backwards incompatible
- changes (up to and including removal of the package) may occur if deemed
- necessary by the core developers.
-
.. seealso::
:pep:`428`: The pathlib module -- object-oriented filesystem paths.
@@ -111,7 +105,8 @@ we also call *flavours*:
PurePosixPath('setup.py')
Each element of *pathsegments* can be either a string representing a
- path segment, or another path object::
+ path segment, an object implementing the :class:`os.PathLike` interface
+ which returns a string, or another path object::
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
@@ -152,6 +147,12 @@ we also call *flavours*:
to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link
to another directory)
+ Pure path objects implement the :class:`os.PathLike` interface, allowing them
+ to be used anywhere the interface is accepted.
+
+ .. versionchanged:: 3.6
+ Added support for the :class:`os.PathLike` interface.
+
.. class:: PurePosixPath(*pathsegments)
A subclass of :class:`PurePath`, this path flavour represents non-Windows
@@ -199,7 +200,7 @@ Paths of a different flavour compare unequal and cannot be ordered::
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- TypeError: unorderable types: PureWindowsPath() < PurePosixPath()
+ TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
Operators
@@ -216,6 +217,14 @@ The slash operator helps create child paths, similarly to :func:`os.path.join`::
>>> '/usr' / q
PurePosixPath('/usr/bin')
+A path object can be used anywhere an object implementing :class:`os.PathLike`
+is accepted::
+
+ >>> import os
+ >>> p = PurePath('/etc')
+ >>> os.fspath(p)
+ '/etc'
+
The string representation of a path is the raw filesystem path itself
(in native form, e.g. with backslashes under Windows), which you can
pass to any function taking a file path as a string::
@@ -910,7 +919,7 @@ call fails (for example because the path doesn't exist):
to an existing file or directory, it will be unconditionally replaced.
-.. method:: Path.resolve()
+.. method:: Path.resolve(strict=False)
Make the path absolute, resolving any symlinks. A new path object is
returned::
@@ -927,10 +936,14 @@ call fails (for example because the path doesn't exist):
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
- If the path doesn't exist, :exc:`FileNotFoundError` is raised. If an
- infinite loop is encountered along the resolution path,
- :exc:`RuntimeError` is raised.
+ If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError`
+ is raised. If *strict* is ``False``, the path is resolved as far as possible
+ and any remainder is appended without checking whether it exists. If an
+ infinite loop is encountered along the resolution path, :exc:`RuntimeError`
+ is raised.
+ .. versionadded:: 3.6
+ The *strict* argument.
.. method:: Path.rglob(pattern)
diff --git a/Doc/library/pdb.rst b/Doc/library/pdb.rst
index ba9e547..7c37bb7 100644
--- a/Doc/library/pdb.rst
+++ b/Doc/library/pdb.rst
@@ -144,7 +144,7 @@ The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
access further features, you have to do this yourself:
.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None, \
- nosigint=False)
+ nosigint=False, readrc=True)
:class:`Pdb` is the debugger class.
@@ -160,6 +160,9 @@ access further features, you have to do this yourself:
This allows you to break into the debugger again by pressing :kbd:`Ctrl-C`. If you
want Pdb not to touch the SIGINT handler, set *nosigint* to true.
+ The *readrc* argument defaults to true and controls whether Pdb will load
+ .pdbrc files from the filesystem.
+
Example call to enable tracing with *skip*::
import pdb; pdb.Pdb(skip=['django.*']).set_trace()
@@ -171,6 +174,9 @@ access further features, you have to do this yourself:
The *nosigint* argument. Previously, a SIGINT handler was never set by
Pdb.
+ .. versionchanged:: 3.6
+ The *readrc* argument.
+
.. method:: run(statement, globals=None, locals=None)
runeval(expression, globals=None, locals=None)
runcall(function, *args, **kwds)
diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst
index 0d64191..6e8430f 100644
--- a/Doc/library/pickle.rst
+++ b/Doc/library/pickle.rst
@@ -492,7 +492,7 @@ methods:
.. method:: object.__getnewargs_ex__()
- In protocols 4 and newer, classes that implements the
+ In protocols 2 and newer, classes that implements the
:meth:`__getnewargs_ex__` method can dictate the values passed to the
:meth:`__new__` method upon unpickling. The method must return a pair
``(args, kwargs)`` where *args* is a tuple of positional arguments
@@ -504,15 +504,22 @@ methods:
class requires keyword-only arguments. Otherwise, it is recommended for
compatibility to implement :meth:`__getnewargs__`.
+ .. versionchanged:: 3.6
+ :meth:`__getnewargs_ex__` is now used in protocols 2 and 3.
+
.. method:: object.__getnewargs__()
- This method serve a similar purpose as :meth:`__getnewargs_ex__` but
- for protocols 2 and newer. It must return a tuple of arguments ``args``
- which will be passed to the :meth:`__new__` method upon unpickling.
+ This method serve a similar purpose as :meth:`__getnewargs_ex__`, but
+ supports only positional arguments. It must return a tuple of arguments
+ ``args`` which will be passed to the :meth:`__new__` method upon unpickling.
+
+ :meth:`__getnewargs__` will not be called if :meth:`__getnewargs_ex__` is
+ defined.
- In protocols 4 and newer, :meth:`__getnewargs__` will not be called if
- :meth:`__getnewargs_ex__` is defined.
+ .. versionchanged:: 3.6
+ Before Python 3.6, :meth:`__getnewargs__` was called instead of
+ :meth:`__getnewargs_ex__` in protocols 2 and 3.
.. method:: object.__getstate__()
diff --git a/Doc/library/pkgutil.rst b/Doc/library/pkgutil.rst
index b9e76f7..fba0ea6 100644
--- a/Doc/library/pkgutil.rst
+++ b/Doc/library/pkgutil.rst
@@ -11,6 +11,11 @@
This module provides utilities for the import system, in particular package
support.
+.. class:: ModuleInfo(module_finder, name, ispkg)
+
+ A namedtuple that holds a brief summary of a module's info.
+
+ .. versionadded:: 3.6
.. function:: extend_path(path, name)
@@ -139,7 +144,7 @@ support.
.. function:: iter_modules(path=None, prefix='')
- Yields ``(module_finder, name, ispkg)`` for all submodules on *path*, or, if
+ Yields :class:`ModuleInfo` for all submodules on *path*, or, if
*path* is ``None``, all top-level modules on ``sys.path``.
*path* should be either ``None`` or a list of paths to look for modules in.
@@ -160,7 +165,7 @@ support.
.. function:: walk_packages(path=None, prefix='', onerror=None)
- Yields ``(module_finder, name, ispkg)`` for all modules recursively on
+ Yields :class:`ModuleInfo` for all modules recursively on
*path*, or, if *path* is ``None``, all accessible modules.
*path* should be either ``None`` or a list of paths to look for modules in.
diff --git a/Doc/library/poplib.rst b/Doc/library/poplib.rst
index ffabc32..d72b660 100644
--- a/Doc/library/poplib.rst
+++ b/Doc/library/poplib.rst
@@ -62,6 +62,13 @@ The :mod:`poplib` module provides two classes:
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
:data:`ssl.HAS_SNI`).
+ .. deprecated:: 3.6
+
+ *keyfile* and *certfile* are deprecated in favor of *context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
+
One exception is defined as an attribute of the :mod:`poplib` module:
diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst
index 924be5a..bd0fc2d 100644
--- a/Doc/library/queue.rst
+++ b/Doc/library/queue.rst
@@ -16,8 +16,9 @@ availability of thread support in Python; see the :mod:`threading`
module.
The module implements three types of queue, which differ only in the order in
-which the entries are retrieved. In a FIFO queue, the first tasks added are
-the first retrieved. In a LIFO queue, the most recently added entry is
+which the entries are retrieved. In a :abbr:`FIFO (first-in, first-out)`
+queue, the first tasks added are the first retrieved. In a
+:abbr:`LIFO (last-in, first-out)` queue, the most recently added entry is
the first retrieved (operating like a stack). With a priority queue,
the entries are kept sorted (using the :mod:`heapq` module) and the
lowest valued entry is retrieved first.
@@ -29,14 +30,16 @@ The :mod:`queue` module defines the following classes and exceptions:
.. class:: Queue(maxsize=0)
- Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
+ Constructor for a :abbr:`FIFO (first-in, first-out)` queue. *maxsize* is
+ an integer that sets the upperbound
limit on the number of items that can be placed in the queue. Insertion will
block once this size has been reached, until queue items are consumed. If
*maxsize* is less than or equal to zero, the queue size is infinite.
.. class:: LifoQueue(maxsize=0)
- Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
+ Constructor for a :abbr:`LIFO (last-in, first-out)` queue. *maxsize* is
+ an integer that sets the upperbound
limit on the number of items that can be placed in the queue. Insertion will
block once this size has been reached, until queue items are consumed. If
*maxsize* is less than or equal to zero, the queue size is infinite.
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 8ae242c..4f25157 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -46,10 +46,24 @@ from sources provided by the operating system.
.. warning::
The pseudo-random generators of this module should not be used for
- security purposes.
+ security purposes. For security or cryptographic uses, see the
+ :mod:`secrets` module.
+.. seealso::
+
+ M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
+ equidistributed uniform pseudorandom number generator", ACM Transactions on
+ Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.
+
+
+ `Complementary-Multiply-with-Carry recipe
+ <https://code.activestate.com/recipes/576707/>`_ for a compatible alternative
+ random number generator with a long period and comparatively simple update
+ operations.
-Bookkeeping functions:
+
+Bookkeeping functions
+---------------------
.. function:: seed(a=None, version=2)
@@ -93,7 +107,8 @@ Bookkeeping functions:
:meth:`randrange` to handle arbitrarily large ranges.
-Functions for integers:
+Functions for integers
+----------------------
.. function:: randrange(stop)
randrange(start, stop[, step])
@@ -116,23 +131,55 @@ Functions for integers:
``randrange(a, b+1)``.
-Functions for sequences:
+Functions for sequences
+-----------------------
.. function:: choice(seq)
Return a random element from the non-empty sequence *seq*. If *seq* is empty,
raises :exc:`IndexError`.
+.. function:: choices(population, weights=None, *, cum_weights=None, k=1)
+
+ Return a *k* sized list of elements chosen from the *population* with replacement.
+ If the *population* is empty, raises :exc:`IndexError`.
+
+ If a *weights* sequence is specified, selections are made according to the
+ relative weights. Alternatively, if a *cum_weights* sequence is given, the
+ selections are made according to the cumulative weights (perhaps computed
+ using :func:`itertools.accumulate`). For example, the relative weights
+ ``[10, 5, 30, 5]`` are equivalent to the cumulative weights
+ ``[10, 15, 45, 50]``. Internally, the relative weights are converted to
+ cumulative weights before making selections, so supplying the cumulative
+ weights saves work.
+
+ If neither *weights* nor *cum_weights* are specified, selections are made
+ with equal probability. If a weights sequence is supplied, it must be
+ the same length as the *population* sequence. It is a :exc:`TypeError`
+ to specify both *weights* and *cum_weights*.
+
+ The *weights* or *cum_weights* can use any numeric type that interoperates
+ with the :class:`float` values returned by :func:`random` (that includes
+ integers, floats, and fractions but excludes decimals).
+
+ .. versionadded:: 3.6
+
.. function:: shuffle(x[, random])
- Shuffle the sequence *x* in place. The optional argument *random* is a
- 0-argument function returning a random float in [0.0, 1.0); by default, this is
- the function :func:`.random`.
+ Shuffle the sequence *x* in place.
+
+ The optional argument *random* is a 0-argument function returning a random
+ float in [0.0, 1.0); by default, this is the function :func:`.random`.
+
+ To shuffle an immutable sequence and return a new shuffled list, use
+ ``sample(x, k=len(x))`` instead.
- Note that for even rather small ``len(x)``, the total number of permutations of
- *x* is larger than the period of most random number generators; this implies
- that most permutations of a long sequence can never be generated.
+ Note that even for small ``len(x)``, the total number of permutations of *x*
+ can quickly grow larger than the period of most random number generators.
+ This implies that most permutations of a long sequence can never be
+ generated. For example, a sequence of length 2080 is the largest that
+ can fit within the period of the Mersenne Twister random number generator.
.. function:: sample(population, k)
@@ -149,13 +196,16 @@ Functions for sequences:
Members of the population need not be :term:`hashable` or unique. If the population
contains repeats, then each occurrence is a possible selection in the sample.
- To choose a sample from a range of integers, use an :func:`range` object as an
+ To choose a sample from a range of integers, use a :func:`range` object as an
argument. This is especially fast and space efficient for sampling from a large
- population: ``sample(range(10000000), 60)``.
+ population: ``sample(range(10000000), k=60)``.
If the sample size is larger than the population size, a :exc:`ValueError`
is raised.
+Real-valued distributions
+-------------------------
+
The following functions generate specific real-valued distributions. Function
parameters are named after the corresponding variables in the distribution's
equation, as used in common mathematical practice; most of these equations can
@@ -250,7 +300,8 @@ be found in any statistics text.
parameter.
-Alternative Generator:
+Alternative Generator
+---------------------
.. class:: SystemRandom([seed])
@@ -262,19 +313,6 @@ Alternative Generator:
:exc:`NotImplementedError` if called.
-.. seealso::
-
- M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
- equidistributed uniform pseudorandom number generator", ACM Transactions on
- Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.
-
-
- `Complementary-Multiply-with-Carry recipe
- <https://code.activestate.com/recipes/576707/>`_ for a compatible alternative
- random number generator with a long period and comparatively simple update
- operations.
-
-
Notes on Reproducibility
------------------------
@@ -296,53 +334,146 @@ change across Python versions, but two aspects are guaranteed not to change:
Examples and Recipes
--------------------
-Basic usage::
+Basic examples::
- >>> random.random() # Random float x, 0.0 <= x < 1.0
+ >>> random() # Random float: 0.0 <= x < 1.0
0.37444887175646646
- >>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0
- 1.1800146073117523
+ >>> uniform(2.5, 10.0) # Random float: 2.5 <= x < 10.0
+ 3.1800146073117523
+
+ >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
+ 5.148957571865031
- >>> random.randrange(10) # Integer from 0 to 9
+ >>> randrange(10) # Integer from 0 to 9 inclusive
7
- >>> random.randrange(0, 101, 2) # Even integer from 0 to 100
+ >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
26
- >>> random.choice('abcdefghij') # Single random element
- 'c'
-
- >>> items = [1, 2, 3, 4, 5, 6, 7]
- >>> random.shuffle(items)
- >>> items
- [7, 3, 2, 5, 6, 4, 1]
-
- >>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement
- [4, 1, 5]
-
-A common task is to make a :func:`random.choice` with weighted probabilities.
+ >>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
+ 'draw'
+
+ >>> deck = 'ace two three four'.split()
+ >>> shuffle(deck) # Shuffle a list
+ >>> deck
+ ['four', 'two', 'ace', 'three']
+
+ >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
+ [40, 10, 50, 30]
+
+Simulations::
+
+ >>> # Six roulette wheel spins (weighted sampling with replacement)
+ >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
+ ['red', 'green', 'black', 'black', 'red', 'black']
+
+ >>> # Deal 20 cards without replacement from a deck of 52 playing cards
+ >>> # and determine the proportion of cards with a ten-value
+ >>> # (a ten, jack, queen, or king).
+ >>> deck = collections.Counter(tens=16, low_cards=36)
+ >>> seen = sample(list(deck.elements()), k=20)
+ >>> seen.count('tens') / 20
+ 0.15
+
+ >>> # Estimate the probability of getting 5 or more heads from 7 spins
+ >>> # of a biased coin that settles on heads 60% of the time.
+ >>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
+ >>> sum(trial() for i in range(10000)) / 10000
+ 0.4169
+
+ >>> # Probability of the median of 5 samples being in middle two quartiles
+ >>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2] < 7500
+ >>> sum(trial() for i in range(10000)) / 10000
+ 0.7958
+
+Example of `statistical bootstrapping
+<https://en.wikipedia.org/wiki/Bootstrapping_(statistics)>`_ using resampling
+with replacement to estimate a confidence interval for the mean of a sample of
+size five::
+
+ # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
+ from statistics import mean
+ from random import choices
+
+ data = 1, 2, 4, 4, 10
+ means = sorted(mean(choices(data, k=5)) for i in range(20))
+ print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
+ f'interval from {means[1]:.1f} to {means[-2]:.1f}')
+
+Example of a `resampling permutation test
+<https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests>`_
+to determine the statistical significance or `p-value
+<https://en.wikipedia.org/wiki/P-value>`_ of an observed difference
+between the effects of a drug versus a placebo::
+
+ # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
+ from statistics import mean
+ from random import shuffle
+
+ drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
+ placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
+ observed_diff = mean(drug) - mean(placebo)
+
+ n = 10000
+ count = 0
+ combined = drug + placebo
+ for i in range(n):
+ shuffle(combined)
+ new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
+ count += (new_diff >= observed_diff)
+
+ print(f'{n} label reshufflings produced only {count} instances with a difference')
+ print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
+ print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
+ print(f'hypothesis that there is no difference between the drug and the placebo.')
+
+Simulation of arrival times and service deliveries in a single server queue::
+
+ from random import expovariate, gauss
+ from statistics import mean, median, stdev
+
+ average_arrival_interval = 5.6
+ average_service_time = 5.0
+ stdev_service_time = 0.5
+
+ num_waiting = 0
+ arrivals = []
+ starts = []
+ arrival = service_end = 0.0
+ for i in range(20000):
+ if arrival <= service_end:
+ num_waiting += 1
+ arrival += expovariate(1.0 / average_arrival_interval)
+ arrivals.append(arrival)
+ else:
+ num_waiting -= 1
+ service_start = service_end if num_waiting else arrival
+ service_time = gauss(average_service_time, stdev_service_time)
+ service_end = service_start + service_time
+ starts.append(service_start)
+
+ waits = [start - arrival for arrival, start in zip(arrivals, starts)]
+ print(f'Mean wait: {mean(waits):.1f}. Stdev wait: {stdev(waits):.1f}.')
+ print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.')
-If the weights are small integer ratios, a simple technique is to build a sample
-population with repeats::
-
- >>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
- >>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
- >>> population
- ['Red', 'Red', 'Red', 'Blue', 'Blue', 'Yellow', 'Green', 'Green', 'Green', 'Green']
-
- >>> random.choice(population)
- 'Green'
-
-A more general approach is to arrange the weights in a cumulative distribution
-with :func:`itertools.accumulate`, and then locate the random value with
-:func:`bisect.bisect`::
-
- >>> choices, weights = zip(*weighted_choices)
- >>> cumdist = list(itertools.accumulate(weights))
- >>> cumdist # [3, 3+2, 3+2+1, 3+2+1+4]
- [3, 5, 6, 10]
+.. seealso::
- >>> x = random.random() * cumdist[-1]
- >>> choices[bisect.bisect(cumdist, x)]
- 'Blue'
+ `Statistics for Hackers <https://www.youtube.com/watch?v=Iq9DzN6mvYA>`_
+ a video tutorial by
+ `Jake Vanderplas <https://us.pycon.org/2016/speaker/profile/295/>`_
+ on statistical analysis using just a few fundamental concepts
+ including simulation, sampling, shuffling, and cross-validation.
+
+ `Economics Simulation
+ <http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb>`_
+ a simulation of a marketplace by
+ `Peter Norvig <http://norvig.com/bio.html>`_ that shows effective
+ use of many of the tools and distributions provided by this module
+ (gauss, uniform, sample, betavariate, choice, triangular, and randrange).
+
+ `A Concrete Introduction to Probability (using Python)
+ <http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb>`_
+ a tutorial by `Peter Norvig <http://norvig.com/bio.html>`_ covering
+ the basics of probability theory, how to write simulations, and
+ how to perform data analysis using Python.
diff --git a/Doc/library/re.rst b/Doc/library/re.rst
index 1ca621e..7ef4cbe 100644
--- a/Doc/library/re.rst
+++ b/Doc/library/re.rst
@@ -230,12 +230,8 @@ The special characters are:
flags are described in :ref:`contents-of-module-re`.) This
is useful if you wish to include the flags as part of the regular
expression, instead of passing a *flag* argument to the
- :func:`re.compile` function.
-
- Note that the ``(?x)`` flag changes how the expression is parsed. It should be
- used first in the expression string, or after one or more whitespace characters.
- If there are non-whitespace characters before the flag, the results are
- undefined.
+ :func:`re.compile` function. Flags should be used first in the
+ expression string.
``(?:...)``
A non-capturing version of regular parentheses. Matches whatever regular
@@ -243,6 +239,16 @@ The special characters are:
*cannot* be retrieved after performing a match or referenced later in the
pattern.
+``(?imsx-imsx:...)``
+ (Zero or more letters from the set ``'i'``, ``'m'``, ``'s'``, ``'x'``,
+ optionally followed by ``'-'`` followed by one or more letters from the
+ same set.) The letters set or removes the corresponding flags:
+ :const:`re.I` (ignore case), :const:`re.M` (multi-line), :const:`re.S`
+ (dot matches all), and :const:`re.X` (verbose), for the part of the
+ expression. (The flags are described in :ref:`contents-of-module-re`.)
+
+ .. versionadded:: 3.6
+
``(?P<name>...)``
Similar to regular parentheses, but the substring matched by the group is
accessible via the symbolic group name *name*. Group names must be valid
@@ -327,8 +333,9 @@ The special characters are:
The special sequences consist of ``'\'`` and a character from the list below.
-If the ordinary character is not on the list, then the resulting RE will match
-the second character. For example, ``\$`` matches the character ``'$'``.
+If the ordinary character is not an ASCII digit or an ASCII letter, then the
+resulting RE will match the second character. For example, ``\$`` matches the
+character ``'$'``.
``\number``
Matches the contents of the group of the same number. Groups are numbered
@@ -448,9 +455,8 @@ three digits in length.
.. versionchanged:: 3.3
The ``'\u'`` and ``'\U'`` escape sequences have been added.
-.. deprecated-removed:: 3.5 3.6
- Unknown escapes consisting of ``'\'`` and ASCII letter now raise a
- deprecation warning and will be forbidden in Python 3.6.
+.. versionchanged:: 3.6
+ Unknown escapes consisting of ``'\'`` and an ASCII letter now are errors.
.. seealso::
@@ -472,6 +478,9 @@ functions are simplified versions of the full featured methods for compiled
regular expressions. Most non-trivial applications always use the compiled
form.
+.. versionchanged:: 3.6
+ Flag constants are now instances of :class:`RegexFlag`, which is a subclass of
+ :class:`enum.IntFlag`.
.. function:: compile(pattern, flags=0)
@@ -538,11 +547,11 @@ form.
current locale. The use of this flag is discouraged as the locale mechanism
is very unreliable, and it only handles one "culture" at a time anyway;
you should use Unicode matching instead, which is the default in Python 3
- for Unicode (str) patterns. This flag makes sense only with bytes patterns.
+ for Unicode (str) patterns. This flag can be used only with bytes patterns.
- .. deprecated-removed:: 3.5 3.6
- Deprecated the use of :const:`re.LOCALE` with string patterns or
- :const:`re.ASCII`.
+ .. versionchanged:: 3.6
+ :const:`re.LOCALE` can be used only with bytes patterns and is
+ not compatible with :const:`re.ASCII`.
.. data:: M
@@ -748,9 +757,13 @@ form.
.. versionchanged:: 3.5
Unmatched groups are replaced with an empty string.
- .. deprecated-removed:: 3.5 3.6
- Unknown escapes consist of ``'\'`` and ASCII letter now raise a
- deprecation warning and will be forbidden in Python 3.6.
+ .. versionchanged:: 3.6
+ Unknown escapes in *pattern* consisting of ``'\'`` and an ASCII letter
+ now are errors.
+
+ .. deprecated-removed:: 3.5 3.7
+ Unknown escapes in *repl* consisting of ``'\'`` and an ASCII letter now raise
+ a deprecation warning and will be forbidden in Python 3.7.
.. function:: subn(pattern, repl, string, count=0, flags=0)
@@ -1016,6 +1029,22 @@ Match objects support the following methods and attributes:
'c3'
+.. method:: match.__getitem__(g)
+
+ This is identical to ``m.group(g)``. This allows easier access to
+ an individual group from a match:
+
+ >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
+ >>> m[0] # The entire match
+ 'Isaac Newton'
+ >>> m[1] # The first parenthesized subgroup.
+ 'Isaac'
+ >>> m[2] # The second parenthesized subgroup.
+ 'Newton'
+
+ .. versionadded:: 3.6
+
+
.. method:: match.groups(default=None)
Return a tuple containing all the subgroups of the match, from 1 up to however
diff --git a/Doc/library/readline.rst b/Doc/library/readline.rst
index 4d3c099..54c54b4 100644
--- a/Doc/library/readline.rst
+++ b/Doc/library/readline.rst
@@ -167,6 +167,20 @@ The following functions operate on a global history list:
This calls :c:func:`add_history` in the underlying library.
+.. function:: set_auto_history(enabled)
+
+ Enable or disable automatic calls to :c:func:`add_history` when reading
+ input via readline. The *enabled* argument should be a Boolean value
+ that when true, enables auto history, and that when false, disables
+ auto history.
+
+ .. versionadded:: 3.6
+
+ .. impl-detail::
+ Auto history is enabled by default, and changes to this do not persist
+ across multiple sessions.
+
+
Startup hooks
-------------
diff --git a/Doc/library/secrets.rst b/Doc/library/secrets.rst
new file mode 100644
index 0000000..9bf848f
--- /dev/null
+++ b/Doc/library/secrets.rst
@@ -0,0 +1,198 @@
+:mod:`secrets` --- Generate secure random numbers for managing secrets
+======================================================================
+
+.. module:: secrets
+ :synopsis: Generate secure random numbers for managing secrets.
+
+.. moduleauthor:: Steven D'Aprano <steve+python@pearwood.info>
+.. sectionauthor:: Steven D'Aprano <steve+python@pearwood.info>
+.. versionadded:: 3.6
+
+.. testsetup::
+
+ from secrets import *
+ __name__ = '<doctest>'
+
+**Source code:** :source:`Lib/secrets.py`
+
+-------------
+
+The :mod:`secrets` module is used for generating cryptographically strong
+random numbers suitable for managing data such as passwords, account
+authentication, security tokens, and related secrets.
+
+In particularly, :mod:`secrets` should be used in preference to the
+default pseudo-random number generator in the :mod:`random` module, which
+is designed for modelling and simulation, not security or cryptography.
+
+.. seealso::
+
+ :pep:`506`
+
+
+Random numbers
+--------------
+
+The :mod:`secrets` module provides access to the most secure source of
+randomness that your operating system provides.
+
+.. class:: SystemRandom
+
+ A class for generating random numbers using the highest-quality
+ sources provided by the operating system. See
+ :class:`random.SystemRandom` for additional details.
+
+.. function:: choice(sequence)
+
+ Return a randomly-chosen element from a non-empty sequence.
+
+.. function:: randbelow(n)
+
+ Return a random int in the range [0, *n*).
+
+.. function:: randbits(k)
+
+ Return an int with *k* random bits.
+
+
+Generating tokens
+-----------------
+
+The :mod:`secrets` module provides functions for generating secure
+tokens, suitable for applications such as password resets,
+hard-to-guess URLs, and similar.
+
+.. function:: token_bytes([nbytes=None])
+
+ Return a random byte string containing *nbytes* number of bytes.
+ If *nbytes* is ``None`` or not supplied, a reasonable default is
+ used.
+
+ .. doctest::
+
+ >>> token_bytes(16) #doctest:+SKIP
+ b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
+
+
+.. function:: token_hex([nbytes=None])
+
+ Return a random text string, in hexadecimal. The string has *nbytes*
+ random bytes, each byte converted to two hex digits. If *nbytes* is
+ ``None`` or not supplied, a reasonable default is used.
+
+ .. doctest::
+
+ >>> token_hex(16) #doctest:+SKIP
+ 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
+
+.. function:: token_urlsafe([nbytes=None])
+
+ Return a random URL-safe text string, containing *nbytes* random
+ bytes. The text is Base64 encoded, so on average each byte results
+ in approximately 1.3 characters. If *nbytes* is ``None`` or not
+ supplied, a reasonable default is used.
+
+ .. doctest::
+
+ >>> token_urlsafe(16) #doctest:+SKIP
+ 'Drmhze6EPcv0fN_81Bj-nA'
+
+
+How many bytes should tokens use?
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+To be secure against
+`brute-force attacks <https://en.wikipedia.org/wiki/Brute-force_attack>`_,
+tokens need to have sufficient randomness. Unfortunately, what is
+considered sufficient will necessarily increase as computers get more
+powerful and able to make more guesses in a shorter period. As of 2015,
+it is believed that 32 bytes (256 bits) of randomness is sufficient for
+the typical use-case expected for the :mod:`secrets` module.
+
+For those who want to manage their own token length, you can explicitly
+specify how much randomness is used for tokens by giving an :class:`int`
+argument to the various ``token_*`` functions. That argument is taken
+as the number of bytes of randomness to use.
+
+Otherwise, if no argument is provided, or if the argument is ``None``,
+the ``token_*`` functions will use a reasonable default instead.
+
+.. note::
+
+ That default is subject to change at any time, including during
+ maintenance releases.
+
+
+Other functions
+---------------
+
+.. function:: compare_digest(a, b)
+
+ Return ``True`` if strings *a* and *b* are equal, otherwise ``False``,
+ in such a way as to reduce the risk of
+ `timing attacks <http://codahale.com/a-lesson-in-timing-attacks/>`_.
+ See :func:`hmac.compare_digest` for additional details.
+
+
+Recipes and best practices
+--------------------------
+
+This section shows recipes and best practices for using :mod:`secrets`
+to manage a basic level of security.
+
+Generate an eight-character alphanumeric password:
+
+.. testcode::
+
+ import string
+ alphabet = string.ascii_letters + string.digits
+ password = ''.join(choice(alphabet) for i in range(8))
+
+
+.. note::
+
+ Applications should not
+ `store passwords in a recoverable format <http://cwe.mitre.org/data/definitions/257.html>`_,
+ whether plain text or encrypted. They should be salted and hashed
+ using a cryptographically-strong one-way (irreversible) hash function.
+
+
+Generate a ten-character alphanumeric password with at least one
+lowercase character, at least one uppercase character, and at least
+three digits:
+
+.. testcode::
+
+ import string
+ alphabet = string.ascii_letters + string.digits
+ while True:
+ password = ''.join(choice(alphabet) for i in range(10))
+ if (any(c.islower() for c in password)
+ and any(c.isupper() for c in password)
+ and sum(c.isdigit() for c in password) >= 3):
+ break
+
+
+Generate an `XKCD-style passphrase <http://xkcd.com/936/>`_:
+
+.. testcode::
+
+ # On standard Linux systems, use a convenient dictionary file.
+ # Other platforms may need to provide their own word-list.
+ with open('/usr/share/dict/words') as f:
+ words = [word.strip() for word in f]
+ password = ' '.join(choice(words) for i in range(4))
+
+
+Generate a hard-to-guess temporary URL containing a security token
+suitable for password recovery applications:
+
+.. testcode::
+
+ url = 'https://mydomain.com/reset=' + token_urlsafe()
+
+
+
+..
+ # This modeline must appear within the last ten lines of the file.
+ kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;
diff --git a/Doc/library/select.rst b/Doc/library/select.rst
index a81386a..f97118e 100644
--- a/Doc/library/select.rst
+++ b/Doc/library/select.rst
@@ -268,35 +268,43 @@ Edge and Level Trigger Polling (epoll) Objects
*eventmask*
- +-----------------------+-----------------------------------------------+
- | Constant | Meaning |
- +=======================+===============================================+
- | :const:`EPOLLIN` | Available for read |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLOUT` | Available for write |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLPRI` | Urgent data for read |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLERR` | Error condition happened on the assoc. fd |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLHUP` | Hang up happened on the assoc. fd |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLET` | Set Edge Trigger behavior, the default is |
- | | Level Trigger behavior |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is |
- | | pulled out, the fd is internally disabled |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLRDNORM` | Equivalent to :const:`EPOLLIN` |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLRDBAND` | Priority data band can be read. |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLWRNORM` | Equivalent to :const:`EPOLLOUT` |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLWRBAND` | Priority data may be written. |
- +-----------------------+-----------------------------------------------+
- | :const:`EPOLLMSG` | Ignored. |
- +-----------------------+-----------------------------------------------+
+ +-------------------------+-----------------------------------------------+
+ | Constant | Meaning |
+ +=========================+===============================================+
+ | :const:`EPOLLIN` | Available for read |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLOUT` | Available for write |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLPRI` | Urgent data for read |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLERR` | Error condition happened on the assoc. fd |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLHUP` | Hang up happened on the assoc. fd |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLET` | Set Edge Trigger behavior, the default is |
+ | | Level Trigger behavior |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is |
+ | | pulled out, the fd is internally disabled |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLEXCLUSIVE` | Wake only one epoll object when the |
+ | | associated fd has an event. The default (if |
+ | | this flag is not set) is to wake all epoll |
+ | | objects polling on on a fd. |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLRDHUP` | Stream socket peer closed connection or shut |
+ | | down writing half of connection. |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLRDNORM` | Equivalent to :const:`EPOLLIN` |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLRDBAND` | Priority data band can be read. |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLWRNORM` | Equivalent to :const:`EPOLLOUT` |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLWRBAND` | Priority data may be written. |
+ +-------------------------+-----------------------------------------------+
+ | :const:`EPOLLMSG` | Ignored. |
+ +-------------------------+-----------------------------------------------+
.. method:: epoll.close()
@@ -385,6 +393,9 @@ linearly scanned again. :c:func:`select` is O(highest file descriptor), while
+-------------------+------------------------------------------+
| :const:`POLLHUP` | Hung up |
+-------------------+------------------------------------------+
+ | :const:`POLLRDHUP`| Stream socket peer closed connection, or |
+ | | shut down writing half of connection |
+ +-------------------+------------------------------------------+
| :const:`POLLNVAL` | Invalid request: descriptor not open |
+-------------------+------------------------------------------+
diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst
index e81f982..1a89bf6 100644
--- a/Doc/library/shlex.rst
+++ b/Doc/library/shlex.rst
@@ -73,11 +73,11 @@ The :mod:`shlex` module defines the following functions:
The :mod:`shlex` module defines the following class:
-.. class:: shlex(instream=None, infile=None, posix=False)
+.. class:: shlex(instream=None, infile=None, posix=False, punctuation_chars=False)
A :class:`~shlex.shlex` instance or subclass instance is a lexical analyzer
object. The initialization argument, if present, specifies where to read
- characters from. It must be a file-/stream-like object with
+ characters from. It must be a file-/stream-like object with
:meth:`~io.TextIOBase.read` and :meth:`~io.TextIOBase.readline` methods, or
a string. If no argument is given, input will be taken from ``sys.stdin``.
The second optional argument is a filename string, which sets the initial
@@ -87,8 +87,19 @@ The :mod:`shlex` module defines the following class:
when *posix* is not true (default), the :class:`~shlex.shlex` instance will
operate in compatibility mode. When operating in POSIX mode,
:class:`~shlex.shlex` will try to be as close as possible to the POSIX shell
- parsing rules.
-
+ parsing rules. The *punctuation_chars* argument provides a way to make the
+ behaviour even closer to how real shells parse. This can take a number of
+ values: the default value, ``False``, preserves the behaviour seen under
+ Python 3.5 and earlier. If set to ``True``, then parsing of the characters
+ ``();<>|&`` is changed: any run of these characters (considered punctuation
+ characters) is returned as a single token. If set to a non-empty string of
+ characters, those characters will be used as the punctuation characters. Any
+ characters in the :attr:`wordchars` attribute that appear in
+ *punctuation_chars* will be removed from :attr:`wordchars`. See
+ :ref:`improved-shell-compatibility` for more information.
+
+ .. versionchanged:: 3.6
+ The *punctuation_chars* parameter was added.
.. seealso::
@@ -191,7 +202,13 @@ variables which either control lexical analysis or can be used for debugging:
.. attribute:: shlex.wordchars
The string of characters that will accumulate into multi-character tokens. By
- default, includes all ASCII alphanumerics and underscore.
+ default, includes all ASCII alphanumerics and underscore. In POSIX mode, the
+ accented characters in the Latin-1 set are also included. If
+ :attr:`punctuation_chars` is not empty, the characters ``~-./*?=``, which can
+ appear in filename specifications and command line parameters, will also be
+ included in this attribute, and any characters which appear in
+ ``punctuation_chars`` will be removed from ``wordchars`` if they are present
+ there.
.. attribute:: shlex.whitespace
@@ -222,9 +239,13 @@ variables which either control lexical analysis or can be used for debugging:
.. attribute:: shlex.whitespace_split
- If ``True``, tokens will only be split in whitespaces. This is useful, for
+ If ``True``, tokens will only be split in whitespaces. This is useful, for
example, for parsing command lines with :class:`~shlex.shlex`, getting
- tokens in a similar way to shell arguments.
+ tokens in a similar way to shell arguments. If this attribute is ``True``,
+ :attr:`punctuation_chars` will have no effect, and splitting will happen
+ only on whitespaces. When using :attr:`punctuation_chars`, which is
+ intended to provide parsing closer to that implemented by shells, it is
+ advisable to leave ``whitespace_split`` as ``False`` (the default value).
.. attribute:: shlex.infile
@@ -245,10 +266,9 @@ variables which either control lexical analysis or can be used for debugging:
This attribute is ``None`` by default. If you assign a string to it, that
string will be recognized as a lexical-level inclusion request similar to the
``source`` keyword in various shells. That is, the immediately following token
- will be opened as a filename and input will
- be taken from that stream until EOF, at which
- point the :meth:`~io.IOBase.close` method of that stream will be called and
- the input source will again become the original input stream. Source
+ will be opened as a filename and input will be taken from that stream until
+ EOF, at which point the :meth:`~io.IOBase.close` method of that stream will be
+ called and the input source will again become the original input stream. Source
requests may be stacked any number of levels deep.
@@ -275,6 +295,16 @@ variables which either control lexical analysis or can be used for debugging:
(``''``), in non-POSIX mode, and to ``None`` in POSIX mode.
+.. attribute:: shlex.punctuation_chars
+
+ Characters that will be considered punctuation. Runs of punctuation
+ characters will be returned as a single token. However, note that no
+ semantic validity checking will be performed: for example, '>>>' could be
+ returned as a token, even though it may not be recognised as such by shells.
+
+ .. versionadded:: 3.6
+
+
.. _shlex-parsing-rules:
Parsing Rules
@@ -327,3 +357,62 @@ following parsing rules.
* EOF is signaled with a :const:`None` value;
* Quoted empty strings (``''``) are allowed.
+
+.. _improved-shell-compatibility:
+
+Improved Compatibility with Shells
+----------------------------------
+
+.. versionadded:: 3.6
+
+The :class:`shlex` class provides compatibility with the parsing performed by
+common Unix shells like ``bash``, ``dash``, and ``sh``. To take advantage of
+this compatibility, specify the ``punctuation_chars`` argument in the
+constructor. This defaults to ``False``, which preserves pre-3.6 behaviour.
+However, if it is set to ``True``, then parsing of the characters ``();<>|&``
+is changed: any run of these characters is returned as a single token. While
+this is short of a full parser for shells (which would be out of scope for the
+standard library, given the multiplicity of shells out there), it does allow
+you to perform processing of command lines more easily than you could
+otherwise. To illustrate, you can see the difference in the following snippet::
+
+ import shlex
+
+ for punct in (False, True):
+ if punct:
+ message = 'Old'
+ else:
+ message = 'New'
+ text = "a && b; c && d || e; f >'abc'; (def \"ghi\")"
+ s = shlex.shlex(text, punctuation_chars=punct)
+ print('%s: %s' % (message, list(s)))
+
+which prints out::
+
+ Old: ['a', '&', '&', 'b', ';', 'c', '&', '&', 'd', '|', '|', 'e', ';', 'f', '>', "'abc'", ';', '(', 'def', '"ghi"', ')']
+ New: ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', "'abc'", ';', '(', 'def', '"ghi"', ')']
+
+Of course, tokens will be returned which are not valid for shells, and you'll
+need to implement your own error checks on the returned tokens.
+
+Instead of passing ``True`` as the value for the punctuation_chars parameter,
+you can pass a string with specific characters, which will be used to determine
+which characters constitute punctuation. For example::
+
+ >>> import shlex
+ >>> s = shlex.shlex("a && b || c", punctuation_chars="|")
+ >>> list(s)
+ ['a', '&', '&', 'b', '||', 'c']
+
+.. note:: When ``punctuation_chars`` is specified, the :attr:`~shlex.wordchars`
+ attribute is augmented with the characters ``~-./*?=``. That is because these
+ characters can appear in file names (including wildcards) and command-line
+ arguments (e.g. ``--color=auto``). Hence::
+
+ >>> import shlex
+ >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
+ ... punctuation_chars=True)
+ >>> list(s)
+ ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']
+
+
diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst
index b020bb3..a85bf33 100644
--- a/Doc/library/shutil.rst
+++ b/Doc/library/shutil.rst
@@ -425,7 +425,7 @@ Another example that uses the *ignore* argument to add a logging call::
import logging
def _logpath(path, names):
- logging.info('Working in %s' % path)
+ logging.info('Working in %s', path)
return [] # nothing will be ignored
copytree(source, destination, ignore=_logpath)
diff --git a/Doc/library/site.rst b/Doc/library/site.rst
index 0a73f5a..43daf79 100644
--- a/Doc/library/site.rst
+++ b/Doc/library/site.rst
@@ -52,7 +52,8 @@ searched for site-packages; otherwise they won't.
A path configuration file is a file whose name has the form :file:`{name}.pth`
and exists in one of the four directories mentioned above; its contents are
additional items (one per line) to be added to ``sys.path``. Non-existing items
-are never added to ``sys.path``. No item is added to ``sys.path`` more than
+are never added to ``sys.path``, and no check is made that the item refers to a
+directory rather than a file. No item is added to ``sys.path`` more than
once. Blank lines and lines beginning with ``#`` are skipped. Lines starting
with ``import`` (followed by space or tab) are executed.
diff --git a/Doc/library/smtpd.rst b/Doc/library/smtpd.rst
index a096de0..e383201 100644
--- a/Doc/library/smtpd.rst
+++ b/Doc/library/smtpd.rst
@@ -29,7 +29,7 @@ SMTPServer Objects
.. class:: SMTPServer(localaddr, remoteaddr, data_size_limit=33554432,\
- map=None, enable_SMTPUTF8=False, decode_data=True)
+ map=None, enable_SMTPUTF8=False, decode_data=False)
Create a new :class:`SMTPServer` object, which binds to local address
*localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. Both
@@ -46,20 +46,19 @@ SMTPServer Objects
global socket map is used.
*enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined
- in :RFC:`6531`) should be enabled. The default is ``False``. If set to
- ``True``, *decode_data* must be ``False`` (otherwise an error is raised).
+ in :RFC:`6531`) should be enabled. The default is ``False``.
When ``True``, ``SMTPUTF8`` is accepted as a parameter to the ``MAIL``
command and when present is passed to :meth:`process_message` in the
- ``kwargs['mail_options']`` list.
+ ``kwargs['mail_options']`` list. *decode_data* and *enable_SMTPUTF8*
+ cannot be set to ``True`` at the same time.
*decode_data* specifies whether the data portion of the SMTP transaction
- should be decoded using UTF-8. The default is ``True`` for backward
- compatibility reasons, but will change to ``False`` in Python 3.6; specify
- the keyword value explicitly to avoid the :exc:`DeprecationWarning`. When
- *decode_data* is set to ``False`` the server advertises the ``8BITMIME``
+ should be decoded using UTF-8. When *decode_data* is ``False`` (the
+ default), the server advertises the ``8BITMIME``
extension (:rfc:`6152`), accepts the ``BODY=8BITMIME`` parameter to
the ``MAIL`` command, and when present passes it to :meth:`process_message`
- in the ``kwargs['mail_options']`` list.
+ in the ``kwargs['mail_options']`` list. *decode_data* and *enable_SMTPUTF8*
+ cannot be set to ``True`` at the same time.
.. method:: process_message(peer, mailfrom, rcpttos, data, **kwargs)
@@ -76,9 +75,8 @@ SMTPServer Objects
will be a bytes object.
*kwargs* is a dictionary containing additional information. It is empty
- unless at least one of ``decode_data=False`` or ``enable_SMTPUTF8=True``
- was given as an init parameter, in which case it contains the following
- keys:
+ if ``decode_data=True`` was given as an init argument, otherwise
+ it contains the following keys:
*mail_options*:
a list of all received parameters to the ``MAIL``
@@ -109,9 +107,12 @@ SMTPServer Objects
*localaddr* and *remoteaddr* may now contain IPv6 addresses.
.. versionadded:: 3.5
- the *decode_data* and *enable_SMTPUTF8* constructor arguments, and the
- *kwargs* argument to :meth:`process_message` when one or more of these is
- specified.
+ The *decode_data* and *enable_SMTPUTF8* constructor parameters, and the
+ *kwargs* parameter to :meth:`process_message` when *decode_data* is
+ ``False``.
+
+ .. versionchanged:: 3.6
+ *decode_data* is now ``False`` by default.
DebuggingServer Objects
@@ -151,7 +152,7 @@ SMTPChannel Objects
-------------------
.. class:: SMTPChannel(server, conn, addr, data_size_limit=33554432,\
- map=None, enable_SMTPUTF8=False, decode_data=True)
+ map=None, enable_SMTPUTF8=False, decode_data=False)
Create a new :class:`SMTPChannel` object which manages the communication
between the server and a single SMTP client.
@@ -163,22 +164,25 @@ SMTPChannel Objects
limit.
*enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined
- in :RFC:`6531`) should be enabled. The default is ``False``. A
- :exc:`ValueError` is raised if both *enable_SMTPUTF8* and *decode_data* are
- set to ``True`` at the same time.
+ in :RFC:`6531`) should be enabled. The default is ``False``.
+ *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same
+ time.
A dictionary can be specified in *map* to avoid using a global socket map.
*decode_data* specifies whether the data portion of the SMTP transaction
- should be decoded using UTF-8. The default is ``True`` for backward
- compatibility reasons, but will change to ``False`` in Python 3.6. Specify
- the keyword value explicitly to avoid the :exc:`DeprecationWarning`.
+ should be decoded using UTF-8. The default is ``False``.
+ *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same
+ time.
To use a custom SMTPChannel implementation you need to override the
:attr:`SMTPServer.channel_class` of your :class:`SMTPServer`.
.. versionchanged:: 3.5
- the *decode_data* and *enable_SMTPUTF8* arguments were added.
+ The *decode_data* and *enable_SMTPUTF8* parameters were added.
+
+ .. versionchanged:: 3.6
+ *decode_data* is now ``False`` by default.
The :class:`SMTPChannel` has the following instance variables:
diff --git a/Doc/library/smtplib.rst b/Doc/library/smtplib.rst
index 8b98ccf..86e769e 100644
--- a/Doc/library/smtplib.rst
+++ b/Doc/library/smtplib.rst
@@ -95,6 +95,14 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
:data:`ssl.HAS_SNI`).
+ .. deprecated:: 3.6
+
+ *keyfile* and *certfile* are deprecated in favor of *context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
+
+
.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
The LMTP protocol, which is very similar to ESMTP, is heavily based on the
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
index 530000b..9c10867 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -133,6 +133,22 @@ created. Socket addresses are represented as follows:
string format. (ex. ``b'12:23:34:45:56:67'``) This protocol is not
supported under FreeBSD.
+- :const:`AF_ALG` is a Linux-only socket based interface to Kernel
+ cryptography. An algorithm socket is configured with a tuple of two to four
+ elements ``(type, name [, feat [, mask]])``, where:
+
+ - *type* is the algorithm type as string, e.g. ``aead``, ``hash``,
+ ``skcipher`` or ``rng``.
+
+ - *name* is the algorithm name and operation mode as string, e.g.
+ ``sha256``, ``hmac(sha256)``, ``cbc(aes)`` or ``drbg_nopr_ctr_aes256``.
+
+ - *feat* and *mask* are unsigned 32bit integers.
+
+ Availability Linux 2.6.38, some algorithm types require more recent Kernels.
+
+ .. versionadded:: 3.6
+
- Certain other address families (:const:`AF_PACKET`, :const:`AF_CAN`)
support specific representations.
@@ -283,6 +299,10 @@ Constants
in the Unix header files are defined; for a few symbols, default values are
provided.
+ .. versionchanged:: 3.6
+ ``SO_DOMAIN``, ``SO_PROTOCOL``, ``SO_PEERSEC``, ``SO_PASSSEC``
+ were added.
+
.. data:: AF_CAN
PF_CAN
SOL_CAN_*
@@ -331,18 +351,33 @@ Constants
.. versionadded:: 3.3
-.. data:: SIO_*
+.. data:: SIO_RCVALL
+ SIO_KEEPALIVE_VALS
+ SIO_LOOPBACK_FAST_PATH
RCVALL_*
Constants for Windows' WSAIoctl(). The constants are used as arguments to the
:meth:`~socket.socket.ioctl` method of socket objects.
+ .. versionchanged:: 3.6
+ ``SIO_LOOPBACK_FAST_PATH`` was added.
+
.. data:: TIPC_*
TIPC related constants, matching the ones exported by the C socket API. See
the TIPC documentation for more information.
+.. data:: AF_ALG
+ SOL_ALG
+ ALG_*
+
+ Constants for Linux Kernel cryptography.
+
+ Availability: Linux >= 2.6.38.
+
+ .. versionadded:: 3.6
+
.. data:: AF_LINK
Availability: BSD, OSX.
@@ -874,6 +909,10 @@ to sockets.
it is recommended to :meth:`close` them explicitly, or to use a
:keyword:`with` statement around them.
+ .. versionchanged:: 3.6
+ :exc:`OSError` is now raised if an error occurs when the underlying
+ :c:func:`close` call is made.
+
.. note::
:meth:`close()` releases the resource associated with a connection but
@@ -994,6 +1033,12 @@ to sockets.
On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
functions may be used; they accept a socket object as their first argument.
+ Currently only the following control codes are supported:
+ ``SIO_RCVALL``, ``SIO_KEEPALIVE_VALS``, and ``SIO_LOOPBACK_FAST_PATH``.
+
+ .. versionchanged:: 3.6
+ ``SIO_LOOPBACK_FAST_PATH`` was added.
+
.. method:: socket.listen([backlog])
Enable a server to accept connections. If *backlog* is specified, it must
@@ -1277,6 +1322,15 @@ to sockets.
an exception, the method now retries the system call instead of raising
an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
+.. method:: socket.sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags]]])
+
+ Specialized version of :meth:`~socket.sendmsg` for :const:`AF_ALG` socket.
+ Set mode, IV, AEAD associated data length and flags for :const:`AF_ALG` socket.
+
+ Availability: Linux >= 2.6.38
+
+ .. versionadded:: 3.6
+
.. method:: socket.sendfile(file, offset=0, count=None)
Send a file until EOF is reached by using high-performance
@@ -1325,21 +1379,29 @@ to sockets.
For further information, please consult the :ref:`notes on socket timeouts <socket-timeouts>`.
-.. method:: socket.setsockopt(level, optname, value)
+.. method:: socket.setsockopt(level, optname, value: int)
+.. method:: socket.setsockopt(level, optname, value: buffer)
+.. method:: socket.setsockopt(level, optname, None, optlen: int)
.. index:: module: struct
Set the value of the given socket option (see the Unix manual page
:manpage:`setsockopt(2)`). The needed symbolic constants are defined in the
- :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or
- a :term:`bytes-like object` representing a buffer. In the latter case it is
- up to the caller to
- ensure that the bytestring contains the proper bits (see the optional built-in
- module :mod:`struct` for a way to encode C structures as bytestrings).
+ :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer,
+ ``None`` or a :term:`bytes-like object` representing a buffer. In the later
+ case it is up to the caller to ensure that the bytestring contains the
+ proper bits (see the optional built-in module :mod:`struct` for a way to
+ encode C structures as bytestrings). When value is set to ``None``,
+ optlen argument is required. It's equivalent to call setsockopt C
+ function with optval=NULL and optlen=optlen.
+
.. versionchanged:: 3.5
Writable :term:`bytes-like object` is now accepted.
+ .. versionchanged:: 3.6
+ setsockopt(level, optname, None, optlen: int) form added.
+
.. method:: socket.shutdown(how)
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index 087f4e0..218a31c 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -52,11 +52,12 @@ handler class by subclassing the :class:`BaseRequestHandler` class and
overriding its :meth:`~BaseRequestHandler.handle` method;
this method will process incoming
requests. Second, you must instantiate one of the server classes, passing it
-the server's address and the request handler class. Then call the
+the server's address and the request handler class. It is recommended to use
+the server in a :keyword:`with` statement. Then call the
:meth:`~BaseServer.handle_request` or
:meth:`~BaseServer.serve_forever` method of the server object to
process one or many requests. Finally, call :meth:`~BaseServer.server_close`
-to close the socket.
+to close the socket (unless you used a :keyword:`with` statement).
When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
you should explicitly declare how you want your threads to behave on an abrupt
@@ -111,6 +112,8 @@ server classes.
:class:`UDPServer`. Setting the various attributes also changes the
behavior of the underlying server mechanism.
+ :class:`ForkingMixIn` and the Forking classes mentioned below are
+ only available on POSIX platforms that support :func:`~os.fork`.
.. class:: ForkingTCPServer
ForkingUDPServer
@@ -304,7 +307,11 @@ Server Objects
This function is called if the :meth:`~BaseRequestHandler.handle`
method of a :attr:`RequestHandlerClass` instance raises
an exception. The default action is to print the traceback to
- standard output and continue handling further requests.
+ standard error and continue handling further requests.
+
+ .. versionchanged:: 3.6
+ Now only called for exceptions derived from the :exc:`Exception`
+ class.
.. method:: handle_timeout()
@@ -349,6 +356,11 @@ Server Objects
default implementation always returns :const:`True`.
+ .. versionchanged:: 3.6
+ Support for the :term:`context manager` protocol was added. Exiting the
+ context manager is equivalent to calling :meth:`server_close`.
+
+
Request Handler Objects
-----------------------
@@ -397,6 +409,15 @@ Request Handler Objects
read or written, respectively, to get the request data or return data
to the client.
+ The :attr:`rfile` attributes of both classes support the
+ :class:`io.BufferedIOBase` readable interface, and
+ :attr:`DatagramRequestHandler.wfile` supports the
+ :class:`io.BufferedIOBase` writable interface.
+
+ .. versionchanged:: 3.6
+ :attr:`StreamRequestHandler.wfile` also supports the
+ :class:`io.BufferedIOBase` writable interface.
+
Examples
--------
@@ -429,11 +450,10 @@ This is the server side::
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
- server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
-
- # Activate the server; this will keep running until you
- # interrupt the program with Ctrl-C
- server.serve_forever()
+ with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
+ # Activate the server; this will keep running until you
+ # interrupt the program with Ctrl-C
+ server.serve_forever()
An alternative request handler class that makes use of streams (file-like
objects that simplify communication by providing the standard file interface)::
@@ -525,8 +545,8 @@ This is the server side::
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
- server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)
- server.serve_forever()
+ with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
+ server.serve_forever()
This is the client side::
@@ -585,22 +605,22 @@ An example for the :class:`ThreadingMixIn` class::
HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
- ip, port = server.server_address
+ with server:
+ ip, port = server.server_address
- # Start a thread with the server -- that thread will then start one
- # more thread for each request
- server_thread = threading.Thread(target=server.serve_forever)
- # Exit the server thread when the main thread terminates
- server_thread.daemon = True
- server_thread.start()
- print("Server loop running in thread:", server_thread.name)
+ # Start a thread with the server -- that thread will then start one
+ # more thread for each request
+ server_thread = threading.Thread(target=server.serve_forever)
+ # Exit the server thread when the main thread terminates
+ server_thread.daemon = True
+ server_thread.start()
+ print("Server loop running in thread:", server_thread.name)
- client(ip, port, "Hello World 1")
- client(ip, port, "Hello World 2")
- client(ip, port, "Hello World 3")
+ client(ip, port, "Hello World 1")
+ client(ip, port, "Hello World 2")
+ client(ip, port, "Hello World 3")
- server.shutdown()
- server.server_close()
+ server.shutdown()
The output of the example should look something like this:
@@ -616,3 +636,5 @@ The output of the example should look something like this:
The :class:`ForkingMixIn` class is used in the same way, except that the server
will spawn a new process for each request.
+Available only on POSIX platforms that support :func:`~os.fork`.
+
diff --git a/Doc/library/spwd.rst b/Doc/library/spwd.rst
index fd3c9ad..c6cad2a 100644
--- a/Doc/library/spwd.rst
+++ b/Doc/library/spwd.rst
@@ -55,6 +55,9 @@ The following functions are defined:
Return the shadow password database entry for the given user name.
+ .. versionchanged:: 3.6
+ Raises a :exc:`PermissionError` instead of :exc:`KeyError` if the user
+ doesn't have privileges.
.. function:: getspall()
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index 84a4783..5635577 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -629,9 +629,16 @@ Cursor Objects
.. attribute:: lastrowid
This read-only attribute provides the rowid of the last modified row. It is
- only set if you issued an ``INSERT`` statement using the :meth:`execute`
- method. For operations other than ``INSERT`` or when :meth:`executemany` is
- called, :attr:`lastrowid` is set to :const:`None`.
+ only set if you issued an ``INSERT`` or a ``REPLACE`` statement using the
+ :meth:`execute` method. For operations other than ``INSERT`` or
+ ``REPLACE`` or when :meth:`executemany` is called, :attr:`lastrowid` is
+ set to :const:`None`.
+
+ If the ``INSERT`` or ``REPLACE`` statement failed to insert the previous
+ successful rowid is returned.
+
+ .. versionchanged:: 3.6
+ Added support for the ``REPLACE`` statement.
.. attribute:: description
@@ -918,9 +925,7 @@ Controlling Transactions
By default, the :mod:`sqlite3` module opens transactions implicitly before a
Data Modification Language (DML) statement (i.e.
-``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
-implicitly before a non-DML, non-query statement (i. e.
-anything other than ``SELECT`` or the aforementioned).
+``INSERT``/``UPDATE``/``DELETE``/``REPLACE``).
So if you are within a transaction and issue a command like ``CREATE TABLE
...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
@@ -940,6 +945,9 @@ Otherwise leave it at its default, which will result in a plain "BEGIN"
statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
"IMMEDIATE" or "EXCLUSIVE".
+.. versionchanged:: 3.6
+ :mod:`sqlite3` used to implicitly commit an open transaction before DDL
+ statements. This is no longer the case.
Using :mod:`sqlite3` efficiently
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index a2f0083..eee4849 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -49,6 +49,12 @@ For more sophisticated applications, the :class:`ssl.SSLContext` class
helps manage settings and certificates, which can then be inherited
by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
+.. versionchanged:: 3.6
+
+ OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.
+ In the future the ssl module will require at least OpenSSL 1.0.2 or
+ 1.1.0.
+
Functions, Constants, and Exceptions
------------------------------------
@@ -186,16 +192,20 @@ instead.
.. table::
- ======================== ========= ========= ========== ========= =========== ===========
- *client* / **server** **SSLv2** **SSLv3** **TLS** **TLSv1** **TLSv1.1** **TLSv1.2**
- ------------------------ --------- --------- ---------- --------- ----------- -----------
- *SSLv2* yes no yes no no no
- *SSLv3* no yes yes no no no
- *TLS* (*SSLv23*) no yes yes yes yes yes
- *TLSv1* no no yes yes no no
- *TLSv1.1* no no yes no yes no
- *TLSv1.2* no no yes no no yes
- ======================== ========= ========= ========== ========= =========== ===========
+ ======================== ============ ============ ============= ========= =========== ===========
+ *client* / **server** **SSLv2** **SSLv3** **TLS** **TLSv1** **TLSv1.1** **TLSv1.2**
+ ------------------------ ------------ ------------ ------------- --------- ----------- -----------
+ *SSLv2* yes no no [1]_ no no no
+ *SSLv3* no yes no [2]_ no no no
+ *TLS* (*SSLv23*) no [1]_ no [2]_ yes yes yes yes
+ *TLSv1* no no yes yes no no
+ *TLSv1.1* no no yes no yes no
+ *TLSv1.2* no no yes no no yes
+ ======================== ============ ============ ============= ========= =========== ===========
+
+ .. rubric:: Footnotes
+ .. [1] :class:`SSLContext` disables SSLv2 with :data:`OP_NO_SSLv2` by default.
+ .. [2] :class:`SSLContext` disables SSLv3 with :data:`OP_NO_SSLv3` by default.
.. note::
@@ -224,7 +234,6 @@ instead.
.. versionchanged:: 3.2
New optional argument *ciphers*.
-
Context creation
^^^^^^^^^^^^^^^^
@@ -279,7 +288,7 @@ purposes.
RC4 was dropped from the default cipher string.
- .. versionchanged:: 3.5.3
+ .. versionchanged:: 3.6
ChaCha20/Poly1305 was added to the default cipher string.
@@ -322,7 +331,7 @@ Random generation
.. versionadded:: 3.3
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
:func:`ssl.RAND_bytes` instead.
@@ -509,6 +518,10 @@ Certificate handling
Constants
^^^^^^^^^
+ All constants are now :class:`enum.IntEnum` or :class:`enum.IntFlag` collections.
+
+ .. versionadded:: 3.6
+
.. data:: CERT_NONE
Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
@@ -542,6 +555,12 @@ Constants
be passed, either to :meth:`SSLContext.load_verify_locations` or as a
value of the ``ca_certs`` parameter to :func:`wrap_socket`.
+.. class:: VerifyMode
+
+ :class:`enum.IntEnum` collection of CERT_* constants.
+
+ .. versionadded:: 3.6
+
.. data:: VERIFY_DEFAULT
Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate
@@ -582,18 +601,40 @@ Constants
.. versionadded:: 3.4.4
+.. class:: VerifyFlags
+
+ :class:`enum.IntFlag` collection of VERIFY_* constants.
+
+ .. versionadded:: 3.6
+
.. data:: PROTOCOL_TLS
Selects the highest protocol version that both the client and server support.
Despite the name, this option can select "TLS" protocols as well as "SSL".
- .. versionadded:: 3.5.3
+ .. versionadded:: 3.6
+
+.. data:: PROTOCOL_TLS_CLIENT
+
+ Auto-negotiate the the highest protocol version like :data:`PROTOCOL_SSLv23`,
+ but only support client-side :class:`SSLSocket` connections. The protocol
+ enables :data:`CERT_REQUIRED` and :attr:`~SSLContext.check_hostname` by
+ default.
+
+ .. versionadded:: 3.6
+
+.. data:: PROTOCOL_TLS_SERVER
+
+ Auto-negotiate the the highest protocol version like :data:`PROTOCOL_SSLv23`,
+ but only support server-side :class:`SSLSocket` connections.
+
+ .. versionadded:: 3.6
.. data:: PROTOCOL_SSLv23
Alias for data:`PROTOCOL_TLS`.
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
Use data:`PROTOCOL_TLS` instead.
@@ -608,7 +649,7 @@ Constants
SSL version 2 is insecure. Its use is highly discouraged.
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has removed support for SSLv2.
@@ -623,7 +664,7 @@ Constants
SSL version 3 is insecure. Its use is highly discouraged.
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has deprecated all version specific protocols. Use the default
protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
@@ -632,7 +673,7 @@ Constants
Selects TLS version 1.0 as the channel encryption protocol.
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has deprecated all version specific protocols. Use the default
protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
@@ -644,7 +685,7 @@ Constants
.. versionadded:: 3.4
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has deprecated all version specific protocols. Use the default
protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
@@ -657,7 +698,7 @@ Constants
.. versionadded:: 3.4
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
OpenSSL has deprecated all version specific protocols. Use the default
protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
@@ -678,7 +719,7 @@ Constants
.. versionadded:: 3.2
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
SSLv2 is deprecated
@@ -691,7 +732,7 @@ Constants
.. versionadded:: 3.2
- .. deprecated:: 3.5.3
+ .. deprecated:: 3.6
SSLv3 is deprecated
@@ -751,6 +792,16 @@ Constants
.. versionadded:: 3.3
+.. class:: Options
+
+ :class:`enum.IntFlag` collection of OP_* constants.
+
+.. data:: OP_NO_TICKET
+
+ Prevent client side from requesting a session ticket.
+
+ .. versionadded:: 3.6
+
.. data:: HAS_ALPN
Whether the OpenSSL library has built-in support for the *Application-Layer
@@ -833,6 +884,12 @@ Constants
.. versionadded:: 3.4
+.. class:: AlertDescription
+
+ :class:`enum.IntEnum` collection of ALERT_DESCRIPTION_* constants.
+
+ .. versionadded:: 3.6
+
.. data:: Purpose.SERVER_AUTH
Option for :func:`create_default_context` and
@@ -851,6 +908,12 @@ Constants
.. versionadded:: 3.4
+.. class:: SSLErrorNumber
+
+ :class:`enum.IntEnum` collection of SSL_ERROR_* constants.
+
+ .. versionadded:: 3.6
+
SSL Sockets
-----------
@@ -885,7 +948,7 @@ SSL Sockets
:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
Usually, :class:`SSLSocket` are not created directly, but using the
- :func:`wrap_socket` function or the :meth:`SSLContext.wrap_socket` method.
+ the :meth:`SSLContext.wrap_socket` method.
.. versionchanged:: 3.5
The :meth:`sendfile` method was added.
@@ -895,6 +958,10 @@ SSL Sockets
are received or sent. The socket timeout is now to maximum total duration
of the shutdown.
+ .. deprecated:: 3.6
+ It is deprecated to create a :class:`SSLSocket` instance directly, use
+ :meth:`SSLContext.wrap_socket` to wrap a socket.
+
SSL sockets also have the following additional methods and attributes:
@@ -915,6 +982,9 @@ SSL sockets also have the following additional methods and attributes:
The socket timeout is now to maximum total duration to read up to *len*
bytes.
+ .. deprecated:: 3.6
+ Use :meth:`~SSLSocket.recv` instead of :meth:`~SSLSocket.read`.
+
.. method:: SSLSocket.write(buf)
Write *buf* to the SSL socket and return the number of bytes written. The
@@ -930,6 +1000,9 @@ SSL sockets also have the following additional methods and attributes:
The socket timeout is no more reset each time bytes are received or sent.
The socket timeout is now to maximum total duration to write *buf*.
+ .. deprecated:: 3.6
+ Use :meth:`~SSLSocket.send` instead of :meth:`~SSLSocket.write`.
+
.. note::
The :meth:`~SSLSocket.read` and :meth:`~SSLSocket.write` methods are the
@@ -1127,6 +1200,19 @@ SSL sockets also have the following additional methods and attributes:
.. versionadded:: 3.2
+.. attribute:: SSLSocket.session
+
+ The :class:`SSLSession` for this SSL connection. The session is available
+ for client and server side sockets after the TLS handshake has been
+ performed. For client sockets the session can be set before
+ :meth:`~SSLSocket.do_handshake` has been called to reuse a session.
+
+ .. versionadded:: 3.6
+
+.. attribute:: SSLSocket.session_reused
+
+ .. versionadded:: 3.6
+
SSL Contexts
------------
@@ -1149,9 +1235,16 @@ to speed up repeated connections from the same clients.
:func:`create_default_context` lets the :mod:`ssl` module choose
security settings for a given purpose.
- .. versionchanged:: 3.5.3
+ .. versionchanged:: 3.6
- :data:`PROTOCOL_TLS` is the default value.
+ The context is created with secure default values. The options
+ :data:`OP_NO_COMPRESSION`, :data:`OP_CIPHER_SERVER_PREFERENCE`,
+ :data:`OP_SINGLE_DH_USE`, :data:`OP_SINGLE_ECDH_USE`,
+ :data:`OP_NO_SSLv2` (except for :data:`PROTOCOL_SSLv2`),
+ and :data:`OP_NO_SSLv3` (except for :data:`PROTOCOL_SSLv3`) are
+ set by default. The initial cipher suite list contains only ``HIGH``
+ ciphers, no ``NULL`` ciphers and no ``MD5`` ciphers (except for
+ :data:`PROTOCOL_SSLv2`).
:class:`SSLContext` objects have the following methods and attributes:
@@ -1259,6 +1352,62 @@ to speed up repeated connections from the same clients.
.. versionadded:: 3.4
+.. method:: SSLContext.get_ciphers()
+
+ Get a list of enabled ciphers. The list is in order of cipher priority.
+ See :meth:`SSLContext.set_ciphers`.
+
+ Example::
+
+ >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+ >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
+ >>> ctx.get_ciphers() # OpenSSL 1.0.x
+ [{'alg_bits': 256,
+ 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA '
+ 'Enc=AESGCM(256) Mac=AEAD',
+ 'id': 50380848,
+ 'name': 'ECDHE-RSA-AES256-GCM-SHA384',
+ 'protocol': 'TLSv1/SSLv3',
+ 'strength_bits': 256},
+ {'alg_bits': 128,
+ 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA '
+ 'Enc=AESGCM(128) Mac=AEAD',
+ 'id': 50380847,
+ 'name': 'ECDHE-RSA-AES128-GCM-SHA256',
+ 'protocol': 'TLSv1/SSLv3',
+ 'strength_bits': 128}]
+
+ On OpenSSL 1.1 and newer the cipher dict contains additional fields::
+ >>> ctx.get_ciphers() # OpenSSL 1.1+
+ [{'aead': True,
+ 'alg_bits': 256,
+ 'auth': 'auth-rsa',
+ 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA '
+ 'Enc=AESGCM(256) Mac=AEAD',
+ 'digest': None,
+ 'id': 50380848,
+ 'kea': 'kx-ecdhe',
+ 'name': 'ECDHE-RSA-AES256-GCM-SHA384',
+ 'protocol': 'TLSv1.2',
+ 'strength_bits': 256,
+ 'symmetric': 'aes-256-gcm'},
+ {'aead': True,
+ 'alg_bits': 128,
+ 'auth': 'auth-rsa',
+ 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA '
+ 'Enc=AESGCM(128) Mac=AEAD',
+ 'digest': None,
+ 'id': 50380847,
+ 'kea': 'kx-ecdhe',
+ 'name': 'ECDHE-RSA-AES128-GCM-SHA256',
+ 'protocol': 'TLSv1.2',
+ 'strength_bits': 128,
+ 'symmetric': 'aes-128-gcm'}]
+
+ Availability: OpenSSL 1.0.2+
+
+ .. versionadded:: 3.6
+
.. method:: SSLContext.set_default_verify_paths()
Load a set of default "certification authority" (CA) certificates from
@@ -1397,7 +1546,7 @@ to speed up repeated connections from the same clients.
.. method:: SSLContext.wrap_socket(sock, server_side=False, \
do_handshake_on_connect=True, suppress_ragged_eofs=True, \
- server_hostname=None)
+ server_hostname=None, session=None)
Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket
@@ -1414,19 +1563,27 @@ to speed up repeated connections from the same clients.
quite similarly to HTTP virtual hosts. Specifying *server_hostname* will
raise a :exc:`ValueError` if *server_side* is true.
+ *session*, see :attr:`~SSLSocket.session`.
+
.. versionchanged:: 3.5
Always allow a server_hostname to be passed, even if OpenSSL does not
have SNI.
+ .. versionchanged:: 3.6
+ *session* argument was added.
+
.. method:: SSLContext.wrap_bio(incoming, outgoing, server_side=False, \
- server_hostname=None)
+ server_hostname=None, session=None)
Create a new :class:`SSLObject` instance by wrapping the BIO objects
*incoming* and *outgoing*. The SSL routines will read input data from the
incoming BIO and write data to the outgoing BIO.
- The *server_side* and *server_hostname* parameters have the same meaning as
- in :meth:`SSLContext.wrap_socket`.
+ The *server_side*, *server_hostname* and *session* parameters have the
+ same meaning as in :meth:`SSLContext.wrap_socket`.
+
+ .. versionchanged:: 3.6
+ *session* argument was added.
.. method:: SSLContext.session_stats()
@@ -1478,6 +1635,12 @@ to speed up repeated connections from the same clients.
to set options, not to clear them. Attempting to clear an option
(by resetting the corresponding bits) will raise a ``ValueError``.
+ .. versionchanged:: 3.6
+ :attr:`SSLContext.options` returns :class:`Options` flags:
+
+ >>> ssl.create_default_context().options
+ <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>
+
.. attribute:: SSLContext.protocol
The protocol version chosen when constructing the context. This attribute
@@ -1492,12 +1655,23 @@ to speed up repeated connections from the same clients.
.. versionadded:: 3.4
+ .. versionchanged:: 3.6
+ :attr:`SSLContext.verify_flags` returns :class:`VerifyFlags` flags:
+
+ >>> ssl.create_default_context().verify_flags
+ <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
+
.. attribute:: SSLContext.verify_mode
Whether to try to verify other peers' certificates and how to behave
if verification fails. This attribute must be one of
:data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
+ .. versionchanged:: 3.6
+ :attr:`SSLContext.verify_mode` returns :class:`VerifyMode` enum:
+
+ >>> ssl.create_default_context().verify_mode
+ <VerifyMode.CERT_REQUIRED: 2>
.. index:: single: certificates
@@ -1916,6 +2090,8 @@ provided.
- :attr:`~SSLSocket.context`
- :attr:`~SSLSocket.server_side`
- :attr:`~SSLSocket.server_hostname`
+ - :attr:`~SSLSocket.session`
+ - :attr:`~SSLSocket.session_reused`
- :meth:`~SSLSocket.read`
- :meth:`~SSLSocket.write`
- :meth:`~SSLSocket.getpeercert`
@@ -1997,6 +2173,22 @@ purpose. It wraps an OpenSSL memory BIO (Basic IO) object:
become true after all data currently in the buffer has been read.
+SSL session
+-----------
+
+.. versionadded:: 3.6
+
+.. class:: SSLSession
+
+ Session object used by :attr:`~SSLSocket.session`.
+
+ .. attribute:: id
+ .. attribute:: time
+ .. attribute:: timeout
+ .. attribute:: ticket_lifetime_hint
+ .. attribute:: has_ticket
+
+
.. _ssl-security:
Security considerations
@@ -2063,18 +2255,20 @@ Protocol versions
SSL versions 2 and 3 are considered insecure and are therefore dangerous to
use. If you want maximum compatibility between clients and servers, it is
-recommended to use :const:`PROTOCOL_TLS` as the protocol version and then
-disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
-attribute::
+recommended to use :const:`PROTOCOL_TLS_CLIENT` or
+:const:`PROTOCOL_TLS_SERVER` as the protocol version. SSLv2 and SSLv3 are
+disabled by default.
+
+ >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ >>> client_context.options |= ssl.OP_NO_TLSv1
+ >>> client_context.options |= ssl.OP_NO_TLSv1_1
- context = ssl.SSLContext(ssl.PROTOCOL_TLS)
- context.options |= ssl.OP_NO_SSLv2
- context.options |= ssl.OP_NO_SSLv3
- context.options |= ssl.OP_NO_TLSv1
- context.options |= ssl.OP_NO_TLSv1_1
The SSL context created above will only allow TLSv1.2 and later (if
-supported by your system) connections.
+supported by your system) connections to a server. :const:`PROTOCOL_TLS_CLIENT`
+implies certificate validation and hostname checks by default. You have to
+load certificates into the context.
+
Cipher selection
''''''''''''''''
@@ -2085,8 +2279,9 @@ enabled when negotiating a SSL session is possible through the
ssl module disables certain weak ciphers by default, but you may want
to further restrict the cipher choice. Be sure to read OpenSSL's documentation
about the `cipher list format <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
-If you want to check which ciphers are enabled by a given cipher list, use the
-``openssl ciphers`` command on your system.
+If you want to check which ciphers are enabled by a given cipher list, use
+:meth:`SSLContext.get_ciphers` or the ``openssl ciphers`` command on your
+system.
Multi-processing
^^^^^^^^^^^^^^^^
diff --git a/Doc/library/statistics.rst b/Doc/library/statistics.rst
index 7685621..2aa778c 100644
--- a/Doc/library/statistics.rst
+++ b/Doc/library/statistics.rst
@@ -39,6 +39,7 @@ or sample.
======================= =============================================
:func:`mean` Arithmetic mean ("average") of data.
+:func:`harmonic_mean` Harmonic mean of data.
:func:`median` Median (middle value) of data.
:func:`median_low` Low median of data.
:func:`median_high` High median of data.
@@ -68,8 +69,7 @@ However, for reading convenience, most of the examples show sorted sequences.
.. function:: mean(data)
- Return the sample arithmetic mean of *data*, a sequence or iterator of
- real-valued numbers.
+ Return the sample arithmetic mean of *data* which can be a sequence or iterator.
The arithmetic mean is the sum of the data divided by the number of data
points. It is commonly called "the average", although it is only one of many
@@ -111,10 +111,43 @@ However, for reading convenience, most of the examples show sorted sequences.
``mean(data)`` is equivalent to calculating the true population mean μ.
+.. function:: harmonic_mean(data)
+
+ Return the harmonic mean of *data*, a sequence or iterator of
+ real-valued numbers.
+
+ The harmonic mean, sometimes called the subcontrary mean, is the
+ reciprocal of the arithmetic :func:`mean` of the reciprocals of the
+ data. For example, the harmonic mean of three values *a*, *b* and *c*
+ will be equivalent to ``3/(1/a + 1/b + 1/c)``.
+
+ The harmonic mean is a type of average, a measure of the central
+ location of the data. It is often appropriate when averaging quantities
+ which are rates or ratios, for example speeds. For example:
+
+ 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?
+
+ .. doctest::
+
+ >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
+ 3.6
+
+ Using the arithmetic mean would give an average of about 5.167, which
+ is too high.
+
+ :exc:`StatisticsError` is raised if *data* is empty, or any element
+ is less than zero.
+
+ .. versionadded:: 3.6
+
+
.. function:: median(data)
Return the median (middle value) of numeric data, using the common "mean of
middle two" method. If *data* is empty, :exc:`StatisticsError` is raised.
+ *data* can be a sequence or iterator.
The median is a robust measure of central location, and is less affected by
the presence of outliers in your data. When the number of data points is
@@ -142,7 +175,7 @@ However, for reading convenience, most of the examples show sorted sequences.
.. function:: median_low(data)
Return the low median of numeric data. If *data* is empty,
- :exc:`StatisticsError` is raised.
+ :exc:`StatisticsError` is raised. *data* can be a sequence or iterator.
The low median is always a member of the data set. When the number of data
points is odd, the middle value is returned. When it is even, the smaller of
@@ -162,7 +195,7 @@ However, for reading convenience, most of the examples show sorted sequences.
.. function:: median_high(data)
Return the high median of data. If *data* is empty, :exc:`StatisticsError`
- is raised.
+ is raised. *data* can be a sequence or iterator.
The high median is always a member of the data set. When the number of data
points is odd, the middle value is returned. When it is even, the larger of
@@ -183,7 +216,7 @@ However, for reading convenience, most of the examples show sorted sequences.
Return the median of grouped continuous data, calculated as the 50th
percentile, using interpolation. If *data* is empty, :exc:`StatisticsError`
- is raised.
+ is raised. *data* can be a sequence or iterator.
.. doctest::
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index 71cb7f2..9a4f42c 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1365,6 +1365,11 @@ objects that compare equal might have different :attr:`~range.start`,
The :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step`
attributes.
+.. seealso::
+
+ * The `linspace recipe <http://code.activestate.com/recipes/579000/>`_
+ shows how to implement a lazy version of range that suitable for floating
+ point applications.
.. index::
single: string; text sequence type
@@ -1455,8 +1460,8 @@ multiple fragments.
For more information on the ``str`` class and its methods, see
:ref:`textseq` and the :ref:`string-methods` section below. To output
- formatted strings, see the :ref:`formatstrings` section. In addition,
- see the :ref:`stringservices` section.
+ formatted strings, see the :ref:`f-strings` and :ref:`formatstrings`
+ sections. In addition, see the :ref:`stringservices` section.
.. index::
@@ -2060,8 +2065,8 @@ expression support in the :mod:`re` module).
.. index::
single: formatting, string (%)
single: interpolation, string (%)
- single: string; formatting
- single: string; interpolation
+ single: string; formatting, printf
+ single: string; interpolation, printf
single: printf-style formatting
single: sprintf-style formatting
single: % formatting
@@ -2071,9 +2076,10 @@ expression support in the :mod:`re` module).
The formatting operations described here exhibit a variety of quirks that
lead to a number of common errors (such as failing to display tuples and
- dictionaries correctly). Using the newer :meth:`str.format` interface
- helps avoid these errors, and also provides a generally more powerful,
- flexible and extensible approach to formatting text.
+ dictionaries correctly). Using the newer :ref:`formatted
+ string literals <f-strings>` or the :meth:`str.format` interface
+ helps avoid these errors. These alternatives also provide more powerful,
+ flexible and extensible approaches to formatting text.
String objects have one unique built-in operation: the ``%`` operator (modulo).
This is also known as the string *formatting* or *interpolation* operator.
@@ -2630,8 +2636,8 @@ arbitrary binary data.
The prefix(es) to search for may be any :term:`bytes-like object`.
-.. method:: bytes.translate(table[, delete])
- bytearray.translate(table[, delete])
+.. method:: bytes.translate(table, delete=b'')
+ bytearray.translate(table, delete=b'')
Return a copy of the bytes or bytearray object where all bytes occurring in
the optional argument *delete* are removed, and the remaining bytes have
@@ -2647,6 +2653,9 @@ arbitrary binary data.
>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
+ .. versionchanged:: 3.6
+ *delete* is now supported as a keyword argument.
+
The following methods on bytes and bytearray objects have default behaviours
that assume the use of ASCII compatible binary formats, but can still be used
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 05418a9..a0977b6 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -188,7 +188,9 @@ Format String Syntax
The :meth:`str.format` method and the :class:`Formatter` class share the same
syntax for format strings (although in the case of :class:`Formatter`,
-subclasses can define their own format string syntax).
+subclasses can define their own format string syntax). The syntax is
+related to that of :ref:`formatted string literals <f-strings>`, but
+there are differences.
Format strings contain "replacement fields" surrounded by curly braces ``{}``.
Anything that is not contained in braces is considered literal text, which is
@@ -283,7 +285,8 @@ Format Specification Mini-Language
"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see
-:ref:`formatstrings`). They can also be passed directly to the built-in
+:ref:`formatstrings` and :ref:`f-strings`).
+They can also be passed directly to the built-in
:func:`format` function. Each formattable type may define how the format
specification is to be interpreted.
@@ -297,18 +300,20 @@ non-empty format string typically modifies the result.
The general form of a *standard format specifier* is:
.. productionlist:: sf
- format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
+ format_spec: [[`fill`]`align`][`sign`][#][0][`width`][`grouping_option`][.`precision`][`type`]
fill: <any character>
align: "<" | ">" | "=" | "^"
sign: "+" | "-" | " "
width: `integer`
+ grouping_option: "_" | ","
precision: `integer`
type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
If a valid *align* value is specified, it can be preceded by a *fill*
character that can be any character and defaults to a space if omitted.
It is not possible to use a literal curly brace ("``{``" or "``}``") as
-the *fill* character when using the :meth:`str.format`
+the *fill* character in a :ref:`formatted string literal
+<f-strings>` or when using the :meth:`str.format`
method. However, it is possible to insert a curly brace
with a nested replacement field. This limitation doesn't
affect the :func:`format` function.
@@ -374,6 +379,16 @@ instead.
.. versionchanged:: 3.1
Added the ``','`` option (see also :pep:`378`).
+The ``'_'`` option signals the use of an underscore for a thousands
+separator for floating point presentation types and for integer
+presentation type ``'d'``. For integer presentation types ``'b'``,
+``'o'``, ``'x'``, and ``'X'``, underscores will be inserted every 4
+digits. For other presentation types, specifying this option is an
+error.
+
+.. versionchanged:: 3.6
+ Added the ``'_'`` option (see also :pep:`515`).
+
*width* is a decimal integer defining the minimum field width. If not
specified, then the field width will be determined by the content.
diff --git a/Doc/library/struct.rst b/Doc/library/struct.rst
index ae2e38f..cc3017b 100644
--- a/Doc/library/struct.rst
+++ b/Doc/library/struct.rst
@@ -216,6 +216,8 @@ platform-dependent.
+--------+--------------------------+--------------------+----------------+------------+
| ``N`` | :c:type:`size_t` | integer | | \(4) |
+--------+--------------------------+--------------------+----------------+------------+
+| ``e`` | \(7) | float | 2 | \(5) |
++--------+--------------------------+--------------------+----------------+------------+
| ``f`` | :c:type:`float` | float | 4 | \(5) |
+--------+--------------------------+--------------------+----------------+------------+
| ``d`` | :c:type:`double` | float | 8 | \(5) |
@@ -230,6 +232,10 @@ platform-dependent.
.. versionchanged:: 3.3
Added support for the ``'n'`` and ``'N'`` formats.
+.. versionchanged:: 3.6
+ Added support for the ``'e'`` format.
+
+
Notes:
(1)
@@ -257,9 +263,10 @@ Notes:
fits your application.
(5)
- For the ``'f'`` and ``'d'`` conversion codes, the packed representation uses
- the IEEE 754 binary32 (for ``'f'``) or binary64 (for ``'d'``) format,
- regardless of the floating-point format used by the platform.
+ For the ``'f'``, ``'d'`` and ``'e'`` conversion codes, the packed
+ representation uses the IEEE 754 binary32, binary64 or binary16 format (for
+ ``'f'``, ``'d'`` or ``'e'`` respectively), regardless of the floating-point
+ format used by the platform.
(6)
The ``'P'`` format character is only available for the native byte ordering
@@ -268,6 +275,16 @@ Notes:
on the host system. The struct module does not interpret this as native
ordering, so the ``'P'`` format is not available.
+(7)
+ The IEEE 754 binary16 "half precision" type was introduced in the 2008
+ revision of the `IEEE 754 standard <ieee 754 standard_>`_. It has a sign
+ bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored),
+ and can represent numbers between approximately ``6.1e-05`` and ``6.5e+04``
+ at full precision. This type is not widely supported by C compilers: on a
+ typical machine, an unsigned short can be used for storage, but not for math
+ operations. See the Wikipedia page on the `half-precision floating-point
+ format <half precision format_>`_ for more information.
+
A format character may be preceded by an integral repeat count. For example,
the format string ``'4h'`` means exactly the same as ``'hhhh'``.
@@ -430,3 +447,7 @@ The :mod:`struct` module also defines the following type:
The calculated size of the struct (and hence of the bytes object produced
by the :meth:`pack` method) corresponding to :attr:`format`.
+
+.. _half precision format: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
+
+.. _ieee 754 standard: https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008
diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst
index c1b28f8..ad2abe8 100644
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -38,7 +38,8 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\
- shell=False, timeout=None, check=False)
+ shell=False, timeout=None, check=False, \
+ encoding=None, errors=None)
Run the command described by *args*. Wait for command to complete, then
return a :class:`CompletedProcess` instance.
@@ -60,15 +61,20 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
The *input* argument is passed to :meth:`Popen.communicate` and thus to the
subprocess's stdin. If used it must be a byte sequence, or a string if
- ``universal_newlines=True``. When used, the internal :class:`Popen` object
- is automatically created with ``stdin=PIPE``, and the *stdin* argument may
- not be used as well.
+ *encoding* or *errors* is specified or *universal_newlines* is true. When
+ used, the internal :class:`Popen` object is automatically created with
+ ``stdin=PIPE``, and the *stdin* argument may not be used as well.
If *check* is true, and the process exits with a non-zero exit code, a
:exc:`CalledProcessError` exception will be raised. Attributes of that
exception hold the arguments, the exit code, and stdout and stderr if they
were captured.
+ If *encoding* or *errors* are specified, or *universal_newlines* is true,
+ file objects for stdin, stdout and stderr are opened in text mode using the
+ specified *encoding* and *errors* or the :class:`io.TextIOWrapper` default.
+ Otherwise, file objects are opened in binary mode.
+
Examples::
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
@@ -85,6 +91,10 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
.. versionadded:: 3.5
+ .. versionchanged:: 3.6
+
+ Added *encoding* and *errors* parameters
+
.. class:: CompletedProcess
The return value from :func:`run`, representing a process that has finished.
@@ -104,8 +114,8 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
.. attribute:: stdout
Captured stdout from the child process. A bytes sequence, or a string if
- :func:`run` was called with ``universal_newlines=True``. ``None`` if stdout
- was not captured.
+ :func:`run` was called with an encoding or errors. ``None`` if stdout was not
+ captured.
If you ran the process with ``stderr=subprocess.STDOUT``, stdout and
stderr will be combined in this attribute, and :attr:`stderr` will be
@@ -114,8 +124,8 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
.. attribute:: stderr
Captured stderr from the child process. A bytes sequence, or a string if
- :func:`run` was called with ``universal_newlines=True``. ``None`` if stderr
- was not captured.
+ :func:`run` was called with an encoding or errors. ``None`` if stderr was not
+ captured.
.. method:: check_returncode()
@@ -249,19 +259,22 @@ default values. The arguments that are most commonly needed are:
.. index::
single: universal newlines; subprocess module
- If *universal_newlines* is ``False`` the file objects *stdin*, *stdout* and
- *stderr* will be opened as binary streams, and no line ending conversion is
- done.
+ If *encoding* or *errors* are specified, or *universal_newlines* is true,
+ the file objects *stdin*, *stdout* and *stderr* will be opened in text
+ mode using the *encoding* and *errors* specified in the call or the
+ defaults for :class:`io.TextIOWrapper`.
+
+ For *stdin*, line ending characters ``'\n'`` in the input will be converted
+ to the default line separator :data:`os.linesep`. For *stdout* and *stderr*,
+ all line endings in the output will be converted to ``'\n'``. For more
+ information see the documentation of the :class:`io.TextIOWrapper` class
+ when the *newline* argument to its constructor is ``None``.
- If *universal_newlines* is ``True``, these file objects
- will be opened as text streams in :term:`universal newlines` mode
- using the encoding returned by :func:`locale.getpreferredencoding(False)
- <locale.getpreferredencoding>`. For *stdin*, line ending characters
- ``'\n'`` in the input will be converted to the default line separator
- :data:`os.linesep`. For *stdout* and *stderr*, all line endings in the
- output will be converted to ``'\n'``. For more information see the
- documentation of the :class:`io.TextIOWrapper` class when the *newline*
- argument to its constructor is ``None``.
+ If text mode is not used, *stdin*, *stdout* and *stderr* will be opened as
+ binary streams. No encoding or line ending conversion is performed.
+
+ .. versionadded:: 3.6
+ Added *encoding* and *errors* parameters.
.. note::
@@ -306,7 +319,8 @@ functions.
stderr=None, preexec_fn=None, close_fds=True, shell=False, \
cwd=None, env=None, universal_newlines=False, \
startupinfo=None, creationflags=0, restore_signals=True, \
- start_new_session=False, pass_fds=())
+ start_new_session=False, pass_fds=(), *, \
+ encoding=None, errors=None)
Execute a child program in a new process. On POSIX, the class uses
:meth:`os.execvp`-like behavior to execute the child program. On Windows,
@@ -482,10 +496,14 @@ functions.
.. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly
- If *universal_newlines* is ``True``, the file objects *stdin*, *stdout*
- and *stderr* are opened as text streams in universal newlines mode, as
- described above in :ref:`frequently-used-arguments`, otherwise they are
- opened as binary streams.
+ If *encoding* or *errors* are specified, the file objects *stdin*, *stdout*
+ and *stderr* are opened in text mode with the specified encoding and
+ *errors*, as described above in :ref:`frequently-used-arguments`. If
+ *universal_newlines* is ``True``, they are opened in text mode with default
+ encoding. Otherwise, they are opened as binary streams.
+
+ .. versionadded:: 3.6
+ *encoding* and *errors* were added.
If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
passed to the underlying ``CreateProcess`` function.
@@ -502,6 +520,10 @@ functions.
.. versionchanged:: 3.2
Added context manager support.
+ .. versionchanged:: 3.6
+ Popen destructor now emits a :exc:`ResourceWarning` warning if the child
+ process is still running.
+
Exceptions
^^^^^^^^^^
@@ -597,11 +619,12 @@ Instances of the :class:`Popen` class have the following methods:
Interact with process: Send data to stdin. Read data from stdout and stderr,
until end-of-file is reached. Wait for process to terminate. The optional
*input* argument should be data to be sent to the child process, or
- ``None``, if no data should be sent to the child. The type of *input*
- must be bytes or, if *universal_newlines* was ``True``, a string.
+ ``None``, if no data should be sent to the child. If streams were opened in
+ text mode, *input* must be a string. Otherwise, it must be bytes.
:meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``.
- The data will be bytes or, if *universal_newlines* was ``True``, strings.
+ The data will be strings if streams were opened in text mode; otherwise,
+ bytes.
Note that if you want to send data to the process's stdin, you need to create
the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
@@ -668,28 +691,30 @@ The following attributes are also available:
.. attribute:: Popen.stdin
If the *stdin* argument was :data:`PIPE`, this attribute is a writeable
- stream object as returned by :func:`open`. If the *universal_newlines*
- argument was ``True``, the stream is a text stream, otherwise it is a byte
- stream. If the *stdin* argument was not :data:`PIPE`, this attribute is
- ``None``.
+ stream object as returned by :func:`open`. If the *encoding* or *errors*
+ arguments were specified or the *universal_newlines* argument was ``True``,
+ the stream is a text stream, otherwise it is a byte stream. If the *stdin*
+ argument was not :data:`PIPE`, this attribute is ``None``.
.. attribute:: Popen.stdout
If the *stdout* argument was :data:`PIPE`, this attribute is a readable
stream object as returned by :func:`open`. Reading from the stream provides
- output from the child process. If the *universal_newlines* argument was
- ``True``, the stream is a text stream, otherwise it is a byte stream. If the
- *stdout* argument was not :data:`PIPE`, this attribute is ``None``.
+ output from the child process. If the *encoding* or *errors* arguments were
+ specified or the *universal_newlines* argument was ``True``, the stream is a
+ text stream, otherwise it is a byte stream. If the *stdout* argument was not
+ :data:`PIPE`, this attribute is ``None``.
.. attribute:: Popen.stderr
If the *stderr* argument was :data:`PIPE`, this attribute is a readable
stream object as returned by :func:`open`. Reading from the stream provides
- error output from the child process. If the *universal_newlines* argument was
- ``True``, the stream is a text stream, otherwise it is a byte stream. If the
- *stderr* argument was not :data:`PIPE`, this attribute is ``None``.
+ error output from the child process. If the *encoding* or *errors* arguments
+ were specified or the *universal_newlines* argument was ``True``, the stream
+ is a text stream, otherwise it is a byte stream. If the *stderr* argument was
+ not :data:`PIPE`, this attribute is ``None``.
.. warning::
@@ -882,7 +907,9 @@ calls these functions.
*timeout* was added.
-.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None)
+.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \
+ encoding=None, errors=None, \
+ universal_newlines=False, timeout=None)
Run command with arguments and return its output.
@@ -1138,7 +1165,7 @@ handling consistency are valid for these functions.
Return ``(status, output)`` of executing *cmd* in a shell.
Execute the string *cmd* in a shell with :meth:`Popen.check_output` and
- return a 2-tuple ``(status, output)``. Universal newlines mode is used;
+ return a 2-tuple ``(status, output)``. The locale encoding is used;
see the notes on :ref:`frequently-used-arguments` for more details.
A trailing newline is stripped from the output.
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index d28ea5d..dd51ffd 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -269,6 +269,11 @@ always available.
the process when called from the main thread, and the exception is not
intercepted.
+ .. versionchanged:: 3.6
+ If an error occurs in the cleanup after the Python interpreter
+ has caught :exc:`SystemExit` (such as an error flushing buffered data
+ in the standard streams), the exit status is changed to 120.
+
.. data:: flags
@@ -423,25 +428,42 @@ always available.
.. function:: getfilesystemencoding()
- Return the name of the encoding used to convert Unicode filenames into
- system file names. The result value depends on the operating system:
+ Return the name of the encoding used to convert between Unicode
+ filenames and bytes filenames. For best compatibility, str should be
+ used for filenames in all cases, although representing filenames as bytes
+ is also supported. Functions accepting or returning filenames should support
+ either str or bytes and internally convert to the system's preferred
+ representation.
- * On Mac OS X, the encoding is ``'utf-8'``.
+ This encoding is always ASCII-compatible.
- * On Unix, the encoding is the user's preference according to the result of
- nl_langinfo(CODESET).
+ :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that
+ the correct encoding and errors mode are used.
+
+ * On Mac OS X, the encoding is ``'utf-8'``.
- * On Windows NT+, file names are Unicode natively, so no conversion is
- performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
- this is the encoding that applications should use when they explicitly
- want to convert Unicode strings to byte strings that are equivalent when
- used as file names.
+ * On Unix, the encoding is the locale encoding.
- * On Windows 9x, the encoding is ``'mbcs'``.
+ * On Windows, the encoding may be ``'utf-8'`` or ``'mbcs'``, depending
+ on user configuration.
.. versionchanged:: 3.2
:func:`getfilesystemencoding` result cannot be ``None`` anymore.
+ .. versionchanged:: 3.6
+ Windows is no longer guaranteed to return ``'mbcs'``. See :pep:`529`
+ and :func:`_enablelegacywindowsfsencoding` for more information.
+
+.. function:: getfilesystemencodeerrors()
+
+ Return the name of the error mode used to convert between Unicode filenames
+ and bytes filenames. The encoding name is returned from
+ :func:`getfilesystemencoding`.
+
+ :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that
+ the correct encoding and errors mode are used.
+
+ .. versionadded:: 3.6
.. function:: getrefcount(object)
@@ -530,26 +552,15 @@ always available.
Return a named tuple describing the Windows version
currently running. The named elements are *major*, *minor*,
*build*, *platform*, *service_pack*, *service_pack_minor*,
- *service_pack_major*, *suite_mask*, and *product_type*.
- *service_pack* contains a string while all other values are
+ *service_pack_major*, *suite_mask*, *product_type* and
+ *platform_version*. *service_pack* contains a string,
+ *platform_version* a 3-tuple and all other values are
integers. The components can also be accessed by name, so
``sys.getwindowsversion()[0]`` is equivalent to
``sys.getwindowsversion().major``. For compatibility with prior
versions, only the first 5 elements are retrievable by indexing.
- *platform* may be one of the following values:
-
- +-----------------------------------------+-------------------------+
- | Constant | Platform |
- +=========================================+=========================+
- | :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
- +-----------------------------------------+-------------------------+
- | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
- +-----------------------------------------+-------------------------+
- | :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
- +-----------------------------------------+-------------------------+
- | :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
- +-----------------------------------------+-------------------------+
+ *platform* will be :const:`2 (VER_PLATFORM_WIN32_NT)`.
*product_type* may be one of the following values:
@@ -565,17 +576,41 @@ always available.
| | a domain controller. |
+---------------------------------------+---------------------------------+
-
This function wraps the Win32 :c:func:`GetVersionEx` function; see the
Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information
about these fields.
+ *platform_version* returns the accurate major version, minor version and
+ build number of the current operating system, rather than the version that
+ is being emulated for the process. It is intended for use in logging rather
+ than for feature detection.
+
Availability: Windows.
.. versionchanged:: 3.2
Changed to a named tuple and added *service_pack_minor*,
*service_pack_major*, *suite_mask*, and *product_type*.
+ .. versionchanged:: 3.6
+ Added *platform_version*
+
+
+.. function:: get_asyncgen_hooks()
+
+ Returns an *asyncgen_hooks* object, which is similar to a
+ :class:`~collections.namedtuple` of the form `(firstiter, finalizer)`,
+ where *firstiter* and *finalizer* are expected to be either ``None`` or
+ functions which take an :term:`asynchronous generator iterator` as an
+ argument, and are used to schedule finalization of an asychronous
+ generator by an event loop.
+
+ .. versionadded:: 3.6
+ See :pep:`525` for more details.
+
+ .. note::
+ This function has been added on a provisional basis (see :pep:`411`
+ for details.)
+
.. function:: get_coroutine_wrapper()
@@ -1081,17 +1116,23 @@ always available.
implementation platform, rather than part of the language definition, and
thus may not be available in all Python implementations.
+.. function:: set_asyncgen_hooks(firstiter, finalizer)
-.. function:: settscdump(on_flag)
+ Accepts two optional keyword arguments which are callables that accept an
+ :term:`asynchronous generator iterator` as an argument. The *firstiter*
+ callable will be called when an asynchronous generator is iterated for the
+ first time. The *finalizer* will be called when an asynchronous generator
+ is about to be garbage collected.
- Activate dumping of VM measurements using the Pentium timestamp counter, if
- *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
- available only if Python was compiled with ``--with-tsc``. To understand
- the output of this dump, read :file:`Python/ceval.c` in the Python sources.
+ .. versionadded:: 3.6
+ See :pep:`525` for more details, and for a reference example of a
+ *finalizer* method see the implementation of
+ ``asyncio.Loop.shutdown_asyncgens`` in
+ :source:`Lib/asyncio/base_events.py`
- .. impl-detail::
- This function is intimately bound to CPython implementation details and
- thus not likely to be implemented elsewhere.
+ .. note::
+ This function has been added on a provisional basis (see :pep:`411`
+ for details.)
.. function:: set_coroutine_wrapper(wrapper)
@@ -1133,6 +1174,18 @@ always available.
This function has been added on a provisional basis (see :pep:`411`
for details.) Use it only for debugging purposes.
+.. function:: _enablelegacywindowsfsencoding()
+
+ Changes the default filesystem encoding and errors mode to 'mbcs' and
+ 'replace' respectively, for consistency with versions of Python prior to 3.6.
+
+ This is equivalent to defining the :envvar:`PYTHONLEGACYWINDOWSFSENCODING`
+ environment variable before launching Python.
+
+ Availability: Windows
+
+ .. versionadded:: 3.6
+ See :pep:`529` for more details.
.. data:: stdin
stdout
diff --git a/Doc/library/sysconfig.rst b/Doc/library/sysconfig.rst
index 02aaab3..08b74a9 100644
--- a/Doc/library/sysconfig.rst
+++ b/Doc/library/sysconfig.rst
@@ -164,7 +164,7 @@ Other functions
.. function:: get_python_version()
Return the ``MAJOR.MINOR`` Python version number as a string. Similar to
- ``sys.version[:3]``.
+ ``'%d.%d' % sys.version_info[:2]``.
.. function:: get_platform()
diff --git a/Doc/library/telnetlib.rst b/Doc/library/telnetlib.rst
index b950e41..f9c5153 100644
--- a/Doc/library/telnetlib.rst
+++ b/Doc/library/telnetlib.rst
@@ -43,6 +43,17 @@ Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
:exc:`EOFError` when the end of the connection is read, because they can return
an empty string for other reasons. See the individual descriptions below.
+ A :class:`Telnet` object is a context manager and can be used in a
+ :keyword:`with` statement. When the :keyword:`with` block ends, the
+ :meth:`close` method is called::
+
+ >>> from telnetlib import Telnet
+ >>> with Telnet('localhost', 23) as tn:
+ ... tn.interact()
+ ...
+
+ .. versionchanged:: 3.6 Context manager support added
+
.. seealso::
diff --git a/Doc/library/test.rst b/Doc/library/test.rst
index 59577f0..fab3e1f 100644
--- a/Doc/library/test.rst
+++ b/Doc/library/test.rst
@@ -582,6 +582,48 @@ The :mod:`test.support` module defines the following functions:
.. versionadded:: 3.5
+.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
+
+ Assert that the ``__all__`` variable of *module* contains all public names.
+
+ The module's public names (its API) are detected automatically
+ based on whether they match the public name convention and were defined in
+ *module*.
+
+ The *name_of_module* argument can specify (as a string or tuple thereof) what
+ module(s) an API could be defined in in order to be detected as a public
+ API. One case for this is when *module* imports part of its public API from
+ other modules, possibly a C backend (like ``csv`` and its ``_csv``).
+
+ The *extra* argument can be a set of names that wouldn't otherwise be automatically
+ detected as "public", like objects without a proper ``__module__``
+ attribute. If provided, it will be added to the automatically detected ones.
+
+ The *blacklist* argument can be a set of names that must not be treated as part of
+ the public API even though their names indicate otherwise.
+
+ Example use::
+
+ import bar
+ import foo
+ import unittest
+ from test import support
+
+ class MiscTestCase(unittest.TestCase):
+ def test__all__(self):
+ support.check__all__(self, foo)
+
+ class OtherTestCase(unittest.TestCase):
+ def test__all__(self):
+ extra = {'BAR_CONST', 'FOO_CONST'}
+ blacklist = {'baz'} # Undocumented name.
+ # bar imports part of its API from _bar.
+ support.check__all__(self, bar, ('bar', '_bar'),
+ extra=extra, blacklist=blacklist)
+
+ .. versionadded:: 3.6
+
+
The :mod:`test.support` module defines the following classes:
.. class:: TransientResource(exc, **kwargs)
diff --git a/Doc/library/time.rst b/Doc/library/time.rst
index e6626f2..ae17f6f 100644
--- a/Doc/library/time.rst
+++ b/Doc/library/time.rst
@@ -83,6 +83,10 @@ An explanation of some terminology and conventions is in order.
and :attr:`tm_zone` attributes when platform supports corresponding
``struct tm`` members.
+ .. versionchanged:: 3.6
+ The :class:`struct_time` attributes :attr:`tm_gmtoff` and :attr:`tm_zone`
+ are now available on all platforms.
+
* Use the following functions to convert between time representations:
+-------------------------+-------------------------+-------------------------+
@@ -566,10 +570,6 @@ The module defines the following functions and data items:
:class:`struct_time`, or having elements of the wrong type, a
:exc:`TypeError` is raised.
- .. versionchanged:: 3.3
- :attr:`tm_gmtoff` and :attr:`tm_zone` attributes are available on platforms
- with C library supporting the corresponding fields in ``struct tm``.
-
.. function:: time()
Return the time in seconds since the epoch as a floating point number.
@@ -637,11 +637,11 @@ The module defines the following functions and data items:
it is possible to refer to February 29.
:samp:`M{m}.{n}.{d}`
- The *d*'th day (0 <= *d* <= 6) or week *n* of month *m* of the year (1
+ The *d*'th day (0 <= *d* <= 6) of week *n* of month *m* of the year (1
<= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in
month *m*" which may occur in either the fourth or the fifth
week). Week 1 is the first week in which the *d*'th day occurs. Day
- zero is Sunday.
+ zero is a Sunday.
``time`` has the same format as ``offset`` except that no leading sign
('-' or '+') is allowed. The default, if time is not given, is 02:00:00.
diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst
index 57a4834..3b77276 100644
--- a/Doc/library/timeit.rst
+++ b/Doc/library/timeit.rst
@@ -100,8 +100,8 @@ The module defines three convenience functions and a public class:
can be controlled by passing a namespace to *globals*.
To measure the execution time of the first statement, use the :meth:`.timeit`
- method. The :meth:`.repeat` method is a convenience to call :meth:`.timeit`
- multiple times and return a list of results.
+ method. The :meth:`.repeat` and :meth:`.autorange` methods are convenience
+ methods to call :meth:`.timeit` multiple times.
The execution time of *setup* is excluded from the overall timed execution run.
@@ -134,6 +134,23 @@ The module defines three convenience functions and a public class:
timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
+ .. method:: Timer.autorange(callback=None)
+
+ Automatically determine how many times to call :meth:`.timeit`.
+
+ This is a convenience function that calls :meth:`.timeit` repeatedly
+ so that the total time >= 0.2 second, returning the eventual
+ (number of loops, time taken for that number of loops). It calls
+ :meth:`.timeit` with *number* set to successive powers of ten (10,
+ 100, 1000, ...) up to a maximum of one billion, until the time taken
+ is at least 0.2 second, or the maximum is reached.
+
+ If *callback* is given and is not ``None``, it will be called after
+ each trial with two arguments: ``callback(number, time_taken)``.
+
+ .. versionadded:: 3.6
+
+
.. method:: Timer.repeat(repeat=3, number=1000000)
Call :meth:`.timeit` a few times.
diff --git a/Doc/library/tkinter.tix.rst b/Doc/library/tkinter.tix.rst
index 41f20dd..11ed755 100644
--- a/Doc/library/tkinter.tix.rst
+++ b/Doc/library/tkinter.tix.rst
@@ -10,6 +10,10 @@
.. index:: single: Tix
+.. deprecated:: 3.6
+ This Tk extension is unmaintained and should not be used in new code. Use
+ :mod:`tkinter.ttk` instead.
+
--------------
The :mod:`tkinter.tix` (Tk Interface Extension) module provides an additional
diff --git a/Doc/library/traceback.rst b/Doc/library/traceback.rst
index 3c1d9bb..066ee96 100644
--- a/Doc/library/traceback.rst
+++ b/Doc/library/traceback.rst
@@ -291,6 +291,20 @@ capture data for later printing in a lightweight fashion.
of tuples. Each tuple should be a 4-tuple with filename, lineno, name,
line as the elements.
+ .. method:: format()
+
+ Returns a list of strings ready for printing. Each string in the
+ resulting list corresponds to a single frame from the stack.
+ Each string ends in a newline; the strings may contain internal
+ newlines as well, for those items with source text lines.
+
+ For long sequences of the same frame and line, the first few
+ repetitions are shown, followed by a summary line stating the exact
+ number of further repetitions.
+
+ .. versionchanged:: 3.6
+ Long sequences of repeated frames are now abbreviated.
+
:class:`FrameSummary` Objects
-----------------------------
diff --git a/Doc/library/tracemalloc.rst b/Doc/library/tracemalloc.rst
index 2c8ad0e..e165669 100644
--- a/Doc/library/tracemalloc.rst
+++ b/Doc/library/tracemalloc.rst
@@ -359,10 +359,32 @@ Functions
See also the :func:`get_object_traceback` function.
+DomainFilter
+^^^^^^^^^^^^
+
+.. class:: DomainFilter(inclusive: bool, domain: int)
+
+ Filter traces of memory blocks by their address space (domain).
+
+ .. versionadded:: 3.6
+
+ .. attribute:: inclusive
+
+ If *inclusive* is ``True`` (include), match memory blocks allocated
+ in the address space :attr:`domain`.
+
+ If *inclusive* is ``False`` (exclude), match memory blocks not allocated
+ in the address space :attr:`domain`.
+
+ .. attribute:: domain
+
+ Address space of a memory block (``int``). Read-only property.
+
+
Filter
^^^^^^
-.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False)
+.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)
Filter on traces of memory blocks.
@@ -382,9 +404,17 @@ Filter
.. versionchanged:: 3.5
The ``'.pyo'`` file extension is no longer replaced with ``'.py'``.
+ .. versionchanged:: 3.6
+ Added the :attr:`domain` attribute.
+
+
+ .. attribute:: domain
+
+ Address space of a memory block (``int`` or ``None``).
+
.. attribute:: inclusive
- If *inclusive* is ``True`` (include), only trace memory blocks allocated
+ If *inclusive* is ``True`` (include), only match memory blocks allocated
in a file with a name matching :attr:`filename_pattern` at line number
:attr:`lineno`.
@@ -399,7 +429,7 @@ Filter
.. attribute:: filename_pattern
- Filename pattern of the filter (``str``).
+ Filename pattern of the filter (``str``). Read-only property.
.. attribute:: all_frames
@@ -462,14 +492,17 @@ Snapshot
.. method:: filter_traces(filters)
Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
- sequence, *filters* is a list of :class:`Filter` instances. If *filters*
- is an empty list, return a new :class:`Snapshot` instance with a copy of
- the traces.
+ sequence, *filters* is a list of :class:`DomainFilter` and
+ :class:`Filter` instances. If *filters* is an empty list, return a new
+ :class:`Snapshot` instance with a copy of the traces.
All inclusive filters are applied at once, a trace is ignored if no
inclusive filters match it. A trace is ignored if at least one exclusive
filter matches it.
+ .. versionchanged:: 3.6
+ :class:`DomainFilter` instances are now also accepted in *filters*.
+
.. classmethod:: load(filename)
diff --git a/Doc/library/types.rst b/Doc/library/types.rst
index 118bc4c..0c5619c 100644
--- a/Doc/library/types.rst
+++ b/Doc/library/types.rst
@@ -55,6 +55,12 @@ Dynamic Type Creation
.. versionadded:: 3.3
+ .. versionchanged:: 3.6
+
+ The default value for the ``namespace`` element of the returned
+ tuple has changed. Now an insertion-order-preserving mapping is
+ used when the metaclass does not have a ``__prepare__`` method,
+
.. seealso::
:ref:`metaclasses`
@@ -98,6 +104,14 @@ Standard names are defined for the following types:
.. versionadded:: 3.5
+.. data:: AsyncGeneratorType
+
+ The type of :term:`asynchronous generator`-iterator objects, created by
+ asynchronous generator functions.
+
+ .. versionadded:: 3.6
+
+
.. data:: CodeType
.. index:: builtin: compile
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index 923cbb8..2bac6f8 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -10,8 +10,8 @@
--------------
-This module supports type hints as specified by :pep:`484`. The most
-fundamental support consists of the types :data:`Any`, :data:`Union`,
+This module supports type hints as specified by :pep:`484` and :pep:`526`.
+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
a simplified introduction to type hints see :pep:`483`.
@@ -523,7 +523,13 @@ The module defines the following classes, functions and decorators:
An alias to :class:`collections.abc.Sized`
-.. class:: AbstractSet(Sized, Iterable[T_co], Container[T_co])
+.. class:: Collection(Sized, Iterable[T_co], Container[T_co])
+
+ A generic version of :class:`collections.abc.Collection`
+
+ .. versionadded:: 3.6
+
+.. class:: AbstractSet(Sized, Collection[T_co])
A generic version of :class:`collections.abc.Set`.
@@ -531,7 +537,7 @@ The module defines the following classes, functions and decorators:
A generic version of :class:`collections.abc.MutableSet`.
-.. class:: Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co])
+.. class:: Mapping(Sized, Collection[KT], Generic[VT_co])
A generic version of :class:`collections.abc.Mapping`.
@@ -539,7 +545,7 @@ The module defines the following classes, functions and decorators:
A generic version of :class:`collections.abc.MutableMapping`.
-.. class:: Sequence(Sized, Iterable[T_co], Container[T_co])
+.. class:: Sequence(Reversible[T_co], Collection[T_co])
A generic version of :class:`collections.abc.Sequence`.
@@ -623,6 +629,12 @@ The module defines the following classes, functions and decorators:
A generic version of :class:`collections.abc.AsyncIterator`.
+.. class:: ContextManager(Generic[T_co])
+
+ A generic version of :class:`contextlib.AbstractContextManager`.
+
+ .. versionadded:: 3.6
+
.. class:: Dict(dict, MutableMapping[KT, VT])
A generic version of :class:`dict`.
@@ -698,23 +710,32 @@ The module defines the following classes, functions and decorators:
``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or
``Match[bytes]``.
-.. function:: NamedTuple(typename, fields)
+.. class:: NamedTuple
Typed version of namedtuple.
Usage::
- Employee = typing.NamedTuple('Employee', [('name', str), ('id', int)])
+ class Employee(NamedTuple):
+ name: str
+ id: int
This is equivalent to::
Employee = collections.namedtuple('Employee', ['name', 'id'])
- The resulting class has one extra attribute: _field_types,
+ The resulting class has one extra attribute: ``_field_types``,
giving a dict mapping field names to types. (The field names
- are in the _fields attribute, which is part of the namedtuple
+ are in the ``_fields`` attribute, which is part of the namedtuple
API.)
+ Backward-compatible usage::
+
+ Employee = NamedTuple('Employee', [('name', str), ('id', int)])
+
+ .. versionchanged:: 3.6
+ Added support for :pep:`526` variable annotation syntax.
+
.. function:: NewType(typ)
A helper function to indicate a distinct types to a typechecker,
@@ -884,8 +905,8 @@ The module defines the following classes, functions and decorators:
and should not be set on instances of that class. Usage::
class Starship:
- stats = {} # type: ClassVar[Dict[str, int]] # class variable
- damage = 10 # type: int # instance variable
+ stats: ClassVar[Dict[str, int]] = {} # class variable
+ damage: int = 10 # instance variable
:data:`ClassVar` accepts only types and cannot be further subscribed.
diff --git a/Doc/library/undoc.rst b/Doc/library/undoc.rst
index 20830e2..2444080 100644
--- a/Doc/library/undoc.rst
+++ b/Doc/library/undoc.rst
@@ -20,7 +20,7 @@ These modules are used to implement the :mod:`os.path` module, and are not
documented beyond this mention. There's little need to document these.
:mod:`ntpath`
- --- Implementation of :mod:`os.path` on Win32, Win64, and WinCE platforms.
+ --- Implementation of :mod:`os.path` on Win32 and Win64 platforms.
:mod:`posixpath`
--- Implementation of :mod:`os.path` on POSIX.
diff --git a/Doc/library/unicodedata.rst b/Doc/library/unicodedata.rst
index 6cd8132..6431809 100644
--- a/Doc/library/unicodedata.rst
+++ b/Doc/library/unicodedata.rst
@@ -17,8 +17,8 @@
This module provides access to the Unicode Character Database (UCD) which
defines character properties for all Unicode characters. The data contained in
-this database is compiled from the `UCD version 8.0.0
-<http://www.unicode.org/Public/8.0.0/ucd>`_.
+this database is compiled from the `UCD version 9.0.0
+<http://www.unicode.org/Public/9.0.0/ucd>`_.
The module uses the same names and symbols as defined by Unicode
Standard Annex #44, `"Unicode Character Database"
@@ -168,6 +168,6 @@ Examples:
.. rubric:: Footnotes
-.. [#] http://www.unicode.org/Public/8.0.0/ucd/NameAliases.txt
+.. [#] http://www.unicode.org/Public/9.0.0/ucd/NameAliases.txt
-.. [#] http://www.unicode.org/Public/8.0.0/ucd/NamedSequences.txt
+.. [#] http://www.unicode.org/Public/9.0.0/ucd/NamedSequences.txt
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst
index ef30c01..3cc22fd 100644
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -262,6 +262,34 @@ the *new_callable* argument to :func:`patch`.
used to set attributes on the mock after it is created. See the
:meth:`configure_mock` method for details.
+ .. method:: assert_called(*args, **kwargs)
+
+ Assert that the mock was called at least once.
+
+ >>> mock = Mock()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called()
+
+ .. versionadded:: 3.6
+
+ .. method:: assert_called_once(*args, **kwargs)
+
+ Assert that the mock was called exactly once.
+
+ >>> mock = Mock()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called_once()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called_once()
+ Traceback (most recent call last):
+ ...
+ AssertionError: Expected 'method' to have been called once. Called 2 times.
+
+ .. versionadded:: 3.6
+
.. method:: assert_called_with(*args, **kwargs)
@@ -339,7 +367,7 @@ the *new_callable* argument to :func:`patch`.
.. versionadded:: 3.5
- .. method:: reset_mock()
+ .. method:: reset_mock(*, return_value=False, side_effect=False)
The reset_mock method resets all the call attributes on a mock object:
@@ -351,12 +379,20 @@ the *new_callable* argument to :func:`patch`.
>>> mock.called
False
+ .. versionchanged:: 3.6
+ Added two keyword only argument to the reset_mock function.
+
This can be useful where you want to make a series of assertions that
reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
return value, :attr:`side_effect` or any child attributes you have
- set using normal assignment. Child mocks and the return value mock
+ set using normal assignment by default. In case you want to reset
+ *return_value* or :attr:`side_effect`, then pass the corresponding
+ parameter as ``True``. Child mocks and the return value mock
(if any) are reset as well.
+ .. note:: *return_value*, and :attr:`side_effect` are keyword only
+ argument.
+
.. method:: mock_add_spec(spec, spec_set=False)
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index ac1224c..c13a731 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -1391,9 +1391,9 @@ Test cases
Add a function to be called after :meth:`tearDown` to cleanup resources
used during the test. Functions will be called in reverse order to the
- order they are added (LIFO). They are called with any arguments and
- keyword arguments passed into :meth:`addCleanup` when they are
- added.
+ order they are added (:abbr:`LIFO (last-in, first-out)`). They
+ are called with any arguments and keyword arguments passed into
+ :meth:`addCleanup` when they are added.
If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
then any cleanup functions added will still be called.
diff --git a/Doc/library/urllib.parse.rst b/Doc/library/urllib.parse.rst
index 499b211..676321b 100644
--- a/Doc/library/urllib.parse.rst
+++ b/Doc/library/urllib.parse.rst
@@ -114,8 +114,9 @@ or on combining URL components into a URL string.
| | | if present | |
+------------------+-------+--------------------------+----------------------+
- See section :ref:`urlparse-result-object` for more information on the result
- object.
+ Reading the :attr:`port` attribute will raise a :exc:`ValueError` if
+ an invalid port is specified in the URL. See section
+ :ref:`urlparse-result-object` for more information on the result object.
.. versionchanged:: 3.2
Added IPv6 URL parsing capabilities.
@@ -125,6 +126,10 @@ or on combining URL components into a URL string.
false), in accordance with :rfc:`3986`. Previously, a whitelist of
schemes that support fragments existed.
+ .. versionchanged:: 3.6
+ Out-of-range port numbers now raise :exc:`ValueError`, instead of
+ returning :const:`None`.
+
.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
@@ -227,8 +232,13 @@ or on combining URL components into a URL string.
| | | if present | |
+------------------+-------+-------------------------+----------------------+
- See section :ref:`urlparse-result-object` for more information on the result
- object.
+ Reading the :attr:`port` attribute will raise a :exc:`ValueError` if
+ an invalid port is specified in the URL. See section
+ :ref:`urlparse-result-object` for more information on the result object.
+
+ .. versionchanged:: 3.6
+ Out-of-range port numbers now raise :exc:`ValueError`, instead of
+ returning :const:`None`.
.. function:: urlunsplit(parts)
diff --git a/Doc/library/urllib.request.rst b/Doc/library/urllib.request.rst
index 618c69d..473effc 100644
--- a/Doc/library/urllib.request.rst
+++ b/Doc/library/urllib.request.rst
@@ -30,18 +30,9 @@ The :mod:`urllib.request` module defines the following functions:
Open the URL *url*, which can be either a string or a
:class:`Request` object.
- *data* must be a bytes object specifying additional data to be sent to the
- server, or ``None`` if no such data is needed. *data* may also be an
- iterable object and in that case Content-Length value must be specified in
- the headers. Currently HTTP requests are the only ones that use *data*; the
- HTTP request will be a POST instead of a GET when the *data* parameter is
- provided.
-
- *data* should be a buffer in the standard
- :mimetype:`application/x-www-form-urlencoded` format. The
- :func:`urllib.parse.urlencode` function takes a mapping or sequence of
- 2-tuples and returns an ASCII text string in this format. It should
- be encoded to bytes before being used as the *data* parameter.
+ *data* must be an object specifying additional data to be sent to the
+ server, or ``None`` if no such data is needed. See :class:`Request`
+ for details.
urllib.request module uses HTTP/1.1 and includes ``Connection:close`` header
in its HTTP requests.
@@ -120,6 +111,12 @@ The :mod:`urllib.request` module defines the following functions:
.. versionchanged:: 3.4.3
*context* was added.
+ .. deprecated:: 3.6
+
+ *cafile*, *capath* and *cadefault* are deprecated in favor of *context*.
+ Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
+ :func:`ssl.create_default_context` select the system's trusted CA
+ certificates for you.
.. function:: install_opener(opener)
@@ -192,14 +189,21 @@ The following classes are provided:
*url* should be a string containing a valid URL.
- *data* must be a bytes object specifying additional data to send to the
- server, or ``None`` if no such data is needed. Currently HTTP requests are
- the only ones that use *data*; the HTTP request will be a POST instead of a
- GET when the *data* parameter is provided. *data* should be a buffer in the
- standard :mimetype:`application/x-www-form-urlencoded` format.
- The :func:`urllib.parse.urlencode` function takes a mapping or sequence of
- 2-tuples and returns an ASCII string in this format. It should be
- encoded to bytes before being used as the *data* parameter.
+ *data* must be an object specifying additional data to send to the
+ server, or ``None`` if no such data is needed. Currently HTTP
+ requests are the only ones that use *data*. The supported object
+ types include bytes, file-like objects, and iterables. If no
+ ``Content-Length`` nor ``Transfer-Encoding`` header field
+ has been provided, :class:`HTTPHandler` will set these headers according
+ to the type of *data*. ``Content-Length`` will be used to send
+ bytes objects, while ``Transfer-Encoding: chunked`` as specified in
+ :rfc:`7230`, Section 3.3.1 will be used to send files and other iterables.
+
+ For an HTTP POST request method, *data* should be a buffer in the
+ standard :mimetype:`application/x-www-form-urlencoded` format. The
+ :func:`urllib.parse.urlencode` function takes a mapping or sequence
+ of 2-tuples and returns an ASCII string in this format. It should
+ be encoded to bytes before being used as the *data* parameter.
*headers* should be a dictionary, and will be treated as if
:meth:`add_header` was called with each key and value as arguments.
@@ -211,8 +215,10 @@ The following classes are provided:
:mod:`urllib`'s default user agent string is
``"Python-urllib/2.6"`` (on Python 2.6).
- An example of using ``Content-Type`` header with *data* argument would be
- sending a dictionary like ``{"Content-Type": "application/x-www-form-urlencoded"}``.
+ An appropriate ``Content-Type`` header should be included if the *data*
+ argument is present. If this header has not been provided and *data*
+ is not None, ``Content-Type: application/x-www-form-urlencoded`` will
+ be added as a default.
The final two arguments are only of interest for correct handling
of third-party HTTP cookies:
@@ -235,15 +241,28 @@ The following classes are provided:
*method* should be a string that indicates the HTTP request method that
will be used (e.g. ``'HEAD'``). If provided, its value is stored in the
:attr:`~Request.method` attribute and is used by :meth:`get_method()`.
- Subclasses may indicate a default method by setting the
+ The default is ``'GET'`` if *data* is ``None`` or ``'POST'`` otherwise.
+ Subclasses may indicate a different default method by setting the
:attr:`~Request.method` attribute in the class itself.
+ .. note::
+ The request will not work as expected if the data object is unable
+ to deliver its content more than once (e.g. a file or an iterable
+ that can produce the content only once) and the request is retried
+ for HTTP redirects or authentication. The *data* is sent to the
+ HTTP server right away after the headers. There is no support for
+ a 100-continue expectation in the library.
+
.. versionchanged:: 3.3
:attr:`Request.method` argument is added to the Request class.
.. versionchanged:: 3.4
Default :attr:`Request.method` may be indicated at the class level.
+ .. versionchanged:: 3.6
+ Do not raise an error if the ``Content-Length`` has not been
+ provided and *data* is neither ``None`` nor a bytes object.
+ Fall back to use chunked transfer encoding instead.
.. class:: OpenerDirector()
diff --git a/Doc/library/urllib.robotparser.rst b/Doc/library/urllib.robotparser.rst
index ba701c3..7d31932 100644
--- a/Doc/library/urllib.robotparser.rst
+++ b/Doc/library/urllib.robotparser.rst
@@ -57,15 +57,41 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
Sets the time the ``robots.txt`` file was last fetched to the current
time.
+ .. method:: crawl_delay(useragent)
-The following example demonstrates basic use of the RobotFileParser class.
+ Returns the value of the ``Crawl-delay`` parameter from ``robots.txt``
+ for the *useragent* in question. If there is no such parameter or it
+ doesn't apply to the *useragent* specified or the ``robots.txt`` entry
+ for this parameter has invalid syntax, return ``None``.
+
+ .. versionadded:: 3.6
+
+ .. method:: request_rate(useragent)
+
+ Returns the contents of the ``Request-rate`` parameter from
+ ``robots.txt`` in the form of a :func:`~collections.namedtuple`
+ ``(requests, seconds)``. If there is no such parameter or it doesn't
+ apply to the *useragent* specified or the ``robots.txt`` entry for this
+ parameter has invalid syntax, return ``None``.
+
+ .. versionadded:: 3.6
+
+
+The following example demonstrates basic use of the :class:`RobotFileParser`
+class::
>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
+ >>> rrate = rp.request_rate("*")
+ >>> rrate.requests
+ 3
+ >>> rrate.seconds
+ 20
+ >>> rp.crawl_delay("*")
+ 6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True
-
diff --git a/Doc/library/venv.rst b/Doc/library/venv.rst
index 0327737..17c80c8 100644
--- a/Doc/library/venv.rst
+++ b/Doc/library/venv.rst
@@ -37,44 +37,50 @@ Creating virtual environments
.. _venv-def:
-.. note:: A virtual environment (also called a ``venv``) is a Python
- environment such that the Python interpreter, libraries and scripts
- installed into it are isolated from those installed in other virtual
- environments, and (by default) any libraries installed in a "system" Python,
- i.e. one which is installed as part of your operating system.
+.. note:: A virtual environment is a Python environment such that the Python
+ interpreter, libraries and scripts installed into it are isolated from those
+ installed in other virtual environments, and (by default) any libraries
+ installed in a "system" Python, i.e., one which is installed as part of your
+ operating system.
- A venv is a directory tree which contains Python executable files and
- other files which indicate that it is a venv.
+ A virtual environment is a directory tree which contains Python executable
+ files and other files which indicate that it is a virtual environment.
Common installation tools such as ``Setuptools`` and ``pip`` work as
- expected with venvs - i.e. when a venv is active, they install Python
- packages into the venv without needing to be told to do so explicitly.
-
- When a venv is active (i.e. the venv's Python interpreter is running), the
- attributes :attr:`sys.prefix` and :attr:`sys.exec_prefix` point to the base
- directory of the venv, whereas :attr:`sys.base_prefix` and
- :attr:`sys.base_exec_prefix` point to the non-venv Python installation
- which was used to create the venv. If a venv is not active, then
- :attr:`sys.prefix` is the same as :attr:`sys.base_prefix` and
- :attr:`sys.exec_prefix` is the same as :attr:`sys.base_exec_prefix` (they
- all point to a non-venv Python installation).
-
- When a venv is active, any options that change the installation path will be
- ignored from all distutils configuration files to prevent projects being
- inadvertently installed outside of the virtual environment.
-
- When working in a command shell, users can make a venv active by running an
- ``activate`` script in the venv's executables directory (the precise filename
- is shell-dependent), which prepends the venv's directory for executables to
- the ``PATH`` environment variable for the running shell. There should be no
- need in other circumstances to activate a venv -- scripts installed into
- venvs have a shebang line which points to the venv's Python interpreter. This
- means that the script will run with that interpreter regardless of the value
- of ``PATH``. On Windows, shebang line processing is supported if you have the
- Python Launcher for Windows installed (this was added to Python in 3.3 - see
- :pep:`397` for more details). Thus, double-clicking an installed script in
- a Windows Explorer window should run the script with the correct interpreter
- without there needing to be any reference to its venv in ``PATH``.
+ expected with virtual environments. In other words, when a virtual
+ environment is active, they install Python packages into the virtual
+ environment without needing to be told to do so explicitly.
+
+ When a virtual environment is active (i.e., the virtual environment's Python
+ interpreter is running), the attributes :attr:`sys.prefix` and
+ :attr:`sys.exec_prefix` point to the base directory of the virtual
+ environment, whereas :attr:`sys.base_prefix` and
+ :attr:`sys.base_exec_prefix` point to the non-virtual environment Python
+ installation which was used to create the virtual environment. If a virtual
+ environment is not active, then :attr:`sys.prefix` is the same as
+ :attr:`sys.base_prefix` and :attr:`sys.exec_prefix` is the same as
+ :attr:`sys.base_exec_prefix` (they all point to a non-virtual environment
+ Python installation).
+
+ When a virtual environment is active, any options that change the
+ installation path will be ignored from all distutils configuration files to
+ prevent projects being inadvertently installed outside of the virtual
+ environment.
+
+ When working in a command shell, users can make a virtual environment active
+ by running an ``activate`` script in the virtual environment's executables
+ directory (the precise filename is shell-dependent), which prepends the
+ virtual environment's directory for executables to the ``PATH`` environment
+ variable for the running shell. There should be no need in other
+ circumstances to activate a virtual environment—scripts installed into
+ virtual environments have a "shebang" line which points to the virtual
+ environment's Python interpreter. This means that the script will run with
+ that interpreter regardless of the value of ``PATH``. On Windows, "shebang"
+ line processing is supported if you have the Python Launcher for Windows
+ installed (this was added to Python in 3.3 - see :pep:`397` for more
+ details). Thus, double-clicking an installed script in a Windows Explorer
+ window should run the script with the correct interpreter without there
+ needing to be any reference to its virtual environment in ``PATH``.
.. _venv-api:
@@ -89,7 +95,8 @@ mechanisms for third-party virtual environment creators to customize environment
creation according to their needs, the :class:`EnvBuilder` class.
.. class:: EnvBuilder(system_site_packages=False, clear=False, \
- symlinks=False, upgrade=False, with_pip=False)
+ symlinks=False, upgrade=False, with_pip=False, \
+ prompt=None)
The :class:`EnvBuilder` class accepts the following keyword arguments on
instantiation:
@@ -113,9 +120,16 @@ creation according to their needs, the :class:`EnvBuilder` class.
installed in the virtual environment. This uses :mod:`ensurepip` with
the ``--default-pip`` option.
+ * ``prompt`` -- a String to be used after virtual environment is activated
+ (defaults to ``None`` which means directory name of the environment would
+ be used).
+
.. versionchanged:: 3.4
Added the ``with_pip`` parameter
+ .. versionadded:: 3.6
+ Added the ``prompt`` parameter
+
Creators of third-party virtual environment tools will be free to use the
provided ``EnvBuilder`` class as a base class.
@@ -225,7 +239,7 @@ An example of extending ``EnvBuilder``
--------------------------------------
The following script shows how to extend :class:`EnvBuilder` by implementing a
-subclass which installs setuptools and pip into a created venv::
+subclass which installs setuptools and pip into a created virtual environment::
import os
import os.path
@@ -239,12 +253,12 @@ subclass which installs setuptools and pip into a created venv::
class ExtendedEnvBuilder(venv.EnvBuilder):
"""
This builder installs setuptools and pip so that you can pip or
- easy_install other packages into the created environment.
+ easy_install other packages into the created virtual environment.
:param nodist: If True, setuptools and pip are not installed into the
- created environment.
+ created virtual environment.
:param nopip: If True, pip is not installed into the created
- environment.
+ virtual environment.
:param progress: If setuptools or pip are installed, the progress of the
installation can be monitored by passing a progress
callable. If specified, it is called with two
@@ -270,10 +284,10 @@ subclass which installs setuptools and pip into a created venv::
def post_setup(self, context):
"""
Set up any packages which need to be pre-installed into the
- environment being created.
+ virtual environment being created.
- :param context: The information for the environment creation request
- being processed.
+ :param context: The information for the virtual environment
+ creation request being processed.
"""
os.environ['VIRTUAL_ENV'] = context.env_dir
if not self.nodist:
@@ -307,7 +321,7 @@ subclass which installs setuptools and pip into a created venv::
fn = os.path.split(path)[-1]
binpath = context.bin_path
distpath = os.path.join(binpath, fn)
- # Download script into the env's binaries folder
+ # Download script into the virtual environment's binaries folder
urlretrieve(url, distpath)
progress = self.progress
if self.verbose:
@@ -319,7 +333,7 @@ subclass which installs setuptools and pip into a created venv::
else:
sys.stderr.write('Installing %s ...%s' % (name, term))
sys.stderr.flush()
- # Install in the env
+ # Install in the virtual environment
args = [context.env_exe, fn]
p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
@@ -338,10 +352,10 @@ subclass which installs setuptools and pip into a created venv::
def install_setuptools(self, context):
"""
- Install setuptools in the environment.
+ Install setuptools in the virtual environment.
- :param context: The information for the environment creation request
- being processed.
+ :param context: The information for the virtual environment
+ creation request being processed.
"""
url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
self.install_script(context, 'setuptools', url)
@@ -354,10 +368,10 @@ subclass which installs setuptools and pip into a created venv::
def install_pip(self, context):
"""
- Install pip in the environment.
+ Install pip in the virtual environment.
- :param context: The information for the environment creation request
- being processed.
+ :param context: The information for the virtual environment
+ creation request being processed.
"""
url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py'
self.install_script(context, 'pip', url)
@@ -380,7 +394,8 @@ subclass which installs setuptools and pip into a created venv::
'more target '
'directories.')
parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
- help='A directory to create the environment in.')
+ help='A directory in which to create the
+ 'virtual environment.')
parser.add_argument('--no-setuptools', default=False,
action='store_true', dest='nodist',
help="Don't install setuptools or pip in the "
@@ -404,14 +419,17 @@ subclass which installs setuptools and pip into a created venv::
'the platform.')
parser.add_argument('--clear', default=False, action='store_true',
dest='clear', help='Delete the contents of the '
- 'environment directory if it '
- 'already exists, before '
+ 'virtual environment '
+ 'directory if it already '
+ 'exists, before virtual '
'environment creation.')
parser.add_argument('--upgrade', default=False, action='store_true',
- dest='upgrade', help='Upgrade the environment '
- 'directory to use this version '
- 'of Python, assuming Python '
- 'has been upgraded in-place.')
+ dest='upgrade', help='Upgrade the virtual '
+ 'environment directory to '
+ 'use this version of '
+ 'Python, assuming Python '
+ 'has been upgraded '
+ 'in-place.')
parser.add_argument('--verbose', default=False, action='store_true',
dest='verbose', help='Display the output '
'from the scripts which '
diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst
index cec55f1..f67f4bc 100644
--- a/Doc/library/warnings.rst
+++ b/Doc/library/warnings.rst
@@ -301,7 +301,7 @@ Available Functions
-------------------
-.. function:: warn(message, category=None, stacklevel=1)
+.. function:: warn(message, category=None, stacklevel=1, source=None)
Issue a warning, or maybe ignore it or raise an exception. The *category*
argument, if given, must be a warning category class (see above); it defaults to
@@ -319,8 +319,14 @@ Available Functions
source of :func:`deprecation` itself (since the latter would defeat the purpose
of the warning message).
+ *source*, if supplied, is the destroyed object which emitted a
+ :exc:`ResourceWarning`.
-.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None)
+ .. versionchanged:: 3.6
+ Added *source* parameter.
+
+
+.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)
This is a low-level interface to the functionality of :func:`warn`, passing in
explicitly the message, category, filename and line number, and optionally the
@@ -336,6 +342,12 @@ Available Functions
source for modules found in zipfiles or other non-filesystem import
sources).
+ *source*, if supplied, is the destroyed object which emitted a
+ :exc:`ResourceWarning`.
+
+ .. versionchanged:: 3.6
+ Add the *source* parameter.
+
.. function:: showwarning(message, category, filename, lineno, file=None, line=None)
diff --git a/Doc/library/winreg.rst b/Doc/library/winreg.rst
index 767ea31..14f7896 100644
--- a/Doc/library/winreg.rst
+++ b/Doc/library/winreg.rst
@@ -635,7 +635,7 @@ For more information, see `Registry Value Types
.. data:: REG_DWORD_LITTLE_ENDIAN
- A 32-bit number in little-endian format.
+ A 32-bit number in little-endian format. Equivalent to :const:`REG_DWORD`.
.. data:: REG_DWORD_BIG_ENDIAN
@@ -659,6 +659,18 @@ For more information, see `Registry Value Types
No defined value type.
+.. data:: REG_QWORD
+
+ A 64-bit number.
+
+ .. versionadded:: 3.6
+
+.. data:: REG_QWORD_LITTLE_ENDIAN
+
+ A 64-bit number in little-endian format. Equivalent to :const:`REG_QWORD`.
+
+ .. versionadded:: 3.6
+
.. data:: REG_RESOURCE_LIST
A device-driver resource list.
diff --git a/Doc/library/winsound.rst b/Doc/library/winsound.rst
index d2c4210..372f792 100644
--- a/Doc/library/winsound.rst
+++ b/Doc/library/winsound.rst
@@ -25,7 +25,8 @@ provided by Windows platforms. It includes functions and several constants.
.. function:: PlaySound(sound, flags)
Call the underlying :c:func:`PlaySound` function from the Platform API. The
- *sound* parameter may be a filename, audio data as a string, or ``None``. Its
+ *sound* parameter may be a filename, a system sound alias, audio data as a
+ :term:`bytes-like object`, or ``None``. Its
interpretation depends on the value of *flags*, which can be a bitwise ORed
combination of the constants described below. If the *sound* parameter is
``None``, any currently playing waveform sound is stopped. If the system
@@ -39,7 +40,8 @@ provided by Windows platforms. It includes functions and several constants.
sound to play; possible values are ``-1``, ``MB_ICONASTERISK``,
``MB_ICONEXCLAMATION``, ``MB_ICONHAND``, ``MB_ICONQUESTION``, and ``MB_OK``, all
described below. The value ``-1`` produces a "simple beep"; this is the final
- fallback if a sound cannot be played otherwise.
+ fallback if a sound cannot be played otherwise. If the system indicates an
+ error, :exc:`RuntimeError` is raised.
.. data:: SND_FILENAME
@@ -92,7 +94,7 @@ provided by Windows platforms. It includes functions and several constants.
.. data:: SND_MEMORY
The *sound* parameter to :func:`PlaySound` is a memory image of a WAV file, as a
- string.
+ :term:`bytes-like object`.
.. note::
diff --git a/Doc/library/wsgiref.rst b/Doc/library/wsgiref.rst
index aad27a8..a1d4469 100644
--- a/Doc/library/wsgiref.rst
+++ b/Doc/library/wsgiref.rst
@@ -133,9 +133,9 @@ parameter expect a WSGI-compliant dictionary to be supplied; please see
for key, value in environ.items()]
return ret
- httpd = make_server('', 8000, simple_app)
- print("Serving on port 8000...")
- httpd.serve_forever()
+ with make_server('', 8000, simple_app) as httpd:
+ print("Serving on port 8000...")
+ httpd.serve_forever()
In addition to the environment functions above, the :mod:`wsgiref.util` module
@@ -285,14 +285,14 @@ request. (E.g., using the :func:`shift_path_info` function from
from wsgiref.simple_server import make_server, demo_app
- httpd = make_server('', 8000, demo_app)
- print("Serving HTTP on port 8000...")
+ with make_server('', 8000, demo_app) as httpd:
+ print("Serving HTTP on port 8000...")
- # Respond to requests until process is killed
- httpd.serve_forever()
+ # Respond to requests until process is killed
+ httpd.serve_forever()
- # Alternative: serve one request, then exit
- httpd.handle_request()
+ # Alternative: serve one request, then exit
+ httpd.handle_request()
.. function:: demo_app(environ, start_response)
@@ -432,9 +432,9 @@ Paste" library.
# This is the application wrapped in a validator
validator_app = validator(simple_app)
- httpd = make_server('', 8000, validator_app)
- print("Listening on port 8000....")
- httpd.serve_forever()
+ with make_server('', 8000, validator_app) as httpd:
+ print("Listening on port 8000....")
+ httpd.serve_forever()
:mod:`wsgiref.handlers` -- server/gateway base classes
@@ -774,8 +774,8 @@ This is a working "Hello World" WSGI application::
# The returned object is going to be printed
return [b"Hello World"]
- httpd = make_server('', 8000, hello_world_app)
- print("Serving on port 8000...")
+ with make_server('', 8000, hello_world_app) as httpd:
+ print("Serving on port 8000...")
- # Serve until process is killed
- httpd.serve_forever()
+ # Serve until process is killed
+ httpd.serve_forever()
diff --git a/Doc/library/xmlrpc.client.rst b/Doc/library/xmlrpc.client.rst
index dad7a02..390828e 100644
--- a/Doc/library/xmlrpc.client.rst
+++ b/Doc/library/xmlrpc.client.rst
@@ -88,9 +88,13 @@ between conformable Python objects and XML on the wire.
+======================+=======================================================+
| ``boolean`` | :class:`bool` |
+----------------------+-------------------------------------------------------+
- | ``int`` or ``i4`` | :class:`int` in range from -2147483648 to 2147483647. |
+ | ``int``, ``i1``, | :class:`int` in range from -2147483648 to 2147483647. |
+ | ``i2``, ``i4``, | Values get the ``<int>`` tag. |
+ | ``i8`` or | |
+ | ``biginteger`` | |
+----------------------+-------------------------------------------------------+
- | ``double`` | :class:`float` |
+ | ``double`` or | :class:`float`. Values get the ``<double>`` tag. |
+ | ``float`` | |
+----------------------+-------------------------------------------------------+
| ``string`` | :class:`str` |
+----------------------+-------------------------------------------------------+
@@ -114,6 +118,8 @@ between conformable Python objects and XML on the wire.
| ``nil`` | The ``None`` constant. Passing is allowed only if |
| | *allow_none* is true. |
+----------------------+-------------------------------------------------------+
+ | ``bigdecimal`` | :class:`decimal.Decimal`. Returned type only. |
+ +----------------------+-------------------------------------------------------+
This is the full set of data types supported by XML-RPC. Method calls may also
raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
@@ -137,6 +143,13 @@ between conformable Python objects and XML on the wire.
.. versionchanged:: 3.5
Added the *context* argument.
+ .. versionchanged:: 3.6
+ Added support of type tags with prefixes (e.g. ``ex:nil``).
+ Added support of unmarsalling additional types used by Apache XML-RPC
+ implementation for numerics: ``i1``, ``i2``, ``i8``, ``biginteger``,
+ ``float`` and ``bigdecimal``.
+ See http://ws.apache.org/xmlrpc/types.html for a description.
+
.. seealso::
diff --git a/Doc/library/xmlrpc.server.rst b/Doc/library/xmlrpc.server.rst
index 1c77e84..0511ddf 100644
--- a/Doc/library/xmlrpc.server.rst
+++ b/Doc/library/xmlrpc.server.rst
@@ -148,29 +148,29 @@ Server code::
rpc_paths = ('/RPC2',)
# Create server
- server = SimpleXMLRPCServer(("localhost", 8000),
- requestHandler=RequestHandler)
- server.register_introspection_functions()
+ with SimpleXMLRPCServer(("localhost", 8000),
+ requestHandler=RequestHandler) as server:
+ server.register_introspection_functions()
- # Register pow() function; this will use the value of
- # pow.__name__ as the name, which is just 'pow'.
- server.register_function(pow)
+ # Register pow() function; this will use the value of
+ # pow.__name__ as the name, which is just 'pow'.
+ server.register_function(pow)
- # Register a function under a different name
- def adder_function(x,y):
- return x + y
- server.register_function(adder_function, 'add')
+ # Register a function under a different name
+ def adder_function(x,y):
+ return x + y
+ server.register_function(adder_function, 'add')
- # Register an instance; all the methods of the instance are
- # published as XML-RPC methods (in this case, just 'mul').
- class MyFuncs:
- def mul(self, x, y):
- return x * y
+ # Register an instance; all the methods of the instance are
+ # published as XML-RPC methods (in this case, just 'mul').
+ class MyFuncs:
+ def mul(self, x, y):
+ return x * y
- server.register_instance(MyFuncs())
+ server.register_instance(MyFuncs())
- # Run the server's main loop
- server.serve_forever()
+ # Run the server's main loop
+ server.serve_forever()
The following client code will call the methods made available by the preceding
server::
@@ -207,18 +207,17 @@ a server allowing dotted names and registering a multicall function.
def getCurrentTime():
return datetime.datetime.now()
- server = SimpleXMLRPCServer(("localhost", 8000))
- server.register_function(pow)
- server.register_function(lambda x,y: x+y, 'add')
- server.register_instance(ExampleService(), allow_dotted_names=True)
- server.register_multicall_functions()
- print('Serving XML-RPC on localhost port 8000')
- try:
- server.serve_forever()
- except KeyboardInterrupt:
- print("\nKeyboard interrupt received, exiting.")
- server.server_close()
- sys.exit(0)
+ with SimpleXMLRPCServer(("localhost", 8000)) as server:
+ server.register_function(pow)
+ server.register_function(lambda x,y: x+y, 'add')
+ server.register_instance(ExampleService(), allow_dotted_names=True)
+ server.register_multicall_functions()
+ print('Serving XML-RPC on localhost port 8000')
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\nKeyboard interrupt received, exiting.")
+ sys.exit(0)
This ExampleService demo can be invoked from the command line::
diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst
index bf482d2..9056489 100644
--- a/Doc/library/zipfile.rst
+++ b/Doc/library/zipfile.rst
@@ -147,10 +147,10 @@ ZipFile Objects
*compression* is the ZIP compression method to use when writing the archive,
and should be :const:`ZIP_STORED`, :const:`ZIP_DEFLATED`,
:const:`ZIP_BZIP2` or :const:`ZIP_LZMA`; unrecognized
- values will cause :exc:`RuntimeError` to be raised. If :const:`ZIP_DEFLATED`,
+ values will cause :exc:`NotImplementedError` to be raised. If :const:`ZIP_DEFLATED`,
:const:`ZIP_BZIP2` or :const:`ZIP_LZMA` is specified but the corresponding module
(:mod:`zlib`, :mod:`bz2` or :mod:`lzma`) is not available, :exc:`RuntimeError`
- is also raised. The default is :const:`ZIP_STORED`. If *allowZip64* is
+ is raised. The default is :const:`ZIP_STORED`. If *allowZip64* is
``True`` (the default) zipfile will create ZIP files that use the ZIP64
extensions when the zipfile is larger than 2 GiB. If it is false :mod:`zipfile`
will raise an exception when the ZIP file would require ZIP64 extensions.
@@ -179,6 +179,10 @@ ZipFile Objects
Added support for writing to unseekable streams.
Added support for the ``'x'`` mode.
+ .. versionchanged:: 3.6
+ Previously, a plain :exc:`RuntimeError` was raised for unrecognized
+ compression values.
+
.. method:: ZipFile.close()
@@ -205,18 +209,12 @@ ZipFile Objects
Return a list of archive members by name.
-.. index::
- single: universal newlines; zipfile.ZipFile.open method
-
-.. method:: ZipFile.open(name, mode='r', pwd=None)
+.. method:: ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)
- Extract a member from the archive as a file-like object (ZipExtFile). *name*
- is the name of the file in the archive, or a :class:`ZipInfo` object. The
- *mode* parameter, if included, must be one of the following: ``'r'`` (the
- default), ``'U'``, or ``'rU'``. Choosing ``'U'`` or ``'rU'`` will enable
- :term:`universal newlines` support in the read-only object. *pwd* is the
- password used for encrypted files. Calling :meth:`.open` on a closed
- ZipFile will raise a :exc:`RuntimeError`.
+ Access a member of the archive as a binary file-like object. *name*
+ can be either the name of a file within the archive or a :class:`ZipInfo`
+ object. The *mode* parameter, if included, must be ``'r'`` (the default)
+ or ``'w'``. *pwd* is the password used to decrypt encrypted ZIP files.
:meth:`~ZipFile.open` is also a context manager and therefore supports the
:keyword:`with` statement::
@@ -225,17 +223,23 @@ ZipFile Objects
with myzip.open('eggs.txt') as myfile:
print(myfile.read())
- .. note::
+ With *mode* ``'r'`` the file-like object
+ (``ZipExtFile``) is read-only and provides the following methods:
+ :meth:`~io.BufferedIOBase.read`, :meth:`~io.IOBase.readline`,
+ :meth:`~io.IOBase.readlines`, :meth:`__iter__`,
+ :meth:`~iterator.__next__`. These objects can operate independently of
+ the ZipFile.
- The file-like object is read-only and provides the following methods:
- :meth:`~io.BufferedIOBase.read`, :meth:`~io.IOBase.readline`,
- :meth:`~io.IOBase.readlines`, :meth:`__iter__`,
- :meth:`~iterator.__next__`.
+ With ``mode='w'``, a writable file handle is returned, which supports the
+ :meth:`~io.BufferedIOBase.write` method. While a writable file handle is open,
+ attempting to read or write other files in the ZIP file will raise a
+ :exc:`ValueError`.
- .. note::
-
- Objects returned by :meth:`.open` can operate independently of the
- ZipFile.
+ When writing a file, if the file size is not known in advance but may exceed
+ 2 GiB, pass ``force_zip64=True`` to ensure that the header format is
+ capable of supporting large files. If the file size is known in advance,
+ construct a :class:`ZipInfo` object with :attr:`~ZipInfo.file_size` set, and
+ use that as the *name* parameter.
.. note::
@@ -243,10 +247,19 @@ ZipFile Objects
or a :class:`ZipInfo` object. You will appreciate this when trying to read a
ZIP file that contains members with duplicate names.
- .. deprecated-removed:: 3.4 3.6
- The ``'U'`` or ``'rU'`` mode. Use :class:`io.TextIOWrapper` for reading
+ .. versionchanged:: 3.6
+ Removed support of ``mode='U'``. Use :class:`io.TextIOWrapper` for reading
compressed text files in :term:`universal newlines` mode.
+ .. versionchanged:: 3.6
+ :meth:`open` can now be used to write files into the archive with the
+ ``mode='w'`` option.
+
+ .. versionchanged:: 3.6
+ Calling :meth:`.open` on a closed ZipFile will raise a :exc:`ValueError`.
+ Previously, a :exc:`RuntimeError` was raised.
+
+
.. method:: ZipFile.extract(member, path=None, pwd=None)
Extract a member from the archive to the current working directory; *member*
@@ -267,6 +280,10 @@ ZipFile Objects
characters (``:``, ``<``, ``>``, ``|``, ``"``, ``?``, and ``*``)
replaced by underscore (``_``).
+ .. versionchanged:: 3.6
+ Calling :meth:`extract` on a closed ZipFile will raise a
+ :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
+
.. method:: ZipFile.extractall(path=None, members=None, pwd=None)
@@ -283,6 +300,10 @@ ZipFile Objects
dots ``".."``. This module attempts to prevent that.
See :meth:`extract` note.
+ .. versionchanged:: 3.6
+ Calling :meth:`extractall` on a closed ZipFile will raise a
+ :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
+
.. method:: ZipFile.printdir()
@@ -300,18 +321,24 @@ ZipFile Objects
file in the archive, or a :class:`ZipInfo` object. The archive must be open for
read or append. *pwd* is the password used for encrypted files and, if specified,
it will override the default password set with :meth:`setpassword`. Calling
- :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`. Calling
:meth:`read` on a ZipFile that uses a compression method other than
:const:`ZIP_STORED`, :const:`ZIP_DEFLATED`, :const:`ZIP_BZIP2` or
:const:`ZIP_LZMA` will raise a :exc:`NotImplementedError`. An error will also
be raised if the corresponding compression module is not available.
+ .. versionchanged:: 3.6
+ Calling :meth:`read` on a closed ZipFile will raise a :exc:`ValueError`.
+ Previously, a :exc:`RuntimeError` was raised.
+
.. method:: ZipFile.testzip()
Read all the files in the archive and check their CRC's and file headers.
- Return the name of the first bad file, or else return ``None``. Calling
- :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
+ Return the name of the first bad file, or else return ``None``.
+
+ .. versionchanged:: 3.6
+ Calling :meth:`testfile` on a closed ZipFile will raise a
+ :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
.. method:: ZipFile.write(filename, arcname=None, compress_type=None)
@@ -321,10 +348,7 @@ ZipFile Objects
letter and with leading path separators removed). If given, *compress_type*
overrides the value given for the *compression* parameter to the constructor for
the new entry.
- The archive must be open with mode ``'w'``, ``'x'`` or ``'a'`` -- calling
- :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
- :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a
- :exc:`RuntimeError`.
+ The archive must be open with mode ``'w'``, ``'x'`` or ``'a'``.
.. note::
@@ -343,16 +367,19 @@ ZipFile Objects
If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
byte, the name of the file in the archive will be truncated at the null byte.
+ .. versionchanged:: 3.6
+ Calling :meth:`write` on a ZipFile created with mode ``'r'`` or
+ a closed ZipFile will raise a :exc:`ValueError`. Previously,
+ a :exc:`RuntimeError` was raised.
+
+
.. method:: ZipFile.writestr(zinfo_or_arcname, data[, compress_type])
Write the string *data* to the archive; *zinfo_or_arcname* is either the file
name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
an instance, at least the filename, date, and time must be given. If it's a
name, the date and time is set to the current date and time.
- The archive must be opened with mode ``'w'``, ``'x'`` or ``'a'`` -- calling
- :meth:`writestr` on a ZipFile created with mode ``'r'`` will raise a
- :exc:`RuntimeError`. Calling :meth:`writestr` on a closed ZipFile will
- raise a :exc:`RuntimeError`.
+ The archive must be opened with mode ``'w'``, ``'x'`` or ``'a'``.
If given, *compress_type* overrides the value given for the *compression*
parameter to the constructor for the new entry, or in the *zinfo_or_arcname*
@@ -368,6 +395,12 @@ ZipFile Objects
.. versionchanged:: 3.2
The *compress_type* argument.
+ .. versionchanged:: 3.6
+ Calling :meth:`writestr` on a ZipFile created with mode ``'r'`` or
+ a closed ZipFile will raise a :exc:`ValueError`. Previously,
+ a :exc:`RuntimeError` was raised.
+
+
The following data attributes are also available:
@@ -465,7 +498,31 @@ Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
:meth:`.infolist` methods of :class:`ZipFile` objects. Each object stores
information about a single member of the ZIP archive.
-Instances have the following attributes:
+There is one classmethod to make a :class:`ZipInfo` instance for a filesystem
+file:
+
+.. classmethod:: ZipInfo.from_file(filename, arcname=None)
+
+ Construct a :class:`ZipInfo` instance for a file on the filesystem, in
+ preparation for adding it to a zip file.
+
+ *filename* should be the path to a file or directory on the filesystem.
+
+ If *arcname* is specified, it is used as the name within the archive.
+ If *arcname* is not specified, the name will be the same as *filename*, but
+ with any drive letter and leading path separators removed.
+
+ .. versionadded:: 3.6
+
+Instances have the following methods and attributes:
+
+.. method:: ZipInfo.is_dir()
+
+ Return ``True`` if this archive member is a directory.
+
+ This uses the entry's name: directories should always end with ``/``.
+
+ .. versionadded:: 3.6
.. attribute:: ZipInfo.filename
diff --git a/Doc/library/zlib.rst b/Doc/library/zlib.rst
index 1de7bae..3d742ab 100644
--- a/Doc/library/zlib.rst
+++ b/Doc/library/zlib.rst
@@ -47,14 +47,19 @@ The available exception and functions in this module are:
platforms, use ``adler32(data) & 0xffffffff``.
-.. function:: compress(data[, level])
+.. function:: compress(data, level=-1)
Compresses the bytes in *data*, returning a bytes object containing compressed data.
- *level* is an integer from ``0`` to ``9`` controlling the level of compression;
+ *level* is an integer from ``0`` to ``9`` or ``-1`` controlling the level of compression;
``1`` is fastest and produces the least compression, ``9`` is slowest and
- produces the most. ``0`` is no compression. The default value is ``6``.
+ produces the most. ``0`` is no compression. The default value is ``-1``
+ (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default
+ compromise between speed and compression (currently equivalent to level 6).
Raises the :exc:`error` exception if any error occurs.
+ .. versionchanged:: 3.6
+ *level* can now be used as a keyword parameter.
+
.. function:: compressobj(level=-1, method=DEFLATED, wbits=15, memLevel=8, strategy=Z_DEFAULT_STRATEGY[, zdict])
@@ -124,7 +129,7 @@ The available exception and functions in this module are:
platforms, use ``crc32(data) & 0xffffffff``.
-.. function:: decompress(data[, wbits[, bufsize]])
+.. function:: decompress(data, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)
Decompresses the bytes in *data*, returning a bytes object containing the
uncompressed data. The *wbits* parameter depends on
@@ -159,14 +164,16 @@ The available exception and functions in this module are:
When decompressing a stream, the window size must not be smaller
than the size originally used to compress the stream; using a too-small
value may result in an :exc:`error` exception. The default *wbits* value
- is 15, which corresponds to the largest window size and requires a zlib
- header and trailer to be included.
+ corresponds to the largest window size and requires a zlib header and
+ trailer to be included.
*bufsize* is the initial size of the buffer used to hold decompressed data. If
more space is required, the buffer size will be increased as needed, so you
don't have to get this value exactly right; tuning it will only save a few calls
- to :c:func:`malloc`. The default size is 16384.
+ to :c:func:`malloc`.
+ .. versionchanged:: 3.6
+ *wbits* and *bufsize* can be used as keyword arguments.
.. function:: decompressobj(wbits=15[, zdict])
@@ -252,7 +259,7 @@ Decompression objects support the following methods and attributes:
.. versionadded:: 3.3
-.. method:: Decompress.decompress(data[, max_length])
+.. method:: Decompress.decompress(data, max_length=0)
Decompress *data*, returning a bytes object containing the uncompressed data
corresponding to at least part of the data in *string*. This data should be
@@ -264,9 +271,11 @@ Decompression objects support the following methods and attributes:
no longer than *max_length*. This may mean that not all of the compressed input
can be processed; and unconsumed data will be stored in the attribute
:attr:`unconsumed_tail`. This bytestring must be passed to a subsequent call to
- :meth:`decompress` if decompression is to continue. If *max_length* is not
- supplied then the whole input is decompressed, and :attr:`unconsumed_tail` is
- empty.
+ :meth:`decompress` if decompression is to continue. If *max_length* is zero
+ then the whole input is decompressed, and :attr:`unconsumed_tail` is empty.
+
+ .. versionchanged:: 3.6
+ *max_length* can be used as a keyword argument.
.. method:: Decompress.flush([length])
diff --git a/Doc/make.bat b/Doc/make.bat
index 5ab8085..da1f876 100644
--- a/Doc/make.bat
+++ b/Doc/make.bat
@@ -40,7 +40,7 @@ if "%1" == "clean" (
goto end
)
-%SPHINXBUILD% 2> nul
+%SPHINXBUILD% >nul 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
diff --git a/Doc/reference/compound_stmts.rst b/Doc/reference/compound_stmts.rst
index 88b94ea..4b425a4 100644
--- a/Doc/reference/compound_stmts.rst
+++ b/Doc/reference/compound_stmts.rst
@@ -471,10 +471,10 @@ A function definition defines a user-defined function object (see section
decorators: `decorator`+
decorator: "@" `dotted_name` ["(" [`argument_list` [","]] ")"] NEWLINE
dotted_name: `identifier` ("." `identifier`)*
- parameter_list: (`defparameter` ",")*
- : | "*" [`parameter`] ("," `defparameter`)* ["," "**" `parameter`]
- : | "**" `parameter`
- : | `defparameter` [","] )
+ parameter_list: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]]
+ : | `parameter_list_starargs`
+ parameter_list_starargs: "*" [`parameter`] ("," `defparameter`)* ["," ["**" `parameter` [","]]]
+ : | "**" `parameter` [","]
parameter: `identifier` [":" `expression`]
defparameter: `parameter` ["=" `expression`]
funcname: `identifier`
@@ -546,11 +546,12 @@ Function call semantics are described in more detail in section :ref:`calls`. A
function call always assigns values to all parameters mentioned in the parameter
list, either from position arguments, from keyword arguments, or from default
values. If the form "``*identifier``" is present, it is initialized to a tuple
-receiving any excess positional parameters, defaulting to the empty tuple. If
-the form "``**identifier``" is present, it is initialized to a new dictionary
-receiving any excess keyword arguments, defaulting to a new empty dictionary.
-Parameters after "``*``" or "``*identifier``" are keyword-only parameters and
-may only be passed used keyword arguments.
+receiving any excess positional parameters, defaulting to the empty tuple.
+If the form "``**identifier``" is present, it is initialized to a new
+ordered mapping receiving any excess keyword arguments, defaulting to a
+new empty mapping of the same type. Parameters after "``*``" or
+"``*identifier``" are keyword-only parameters and may only be passed
+used keyword arguments.
.. index:: pair: function; annotations
@@ -632,6 +633,11 @@ list for the base classes and the saved local namespace for the attribute
dictionary. The class name is bound to this class object in the original local
namespace.
+The order in which attributes are defined in the class body is preserved
+in the new class's ``__dict__``. Note that this is reliable only right
+after the class is created and only for classes that were defined using
+the definition syntax.
+
Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`.
Classes can also be decorated: just like when decorating functions, ::
@@ -691,7 +697,7 @@ coroutine bodies.
Functions defined with ``async def`` syntax are always coroutine functions,
even if they do not contain ``await`` or ``async`` keywords.
-It is a :exc:`SyntaxError` to use :keyword:`yield` expressions in
+It is a :exc:`SyntaxError` to use ``yield from`` expressions in
``async def`` coroutines.
An example of a coroutine function::
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 73eec1c..f2a2b12 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -627,6 +627,25 @@ Callable types
as well as :keyword:`async with` and :keyword:`async for` statements. See
also the :ref:`coroutine-objects` section.
+ Asynchronous generator functions
+ .. index::
+ single: asynchronous generator; function
+ single: asynchronous generator; asynchronous iterator
+
+ A function or method which is defined using :keyword:`async def` and
+ which uses the :keyword:`yield` statement is called a
+ :dfn:`asynchronous generator function`. Such a function, when called,
+ returns an asynchronous iterator object which can be used in an
+ :keyword:`async for` statement to execute the body of the function.
+
+ Calling the asynchronous iterator's :meth:`aiterator.__anext__` method
+ will return an :term:`awaitable` which when awaited
+ will execute until it provides a value using the :keyword:`yield`
+ expression. When the function executes an empty :keyword:`return`
+ statement or falls off the end, a :exc:`StopAsyncIteration` exception
+ is raised and the asynchronous iterator will have reached the end of
+ the set of values to be yielded.
+
Built-in functions
.. index::
object: built-in function
@@ -686,33 +705,36 @@ Modules
Attribute assignment updates the module's namespace dictionary, e.g.,
``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.
- .. index:: single: __dict__ (module attribute)
-
- Special read-only attribute: :attr:`~object.__dict__` is the module's namespace as a
- dictionary object.
-
- .. impl-detail::
-
- Because of the way CPython clears module dictionaries, the module
- dictionary will be cleared when the module falls out of scope even if the
- dictionary still has live references. To avoid this, copy the dictionary
- or keep the module around while using its dictionary directly.
-
.. index::
single: __name__ (module attribute)
single: __doc__ (module attribute)
single: __file__ (module attribute)
+ single: __annotations__ (module attribute)
pair: module; namespace
Predefined (writable) attributes: :attr:`__name__` is the module's name;
:attr:`__doc__` is the module's documentation string, or ``None`` if
- unavailable; :attr:`__file__` is the pathname of the file from which the
+ unavailable; :attr:`__annotations__` (optional) is a dictionary containing
+ :term:`variable annotations <variable annotation>` collected during module
+ body execution; :attr:`__file__` is the pathname of the file from which the
module was loaded, if it was loaded from a file. The :attr:`__file__`
attribute may be missing for certain types of modules, such as C modules
that are statically linked into the interpreter; for extension modules
loaded dynamically from a shared library, it is the pathname of the shared
library file.
+ .. index:: single: __dict__ (module attribute)
+
+ Special read-only attribute: :attr:`~object.__dict__` is the module's
+ namespace as a dictionary object.
+
+ .. impl-detail::
+
+ Because of the way CPython clears module dictionaries, the module
+ dictionary will be cleared when the module falls out of scope even if the
+ dictionary still has live references. To avoid this, copy the dictionary
+ or keep the module around while using its dictionary directly.
+
Custom classes
Custom class types are typically created by class definitions (see section
:ref:`class`). A class has a namespace implemented by a dictionary object.
@@ -761,13 +783,17 @@ Custom classes
single: __dict__ (class attribute)
single: __bases__ (class attribute)
single: __doc__ (class attribute)
+ single: __annotations__ (class attribute)
Special attributes: :attr:`~definition.__name__` is the class name; :attr:`__module__` is
the module name in which the class was defined; :attr:`~object.__dict__` is the
dictionary containing the class's namespace; :attr:`~class.__bases__` is a
tuple (possibly empty or a singleton) containing the base classes, in the
order of their occurrence in the base class list; :attr:`__doc__` is the
- class's documentation string, or ``None`` if undefined.
+ class's documentation string, or ``None`` if undefined;
+ :attr:`__annotations__` (optional) is a dictionary containing
+ :term:`variable annotations <variable annotation>` collected during
+ class body execution.
Class instances
.. index::
@@ -1063,6 +1089,12 @@ to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute a
operation raise an exception when no appropriate method is defined (typically
:exc:`AttributeError` or :exc:`TypeError`).
+Setting a special method to ``None`` indicates that the corresponding
+operation is not available. For example, if a class sets
+:meth:`__iter__` to ``None``, the class is not iterable, so calling
+:func:`iter` on its instances will raise a :exc:`TypeError` (without
+falling back to :meth:`__getitem__`). [#]_
+
When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled. For example, some sequences may work well with retrieval
@@ -1233,8 +1265,9 @@ Basic customization
.. method:: object.__format__(self, format_spec)
- Called by the :func:`format` built-in function (and by extension, the
- :meth:`str.format` method of class :class:`str`) to produce a "formatted"
+ Called by the :func:`format` built-in function,
+ and by extension, evaluation of :ref:`formatted string literals
+ <f-strings>` and the :meth:`str.format` method, to produce a "formatted"
string representation of an object. The ``format_spec`` argument is
a string that contains a description of the formatting options desired.
The interpretation of the ``format_spec`` argument is up to the type
@@ -1494,6 +1527,14 @@ class' :attr:`~object.__dict__`.
Called to delete the attribute on an instance *instance* of the owner class.
+.. method:: object.__set_name__(self, owner, name)
+
+ Called at the time the owning class *owner* is created. The
+ descriptor has been assigned to *name*.
+
+ .. versionadded:: 3.6
+
+
The attribute :attr:`__objclass__` is interpreted by the :mod:`inspect` module
as specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class attributes).
@@ -1631,11 +1672,60 @@ Notes on using *__slots__*
* *__class__* assignment works only if both classes have the same *__slots__*.
-.. _metaclasses:
+.. _class-customization:
Customizing class creation
--------------------------
+Whenever a class inherits from another class, *__init_subclass__* is
+called on that class. This way, it is possible to write classes which
+change the behavior of subclasses. This is closely related to class
+decorators, but where class decorators only affect the specific class they're
+applied to, ``__init_subclass__`` solely applies to future subclasses of the
+class defining the method.
+
+.. classmethod:: object.__init_subclass__(cls)
+
+ This method is called whenever the containing class is subclassed.
+ *cls* is then the new subclass. If defined as a normal instance method,
+ this method is implicitly converted to a class method.
+
+ Keyword arguments which are given to a new class are passed to
+ the parent's class ``__init_subclass__``. For compatibility with
+ other classes using ``__init_subclass__``, one should take out the
+ needed keyword arguments and pass the others over to the base
+ class, as in::
+
+ class Philosopher:
+ def __init_subclass__(cls, default_name, **kwargs):
+ super().__init_subclass__(**kwargs)
+ cls.default_name = default_name
+
+ class AustralianPhilosopher(Philosopher, default_name="Bruce"):
+ pass
+
+ The default implementation ``object.__init_subclass__`` does
+ nothing, but raises an error if it is called with any arguments.
+
+ .. note::
+
+ The metaclass hint ``metaclass`` is consumed by the rest of the type
+ machinery, and is never passed to ``__init_subclass__`` implementations.
+ The actual metaclass (rather than the explicit hint) can be accessed as
+ ``type(cls)``.
+
+ .. versionadded:: 3.6
+
+
+.. _metaclasses:
+
+Metaclasses
+^^^^^^^^^^^
+
+.. index::
+ single: metaclass
+ builtin: type
+
By default, classes are constructed using :func:`type`. The class body is
executed in a new namespace and the class name is bound locally to the
result of ``type(name, bases, namespace)``.
@@ -1666,6 +1756,8 @@ When a class definition is executed, the following steps occur:
Determining the appropriate metaclass
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+.. index::
+ single: metaclass hint
The appropriate metaclass for a class definition is determined as follows:
@@ -1687,13 +1779,16 @@ that criterion, then the class definition will fail with ``TypeError``.
Preparing the class namespace
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+.. index::
+ single: __prepare__ (metaclass method)
+
Once the appropriate metaclass has been identified, then the class namespace
is prepared. If the metaclass has a ``__prepare__`` attribute, it is called
as ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (where the
additional keyword arguments, if any, come from the class definition).
If the metaclass has no ``__prepare__`` attribute, then the class namespace
-is initialised as an empty :func:`dict` instance.
+is initialised as an empty ordered mapping.
.. seealso::
@@ -1704,6 +1799,9 @@ is initialised as an empty :func:`dict` instance.
Executing the class body
^^^^^^^^^^^^^^^^^^^^^^^^
+.. index::
+ single: class; body
+
The class body is executed (approximately) as
``exec(body, globals(), namespace)``. The key difference from a normal
call to :func:`exec` is that lexical scoping allows the class body (including
@@ -1713,12 +1811,19 @@ class definition occurs inside a function.
However, even when the class definition occurs inside the function, methods
defined inside the class still cannot see names defined at the class scope.
Class variables must be accessed through the first parameter of instance or
-class methods, and cannot be accessed at all from static methods.
+class methods, or through the implicit lexically scoped ``__class__`` reference
+described in the next section.
+.. _class-object-creation:
Creating the class object
^^^^^^^^^^^^^^^^^^^^^^^^^
+.. index::
+ single: __class__ (method cell)
+ single: __classcell__ (class namespace entry)
+
+
Once the class namespace has been populated by executing the class body,
the class object is created by calling
``metaclass(name, bases, namespace, **kwds)`` (the additional keywords
@@ -1732,14 +1837,34 @@ created by the compiler if any methods in a class body refer to either
lexical scoping, while the class or instance that was used to make the
current call is identified based on the first argument passed to the method.
+.. impl-detail::
+
+ In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass
+ as a ``__classcell__`` entry in the class namespace. If present, this must
+ be propagated up to the ``type.__new__`` call in order for the class to be
+ initialised correctly.
+ Failing to do so will result in a :exc:`DeprecationWarning` in Python 3.6,
+ and a :exc:`RuntimeWarning` in the future.
+
+When using the default metaclass :class:`type`, or any metaclass that ultimately
+calls ``type.__new__``, the following additional customisation steps are
+invoked after creating the class object:
+
+* first, ``type.__new__`` collects all of the descriptors in the class
+ namespace that define a :meth:`~object.__set_name__` method;
+* second, all of these ``__set_name__`` methods are called with the class
+ being defined and the assigned name of that particular descriptor; and
+* finally, the :meth:`~object.__init_subclass__` hook is called on the
+ immediate parent of the new class in its method resolution order.
+
After the class object is created, it is passed to the class decorators
included in the class definition (if any) and the resulting object is bound
in the local namespace as the defined class.
When a new class is created by ``type.__new__``, the object provided as the
-namespace parameter is copied to a standard Python dictionary and the original
-object is discarded. The new copy becomes the :attr:`~object.__dict__` attribute
-of the class object.
+namespace parameter is copied to a new ordered mapping and the original
+object is discarded. The new copy is wrapped in a read-only proxy, which
+becomes the :attr:`~object.__dict__` attribute of the class object.
.. seealso::
@@ -2062,7 +2187,7 @@ left undefined.
(``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`,
:func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected
(swapped) operands. These functions are only called if the left operand does
- not support the corresponding operation and the operands are of different
+ not support the corresponding operation [#]_ and the operands are of different
types. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is
an instance of a class that has an :meth:`__rsub__` method, ``y.__rsub__(x)``
is called if ``x.__sub__(y)`` returns *NotImplemented*.
@@ -2478,6 +2603,17 @@ An example of an asynchronous context manager class::
controlled conditions. It generally isn't a good idea though, since it can
lead to some very strange behaviour if it is handled incorrectly.
+.. [#] The :meth:`__hash__`, :meth:`__iter__`, :meth:`__reversed__`, and
+ :meth:`__contains__` methods have special handling for this; others
+ will still raise a :exc:`TypeError`, but may do so by relying on
+ the behavior that ``None`` is not callable.
+
+.. [#] "Does not support" here means that the class has no such method, or
+ the method returns ``NotImplemented``. Do not set the method to
+ ``None`` if you want to force fallback to the right operand's reflected
+ method—that will instead have the opposite effect of explicitly
+ *blocking* such fallback.
+
.. [#] For operands of the same type, it is assumed that if the non-reflected method
(such as :meth:`__add__`) fails the operation is not supported, which is why the
reflected method is not called.
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index 9792399..b37df92 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -172,7 +172,7 @@ Common syntax elements for comprehensions are:
.. productionlist::
comprehension: `expression` `comp_for`
- comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
+ comp_for: [ASYNC] "for" `target_list` "in" `or_test` [`comp_iter`]
comp_iter: `comp_for` | `comp_if`
comp_if: "if" `expression_nocond` [`comp_iter`]
@@ -186,6 +186,17 @@ each time the innermost block is reached.
Note that the comprehension is executed in a separate scope, so names assigned
to in the target list don't "leak" into the enclosing scope.
+Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
+clause may be used to iterate over a :term:`asynchronous iterator`.
+A comprehension in an :keyword:`async def` function may consist of either a
+:keyword:`for` or :keyword:`async for` clause following the leading
+expression, may contan additonal :keyword:`for` or :keyword:`async for`
+clauses, and may also use :keyword:`await` expressions.
+If a comprehension contains either :keyword:`async for` clauses
+or :keyword:`await` expressions it is called an
+:dfn:`asynchronous comprehension`. An asynchronous comprehension may
+suspend the execution of the coroutine function in which it appears.
+See also :pep:`530`.
.. _lists:
@@ -315,6 +326,14 @@ range(10) for y in bar(x))``.
The parentheses can be omitted on calls with only one argument. See section
:ref:`calls` for details.
+Since Python 3.6, if the generator appears in an :keyword:`async def` function,
+then :keyword:`async for` clauses and :keyword:`await` expressions are permitted
+as with an asynchronous comprehension. If a generator expression
+contains either :keyword:`async for` clauses or :keyword:`await` expressions
+it is called an :dfn:`asynchronous generator expression`.
+An asynchronous generator expression yields a new asynchronous
+generator object, which is an asynchronous iterator
+(see :ref:`async-iterators`).
.. _yieldexpr:
@@ -330,9 +349,22 @@ Yield expressions
yield_atom: "(" `yield_expression` ")"
yield_expression: "yield" [`expression_list` | "from" `expression`]
-The yield expression is only used when defining a :term:`generator` function and
+The yield expression is used when defining a :term:`generator` function
+or an :term:`asynchronous generator` function and
thus can only be used in the body of a function definition. Using a yield
-expression in a function's body causes that function to be a generator.
+expression in a function's body causes that function to be a generator,
+and using it in an :keyword:`async def` function's body causes that
+coroutine function to be an asynchronous generator. For example::
+
+ def gen(): # defines a generator function
+ yield 123
+
+ async def agen(): # defines an asynchronous generator function (PEP 525)
+ yield 123
+
+Generator functions are described below, while asynchronous generator
+functions are described separately in section
+:ref:`asynchronous-generator-functions`.
When a generator function is called, it returns an iterator known as a
generator. That generator then controls the execution of the generator function.
@@ -496,6 +528,134 @@ generator functions::
For examples using ``yield from``, see :ref:`pep-380` in "What's New in
Python."
+.. _asynchronous-generator-functions:
+
+Asynchronous generator functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The presence of a yield expression in a function or method defined using
+:keyword:`async def` further defines the function as a
+:term:`asynchronous generator` function.
+
+When an asynchronous generator function is called, it returns an
+asynchronous iterator known as an asynchronous generator object.
+That object then controls the execution of the generator function.
+An asynchronous generator object is typically used in an
+:keyword:`async for` statement in a coroutine function analogously to
+how a generator object would be used in a :keyword:`for` statement.
+
+Calling one of the asynchronous generator's methods returns an
+:term:`awaitable` object, and the execution starts when this object
+is awaited on. At that time, the execution proceeds to the first yield
+expression, where it is suspended again, returning the value of
+:token:`expression_list` to the awaiting coroutine. As with a generator,
+suspension means that all local state is retained, including the
+current bindings of local variables, the instruction pointer, the internal
+evaluation stack, and the state of any exception handling. When the execution
+is resumed by awaiting on the next object returned by the asynchronous
+generator's methods, the function can proceed exactly as if the yield
+expression were just another external call. The value of the yield expression
+after resuming depends on the method which resumed the execution. If
+:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
+:meth:`~agen.asend` is used, then the result will be the value passed in to
+that method.
+
+In an asynchronous generator function, yield expressions are allowed anywhere
+in a :keyword:`try` construct. However, if an asynchronous generator is not
+resumed before it is finalized (by reaching a zero reference count or by
+being garbage collected), then a yield expression within a :keyword:`try`
+construct could result in a failure to execute pending :keyword:`finally`
+clauses. In this case, it is the responsibility of the event loop or
+scheduler running the asynchronous generator to call the asynchronous
+generator-iterator's :meth:`~agen.aclose` method and run the resulting
+coroutine object, thus allowing any pending :keyword:`finally` clauses
+to execute.
+
+To take care of finalization, an event loop should define
+a *finalizer* function which takes an asynchronous generator-iterator
+and presumably calls :meth:`~agen.aclose` and executes the coroutine.
+This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
+When first iterated over, an asynchronous generator-iterator will store the
+registered *finalizer* to be called upon finalization. For a reference example
+of a *finalizer* method see the implementation of
+``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
+
+The expression ``yield from <expr>`` is a syntax error when used in an
+asynchronous generator function.
+
+.. index:: object: asynchronous-generator
+.. _asynchronous-generator-methods:
+
+Asynchronous generator-iterator methods
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This subsection describes the methods of an asynchronous generator iterator,
+which are used to control the execution of a generator function.
+
+
+.. index:: exception: StopAsyncIteration
+
+.. coroutinemethod:: agen.__anext__()
+
+ Returns an awaitable which when run starts to execute the asynchronous
+ generator or resumes it at the last executed yield expression. When an
+ asynchronous generator function is resumed with a :meth:`~agen.__anext__`
+ method, the current yield expression always evaluates to :const:`None` in
+ the returned awaitable, which when run will continue to the next yield
+ expression. The value of the :token:`expression_list` of the yield
+ expression is the value of the :exc:`StopIteration` exception raised by
+ the completing coroutine. If the asynchronous generator exits without
+ yielding another value, the awaitable instead raises an
+ :exc:`StopAsyncIteration` exception, signalling that the asynchronous
+ iteration has completed.
+
+ This method is normally called implicitly by a :keyword:`async for` loop.
+
+
+.. coroutinemethod:: agen.asend(value)
+
+ Returns an awaitable which when run resumes the execution of the
+ asynchronous generator. As with the :meth:`~generator.send()` method for a
+ generator, this "sends" a value into the asynchronous generator function,
+ and the *value* argument becomes the result of the current yield expression.
+ The awaitable returned by the :meth:`asend` method will return the next
+ value yielded by the generator as the value of the raised
+ :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
+ asynchronous generator exits without yielding another value. When
+ :meth:`asend` is called to start the asynchronous
+ generator, it must be called with :const:`None` as the argument,
+ because there is no yield expression that could receive the value.
+
+
+.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
+
+ Returns an awaitable that raises an exception of type ``type`` at the point
+ where the asynchronous generator was paused, and returns the next value
+ yielded by the generator function as the value of the raised
+ :exc:`StopIteration` exception. If the asynchronous generator exits
+ without yielding another value, an :exc:`StopAsyncIteration` exception is
+ raised by the awaitable.
+ If the generator function does not catch the passed-in exception, or
+ raises a different exception, then when the awaitalbe is run that exception
+ propagates to the caller of the awaitable.
+
+.. index:: exception: GeneratorExit
+
+
+.. coroutinemethod:: agen.aclose()
+
+ Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
+ the asynchronous generator function at the point where it was paused.
+ If the asynchronous generator function then exits gracefully, is already
+ closed, or raises :exc:`GeneratorExit` (by not catching the exception),
+ then the returned awaitable will raise a :exc:`StopIteration` exception.
+ Any further awaitables returned by subsequent calls to the asynchronous
+ generator will raise a :exc:`StopAsyncIteration` exception. If the
+ asynchronous generator yields a value, a :exc:`RuntimeError` is raised
+ by the awaitable. If the asynchronous generator raises any other exception,
+ it is propagated to the caller of the awaitable. If the asynchronous
+ generator has already exited due to an exception or normal exit, then
+ further calls to :meth:`aclose` will return an awaitable that does nothing.
.. _primaries:
diff --git a/Doc/reference/import.rst b/Doc/reference/import.rst
index 64302b8..5e2c1c8 100644
--- a/Doc/reference/import.rst
+++ b/Doc/reference/import.rst
@@ -36,7 +36,7 @@ implement import semantics.
When a module is first imported, Python searches for the module and if found,
it creates a module object [#fnmo]_, initializing it. If the named module
-cannot be found, an :exc:`ImportError` is raised. Python implements various
+cannot be found, an :exc:`ModuleNotFoundError` is raised. Python implements various
strategies to search for the named module when the import machinery is
invoked. These strategies can be modified and extended by using various hooks
described in the sections below.
@@ -167,7 +167,7 @@ arguments to the :keyword:`import` statement, or from the parameters to the
This name will be used in various phases of the import search, and it may be
the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python
first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``.
-If any of the intermediate imports fail, an :exc:`ImportError` is raised.
+If any of the intermediate imports fail, an :exc:`ModuleNotFoundError` is raised.
The module cache
@@ -186,7 +186,7 @@ object.
During import, the module name is looked up in :data:`sys.modules` and if
present, the associated value is the module satisfying the import, and the
process completes. However, if the value is ``None``, then an
-:exc:`ImportError` is raised. If the module name is missing, Python will
+:exc:`ModuleNotFoundError` is raised. If the module name is missing, Python will
continue searching for the module.
:data:`sys.modules` is writable. Deleting a key may not destroy the
@@ -194,7 +194,7 @@ associated module (as other modules may hold references to it),
but it will invalidate the cache entry for the named module, causing
Python to search anew for the named module upon its next
import. The key can also be assigned to ``None``, forcing the next import
-of the module to result in an :exc:`ImportError`.
+of the module to result in an :exc:`ModuleNotFoundError`.
Beware though, as if you keep a reference to the module object,
invalidate its cache entry in :data:`sys.modules`, and then re-import the
@@ -288,8 +288,8 @@ the named module or not.
If the meta path finder knows how to handle the named module, it returns a
spec object. If it cannot handle the named module, it returns ``None``. If
:data:`sys.meta_path` processing reaches the end of its list without returning
-a spec, then an :exc:`ImportError` is raised. Any other exceptions raised
-are simply propagated up, aborting the import process.
+a spec, then a :exc:`ModuleNotFoundError` is raised. Any other exceptions
+raised are simply propagated up, aborting the import process.
The :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path
finders is called with two or three arguments. The first is the fully
@@ -298,9 +298,9 @@ The second argument is the path entries to use for the module search. For
top-level modules, the second argument is ``None``, but for submodules or
subpackages, the second argument is the value of the parent package's
``__path__`` attribute. If the appropriate ``__path__`` attribute cannot
-be accessed, an :exc:`ImportError` is raised. The third argument is an
-existing module object that will be the target of loading later. The
-import system passes in a target module only during reload.
+be accessed, an :exc:`ModuleNotFoundError` is raised. The third argument
+is an existing module object that will be the target of loading later.
+The import system passes in a target module only during reload.
The meta path may be traversed multiple times for a single import request.
For example, assuming none of the modules involved has already been cached,
@@ -554,19 +554,30 @@ the module.
details.
This attribute is used instead of ``__name__`` to calculate explicit
- relative imports for main modules, as defined in :pep:`366`.
+ relative imports for main modules, as defined in :pep:`366`. It is
+ expected to have the same value as ``__spec__.parent``.
+
+ .. versionchanged:: 3.6
+ The value of ``__package__`` is expected to be the same as
+ ``__spec__.parent``.
.. attribute:: __spec__
The ``__spec__`` attribute must be set to the module spec that was
- used when importing the module. This is used primarily for
- introspection and during reloading. Setting ``__spec__``
+ used when importing the module. Setting ``__spec__``
appropriately applies equally to :ref:`modules initialized during
interpreter startup <programs>`. The one exception is ``__main__``,
where ``__spec__`` is :ref:`set to None in some cases <main_spec>`.
+ When ``__package__`` is not defined, ``__spec__.parent`` is used as
+ a fallback.
+
.. versionadded:: 3.4
+ .. versionchanged:: 3.6
+ ``__spec__.parent`` is used as a fallback when ``__package__`` is
+ not defined.
+
.. attribute:: __path__
If the module is a package (either regular or namespace), the module
@@ -876,7 +887,7 @@ import statements within that module.
To selectively prevent import of some modules from a hook early on the
meta path (rather than disabling the standard import system entirely),
-it is sufficient to raise :exc:`ImportError` directly from
+it is sufficient to raise :exc:`ModuleNoFoundError` directly from
:meth:`~importlib.abc.MetaPathFinder.find_spec` instead of returning
``None``. The latter indicates that the meta path search should continue,
while raising an exception terminates it immediately.
diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst
index 37f25f1..da7017a 100644
--- a/Doc/reference/lexical_analysis.rst
+++ b/Doc/reference/lexical_analysis.rst
@@ -405,7 +405,8 @@ String literals are described by the following lexical definitions:
.. productionlist::
stringliteral: [`stringprefix`](`shortstring` | `longstring`)
- stringprefix: "r" | "u" | "R" | "U"
+ stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
+ : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
shortstringitem: `shortstringchar` | `stringescapeseq`
@@ -464,6 +465,11 @@ is not supported.
to simplify the maintenance of dual Python 2.x and 3.x codebases.
See :pep:`414` for more information.
+A string literal with ``'f'`` or ``'F'`` in its prefix is a
+:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be
+combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw
+formatted strings are possible, but formatted bytes literals are not.
+
In triple-quoted literals, unescaped newlines and quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the literal. (A
"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.)
@@ -554,6 +560,10 @@ is more easily recognized as broken.) It is also important to note that the
escape sequences only recognized in string literals fall into the category of
unrecognized escapes for bytes literals.
+ .. versionchanged:: 3.6
+ Unrecognized escape sequences produce a DeprecationWarning. In
+ some future version of Python they will be a SyntaxError.
+
Even in a raw literal, quotes can be escaped with a backslash, but the
backslash remains in the result; for example, ``r"\""`` is a valid string
literal consisting of two characters: a backslash and a double quote; ``r"\"``
@@ -583,7 +593,111 @@ comments to parts of strings, for example::
Note that this feature is defined at the syntactical level, but implemented at
compile time. The '+' operator must be used to concatenate string expressions
at run time. Also note that literal concatenation can use different quoting
-styles for each component (even mixing raw strings and triple quoted strings).
+styles for each component (even mixing raw strings and triple quoted strings),
+and formatted string literals may be concatenated with plain string literals.
+
+
+.. index::
+ single: formatted string literal
+ single: interpolated string literal
+ single: string; formatted literal
+ single: string; interpolated literal
+ single: f-string
+.. _f-strings:
+
+Formatted string literals
+-------------------------
+
+.. versionadded:: 3.6
+
+A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
+that is prefixed with ``'f'`` or ``'F'``. These strings may contain
+replacement fields, which are expressions delimited by curly braces ``{}``.
+While other string literals always have a constant value, formatted strings
+are really expressions evaluated at run time.
+
+Escape sequences are decoded like in ordinary string literals (except when
+a literal is also marked as a raw string). After decoding, the grammar
+for the contents of the string is:
+
+.. productionlist::
+ f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
+ replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}"
+ f_expression: (`conditional_expression` | "*" `or_expr`)
+ : ("," `conditional_expression` | "," "*" `or_expr`)* [","]
+ : | `yield_expression`
+ conversion: "s" | "r" | "a"
+ format_spec: (`literal_char` | NULL | `replacement_field`)*
+ literal_char: <any code point except "{", "}" or NULL>
+
+The parts of the string outside curly braces are treated literally,
+except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
+with the corresponding single curly brace. A single opening curly
+bracket ``'{'`` marks a replacement field, which starts with a
+Python expression. After the expression, there may be a conversion field,
+introduced by an exclamation point ``'!'``. A format specifier may also
+be appended, introduced by a colon ``':'``. A replacement field ends
+with a closing curly bracket ``'}'``.
+
+Expressions in formatted string literals are treated like regular
+Python expressions surrounded by parentheses, with a few exceptions.
+An empty expression is not allowed, and a :keyword:`lambda` expression
+must be surrounded by explicit parentheses. Replacement expressions
+can contain line breaks (e.g. in triple-quoted strings), but they
+cannot contain comments. Each expression is evaluated in the context
+where the formatted string literal appears, in order from left to right.
+
+If a conversion is specified, the result of evaluating the expression
+is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
+the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
+
+The result is then formatted using the :func:`format` protocol. The
+format specifier is passed to the :meth:`__format__` method of the
+expression or conversion result. An empty string is passed when the
+format specifier is omitted. The formatted result is then included in
+the final value of the whole string.
+
+Top-level format specifiers may include nested replacement fields.
+These nested fields may include their own conversion fields and
+format specifiers, but may not include more deeply-nested replacement fields.
+
+Formatted string literals may be concatenated, but replacement fields
+cannot be split across literals.
+
+Some examples of formatted string literals::
+
+ >>> name = "Fred"
+ >>> f"He said his name is {name!r}."
+ "He said his name is 'Fred'."
+ >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
+ "He said his name is 'Fred'."
+ >>> width = 10
+ >>> precision = 4
+ >>> value = decimal.Decimal("12.34567")
+ >>> f"result: {value:{width}.{precision}}" # nested fields
+ 'result: 12.35'
+
+A consequence of sharing the same syntax as regular string literals is
+that characters in the replacement fields must not conflict with the
+quoting used in the outer formatted string literal::
+
+ f"abc {a["x"]} def" # error: outer string literal ended prematurely
+ f"abc {a['x']} def" # workaround: use different quoting
+
+Backslashes are not allowed in format expressions and will raise
+an error::
+
+ f"newline: {ord('\n')}" # raises SyntaxError
+
+To include a value in which a backslash escape is required, create
+a temporary variable.
+
+ >>> newline = ord('\n')
+ >>> f"newline: {newline}"
+ 'newline: 10'
+
+See also :pep:`498` for the proposal that added formatted string literals,
+and :meth:`str.format`, which uses a related format string mechanism.
.. _numbers:
@@ -612,20 +726,24 @@ Integer literals
Integer literals are described by the following lexical definitions:
.. productionlist::
- integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger`
- decimalinteger: `nonzerodigit` `digit`* | "0"+
+ integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger`
+ decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")*
+ bininteger: "0" ("b" | "B") (["_"] `bindigit`)+
+ octinteger: "0" ("o" | "O") (["_"] `octdigit`)+
+ hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+
nonzerodigit: "1"..."9"
digit: "0"..."9"
- octinteger: "0" ("o" | "O") `octdigit`+
- hexinteger: "0" ("x" | "X") `hexdigit`+
- bininteger: "0" ("b" | "B") `bindigit`+
+ bindigit: "0" | "1"
octdigit: "0"..."7"
hexdigit: `digit` | "a"..."f" | "A"..."F"
- bindigit: "0" | "1"
There is no limit for the length of integer literals apart from what can be
stored in available memory.
+Underscores are ignored for determining the numeric value of the literal. They
+can be used to group digits for enhanced readability. One underscore can occur
+between digits, and after base specifiers like ``0x``.
+
Note that leading zeros in a non-zero decimal number are not allowed. This is
for disambiguation with C-style octal literals, which Python used before version
3.0.
@@ -634,6 +752,10 @@ Some examples of integer literals::
7 2147483647 0o177 0b100110111
3 79228162514264337593543950336 0o377 0xdeadbeef
+ 100_000_000_000 0b_1110_0101
+
+.. versionchanged:: 3.6
+ Underscores are now allowed for grouping purposes in literals.
.. _floating:
@@ -645,23 +767,28 @@ Floating point literals are described by the following lexical definitions:
.. productionlist::
floatnumber: `pointfloat` | `exponentfloat`
- pointfloat: [`intpart`] `fraction` | `intpart` "."
- exponentfloat: (`intpart` | `pointfloat`) `exponent`
- intpart: `digit`+
- fraction: "." `digit`+
- exponent: ("e" | "E") ["+" | "-"] `digit`+
+ pointfloat: [`digitpart`] `fraction` | `digitpart` "."
+ exponentfloat: (`digitpart` | `pointfloat`) `exponent`
+ digitpart: `digit` (["_"] `digit`)*
+ fraction: "." `digitpart`
+ exponent: ("e" | "E") ["+" | "-"] `digitpart`
Note that the integer and exponent parts are always interpreted using radix 10.
For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The
-allowed range of floating point literals is implementation-dependent. Some
-examples of floating point literals::
+allowed range of floating point literals is implementation-dependent. As in
+integer literals, underscores are supported for digit grouping.
- 3.14 10. .001 1e100 3.14e-10 0e0
+Some examples of floating point literals::
+
+ 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
Note that numeric literals do not include a sign; a phrase like ``-1`` is
actually an expression composed of the unary operator ``-`` and the literal
``1``.
+.. versionchanged:: 3.6
+ Underscores are now allowed for grouping purposes in literals.
+
.. _imaginary:
@@ -671,7 +798,7 @@ Imaginary literals
Imaginary literals are described by the following lexical definitions:
.. productionlist::
- imagnumber: (`floatnumber` | `intpart`) ("j" | "J")
+ imagnumber: (`floatnumber` | `digitpart`) ("j" | "J")
An imaginary literal yields a complex number with a real part of 0.0. Complex
numbers are represented as a pair of floating point numbers and have the same
@@ -679,7 +806,7 @@ restrictions on their range. To create a complex number with a nonzero real
part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
imaginary literals::
- 3.14j 10.j 10j .001j 1e100j 3.14e-10j
+ 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j
.. _operators:
diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst
index d403c4d..e152b16 100644
--- a/Doc/reference/simple_stmts.rst
+++ b/Doc/reference/simple_stmts.rst
@@ -16,6 +16,7 @@ simple statements is:
: | `assert_stmt`
: | `assignment_stmt`
: | `augmented_assignment_stmt`
+ : | `annotated_assignment_stmt`
: | `pass_stmt`
: | `del_stmt`
: | `return_stmt`
@@ -84,7 +85,7 @@ attributes or items of mutable objects:
assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`)
target_list: `target` ("," `target`)* [","]
target: `identifier`
- : | "(" `target_list` ")"
+ : | "(" [`target_list`] ")"
: | "[" [`target_list`] "]"
: | `attributeref`
: | `subscription`
@@ -312,6 +313,50 @@ For targets which are attribute references, the same :ref:`caveat about class
and instance attributes <attr-target-note>` applies as for regular assignments.
+.. _annassign:
+
+Annotated assignment statements
+-------------------------------
+
+.. index::
+ pair: annotated; assignment
+ single: statement; assignment, annotated
+
+Annotation assignment is the combination, in a single statement,
+of a variable or attribute annotation and an optional assignment statement:
+
+.. productionlist::
+ annotated_assignment_stmt: `augtarget` ":" `expression` ["=" `expression`]
+
+The difference from normal :ref:`assignment` is that only single target and
+only single right hand side value is allowed.
+
+For simple names as assignment targets, if in class or module scope,
+the annotations are evaluated and stored in a special class or module
+attribute :attr:`__annotations__`
+that is a dictionary mapping from variable names (mangled if private) to
+evaluated annotations. This attribute is writable and is automatically
+created at the start of class or module body execution, if annotations
+are found statically.
+
+For expressions as assignment targets, the annotations are evaluated if
+in class or module scope, but not stored.
+
+If a name is annotated in a function scope, then this name is local for
+that scope. Annotations are never evaluated and stored in function scopes.
+
+If the right hand side is present, an annotated
+assignment performs the actual assignment before evaluating annotations
+(where applicable). If the right hand side is not present for an expression
+target, then the interpreter evaluates the target except for the last
+:meth:`__setitem__` or :meth:`__setattr__` call.
+
+.. seealso::
+
+ :pep:`526` - Variable and attribute annotation syntax
+ :pep:`484` - Type hints
+
+
.. _assert:
The :keyword:`assert` statement
@@ -447,6 +492,10 @@ generator is done and will cause :exc:`StopIteration` to be raised. The returned
value (if any) is used as an argument to construct :exc:`StopIteration` and
becomes the :attr:`StopIteration.value` attribute.
+In an asynchronous generator function, an empty :keyword:`return` statement
+indicates that the asynchronous generator is done and will cause
+:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`return`
+statement is a syntax error in an asynchronous generator function.
.. _yield:
@@ -859,11 +908,12 @@ 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`
-definition, function definition, or :keyword:`import` statement.
+definition, function definition, :keyword:`import` statement, or variable
+annotation.
.. impl-detail::
- The current implementation does not enforce the two restrictions, but
+ The current implementation does not enforce some of these restriction, but
programs should not abuse this freedom, as future implementations may enforce
them or silently change the meaning of the program.
diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py
index 6311283..273191b 100644
--- a/Doc/tools/extensions/pyspecific.py
+++ b/Doc/tools/extensions/pyspecific.py
@@ -34,7 +34,7 @@ import suspicious
ISSUE_URI = 'https://bugs.python.org/issue%s'
-SOURCE_URI = 'https://hg.python.org/cpython/file/3.5/%s'
+SOURCE_URI = 'https://hg.python.org/cpython/file/3.6/%s'
# monkey-patch reST parser to disable alphabetic and roman enumerated lists
from docutils.parsers.rst.states import Body
diff --git a/Doc/tools/rstlint.py b/Doc/tools/rstlint.py
index de78041..2c1816e 100755
--- a/Doc/tools/rstlint.py
+++ b/Doc/tools/rstlint.py
@@ -9,8 +9,6 @@
# TODO: - wrong versions in versionadded/changed
# - wrong markup after versionchanged directive
-from __future__ import with_statement
-
import os
import re
import sys
diff --git a/Doc/tools/susp-ignored.csv b/Doc/tools/susp-ignored.csv
index dba93bf..96483c4 100644
--- a/Doc/tools/susp-ignored.csv
+++ b/Doc/tools/susp-ignored.csv
@@ -25,6 +25,30 @@ howto/curses,,:blue,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white.
howto/curses,,:magenta,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The"
howto/curses,,:cyan,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The"
howto/curses,,:white,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The"
+howto/instrumentation,,::,python$target:::function-entry
+howto/instrumentation,,:function,python$target:::function-entry
+howto/instrumentation,,::,python$target:::function-return
+howto/instrumentation,,:function,python$target:::function-return
+howto/instrumentation,,:call,156641360502280 function-entry:call_stack.py:start:23
+howto/instrumentation,,:start,156641360502280 function-entry:call_stack.py:start:23
+howto/instrumentation,,:function,156641360518804 function-entry: call_stack.py:function_1:1
+howto/instrumentation,,:function,156641360532797 function-entry: call_stack.py:function_3:9
+howto/instrumentation,,:function,156641360546807 function-return: call_stack.py:function_3:10
+howto/instrumentation,,:function,156641360563367 function-return: call_stack.py:function_1:2
+howto/instrumentation,,:function,156641360578365 function-entry: call_stack.py:function_2:5
+howto/instrumentation,,:function,156641360591757 function-entry: call_stack.py:function_1:1
+howto/instrumentation,,:function,156641360605556 function-entry: call_stack.py:function_3:9
+howto/instrumentation,,:function,156641360617482 function-return: call_stack.py:function_3:10
+howto/instrumentation,,:function,156641360629814 function-return: call_stack.py:function_1:2
+howto/instrumentation,,:function,156641360642285 function-return: call_stack.py:function_2:6
+howto/instrumentation,,:function,156641360656770 function-entry: call_stack.py:function_3:9
+howto/instrumentation,,:function,156641360669707 function-return: call_stack.py:function_3:10
+howto/instrumentation,,:function,156641360687853 function-entry: call_stack.py:function_4:13
+howto/instrumentation,,:function,156641360700719 function-return: call_stack.py:function_4:14
+howto/instrumentation,,:function,156641360719640 function-entry: call_stack.py:function_5:18
+howto/instrumentation,,:function,156641360732567 function-return: call_stack.py:function_5:21
+howto/instrumentation,,:call,156641360747370 function-return:call_stack.py:start:28
+howto/instrumentation,,:start,156641360747370 function-return:call_stack.py:start:28
howto/ipaddress,,:DB8,>>> ipaddress.ip_address('2001:DB8::1')
howto/ipaddress,,::,>>> ipaddress.ip_address('2001:DB8::1')
howto/ipaddress,,:db8,IPv6Address('2001:db8::1')
@@ -106,6 +130,10 @@ library/exceptions,,:err,err.object[err.start:err.end]
library/functions,,:step,a[start:stop:step]
library/functions,,:stop,"a[start:stop, i]"
library/functions,,:stop,a[start:stop:step]
+library/hashlib-blake2,,:vatrogasac,>>> cookie = b'user:vatrogasac'
+library/hashlib-blake2,,:vatrogasac,"user:vatrogasac,349cf904533767ed2d755279a8df84d0"
+library/hashlib-blake2,,:policajac,">>> compare_digest(b'user:policajac', sig)"
+library/hashlib-blake2,,:LEAF,"h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,"
library/http.client,,:port,host:port
library/http.cookies,,`,!#$%&'*+-.^_`|~:
library/imaplib,,:MM,"""DD-Mmm-YYYY HH:MM:SS"
@@ -161,6 +189,7 @@ library/pprint,,::,"'Programming Language :: Python :: 2.7',"
library/profile,,:lineno,filename:lineno(function)
library/pyexpat,,:elem1,<py:elem1 />
library/pyexpat,,:py,"xmlns:py = ""http://www.python.org/ns/"">"
+library/random,,:len,new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
library/smtplib,,:port,method must support that as well as a regular host:port
library/socket,,::,'5aef:2b::8'
library/socket,,:can,"return (can_id, can_dlc, data[:can_dlc])"
@@ -205,7 +234,8 @@ library/uuid,,:uuid,urn:uuid:12345678-1234-5678-1234-567812345678
library/venv,,:param,":param nodist: If True, setuptools and pip are not installed into the"
library/venv,,:param,":param progress: If setuptools or pip are installed, the progress of the"
library/venv,,:param,":param nopip: If True, pip is not installed into the created"
-library/venv,,:param,:param context: The information for the environment creation request
+library/venv,,:param,:param context: The information for the virtual environment
+library/xmlrpc.client,,:nil,ex:nil
library/xmlrpc.client,,:pass,http://user:pass@host:port/path
library/xmlrpc.client,,:pass,user:pass
library/xmlrpc.client,,:port,http://user:pass@host:port/path
@@ -239,7 +269,7 @@ using/cmdline,,:line,file:line: category: message
using/cmdline,,:message,action:message:category:module:line
using/cmdline,,:module,action:message:category:module:line
using/unix,,:Packaging,https://en.opensuse.org/Portal:Packaging
-whatsnew/2.0,418,:len,
+whatsnew/2.0,,:len,
whatsnew/2.3,,::,
whatsnew/2.3,,:config,
whatsnew/2.3,,:Critical,
@@ -272,27 +302,28 @@ whatsnew/3.2,,:feed,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:
whatsnew/3.2,,:gz,">>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:"
whatsnew/3.2,,:location,zope9-location = ${zope9:location}
whatsnew/3.2,,:prefix,zope-conf = ${custom:prefix}/etc/zope.conf
-whatsnew/changelog,,:gz,": TarFile opened with external fileobj and ""w:gz"" mode didn't"
-whatsnew/changelog,,::,": Use ""127.0.0.1"" or ""::1"" instead of ""localhost"" as much as"
-library/tarfile,149,:xz,'x:xz'
-library/xml.etree.elementtree,290,:sometag,prefix:sometag
-library/xml.etree.elementtree,301,:fictional,"<actors xmlns:fictional=""http://characters.example.com"""
-library/xml.etree.elementtree,301,:character,<fictional:character>Lancelot</fictional:character>
-library/xml.etree.elementtree,301,:character,<fictional:character>Archie Leach</fictional:character>
-library/xml.etree.elementtree,301,:character,<fictional:character>Sir Robin</fictional:character>
-library/xml.etree.elementtree,301,:character,<fictional:character>Gunther</fictional:character>
-library/xml.etree.elementtree,301,:character,<fictional:character>Commander Clement</fictional:character>
+library/tarfile,,:xz,'x:xz'
+library/xml.etree.elementtree,,:sometag,prefix:sometag
+library/xml.etree.elementtree,,:fictional,"<actors xmlns:fictional=""http://characters.example.com"""
+library/xml.etree.elementtree,,:character,<fictional:character>Lancelot</fictional:character>
+library/xml.etree.elementtree,,:character,<fictional:character>Archie Leach</fictional:character>
+library/xml.etree.elementtree,,:character,<fictional:character>Sir Robin</fictional:character>
+library/xml.etree.elementtree,,:character,<fictional:character>Gunther</fictional:character>
+library/xml.etree.elementtree,,:character,<fictional:character>Commander Clement</fictional:character>
library/xml.etree.elementtree,,:actor,"for actor in root.findall('real_person:actor', ns):"
library/xml.etree.elementtree,,:name,"name = actor.find('real_person:name', ns)"
library/xml.etree.elementtree,,:character,"for char in actor.findall('role:character', ns):"
-library/zipapp,31,:main,"$ python -m zipapp myapp -m ""myapp:main"""
-library/zipapp,82,:fn,"argument should have the form ""pkg.mod:fn"", where ""pkg.mod"" is a"
-library/zipapp,155,:callable,"""pkg.module:callable"" and the archive will be run by importing"
+library/zipapp,,:main,"$ python -m zipapp myapp -m ""myapp:main"""
+library/zipapp,,:fn,"argument should have the form ""pkg.mod:fn"", where ""pkg.mod"" is a"
+library/zipapp,,:callable,"""pkg.module:callable"" and the archive will be run by importing"
library/stdtypes,,::,>>> m[::2].tolist()
library/sys,,`,# ``wrapper`` creates a ``wrap(coro)`` coroutine:
-tutorial/venv,77,:c7b9645a6f35,"Python 3.4.3+ (3.4:c7b9645a6f35+, May 22 2015, 09:31:25)"
whatsnew/3.5,,:root,'WARNING:root:warning\n'
whatsnew/3.5,,:warning,'WARNING:root:warning\n'
whatsnew/3.5,,::,>>> addr6 = ipaddress.IPv6Address('::1')
whatsnew/3.5,,:root,ERROR:root:exception
whatsnew/3.5,,:exception,ERROR:root:exception
+whatsnew/changelog,,:version,import sys; I = version[:version.index(' ')]
+whatsnew/changelog,,:gz,": TarFile opened with external fileobj and ""w:gz"" mode didn't"
+whatsnew/changelog,,::,": Use ""127.0.0.1"" or ""::1"" instead of ""localhost"" as much as"
+whatsnew/changelog,,`,"for readability (was ""`"")."
diff --git a/Doc/tools/templates/indexsidebar.html b/Doc/tools/templates/indexsidebar.html
index b7bcd74..413c0a7 100644
--- a/Doc/tools/templates/indexsidebar.html
+++ b/Doc/tools/templates/indexsidebar.html
@@ -3,7 +3,7 @@
<h3>{% trans %}Docs for other versions{% endtrans %}</h3>
<ul>
<li><a href="https://docs.python.org/2.7/">{% trans %}Python 2.7 (stable){% endtrans %}</a></li>
- <li><a href="https://docs.python.org/3.6/">{% trans %}Python 3.6 (stable){% endtrans %}</a></li>
+ <li><a href="https://docs.python.org/3.5/">{% trans %}Python 3.5 (stable){% endtrans %}</a></li>
<li><a href="https://docs.python.org/3.7/">{% trans %}Python 3.7 (in development){% endtrans %}</a></li>
<li><a href="https://www.python.org/doc/versions/">{% trans %}Old versions{% endtrans %}</a></li>
</ul>
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index 12989b2..d434618 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -78,6 +78,9 @@ slice notation makes this especially convenient::
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
+With ``for w in words:``, the example would attempt to create an infinite list,
+inserting ``defenestrate`` over and over again.
+
.. _tut-range:
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index b39bdf4..953a68b 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -60,11 +60,16 @@ objects:
Remove all items from the list. Equivalent to ``del a[:]``.
-.. method:: list.index(x)
+.. method:: list.index(x[, start[, end]])
:noindex:
- Return the index in the list of the first item whose value is *x*. It is an
- error if there is no such item.
+ Return zero-based index in the list of the first item whose value is *x*.
+ Raises a :exc:`ValueError` if there is no such item.
+
+ The optional arguments *start* and *end* are interpreted as in the slice
+ notation and are used to limit the search to a particular subsequence of
+ *x*. The returned index is computed relative to the beginning of the full
+ sequence rather than the *start* argument.
.. method:: list.count(x)
@@ -94,28 +99,26 @@ objects:
An example that uses most of the list methods::
- >>> a = [66.25, 333, 333, 1, 1234.5]
- >>> print(a.count(333), a.count(66.25), a.count('x'))
- 2 1 0
- >>> a.insert(2, -1)
- >>> a.append(333)
- >>> a
- [66.25, 333, -1, 333, 1, 1234.5, 333]
- >>> a.index(333)
- 1
- >>> a.remove(333)
- >>> a
- [66.25, -1, 333, 1, 1234.5, 333]
- >>> a.reverse()
- >>> a
- [333, 1234.5, 1, 333, -1, 66.25]
- >>> a.sort()
- >>> a
- [-1, 1, 66.25, 333, 333, 1234.5]
- >>> a.pop()
- 1234.5
- >>> a
- [-1, 1, 66.25, 333, 333]
+ >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
+ >>> fruits.count('apple')
+ 2
+ >>> fruits.count('tangerine')
+ 0
+ >>> fruits.index('banana')
+ 3
+ >>> fruits.index('banana', 4) # Find next banana starting a position 4
+ 6
+ >>> fruits.reverse()
+ >>> fruits
+ ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
+ >>> fruits.append('grape')
+ >>> fruits
+ ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
+ >>> fruits.sort()
+ >>> fruits
+ ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
+ >>> fruits.pop()
+ 'pear'
You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
only modify the list have no return value printed -- they return the default
diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst
index 759588f..aba61da 100644
--- a/Doc/tutorial/errors.rst
+++ b/Doc/tutorial/errors.rst
@@ -174,7 +174,7 @@ example::
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
- except IOError:
+ except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index dd9c7cd..beeaac3 100644
--- a/Doc/tutorial/inputoutput.rst
+++ b/Doc/tutorial/inputoutput.rst
@@ -25,7 +25,8 @@ first way is to do all the string handling yourself; using string slicing and
concatenation operations you can create any layout you can imagine. The
string type has some methods that perform useful operations for padding
strings to a given column width; these will be discussed shortly. The second
-way is to use the :meth:`str.format` method.
+way is to use :ref:`formatted string literals <f-strings>`, or the
+:meth:`str.format` method.
The :mod:`string` module contains a :class:`~string.Template` class which offers
yet another way to substitute values into strings.
diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst
index e8d8e2b..faf57a3 100644
--- a/Doc/tutorial/interpreter.rst
+++ b/Doc/tutorial/interpreter.rst
@@ -10,13 +10,13 @@ Using the Python Interpreter
Invoking the Interpreter
========================
-The Python interpreter is usually installed as :file:`/usr/local/bin/python3.5`
+The Python interpreter is usually installed as :file:`/usr/local/bin/python3.6`
on those machines where it is available; putting :file:`/usr/local/bin` in your
Unix shell's search path makes it possible to start it by typing the command:
.. code-block:: text
- python3.5
+ python3.6
to the shell. [#]_ Since the choice of the directory where the interpreter lives
is an installation option, other places are possible; check with your local
@@ -24,11 +24,11 @@ Python guru or system administrator. (E.g., :file:`/usr/local/python` is a
popular alternative location.)
On Windows machines, the Python installation is usually placed in
-:file:`C:\\Python35`, though you can change this when you're running the
+:file:`C:\\Python36`, though you can change this when you're running the
installer. To add this directory to your path, you can type the following
command into the command prompt in a DOS box::
- set path=%path%;C:\python35
+ set path=%path%;C:\python36
Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
@@ -98,8 +98,8 @@ before printing the first prompt:
.. code-block:: shell-session
- $ python3.5
- Python 3.5 (default, Sep 16 2015, 09:25:04)
+ $ python3.6
+ Python 3.6 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst
index 2140329..7e8ee3e 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -352,6 +352,9 @@ The built-in function :func:`len` returns the length of a string::
Strings support a large number of methods for
basic transformations and searching.
+ :ref:`f-strings`
+ String literals that have embedded expressions.
+
:ref:`formatstrings`
Information about string formatting with :meth:`str.format`.
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
index 52ffdbe..1dd06c2 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -15,7 +15,7 @@ operating system::
>>> import os
>>> os.getcwd() # Return the current working directory
- 'C:\\Python35'
+ 'C:\\Python36'
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
0
diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst
index f733ffc..bf02c71 100644
--- a/Doc/tutorial/stdlib2.rst
+++ b/Doc/tutorial/stdlib2.rst
@@ -278,7 +278,7 @@ applications include caching objects that are expensive to create::
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
- File "C:/python35/lib/weakref.py", line 46, in __getitem__
+ File "C:/python36/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
diff --git a/Doc/tutorial/venv.rst b/Doc/tutorial/venv.rst
index 3b2ee2e..e2dd57d 100644
--- a/Doc/tutorial/venv.rst
+++ b/Doc/tutorial/venv.rst
@@ -20,15 +20,14 @@ the requirements of every application. If application A needs version
the requirements are in conflict and installing either version 1.0 or 2.0
will leave one application unable to run.
-The solution for this problem is to create a :term:`virtual
-environment` (often shortened to "virtualenv"), a self-contained
-directory tree that contains a Python installation for a particular
-version of Python, plus a number of additional packages.
+The solution for this problem is to create a :term:`virtual environment`, a
+self-contained directory tree that contains a Python installation for a
+particular version of Python, plus a number of additional packages.
Different applications can then use different virtual environments.
To resolve the earlier example of conflicting requirements,
application A can have its own virtual environment with version 1.0
-installed while application B has another virtualenv with version 2.0.
+installed while application B has another virtual environment with version 2.0.
If application B requires a library be upgraded to version 3.0, this will
not affect application A's environment.
@@ -36,29 +35,26 @@ not affect application A's environment.
Creating Virtual Environments
=============================
-The script used to create and manage virtual environments is called
-:program:`pyvenv`. :program:`pyvenv` will usually install the most
-recent version of Python that you have available; the script is also
-installed with a version number, so if you have multiple versions of
-Python on your system you can select a specific Python version by
-running ``pyvenv-3.4`` or whichever version you want.
+The module used to create and manage virtual environments is called
+:mod:`venv`. :mod:`venv` will usually install the most recent version of
+Python that you have available. If you have multiple versions of Python on your
+system, you can select a specific Python version by running ``python3`` or
+whichever version you want.
-To create a virtualenv, decide upon a directory
-where you want to place it and run :program:`pyvenv` with the
-directory path::
+To create a virtual environment, decide upon a directory where you want to
+place it, and run the :mod:`venv` module as a script with the directory path::
- pyvenv tutorial-env
+ python3 -m venv tutorial-env
This will create the ``tutorial-env`` directory if it doesn't exist,
and also create directories inside it containing a copy of the Python
interpreter, the standard library, and various supporting files.
-Once you've created a virtual environment, you need to
-activate it.
+Once you've created a virtual environment, you may activate it.
On Windows, run::
- tutorial-env/Scripts/activate
+ tutorial-env\Scripts\activate.bat
On Unix or MacOS, run::
@@ -69,33 +65,36 @@ On Unix or MacOS, run::
``activate.csh`` and ``activate.fish`` scripts you should use
instead.)
-Activating the virtualenv will change your shell's prompt to show what
-virtualenv you're using, and modify the environment so that running
-``python`` will get you that particular version and installation of
-Python. For example::
+Activating the virtual environment will change your shell's prompt to show what
+virtual environment you're using, and modify the environment so that running
+``python`` will get you that particular version and installation of Python.
+For example:
- -> source ~/envs/tutorial-env/bin/activate
- (tutorial-env) -> python
- Python 3.4.3+ (3.4:c7b9645a6f35+, May 22 2015, 09:31:25)
+.. code-block:: bash
+
+ $ source ~/envs/tutorial-env/bin/activate
+ (tutorial-env) $ python
+ Python 3.5.1 (default, May 6 2016, 10:59:36)
...
>>> import sys
>>> sys.path
- ['', '/usr/local/lib/python34.zip', ...,
- '~/envs/tutorial-env/lib/python3.4/site-packages']
+ ['', '/usr/local/lib/python35.zip', ...,
+ '~/envs/tutorial-env/lib/python3.5/site-packages']
>>>
Managing Packages with pip
==========================
-Once you've activated a virtual environment, you can install, upgrade,
-and remove packages using a program called :program:`pip`. By default
-``pip`` will install packages from the Python Package Index,
-<https://pypi.python.org/pypi>. You can browse the Python Package Index
-by going to it in your web browser, or you can use ``pip``'s
-limited search feature::
+You can install, upgrade, and remove packages using a program called
+:program:`pip`. By default ``pip`` will install packages from the Python
+Package Index, <https://pypi.python.org/pypi>. You can browse the Python
+Package Index by going to it in your web browser, or you can use ``pip``'s
+limited search feature:
+
+.. code-block:: bash
- (tutorial-env) -> pip search astronomy
+ (tutorial-env) $ pip search astronomy
skyfield - Elegant astronomy for Python
gary - Galactic astronomy and gravitational dynamics.
novas - The United States Naval Observatory NOVAS astronomy library
@@ -107,9 +106,11 @@ limited search feature::
"freeze", etc. (Consult the :ref:`installing-index` guide for
complete documentation for ``pip``.)
-You can install the latest version of a package by specifying a package's name::
+You can install the latest version of a package by specifying a package's name:
+
+.. code-block:: bash
- -> pip install novas
+ (tutorial-env) $ pip install novas
Collecting novas
Downloading novas-3.1.1.3.tar.gz (136kB)
Installing collected packages: novas
@@ -117,9 +118,11 @@ You can install the latest version of a package by specifying a package's name::
Successfully installed novas-3.1.1.3
You can also install a specific version of a package by giving the
-package name followed by ``==`` and the version number::
+package name followed by ``==`` and the version number:
- -> pip install requests==2.6.0
+.. code-block:: bash
+
+ (tutorial-env) $ pip install requests==2.6.0
Collecting requests==2.6.0
Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
@@ -128,9 +131,11 @@ package name followed by ``==`` and the version number::
If you re-run this command, ``pip`` will notice that the requested
version is already installed and do nothing. You can supply a
different version number to get that version, or you can run ``pip
-install --upgrade`` to upgrade the package to the latest version::
+install --upgrade`` to upgrade the package to the latest version:
+
+.. code-block:: bash
- -> pip install --upgrade requests
+ (tutorial-env) $ pip install --upgrade requests
Collecting requests
Installing collected packages: requests
Found existing installation: requests 2.6.0
@@ -141,9 +146,11 @@ install --upgrade`` to upgrade the package to the latest version::
``pip uninstall`` followed by one or more package names will remove the
packages from the virtual environment.
-``pip show`` will display information about a particular package::
+``pip show`` will display information about a particular package:
- (tutorial-env) -> pip show requests
+.. code-block:: bash
+
+ (tutorial-env) $ pip show requests
---
Metadata-Version: 2.0
Name: requests
@@ -157,9 +164,11 @@ packages from the virtual environment.
Requires:
``pip list`` will display all of the packages installed in the virtual
-environment::
+environment:
+
+.. code-block:: bash
- (tutorial-env) -> pip list
+ (tutorial-env) $ pip list
novas (3.1.1.3)
numpy (1.9.2)
pip (7.0.3)
@@ -168,19 +177,23 @@ environment::
``pip freeze`` will produce a similar list of the installed packages,
but the output uses the format that ``pip install`` expects.
-A common convention is to put this list in a ``requirements.txt`` file::
+A common convention is to put this list in a ``requirements.txt`` file:
- (tutorial-env) -> pip freeze > requirements.txt
- (tutorial-env) -> cat requirements.txt
+.. code-block:: bash
+
+ (tutorial-env) $ pip freeze > requirements.txt
+ (tutorial-env) $ cat requirements.txt
novas==3.1.1.3
numpy==1.9.2
requests==2.7.0
The ``requirements.txt`` can then be committed to version control and
shipped as part of an application. Users can then install all the
-necessary packages with ``install -r``::
+necessary packages with ``install -r``:
+
+.. code-block:: bash
- -> pip install -r requirements.txt
+ (tutorial-env) $ pip install -r requirements.txt
Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
...
Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst
index 6117796..c0e64d6 100644
--- a/Doc/using/cmdline.rst
+++ b/Doc/using/cmdline.rst
@@ -180,8 +180,15 @@ Generic options
Print the Python version number and exit. Example output could be::
- Python 3.0
+ Python 3.6.0b2+
+ When given twice, print more information about the build, like::
+
+ Python 3.6.0b2+ (3.6:84a3c5003510+, Oct 26 2016, 02:33:55)
+ [GCC 6.2.0 20161005]
+
+ .. versionadded:: 3.6
+ The ``-VV`` option.
.. _using-on-misc-options:
@@ -396,6 +403,8 @@ Miscellaneous options
stored in a traceback of a trace. Use ``-X tracemalloc=NFRAME`` to start
tracing with a traceback limit of *NFRAME* frames. See the
:func:`tracemalloc.start` for more information.
+ * ``-X showalloccount`` to enable the output of the total count of allocated
+ objects for each type (only works when built with ``COUNT_ALLOCS`` defined);
It also allows passing arbitrary values and retrieving them through the
:data:`sys._xoptions` dictionary.
@@ -409,6 +418,9 @@ Miscellaneous options
.. versionadded:: 3.4
The ``-X showrefcount`` and ``-X tracemalloc`` options.
+ .. versionadded:: 3.6
+ The ``-X showalloccount`` option.
+
Options you shouldn't use
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -555,6 +567,10 @@ conflict.
.. versionchanged:: 3.4
The ``encodingname`` part is now optional.
+ .. versionchanged:: 3.6
+ On Windows, the encoding specified by this variable is ignored for interactive
+ console buffers unless :envvar:`PYTHONLEGACYWINDOWSIOENCODING` is also specified.
+ Files and pipes redirected through the standard streams are not affected.
.. envvar:: PYTHONNOUSERSITE
@@ -620,6 +636,81 @@ conflict.
.. versionadded:: 3.4
+.. envvar:: PYTHONMALLOC
+
+ Set the Python memory allocators and/or install debug hooks.
+
+ Set the family of memory allocators used by Python:
+
+ * ``malloc``: use the :c:func:`malloc` function of the C library
+ for all domains (:c:data:`PYMEM_DOMAIN_RAW`, :c:data:`PYMEM_DOMAIN_MEM`,
+ :c:data:`PYMEM_DOMAIN_OBJ`).
+ * ``pymalloc``: use the :ref:`pymalloc allocator <pymalloc>` for
+ :c:data:`PYMEM_DOMAIN_MEM` and :c:data:`PYMEM_DOMAIN_OBJ` domains and use
+ the :c:func:`malloc` function for the :c:data:`PYMEM_DOMAIN_RAW` domain.
+
+ Install debug hooks:
+
+ * ``debug``: install debug hooks on top of the default memory allocator
+ * ``malloc_debug``: same as ``malloc`` but also install debug hooks
+ * ``pymalloc_debug``: same as ``pymalloc`` but also install debug hooks
+
+ When Python is compiled in release mode, the default is ``pymalloc``. When
+ compiled in debug mode, the default is ``pymalloc_debug`` and the debug hooks
+ are used automatically.
+
+ If Python is configured without ``pymalloc`` support, ``pymalloc`` and
+ ``pymalloc_debug`` are not available, the default is ``malloc`` in release
+ mode and ``malloc_debug`` in debug mode.
+
+ See the :c:func:`PyMem_SetupDebugHooks` function for debug hooks on Python
+ memory allocators.
+
+ .. versionadded:: 3.6
+
+
+.. envvar:: PYTHONMALLOCSTATS
+
+ If set to a non-empty string, Python will print statistics of the
+ :ref:`pymalloc memory allocator <pymalloc>` every time a new pymalloc object
+ arena is created, and on shutdown.
+
+ This variable is ignored if the :envvar:`PYTHONMALLOC` environment variable
+ is used to force the :c:func:`malloc` allocator of the C library, or if
+ Python is configured without ``pymalloc`` support.
+
+ .. versionchanged:: 3.6
+ This variable can now also be used on Python compiled in release mode.
+ It now has no effect if set to an empty string.
+
+
+.. envvar:: PYTHONLEGACYWINDOWSFSENCODING
+
+ If set to a non-empty string, the default filesystem encoding and errors mode
+ will revert to their pre-3.6 values of 'mbcs' and 'replace', respectively.
+ Otherwise, the new defaults 'utf-8' and 'surrogatepass' are used.
+
+ This may also be enabled at runtime with
+ :func:`sys._enablelegacywindowsfsencoding()`.
+
+ Availability: Windows
+
+ .. versionadded:: 3.6
+ See :pep:`529` for more details.
+
+.. envvar:: PYTHONLEGACYWINDOWSIOENCODING
+
+ If set to a non-empty string, does not use the new console reader and
+ writer. This means that Unicode characters will be encoded according to
+ the active console code page, rather than using utf-8.
+
+ This variable is ignored if the standard streams are redirected (to files
+ or pipes) rather than referring to console buffers.
+
+ Availability: Windows
+
+ .. versionadded:: 3.6
+
Debug-mode variables
~~~~~~~~~~~~~~~~~~~~
@@ -635,9 +726,3 @@ if Python was configured with the ``--with-pydebug`` build option.
If set, Python will dump objects and reference counts still alive after
shutting down the interpreter.
-
-
-.. envvar:: PYTHONMALLOCSTATS
-
- If set, Python will print memory allocation statistics every time a new
- object arena is created, and on shutdown.
diff --git a/Doc/using/index.rst b/Doc/using/index.rst
index 502afa9..a5df713 100644
--- a/Doc/using/index.rst
+++ b/Doc/using/index.rst
@@ -17,4 +17,3 @@ interpreter and things that make working with Python easier.
unix.rst
windows.rst
mac.rst
- scripts.rst
diff --git a/Doc/using/mac.rst b/Doc/using/mac.rst
index 05c91bb..8f1ac3f 100644
--- a/Doc/using/mac.rst
+++ b/Doc/using/mac.rst
@@ -25,7 +25,7 @@ there.
What you get after installing is a number of things:
-* A :file:`MacPython 3.5` folder in your :file:`Applications` folder. In here
+* A :file:`MacPython 3.6` folder in your :file:`Applications` folder. In here
you find IDLE, the development environment that is a standard part of official
Python distributions; PythonLauncher, which handles double-clicking Python
scripts from the Finder; and the "Build Applet" tool, which allows you to
@@ -93,7 +93,7 @@ aware of: programs that talk to the Aqua window manager (in other words,
anything that has a GUI) need to be run in a special way. Use :program:`pythonw`
instead of :program:`python` to start such scripts.
-With Python 3.5, you can use either :program:`python` or :program:`pythonw`.
+With Python 3.6, you can use either :program:`python` or :program:`pythonw`.
Configuration
@@ -159,7 +159,7 @@ https://riverbankcomputing.com/software/pyqt/intro.
Distributing Python Applications on the Mac
===========================================
-The "Build Applet" tool that is placed in the MacPython 3.5 folder is fine for
+The "Build Applet" tool that is placed in the MacPython 3.6 folder is fine for
packaging small Python scripts on your own machine to run as a standard Mac
application. This tool, however, is not robust enough to distribute Python
applications to other users.
diff --git a/Doc/using/scripts.rst b/Doc/using/scripts.rst
deleted file mode 100644
index 2c87416..0000000
--- a/Doc/using/scripts.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-.. _tools-and-scripts:
-
-Additional Tools and Scripts
-============================
-
-.. _scripts-pyvenv:
-
-pyvenv - Creating virtual environments
---------------------------------------
-
-.. include:: venv-create.inc
-
diff --git a/Doc/using/venv-create.inc b/Doc/using/venv-create.inc
index 7ad3008..53f431b 100644
--- a/Doc/using/venv-create.inc
+++ b/Doc/using/venv-create.inc
@@ -1,31 +1,39 @@
Creation of :ref:`virtual environments <venv-def>` is done by executing the
-``pyvenv`` script::
+command ``venv``::
- pyvenv /path/to/new/virtual/environment
+ python3 -m venv /path/to/new/virtual/environment
Running this command creates the target directory (creating any parent
directories that don't exist already) and places a ``pyvenv.cfg`` file in it
-with a ``home`` key pointing to the Python installation the command was run
-from. It also creates a ``bin`` (or ``Scripts`` on Windows) subdirectory
+with a ``home`` key pointing to the Python installation from which the command
+was run. It also creates a ``bin`` (or ``Scripts`` on Windows) subdirectory
containing a copy of the ``python`` binary (or binaries, in the case of
Windows). It also creates an (initially empty) ``lib/pythonX.Y/site-packages``
subdirectory (on Windows, this is ``Lib\site-packages``).
+.. deprecated:: 3.6
+ ``pyvenv`` was the recommended tool for creating virtual environments for
+ Python 3.3 and 3.4, and is `deprecated in Python 3.6
+ <https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features>`_.
+
+.. versionchanged:: 3.5
+ The use of ``venv`` is now recommended for creating virtual environments.
+
.. seealso::
`Python Packaging User Guide: Creating and using virtual environments
- <https://packaging.python.org/en/latest/installing/#creating-virtual-environments>`__
+ <https://packaging.python.org/installing/#creating-virtual-environments>`__
.. highlight:: none
-On Windows, you may have to invoke the ``pyvenv`` script as follows, if you
-don't have the relevant PATH and PATHEXT settings::
+On Windows, invoke the ``venv`` command as follows::
- c:\Temp>c:\Python35\python c:\Python35\Tools\Scripts\pyvenv.py myenv
+ c:\>c:\Python35\python -m venv c:\path\to\myenv
-or equivalently::
+Alternatively, if you configured the ``PATH`` and ``PATHEXT`` variables for
+your :ref:`Python installation <using-on-windows>`::
- c:\Temp>c:\Python35\python -m venv myenv
+ c:\>python -m venv myenv c:\path\to\myenv
The command, if run with ``-h``, will show the available options::
@@ -36,25 +44,26 @@ The command, if run with ``-h``, will show the available options::
Creates virtual Python environments in one or more target directories.
positional arguments:
- ENV_DIR A directory to create the environment in.
+ ENV_DIR A directory to create the environment in.
optional arguments:
- -h, --help show this help message and exit
- --system-site-packages Give the virtual environment access to the system
- site-packages dir.
- --symlinks Try to use symlinks rather than copies, when symlinks
- are not the default for the platform.
- --copies Try to use copies rather than symlinks, even when
- symlinks are the default for the platform.
- --clear Delete the contents of the environment directory if it
- already exists, before environment creation.
- --upgrade Upgrade the environment directory to use this version
- of Python, assuming Python has been upgraded in-place.
- --without-pip Skips installing or upgrading pip in the virtual
- environment (pip is bootstrapped by default)
-
-Depending on how the ``venv`` functionality has been invoked, the usage message
-may vary slightly, e.g. referencing ``pyvenv`` rather than ``venv``.
+ -h, --help show this help message and exit
+ --system-site-packages
+ Give the virtual environment access to the system
+ site-packages dir.
+ --symlinks Try to use symlinks rather than copies, when symlinks
+ are not the default for the platform.
+ --copies Try to use copies rather than symlinks, even when
+ symlinks are the default for the platform.
+ --clear Delete the contents of the environment directory if it
+ already exists, before environment creation.
+ --upgrade Upgrade the environment directory to use this version
+ of Python, assuming Python has been upgraded in-place.
+ --without-pip Skips installing or upgrading pip in the virtual
+ environment (pip is bootstrapped by default)
+
+ Once an environment has been created, you may wish to activate it, e.g. by
+ sourcing an activate script in its bin directory.
.. versionchanged:: 3.4
Installs pip by default, added the ``--without-pip`` and ``--copies``
@@ -73,12 +82,13 @@ run with the ``--system-site-packages`` option, ``false`` otherwise.
Unless the ``--without-pip`` option is given, :mod:`ensurepip` will be
invoked to bootstrap ``pip`` into the virtual environment.
-Multiple paths can be given to ``pyvenv``, in which case an identical
-virtualenv will be created, according to the given options, at each
-provided path.
+Multiple paths can be given to ``venv``, in which case an identical virtual
+environment will be created, according to the given options, at each provided
+path.
-Once a venv has been created, it can be "activated" using a script in the
-venv's binary directory. The invocation of the script is platform-specific:
+Once a virtual environment has been created, it can be "activated" using a
+script in the virtual environment's binary directory. The invocation of the
+script is platform-specific:
+-------------+-----------------+-----------------------------------------+
| Platform | Shell | Command to activate virtual environment |
@@ -95,16 +105,17 @@ venv's binary directory. The invocation of the script is platform-specific:
+-------------+-----------------+-----------------------------------------+
You don't specifically *need* to activate an environment; activation just
-prepends the venv's binary directory to your path, so that "python" invokes the
-venv's Python interpreter and you can run installed scripts without having to
-use their full path. However, all scripts installed in a venv should be
-runnable without activating it, and run with the venv's Python automatically.
-
-You can deactivate a venv by typing "deactivate" in your shell. The exact
-mechanism is platform-specific: for example, the Bash activation script defines
-a "deactivate" function, whereas on Windows there are separate scripts called
-``deactivate.bat`` and ``Deactivate.ps1`` which are installed when the venv is
-created.
+prepends the virtual environment's binary directory to your path, so that
+"python" invokes the virtual environment's Python interpreter and you can run
+installed scripts without having to use their full path. However, all scripts
+installed in a virtual environment should be runnable without activating it,
+and run with the virtual environment's Python automatically.
+
+You can deactivate a virtual environment by typing "deactivate" in your shell.
+The exact mechanism is platform-specific: for example, the Bash activation
+script defines a "deactivate" function, whereas on Windows there are separate
+scripts called ``deactivate.bat`` and ``Deactivate.ps1`` which are installed
+when the virtual environment is created.
.. versionadded:: 3.4
``fish`` and ``csh`` activation scripts.
diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst
index a4a6a30..3e4b70e 100644
--- a/Doc/using/windows.rst
+++ b/Doc/using/windows.rst
@@ -29,15 +29,15 @@ Supported Versions
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 3.5 supports Windows Vista and newer. If you require Windows XP support
-then please install Python 3.4.
+Python |version| supports Windows Vista and newer. If you require Windows XP
+support then please install Python 3.4.
Installation Steps
------------------
-Four Python 3.5 installers are available for download - two each for the 32-bit
-and 64-bit versions of the interpreter. The *web installer* is a small initial
-download, and it will automatically download the required components as
+Four Python |version| installers are available for download - two each for the
+32-bit and 64-bit versions of the interpreter. The *web installer* is a small
+initial download, and it will automatically download the required components as
necessary. The *offline installer* includes the components necessary for a
default installation and only requires an internet connection for optional
features. See :ref:`install-layout-option` for other ways to avoid downloading
@@ -74,6 +74,31 @@ installation". In this case:
* If selected, the install directory will be added to the system :envvar:`PATH`
* Shortcuts are available for all users
+.. _max-path:
+
+Removing the MAX_PATH Limitation
+--------------------------------
+
+Windows historically has limited path lengths to 260 characters. This meant that
+paths longer than this would not resolve and errors would result.
+
+In the latest versions of Windows, this limitation can be expanded to
+approximately 32,000 characters. Your administrator will need to activate the
+"Enable Win32 long paths" group policy, or set the registry value
+``HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem@LongPathsEnabled``
+to ``1``.
+
+This allows the :func:`open` function, the :mod:`os` module and most other
+path functionality to accept and return paths longer than 260 characters when
+using strings. (Use of bytes as paths is deprecated on Windows, and this feature
+is not available when using bytes.)
+
+After changing the above option, no further configuration is required.
+
+.. versionchanged:: 3.6
+
+ Support for long paths was enabled in Python.
+
.. _install-quiet-option:
Installing Without UI
@@ -168,13 +193,13 @@ of available options is shown below.
For example, to silently install a default, system-wide Python installation,
you could use the following command (from an elevated command prompt)::
- python-3.5.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
+ python-3.6.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
To allow users to easily install a personal copy of Python without the test
suite, you could provide a shortcut with the following command. This will
display a simplified initial page and disallow customization::
- python-3.5.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
+ python-3.6.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."
(Note that omitting the launcher also omits file associations, and is only
@@ -209,13 +234,13 @@ where a large number of installations are going to be performed it is very
useful to have a locally cached copy.
Execute the following command from Command Prompt to download all possible
-required files. Remember to substitute ``python-3.5.0.exe`` for the actual
+required files. Remember to substitute ``python-3.6.0.exe`` for the actual
name of your installer, and to create layouts in their own directories to
avoid collisions between files with the same name.
::
- python-3.5.0.exe /layout [optional target directory]
+ python-3.6.0.exe /layout [optional target directory]
You may also specify the ``/quiet`` option to hide the progress display.
@@ -320,7 +345,7 @@ User level and the System level, or temporarily in a command prompt.
To temporarily set environment variables, open Command Prompt and use the
:command:`set` command::
- C:\>set PATH=C:\Program Files\Python 3.5;%PATH%
+ C:\>set PATH=C:\Program Files\Python 3.6;%PATH%
C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
C:\>python
@@ -376,10 +401,10 @@ Finding the Python executable
Besides using the automatically created start menu entry for the Python
interpreter, you might want to start Python in the command prompt. The
-installer for Python 3.5 and later has an option to set that up for you.
+installer has an option to set that up for you.
-On the first page of the installer, an option labelled "Add Python 3.5 to
-PATH" can be selected to have the installer add the install location into the
+On the first page of the installer, an option labelled "Add Python to PATH"
+may be selected to have the installer add the install location into the
:envvar:`PATH`. The location of the :file:`Scripts\\` folder is also added.
This allows you to type :command:`python` to run the interpreter, and
:command:`pip` for the package installer. Thus, you can also execute your
@@ -393,7 +418,7 @@ of your Python installation, delimited by a semicolon from other entries. An
example variable could look like this (assuming the first two entries already
existed)::
- C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.5
+ C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.6
.. _launcher:
@@ -418,6 +443,8 @@ Getting started
From the command-line
^^^^^^^^^^^^^^^^^^^^^
+.. versionchanged:: 3.6
+
System-wide installations of Python 3.3 and later will put the launcher on your
:envvar:`PATH`. The launcher is compatible with all available versions of
Python, so it does not matter which version is installed. To check that the
@@ -427,25 +454,26 @@ launcher is available, execute the following command in Command Prompt:
py
-You should find that the latest version of Python 2.x you have installed is
+You should find that the latest version of Python you have installed is
started - it can be exited as normal, and any additional command-line
arguments specified will be sent directly to Python.
-If you have multiple versions of Python 2.x installed (e.g., 2.6 and 2.7) you
-will have noticed that Python 2.7 was started - to launch Python 2.6, try the
-command:
+If you have multiple versions of Python installed (e.g., 2.7 and |version|) you
+will have noticed that Python |version| was started - to launch Python 2.7, try
+the command:
::
- py -2.6
+ py -2.7
-If you have a Python 3.x installed, try the command:
+If you want the latest version of Python 2.x you have installed, try the
+command:
::
- py -3
+ py -2
-You should find the latest version of Python 3.x starts.
+You should find the latest version of Python 2.x starts.
If you see the following error, you do not have the launcher installed:
@@ -500,6 +528,11 @@ version qualifier. Assuming you have Python 2.6 installed, try changing the
first line to ``#! python2.6`` and you should find the 2.6 version
information printed.
+Note that unlike interactive use, a bare "python" will use the latest
+version of Python 2.x that you have installed. This is for backward
+compatibility and for compatibility with Unix, where the command ``python``
+typically refers to Python 2.
+
From file associations
^^^^^^^^^^^^^^^^^^^^^^
@@ -676,7 +709,7 @@ target Python.
-.. finding_modules:
+.. _finding_modules:
Finding modules
===============
@@ -687,7 +720,24 @@ installation directory. So, if you had installed Python to
:file:`C:\\Python\\Lib\\` and third-party modules should be stored in
:file:`C:\\Python\\Lib\\site-packages\\`.
-This is how :data:`sys.path` is populated on Windows:
+To completely override :data:`sys.path`, create a ``._pth`` file with the same
+name as the DLL (``python36._pth``) or the executable (``python._pth``) and
+specify one line for each path to add to :data:`sys.path`. The file based on the
+DLL name overrides the one based on the executable, which allows paths to be
+restricted for any program loading the runtime if desired.
+
+When the file exists, all registry and environment variables are ignored,
+isolated mode is enabled, and :mod:`site` is not imported unless one line in the
+file specifies ``import site``. Blank paths and lines starting with ``#`` are
+ignored. Each path may be absolute or relative to the location of the file.
+Import statements other than to ``site`` are not permitted, and arbitrary code
+cannot be specified.
+
+Note that ``.pth`` files (without leading underscore) will be processed normally
+by the :mod:`site` module.
+
+When no ``._pth`` file is found, this is how :data:`sys.path` is populated on
+Windows:
* An empty entry is added at the start, which corresponds to the current
directory.
@@ -706,10 +756,11 @@ This is how :data:`sys.path` is populated on Windows:
* If the environment variable :envvar:`PYTHONHOME` is set, it is assumed as
"Python Home". Otherwise, the path of the main Python executable is used to
- locate a "landmark file" (``Lib\os.py``) to deduce the "Python Home". If a
- Python home is found, the relevant sub-directories added to :data:`sys.path`
- (``Lib``, ``plat-win``, etc) are based on that folder. Otherwise, the core
- Python path is constructed from the PythonPath stored in the registry.
+ locate a "landmark file" (either ``Lib\os.py`` or ``pythonXY.zip``) to deduce
+ the "Python Home". If a Python home is found, the relevant sub-directories
+ added to :data:`sys.path` (``Lib``, ``plat-win``, etc) are based on that
+ folder. Otherwise, the core Python path is constructed from the PythonPath
+ stored in the registry.
* If the Python Home cannot be located, no :envvar:`PYTHONPATH` is specified in
the environment, and no registry entries can be found, a default path with
@@ -722,10 +773,6 @@ directory one level above the executable, the following variations apply:
path is used instead of the path to the main executable when deducing the
home location.
-* If ``applocal`` is set to true, the ``home`` property or the main executable
- is always used as the home path, and all environment variables or registry
- values affecting the path are ignored. The landmark file is not checked.
-
The end result of all this is:
* When running :file:`python.exe`, or any other .exe in the main Python
@@ -744,13 +791,12 @@ The end result of all this is:
For those who want to bundle Python into their application or distribution, the
following advice will prevent conflicts with other installations:
-* Include a ``pyvenv.cfg`` file alongside your executable containing
- ``applocal = true``. This will ensure that your own directory will be used to
- resolve paths even if you have included the standard library in a ZIP file.
- It will also ignore user site-packages and other paths listed in the
- registry.
+* Include a ``._pth`` file alongside your executable containing the
+ directories to include. This will ignore paths listed in the registry and
+ environment variables, and also ignore :mod:`site` unless ``import site`` is
+ listed.
-* If you are loading :file:`python3.dll` or :file:`python35.dll` in your own
+* If you are loading :file:`python3.dll` or :file:`python36.dll` in your own
executable, explicitly call :c:func:`Py_SetPath` or (at least)
:c:func:`Py_SetProgramName` before :c:func:`Py_Initialize`.
@@ -760,7 +806,8 @@ following advice will prevent conflicts with other installations:
* If you cannot use the previous suggestions (for example, you are a
distribution that allows people to run :file:`python.exe` directly), ensure
that the landmark file (:file:`Lib\\os.py`) exists in your install directory.
- (Note that it will not be detected inside a ZIP file.)
+ (Note that it will not be detected inside a ZIP file, but a correctly named
+ ZIP file will be detected instead.)
These will ensure that the files in a system-wide installation will not take
precedence over the copy of the standard library bundled with your application.
@@ -768,6 +815,22 @@ Otherwise, your users may experience problems using your application. Note that
the first suggestion is the best, as the other may still be susceptible to
non-standard paths in the registry and user site-packages.
+.. versionchanged::
+ 3.6
+
+ * Adds ``._pth`` file support and removes ``applocal`` option from
+ ``pyvenv.cfg``.
+ * Adds ``pythonXX.zip`` as a potential landmark when directly adjacent
+ to the executable.
+
+.. deprecated::
+ 3.6
+
+ Modules specified in the registry under ``Modules`` (not ``PythonPath``)
+ may be imported by :class:`importlib.machinery.WindowsRegistryFinder`.
+ This finder is enabled on Windows in 3.6.0 and earlier, but may need to
+ be explicitly added to :attr:`sys.meta_path` in the future.
+
Additional modules
==================
@@ -867,7 +930,7 @@ directly accessed by end-users.
When extracted, the embedded distribution is (almost) fully isolated from the
user's system, including environment variables, system registry settings, and
installed packages. The standard library is included as pre-compiled and
-optimized ``.pyc`` files in a ZIP, and ``python3.dll``, ``python35.dll``,
+optimized ``.pyc`` files in a ZIP, and ``python3.dll``, ``python36.dll``,
``python.exe`` and ``pythonw.exe`` are all provided. Tcl/tk (including all
dependants, such as Idle), pip and the Python documentation are not included.
diff --git a/Doc/whatsnew/2.1.rst b/Doc/whatsnew/2.1.rst
index 00151d7..380edec 100644
--- a/Doc/whatsnew/2.1.rst
+++ b/Doc/whatsnew/2.1.rst
@@ -367,7 +367,7 @@ dictionary::
This version works for simple things such as integers, but it has a side effect;
the ``_cache`` dictionary holds a reference to the return values, so they'll
-never be deallocated until the Python process exits and cleans up This isn't
+never be deallocated until the Python process exits and cleans up. This isn't
very noticeable for integers, but if :func:`f` returns an object, or a data
structure that takes up a lot of memory, this can be a problem.
diff --git a/Doc/whatsnew/3.2.rst b/Doc/whatsnew/3.2.rst
index 9acc734..b900e77 100644
--- a/Doc/whatsnew/3.2.rst
+++ b/Doc/whatsnew/3.2.rst
@@ -1253,9 +1253,9 @@ definition::
@contextmanager
def track_entry_and_exit(name):
- logging.info('Entering: {}'.format(name))
+ logging.info('Entering: %s', name)
yield
- logging.info('Exiting: {}'.format(name))
+ logging.info('Exiting: %s', name)
Formerly, this would have only been usable as a context manager::
diff --git a/Doc/whatsnew/3.3.rst b/Doc/whatsnew/3.3.rst
index 0c9f2bb..93b297c 100644
--- a/Doc/whatsnew/3.3.rst
+++ b/Doc/whatsnew/3.3.rst
@@ -108,7 +108,7 @@ packages. Their concept and implementation are inspired by the popular
with the interpreter core.
This PEP adds the :mod:`venv` module for programmatic access, and the
-:ref:`pyvenv <scripts-pyvenv>` script for command-line access and
+``pyvenv`` script for command-line access and
administration. The Python interpreter checks for a ``pyvenv.cfg``,
file whose existence signals the base of a virtual environment's directory
tree.
diff --git a/Doc/whatsnew/3.4.rst b/Doc/whatsnew/3.4.rst
index 1e5c9d1..72398f9 100644
--- a/Doc/whatsnew/3.4.rst
+++ b/Doc/whatsnew/3.4.rst
@@ -197,7 +197,7 @@ will also be installed. On other platforms, the system wide unversioned
``pip`` command typically refers to the separately installed Python 2
version.
-The :ref:`pyvenv <scripts-pyvenv>` command line utility and the :mod:`venv`
+The ``pyvenv`` command line utility and the :mod:`venv`
module make use of the :mod:`ensurepip` module to make ``pip`` readily
available in virtual environments. When using the command line utility,
``pip`` is installed by default, while when using the :mod:`venv` module
@@ -824,7 +824,7 @@ currently in the new module, which is being added as part of email's new
:term:`provisional API`. These classes provide a number of new methods that
make extracting content from and inserting content into email messages much
easier. For details, see the :mod:`~email.contentmanager` documentation and
-the :ref:`email-contentmanager-api-examples`. These API additions complete the
+the :ref:`email-examples`. These API additions complete the
bulk of the work that was planned as part of the email6 project. The currently
provisional API is scheduled to become final in Python 3.5 (possibly with a few
minor additions in the area of error handling). (Contributed by R. David
@@ -1989,11 +1989,11 @@ Other Improvements
Stinner using his :pep:`445`-based ``pyfailmalloc`` tool (:issue:`18408`,
:issue:`18520`).
-* The :ref:`pyvenv <scripts-pyvenv>` command now accepts a ``--copies`` option
+* The ``pyvenv`` command now accepts a ``--copies`` option
to use copies rather than symlinks even on systems where symlinks are the
default. (Contributed by Vinay Sajip in :issue:`18807`.)
-* The :ref:`pyvenv <scripts-pyvenv>` command also accepts a ``--without-pip``
+* The ``pyvenv`` command also accepts a ``--without-pip``
option to suppress the otherwise-automatic bootstrapping of pip into
the virtual environment. (Contributed by Nick Coghlan in :issue:`19552`
as part of the :pep:`453` implementation.)
@@ -2459,7 +2459,7 @@ Changes in the Python API
stream in :mod:`~io.TextIOWrapper` to use its *newline* argument
(:issue:`15204`).
-* If you use :ref:`pyvenv <scripts-pyvenv>` in a script and desire that pip
+* If you use ``pyvenv`` in a script and desire that pip
*not* be installed, you must add ``--without-pip`` to your command
invocation.
diff --git a/Doc/whatsnew/3.5.rst b/Doc/whatsnew/3.5.rst
index ab61d7a..edb74f0 100644
--- a/Doc/whatsnew/3.5.rst
+++ b/Doc/whatsnew/3.5.rst
@@ -46,7 +46,8 @@
This article explains the new features in Python 3.5, compared to 3.4.
Python 3.5 was released on September 13, 2015.  See the
-:ref:`changelog <changelog>` for a full list of changes.
+`changelog <https://docs.python.org/3.5/whatsnew/changelog.html>`_ for a full
+list of changes.
.. seealso::
@@ -2175,8 +2176,7 @@ New ``calloc`` functions were added:
* :c:func:`PyMem_RawCalloc`,
* :c:func:`PyMem_Calloc`,
-* :c:func:`PyObject_Calloc`,
-* :c:func:`_PyObject_GC_Calloc`.
+* :c:func:`PyObject_Calloc`.
(Contributed by Victor Stinner in :issue:`21233`.)
diff --git a/Doc/whatsnew/3.6.rst b/Doc/whatsnew/3.6.rst
new file mode 100644
index 0000000..2d483a2
--- /dev/null
+++ b/Doc/whatsnew/3.6.rst
@@ -0,0 +1,2310 @@
+****************************
+ What's New In Python 3.6
+****************************
+
+:Release: |release|
+:Date: |today|
+:Editors: Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>
+
+.. Rules for maintenance:
+
+ * Anyone can add text to this document. Do not spend very much time
+ on the wording of your changes, because your text will probably
+ get rewritten to some degree.
+
+ * The maintainer will go through Misc/NEWS periodically and add
+ changes; it's therefore more important to add your changes to
+ Misc/NEWS than to this file.
+
+ * This is not a complete list of every single change; completeness
+ is the purpose of Misc/NEWS. Some changes I consider too small
+ or esoteric to include. If such a change is added to the text,
+ I'll just remove it. (This is another reason you shouldn't spend
+ too much time on writing your addition.)
+
+ * If you want to draw your new text to the attention of the
+ maintainer, add 'XXX' to the beginning of the paragraph or
+ section.
+
+ * It's OK to just add a fragmentary note about a change. For
+ example: "XXX Describe the transmogrify() function added to the
+ socket module." The maintainer will research the change and
+ write the necessary text.
+
+ * You can comment out your additions if you like, but it's not
+ necessary (especially when a final release is some months away).
+
+ * Credit the author of a patch or bugfix. Just the name is
+ sufficient; the e-mail address isn't necessary.
+
+ * It's helpful to add the bug/patch number as a comment:
+
+ XXX Describe the transmogrify() function added to the socket
+ module.
+ (Contributed by P.Y. Developer in :issue:`12345`.)
+
+ This saves the maintainer the effort of going through the Mercurial log
+ when researching a change.
+
+This article explains the new features in Python 3.6, compared to 3.5.
+Python 3.6 was released on December 23, 2016.  See the
+`changelog <https://docs.python.org/3.6/whatsnew/changelog.html>`_ for a full
+list of changes.
+
+.. seealso::
+
+ :pep:`494` - Python 3.6 Release Schedule
+
+
+Summary -- Release highlights
+=============================
+
+New syntax features:
+
+* :ref:`PEP 498 <whatsnew36-pep498>`, formatted string literals.
+
+* :ref:`PEP 515 <whatsnew36-pep515>`, underscores in numeric literals.
+
+* :ref:`PEP 526 <whatsnew36-pep526>`, syntax for variable annotations.
+
+* :ref:`PEP 525 <whatsnew36-pep525>`, asynchronous generators.
+
+* :ref:`PEP 530 <whatsnew36-pep530>`: asynchronous comprehensions.
+
+
+New library modules:
+
+* :mod:`secrets`: :ref:`PEP 506 -- Adding A Secrets Module To The Standard Library <whatsnew36-pep506>`.
+
+
+CPython implementation improvements:
+
+* The :ref:`dict <typesmapping>` type has been reimplemented to use
+ a :ref:`more compact representation <whatsnew36-compactdict>`
+ based on `a proposal by Raymond Hettinger
+ <https://mail.python.org/pipermail/python-dev/2012-December/123028.html>`_
+ and similar to the `PyPy dict implementation`_. This resulted in dictionaries
+ using 20% to 25% less memory when compared to Python 3.5.
+
+* Customization of class creation has been simplified with the
+ :ref:`new protocol <whatsnew36-pep487>`.
+
+* The class attribute definition order is
+ :ref:`now preserved <whatsnew36-pep520>`.
+
+* The order of elements in ``**kwargs`` now
+ :ref:`corresponds to the order <whatsnew36-pep468>` in which keyword
+ arguments were passed to the function.
+
+* DTrace and SystemTap :ref:`probing support <whatsnew36-tracing>` has
+ been added.
+
+* The new :ref:`PYTHONMALLOC <whatsnew36-pythonmalloc>` environment variable
+ can now be used to debug the interpreter memory allocation and access
+ errors.
+
+
+Significant improvements in the standard library:
+
+* The :mod:`asyncio` module has received new features, significant
+ usability and performance improvements, and a fair amount of bug fixes.
+ Starting with Python 3.6 the ``asyncio`` module is no longer provisional
+ and its API is considered stable.
+
+* A new :ref:`file system path protocol <whatsnew36-pep519>` has been
+ implemented to support :term:`path-like objects <path-like object>`.
+ All standard library functions operating on paths have been updated to
+ work with the new protocol.
+
+* The :mod:`datetime` module has gained support for
+ :ref:`Local Time Disambiguation <whatsnew36-pep495>`.
+
+* The :mod:`typing` module received a number of
+ :ref:`improvements <whatsnew36-typing>` and is no longer provisional.
+
+* The :mod:`tracemalloc` module has been significantly reworked
+ and is now used to provide better output for :exc:`ResourceWarning`
+ as well as provide better diagnostics for memory allocation errors.
+ See the :ref:`PYTHONMALLOC section <whatsnew36-pythonmalloc>` for more
+ information.
+
+
+Security improvements:
+
+* The new :mod:`secrets` module has been added to simplify the generation of
+ cryptographically strong pseudo-random numbers suitable for
+ managing secrets such as account authentication, tokens, and similar.
+
+* On Linux, :func:`os.urandom` now blocks until the system urandom entropy
+ pool is initialized to increase the security. See the :pep:`524` for the
+ rationale.
+
+* The :mod:`hashlib` and :mod:`ssl` modules now support OpenSSL 1.1.0.
+
+* The default settings and feature set of the :mod:`ssl` module have been
+ improved.
+
+* The :mod:`hashlib` module received support for the BLAKE2, SHA-3 and SHAKE
+ hash algorithms and the :func:`~hashlib.scrypt` key derivation function.
+
+
+Windows improvements:
+
+* :ref:`PEP 528 <whatsnew36-pep529>` and :ref:`PEP 529 <whatsnew36-pep529>`,
+ Windows filesystem and console encoding changed to UTF-8.
+
+* The ``py.exe`` launcher, when used interactively, no longer prefers
+ Python 2 over Python 3 when the user doesn't specify a version (via
+ command line arguments or a config file). Handling of shebang lines
+ remains unchanged - "python" refers to Python 2 in that case.
+
+* ``python.exe`` and ``pythonw.exe`` have been marked as long-path aware,
+ which means that the 260 character path limit may no longer apply.
+ See :ref:`removing the MAX_PATH limitation <max-path>` for details.
+
+* A ``._pth`` file can be added to force isolated mode and fully specify
+ all search paths to avoid registry and environment lookup. See
+ :ref:`the documentation <finding_modules>` for more information.
+
+* A ``python36.zip`` file now works as a landmark to infer
+ :envvar:`PYTHONHOME`. See :ref:`the documentation <finding_modules>` for
+ more information.
+
+
+.. _PyPy dict implementation: https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
+
+
+New Features
+============
+
+.. _whatsnew36-pep498:
+
+PEP 498: Formatted string literals
+----------------------------------
+
+:pep:`498` introduces a new kind of string literals: *f-strings*, or
+:ref:`formatted string literals <f-strings>`.
+
+Formatted string literals are prefixed with ``'f'`` and are similar to
+the format strings accepted by :meth:`str.format`. They contain replacement
+fields surrounded by curly braces. The replacement fields are expressions,
+which are evaluated at run time, and then formatted using the
+:func:`format` protocol::
+
+ >>> name = "Fred"
+ >>> f"He said his name is {name}."
+ 'He said his name is Fred.'
+ >>> width = 10
+ >>> precision = 4
+ >>> value = decimal.Decimal("12.34567")
+ >>> f"result: {value:{width}.{precision}}" # nested fields
+ 'result: 12.35'
+
+.. seealso::
+
+ :pep:`498` -- Literal String Interpolation.
+ PEP written and implemented by Eric V. Smith.
+
+ :ref:`Feature documentation <f-strings>`.
+
+
+.. _whatsnew36-pep526:
+
+PEP 526: Syntax for variable annotations
+----------------------------------------
+
+:pep:`484` introduced the standard for type annotations of function
+parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating
+the types of variables including class variables and instance variables::
+
+ primes: List[int] = []
+
+ captain: str # Note: no initial value!
+
+ class Starship:
+ stats: Dict[str, int] = {}
+
+Just as for function annotations, the Python interpreter does not attach any
+particular meaning to variable annotations and only stores them in the
+``__annotations__`` attribute of a class or module.
+
+In contrast to variable declarations in statically typed languages,
+the goal of annotation syntax is to provide an easy way to specify structured
+type metadata for third party tools and libraries via the abstract syntax tree
+and the ``__annotations__`` attribute.
+
+.. seealso::
+
+ :pep:`526` -- Syntax for variable annotations.
+ PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach,
+ and Guido van Rossum. Implemented by Ivan Levkivskyi.
+
+ Tools that use or will use the new syntax:
+ `mypy <http://github.com/python/mypy>`_,
+ `pytype <http://github.com/google/pytype>`_, PyCharm, etc.
+
+
+.. _whatsnew36-pep515:
+
+PEP 515: Underscores in Numeric Literals
+----------------------------------------
+
+:pep:`515` adds the ability to use underscores in numeric literals for
+improved readability. For example::
+
+ >>> 1_000_000_000_000_000
+ 1000000000000000
+ >>> 0x_FF_FF_FF_FF
+ 4294967295
+
+Single underscores are allowed between digits and after any base
+specifier. Leading, trailing, or multiple underscores in a row are not
+allowed.
+
+The :ref:`string formatting <formatspec>` language also now has support
+for the ``'_'`` option to signal the use of an underscore for a thousands
+separator for floating point presentation types and for integer
+presentation type ``'d'``. For integer presentation types ``'b'``,
+``'o'``, ``'x'``, and ``'X'``, underscores will be inserted every 4
+digits::
+
+ >>> '{:_}'.format(1000000)
+ '1_000_000'
+ >>> '{:_x}'.format(0xFFFFFFFF)
+ 'ffff_ffff'
+
+.. seealso::
+
+ :pep:`515` -- Underscores in Numeric Literals
+ PEP written by Georg Brandl and Serhiy Storchaka.
+
+
+.. _whatsnew36-pep525:
+
+PEP 525: Asynchronous Generators
+--------------------------------
+
+:pep:`492` introduced support for native coroutines and ``async`` / ``await``
+syntax to Python 3.5. A notable limitation of the Python 3.5 implementation
+is that it was not possible to use ``await`` and ``yield`` in the same
+function body. In Python 3.6 this restriction has been lifted, making it
+possible to define *asynchronous generators*::
+
+ async def ticker(delay, to):
+ """Yield numbers from 0 to *to* every *delay* seconds."""
+ for i in range(to):
+ yield i
+ await asyncio.sleep(delay)
+
+The new syntax allows for faster and more concise code.
+
+.. seealso::
+
+ :pep:`525` -- Asynchronous Generators
+ PEP written and implemented by Yury Selivanov.
+
+
+.. _whatsnew36-pep530:
+
+PEP 530: Asynchronous Comprehensions
+------------------------------------
+
+:pep:`530` adds support for using ``async for`` in list, set, dict
+comprehensions and generator expressions::
+
+ result = [i async for i in aiter() if i % 2]
+
+Additionally, ``await`` expressions are supported in all kinds
+of comprehensions::
+
+ result = [await fun() for fun in funcs if await condition()]
+
+.. seealso::
+
+ :pep:`530` -- Asynchronous Comprehensions
+ PEP written and implemented by Yury Selivanov.
+
+
+.. _whatsnew36-pep487:
+
+PEP 487: Simpler customization of class creation
+------------------------------------------------
+
+It is now possible to customize subclass creation without using a metaclass.
+The new ``__init_subclass__`` classmethod will be called on the base class
+whenever a new subclass is created::
+
+ class PluginBase:
+ subclasses = []
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ cls.subclasses.append(cls)
+
+ class Plugin1(PluginBase):
+ pass
+
+ class Plugin2(PluginBase):
+ pass
+
+In order to allow zero-argument :func:`super` calls to work correctly from
+:meth:`~object.__init_subclass__` implementations, custom metaclasses must
+ensure that the new ``__classcell__`` namespace entry is propagated to
+``type.__new__`` (as described in :ref:`class-object-creation`).
+
+.. seealso::
+
+ :pep:`487` -- Simpler customization of class creation
+ PEP written and implemented by Martin Teichmann.
+
+ :ref:`Feature documentation <class-customization>`
+
+
+.. _whatsnew36-pep487-descriptors:
+
+PEP 487: Descriptor Protocol Enhancements
+-----------------------------------------
+
+:pep:`487` extends the descriptor protocol to include the new optional
+:meth:`~object.__set_name__` method. Whenever a new class is defined, the new
+method will be called on all descriptors included in the definition, providing
+them with a reference to the class being defined and the name given to the
+descriptor within the class namespace. In other words, instances of
+descriptors can now know the attribute name of the descriptor in the
+owner class::
+
+ class IntField:
+ def __get__(self, instance, owner):
+ return instance.__dict__[self.name]
+
+ def __set__(self, instance, value):
+ if not isinstance(value, int):
+ raise ValueError(f'expecting integer in {self.name}')
+ instance.__dict__[self.name] = value
+
+ # this is the new initializer:
+ def __set_name__(self, owner, name):
+ self.name = name
+
+ class Model:
+ int_field = IntField()
+
+
+.. seealso::
+
+ :pep:`487` -- Simpler customization of class creation
+ PEP written and implemented by Martin Teichmann.
+
+ :ref:`Feature documentation <descriptors>`
+
+
+.. _whatsnew36-pep519:
+
+PEP 519: Adding a file system path protocol
+-------------------------------------------
+
+File system paths have historically been represented as :class:`str`
+or :class:`bytes` objects. This has led to people who write code which
+operate on file system paths to assume that such objects are only one
+of those two types (an :class:`int` representing a file descriptor
+does not count as that is not a file path). Unfortunately that
+assumption prevents alternative object representations of file system
+paths like :mod:`pathlib` from working with pre-existing code,
+including Python's standard library.
+
+To fix this situation, a new interface represented by
+:class:`os.PathLike` has been defined. By implementing the
+:meth:`~os.PathLike.__fspath__` method, an object signals that it
+represents a path. An object can then provide a low-level
+representation of a file system path as a :class:`str` or
+:class:`bytes` object. This means an object is considered
+:term:`path-like <path-like object>` if it implements
+:class:`os.PathLike` or is a :class:`str` or :class:`bytes` object
+which represents a file system path. Code can use :func:`os.fspath`,
+:func:`os.fsdecode`, or :func:`os.fsencode` to explicitly get a
+:class:`str` and/or :class:`bytes` representation of a path-like
+object.
+
+The built-in :func:`open` function has been updated to accept
+:class:`os.PathLike` objects, as have all relevant functions in the
+:mod:`os` and :mod:`os.path` modules, and most other functions and
+classes in the standard library. The :class:`os.DirEntry` class
+and relevant classes in :mod:`pathlib` have also been updated to
+implement :class:`os.PathLike`.
+
+The hope is that updating the fundamental functions for operating
+on file system paths will lead to third-party code to implicitly
+support all :term:`path-like objects <path-like object>` without any
+code changes, or at least very minimal ones (e.g. calling
+:func:`os.fspath` at the beginning of code before operating on a
+path-like object).
+
+Here are some examples of how the new interface allows for
+:class:`pathlib.Path` to be used more easily and transparently with
+pre-existing code::
+
+ >>> import pathlib
+ >>> with open(pathlib.Path("README")) as f:
+ ... contents = f.read()
+ ...
+ >>> import os.path
+ >>> os.path.splitext(pathlib.Path("some_file.txt"))
+ ('some_file', '.txt')
+ >>> os.path.join("/a/b", pathlib.Path("c"))
+ '/a/b/c'
+ >>> import os
+ >>> os.fspath(pathlib.Path("some_file.txt"))
+ 'some_file.txt'
+
+(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)
+
+.. seealso::
+
+ :pep:`519` -- Adding a file system path protocol
+ PEP written by Brett Cannon and Koos Zevenhoven.
+
+
+.. _whatsnew36-pep495:
+
+PEP 495: Local Time Disambiguation
+----------------------------------
+
+In most world locations, there have been and will be times when local clocks
+are moved back. In those times, intervals are introduced in which local
+clocks show the same time twice in the same day. In these situations, the
+information displayed on a local clock (or stored in a Python datetime
+instance) is insufficient to identify a particular moment in time.
+
+:pep:`495` adds the new *fold* attribute to instances of
+:class:`datetime.datetime` and :class:`datetime.time` classes to differentiate
+between two moments in time for which local times are the same::
+
+ >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
+ >>> for i in range(4):
+ ... u = u0 + i*HOUR
+ ... t = u.astimezone(Eastern)
+ ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
+ ...
+ 04:00:00 UTC = 00:00:00 EDT 0
+ 05:00:00 UTC = 01:00:00 EDT 0
+ 06:00:00 UTC = 01:00:00 EST 1
+ 07:00:00 UTC = 02:00:00 EST 0
+
+The values of the :attr:`fold <datetime.datetime.fold>` attribute have the
+value ``0`` for all instances except those that represent the second
+(chronologically) moment in time in an ambiguous case.
+
+.. seealso::
+
+ :pep:`495` -- Local Time Disambiguation
+ PEP written by Alexander Belopolsky and Tim Peters, implementation
+ by Alexander Belopolsky.
+
+
+.. _whatsnew36-pep529:
+
+PEP 529: Change Windows filesystem encoding to UTF-8
+----------------------------------------------------
+
+Representing filesystem paths is best performed with str (Unicode) rather than
+bytes. However, there are some situations where using bytes is sufficient and
+correct.
+
+Prior to Python 3.6, data loss could result when using bytes paths on Windows.
+With this change, using bytes to represent paths is now supported on Windows,
+provided those bytes are encoded with the encoding returned by
+:func:`sys.getfilesystemencoding()`, which now defaults to ``'utf-8'``.
+
+Applications that do not use str to represent paths should use
+:func:`os.fsencode()` and :func:`os.fsdecode()` to ensure their bytes are
+correctly encoded. To revert to the previous behaviour, set
+:envvar:`PYTHONLEGACYWINDOWSFSENCODING` or call
+:func:`sys._enablelegacywindowsfsencoding`.
+
+See :pep:`529` for more information and discussion of code modifications that
+may be required.
+
+
+.. _whatsnew36-pep528:
+
+PEP 528: Change Windows console encoding to UTF-8
+-------------------------------------------------
+
+The default console on Windows will now accept all Unicode characters and
+provide correctly read str objects to Python code. ``sys.stdin``,
+``sys.stdout`` and ``sys.stderr`` now default to utf-8 encoding.
+
+This change only applies when using an interactive console, and not when
+redirecting files or pipes. To revert to the previous behaviour for interactive
+console use, set :envvar:`PYTHONLEGACYWINDOWSIOENCODING`.
+
+.. seealso::
+
+ :pep:`528` -- Change Windows console encoding to UTF-8
+ PEP written and implemented by Steve Dower.
+
+
+.. _whatsnew36-pep520:
+
+PEP 520: Preserving Class Attribute Definition Order
+----------------------------------------------------
+
+Attributes in a class definition body have a natural ordering: the same
+order in which the names appear in the source. This order is now
+preserved in the new class's :attr:`~object.__dict__` attribute.
+
+Also, the effective default class *execution* namespace (returned from
+:ref:`type.__prepare__() <prepare>`) is now an insertion-order-preserving
+mapping.
+
+.. seealso::
+
+ :pep:`520` -- Preserving Class Attribute Definition Order
+ PEP written and implemented by Eric Snow.
+
+
+.. _whatsnew36-pep468:
+
+PEP 468: Preserving Keyword Argument Order
+------------------------------------------
+
+``**kwargs`` in a function signature is now guaranteed to be an
+insertion-order-preserving mapping.
+
+.. seealso::
+
+ :pep:`468` -- Preserving Keyword Argument Order
+ PEP written and implemented by Eric Snow.
+
+
+.. _whatsnew36-compactdict:
+
+New :ref:`dict <typesmapping>` implementation
+---------------------------------------------
+
+The :ref:`dict <typesmapping>` type now uses a "compact" representation
+based on `a proposal by Raymond Hettinger
+<https://mail.python.org/pipermail/python-dev/2012-December/123028.html>`_
+which was `first implemented by PyPy
+<https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html>`_.
+The memory usage of the new :func:`dict` is between 20% and 25% smaller
+compared to Python 3.5.
+
+The order-preserving aspect of this new implementation is considered an
+implementation detail and should not be relied upon (this may change in
+the future, but it is desired to have this new dict implementation in
+the language for a few releases before changing the language spec to mandate
+order-preserving semantics for all current and future Python
+implementations; this also helps preserve backwards-compatibility
+with older versions of the language where random iteration order is
+still in effect, e.g. Python 3.5).
+
+(Contributed by INADA Naoki in :issue:`27350`. Idea
+`originally suggested by Raymond Hettinger
+<https://mail.python.org/pipermail/python-dev/2012-December/123028.html>`_.)
+
+
+.. _whatsnew36-pep523:
+
+PEP 523: Adding a frame evaluation API to CPython
+-------------------------------------------------
+
+While Python provides extensive support to customize how code
+executes, one place it has not done so is in the evaluation of frame
+objects. If you wanted some way to intercept frame evaluation in
+Python there really wasn't any way without directly manipulating
+function pointers for defined functions.
+
+:pep:`523` changes this by providing an API to make frame
+evaluation pluggable at the C level. This will allow for tools such
+as debuggers and JITs to intercept frame evaluation before the
+execution of Python code begins. This enables the use of alternative
+evaluation implementations for Python code, tracking frame
+evaluation, etc.
+
+This API is not part of the limited C API and is marked as private to
+signal that usage of this API is expected to be limited and only
+applicable to very select, low-level use-cases. Semantics of the
+API will change with Python as necessary.
+
+.. seealso::
+
+ :pep:`523` -- Adding a frame evaluation API to CPython
+ PEP written by Brett Cannon and Dino Viehland.
+
+
+.. _whatsnew36-pythonmalloc:
+
+PYTHONMALLOC environment variable
+---------------------------------
+
+The new :envvar:`PYTHONMALLOC` environment variable allows setting the Python
+memory allocators and installing debug hooks.
+
+It is now possible to install debug hooks on Python memory allocators on Python
+compiled in release mode using ``PYTHONMALLOC=debug``. Effects of debug hooks:
+
+* Newly allocated memory is filled with the byte ``0xCB``
+* Freed memory is filled with the byte ``0xDB``
+* Detect violations of the Python memory allocator API. For example,
+ :c:func:`PyObject_Free` called on a memory block allocated by
+ :c:func:`PyMem_Malloc`.
+* Detect writes before the start of a buffer (buffer underflows)
+* Detect writes after the end of a buffer (buffer overflows)
+* Check that the :term:`GIL <global interpreter lock>` is held when allocator
+ functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) and
+ :c:data:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) domains are called.
+
+Checking if the GIL is held is also a new feature of Python 3.6.
+
+See the :c:func:`PyMem_SetupDebugHooks` function for debug hooks on Python
+memory allocators.
+
+It is now also possible to force the usage of the :c:func:`malloc` allocator of
+the C library for all Python memory allocations using ``PYTHONMALLOC=malloc``.
+This is helpful when using external memory debuggers like Valgrind on
+a Python compiled in release mode.
+
+On error, the debug hooks on Python memory allocators now use the
+:mod:`tracemalloc` module to get the traceback where a memory block was
+allocated.
+
+Example of fatal error on buffer overflow using
+``python3.6 -X tracemalloc=5`` (store 5 frames in traces)::
+
+ Debug memory block at address p=0x7fbcd41666f8: API 'o'
+ 4 bytes originally requested
+ The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
+ The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
+ at tail+0: 0x02 *** OUCH
+ at tail+1: 0xfb
+ at tail+2: 0xfb
+ at tail+3: 0xfb
+ at tail+4: 0xfb
+ at tail+5: 0xfb
+ at tail+6: 0xfb
+ at tail+7: 0xfb
+ The block was made by call #1233329 to debug malloc/realloc.
+ Data at p: 1a 2b 30 00
+
+ Memory block allocated at (most recent call first):
+ File "test/test_bytes.py", line 323
+ File "unittest/case.py", line 600
+ File "unittest/case.py", line 648
+ File "unittest/suite.py", line 122
+ File "unittest/suite.py", line 84
+
+ Fatal Python error: bad trailing pad byte
+
+ Current thread 0x00007fbcdbd32700 (most recent call first):
+ File "test/test_bytes.py", line 323 in test_hex
+ File "unittest/case.py", line 600 in run
+ File "unittest/case.py", line 648 in __call__
+ File "unittest/suite.py", line 122 in run
+ File "unittest/suite.py", line 84 in __call__
+ File "unittest/suite.py", line 122 in run
+ File "unittest/suite.py", line 84 in __call__
+ ...
+
+(Contributed by Victor Stinner in :issue:`26516` and :issue:`26564`.)
+
+
+.. _whatsnew36-tracing:
+
+DTrace and SystemTap probing support
+------------------------------------
+
+Python can now be built ``--with-dtrace`` which enables static markers
+for the following events in the interpreter:
+
+* function call/return
+
+* garbage collection started/finished
+
+* line of code executed.
+
+This can be used to instrument running interpreters in production,
+without the need to recompile specific debug builds or providing
+application-specific profiling/debugging code.
+
+More details in :ref:`instrumentation`.
+
+The current implementation is tested on Linux and macOS. Additional
+markers may be added in the future.
+
+(Contributed by Łukasz Langa in :issue:`21590`, based on patches by
+Jesús Cea Avión, David Malcolm, and Nikhil Benesch.)
+
+
+Other Language Changes
+======================
+
+Some smaller changes made to the core Python language are:
+
+* A ``global`` or ``nonlocal`` statement must now textually appear
+ before the first use of the affected name in the same scope.
+ Previously this was a ``SyntaxWarning``.
+
+* It is now possible to set a :ref:`special method <specialnames>` to
+ ``None`` to indicate that the corresponding operation is not available.
+ For example, if a class sets :meth:`__iter__` to ``None``, the class
+ is not iterable.
+ (Contributed by Andrew Barnert and Ivan Levkivskyi in :issue:`25958`.)
+
+* Long sequences of repeated traceback lines are now abbreviated as
+ ``"[Previous line repeated {count} more times]"`` (see
+ :ref:`whatsnew36-traceback` for an example).
+ (Contributed by Emanuel Barry in :issue:`26823`.)
+
+* Import now raises the new exception :exc:`ModuleNotFoundError`
+ (subclass of :exc:`ImportError`) when it cannot find a module. Code
+ that currently checks for ImportError (in try-except) will still work.
+ (Contributed by Eric Snow in :issue:`15767`.)
+
+* Class methods relying on zero-argument ``super()`` will now work correctly
+ when called from metaclass methods during class creation.
+ (Contributed by Martin Teichmann in :issue:`23722`.)
+
+
+New Modules
+===========
+
+.. _whatsnew36-pep506:
+
+secrets
+-------
+
+The main purpose of the new :mod:`secrets` module is to provide an obvious way
+to reliably generate cryptographically strong pseudo-random values suitable
+for managing secrets, such as account authentication, tokens, and similar.
+
+.. warning::
+
+ Note that the pseudo-random generators in the :mod:`random` module
+ should *NOT* be used for security purposes. Use :mod:`secrets`
+ on Python 3.6+ and :func:`os.urandom()` on Python 3.5 and earlier.
+
+.. seealso::
+
+ :pep:`506` -- Adding A Secrets Module To The Standard Library
+ PEP written and implemented by Steven D'Aprano.
+
+
+Improved Modules
+================
+
+array
+-----
+
+Exhausted iterators of :class:`array.array` will now stay exhausted even
+if the iterated array is extended. This is consistent with the behavior
+of other mutable sequences.
+
+Contributed by Serhiy Storchaka in :issue:`26492`.
+
+ast
+---
+
+The new :class:`ast.Constant` AST node has been added. It can be used
+by external AST optimizers for the purposes of constant folding.
+
+Contributed by Victor Stinner in :issue:`26146`.
+
+
+asyncio
+-------
+
+Starting with Python 3.6 the ``asyncio`` module is no longer provisional and its
+API is considered stable.
+
+Notable changes in the :mod:`asyncio` module since Python 3.5.0
+(all backported to 3.5.x due to the provisional status):
+
+* The :func:`~asyncio.get_event_loop` function has been changed to
+ always return the currently running loop when called from couroutines
+ and callbacks.
+ (Contributed by Yury Selivanov in :issue:`28613`.)
+
+* The :func:`~asyncio.ensure_future` function and all functions that
+ use it, such as :meth:`loop.run_until_complete() <asyncio.BaseEventLoop.run_until_complete>`,
+ now accept all kinds of :term:`awaitable objects <awaitable>`.
+ (Contributed by Yury Selivanov.)
+
+* New :func:`~asyncio.run_coroutine_threadsafe` function to submit
+ coroutines to event loops from other threads.
+ (Contributed by Vincent Michel.)
+
+* New :meth:`Transport.is_closing() <asyncio.BaseTransport.is_closing>`
+ method to check if the transport is closing or closed.
+ (Contributed by Yury Selivanov.)
+
+* The :meth:`loop.create_server() <asyncio.BaseEventLoop.create_server>`
+ method can now accept a list of hosts.
+ (Contributed by Yann Sionneau.)
+
+* New :meth:`loop.create_future() <asyncio.BaseEventLoop.create_future>`
+ method to create Future objects. This allows alternative event
+ loop implementations, such as
+ `uvloop <https://github.com/MagicStack/uvloop>`_, to provide a faster
+ :class:`asyncio.Future` implementation.
+ (Contributed by Yury Selivanov in :issue:`27041`.)
+
+* New :meth:`loop.get_exception_handler() <asyncio.BaseEventLoop.get_exception_handler>`
+ method to get the current exception handler.
+ (Contributed by Yury Selivanov in :issue:`27040`.)
+
+* New :meth:`StreamReader.readuntil() <asyncio.StreamReader.readuntil>`
+ method to read data from the stream until a separator bytes
+ sequence appears.
+ (Contributed by Mark Korenberg.)
+
+* The performance of :meth:`StreamReader.readexactly() <asyncio.StreamReader.readexactly>`
+ has been improved.
+ (Contributed by Mark Korenberg in :issue:`28370`.)
+
+* The :meth:`loop.getaddrinfo() <asyncio.BaseEventLoop.getaddrinfo>`
+ method is optimized to avoid calling the system ``getaddrinfo``
+ function if the address is already resolved.
+ (Contributed by A. Jesse Jiryu Davis.)
+
+* The :meth:`loop.stop() <asyncio.BaseEventLoop.stop>`
+ method has been changed to stop the loop immediately after
+ the current iteration. Any new callbacks scheduled as a result
+ of the last iteration will be discarded.
+ (Contributed by Guido van Rossum in :issue:`25593`.)
+
+* :meth:`Future.set_exception <asyncio.futures.Future.set_exception>`
+ will now raise :exc:`TypeError` when passed an instance of
+ the :exc:`StopIteration` exception.
+ (Contributed by Chris Angelico in :issue:`26221`.)
+
+* New :meth:`loop.connect_accepted_socket() <asyncio.BaseEventLoop.connect_accepted_socket>`
+ method to be used by servers that accept connections outside of asyncio,
+ but that use asyncio to handle them.
+ (Contributed by Jim Fulton in :issue:`27392`.)
+
+* ``TCP_NODELAY`` flag is now set for all TCP transports by default.
+ (Contributed by Yury Selivanov in :issue:`27456`.)
+
+* New :meth:`loop.shutdown_asyncgens() <asyncio.AbstractEventLoop.shutdown_asyncgens>`
+ to properly close pending asynchronous generators before closing the
+ loop.
+ (Contributed by Yury Selivanov in :issue:`28003`.)
+
+* :class:`Future <asyncio.Future>` and :class:`Task <asyncio.Task>`
+ classes now have an optimized C implementation which makes asyncio
+ code up to 30% faster.
+ (Contributed by Yury Selivanov and INADA Naoki in :issue:`26081`
+ and :issue:`28544`.)
+
+
+binascii
+--------
+
+The :func:`~binascii.b2a_base64` function now accepts an optional *newline*
+keyword argument to control whether the newline character is appended to the
+return value.
+(Contributed by Victor Stinner in :issue:`25357`.)
+
+
+cmath
+-----
+
+The new :const:`cmath.tau` (τ) constant has been added.
+(Contributed by Lisa Roach in :issue:`12345`, see :pep:`628` for details.)
+
+New constants: :const:`cmath.inf` and :const:`cmath.nan` to
+match :const:`math.inf` and :const:`math.nan`, and also :const:`cmath.infj`
+and :const:`cmath.nanj` to match the format used by complex repr.
+(Contributed by Mark Dickinson in :issue:`23229`.)
+
+
+collections
+-----------
+
+The new :class:`~collections.abc.Collection` abstract base class has been
+added to represent sized iterable container classes.
+(Contributed by Ivan Levkivskyi, docs by Neil Girdhar in :issue:`27598`.)
+
+The new :class:`~collections.abc.Reversible` abstract base class represents
+iterable classes that also provide the :meth:`__reversed__` method.
+(Contributed by Ivan Levkivskyi in :issue:`25987`.)
+
+The new :class:`~collections.abc.AsyncGenerator` abstract base class represents
+asynchronous generators.
+(Contributed by Yury Selivanov in :issue:`28720`.)
+
+The :func:`~collections.namedtuple` function now accepts an optional
+keyword argument *module*, which, when specified, is used for
+the ``__module__`` attribute of the returned named tuple class.
+(Contributed by Raymond Hettinger in :issue:`17941`.)
+
+The *verbose* and *rename* arguments for
+:func:`~collections.namedtuple` are now keyword-only.
+(Contributed by Raymond Hettinger in :issue:`25628`.)
+
+Recursive :class:`collections.deque` instances can now be pickled.
+(Contributed by Serhiy Storchaka in :issue:`26482`.)
+
+
+concurrent.futures
+------------------
+
+The :class:`ThreadPoolExecutor <concurrent.futures.ThreadPoolExecutor>`
+class constructor now accepts an optional *thread_name_prefix* argument
+to make it possible to customize the names of the threads created by the
+pool.
+(Contributed by Gregory P. Smith in :issue:`27664`.)
+
+
+contextlib
+----------
+
+The :class:`contextlib.AbstractContextManager` class has been added to
+provide an abstract base class for context managers. It provides a
+sensible default implementation for `__enter__()` which returns
+``self`` and leaves `__exit__()` an abstract method. A matching
+class has been added to the :mod:`typing` module as
+:class:`typing.ContextManager`.
+(Contributed by Brett Cannon in :issue:`25609`.)
+
+
+datetime
+--------
+
+The :class:`~datetime.datetime` and :class:`~datetime.time` classes have
+the new :attr:`~time.fold` attribute used to disambiguate local time
+when necessary. Many functions in the :mod:`datetime` have been
+updated to support local time disambiguation.
+See :ref:`Local Time Disambiguation <whatsnew36-pep495>` section for more
+information.
+(Contributed by Alexander Belopolsky in :issue:`24773`.)
+
+The :meth:`datetime.strftime() <datetime.datetime.strftime>` and
+:meth:`date.strftime() <datetime.date.strftime>` methods now support
+ISO 8601 date directives ``%G``, ``%u`` and ``%V``.
+(Contributed by Ashley Anderson in :issue:`12006`.)
+
+The :func:`datetime.isoformat() <datetime.datetime.isoformat>` function
+now accepts an optional *timespec* argument that specifies the number
+of additional components of the time value to include.
+(Contributed by Alessandro Cucci and Alexander Belopolsky in :issue:`19475`.)
+
+The :meth:`datetime.combine() <datetime.datetime.combine>` now
+accepts an optional *tzinfo* argument.
+(Contributed by Alexander Belopolsky in :issue:`27661`.)
+
+
+decimal
+-------
+
+New :meth:`Decimal.as_integer_ratio() <decimal.Decimal.as_integer_ratio>`
+method that returns a pair ``(n, d)`` of integers that represent the given
+:class:`~decimal.Decimal` instance as a fraction, in lowest terms and
+with a positive denominator::
+
+ >>> Decimal('-3.14').as_integer_ratio()
+ (-157, 50)
+
+(Contributed by Stefan Krah amd Mark Dickinson in :issue:`25928`.)
+
+
+
+distutils
+---------
+
+The ``default_format`` attribute has been removed from
+:class:`distutils.command.sdist.sdist` and the ``formats``
+attribute defaults to ``['gztar']``. Although not anticipated,
+any code relying on the presence of ``default_format`` may
+need to be adapted. See :issue:`27819` for more details.
+
+
+email
+-----
+
+The new email API, enabled via the *policy* keyword to various constructors, is
+no longer provisional. The :mod:`email` documentation has been reorganized and
+rewritten to focus on the new API, while retaining the old documentation for
+the legacy API. (Contributed by R. David Murray in :issue:`24277`.)
+
+The :mod:`email.mime` classes now all accept an optional *policy* keyword.
+(Contributed by Berker Peksag in :issue:`27331`.)
+
+The :class:`~email.generator.DecodedGenerator` now supports the *policy*
+keyword.
+
+There is a new :mod:`~email.policy` attribute,
+:attr:`~email.policy.Policy.message_factory`, that controls what class is used
+by default when the parser creates new message objects. For the
+:attr:`email.policy.compat32` policy this is :class:`~email.message.Message`,
+for the new policies it is :class:`~email.message.EmailMessage`.
+(Contributed by R. David Murray in :issue:`20476`.)
+
+
+encodings
+---------
+
+On Windows, added the ``'oem'`` encoding to use ``CP_OEMCP``, and the ``'ansi'``
+alias for the existing ``'mbcs'`` encoding, which uses the ``CP_ACP`` code page.
+(Contributed by Steve Dower in :issue:`27959`.)
+
+
+enum
+----
+
+Two new enumeration base classes have been added to the :mod:`enum` module:
+:class:`~enum.Flag` and :class:`~enum.IntFlags`. Both are used to define
+constants that can be combined using the bitwise operators.
+(Contributed by Ethan Furman in :issue:`23591`.)
+
+Many standard library modules have been updated to use the
+:class:`~enum.IntFlags` class for their constants.
+
+The new :class:`enum.auto` value can be used to assign values to enum
+members automatically::
+
+ >>> from enum import Enum, auto
+ >>> class Color(Enum):
+ ... red = auto()
+ ... blue = auto()
+ ... green = auto()
+ ...
+ >>> list(Color)
+ [<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
+
+
+faulthandler
+------------
+
+On Windows, the :mod:`faulthandler` module now installs a handler for Windows
+exceptions: see :func:`faulthandler.enable`. (Contributed by Victor Stinner in
+:issue:`23848`.)
+
+
+fileinput
+---------
+
+:func:`~fileinput.hook_encoded` now supports the *errors* argument.
+(Contributed by Joseph Hackman in :issue:`25788`.)
+
+
+hashlib
+-------
+
+:mod:`hashlib` supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2.
+(Contributed by Christian Heimes in :issue:`26470`.)
+
+BLAKE2 hash functions were added to the module. :func:`~hashlib.blake2b`
+and :func:`~hashlib.blake2s` are always available and support the full
+feature set of BLAKE2.
+(Contributed by Christian Heimes in :issue:`26798` based on code by
+Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)
+
+The SHA-3 hash functions :func:`~hashlib.sha3_224`, :func:`~hashlib.sha3_256`,
+:func:`~hashlib.sha3_384`, :func:`~hashlib.sha3_512`, and SHAKE hash functions
+:func:`~hashlib.shake_128` and :func:`~hashlib.shake_256` were added.
+(Contributed by Christian Heimes in :issue:`16113`. Keccak Code Package
+by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and
+Ronny Van Keer.)
+
+The password-based key derivation function :func:`~hashlib.scrypt` is now
+available with OpenSSL 1.1.0 and newer.
+(Contributed by Christian Heimes in :issue:`27928`.)
+
+http.client
+-----------
+
+:meth:`HTTPConnection.request() <http.client.HTTPConnection.request>` and
+:meth:`~http.client.HTTPConnection.endheaders` both now support
+chunked encoding request bodies.
+(Contributed by Demian Brecht and Rolf Krahl in :issue:`12319`.)
+
+
+idlelib and IDLE
+----------------
+
+The idlelib package is being modernized and refactored to make IDLE look and
+work better and to make the code easier to understand, test, and improve. Part
+of making IDLE look better, especially on Linux and Mac, is using ttk widgets,
+mostly in the dialogs. As a result, IDLE no longer runs with tcl/tk 8.4. It
+now requires tcl/tk 8.5 or 8.6. We recommend running the latest release of
+either.
+
+'Modernizing' includes renaming and consolidation of idlelib modules. The
+renaming of files with partial uppercase names is similar to the renaming of,
+for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0. As a
+result, imports of idlelib files that worked in 3.5 will usually not work in
+3.6. At least a module name change will be needed (see idlelib/README.txt),
+sometimes more. (Name changes contributed by Al Swiegart and Terry Reedy in
+:issue:`24225`. Most idlelib patches since have been and will be part of the
+process.)
+
+In compensation, the eventual result with be that some idlelib classes will be
+easier to use, with better APIs and docstrings explaining them. Additional
+useful information will be added to idlelib when available.
+
+
+importlib
+---------
+
+Import now raises the new exception :exc:`ModuleNotFoundError`
+(subclass of :exc:`ImportError`) when it cannot find a module. Code
+that current checks for ``ImportError`` (in try-except) will still work.
+(Contributed by Eric Snow in :issue:`15767`.)
+
+:class:`importlib.util.LazyLoader` now calls
+:meth:`~importlib.abc.Loader.create_module` on the wrapped loader, removing the
+restriction that :class:`importlib.machinery.BuiltinImporter` and
+:class:`importlib.machinery.ExtensionFileLoader` couldn't be used with
+:class:`importlib.util.LazyLoader`.
+
+:func:`importlib.util.cache_from_source`,
+:func:`importlib.util.source_from_cache`, and
+:func:`importlib.util.spec_from_file_location` now accept a
+:term:`path-like object`.
+
+
+inspect
+-------
+
+The :func:`inspect.signature() <inspect.signature>` function now reports the
+implicit ``.0`` parameters generated by the compiler for comprehension and
+generator expression scopes as if they were positional-only parameters called
+``implicit0``. (Contributed by Jelle Zijlstra in :issue:`19611`.)
+
+To reduce code churn when upgrading from Python 2.7 and the legacy
+:func:`inspect.getargspec` API, the previously documented deprecation of
+:func:`inspect.getfullargspec` has been reversed. While this function is
+convenient for single/source Python 2/3 code bases, the richer
+:func:`inspect.signature` interface remains the recommended approach for new
+code. (Contributed by Nick Coghlan in :issue:`27172`)
+
+
+json
+----
+
+:func:`json.load` and :func:`json.loads` now support binary input. Encoded
+JSON should be represented using either UTF-8, UTF-16, or UTF-32.
+(Contributed by Serhiy Storchaka in :issue:`17909`.)
+
+
+logging
+-------
+
+The new :meth:`WatchedFileHandler.reopenIfNeeded() <logging.handlers.WatchedFileHandler.reopenIfNeeded>`
+method has been added to add the ability to check if the log file needs to
+be reopened.
+(Contributed by Marian Horban in :issue:`24884`.)
+
+
+math
+----
+
+The tau (τ) constant has been added to the :mod:`math` and :mod:`cmath`
+modules.
+(Contributed by Lisa Roach in :issue:`12345`, see :pep:`628` for details.)
+
+
+multiprocessing
+---------------
+
+:ref:`Proxy Objects <multiprocessing-proxy_objects>` returned by
+:func:`multiprocessing.Manager` can now be nested.
+(Contributed by Davin Potts in :issue:`6766`.)
+
+
+os
+--
+
+See the summary of :ref:`PEP 519 <whatsnew36-pep519>` for details on how the
+:mod:`os` and :mod:`os.path` modules now support
+:term:`path-like objects <path-like object>`.
+
+:func:`~os.scandir` now supports :class:`bytes` paths on Windows.
+
+A new :meth:`~os.scandir.close` method allows explicitly closing a
+:func:`~os.scandir` iterator. The :func:`~os.scandir` iterator now
+supports the :term:`context manager` protocol. If a :func:`scandir`
+iterator is neither exhausted nor explicitly closed a :exc:`ResourceWarning`
+will be emitted in its destructor.
+(Contributed by Serhiy Storchaka in :issue:`25994`.)
+
+On Linux, :func:`os.urandom` now blocks until the system urandom entropy pool
+is initialized to increase the security. See the :pep:`524` for the rationale.
+
+The Linux ``getrandom()`` syscall (get random bytes) is now exposed as the new
+:func:`os.getrandom` function.
+(Contributed by Victor Stinner, part of the :pep:`524`)
+
+
+pathlib
+-------
+
+:mod:`pathlib` now supports :term:`path-like objects <path-like object>`.
+(Contributed by Brett Cannon in :issue:`27186`.)
+
+See the summary of :ref:`PEP 519 <whatsnew36-pep519>` for details.
+
+
+pdb
+---
+
+The :class:`~pdb.Pdb` class constructor has a new optional *readrc* argument
+to control whether ``.pdbrc`` files should be read.
+
+
+pickle
+------
+
+Objects that need ``__new__`` called with keyword arguments can now be pickled
+using :ref:`pickle protocols <pickle-protocols>` older than protocol version 4.
+Protocol version 4 already supports this case. (Contributed by Serhiy
+Storchaka in :issue:`24164`.)
+
+
+pickletools
+-----------
+
+:func:`pickletools.dis()` now outputs the implicit memo index for the
+``MEMOIZE`` opcode.
+(Contributed by Serhiy Storchaka in :issue:`25382`.)
+
+
+pydoc
+-----
+
+The :mod:`pydoc` module has learned to respect the ``MANPAGER``
+environment variable.
+(Contributed by Matthias Klose in :issue:`8637`.)
+
+:func:`help` and :mod:`pydoc` can now list named tuple fields in the
+order they were defined rather than alphabetically.
+(Contributed by Raymond Hettinger in :issue:`24879`.)
+
+
+random
+-------
+
+The new :func:`~random.choices` function returns a list of elements of
+specified size from the given population with optional weights.
+(Contributed by Raymond Hettinger in :issue:`18844`.)
+
+
+re
+--
+
+Added support of modifier spans in regular expressions. Examples:
+``'(?i:p)ython'`` matches ``'python'`` and ``'Python'``, but not ``'PYTHON'``;
+``'(?i)g(?-i:v)r'`` matches ``'GvR'`` and ``'gvr'``, but not ``'GVR'``.
+(Contributed by Serhiy Storchaka in :issue:`433028`.)
+
+Match object groups can be accessed by ``__getitem__``, which is
+equivalent to ``group()``. So ``mo['name']`` is now equivalent to
+``mo.group('name')``. (Contributed by Eric Smith in :issue:`24454`.)
+
+:class:`~re.Match` objects now support
+:meth:`index-like objects <object.__index__>` as group
+indices.
+(Contributed by Jeroen Demeyer and Xiang Zhang in :issue:`27177`.)
+
+
+readline
+--------
+
+Added :func:`~readline.set_auto_history` to enable or disable
+automatic addition of input to the history list. (Contributed by
+Tyler Crompton in :issue:`26870`.)
+
+
+rlcompleter
+-----------
+
+Private and special attribute names now are omitted unless the prefix starts
+with underscores. A space or a colon is added after some completed keywords.
+(Contributed by Serhiy Storchaka in :issue:`25011` and :issue:`25209`.)
+
+
+shlex
+-----
+
+The :class:`~shlex.shlex` has much
+:ref:`improved shell compatibility <improved-shell-compatibility>`
+through the new *punctuation_chars* argument to control which characters
+are treated as punctuation.
+(Contributed by Vinay Sajip in :issue:`1521950`.)
+
+
+site
+----
+
+When specifying paths to add to :attr:`sys.path` in a `.pth` file,
+you may now specify file paths on top of directories (e.g. zip files).
+(Contributed by Wolfgang Langner in :issue:`26587`).
+
+
+sqlite3
+-------
+
+:attr:`sqlite3.Cursor.lastrowid` now supports the ``REPLACE`` statement.
+(Contributed by Alex LordThorsen in :issue:`16864`.)
+
+
+socket
+------
+
+The :func:`~socket.socket.ioctl` function now supports the
+:data:`~socket.SIO_LOOPBACK_FAST_PATH` control code.
+(Contributed by Daniel Stokes in :issue:`26536`.)
+
+The :meth:`~socket.socket.getsockopt` constants ``SO_DOMAIN``,
+``SO_PROTOCOL``, ``SO_PEERSEC``, and ``SO_PASSSEC`` are now supported.
+(Contributed by Christian Heimes in :issue:`26907`.)
+
+The :meth:`~socket.socket.setsockopt` now supports the
+``setsockopt(level, optname, None, optlen: int)`` form.
+(Contributed by Christian Heimes in :issue:`27744`.)
+
+The socket module now supports the address family
+:data:`~socket.AF_ALG` to interface with Linux Kernel crypto API. ``ALG_*``,
+``SOL_ALG`` and :meth:`~socket.socket.sendmsg_afalg` were added.
+(Contributed by Christian Heimes in :issue:`27744` with support from
+Victor Stinner.)
+
+
+socketserver
+------------
+
+Servers based on the :mod:`socketserver` module, including those
+defined in :mod:`http.server`, :mod:`xmlrpc.server` and
+:mod:`wsgiref.simple_server`, now support the :term:`context manager`
+protocol.
+(Contributed by Aviv Palivoda in :issue:`26404`.)
+
+The :attr:`~socketserver.StreamRequestHandler.wfile` attribute of
+:class:`~socketserver.StreamRequestHandler` classes now implements
+the :class:`io.BufferedIOBase` writable interface. In particular,
+calling :meth:`~io.BufferedIOBase.write` is now guaranteed to send the
+data in full. (Contributed by Martin Panter in :issue:`26721`.)
+
+
+ssl
+---
+
+:mod:`ssl` supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2.
+(Contributed by Christian Heimes in :issue:`26470`.)
+
+3DES has been removed from the default cipher suites and ChaCha20 Poly1305
+cipher suites have been added.
+(Contributed by Christian Heimes in :issue:`27850` and :issue:`27766`.)
+
+:class:`~ssl.SSLContext` has better default configuration for options
+and ciphers.
+(Contributed by Christian Heimes in :issue:`28043`.)
+
+SSL session can be copied from one client-side connection to another
+with the new :class:`~ssl.SSLSession` class. TLS session resumption can
+speed up the initial handshake, reduce latency and improve performance
+(Contributed by Christian Heimes in :issue:`19500` based on a draft by
+Alex Warhawk.)
+
+The new :meth:`~ssl.SSLContext.get_ciphers` method can be used to
+get a list of enabled ciphers in order of cipher priority.
+
+All constants and flags have been converted to :class:`~enum.IntEnum` and
+:class:`~enum.IntFlags`.
+(Contributed by Christian Heimes in :issue:`28025`.)
+
+Server and client-side specific TLS protocols for :class:`~ssl.SSLContext`
+were added.
+(Contributed by Christian Heimes in :issue:`28085`.)
+
+
+statistics
+----------
+
+A new :func:`~statistics.harmonic_mean` function has been added.
+(Contributed by Steven D'Aprano in :issue:`27181`.)
+
+
+struct
+------
+
+:mod:`struct` now supports IEEE 754 half-precision floats via the ``'e'``
+format specifier.
+(Contributed by Eli Stevens, Mark Dickinson in :issue:`11734`.)
+
+
+subprocess
+----------
+
+:class:`subprocess.Popen` destructor now emits a :exc:`ResourceWarning` warning
+if the child process is still running. Use the context manager protocol (``with
+proc: ...``) or explicitly call the :meth:`~subprocess.Popen.wait` method to
+read the exit status of the child process. (Contributed by Victor Stinner in
+:issue:`26741`.)
+
+The :class:`subprocess.Popen` constructor and all functions that pass arguments
+through to it now accept *encoding* and *errors* arguments. Specifying either
+of these will enable text mode for the *stdin*, *stdout* and *stderr* streams.
+(Contributed by Steve Dower in :issue:`6135`.)
+
+
+sys
+---
+
+The new :func:`~sys.getfilesystemencodeerrors` function returns the name of
+the error mode used to convert between Unicode filenames and bytes filenames.
+(Contributed by Steve Dower in :issue:`27781`.)
+
+On Windows the return value of the :func:`~sys.getwindowsversion` function
+now includes the *platform_version* field which contains the accurate major
+version, minor version and build number of the current operating system,
+rather than the version that is being emulated for the process
+(Contributed by Steve Dower in :issue:`27932`.)
+
+
+telnetlib
+---------
+
+:class:`~telnetlib.Telnet` is now a context manager (contributed by
+Stéphane Wirtel in :issue:`25485`).
+
+
+time
+----
+
+The :class:`~time.struct_time` attributes :attr:`tm_gmtoff` and
+:attr:`tm_zone` are now available on all platforms.
+
+
+timeit
+------
+
+The new :meth:`Timer.autorange() <timeit.Timer.autorange>` convenience
+method has been added to call :meth:`Timer.timeit() <timeit.Timer.timeit>`
+repeatedly so that the total run time is greater or equal to 200 milliseconds.
+(Contributed by Steven D'Aprano in :issue:`6422`.)
+
+:mod:`timeit` now warns when there is substantial (4x) variance
+between best and worst times.
+(Contributed by Serhiy Storchaka in :issue:`23552`.)
+
+
+tkinter
+-------
+
+Added methods :meth:`~tkinter.Variable.trace_add`,
+:meth:`~tkinter.Variable.trace_remove` and :meth:`~tkinter.Variable.trace_info`
+in the :class:`tkinter.Variable` class. They replace old methods
+:meth:`~tkinter.Variable.trace_variable`, :meth:`~tkinter.Variable.trace`,
+:meth:`~tkinter.Variable.trace_vdelete` and
+:meth:`~tkinter.Variable.trace_vinfo` that use obsolete Tcl commands and might
+not work in future versions of Tcl.
+(Contributed by Serhiy Storchaka in :issue:`22115`).
+
+
+.. _whatsnew36-traceback:
+
+traceback
+---------
+
+Both the traceback module and the interpreter's builtin exception display now
+abbreviate long sequences of repeated lines in tracebacks as shown in the
+following example::
+
+ >>> def f(): f()
+ ...
+ >>> f()
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "<stdin>", line 1, in f
+ File "<stdin>", line 1, in f
+ File "<stdin>", line 1, in f
+ [Previous line repeated 995 more times]
+ RecursionError: maximum recursion depth exceeded
+
+(Contributed by Emanuel Barry in :issue:`26823`.)
+
+
+tracemalloc
+-----------
+
+The :mod:`tracemalloc` module now supports tracing memory allocations in
+multiple different address spaces.
+
+The new :class:`~tracemalloc.DomainFilter` filter class has been added
+to filter block traces by their address space (domain).
+
+(Contributed by Victor Stinner in :issue:`26588`.)
+
+
+.. _whatsnew36-typing:
+
+typing
+------
+
+Starting with Python 3.6 the :mod:`typing` module is no longer provisional
+and its API is considered stable.
+
+Since the :mod:`typing` module was :term:`provisional <provisional api>`
+in Python 3.5, all changes introduced in Python 3.6 have also been
+backported to Python 3.5.x.
+
+The :mod:`typing` module has a much improved support for generic type
+aliases. For example ``Dict[str, Tuple[S, T]]`` is now a valid
+type annotation.
+(Contributed by Guido van Rossum in `Github #195
+<https://github.com/python/typing/pull/195>`_.)
+
+The :class:`typing.ContextManager` class has been added for
+representing :class:`contextlib.AbstractContextManager`.
+(Contributed by Brett Cannon in :issue:`25609`.)
+
+The :class:`typing.Collection` class has been added for
+representing :class:`collections.abc.Collection`.
+(Contributed by Ivan Levkivskyi in :issue:`27598`.)
+
+The :const:`typing.ClassVar` type construct has been added to
+mark class variables. As introduced in :pep:`526`, a variable annotation
+wrapped in ClassVar indicates that a given attribute is intended to be used as
+a class variable and should not be set on instances of that class.
+(Contributed by Ivan Levkivskyi in `Github #280
+<https://github.com/python/typing/issues/280>`_.)
+
+A new :const:`~typing.TYPE_CHECKING` constant that is assumed to be
+``True`` by the static type chekers, but is ``False`` at runtime.
+(Contributed by Guido van Rossum in `Github #230
+<https://github.com/python/typing/issues/230>`_.)
+
+A new :func:`~typing.NewType` helper function has been added to create
+lightweight distinct types for annotations::
+
+ from typing import NewType
+
+ UserId = NewType('UserId', int)
+ some_id = UserId(524313)
+
+The static type checker will treat the new type as if it were a subclass
+of the original type. (Contributed by Ivan Levkivskyi in `Github #189
+<https://github.com/python/typing/issues/189>`_.)
+
+
+unicodedata
+-----------
+
+The :mod:`unicodedata` module now uses data from `Unicode 9.0.0
+<http://unicode.org/versions/Unicode9.0.0/>`_.
+(Contributed by Benjamin Peterson.)
+
+
+unittest.mock
+-------------
+
+The :class:`~unittest.mock.Mock` class has the following improvements:
+
+* Two new methods, :meth:`Mock.assert_called()
+ <unittest.mock.Mock.assert_called>` and :meth:`Mock.assert_called_once()
+ <unittest.mock.Mock.assert_called_once>` to check if the mock object
+ was called.
+ (Contributed by Amit Saha in :issue:`26323`.)
+
+* The :meth:`Mock.reset_mock() <unittest.mock.Mock.reset_mock>` method
+ now has two optional keyword only arguments: *return_value* and
+ *side_effect*.
+ (Contributed by Kushal Das in :issue:`21271`.)
+
+
+urllib.request
+--------------
+
+If a HTTP request has a file or iterable body (other than a
+bytes object) but no ``Content-Length`` header, rather than
+throwing an error, :class:`~urllib.request.AbstractHTTPHandler` now
+falls back to use chunked transfer encoding.
+(Contributed by Demian Brecht and Rolf Krahl in :issue:`12319`.)
+
+
+urllib.robotparser
+------------------
+
+:class:`~urllib.robotparser.RobotFileParser` now supports the ``Crawl-delay`` and
+``Request-rate`` extensions.
+(Contributed by Nikolay Bogoychev in :issue:`16099`.)
+
+
+venv
+----
+
+:mod:`venv` accepts a new parameter ``--prompt``. This parameter provides an
+alternative prefix for the virtual environment. (Proposed by Łukasz Balcerzak
+and ported to 3.6 by Stéphane Wirtel in :issue:`22829`.)
+
+
+warnings
+--------
+
+A new optional *source* parameter has been added to the
+:func:`warnings.warn_explicit` function: the destroyed object which emitted a
+:exc:`ResourceWarning`. A *source* attribute has also been added to
+:class:`warnings.WarningMessage` (contributed by Victor Stinner in
+:issue:`26568` and :issue:`26567`).
+
+When a :exc:`ResourceWarning` warning is logged, the :mod:`tracemalloc` module is now
+used to try to retrieve the traceback where the destroyed object was allocated.
+
+Example with the script ``example.py``::
+
+ import warnings
+
+ def func():
+ return open(__file__)
+
+ f = func()
+ f = None
+
+Output of the command ``python3.6 -Wd -X tracemalloc=5 example.py``::
+
+ example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
+ f = None
+ Object allocated at (most recent call first):
+ File "example.py", lineno 4
+ return open(__file__)
+ File "example.py", lineno 6
+ f = func()
+
+The "Object allocated at" traceback is new and is only displayed if
+:mod:`tracemalloc` is tracing Python memory allocations and if the
+:mod:`warnings` module was already imported.
+
+
+winreg
+------
+
+Added the 64-bit integer type :data:`REG_QWORD <winreg.REG_QWORD>`.
+(Contributed by Clement Rouault in :issue:`23026`.)
+
+
+winsound
+--------
+
+Allowed keyword arguments to be passed to :func:`Beep <winsound.Beep>`,
+:func:`MessageBeep <winsound.MessageBeep>`, and :func:`PlaySound
+<winsound.PlaySound>` (:issue:`27982`).
+
+
+xmlrpc.client
+-------------
+
+The :mod:`xmlrpc.client` module now supports unmarshalling
+additional data types used by the Apache XML-RPC implementation
+for numerics and ``None``.
+(Contributed by Serhiy Storchaka in :issue:`26885`.)
+
+
+zipfile
+-------
+
+A new :meth:`ZipInfo.from_file() <zipfile.ZipInfo.from_file>` class method
+allows making a :class:`~zipfile.ZipInfo` instance from a filesystem file.
+A new :meth:`ZipInfo.is_dir() <zipfile.ZipInfo.is_dir>` method can be used
+to check if the :class:`~zipfile.ZipInfo` instance represents a directory.
+(Contributed by Thomas Kluyver in :issue:`26039`.)
+
+The :meth:`ZipFile.open() <zipfile.ZipFile.open>` method can now be used to
+write data into a ZIP file, as well as for extracting data.
+(Contributed by Thomas Kluyver in :issue:`26039`.)
+
+
+zlib
+----
+
+The :func:`~zlib.compress` and :func:`~zlib.decompress` functions now accept
+keyword arguments.
+(Contributed by Aviv Palivoda in :issue:`26243` and
+Xiang Zhang in :issue:`16764` respectively.)
+
+
+Optimizations
+=============
+
+* The Python interpreter now uses a 16-bit wordcode instead of bytecode which
+ made a number of opcode optimizations possible.
+ (Contributed by Demur Rumed with input and reviews from
+ Serhiy Storchaka and Victor Stinner in :issue:`26647` and :issue:`28050`.)
+
+* The :class:`asyncio.Future` class now has an optimized C implementation.
+ (Contributed by Yury Selivanov and INADA Naoki in :issue:`26081`.)
+
+* The :class:`asyncio.Task` class now has an optimized
+ C implementation. (Contributed by Yury Selivanov in :issue:`28544`.)
+
+* Various implementation improvements in the :mod:`typing` module
+ (such as caching of generic types) allow up to 30 times performance
+ improvements and reduced memory footprint.
+
+* The ASCII decoder is now up to 60 times as fast for error handlers
+ ``surrogateescape``, ``ignore`` and ``replace`` (Contributed
+ by Victor Stinner in :issue:`24870`).
+
+* The ASCII and the Latin1 encoders are now up to 3 times as fast for the
+ error handler ``surrogateescape``
+ (Contributed by Victor Stinner in :issue:`25227`).
+
+* The UTF-8 encoder is now up to 75 times as fast for error handlers
+ ``ignore``, ``replace``, ``surrogateescape``, ``surrogatepass`` (Contributed
+ by Victor Stinner in :issue:`25267`).
+
+* The UTF-8 decoder is now up to 15 times as fast for error handlers
+ ``ignore``, ``replace`` and ``surrogateescape`` (Contributed
+ by Victor Stinner in :issue:`25301`).
+
+* ``bytes % args`` is now up to 2 times faster. (Contributed by Victor Stinner
+ in :issue:`25349`).
+
+* ``bytearray % args`` is now between 2.5 and 5 times faster. (Contributed by
+ Victor Stinner in :issue:`25399`).
+
+* Optimize :meth:`bytes.fromhex` and :meth:`bytearray.fromhex`: they are now
+ between 2x and 3.5x faster. (Contributed by Victor Stinner in :issue:`25401`).
+
+* Optimize ``bytes.replace(b'', b'.')`` and ``bytearray.replace(b'', b'.')``:
+ up to 80% faster. (Contributed by Josh Snider in :issue:`26574`).
+
+* Allocator functions of the :c:func:`PyMem_Malloc` domain
+ (:c:data:`PYMEM_DOMAIN_MEM`) now use the :ref:`pymalloc memory allocator
+ <pymalloc>` instead of :c:func:`malloc` function of the C library. The
+ pymalloc allocator is optimized for objects smaller or equal to 512 bytes
+ with a short lifetime, and use :c:func:`malloc` for larger memory blocks.
+ (Contributed by Victor Stinner in :issue:`26249`).
+
+* :func:`pickle.load` and :func:`pickle.loads` are now up to 10% faster when
+ deserializing many small objects (Contributed by Victor Stinner in
+ :issue:`27056`).
+
+* Passing :term:`keyword arguments <keyword argument>` to a function has an
+ overhead in comparison with passing :term:`positional arguments
+ <positional argument>`. Now in extension functions implemented with using
+ Argument Clinic this overhead is significantly decreased.
+ (Contributed by Serhiy Storchaka in :issue:`27574`).
+
+* Optimized :func:`~glob.glob` and :func:`~glob.iglob` functions in the
+ :mod:`glob` module; they are now about 3--6 times faster.
+ (Contributed by Serhiy Storchaka in :issue:`25596`).
+
+* Optimized globbing in :mod:`pathlib` by using :func:`os.scandir`;
+ it is now about 1.5--4 times faster.
+ (Contributed by Serhiy Storchaka in :issue:`26032`).
+
+* :class:`xml.etree.ElementTree` parsing, iteration and deepcopy performance
+ has been significantly improved.
+ (Contributed by Serhiy Storchaka in :issue:`25638`, :issue:`25873`,
+ and :issue:`25869`.)
+
+* Creation of :class:`fractions.Fraction` instances from floats and
+ decimals is now 2 to 3 times faster.
+ (Contributed by Serhiy Storchaka in :issue:`25971`.)
+
+
+Build and C API Changes
+=======================
+
+* Python now requires some C99 support in the toolchain to build.
+ Most notably, Python now uses standard integer types and macros in
+ place of custom macros like ``PY_LONG_LONG``.
+ For more information, see :pep:`7` and :issue:`17884`.
+
+* Cross-compiling CPython with the Android NDK and the Android API level set to
+ 21 (Android 5.0 Lollilop) or greater runs successfully. While Android is not
+ yet a supported platform, the Python test suite runs on the Android emulator
+ with only about 16 tests failures. See the Android meta-issue :issue:`26865`.
+
+* The ``--enable-optimizations`` configure flag has been added. Turning it on
+ will activate expensive optimizations like PGO.
+ (Original patch by Alecsandru Patrascu of Intel in :issue:`26539`.)
+
+* The :term:`GIL <global interpreter lock>` must now be held when allocator
+ functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) and
+ :c:data:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) domains are called.
+
+* New :c:func:`Py_FinalizeEx` API which indicates if flushing buffered data
+ failed.
+ (Contributed by Martin Panter in :issue:`5319`.)
+
+* :c:func:`PyArg_ParseTupleAndKeywords` now supports :ref:`positional-only
+ parameters <positional-only_parameter>`. Positional-only parameters are
+ defined by empty names.
+ (Contributed by Serhiy Storchaka in :issue:`26282`).
+
+* ``PyTraceback_Print`` method now abbreviates long sequences of repeated lines
+ as ``"[Previous line repeated {count} more times]"``.
+ (Contributed by Emanuel Barry in :issue:`26823`.)
+
+* The new :c:func:`PyErr_SetImportErrorSubclass` function allows for
+ specifying a subclass of :exc:`ImportError` to raise.
+ (Contributed by Eric Snow in :issue:`15767`.)
+
+* The new :c:func:`PyErr_ResourceWarning` function can be used to generate
+ a :exc:`ResourceWarning` providing the source of the resource allocation.
+ (Contributed by Victor Stinner in :issue:`26567`.)
+
+* The new :c:func:`PyOS_FSPath` function returns the file system
+ representation of a :term:`path-like object`.
+ (Contributed by Brett Cannon in :issue:`27186`.)
+
+* The :c:func:`PyUnicode_FSConverter` and :c:func:`PyUnicode_FSDecoder`
+ functions will now accept :term:`path-like objects <path-like object>`.
+
+
+Other Improvements
+==================
+
+* When :option:`--version` (short form: :option:`-V`) is supplied twice,
+ Python prints :data:`sys.version` for detailed information.
+
+ .. code-block:: shell-session
+
+ $ ./python -VV
+ Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
+ [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
+
+
+Deprecated
+==========
+
+New Keywords
+------------
+
+``async`` and ``await`` are not recommended to be used as variable, class,
+function or module names. Introduced by :pep:`492` in Python 3.5, they will
+become proper keywords in Python 3.7. Starting in Python 3.6, the use of
+``async`` or ``await`` as names will generate a :exc:`DeprecationWarning`.
+
+
+Deprecated Python behavior
+--------------------------
+
+Raising the :exc:`StopIteration` exception inside a generator will now
+generate a :exc:`DeprecationWarning`, and will trigger a :exc:`RuntimeError`
+in Python 3.7. See :ref:`whatsnew-pep-479` for details.
+
+The :meth:`__aiter__` method is now expected to return an asynchronous
+iterator directly instead of returning an awaitable as previously.
+Doing the former will trigger a :exc:`DeprecationWarning`. Backward
+compatibility will be removed in Python 3.7.
+(Contributed by Yury Selivanov in :issue:`27243`.)
+
+A backslash-character pair that is not a valid escape sequence now generates
+a :exc:`DeprecationWarning`. Although this will eventually become a
+:exc:`SyntaxError`, that will not be for several Python releases.
+(Contributed by Emanuel Barry in :issue:`27364`.)
+
+When performing a relative import, falling back on ``__name__`` and
+``__path__`` from the calling module when ``__spec__`` or
+``__package__`` are not defined now raises an :exc:`ImportWarning`.
+(Contributed by Rose Ames in :issue:`25791`.)
+
+
+Deprecated Python modules, functions and methods
+------------------------------------------------
+
+asynchat
+~~~~~~~~
+
+The :mod:`asynchat` has been deprecated in favor of :mod:`asyncio`.
+(Contributed by Mariatta in :issue:`25002`.)
+
+
+asyncore
+~~~~~~~~
+
+The :mod:`asyncore` has been deprecated in favor of :mod:`asyncio`.
+(Contributed by Mariatta in :issue:`25002`.)
+
+
+dbm
+~~~
+
+Unlike other :mod:`dbm` implementations, the :mod:`dbm.dumb` module
+creates databases with the ``'rw'`` mode and allows modifying the database
+opened with the ``'r'`` mode. This behavior is now deprecated and will
+be removed in 3.8.
+(Contributed by Serhiy Storchaka in :issue:`21708`.)
+
+
+distutils
+~~~~~~~~~
+
+The undocumented ``extra_path`` argument to the
+:class:`~distutils.Distribution` constructor is now considered deprecated
+and will raise a warning if set. Support for this parameter will be
+removed in a future Python release. See :issue:`27919` for details.
+
+
+grp
+~~~
+
+The support of non-integer arguments in :func:`~grp.getgrgid` has been
+deprecated.
+(Contributed by Serhiy Storchaka in :issue:`26129`.)
+
+
+importlib
+~~~~~~~~~
+
+The :meth:`importlib.machinery.SourceFileLoader.load_module` and
+:meth:`importlib.machinery.SourcelessFileLoader.load_module` methods
+are now deprecated. They were the only remaining implementations of
+:meth:`importlib.abc.Loader.load_module` in :mod:`importlib` that had not
+been deprecated in previous versions of Python in favour of
+:meth:`importlib.abc.Loader.exec_module`.
+
+The :class:`importlib.machinery.WindowsRegistryFinder` class is now
+deprecated. As of 3.6.0, it is still added to :attr:`sys.meta_path` by
+default (on Windows), but this may change in future releases.
+
+os
+~~
+
+Undocumented support of general :term:`bytes-like objects <bytes-like object>`
+as paths in :mod:`os` functions, :func:`compile` and similar functions is
+now deprecated.
+(Contributed by Serhiy Storchaka in :issue:`25791` and :issue:`26754`.)
+
+re
+~~
+
+Support for inline flags ``(?letters)`` in the middle of the regular
+expression has been deprecated and will be removed in a future Python
+version. Flags at the start of a regular expression are still allowed.
+(Contributed by Serhiy Storchaka in :issue:`22493`.)
+
+ssl
+~~~
+
+OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.
+In the future the :mod:`ssl` module will require at least OpenSSL 1.0.2 or
+1.1.0.
+
+SSL-related arguments like ``certfile``, ``keyfile`` and ``check_hostname``
+in :mod:`ftplib`, :mod:`http.client`, :mod:`imaplib`, :mod:`poplib`,
+and :mod:`smtplib` have been deprecated in favor of ``context``.
+(Contributed by Christian Heimes in :issue:`28022`.)
+
+A couple of protocols and functions of the :mod:`ssl` module are now
+deprecated. Some features will no longer be available in future versions
+of OpenSSL. Other features are deprecated in favor of a different API.
+(Contributed by Christian Heimes in :issue:`28022` and :issue:`26470`.)
+
+tkinter
+~~~~~~~
+
+The :mod:`tkinter.tix` module is now deprecated. :mod:`tkinter` users
+should use :mod:`tkinter.ttk` instead.
+
+venv
+~~~~
+
+The ``pyvenv`` script has been deprecated in favour of ``python3 -m venv``.
+This prevents confusion as to what Python interpreter ``pyvenv`` is
+connected to and thus what Python interpreter will be used by the virtual
+environment. (Contributed by Brett Cannon in :issue:`25154`.)
+
+
+Deprecated functions and types of the C API
+-------------------------------------------
+
+Undocumented functions :c:func:`PyUnicode_AsEncodedObject`,
+:c:func:`PyUnicode_AsDecodedObject`, :c:func:`PyUnicode_AsEncodedUnicode`
+and :c:func:`PyUnicode_AsDecodedUnicode` are deprecated now.
+Use the :ref:`generic codec based API <codec-registry>` instead.
+
+
+Deprecated Build Options
+------------------------
+
+The ``--with-system-ffi`` configure flag is now on by default on non-macOS
+UNIX platforms. It may be disabled by using ``--without-system-ffi``, but
+using the flag is deprecated and will not be accepted in Python 3.7.
+macOS is unaffected by this change. Note that many OS distributors already
+use the ``--with-system-ffi`` flag when building their system Python.
+
+
+Removed
+=======
+
+API and Feature Removals
+------------------------
+
+* Unknown escapes consisting of ``'\'`` and an ASCII letter in
+ regular expressions will now cause an error. In replacement templates for
+ :func:`re.sub` they are still allowed, but deprecated.
+ The :const:`re.LOCALE` flag can now only be used with binary patterns.
+
+* ``inspect.getmoduleinfo()`` was removed (was deprecated since CPython 3.3).
+ :func:`inspect.getmodulename` should be used for obtaining the module
+ name for a given path.
+ (Contributed by Yury Selivanov in :issue:`13248`.)
+
+* ``traceback.Ignore`` class and ``traceback.usage``, ``traceback.modname``,
+ ``traceback.fullmodname``, ``traceback.find_lines_from_code``,
+ ``traceback.find_lines``, ``traceback.find_strings``,
+ ``traceback.find_executable_lines`` methods were removed from the
+ :mod:`traceback` module. They were undocumented methods deprecated since
+ Python 3.2 and equivalent functionality is available from private methods.
+
+* The ``tk_menuBar()`` and ``tk_bindForTraversal()`` dummy methods in
+ :mod:`tkinter` widget classes were removed (corresponding Tk commands
+ were obsolete since Tk 4.0).
+
+* The :meth:`~zipfile.ZipFile.open` method of the :class:`zipfile.ZipFile`
+ class no longer supports the ``'U'`` mode (was deprecated since Python 3.4).
+ Use :class:`io.TextIOWrapper` for reading compressed text files in
+ :term:`universal newlines` mode.
+
+* The undocumented ``IN``, ``CDROM``, ``DLFCN``, ``TYPES``, ``CDIO``, and
+ ``STROPTS`` modules have been removed. They had been available in the
+ platform specific ``Lib/plat-*/`` directories, but were chronically out of
+ date, inconsistently available across platforms, and unmaintained. The
+ script that created these modules is still available in the source
+ distribution at :source:`Tools/scripts/h2py.py`.
+
+* The deprecated ``asynchat.fifo`` class has been removed.
+
+
+Porting to Python 3.6
+=====================
+
+This section lists previously described changes and other bugfixes
+that may require changes to your code.
+
+Changes in 'python' Command Behavior
+------------------------------------
+
+* The output of a special Python build with defined ``COUNT_ALLOCS``,
+ ``SHOW_ALLOC_COUNT`` or ``SHOW_TRACK_COUNT`` macros is now off by
+ default. It can be re-enabled using the ``-X showalloccount`` option.
+ It now outputs to ``stderr`` instead of ``stdout``.
+ (Contributed by Serhiy Storchaka in :issue:`23034`.)
+
+
+Changes in the Python API
+-------------------------
+
+* :func:`open() <open>` will no longer allow combining the ``'U'`` mode flag
+ with ``'+'``.
+ (Contributed by Jeff Balogh and John O'Connor in :issue:`2091`.)
+
+* :mod:`sqlite3` no longer implicitly commits an open transaction before DDL
+ statements.
+
+* On Linux, :func:`os.urandom` now blocks until the system urandom entropy pool
+ is initialized to increase the security.
+
+* When :meth:`importlib.abc.Loader.exec_module` is defined,
+ :meth:`importlib.abc.Loader.create_module` must also be defined.
+
+* :c:func:`PyErr_SetImportError` now sets :exc:`TypeError` when its **msg**
+ argument is not set. Previously only ``NULL`` was returned.
+
+* The format of the ``co_lnotab`` attribute of code objects changed to support
+ a negative line number delta. By default, Python does not emit bytecode with
+ a negative line number delta. Functions using ``frame.f_lineno``,
+ ``PyFrame_GetLineNumber()`` or ``PyCode_Addr2Line()`` are not affected.
+ Functions directly decoding ``co_lnotab`` should be updated to use a signed
+ 8-bit integer type for the line number delta, but this is only required to
+ support applications using a negative line number delta. See
+ ``Objects/lnotab_notes.txt`` for the ``co_lnotab`` format and how to decode
+ it, and see the :pep:`511` for the rationale.
+
+* The functions in the :mod:`compileall` module now return booleans instead
+ of ``1`` or ``0`` to represent success or failure, respectively. Thanks to
+ booleans being a subclass of integers, this should only be an issue if you
+ were doing identity checks for ``1`` or ``0``. See :issue:`25768`.
+
+* Reading the :attr:`~urllib.parse.SplitResult.port` attribute of
+ :func:`urllib.parse.urlsplit` and :func:`~urllib.parse.urlparse` results
+ now raises :exc:`ValueError` for out-of-range values, rather than
+ returning :const:`None`. See :issue:`20059`.
+
+* The :mod:`imp` module now raises a :exc:`DeprecationWarning` instead of
+ :exc:`PendingDeprecationWarning`.
+
+* The following modules have had missing APIs added to their :attr:`__all__`
+ attributes to match the documented APIs:
+ :mod:`calendar`, :mod:`cgi`, :mod:`csv`,
+ :mod:`~xml.etree.ElementTree`, :mod:`enum`,
+ :mod:`fileinput`, :mod:`ftplib`, :mod:`logging`, :mod:`mailbox`,
+ :mod:`mimetypes`, :mod:`optparse`, :mod:`plistlib`, :mod:`smtpd`,
+ :mod:`subprocess`, :mod:`tarfile`, :mod:`threading` and
+ :mod:`wave`. This means they will export new symbols when ``import *``
+ is used.
+ (Contributed by Joel Taddei and Jacek Kołodziej in :issue:`23883`.)
+
+* When performing a relative import, if ``__package__`` does not compare equal
+ to ``__spec__.parent`` then :exc:`ImportWarning` is raised.
+ (Contributed by Brett Cannon in :issue:`25791`.)
+
+* When a relative import is performed and no parent package is known, then
+ :exc:`ImportError` will be raised. Previously, :exc:`SystemError` could be
+ raised. (Contributed by Brett Cannon in :issue:`18018`.)
+
+* Servers based on the :mod:`socketserver` module, including those
+ defined in :mod:`http.server`, :mod:`xmlrpc.server` and
+ :mod:`wsgiref.simple_server`, now only catch exceptions derived
+ from :exc:`Exception`. Therefore if a request handler raises
+ an exception like :exc:`SystemExit` or :exc:`KeyboardInterrupt`,
+ :meth:`~socketserver.BaseServer.handle_error` is no longer called, and
+ the exception will stop a single-threaded server. (Contributed by
+ Martin Panter in :issue:`23430`.)
+
+* :func:`spwd.getspnam` now raises a :exc:`PermissionError` instead of
+ :exc:`KeyError` if the user doesn't have privileges.
+
+* The :meth:`socket.socket.close` method now raises an exception if
+ an error (e.g. ``EBADF``) was reported by the underlying system call.
+ (Contributed by Martin Panter in :issue:`26685`.)
+
+* The *decode_data* argument for the :class:`smtpd.SMTPChannel` and
+ :class:`smtpd.SMTPServer` constructors is now ``False`` by default.
+ This means that the argument passed to
+ :meth:`~smtpd.SMTPServer.process_message` is now a bytes object by
+ default, and ``process_message()`` will be passed keyword arguments.
+ Code that has already been updated in accordance with the deprecation
+ warning generated by 3.5 will not be affected.
+
+* All optional arguments of the :func:`~json.dump`, :func:`~json.dumps`,
+ :func:`~json.load` and :func:`~json.loads` functions and
+ :class:`~json.JSONEncoder` and :class:`~json.JSONDecoder` class
+ constructors in the :mod:`json` module are now :ref:`keyword-only
+ <keyword-only_parameter>`.
+ (Contributed by Serhiy Storchaka in :issue:`18726`.)
+
+* Subclasses of :class:`type` which don't override ``type.__new__`` may no
+ longer use the one-argument form to get the type of an object.
+
+* As part of :pep:`487`, the handling of keyword arguments passed to
+ :class:`type` (other than the metaclass hint, ``metaclass``) is now
+ consistently delegated to :meth:`object.__init_subclass__`. This means that
+ :meth:`type.__new__` and :meth:`type.__init__` both now accept arbitrary
+ keyword arguments, but :meth:`object.__init_subclass__` (which is called from
+ :meth:`type.__new__`) will reject them by default. Custom metaclasses
+ accepting additional keyword arguments will need to adjust their calls to
+ :meth:`type.__new__` (whether direct or via :class:`super`) accordingly.
+
+* In :class:`distutils.command.sdist.sdist`, the ``default_format``
+ attribute has been removed and is no longer honored. Instead, the
+ gzipped tarfile format is the default on all platforms and no
+ platform-specific selection is made.
+ In environments where distributions are
+ built on Windows and zip distributions are required, configure
+ the project with a ``setup.cfg`` file containing the following::
+
+ [sdist]
+ formats=zip
+
+ This behavior has also been backported to earlier Python versions
+ by Setuptools 26.0.0.
+
+* In the :mod:`urllib.request` module and the
+ :meth:`http.client.HTTPConnection.request` method, if no Content-Length
+ header field has been specified and the request body is a file object,
+ it is now sent with HTTP 1.1 chunked encoding. If a file object has to
+ be sent to a HTTP 1.0 server, the Content-Length value now has to be
+ specified by the caller.
+ (Contributed by Demian Brecht and Rolf Krahl with tweaks from
+ Martin Panter in :issue:`12319`.)
+
+* The :class:`~csv.DictReader` now returns rows of type
+ :class:`~collections.OrderedDict`.
+ (Contributed by Steve Holden in :issue:`27842`.)
+
+* The :const:`crypt.METHOD_CRYPT` will no longer be added to ``crypt.methods``
+ if unsupported by the platform.
+ (Contributed by Victor Stinner in :issue:`25287`.)
+
+* The *verbose* and *rename* arguments for
+ :func:`~collections.namedtuple` are now keyword-only.
+ (Contributed by Raymond Hettinger in :issue:`25628`.)
+
+* On Linux, :func:`ctypes.util.find_library` now looks in
+ ``LD_LIBRARY_PATH`` for shared libraries.
+ (Contributed by Vinay Sajip in :issue:`9998`.)
+
+* The :class:`imaplib.IMAP4` class now handles flags containing the
+ ``']'`` character in messages sent from the server to improve
+ real-world compatibility.
+ (Contributed by Lita Cho in :issue:`21815`.)
+
+* The :func:`mmap.write() <mmap.write>` function now returns the number
+ of bytes written like other write methods.
+ (Contributed by Jakub Stasiak in :issue:`26335`.)
+
+* The :func:`pkgutil.iter_modules` and :func:`pkgutil.walk_packages`
+ functions now return :class:`~pkgutil.ModuleInfo` named tuples.
+ (Contributed by Ramchandra Apte in :issue:`17211`.)
+
+* :func:`re.sub` now raises an error for invalid numerical group
+ references in replacement templates even if the pattern is not
+ found in the string. The error message for invalid group references
+ now includes the group index and the position of the reference.
+ (Contributed by SilentGhost, Serhiy Storchaka in :issue:`25953`.)
+
+* :class:`zipfile.ZipFile` will now raise :exc:`NotImplementedError` for
+ unrecognized compression values. Previously a plain :exc:`RuntimeError`
+ was raised. Additionally, calling :class:`~zipfile.ZipFile` methods
+ on a closed ZipFile or calling the :meth:`~zipfile.ZipFile.write` method
+ on a ZipFile created with mode ``'r'`` will raise a :exc:`ValueError`.
+ Previously, a :exc:`RuntimeError` was raised in those scenarios.
+
+* when custom metaclasses are combined with zero-argument :func:`super` or
+ direct references from methods to the implicit ``__class__`` closure
+ variable, the implicit ``__classcell__`` namespace entry must now be passed
+ up to ``type.__new__`` for initialisation. Failing to do so will result in
+ a :exc:`DeprecationWarning` in 3.6 and a :exc:`RuntimeWarning` in the future.
+
+Changes in the C API
+--------------------
+
+* The :c:func:`PyMem_Malloc` allocator family now uses the :ref:`pymalloc allocator
+ <pymalloc>` rather than the system :c:func:`malloc`. Applications calling
+ :c:func:`PyMem_Malloc` without holding the GIL can now crash. Set the
+ :envvar:`PYTHONMALLOC` environment variable to ``debug`` to validate the
+ usage of memory allocators in your application. See :issue:`26249`.
+
+* :c:func:`Py_Exit` (and the main interpreter) now override the exit status
+ with 120 if flushing buffered data failed. See :issue:`5319`.
+
+
+CPython bytecode changes
+------------------------
+
+There have been several major changes to the :term:`bytecode` in Python 3.6.
+
+* The Python interpreter now uses a 16-bit wordcode instead of bytecode.
+ (Contributed by Demur Rumed with input and reviews from
+ Serhiy Storchaka and Victor Stinner in :issue:`26647` and :issue:`28050`.)
+
+* The new :opcode:`FORMAT_VALUE` and :opcode:`BUILD_STRING` opcodes as part
+ of the :ref:`formatted string literal <whatsnew36-pep498>` implementation.
+ (Contributed by Eric Smith in :issue:`25483` and
+ Serhiy Storchaka in :issue:`27078`.)
+
+* The new :opcode:`BUILD_CONST_KEY_MAP` opcode to optimize the creation
+ of dictionaries with constant keys.
+ (Contributed by Serhiy Storchaka in :issue:`27140`.)
+
+* The function call opcodes have been heavily reworked for better performance
+ and simpler implementation.
+ The :opcode:`MAKE_FUNCTION`, :opcode:`CALL_FUNCTION`,
+ :opcode:`CALL_FUNCTION_KW` and :opcode:`BUILD_MAP_UNPACK_WITH_CALL` opcodes
+ have been modified, the new :opcode:`CALL_FUNCTION_EX` and
+ :opcode:`BUILD_TUPLE_UNPACK_WITH_CALL` have been added, and
+ ``CALL_FUNCTION_VAR``, ``CALL_FUNCTION_VAR_KW`` and ``MAKE_CLOSURE`` opcodes
+ have been removed.
+ (Contributed by Demur Rumed in :issue:`27095`, and Serhiy Storchaka in
+ :issue:`27213`, :issue:`28257`.)
+
+* The new :opcode:`SETUP_ANNOTATIONS` and :opcode:`STORE_ANNOTATION` opcodes
+ have been added to support the new :term:`variable annotation` syntax.
+ (Contributed by Ivan Levkivskyi in :issue:`27985`.)
diff --git a/Doc/whatsnew/index.rst b/Doc/whatsnew/index.rst
index edb5502..7c92524 100644
--- a/Doc/whatsnew/index.rst
+++ b/Doc/whatsnew/index.rst
@@ -11,6 +11,7 @@ anyone wishing to stay up-to-date after a new release.
.. toctree::
:maxdepth: 2
+ 3.6.rst
3.5.rst
3.4.rst
3.3.rst
diff --git a/Grammar/Grammar b/Grammar/Grammar
index 4307523..b139e9f 100644
--- a/Grammar/Grammar
+++ b/Grammar/Grammar
@@ -27,25 +27,31 @@ async_funcdef: ASYNC funcdef
funcdef: 'def' NAME parameters ['->' test] ':' suite
parameters: '(' [typedargslist] ')'
-typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
- ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]
- | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
+typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
+ '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
+ | '**' tfpdef [',']]]
+ | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
+ | '**' tfpdef [','])
tfpdef: NAME [':' test]
-varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','
- ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]
- | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
+varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
+ '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
+ | '**' vfpdef [',']]]
+ | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
+ | '**' vfpdef [',']
+)
vfpdef: NAME
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
-expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) |
+expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))*)
+annassign: ':' test ['=' test]
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
-# For normal assignments, additional restrictions enforced by the interpreter
+# For normal and annotated assignments, additional restrictions enforced by the interpreter
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
@@ -140,7 +146,7 @@ argument: ( test [comp_for] |
'*' test )
comp_iter: comp_for | comp_if
-comp_for: 'for' exprlist 'in' or_test [comp_iter]
+comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
comp_if: 'if' test_nocond [comp_iter]
# not used in grammar, but may appear in "node" passed from Parser to Compiler
diff --git a/Include/Python-ast.h b/Include/Python-ast.h
index 2d3eacb..70494b7 100644
--- a/Include/Python-ast.h
+++ b/Include/Python-ast.h
@@ -65,11 +65,12 @@ struct _mod {
enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3,
Return_kind=4, Delete_kind=5, Assign_kind=6,
- AugAssign_kind=7, For_kind=8, AsyncFor_kind=9, While_kind=10,
- If_kind=11, With_kind=12, AsyncWith_kind=13, Raise_kind=14,
- Try_kind=15, Assert_kind=16, Import_kind=17,
- ImportFrom_kind=18, Global_kind=19, Nonlocal_kind=20,
- Expr_kind=21, Pass_kind=22, Break_kind=23, Continue_kind=24};
+ AugAssign_kind=7, AnnAssign_kind=8, For_kind=9,
+ AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13,
+ AsyncWith_kind=14, Raise_kind=15, Try_kind=16,
+ Assert_kind=17, Import_kind=18, ImportFrom_kind=19,
+ Global_kind=20, Nonlocal_kind=21, Expr_kind=22, Pass_kind=23,
+ Break_kind=24, Continue_kind=25};
struct _stmt {
enum _stmt_kind kind;
union {
@@ -118,6 +119,13 @@ struct _stmt {
struct {
expr_ty target;
+ expr_ty annotation;
+ expr_ty value;
+ int simple;
+ } AnnAssign;
+
+ struct {
+ expr_ty target;
expr_ty iter;
asdl_seq *body;
asdl_seq *orelse;
@@ -201,9 +209,10 @@ enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4,
SetComp_kind=9, DictComp_kind=10, GeneratorExp_kind=11,
Await_kind=12, Yield_kind=13, YieldFrom_kind=14,
Compare_kind=15, Call_kind=16, Num_kind=17, Str_kind=18,
- Bytes_kind=19, NameConstant_kind=20, Ellipsis_kind=21,
- Attribute_kind=22, Subscript_kind=23, Starred_kind=24,
- Name_kind=25, List_kind=26, Tuple_kind=27};
+ FormattedValue_kind=19, JoinedStr_kind=20, Bytes_kind=21,
+ NameConstant_kind=22, Ellipsis_kind=23, Constant_kind=24,
+ Attribute_kind=25, Subscript_kind=26, Starred_kind=27,
+ Name_kind=28, List_kind=29, Tuple_kind=30};
struct _expr {
enum _expr_kind kind;
union {
@@ -297,6 +306,16 @@ struct _expr {
} Str;
struct {
+ expr_ty value;
+ int conversion;
+ expr_ty format_spec;
+ } FormattedValue;
+
+ struct {
+ asdl_seq *values;
+ } JoinedStr;
+
+ struct {
bytes s;
} Bytes;
@@ -305,6 +324,10 @@ struct _expr {
} NameConstant;
struct {
+ constant value;
+ } Constant;
+
+ struct {
expr_ty value;
identifier attr;
expr_context_ty ctx;
@@ -366,6 +389,7 @@ struct _comprehension {
expr_ty target;
expr_ty iter;
asdl_seq *ifs;
+ int is_async;
};
enum _excepthandler_kind {ExceptHandler_kind=1};
@@ -446,6 +470,9 @@ stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int
#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5)
stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int
lineno, int col_offset, PyArena *arena);
+#define AnnAssign(a0, a1, a2, a3, a4, a5, a6) _Py_AnnAssign(a0, a1, a2, a3, a4, a5, a6)
+stmt_ty _Py_AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int
+ simple, int lineno, int col_offset, PyArena *arena);
#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6)
stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq *
orelse, int lineno, int col_offset, PyArena *arena);
@@ -543,6 +570,12 @@ expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, int
expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena);
#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3)
expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena);
+#define FormattedValue(a0, a1, a2, a3, a4, a5) _Py_FormattedValue(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_FormattedValue(expr_ty value, int conversion, expr_ty format_spec,
+ int lineno, int col_offset, PyArena *arena);
+#define JoinedStr(a0, a1, a2, a3) _Py_JoinedStr(a0, a1, a2, a3)
+expr_ty _Py_JoinedStr(asdl_seq * values, int lineno, int col_offset, PyArena
+ *arena);
#define Bytes(a0, a1, a2, a3) _Py_Bytes(a0, a1, a2, a3)
expr_ty _Py_Bytes(bytes s, int lineno, int col_offset, PyArena *arena);
#define NameConstant(a0, a1, a2, a3) _Py_NameConstant(a0, a1, a2, a3)
@@ -550,6 +583,9 @@ expr_ty _Py_NameConstant(singleton value, int lineno, int col_offset, PyArena
*arena);
#define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2)
expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena);
+#define Constant(a0, a1, a2, a3) _Py_Constant(a0, a1, a2, a3)
+expr_ty _Py_Constant(constant value, int lineno, int col_offset, PyArena
+ *arena);
#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5)
expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int
lineno, int col_offset, PyArena *arena);
@@ -574,9 +610,9 @@ slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena);
slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena);
#define Index(a0, a1) _Py_Index(a0, a1)
slice_ty _Py_Index(expr_ty value, PyArena *arena);
-#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3)
+#define comprehension(a0, a1, a2, a3, a4) _Py_comprehension(a0, a1, a2, a3, a4)
comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq *
- ifs, PyArena *arena);
+ ifs, int is_async, PyArena *arena);
#define ExceptHandler(a0, a1, a2, a3, a4, a5) _Py_ExceptHandler(a0, a1, a2, a3, a4, a5)
excepthandler_ty _Py_ExceptHandler(expr_ty type, identifier name, asdl_seq *
body, int lineno, int col_offset, PyArena
diff --git a/Include/Python.h b/Include/Python.h
index 858dbd1..4c7c9a4 100644
--- a/Include/Python.h
+++ b/Include/Python.h
@@ -116,6 +116,7 @@
#include "pylifecycle.h"
#include "ceval.h"
#include "sysmodule.h"
+#include "osmodule.h"
#include "intrcheck.h"
#include "import.h"
diff --git a/Include/abstract.h b/Include/abstract.h
index 7dbbb74..7d137a2 100644
--- a/Include/abstract.h
+++ b/Include/abstract.h
@@ -7,7 +7,9 @@ extern "C" {
#ifdef PY_SSIZE_T_CLEAN
#define PyObject_CallFunction _PyObject_CallFunction_SizeT
#define PyObject_CallMethod _PyObject_CallMethod_SizeT
+#ifndef Py_LIMITED_API
#define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT
+#endif /* !Py_LIMITED_API */
#endif
/* Abstract Object Interface (many thanks to Jim Fulton) */
@@ -264,19 +266,97 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
*/
PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
- PyObject *args, PyObject *kw);
+ PyObject *args, PyObject *kwargs);
/*
Call a callable Python object, callable_object, with
arguments and keywords arguments. The 'args' argument can not be
- NULL, but the 'kw' argument can be NULL.
+ NULL.
*/
#ifndef Py_LIMITED_API
+ PyAPI_FUNC(PyObject*) _PyStack_AsTuple(
+ PyObject **stack,
+ Py_ssize_t nargs);
+
+ /* Convert keyword arguments from the (stack, kwnames) format to a Python
+ dictionary.
+
+ kwnames must only contains str strings, no subclass, and all keys must
+ be unique. kwnames is not checked, usually these checks are done before or later
+ calling _PyStack_AsDict(). For example, _PyArg_ParseStack() raises an
+ error if a key is not a string. */
+ PyAPI_FUNC(PyObject *) _PyStack_AsDict(
+ PyObject **values,
+ PyObject *kwnames);
+
+ /* Convert (args, nargs, kwargs) into a (stack, nargs, kwnames).
+
+ Return a new stack which should be released by PyMem_Free(), or return
+ args unchanged if kwargs is NULL or an empty dictionary.
+
+ The stack uses borrowed references.
+
+ The type of keyword keys is not checked, these checks should be done
+ later (ex: _PyArg_ParseStack). */
+ PyAPI_FUNC(PyObject **) _PyStack_UnpackDict(
+ PyObject **args,
+ Py_ssize_t nargs,
+ PyObject *kwargs,
+ PyObject **kwnames,
+ PyObject *func);
+
+ /* Call the callable object func with the "fast call" calling convention:
+ args is a C array for positional arguments (nargs is the number of
+ positional arguments), kwargs is a dictionary for keyword arguments.
+
+ If nargs is equal to zero, args can be NULL. kwargs can be NULL.
+ nargs must be greater or equal to zero.
+
+ Return the result on success. Raise an exception on return NULL on
+ error. */
+ PyAPI_FUNC(PyObject *) _PyObject_FastCallDict(PyObject *func,
+ PyObject **args, Py_ssize_t nargs,
+ PyObject *kwargs);
+
+ /* Call the callable object func with the "fast call" calling convention:
+ args is a C array for positional arguments followed by values of
+ keyword arguments. Keys of keyword arguments are stored as a tuple
+ of strings in kwnames. nargs is the number of positional parameters at
+ the beginning of stack. The size of kwnames gives the number of keyword
+ values in the stack after positional arguments.
+
+ kwnames must only contains str strings, no subclass, and all keys must
+ be unique.
+
+ If nargs is equal to zero and there is no keyword argument (kwnames is
+ NULL or its size is zero), args can be NULL.
+
+ Return the result on success. Raise an exception and return NULL on
+ error. */
+ PyAPI_FUNC(PyObject *) _PyObject_FastCallKeywords
+ (PyObject *func,
+ PyObject **args,
+ Py_ssize_t nargs,
+ PyObject *kwnames);
+
+#define _PyObject_FastCall(func, args, nargs) \
+ _PyObject_FastCallDict((func), (args), (nargs), NULL)
+
+#define _PyObject_CallNoArg(func) \
+ _PyObject_FastCall((func), NULL, 0)
+
+#define _PyObject_CallArg1(func, arg) \
+ _PyObject_FastCall((func), &(arg), 1)
+
+ PyAPI_FUNC(PyObject *) _PyObject_Call_Prepend(PyObject *func,
+ PyObject *obj, PyObject *args,
+ PyObject *kwargs);
+
PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(PyObject *func,
PyObject *result,
const char *where);
-#endif
+#endif /* Py_LIMITED_API */
PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable_object,
PyObject *args);
@@ -315,6 +395,7 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
Python expression: o.method(args).
*/
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyObject_CallMethodId(PyObject *o,
_Py_Identifier *method,
const char *format, ...);
@@ -323,6 +404,7 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
Like PyObject_CallMethod, but expect a _Py_Identifier* as the
method name.
*/
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable,
const char *format,
@@ -331,10 +413,12 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
const char *name,
const char *format,
...);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyObject_CallMethodId_SizeT(PyObject *o,
_Py_Identifier *name,
const char *format,
...);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable,
...);
@@ -350,9 +434,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyObject_CallMethodObjArgs(PyObject *o,
PyObject *method, ...);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyObject_CallMethodIdObjArgs(PyObject *o,
struct _Py_Identifier *method,
...);
+#endif /* !Py_LIMITED_API */
/*
Call the method named m of object o with a variable number of
@@ -664,11 +750,13 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
o1*o2.
*/
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(PyObject *) PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2);
/*
This is the equivalent of the Python expression: o1 @ o2.
*/
+#endif
PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
@@ -844,11 +932,13 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
o1 *= o2.
*/
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(PyObject *) PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2);
/*
This is the equivalent of the Python expression: o1 @= o2.
*/
+#endif
PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1,
PyObject *o2);
@@ -1270,13 +1360,13 @@ PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self);
PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]);
-#endif
/* For internal use by buffer API functions */
PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,
const Py_ssize_t *shape);
PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index,
const Py_ssize_t *shape);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
diff --git a/Include/asdl.h b/Include/asdl.h
index 495153c..35e9fa1 100644
--- a/Include/asdl.h
+++ b/Include/asdl.h
@@ -6,6 +6,7 @@ typedef PyObject * string;
typedef PyObject * bytes;
typedef PyObject * object;
typedef PyObject * singleton;
+typedef PyObject * constant;
/* It would be nice if the code generated by asdl_c.py was completely
independent of Python, but it is a goal the requires too much work
diff --git a/Include/bytes_methods.h b/Include/bytes_methods.h
index 11d5f42..7fa7540 100644
--- a/Include/bytes_methods.h
+++ b/Include/bytes_methods.h
@@ -17,9 +17,18 @@ extern PyObject* _Py_bytes_istitle(const char *cptr, Py_ssize_t len);
/* These store their len sized answer in the given preallocated *result arg. */
extern void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len);
extern void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len);
-extern void _Py_bytes_title(char *result, char *s, Py_ssize_t len);
-extern void _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len);
-extern void _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len);
+extern void _Py_bytes_title(char *result, const char *s, Py_ssize_t len);
+extern void _Py_bytes_capitalize(char *result, const char *s, Py_ssize_t len);
+extern void _Py_bytes_swapcase(char *result, const char *s, Py_ssize_t len);
+
+extern PyObject *_Py_bytes_find(const char *str, Py_ssize_t len, PyObject *args);
+extern PyObject *_Py_bytes_index(const char *str, Py_ssize_t len, PyObject *args);
+extern PyObject *_Py_bytes_rfind(const char *str, Py_ssize_t len, PyObject *args);
+extern PyObject *_Py_bytes_rindex(const char *str, Py_ssize_t len, PyObject *args);
+extern PyObject *_Py_bytes_count(const char *str, Py_ssize_t len, PyObject *args);
+extern int _Py_bytes_contains(const char *str, Py_ssize_t len, PyObject *arg);
+extern PyObject *_Py_bytes_startswith(const char *str, Py_ssize_t len, PyObject *args);
+extern PyObject *_Py_bytes_endswith(const char *str, Py_ssize_t len, PyObject *args);
/* The maketrans() static method. */
extern PyObject* _Py_bytes_maketrans(Py_buffer *frm, Py_buffer *to);
@@ -37,7 +46,19 @@ extern const char _Py_upper__doc__[];
extern const char _Py_title__doc__[];
extern const char _Py_capitalize__doc__[];
extern const char _Py_swapcase__doc__[];
+extern const char _Py_count__doc__[];
+extern const char _Py_find__doc__[];
+extern const char _Py_index__doc__[];
+extern const char _Py_rfind__doc__[];
+extern const char _Py_rindex__doc__[];
+extern const char _Py_startswith__doc__[];
+extern const char _Py_endswith__doc__[];
extern const char _Py_maketrans__doc__[];
+extern const char _Py_expandtabs__doc__[];
+extern const char _Py_ljust__doc__[];
+extern const char _Py_rjust__doc__[];
+extern const char _Py_center__doc__[];
+extern const char _Py_zfill__doc__[];
/* this is needed because some docs are shared from the .o, not static */
#define PyDoc_STRVAR_shared(name,str) const char name[] = PyDoc_STR(str)
diff --git a/Include/bytesobject.h b/Include/bytesobject.h
index 6c1e0c3..0f0bf9f 100644
--- a/Include/bytesobject.h
+++ b/Include/bytesobject.h
@@ -62,11 +62,25 @@ PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *);
PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *);
#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _PyBytes_Resize(PyObject **, Py_ssize_t);
-PyAPI_FUNC(PyObject *) _PyBytes_Format(PyObject *, PyObject *);
+PyAPI_FUNC(PyObject*) _PyBytes_FormatEx(
+ const char *format,
+ Py_ssize_t format_len,
+ PyObject *args,
+ int use_bytearray);
+PyAPI_FUNC(PyObject*) _PyBytes_FromHex(
+ PyObject *string,
+ int use_bytearray);
#endif
PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t,
const char *, Py_ssize_t,
const char *);
+#ifndef Py_LIMITED_API
+/* Helper for PyBytes_DecodeEscape that detects invalid escape chars. */
+PyAPI_FUNC(PyObject *) _PyBytes_DecodeEscape(const char *, Py_ssize_t,
+ const char *, Py_ssize_t,
+ const char *,
+ const char **);
+#endif
/* Macro, trading safety for speed */
#ifndef Py_LIMITED_API
@@ -123,6 +137,87 @@ PyAPI_FUNC(Py_ssize_t) _PyBytes_InsertThousandsGrouping(char *buffer,
#define F_ALT (1<<3)
#define F_ZERO (1<<4)
+#ifndef Py_LIMITED_API
+/* The _PyBytesWriter structure is big: it contains an embedded "stack buffer".
+ A _PyBytesWriter variable must be declared at the end of variables in a
+ function to optimize the memory allocation on the stack. */
+typedef struct {
+ /* bytes, bytearray or NULL (when the small buffer is used) */
+ PyObject *buffer;
+
+ /* Number of allocated size. */
+ Py_ssize_t allocated;
+
+ /* Minimum number of allocated bytes,
+ incremented by _PyBytesWriter_Prepare() */
+ Py_ssize_t min_size;
+
+ /* If non-zero, use a bytearray instead of a bytes object for buffer. */
+ int use_bytearray;
+
+ /* If non-zero, overallocate the buffer (default: 0).
+ This flag must be zero if use_bytearray is non-zero. */
+ int overallocate;
+
+ /* Stack buffer */
+ int use_small_buffer;
+ char small_buffer[512];
+} _PyBytesWriter;
+
+/* Initialize a bytes writer
+
+ By default, the overallocation is disabled. Set the overallocate attribute
+ to control the allocation of the buffer. */
+PyAPI_FUNC(void) _PyBytesWriter_Init(_PyBytesWriter *writer);
+
+/* Get the buffer content and reset the writer.
+ Return a bytes object, or a bytearray object if use_bytearray is non-zero.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(PyObject *) _PyBytesWriter_Finish(_PyBytesWriter *writer,
+ void *str);
+
+/* Deallocate memory of a writer (clear its internal buffer). */
+PyAPI_FUNC(void) _PyBytesWriter_Dealloc(_PyBytesWriter *writer);
+
+/* Allocate the buffer to write size bytes.
+ Return the pointer to the beginning of buffer data.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_Alloc(_PyBytesWriter *writer,
+ Py_ssize_t size);
+
+/* Ensure that the buffer is large enough to write *size* bytes.
+ Add size to the writer minimum size (min_size attribute).
+
+ str is the current pointer inside the buffer.
+ Return the updated current pointer inside the buffer.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_Prepare(_PyBytesWriter *writer,
+ void *str,
+ Py_ssize_t size);
+
+/* Resize the buffer to make it larger.
+ The new buffer may be larger than size bytes because of overallocation.
+ Return the updated current pointer inside the buffer.
+ Raise an exception and return NULL on error.
+
+ Note: size must be greater than the number of allocated bytes in the writer.
+
+ This function doesn't use the writer minimum size (min_size attribute).
+
+ See also _PyBytesWriter_Prepare().
+ */
+PyAPI_FUNC(void*) _PyBytesWriter_Resize(_PyBytesWriter *writer,
+ void *str,
+ Py_ssize_t size);
+
+/* Write bytes.
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(void*) _PyBytesWriter_WriteBytes(_PyBytesWriter *writer,
+ void *str,
+ const void *bytes,
+ Py_ssize_t size);
+#endif /* Py_LIMITED_API */
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/ceval.h b/Include/ceval.h
index b5373a9..89c6062 100644
--- a/Include/ceval.h
+++ b/Include/ceval.h
@@ -8,7 +8,7 @@ extern "C" {
/* Interface to random parts in ceval.c */
PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
- PyObject *, PyObject *, PyObject *);
+ PyObject *func, PyObject *args, PyObject *kwargs);
/* Inline this */
#define PyEval_CallObject(func,arg) \
@@ -25,6 +25,10 @@ PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *);
PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *);
PyAPI_FUNC(void) _PyEval_SetCoroutineWrapper(PyObject *);
PyAPI_FUNC(PyObject *) _PyEval_GetCoroutineWrapper(void);
+PyAPI_FUNC(void) _PyEval_SetAsyncGenFirstiter(PyObject *);
+PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFirstiter(void);
+PyAPI_FUNC(void) _PyEval_SetAsyncGenFinalizer(PyObject *);
+PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFinalizer(void);
#endif
struct _frame; /* Avoid including frameobject.h */
@@ -119,6 +123,9 @@ PyAPI_FUNC(const char *) PyEval_GetFuncDesc(PyObject *);
PyAPI_FUNC(PyObject *) PyEval_GetCallStats(PyObject *);
PyAPI_FUNC(PyObject *) PyEval_EvalFrame(struct _frame *);
PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(struct _frame *f, int exc);
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _PyEval_EvalFrameDefault(struct _frame *f, int exc);
+#endif
/* Interface for threads.
@@ -172,7 +179,9 @@ PyAPI_FUNC(void) PyEval_RestoreThread(PyThreadState *);
PyAPI_FUNC(int) PyEval_ThreadsInitialized(void);
PyAPI_FUNC(void) PyEval_InitThreads(void);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(void) _PyEval_FiniThreads(void);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(void) PyEval_AcquireLock(void);
PyAPI_FUNC(void) PyEval_ReleaseLock(void);
PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate);
@@ -184,6 +193,10 @@ PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds);
PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void);
#endif
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(Py_ssize_t) _PyEval_RequestCodeExtraIndex(freefunc);
+#endif
+
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
@@ -206,6 +219,14 @@ PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *);
PyAPI_FUNC(void) _PyEval_SignalAsyncExc(void);
#endif
+/* Masks and values used by FORMAT_VALUE opcode. */
+#define FVC_MASK 0x3
+#define FVC_NONE 0x0
+#define FVC_STR 0x1
+#define FVC_REPR 0x2
+#define FVC_ASCII 0x3
+#define FVS_MASK 0x4
+#define FVS_HAVE_SPEC 0x4
#ifdef __cplusplus
}
diff --git a/Include/code.h b/Include/code.h
index 8ecf38a..c5fce3c 100644
--- a/Include/code.h
+++ b/Include/code.h
@@ -7,6 +7,16 @@
extern "C" {
#endif
+typedef uint16_t _Py_CODEUNIT;
+
+#ifdef WORDS_BIGENDIAN
+# define _Py_OPCODE(word) ((word) >> 8)
+# define _Py_OPARG(word) ((word) & 255)
+#else
+# define _Py_OPCODE(word) ((word) & 255)
+# define _Py_OPARG(word) ((word) >> 8)
+#endif
+
/* Bytecode object */
typedef struct {
PyObject_HEAD
@@ -15,26 +25,29 @@ typedef struct {
int co_nlocals; /* #local variables */
int co_stacksize; /* #entries needed for evaluation stack */
int co_flags; /* CO_..., see below */
+ int co_firstlineno; /* first source line number */
PyObject *co_code; /* instruction opcodes */
PyObject *co_consts; /* list (constants used) */
PyObject *co_names; /* list of strings (names used) */
PyObject *co_varnames; /* tuple of strings (local variable names) */
PyObject *co_freevars; /* tuple of strings (free variable names) */
PyObject *co_cellvars; /* tuple of strings (cell variable names) */
- /* The rest aren't used in either hash or comparisons, except for
- co_name (used in both) and co_firstlineno (used only in
- comparisons). This is done to preserve the name and line number
+ /* The rest aren't used in either hash or comparisons, except for co_name,
+ used in both. This is done to preserve the name and line number
for tracebacks and debuggers; otherwise, constant de-duplication
would collapse identical functions/lambdas defined on different lines.
*/
unsigned char *co_cell2arg; /* Maps cell vars which are arguments. */
PyObject *co_filename; /* unicode (where it was loaded from) */
PyObject *co_name; /* unicode (name, for reference) */
- int co_firstlineno; /* first source line number */
PyObject *co_lnotab; /* string (encoding addr<->lineno mapping) See
Objects/lnotab_notes.txt for details. */
void *co_zombieframe; /* for optimization only (see frameobject.c) */
PyObject *co_weakreflist; /* to support weakrefs to code objects */
+ /* Scratch space for extra data relating to the code object.
+ Type is a void* to keep the format private in codeobject.c to force
+ people to go through the proper APIs. */
+ void *co_extra;
} PyCodeObject;
/* Masks for co_flags above */
@@ -55,6 +68,7 @@ typedef struct {
``async def`` keywords) */
#define CO_COROUTINE 0x0080
#define CO_ITERABLE_COROUTINE 0x0100
+#define CO_ASYNC_GENERATOR 0x0200
/* These are no longer used. */
#if 0
@@ -126,7 +140,15 @@ PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj);
#endif
PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
- PyObject *names, PyObject *lineno_obj);
+ PyObject *names, PyObject *lnotab);
+
+
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(int) _PyCode_GetExtra(PyObject *code, Py_ssize_t index,
+ void **extra);
+PyAPI_FUNC(int) _PyCode_SetExtra(PyObject *code, Py_ssize_t index,
+ void *extra);
+#endif
#ifdef __cplusplus
}
diff --git a/Include/codecs.h b/Include/codecs.h
index f8275a1..3ad0f2b 100644
--- a/Include/codecs.h
+++ b/Include/codecs.h
@@ -225,10 +225,14 @@ PyAPI_FUNC(PyObject *) PyCodec_XMLCharRefReplaceErrors(PyObject *exc);
/* replace the unicode encode error with backslash escapes (\x, \u and \U) */
PyAPI_FUNC(PyObject *) PyCodec_BackslashReplaceErrors(PyObject *exc);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
/* replace the unicode encode error with backslash escapes (\N, \x, \u and \U) */
PyAPI_FUNC(PyObject *) PyCodec_NameReplaceErrors(PyObject *exc);
+#endif
+#ifndef Py_LIMITED_API
PyAPI_DATA(const char *) Py_hexdigits;
+#endif
#ifdef __cplusplus
}
diff --git a/Include/datetime.h b/Include/datetime.h
index 06cbc4a..3bf35cb 100644
--- a/Include/datetime.h
+++ b/Include/datetime.h
@@ -81,6 +81,7 @@ typedef struct
typedef struct
{
_PyDateTime_TIMEHEAD
+ unsigned char fold;
PyObject *tzinfo;
} PyDateTime_Time; /* hastzinfo true */
@@ -108,6 +109,7 @@ typedef struct
typedef struct
{
_PyDateTime_DATETIMEHEAD
+ unsigned char fold;
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
@@ -125,6 +127,7 @@ typedef struct
((((PyDateTime_DateTime*)o)->data[7] << 16) | \
(((PyDateTime_DateTime*)o)->data[8] << 8) | \
((PyDateTime_DateTime*)o)->data[9])
+#define PyDateTime_DATE_GET_FOLD(o) (((PyDateTime_DateTime*)o)->fold)
/* Apply for time instances. */
#define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0])
@@ -134,6 +137,7 @@ typedef struct
((((PyDateTime_Time*)o)->data[3] << 16) | \
(((PyDateTime_Time*)o)->data[4] << 8) | \
((PyDateTime_Time*)o)->data[5])
+#define PyDateTime_TIME_GET_FOLD(o) (((PyDateTime_Time*)o)->fold)
/* Apply for time delta instances */
#define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
@@ -162,6 +166,11 @@ typedef struct {
PyObject *(*DateTime_FromTimestamp)(PyObject*, PyObject*, PyObject*);
PyObject *(*Date_FromTimestamp)(PyObject*, PyObject*);
+ /* PEP 495 constructors */
+ PyObject *(*DateTime_FromDateAndTimeAndFold)(int, int, int, int, int, int, int,
+ PyObject*, int, PyTypeObject*);
+ PyObject *(*Time_FromTimeAndFold)(int, int, int, int, PyObject*, int, PyTypeObject*);
+
} PyDateTime_CAPI;
#define PyDateTime_CAPSULE_NAME "datetime.datetime_CAPI"
@@ -217,10 +226,18 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL;
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
+#define PyDateTime_FromDateAndTimeAndFold(year, month, day, hour, min, sec, usec, fold) \
+ PyDateTimeAPI->DateTime_FromDateAndTimeAndFold(year, month, day, hour, \
+ min, sec, usec, Py_None, fold, PyDateTimeAPI->DateTimeType)
+
#define PyTime_FromTime(hour, minute, second, usecond) \
PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
Py_None, PyDateTimeAPI->TimeType)
+#define PyTime_FromTimeAndFold(hour, minute, second, usecond, fold) \
+ PyDateTimeAPI->Time_FromTimeAndFold(hour, minute, second, usecond, \
+ Py_None, fold, PyDateTimeAPI->TimeType)
+
#define PyDelta_FromDSU(days, seconds, useconds) \
PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
PyDateTimeAPI->DeltaType)
diff --git a/Include/descrobject.h b/Include/descrobject.h
index e2ba97f..8f3e84c 100644
--- a/Include/descrobject.h
+++ b/Include/descrobject.h
@@ -78,7 +78,9 @@ PyAPI_DATA(PyTypeObject) PyMemberDescr_Type;
PyAPI_DATA(PyTypeObject) PyMethodDescr_Type;
PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type;
PyAPI_DATA(PyTypeObject) PyDictProxy_Type;
+#ifndef Py_LIMITED_API
PyAPI_DATA(PyTypeObject) _PyMethodWrapper_Type;
+#endif /* Py_LIMITED_API */
PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
diff --git a/Include/dictobject.h b/Include/dictobject.h
index e0e1c26..6ef5e03 100644
--- a/Include/dictobject.h
+++ b/Include/dictobject.h
@@ -22,8 +22,21 @@ typedef struct _dictkeysobject PyDictKeysObject;
*/
typedef struct {
PyObject_HEAD
+
+ /* Number of items in the dictionary */
Py_ssize_t ma_used;
+
+ /* Dictionary version: globally unique, value change each time
+ the dictionary is modified */
+ uint64_t ma_version_tag;
+
PyDictKeysObject *ma_keys;
+
+ /* If ma_values is NULL, the table is "combined": keys and values
+ are stored in ma_keys.
+
+ If ma_values is not NULL, the table is splitted:
+ keys are stored in ma_keys and values are stored in ma_values */
PyObject **ma_values;
} PyDictObject;
@@ -60,9 +73,9 @@ PyAPI_FUNC(PyObject *) _PyDict_GetItem_KnownHash(PyObject *mp, PyObject *key,
Py_hash_t hash);
#endif
PyAPI_FUNC(PyObject *) PyDict_GetItemWithError(PyObject *mp, PyObject *key);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyDict_GetItemIdWithError(PyObject *dp,
struct _Py_Identifier *key);
-#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) PyDict_SetDefault(
PyObject *mp, PyObject *key, PyObject *defaultobj);
#endif
@@ -101,7 +114,7 @@ PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp);
PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp);
Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys);
Py_ssize_t _PyDict_SizeOf(PyDictObject *);
-PyObject *_PyDict_Pop(PyDictObject *, PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyDict_Pop(PyObject *, PyObject *, PyObject *);
PyObject *_PyDict_FromKeys(PyObject *, PyObject *, PyObject *);
#define _PyDict_HasSplitTable(d) ((d)->ma_values != NULL)
@@ -121,6 +134,12 @@ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
int override);
#ifndef Py_LIMITED_API
+/* Like PyDict_Merge, but override can be 0, 1 or 2. If override is 0,
+ the first occurrence of a key wins, if override is 1, the last occurrence
+ of a key wins, if override is 2, a KeyError with conflicting key as
+ argument is raised.
+*/
+PyAPI_FUNC(int) _PyDict_MergeEx(PyObject *mp, PyObject *other, int override);
PyAPI_FUNC(PyObject *) _PyDictView_Intersect(PyObject* self, PyObject *other);
#endif
@@ -134,9 +153,13 @@ PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
int override);
PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _PyDict_SetItemId(PyObject *dp, struct _Py_Identifier *key, PyObject *item);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
#ifndef Py_LIMITED_API
diff --git a/Include/fileobject.h b/Include/fileobject.h
index 03155d3..6120e51 100644
--- a/Include/fileobject.h
+++ b/Include/fileobject.h
@@ -23,6 +23,9 @@ PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
If non-NULL, this is different than the default encoding for strings
*/
PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_DATA(const char *) Py_FileSystemDefaultEncodeErrors;
+#endif
PyAPI_DATA(int) Py_HasFileSystemDefaultEncoding;
/* Internal API
diff --git a/Include/fileutils.h b/Include/fileutils.h
index b4a683c..b933e98 100644
--- a/Include/fileutils.h
+++ b/Include/fileutils.h
@@ -5,8 +5,7 @@
extern "C" {
#endif
-PyAPI_FUNC(PyObject *) _Py_device_encoding(int);
-
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(wchar_t *) Py_DecodeLocale(
const char *arg,
size_t *size);
@@ -14,9 +13,12 @@ PyAPI_FUNC(wchar_t *) Py_DecodeLocale(
PyAPI_FUNC(char*) Py_EncodeLocale(
const wchar_t *text,
size_t *error_pos);
+#endif
#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _Py_device_encoding(int);
+
#ifdef MS_WINDOWS
struct _Py_stat_struct {
unsigned long st_dev;
@@ -46,13 +48,11 @@ PyAPI_FUNC(int) _Py_fstat(
PyAPI_FUNC(int) _Py_fstat_noraise(
int fd,
struct _Py_stat_struct *status);
-#endif /* Py_LIMITED_API */
PyAPI_FUNC(int) _Py_stat(
PyObject *path,
struct stat *status);
-#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _Py_open(
const char *pathname,
int flags);
@@ -60,7 +60,6 @@ PyAPI_FUNC(int) _Py_open(
PyAPI_FUNC(int) _Py_open_noraise(
const char *pathname,
int flags);
-#endif
PyAPI_FUNC(FILE *) _Py_wfopen(
const wchar_t *path,
@@ -107,7 +106,6 @@ PyAPI_FUNC(wchar_t*) _Py_wgetcwd(
wchar_t *buf,
size_t size);
-#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _Py_get_inheritable(int fd);
PyAPI_FUNC(int) _Py_set_inheritable(int fd, int inheritable,
@@ -121,18 +119,6 @@ PyAPI_FUNC(int) _Py_get_blocking(int fd);
PyAPI_FUNC(int) _Py_set_blocking(int fd, int blocking);
#endif /* !MS_WINDOWS */
-#if defined _MSC_VER && _MSC_VER >= 1400 && _MSC_VER < 1900
-/* A routine to check if a file descriptor is valid on Windows. Returns 0
- * and sets errno to EBADF if it isn't. This is to avoid Assertions
- * from various functions in the Windows CRT beginning with
- * Visual Studio 2005
- */
-int _PyVerify_fd(int fd);
-
-#else
-#define _PyVerify_fd(A) (1) /* dummy */
-#endif
-
#endif /* Py_LIMITED_API */
#ifdef __cplusplus
diff --git a/Include/floatobject.h b/Include/floatobject.h
index e240fdb..f1044d6 100644
--- a/Include/floatobject.h
+++ b/Include/floatobject.h
@@ -74,9 +74,9 @@ PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
* happens in such cases is partly accidental (alas).
*/
-/* The pack routines write 4 or 8 bytes, starting at p. le is a bool
+/* The pack routines write 2, 4 or 8 bytes, starting at p. le is a bool
* argument, true if you want the string in little-endian format (exponent
- * last, at p+3 or p+7), false if you want big-endian format (exponent
+ * last, at p+1, p+3 or p+7), false if you want big-endian format (exponent
* first, at p).
* Return value: 0 if all is OK, -1 if error (and an exception is
* set, most likely OverflowError).
@@ -84,6 +84,7 @@ PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
* 1): What this does is undefined if x is a NaN or infinity.
* 2): -0.0 and +0.0 produce the same string.
*/
+PyAPI_FUNC(int) _PyFloat_Pack2(double x, unsigned char *p, int le);
PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le);
PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le);
@@ -96,14 +97,15 @@ PyAPI_FUNC(int) _PyFloat_Repr(double x, char *p, size_t len);
PyAPI_FUNC(int) _PyFloat_Digits(char *buf, double v, int *signum);
PyAPI_FUNC(void) _PyFloat_DigitsInit(void);
-/* The unpack routines read 4 or 8 bytes, starting at p. le is a bool
+/* The unpack routines read 2, 4 or 8 bytes, starting at p. le is a bool
* argument, true if the string is in little-endian format (exponent
- * last, at p+3 or p+7), false if big-endian (exponent first, at p).
+ * last, at p+1, p+3 or p+7), false if big-endian (exponent first, at p).
* Return value: The unpacked double. On error, this is -1.0 and
* PyErr_Occurred() is true (and an exception is set, most likely
* OverflowError). Note that on a non-IEEE platform this will refuse
* to unpack a string that represents a NaN or infinity.
*/
+PyAPI_FUNC(double) _PyFloat_Unpack2(const unsigned char *p, int le);
PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le);
PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le);
diff --git a/Include/funcobject.h b/Include/funcobject.h
index cc1426c..77bb8c3 100644
--- a/Include/funcobject.h
+++ b/Include/funcobject.h
@@ -58,6 +58,20 @@ PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) PyFunction_GetAnnotations(PyObject *);
PyAPI_FUNC(int) PyFunction_SetAnnotations(PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _PyFunction_FastCallDict(
+ PyObject *func,
+ PyObject **args,
+ Py_ssize_t nargs,
+ PyObject *kwargs);
+
+PyAPI_FUNC(PyObject *) _PyFunction_FastCallKeywords(
+ PyObject *func,
+ PyObject **stack,
+ Py_ssize_t nargs,
+ PyObject *kwnames);
+#endif
+
/* Macros for direct access to these values. Type checks are *not*
done, so use with care. */
#define PyFunction_GET_CODE(func) \
diff --git a/Include/genobject.h b/Include/genobject.h
index 61e708a..8c1825f 100644
--- a/Include/genobject.h
+++ b/Include/genobject.h
@@ -43,7 +43,7 @@ PyAPI_FUNC(PyObject *) PyGen_NewWithQualName(struct _frame *,
PyAPI_FUNC(int) PyGen_NeedsFinalizing(PyGenObject *);
PyAPI_FUNC(int) _PyGen_SetStopIterationValue(PyObject *);
PyAPI_FUNC(int) _PyGen_FetchStopIterationValue(PyObject **);
-PyObject *_PyGen_Send(PyGenObject *, PyObject *);
+PyAPI_FUNC(PyObject *) _PyGen_Send(PyGenObject *, PyObject *);
PyObject *_PyGen_yf(PyGenObject *);
PyAPI_FUNC(void) _PyGen_Finalize(PyObject *self);
@@ -62,6 +62,37 @@ PyObject *_PyAIterWrapper_New(PyObject *aiter);
PyObject *_PyCoro_GetAwaitableIter(PyObject *o);
PyAPI_FUNC(PyObject *) PyCoro_New(struct _frame *,
PyObject *name, PyObject *qualname);
+
+/* Asynchronous Generators */
+
+typedef struct {
+ _PyGenObject_HEAD(ag)
+ PyObject *ag_finalizer;
+
+ /* Flag is set to 1 when hooks set up by sys.set_asyncgen_hooks
+ were called on the generator, to avoid calling them more
+ than once. */
+ int ag_hooks_inited;
+
+ /* Flag is set to 1 when aclose() is called for the first time, or
+ when a StopAsyncIteration exception is raised. */
+ int ag_closed;
+} PyAsyncGenObject;
+
+PyAPI_DATA(PyTypeObject) PyAsyncGen_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenASend_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenWrappedValue_Type;
+PyAPI_DATA(PyTypeObject) _PyAsyncGenAThrow_Type;
+
+PyAPI_FUNC(PyObject *) PyAsyncGen_New(struct _frame *,
+ PyObject *name, PyObject *qualname);
+
+#define PyAsyncGen_CheckExact(op) (Py_TYPE(op) == &PyAsyncGen_Type)
+
+PyObject *_PyAsyncGenValueWrapperNew(PyObject *);
+
+int PyAsyncGen_ClearFreeLists(void);
+
#endif
#undef _PyGenObject_HEAD
diff --git a/Include/graminit.h b/Include/graminit.h
index d030bc3..e9b4a93 100644
--- a/Include/graminit.h
+++ b/Include/graminit.h
@@ -17,71 +17,72 @@
#define simple_stmt 270
#define small_stmt 271
#define expr_stmt 272
-#define testlist_star_expr 273
-#define augassign 274
-#define del_stmt 275
-#define pass_stmt 276
-#define flow_stmt 277
-#define break_stmt 278
-#define continue_stmt 279
-#define return_stmt 280
-#define yield_stmt 281
-#define raise_stmt 282
-#define import_stmt 283
-#define import_name 284
-#define import_from 285
-#define import_as_name 286
-#define dotted_as_name 287
-#define import_as_names 288
-#define dotted_as_names 289
-#define dotted_name 290
-#define global_stmt 291
-#define nonlocal_stmt 292
-#define assert_stmt 293
-#define compound_stmt 294
-#define async_stmt 295
-#define if_stmt 296
-#define while_stmt 297
-#define for_stmt 298
-#define try_stmt 299
-#define with_stmt 300
-#define with_item 301
-#define except_clause 302
-#define suite 303
-#define test 304
-#define test_nocond 305
-#define lambdef 306
-#define lambdef_nocond 307
-#define or_test 308
-#define and_test 309
-#define not_test 310
-#define comparison 311
-#define comp_op 312
-#define star_expr 313
-#define expr 314
-#define xor_expr 315
-#define and_expr 316
-#define shift_expr 317
-#define arith_expr 318
-#define term 319
-#define factor 320
-#define power 321
-#define atom_expr 322
-#define atom 323
-#define testlist_comp 324
-#define trailer 325
-#define subscriptlist 326
-#define subscript 327
-#define sliceop 328
-#define exprlist 329
-#define testlist 330
-#define dictorsetmaker 331
-#define classdef 332
-#define arglist 333
-#define argument 334
-#define comp_iter 335
-#define comp_for 336
-#define comp_if 337
-#define encoding_decl 338
-#define yield_expr 339
-#define yield_arg 340
+#define annassign 273
+#define testlist_star_expr 274
+#define augassign 275
+#define del_stmt 276
+#define pass_stmt 277
+#define flow_stmt 278
+#define break_stmt 279
+#define continue_stmt 280
+#define return_stmt 281
+#define yield_stmt 282
+#define raise_stmt 283
+#define import_stmt 284
+#define import_name 285
+#define import_from 286
+#define import_as_name 287
+#define dotted_as_name 288
+#define import_as_names 289
+#define dotted_as_names 290
+#define dotted_name 291
+#define global_stmt 292
+#define nonlocal_stmt 293
+#define assert_stmt 294
+#define compound_stmt 295
+#define async_stmt 296
+#define if_stmt 297
+#define while_stmt 298
+#define for_stmt 299
+#define try_stmt 300
+#define with_stmt 301
+#define with_item 302
+#define except_clause 303
+#define suite 304
+#define test 305
+#define test_nocond 306
+#define lambdef 307
+#define lambdef_nocond 308
+#define or_test 309
+#define and_test 310
+#define not_test 311
+#define comparison 312
+#define comp_op 313
+#define star_expr 314
+#define expr 315
+#define xor_expr 316
+#define and_expr 317
+#define shift_expr 318
+#define arith_expr 319
+#define term 320
+#define factor 321
+#define power 322
+#define atom_expr 323
+#define atom 324
+#define testlist_comp 325
+#define trailer 326
+#define subscriptlist 327
+#define subscript 328
+#define sliceop 329
+#define exprlist 330
+#define testlist 331
+#define dictorsetmaker 332
+#define classdef 333
+#define arglist 334
+#define argument 335
+#define comp_iter 336
+#define comp_for 337
+#define comp_if 338
+#define encoding_decl 339
+#define yield_expr 340
+#define yield_arg 341
diff --git a/Include/grammar.h b/Include/grammar.h
index 85120b9..f775f96 100644
--- a/Include/grammar.h
+++ b/Include/grammar.h
@@ -69,6 +69,7 @@ typedef struct {
/* FUNCTIONS */
grammar *newgrammar(int start);
+void freegrammar(grammar *g);
dfa *adddfa(grammar *g, int type, const char *name);
int addstate(dfa *d);
void addarc(dfa *d, int from, int to, int lbl);
diff --git a/Include/import.h b/Include/import.h
index afdfac2..bb6beba6 100644
--- a/Include/import.h
+++ b/Include/import.h
@@ -7,9 +7,11 @@
extern "C" {
#endif
+#ifndef Py_LIMITED_API
PyAPI_FUNC(void) _PyImportZip_Init(void);
PyMODINIT_FUNC PyInit_imp(void);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(long) PyImport_GetMagicNumber(void);
PyAPI_FUNC(const char *) PyImport_GetMagicTag(void);
PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(
@@ -27,16 +29,20 @@ PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleWithPathnames(
const char *pathname, /* decoded from the filesystem encoding */
const char *cpathname /* decoded from the filesystem encoding */
);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleObject(
PyObject *name,
PyObject *co,
PyObject *pathname,
PyObject *cpathname
);
+#endif
PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyImport_AddModuleObject(
PyObject *name
);
+#endif
PyAPI_FUNC(PyObject *) PyImport_AddModule(
const char *name /* UTF-8 encoded string */
);
@@ -53,6 +59,7 @@ PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(
PyObject *fromlist,
int level
);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevelObject(
PyObject *name,
PyObject *globals,
@@ -60,6 +67,7 @@ PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevelObject(
PyObject *fromlist,
int level
);
+#endif
#define PyImport_ImportModuleEx(n, g, l, f) \
PyImport_ImportModuleLevel(n, g, l, f, 0)
@@ -68,9 +76,11 @@ PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path);
PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name);
PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m);
PyAPI_FUNC(void) PyImport_Cleanup(void);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(int) PyImport_ImportFrozenModuleObject(
PyObject *name
);
+#endif
PyAPI_FUNC(int) PyImport_ImportFrozenModule(
const char *name /* UTF-8 encoded string */
);
diff --git a/Include/intrcheck.h b/Include/intrcheck.h
index f53fee1..8fb96cf 100644
--- a/Include/intrcheck.h
+++ b/Include/intrcheck.h
@@ -8,12 +8,15 @@ extern "C" {
PyAPI_FUNC(int) PyOS_InterruptOccurred(void);
PyAPI_FUNC(void) PyOS_InitInterrupts(void);
PyAPI_FUNC(void) PyOS_AfterFork(void);
+
+#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _PyOS_IsMainThread(void);
#ifdef MS_WINDOWS
/* windows.h is not included by Python.h so use void* instead of HANDLE */
PyAPI_FUNC(void*) _PyOS_SigintEvent(void);
#endif
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/longintrepr.h b/Include/longintrepr.h
index bbba4d8..a3b74b4 100644
--- a/Include/longintrepr.h
+++ b/Include/longintrepr.h
@@ -42,14 +42,10 @@ extern "C" {
*/
#if PYLONG_BITS_IN_DIGIT == 30
-#if !(defined HAVE_UINT64_T && defined HAVE_UINT32_T && \
- defined HAVE_INT64_T && defined HAVE_INT32_T)
-#error "30-bit long digits requested, but the necessary types are not available on this platform"
-#endif
-typedef PY_UINT32_T digit;
-typedef PY_INT32_T sdigit; /* signed variant of digit */
-typedef PY_UINT64_T twodigits;
-typedef PY_INT64_T stwodigits; /* signed variant of twodigits */
+typedef uint32_t digit;
+typedef int32_t sdigit; /* signed variant of digit */
+typedef uint64_t twodigits;
+typedef int64_t stwodigits; /* signed variant of twodigits */
#define PyLong_SHIFT 30
#define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */
#define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */
diff --git a/Include/longobject.h b/Include/longobject.h
index 2a2eecf..efd409c 100644
--- a/Include/longobject.h
+++ b/Include/longobject.h
@@ -65,7 +65,8 @@ PyAPI_FUNC(PyObject *) PyLong_GetInfo(void);
# error "void* different in size from int, long and long long"
#endif /* SIZEOF_VOID_P */
-/* Used by Python/mystrtoul.c. */
+/* Used by Python/mystrtoul.c, _PyBytes_FromHex(),
+ _PyBytes_DecodeEscapeRecode(), etc. */
#ifndef Py_LIMITED_API
PyAPI_DATA(unsigned char) _PyLong_DigitValue[256];
#endif
@@ -84,14 +85,12 @@ PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
PyAPI_FUNC(void *) PyLong_AsVoidPtr(PyObject *);
-#ifdef HAVE_LONG_LONG
-PyAPI_FUNC(PyObject *) PyLong_FromLongLong(PY_LONG_LONG);
-PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG);
-PyAPI_FUNC(PY_LONG_LONG) PyLong_AsLongLong(PyObject *);
-PyAPI_FUNC(unsigned PY_LONG_LONG) PyLong_AsUnsignedLongLong(PyObject *);
-PyAPI_FUNC(unsigned PY_LONG_LONG) PyLong_AsUnsignedLongLongMask(PyObject *);
-PyAPI_FUNC(PY_LONG_LONG) PyLong_AsLongLongAndOverflow(PyObject *, int *);
-#endif /* HAVE_LONG_LONG */
+PyAPI_FUNC(PyObject *) PyLong_FromLongLong(long long);
+PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned long long);
+PyAPI_FUNC(long long) PyLong_AsLongLong(PyObject *);
+PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLong(PyObject *);
+PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLongMask(PyObject *);
+PyAPI_FUNC(long long) PyLong_AsLongLongAndOverflow(PyObject *, int *);
PyAPI_FUNC(PyObject *) PyLong_FromString(const char *, char **, int);
#ifndef Py_LIMITED_API
@@ -182,6 +181,13 @@ PyAPI_FUNC(int) _PyLong_FormatWriter(
int base,
int alternate);
+PyAPI_FUNC(char*) _PyLong_FormatBytesWriter(
+ _PyBytesWriter *writer,
+ char *str,
+ PyObject *obj,
+ int base,
+ int alternate);
+
/* Format the object based on the format_spec, as defined in PEP 3101
(Advanced String Formatting). */
PyAPI_FUNC(int) _PyLong_FormatAdvancedWriter(
@@ -198,8 +204,10 @@ PyAPI_FUNC(int) _PyLong_FormatAdvancedWriter(
PyAPI_FUNC(unsigned long) PyOS_strtoul(const char *, char **, int);
PyAPI_FUNC(long) PyOS_strtol(const char *, char **, int);
+#ifndef Py_LIMITED_API
/* For use by the gcd function in mathmodule.c */
PyAPI_FUNC(PyObject *) _PyLong_GCD(PyObject *, PyObject *);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/memoryobject.h b/Include/memoryobject.h
index ab5ee09..990a716 100644
--- a/Include/memoryobject.h
+++ b/Include/memoryobject.h
@@ -21,8 +21,10 @@ PyAPI_DATA(PyTypeObject) PyMemoryView_Type;
#endif
PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(char *mem, Py_ssize_t size,
int flags);
+#endif
#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(Py_buffer *info);
#endif
diff --git a/Include/methodobject.h b/Include/methodobject.h
index e2ad804..79fad82 100644
--- a/Include/methodobject.h
+++ b/Include/methodobject.h
@@ -16,6 +16,8 @@ PyAPI_DATA(PyTypeObject) PyCFunction_Type;
#define PyCFunction_Check(op) (Py_TYPE(op) == &PyCFunction_Type)
typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
+typedef PyObject *(*_PyCFunctionFast) (PyObject *self, PyObject **args,
+ Py_ssize_t nargs, PyObject *kwnames);
typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *,
PyObject *);
typedef PyObject *(*PyNoArgsFunction)(PyObject *);
@@ -37,6 +39,18 @@ PyAPI_FUNC(int) PyCFunction_GetFlags(PyObject *);
#endif
PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _PyCFunction_FastCallDict(PyObject *func,
+ PyObject **args,
+ Py_ssize_t nargs,
+ PyObject *kwargs);
+
+PyAPI_FUNC(PyObject *) _PyCFunction_FastCallKeywords(PyObject *func,
+ PyObject **stack,
+ Py_ssize_t nargs,
+ PyObject *kwnames);
+#endif
+
struct PyMethodDef {
const char *ml_name; /* The name of the built-in function/method */
PyCFunction ml_meth; /* The C function that implements it */
@@ -72,6 +86,8 @@ PyAPI_FUNC(PyObject *) PyCFunction_NewEx(PyMethodDef *, PyObject *,
#define METH_COEXIST 0x0040
#ifndef Py_LIMITED_API
+#define METH_FASTCALL 0x0080
+
typedef struct {
PyObject_HEAD
PyMethodDef *m_ml; /* Description of the C function to call */
diff --git a/Include/modsupport.h b/Include/modsupport.h
index 829aaf8..833e33d 100644
--- a/Include/modsupport.h
+++ b/Include/modsupport.h
@@ -15,12 +15,16 @@ extern "C" {
#define PyArg_Parse _PyArg_Parse_SizeT
#define PyArg_ParseTuple _PyArg_ParseTuple_SizeT
#define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT
+#ifndef Py_LIMITED_API
#define PyArg_VaParse _PyArg_VaParse_SizeT
#define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT
+#endif /* !Py_LIMITED_API */
#define Py_BuildValue _Py_BuildValue_SizeT
#define Py_VaBuildValue _Py_VaBuildValue_SizeT
#else
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _Py_VaBuildValue_SizeT(const char *, va_list);
+#endif /* !Py_LIMITED_API */
#endif
/* Due to a glitch in 3.2, the _SizeT versions weren't exported from the DLL. */
@@ -44,6 +48,32 @@ PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
#endif
PyAPI_FUNC(PyObject *) Py_VaBuildValue(const char *, va_list);
+#ifndef Py_LIMITED_API
+typedef struct _PyArg_Parser {
+ const char *format;
+ const char * const *keywords;
+ const char *fname;
+ const char *custom_msg;
+ int pos; /* number of positional-only arguments */
+ int min; /* minimal number of arguments */
+ int max; /* maximal number of positional arguments */
+ PyObject *kwtuple; /* tuple of keyword parameter names */
+ struct _PyArg_Parser *next;
+} _PyArg_Parser;
+#ifdef PY_SSIZE_T_CLEAN
+#define _PyArg_ParseTupleAndKeywordsFast _PyArg_ParseTupleAndKeywordsFast_SizeT
+#define _PyArg_ParseStack _PyArg_ParseStack_SizeT
+#define _PyArg_VaParseTupleAndKeywordsFast _PyArg_VaParseTupleAndKeywordsFast_SizeT
+#endif
+PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *,
+ struct _PyArg_Parser *, ...);
+PyAPI_FUNC(int) _PyArg_ParseStack(PyObject **args, Py_ssize_t nargs, PyObject *kwnames,
+ struct _PyArg_Parser *, ...);
+PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *,
+ struct _PyArg_Parser *, va_list);
+void _PyArg_Fini(void);
+#endif
+
PyAPI_FUNC(int) PyModule_AddObject(PyObject *, const char *, PyObject *);
PyAPI_FUNC(int) PyModule_AddIntConstant(PyObject *, const char *, long);
PyAPI_FUNC(int) PyModule_AddStringConstant(PyObject *, const char *, const char *);
diff --git a/Include/moduleobject.h b/Include/moduleobject.h
index b44fb9b..b6e4933 100644
--- a/Include/moduleobject.h
+++ b/Include/moduleobject.h
@@ -12,14 +12,18 @@ PyAPI_DATA(PyTypeObject) PyModule_Type;
#define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type)
#define PyModule_CheckExact(op) (Py_TYPE(op) == &PyModule_Type)
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyModule_NewObject(
PyObject *name
);
+#endif
PyAPI_FUNC(PyObject *) PyModule_New(
const char *name /* UTF-8 encoded string */
);
PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyModule_GetNameObject(PyObject *);
+#endif
PyAPI_FUNC(const char *) PyModule_GetName(PyObject *);
PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *);
PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *);
diff --git a/Include/namespaceobject.h b/Include/namespaceobject.h
index a412f05..0c8d95c 100644
--- a/Include/namespaceobject.h
+++ b/Include/namespaceobject.h
@@ -7,9 +7,11 @@
extern "C" {
#endif
+#ifndef Py_LIMITED_API
PyAPI_DATA(PyTypeObject) _PyNamespace_Type;
PyAPI_FUNC(PyObject *) _PyNamespace_New(PyObject *kwds);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/object.h b/Include/object.h
index 50d9747..63e37b8 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -118,6 +118,7 @@ typedef struct {
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
+#ifndef Py_LIMITED_API
/********************* String Literals ****************************************/
/* This structure helps managing static strings. The basic usage goes like this:
Instead of doing
@@ -144,10 +145,12 @@ typedef struct _Py_Identifier {
PyObject *object;
} _Py_Identifier;
-#define _Py_static_string_init(value) { 0, value, 0 }
+#define _Py_static_string_init(value) { .next = NULL, .string = value, .object = NULL }
#define _Py_static_string(varname, value) static _Py_Identifier varname = _Py_static_string_init(value)
#define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
+#endif /* !Py_LIMITED_API */
+
/*
Type objects contain a string containing the type name (to help somewhat
in debugging), the allocation parameters (see PyObject_New() and
@@ -512,8 +515,8 @@ PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *, con
#endif
/* Generic operations on objects */
-struct _Py_Identifier;
#ifndef Py_LIMITED_API
+struct _Py_Identifier;
PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
PyAPI_FUNC(void) _Py_BreakPoint(void);
PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
@@ -530,11 +533,11 @@ PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _PyObject_IsAbstract(PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_GetAttrId(PyObject *, struct _Py_Identifier *);
PyAPI_FUNC(int) _PyObject_SetAttrId(PyObject *, struct _Py_Identifier *, PyObject *);
PyAPI_FUNC(int) _PyObject_HasAttrId(PyObject *, struct _Py_Identifier *);
-#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
#endif
PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
@@ -544,7 +547,9 @@ PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
+#endif
PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
@@ -557,6 +562,7 @@ PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *);
PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
#endif
+#ifndef Py_LIMITED_API
/* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
dict as the last parameter. */
PyAPI_FUNC(PyObject *)
@@ -564,6 +570,7 @@ _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *);
PyAPI_FUNC(int)
_PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
PyObject *, PyObject *);
+#endif /* !Py_LIMITED_API */
/* Helper to look up a builtin object */
#ifndef Py_LIMITED_API
@@ -708,7 +715,6 @@ you can count such references to the type object.)
PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,
int lineno, PyObject *op);
-PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);
PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
#define _Py_INC_REFTOTAL _Py_RefTotal++
#define _Py_DEC_REFTOTAL _Py_RefTotal--
@@ -785,7 +791,7 @@ PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
--(_py_decref_tmp)->ob_refcnt != 0) \
_Py_CHECK_REFCNT(_py_decref_tmp) \
else \
- _Py_Dealloc(_py_decref_tmp); \
+ _Py_Dealloc(_py_decref_tmp); \
} while (0)
/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
@@ -889,8 +895,10 @@ they can have object code that is not dependent on Python compilation flags.
PyAPI_FUNC(void) Py_IncRef(PyObject *);
PyAPI_FUNC(void) Py_DecRef(PyObject *);
+#ifndef Py_LIMITED_API
PyAPI_DATA(PyTypeObject) _PyNone_Type;
PyAPI_DATA(PyTypeObject) _PyNotImplemented_Type;
+#endif /* !Py_LIMITED_API */
/*
_Py_NoneStruct is an object of undefined type which can be used in contexts
@@ -923,10 +931,12 @@ PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
#define Py_GT 4
#define Py_GE 5
+#ifndef Py_LIMITED_API
/* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
* Defined in object.c.
*/
PyAPI_DATA(int) _Py_SwappedOp[];
+#endif /* !Py_LIMITED_API */
/*
@@ -1023,12 +1033,14 @@ chain of N deallocations is broken into N / PyTrash_UNWIND_LEVEL pieces,
with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
*/
+#ifndef Py_LIMITED_API
/* This is the old private API, invoked by the macros before 3.2.4.
Kept for binary compatibility of extensions using the stable ABI. */
PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
PyAPI_DATA(int) _PyTrash_delete_nesting;
PyAPI_DATA(PyObject *) _PyTrash_delete_later;
+#endif /* !Py_LIMITED_API */
/* The new thread-safe private API, invoked by the macros below. */
PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyObject*);
diff --git a/Include/objimpl.h b/Include/objimpl.h
index 65b6d91..746f9c9 100644
--- a/Include/objimpl.h
+++ b/Include/objimpl.h
@@ -95,12 +95,16 @@ PyObject_{New, NewVar, Del}.
the raw memory.
*/
PyAPI_FUNC(void *) PyObject_Malloc(size_t size);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(void *) PyObject_Calloc(size_t nelem, size_t elsize);
+#endif
PyAPI_FUNC(void *) PyObject_Realloc(void *ptr, size_t new_size);
PyAPI_FUNC(void) PyObject_Free(void *ptr);
+#ifndef Py_LIMITED_API
/* This function returns the number of allocated memory blocks, regardless of size */
PyAPI_FUNC(Py_ssize_t) _Py_GetAllocatedBlocks(void);
+#endif /* !Py_LIMITED_API */
/* Macros */
#ifdef WITH_PYMALLOC
@@ -224,11 +228,12 @@ PyAPI_FUNC(void) PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator);
* ==========================
*/
-/* C equivalent of gc.collect(). */
+/* C equivalent of gc.collect() which ignores the state of gc.enabled. */
PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
#ifndef Py_LIMITED_API
PyAPI_FUNC(Py_ssize_t) _PyGC_CollectNoFail(void);
+PyAPI_FUNC(Py_ssize_t) _PyGC_CollectIfEnabled(void);
#endif
/* Test if a type has a GC head */
@@ -322,8 +327,10 @@ extern PyGC_Head *_PyGC_generation0;
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
#endif /* Py_LIMITED_API */
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t size);
PyAPI_FUNC(PyObject *) _PyObject_GC_Calloc(size_t size);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
PyAPI_FUNC(void) PyObject_GC_Track(void *);
diff --git a/Include/odictobject.h b/Include/odictobject.h
index c1d9592..381de58 100644
--- a/Include/odictobject.h
+++ b/Include/odictobject.h
@@ -17,12 +17,13 @@ PyAPI_DATA(PyTypeObject) PyODictKeys_Type;
PyAPI_DATA(PyTypeObject) PyODictItems_Type;
PyAPI_DATA(PyTypeObject) PyODictValues_Type;
-#endif /* Py_LIMITED_API */
-
#define PyODict_Check(op) PyObject_TypeCheck(op, &PyODict_Type)
#define PyODict_CheckExact(op) (Py_TYPE(op) == &PyODict_Type)
#define PyODict_SIZE(op) ((PyDictObject *)op)->ma_used
-#define PyODict_HasKey(od, key) (PyMapping_HasKey(PyObject *)od, key)
+
+#endif /* Py_LIMITED_API */
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(PyObject *) PyODict_New(void);
PyAPI_FUNC(int) PyODict_SetItem(PyObject *od, PyObject *key, PyObject *item);
@@ -37,6 +38,8 @@ PyAPI_FUNC(int) PyODict_DelItem(PyObject *od, PyObject *key);
#define PyODict_GetItemString(od, key) \
PyDict_GetItemString((PyObject *)od, key)
+#endif
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/opcode.h b/Include/opcode.h
index 3f917fb..be360e1 100644
--- a/Include/opcode.h
+++ b/Include/opcode.h
@@ -60,6 +60,7 @@ extern "C" {
#define WITH_CLEANUP_FINISH 82
#define RETURN_VALUE 83
#define IMPORT_STAR 84
+#define SETUP_ANNOTATIONS 85
#define YIELD_VALUE 86
#define POP_BLOCK 87
#define END_FINALLY 88
@@ -98,18 +99,17 @@ extern "C" {
#define LOAD_FAST 124
#define STORE_FAST 125
#define DELETE_FAST 126
+#define STORE_ANNOTATION 127
#define RAISE_VARARGS 130
#define CALL_FUNCTION 131
#define MAKE_FUNCTION 132
#define BUILD_SLICE 133
-#define MAKE_CLOSURE 134
#define LOAD_CLOSURE 135
#define LOAD_DEREF 136
#define STORE_DEREF 137
#define DELETE_DEREF 138
-#define CALL_FUNCTION_VAR 140
#define CALL_FUNCTION_KW 141
-#define CALL_FUNCTION_VAR_KW 142
+#define CALL_FUNCTION_EX 142
#define SETUP_WITH 143
#define EXTENDED_ARG 144
#define LIST_APPEND 145
@@ -122,6 +122,10 @@ extern "C" {
#define BUILD_TUPLE_UNPACK 152
#define BUILD_SET_UNPACK 153
#define SETUP_ASYNC_WITH 154
+#define FORMAT_VALUE 155
+#define BUILD_CONST_KEY_MAP 156
+#define BUILD_STRING 157
+#define BUILD_TUPLE_UNPACK_WITH_CALL 158
/* EXCEPT_HANDLER is a special, implicit block type which is created when
entering an except handler. It is not an opcode but we define it here
diff --git a/Include/osmodule.h b/Include/osmodule.h
new file mode 100644
index 0000000..9095c2f
--- /dev/null
+++ b/Include/osmodule.h
@@ -0,0 +1,17 @@
+
+/* os module interface */
+
+#ifndef Py_OSMODULE_H
+#define Py_OSMODULE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_FUNC(PyObject *) PyOS_FSPath(PyObject *path);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_OSMODULE_H */
diff --git a/Include/patchlevel.h b/Include/patchlevel.h
index 45e5736..49930e8 100644
--- a/Include/patchlevel.h
+++ b/Include/patchlevel.h
@@ -17,13 +17,13 @@
/* Version parsed out into numeric values */
/*--start constants--*/
#define PY_MAJOR_VERSION 3
-#define PY_MINOR_VERSION 5
-#define PY_MICRO_VERSION 2
+#define PY_MINOR_VERSION 6
+#define PY_MICRO_VERSION 0
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
#define PY_RELEASE_SERIAL 0
/* Version as a string */
-#define PY_VERSION "3.5.2+"
+#define PY_VERSION "3.6.0+"
/*--end constants--*/
/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
diff --git a/Include/pgenheaders.h b/Include/pgenheaders.h
index 2049ae3..4843de6 100644
--- a/Include/pgenheaders.h
+++ b/Include/pgenheaders.h
@@ -23,6 +23,7 @@ PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
#define delbitset _Py_delbitset
#define dumptree _Py_dumptree
#define findlabel _Py_findlabel
+#define freegrammar _Py_freegrammar
#define mergebitset _Py_mergebitset
#define meta_grammar _Py_meta_grammar
#define newbitset _Py_newbitset
diff --git a/Include/py_curses.h b/Include/py_curses.h
index f2c08f6..3c21697 100644
--- a/Include/py_curses.h
+++ b/Include/py_curses.h
@@ -103,8 +103,8 @@ static void **PyCurses_API;
#endif
/* general error messages */
-static char *catchall_ERR = "curses function returned ERR";
-static char *catchall_NULL = "curses function returned NULL";
+static const char catchall_ERR[] = "curses function returned ERR";
+static const char catchall_NULL[] = "curses function returned NULL";
/* Function Prototype Macros - They are ugly but very, very useful. ;-)
diff --git a/Include/pyatomic.h b/Include/pyatomic.h
index 89028ef..893d30d 100644
--- a/Include/pyatomic.h
+++ b/Include/pyatomic.h
@@ -61,7 +61,7 @@ typedef enum _Py_memory_order {
} _Py_memory_order;
typedef struct _Py_atomic_address {
- Py_uintptr_t _value;
+ uintptr_t _value;
} _Py_atomic_address;
typedef struct _Py_atomic_int {
@@ -98,7 +98,7 @@ typedef enum _Py_memory_order {
} _Py_memory_order;
typedef struct _Py_atomic_address {
- Py_uintptr_t _value;
+ uintptr_t _value;
} _Py_atomic_address;
typedef struct _Py_atomic_int {
diff --git a/Include/pydebug.h b/Include/pydebug.h
index 19bec2b..6e23a89 100644
--- a/Include/pydebug.h
+++ b/Include/pydebug.h
@@ -24,6 +24,10 @@ PyAPI_DATA(int) Py_UnbufferedStdioFlag;
PyAPI_DATA(int) Py_HashRandomizationFlag;
PyAPI_DATA(int) Py_IsolatedFlag;
+#ifdef MS_WINDOWS
+PyAPI_DATA(int) Py_LegacyWindowsStdioFlag;
+#endif
+
/* this is a wrapper around getenv() that pays attention to
Py_IgnoreEnvironmentFlag. It should be used for getting variables like
PYTHONPATH and PYTHONHOME from the environment */
diff --git a/Include/pydtrace.d b/Include/pydtrace.d
new file mode 100644
index 0000000..8836055
--- /dev/null
+++ b/Include/pydtrace.d
@@ -0,0 +1,19 @@
+/* Python DTrace provider */
+
+provider python {
+ probe function__entry(const char *, const char *, int);
+ probe function__return(const char *, const char *, int);
+ probe instance__new__start(const char *, const char *);
+ probe instance__new__done(const char *, const char *);
+ probe instance__delete__start(const char *, const char *);
+ probe instance__delete__done(const char *, const char *);
+ probe line(const char *, const char *, int);
+ probe gc__start(int);
+ probe gc__done(long);
+};
+
+#pragma D attributes Evolving/Evolving/Common provider python provider
+#pragma D attributes Evolving/Evolving/Common provider python module
+#pragma D attributes Evolving/Evolving/Common provider python function
+#pragma D attributes Evolving/Evolving/Common provider python name
+#pragma D attributes Evolving/Evolving/Common provider python args
diff --git a/Include/pydtrace.h b/Include/pydtrace.h
new file mode 100644
index 0000000..c43a253
--- /dev/null
+++ b/Include/pydtrace.h
@@ -0,0 +1,53 @@
+/* Static DTrace probes interface */
+
+#ifndef Py_DTRACE_H
+#define Py_DTRACE_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef WITH_DTRACE
+
+#include "pydtrace_probes.h"
+
+/* pydtrace_probes.h, on systems with DTrace, is auto-generated to include
+ `PyDTrace_{PROBE}` and `PyDTrace_{PROBE}_ENABLED()` macros for every probe
+ defined in pydtrace_provider.d.
+
+ Calling these functions must be guarded by a `PyDTrace_{PROBE}_ENABLED()`
+ check to minimize performance impact when probing is off. For example:
+
+ if (PyDTrace_FUNCTION_ENTRY_ENABLED())
+ PyDTrace_FUNCTION_ENTRY(f);
+*/
+
+#else
+
+/* Without DTrace, compile to nothing. */
+
+static inline void PyDTrace_LINE(const char *arg0, const char *arg1, int arg2) {}
+static inline void PyDTrace_FUNCTION_ENTRY(const char *arg0, const char *arg1, int arg2) {}
+static inline void PyDTrace_FUNCTION_RETURN(const char *arg0, const char *arg1, int arg2) {}
+static inline void PyDTrace_GC_START(int arg0) {}
+static inline void PyDTrace_GC_DONE(int arg0) {}
+static inline void PyDTrace_INSTANCE_NEW_START(int arg0) {}
+static inline void PyDTrace_INSTANCE_NEW_DONE(int arg0) {}
+static inline void PyDTrace_INSTANCE_DELETE_START(int arg0) {}
+static inline void PyDTrace_INSTANCE_DELETE_DONE(int arg0) {}
+
+static inline int PyDTrace_LINE_ENABLED(void) { return 0; }
+static inline int PyDTrace_FUNCTION_ENTRY_ENABLED(void) { return 0; }
+static inline int PyDTrace_FUNCTION_RETURN_ENABLED(void) { return 0; }
+static inline int PyDTrace_GC_START_ENABLED(void) { return 0; }
+static inline int PyDTrace_GC_DONE_ENABLED(void) { return 0; }
+static inline int PyDTrace_INSTANCE_NEW_START_ENABLED(void) { return 0; }
+static inline int PyDTrace_INSTANCE_NEW_DONE_ENABLED(void) { return 0; }
+static inline int PyDTrace_INSTANCE_DELETE_START_ENABLED(void) { return 0; }
+static inline int PyDTrace_INSTANCE_DELETE_DONE_ENABLED(void) { return 0; }
+
+#endif /* !WITH_DTRACE */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !Py_DTRACE_H */
diff --git a/Include/pyerrors.h b/Include/pyerrors.h
index 35aedb7..8c1dbc5 100644
--- a/Include/pyerrors.h
+++ b/Include/pyerrors.h
@@ -87,8 +87,10 @@ PyAPI_FUNC(PyObject *) PyErr_Occurred(void);
PyAPI_FUNC(void) PyErr_Clear(void);
PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **);
PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(void) PyErr_GetExcInfo(PyObject **, PyObject **, PyObject **);
PyAPI_FUNC(void) PyErr_SetExcInfo(PyObject *, PyObject *, PyObject *);
+#endif
#if defined(__clang__) || \
(defined(__GNUC_MAJOR__) && \
@@ -147,7 +149,9 @@ PyAPI_FUNC(void) _PyErr_ChainExceptions(PyObject *, PyObject *, PyObject *);
PyAPI_DATA(PyObject *) PyExc_BaseException;
PyAPI_DATA(PyObject *) PyExc_Exception;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_DATA(PyObject *) PyExc_StopAsyncIteration;
+#endif
PyAPI_DATA(PyObject *) PyExc_StopIteration;
PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
@@ -160,6 +164,9 @@ PyAPI_DATA(PyObject *) PyExc_EOFError;
PyAPI_DATA(PyObject *) PyExc_FloatingPointError;
PyAPI_DATA(PyObject *) PyExc_OSError;
PyAPI_DATA(PyObject *) PyExc_ImportError;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_DATA(PyObject *) PyExc_ModuleNotFoundError;
+#endif
PyAPI_DATA(PyObject *) PyExc_IndexError;
PyAPI_DATA(PyObject *) PyExc_KeyError;
PyAPI_DATA(PyObject *) PyExc_KeyboardInterrupt;
@@ -167,7 +174,9 @@ PyAPI_DATA(PyObject *) PyExc_MemoryError;
PyAPI_DATA(PyObject *) PyExc_NameError;
PyAPI_DATA(PyObject *) PyExc_OverflowError;
PyAPI_DATA(PyObject *) PyExc_RuntimeError;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_DATA(PyObject *) PyExc_RecursionError;
+#endif
PyAPI_DATA(PyObject *) PyExc_NotImplementedError;
PyAPI_DATA(PyObject *) PyExc_SyntaxError;
PyAPI_DATA(PyObject *) PyExc_IndentationError;
@@ -184,6 +193,7 @@ PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError;
PyAPI_DATA(PyObject *) PyExc_ValueError;
PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError;
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_DATA(PyObject *) PyExc_BlockingIOError;
PyAPI_DATA(PyObject *) PyExc_BrokenPipeError;
PyAPI_DATA(PyObject *) PyExc_ChildProcessError;
@@ -199,6 +209,7 @@ PyAPI_DATA(PyObject *) PyExc_NotADirectoryError;
PyAPI_DATA(PyObject *) PyExc_PermissionError;
PyAPI_DATA(PyObject *) PyExc_ProcessLookupError;
PyAPI_DATA(PyObject *) PyExc_TimeoutError;
+#endif
/* Compatibility aliases */
@@ -231,8 +242,10 @@ PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
PyObject *, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObjects(
PyObject *, PyObject *, PyObject *);
+#endif
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
PyObject *exc,
const char *filename /* decoded from the filesystem encoding */
@@ -254,6 +267,17 @@ PyAPI_FUNC(PyObject *) PyErr_FormatV(
va_list vargs);
#endif
+#ifndef Py_LIMITED_API
+/* Like PyErr_Format(), but saves current exception as __context__ and
+ __cause__.
+ */
+PyAPI_FUNC(PyObject *) _PyErr_FormatFromCause(
+ PyObject *exception,
+ const char *format, /* ASCII-encoded string */
+ ...
+ );
+#endif
+
#ifdef MS_WINDOWS
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
int ierr,
@@ -267,8 +291,10 @@ PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
PyObject *,int, PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObjects(
PyObject *,int, PyObject *, PyObject *);
+#endif
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
PyObject *exc,
int ierr,
@@ -281,10 +307,14 @@ PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
#endif /* MS_WINDOWS */
-PyAPI_FUNC(PyObject *) PyErr_SetExcWithArgsKwargs(PyObject *, PyObject *,
- PyObject *);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+PyAPI_FUNC(PyObject *) PyErr_SetImportErrorSubclass(PyObject *, PyObject *,
+ PyObject *, PyObject *);
+#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject *) PyErr_SetImportError(PyObject *, PyObject *,
PyObject *);
+#endif
/* Export the old function so that the existing API remains available: */
PyAPI_FUNC(void) PyErr_BadInternalCall(void);
diff --git a/Include/pygetopt.h b/Include/pygetopt.h
index 425c7dd..962720c 100644
--- a/Include/pygetopt.h
+++ b/Include/pygetopt.h
@@ -11,9 +11,9 @@ PyAPI_DATA(int) _PyOS_optind;
PyAPI_DATA(wchar_t *) _PyOS_optarg;
PyAPI_FUNC(void) _PyOS_ResetGetOpt(void);
-#endif
PyAPI_FUNC(int) _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/pyhash.h b/Include/pyhash.h
index a7ca937..a814af6 100644
--- a/Include/pyhash.h
+++ b/Include/pyhash.h
@@ -36,14 +36,14 @@ PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t);
* memory layout on 64 bit systems
* cccccccc cccccccc cccccccc uc -- unsigned char[24]
* pppppppp ssssssss ........ fnv -- two Py_hash_t
- * k0k0k0k0 k1k1k1k1 ........ siphash -- two PY_UINT64_T
+ * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t
* ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t
* ........ ........ eeeeeeee pyexpat XML hash salt
*
* memory layout on 32 bit systems
* cccccccc cccccccc cccccccc uc
* ppppssss ........ ........ fnv -- two Py_hash_t
- * k0k0k0k0 k1k1k1k1 ........ siphash -- two PY_UINT64_T (*)
+ * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*)
* ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t
* ........ ........ eeee.... pyexpat XML hash salt
*
@@ -59,13 +59,11 @@ typedef union {
Py_hash_t prefix;
Py_hash_t suffix;
} fnv;
-#ifdef PY_UINT64_T
/* two uint64 for SipHash24 */
struct {
- PY_UINT64_T k0;
- PY_UINT64_T k1;
+ uint64_t k0;
+ uint64_t k1;
} siphash;
-#endif
/* a different (!) Py_hash_t for small string optimization */
struct {
unsigned char padding[16];
@@ -121,8 +119,7 @@ PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void);
* configure script.
*
* - FNV is available on all platforms and architectures.
- * - SIPHASH24 only works on plaforms that provide PY_UINT64_T and doesn't
- * require aligned memory for integers.
+ * - SIPHASH24 only works on plaforms that don't require aligned memory for integers.
* - With EXTERNAL embedders can provide an alternative implementation with::
*
* PyHash_FuncDef PyHash_Func = {...};
@@ -134,8 +131,7 @@ PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void);
#define Py_HASH_FNV 2
#ifndef Py_HASH_ALGORITHM
-# if (defined(PY_UINT64_T) && defined(PY_UINT32_T) \
- && !defined(HAVE_ALIGNED_REQUIRED))
+# ifndef HAVE_ALIGNED_REQUIRED
# define Py_HASH_ALGORITHM Py_HASH_SIPHASH24
# else
# define Py_HASH_ALGORITHM Py_HASH_FNV
diff --git a/Include/pylifecycle.h b/Include/pylifecycle.h
index ccdebe2..5a67666 100644
--- a/Include/pylifecycle.h
+++ b/Include/pylifecycle.h
@@ -27,6 +27,7 @@ PyAPI_FUNC(void) Py_InitializeEx(int);
PyAPI_FUNC(void) _Py_InitializeEx_Private(int, int);
#endif
PyAPI_FUNC(void) Py_Finalize(void);
+PyAPI_FUNC(int) Py_FinalizeEx(void);
PyAPI_FUNC(int) Py_IsInitialized(void);
PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void);
PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
@@ -106,6 +107,7 @@ PyAPI_FUNC(void) _PyGC_Fini(void);
PyAPI_FUNC(void) PySlice_Fini(void);
PyAPI_FUNC(void) _PyType_Fini(void);
PyAPI_FUNC(void) _PyRandom_Fini(void);
+PyAPI_FUNC(void) PyAsyncGen_Fini(void);
PyAPI_DATA(PyThreadState *) _Py_Finalizing;
#endif
@@ -115,8 +117,11 @@ typedef void (*PyOS_sighandler_t)(int);
PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int);
PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t);
+#ifndef Py_LIMITED_API
/* Random */
-PyAPI_FUNC(int) _PyOS_URandom (void *buffer, Py_ssize_t size);
+PyAPI_FUNC(int) _PyOS_URandom(void *buffer, Py_ssize_t size);
+PyAPI_FUNC(int) _PyOS_URandomNonblock(void *buffer, Py_ssize_t size);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/pymacro.h b/Include/pymacro.h
index 3f6f5dc..2a839ab 100644
--- a/Include/pymacro.h
+++ b/Include/pymacro.h
@@ -18,6 +18,9 @@
by "__LINE__". */
#define Py_STRINGIFY(x) _Py_XSTRINGIFY(x)
+/* Get the size of a structure member in bytes */
+#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
+
/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
@@ -36,6 +39,10 @@
#define Py_BUILD_ASSERT_EXPR(cond) \
(sizeof(char [1 - 2*!(cond)]) - 1)
+#define Py_BUILD_ASSERT(cond) do { \
+ (void)Py_BUILD_ASSERT_EXPR(cond); \
+ } while(0)
+
/* Get the number of elements in a visible array
This does not work on pointers, or arrays declared as [], or function
@@ -75,12 +82,12 @@
#define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \
(size_t)((a) - 1)) & ~(size_t)((a) - 1))
/* Round pointer "p" down to the closest "a"-aligned address <= "p". */
-#define _Py_ALIGN_DOWN(p, a) ((void *)((Py_uintptr_t)(p) & ~(Py_uintptr_t)((a) - 1)))
+#define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1)))
/* Round pointer "p" up to the closest "a"-aligned address >= "p". */
-#define _Py_ALIGN_UP(p, a) ((void *)(((Py_uintptr_t)(p) + \
- (Py_uintptr_t)((a) - 1)) & ~(Py_uintptr_t)((a) - 1)))
+#define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \
+ (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1)))
/* Check if pointer "p" is aligned to "a"-bytes boundary. */
-#define _Py_IS_ALIGNED(p, a) (!((Py_uintptr_t)(p) & (Py_uintptr_t)((a) - 1)))
+#define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1)))
#ifdef __GNUC__
#define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
diff --git a/Include/pymath.h b/Include/pymath.h
index 1c8d718..7216a09 100644
--- a/Include/pymath.h
+++ b/Include/pymath.h
@@ -55,6 +55,12 @@ extern double pow(double, double);
#define Py_MATH_E 2.7182818284590452354
#endif
+/* Tau (2pi) to 40 digits, taken from tauday.com/tau-digits. */
+#ifndef Py_MATH_TAU
+#define Py_MATH_TAU 6.2831853071795864769252867665590057683943L
+#endif
+
+
/* On x86, Py_FORCE_DOUBLE forces a floating-point number out of an x87 FPU
register and into a 64-bit memory location, rounding from extended
precision to double precision in the process. On other platforms it does
@@ -169,7 +175,7 @@ PyAPI_FUNC(void) _Py_set_387controlword(unsigned short);
#pragma float_control (pop)
#define Py_NAN __icc_nan()
#else /* ICC_NAN_RELAXED as default for Intel Compiler */
- static union { unsigned char buf[8]; double __icc_nan; } __nan_store = {0,0,0,0,0,0,0xf8,0x7f};
+ static const union { unsigned char buf[8]; double __icc_nan; } __nan_store = {0,0,0,0,0,0,0xf8,0x7f};
#define Py_NAN (__nan_store.__icc_nan)
#endif /* ICC_NAN_STRICT */
#endif /* __INTEL_COMPILER */
diff --git a/Include/pymem.h b/Include/pymem.h
index 043db64..a7eb4d2 100644
--- a/Include/pymem.h
+++ b/Include/pymem.h
@@ -16,8 +16,51 @@ PyAPI_FUNC(void *) PyMem_RawMalloc(size_t size);
PyAPI_FUNC(void *) PyMem_RawCalloc(size_t nelem, size_t elsize);
PyAPI_FUNC(void *) PyMem_RawRealloc(void *ptr, size_t new_size);
PyAPI_FUNC(void) PyMem_RawFree(void *ptr);
+
+/* Configure the Python memory allocators. Pass NULL to use default
+ allocators. */
+PyAPI_FUNC(int) _PyMem_SetupAllocators(const char *opt);
+
+#ifdef WITH_PYMALLOC
+PyAPI_FUNC(int) _PyMem_PymallocEnabled(void);
#endif
+/* Identifier of an address space (domain) in tracemalloc */
+typedef unsigned int _PyTraceMalloc_domain_t;
+
+/* Track an allocated memory block in the tracemalloc module.
+ Return 0 on success, return -1 on error (failed to allocate memory to store
+ the trace).
+
+ Return -2 if tracemalloc is disabled.
+
+ If memory block is already tracked, update the existing trace. */
+PyAPI_FUNC(int) _PyTraceMalloc_Track(
+ _PyTraceMalloc_domain_t domain,
+ uintptr_t ptr,
+ size_t size);
+
+/* Untrack an allocated memory block in the tracemalloc module.
+ Do nothing if the block was not tracked.
+
+ Return -2 if tracemalloc is disabled, otherwise return 0. */
+PyAPI_FUNC(int) _PyTraceMalloc_Untrack(
+ _PyTraceMalloc_domain_t domain,
+ uintptr_t ptr);
+
+/* Get the traceback where a memory block was allocated.
+
+ Return a tuple of (filename: str, lineno: int) tuples.
+
+ Return None if the tracemalloc module is disabled or if the memory block
+ is not tracked by tracemalloc.
+
+ Raise an exception and return NULL on error. */
+PyAPI_FUNC(PyObject*) _PyTraceMalloc_GetTraceback(
+ _PyTraceMalloc_domain_t domain,
+ uintptr_t ptr);
+#endif /* !Py_LIMITED_API */
+
/* BEWARE:
@@ -58,7 +101,9 @@ PyAPI_FUNC(void) PyMem_RawFree(void *ptr);
*/
PyAPI_FUNC(void *) PyMem_Malloc(size_t size);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize);
+#endif
PyAPI_FUNC(void *) PyMem_Realloc(void *ptr, size_t new_size);
PyAPI_FUNC(void) PyMem_Free(void *ptr);
diff --git a/Include/pyport.h b/Include/pyport.h
index e7e5178..28bf4b2 100644
--- a/Include/pyport.h
+++ b/Include/pyport.h
@@ -3,15 +3,7 @@
#include "pyconfig.h" /* include for defines */
-/* Some versions of HP-UX & Solaris need inttypes.h for int32_t,
- INT32_MAX, etc. */
-#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
-#endif
-
-#ifdef HAVE_STDINT_H
-#include <stdint.h>
-#endif
/**************************************************************************
Symbols and macros to supply platform-independent interfaces to basic
@@ -31,14 +23,6 @@ Py_DEBUG
Meaning: Extra checks compiled in for debug mode.
Used in: Py_SAFE_DOWNCAST
-HAVE_UINTPTR_T
-Meaning: The C9X type uintptr_t is supported by the compiler
-Used in: Py_uintptr_t
-
-HAVE_LONG_LONG
-Meaning: The compiler supports the C type "long long"
-Used in: PY_LONG_LONG
-
**************************************************************************/
/* typedefs for some C9X-defined synonyms for integral types.
@@ -53,91 +37,31 @@ Used in: PY_LONG_LONG
* integral synonyms. Only define the ones we actually need.
*/
-#ifdef HAVE_LONG_LONG
+// long long is required. Ensure HAVE_LONG_LONG is defined for compatibility.
+#ifndef HAVE_LONG_LONG
+#define HAVE_LONG_LONG
+#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG long long
-#if defined(LLONG_MAX)
/* If LLONG_MAX is defined in limits.h, use that. */
#define PY_LLONG_MIN LLONG_MIN
#define PY_LLONG_MAX LLONG_MAX
#define PY_ULLONG_MAX ULLONG_MAX
-#elif defined(__LONG_LONG_MAX__)
-/* Otherwise, if GCC has a builtin define, use that. (Definition of
- * PY_LLONG_MIN assumes two's complement with no trap representation.) */
-#define PY_LLONG_MAX __LONG_LONG_MAX__
-#define PY_LLONG_MIN (-PY_LLONG_MAX - 1)
-#define PY_ULLONG_MAX (PY_LLONG_MAX * Py_ULL(2) + 1)
-#elif defined(SIZEOF_LONG_LONG)
-/* Otherwise compute from SIZEOF_LONG_LONG, assuming two's complement, no
- padding bits, and no trap representation. Note: PY_ULLONG_MAX was
- previously #defined as (~0ULL) here; but that'll give the wrong value in a
- preprocessor expression on systems where long long != intmax_t. */
-#define PY_LLONG_MAX \
- (1 + 2 * ((Py_LL(1) << (CHAR_BIT * SIZEOF_LONG_LONG - 2)) - 1))
-#define PY_LLONG_MIN (-PY_LLONG_MAX - 1)
-#define PY_ULLONG_MAX (PY_LLONG_MAX * Py_ULL(2) + 1)
-#endif /* LLONG_MAX */
-#endif
-#endif /* HAVE_LONG_LONG */
-
-/* a build with 30-bit digits for Python integers needs an exact-width
- * 32-bit unsigned integer type to store those digits. (We could just use
- * type 'unsigned long', but that would be wasteful on a system where longs
- * are 64-bits.) On Unix systems, the autoconf macro AC_TYPE_UINT32_T defines
- * uint32_t to be such a type unless stdint.h or inttypes.h defines uint32_t.
- * However, it doesn't set HAVE_UINT32_T, so we do that here.
- */
-#ifdef uint32_t
-#define HAVE_UINT32_T 1
#endif
-#ifdef HAVE_UINT32_T
-#ifndef PY_UINT32_T
#define PY_UINT32_T uint32_t
-#endif
-#endif
-
-/* Macros for a 64-bit unsigned integer type; used for type 'twodigits' in the
- * integer implementation, when 30-bit digits are enabled.
- */
-#ifdef uint64_t
-#define HAVE_UINT64_T 1
-#endif
-
-#ifdef HAVE_UINT64_T
-#ifndef PY_UINT64_T
#define PY_UINT64_T uint64_t
-#endif
-#endif
/* Signed variants of the above */
-#ifdef int32_t
-#define HAVE_INT32_T 1
-#endif
-
-#ifdef HAVE_INT32_T
-#ifndef PY_INT32_T
#define PY_INT32_T int32_t
-#endif
-#endif
-
-#ifdef int64_t
-#define HAVE_INT64_T 1
-#endif
-
-#ifdef HAVE_INT64_T
-#ifndef PY_INT64_T
#define PY_INT64_T int64_t
-#endif
-#endif
/* If PYLONG_BITS_IN_DIGIT is not defined then we'll use 30-bit digits if all
the necessary integer types are available, and we're on a 64-bit platform
(as determined by SIZEOF_VOID_P); otherwise we use 15-bit digits. */
#ifndef PYLONG_BITS_IN_DIGIT
-#if (defined HAVE_UINT64_T && defined HAVE_INT64_T && \
- defined HAVE_UINT32_T && defined HAVE_INT32_T && SIZEOF_VOID_P >= 8)
+#if SIZEOF_VOID_P >= 8
#define PYLONG_BITS_IN_DIGIT 30
#else
#define PYLONG_BITS_IN_DIGIT 15
@@ -149,26 +73,9 @@ Used in: PY_LONG_LONG
* without loss of information. Similarly for intptr_t, wrt a signed
* integral type.
*/
-#ifdef HAVE_UINTPTR_T
typedef uintptr_t Py_uintptr_t;
typedef intptr_t Py_intptr_t;
-#elif SIZEOF_VOID_P <= SIZEOF_INT
-typedef unsigned int Py_uintptr_t;
-typedef int Py_intptr_t;
-
-#elif SIZEOF_VOID_P <= SIZEOF_LONG
-typedef unsigned long Py_uintptr_t;
-typedef long Py_intptr_t;
-
-#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)
-typedef unsigned PY_LONG_LONG Py_uintptr_t;
-typedef PY_LONG_LONG Py_intptr_t;
-
-#else
-# error "Python needs a typedef for Py_uintptr_t in pyport.h."
-#endif /* HAVE_UINTPTR_T */
-
/* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) ==
* sizeof(size_t). C99 doesn't define such a thing directly (size_t is an
* unsigned integral type). See PEP 353 for details.
@@ -195,16 +102,8 @@ typedef Py_ssize_t Py_ssize_clean_t;
typedef int Py_ssize_clean_t;
#endif
-/* Largest possible value of size_t.
- SIZE_MAX is part of C99, so it might be defined on some
- platforms. If it is not defined, (size_t)-1 is a portable
- definition for C89, due to the way signed->unsigned
- conversion is defined. */
-#ifdef SIZE_MAX
+/* Largest possible value of size_t. */
#define PY_SIZE_MAX SIZE_MAX
-#else
-#define PY_SIZE_MAX ((size_t)-1)
-#endif
/* Largest positive value of type Py_ssize_t. */
#define PY_SSIZE_T_MAX ((Py_ssize_t)(((size_t)-1)>>1))
@@ -247,22 +146,6 @@ typedef int Py_ssize_clean_t;
# endif
#endif
-/* PY_FORMAT_LONG_LONG is analogous to PY_FORMAT_SIZE_T above, but for
- * the long long type instead of the size_t type. It's only available
- * when HAVE_LONG_LONG is defined. The "high level" Python format
- * functions listed above will interpret "lld" or "llu" correctly on
- * all platforms.
- */
-#ifdef HAVE_LONG_LONG
-# ifndef PY_FORMAT_LONG_LONG
-# ifdef MS_WINDOWS
-# define PY_FORMAT_LONG_LONG "I64"
-# else
-# error "This platform's pyconfig.h needs to define PY_FORMAT_LONG_LONG"
-# endif
-# endif
-#endif
-
/* Py_LOCAL can be used instead of static to get the fastest possible calling
* convention for functions that are local to a given module.
*
@@ -298,26 +181,9 @@ typedef int Py_ssize_clean_t;
#define Py_LOCAL_INLINE(type) static type
#endif
-/* Py_MEMCPY can be used instead of memcpy in cases where the copied blocks
- * are often very short. While most platforms have highly optimized code for
- * large transfers, the setup costs for memcpy are often quite high. MEMCPY
- * solves this by doing short copies "in line".
- */
-
-#if defined(_MSC_VER)
-#define Py_MEMCPY(target, source, length) do { \
- size_t i_, n_ = (length); \
- char *t_ = (void*) (target); \
- const char *s_ = (void*) (source); \
- if (n_ >= 16) \
- memcpy(t_, s_, n_); \
- else \
- for (i_ = 0; i_ < n_; i_++) \
- t_[i_] = s_[i_]; \
- } while (0)
-#else
+/* Py_MEMCPY is kept for backwards compatibility,
+ * see https://bugs.python.org/issue28126 */
#define Py_MEMCPY memcpy
-#endif
#include <stdlib.h>
@@ -570,18 +436,18 @@ extern "C" {
#define HAVE_PY_SET_53BIT_PRECISION 1
#define _Py_SET_53BIT_PRECISION_HEADER \
unsigned int old_fpcr, new_fpcr
-#define _Py_SET_53BIT_PRECISION_START \
- do { \
- __asm__ ("fmove.l %%fpcr,%0" : "=g" (old_fpcr)); \
- /* Set double precision / round to nearest. */ \
- new_fpcr = (old_fpcr & ~0xf0) | 0x80; \
- if (new_fpcr != old_fpcr) \
- __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (new_fpcr)); \
+#define _Py_SET_53BIT_PRECISION_START \
+ do { \
+ __asm__ ("fmove.l %%fpcr,%0" : "=g" (old_fpcr)); \
+ /* Set double precision / round to nearest. */ \
+ new_fpcr = (old_fpcr & ~0xf0) | 0x80; \
+ if (new_fpcr != old_fpcr) \
+ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (new_fpcr)); \
} while (0)
-#define _Py_SET_53BIT_PRECISION_END \
- do { \
- if (new_fpcr != old_fpcr) \
- __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (old_fpcr)); \
+#define _Py_SET_53BIT_PRECISION_END \
+ do { \
+ if (new_fpcr != old_fpcr) \
+ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (old_fpcr)); \
} while (0)
#endif
@@ -850,10 +716,6 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
#pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED)
#endif
-/*
- * Older Microsoft compilers don't support the C99 long long literal suffixes,
- * so these will be defined in PC/pyconfig.h for those compilers.
- */
#ifndef Py_LL
#define Py_LL(x) x##LL
#endif
@@ -862,15 +724,7 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
#define Py_ULL(x) Py_LL(x##U)
#endif
-#ifdef VA_LIST_IS_ARRAY
-#define Py_VA_COPY(x, y) Py_MEMCPY((x), (y), sizeof(va_list))
-#else
-#ifdef __va_copy
-#define Py_VA_COPY __va_copy
-#else
-#define Py_VA_COPY(x, y) (x) = (y)
-#endif
-#endif
+#define Py_VA_COPY va_copy
/*
* Convenient macros to deal with endianness of the platform. WORDS_BIGENDIAN is
@@ -906,4 +760,8 @@ extern _invalid_parameter_handler _Py_silent_invalid_parameter_handler;
#endif /* _MSC_VER >= 1900 */
#endif /* Py_BUILD_CORE */
+#ifdef __ANDROID__
+#include <android/api-level.h>
+#endif
+
#endif /* Py_PYPORT_H */
diff --git a/Include/pystate.h b/Include/pystate.h
index 0499a74..afc3c0c 100644
--- a/Include/pystate.h
+++ b/Include/pystate.h
@@ -8,14 +8,21 @@
extern "C" {
#endif
+/* This limitation is for performance and simplicity. If needed it can be
+removed (with effort). */
+#define MAX_CO_EXTRA_USERS 255
+
/* State shared between threads */
struct _ts; /* Forward */
struct _is; /* Forward */
+struct _frame; /* Forward declaration for PyFrameObject. */
#ifdef Py_LIMITED_API
typedef struct _is PyInterpreterState;
#else
+typedef PyObject* (*_PyFrameEvalFunction)(struct _frame *, int);
+
typedef struct _is {
struct _is *next;
@@ -36,19 +43,17 @@ typedef struct _is {
#ifdef HAVE_DLOPEN
int dlopenflags;
#endif
-#ifdef WITH_TSC
- int tscdump;
-#endif
PyObject *builtins_copy;
+ PyObject *import_func;
+ /* Initialized to PyEval_EvalFrameDefault(). */
+ _PyFrameEvalFunction eval_frame;
} PyInterpreterState;
#endif
/* State unique per thread */
-struct _frame; /* Avoid including frameobject.h */
-
#ifndef Py_LIMITED_API
/* Py_tracefunc return -1 when raising an exception, or 0 for success. */
typedef int (*Py_tracefunc)(PyObject *, struct _frame *, int, PyObject *);
@@ -137,6 +142,12 @@ typedef struct _ts {
PyObject *coroutine_wrapper;
int in_coroutine_wrapper;
+ Py_ssize_t co_extra_user_count;
+ freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS];
+
+ PyObject *async_gen_firstiter;
+ PyObject *async_gen_finalizer;
+
/* XXX signal handlers should also be here */
} PyThreadState;
@@ -146,7 +157,9 @@ typedef struct _ts {
PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void);
PyAPI_FUNC(void) PyInterpreterState_Clear(PyInterpreterState *);
PyAPI_FUNC(void) PyInterpreterState_Delete(PyInterpreterState *);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(int) _PyState_AddModule(PyObject*, struct PyModuleDef*);
+#endif /* !Py_LIMITED_API */
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* New in 3.3 */
PyAPI_FUNC(int) PyState_AddModule(PyObject*, struct PyModuleDef*);
@@ -158,14 +171,20 @@ PyAPI_FUNC(void) _PyState_ClearModules(void);
#endif
PyAPI_FUNC(PyThreadState *) PyThreadState_New(PyInterpreterState *);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *);
PyAPI_FUNC(void) _PyThreadState_Init(PyThreadState *);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(void) PyThreadState_Clear(PyThreadState *);
PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(void) _PyThreadState_DeleteExcept(PyThreadState *tstate);
+#endif /* !Py_LIMITED_API */
#ifdef WITH_THREAD
PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
+#ifndef Py_LIMITED_API
PyAPI_FUNC(void) _PyGILState_Reinit(void);
+#endif /* !Py_LIMITED_API */
#endif
/* Return the current thread state. The global interpreter lock must be held.
@@ -173,9 +192,11 @@ PyAPI_FUNC(void) _PyGILState_Reinit(void);
* the caller needn't check for NULL). */
PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
+#ifndef Py_LIMITED_API
/* Similar to PyThreadState_Get(), but don't issue a fatal error
* if it is NULL. */
PyAPI_FUNC(PyThreadState *) _PyThreadState_UncheckedGet(void);
+#endif /* !Py_LIMITED_API */
PyAPI_FUNC(PyThreadState *) PyThreadState_Swap(PyThreadState *);
PyAPI_FUNC(PyObject *) PyThreadState_GetDict(void);
@@ -241,11 +262,23 @@ PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE);
*/
PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
-/* Helper/diagnostic function - return 1 if the current thread
- * currently holds the GIL, 0 otherwise
- */
#ifndef Py_LIMITED_API
+/* Issue #26558: Flag to disable PyGILState_Check().
+ If set to non-zero, PyGILState_Check() always return 1. */
+PyAPI_DATA(int) _PyGILState_check_enabled;
+
+/* Helper/diagnostic function - return 1 if the current thread
+ currently holds the GIL, 0 otherwise.
+
+ The function returns 1 if _PyGILState_check_enabled is non-zero. */
PyAPI_FUNC(int) PyGILState_Check(void);
+
+/* Unsafe function to get the single PyInterpreterState used by this process'
+ GILState implementation.
+
+ Return NULL before _PyGILState_Init() is called and after _PyGILState_Fini()
+ is called. */
+PyAPI_FUNC(PyInterpreterState *) _PyGILState_GetInterpreterStateUnsafe(void);
#endif
#endif /* #ifdef WITH_THREAD */
diff --git a/Include/pystrhex.h b/Include/pystrhex.h
index 1dc1255..66a30e2 100644
--- a/Include/pystrhex.h
+++ b/Include/pystrhex.h
@@ -5,10 +5,12 @@
extern "C" {
#endif
+#ifndef Py_LIMITED_API
/* Returns a str() containing the hex representation of argbuf. */
PyAPI_FUNC(PyObject*) _Py_strhex(const char* argbuf, const Py_ssize_t arglen);
/* Returns a bytes() containing the ASCII hex representation of argbuf. */
PyAPI_FUNC(PyObject*) _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/pystrtod.h b/Include/pystrtod.h
index 23fd1c6..c1e84de 100644
--- a/Include/pystrtod.h
+++ b/Include/pystrtod.h
@@ -19,6 +19,10 @@ PyAPI_FUNC(char *) PyOS_double_to_string(double val,
int *type);
#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _Py_string_to_number_with_underscores(
+ const char *str, Py_ssize_t len, const char *what, PyObject *obj, void *arg,
+ PyObject *(*innerfunc)(const char *, Py_ssize_t, void *));
+
PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr);
#endif
diff --git a/Include/pythonrun.h b/Include/pythonrun.h
index 9c2e813..efc613f 100644
--- a/Include/pythonrun.h
+++ b/Include/pythonrun.h
@@ -66,8 +66,8 @@ PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(
const char *filename, /* decoded from the filesystem encoding */
const char* enc,
int start,
- char *ps1,
- char *ps2,
+ const char *ps1,
+ const char *ps2,
PyCompilerFlags *flags,
int *errcode,
PyArena *arena);
@@ -76,8 +76,8 @@ PyAPI_FUNC(struct _mod *) PyParser_ASTFromFileObject(
PyObject *filename,
const char* enc,
int start,
- char *ps1,
- char *ps2,
+ const char *ps1,
+ const char *ps2,
PyCompilerFlags *flags,
int *errcode,
PyArena *arena);
@@ -91,9 +91,11 @@ PyAPI_FUNC(struct _mod *) PyParser_ASTFromFileObject(
#endif
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
int);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlagsFilename(const char *,
const char *,
int, int);
+#endif
PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *,
int, int);
diff --git a/Include/pythread.h b/Include/pythread.h
index 6e9f303..88c4873 100644
--- a/Include/pythread.h
+++ b/Include/pythread.h
@@ -37,19 +37,14 @@ PyAPI_FUNC(int) PyThread_acquire_lock(PyThread_type_lock, int);
module exposes a higher-level API, with timeouts expressed in seconds
and floating-point numbers allowed.
*/
-#if defined(HAVE_LONG_LONG)
-#define PY_TIMEOUT_T PY_LONG_LONG
+#define PY_TIMEOUT_T long long
#define PY_TIMEOUT_MAX PY_LLONG_MAX
-#else
-#define PY_TIMEOUT_T long
-#define PY_TIMEOUT_MAX LONG_MAX
-#endif
/* In the NT API, the timeout is a DWORD and is expressed in milliseconds */
#if defined (NT_THREADS)
-#if (Py_LL(0xFFFFFFFF) * 1000 < PY_TIMEOUT_MAX)
+#if 0xFFFFFFFFLL * 1000 < PY_TIMEOUT_MAX
#undef PY_TIMEOUT_MAX
-#define PY_TIMEOUT_MAX (Py_LL(0xFFFFFFFF) * 1000)
+#define PY_TIMEOUT_MAX (0xFFFFFFFFLL * 1000)
#endif
#endif
@@ -74,7 +69,9 @@ PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock);
PyAPI_FUNC(size_t) PyThread_get_stacksize(void);
PyAPI_FUNC(int) PyThread_set_stacksize(size_t);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject*) PyThread_GetInfo(void);
+#endif
/* Thread Local Storage (TLS) API */
PyAPI_FUNC(int) PyThread_create_key(void);
diff --git a/Include/pytime.h b/Include/pytime.h
index 494322c..87ac7fc 100644
--- a/Include/pytime.h
+++ b/Include/pytime.h
@@ -13,16 +13,12 @@ functions and constants
extern "C" {
#endif
-#ifdef PY_INT64_T
/* _PyTime_t: Python timestamp with subsecond precision. It can be used to
store a duration, and so indirectly a date (related to another date, like
UNIX epoch). */
-typedef PY_INT64_T _PyTime_t;
+typedef int64_t _PyTime_t;
#define _PyTime_MIN PY_LLONG_MIN
#define _PyTime_MAX PY_LLONG_MAX
-#else
-# error "_PyTime_t need signed 64-bit integer type"
-#endif
typedef enum {
/* Round towards minus infinity (-inf).
@@ -30,7 +26,10 @@ typedef enum {
_PyTime_ROUND_FLOOR=0,
/* Round towards infinity (+inf).
For example, used for timeout to wait "at least" N seconds. */
- _PyTime_ROUND_CEILING
+ _PyTime_ROUND_CEILING=1,
+ /* Round to nearest with ties going to nearest even integer.
+ For example, used to round from a Python float. */
+ _PyTime_ROUND_HALF_EVEN
} _PyTime_round_t;
/* Convert a time_t to a PyLong. */
@@ -75,7 +74,7 @@ PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
((_PyTime_t)(seconds) * (1000 * 1000 * 1000))
/* Create a timestamp from a number of nanoseconds. */
-PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(PY_LONG_LONG ns);
+PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(long long ns);
/* Convert a number of seconds (Python float or int) to a timetamp.
Raise an exception and return -1 on error, return 0 on success. */
@@ -185,6 +184,14 @@ PyAPI_FUNC(int) _PyTime_GetMonotonicClockWithInfo(
Return 0 on success, raise an exception and return -1 on error. */
PyAPI_FUNC(int) _PyTime_Init(void);
+/* Converts a timestamp to the Gregorian time, using the local time zone.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_localtime(time_t t, struct tm *tm);
+
+/* Converts a timestamp to the Gregorian time, assuming UTC.
+ Return 0 on success, raise an exception and return -1 on error. */
+PyAPI_FUNC(int) _PyTime_gmtime(time_t t, struct tm *tm);
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/setobject.h b/Include/setobject.h
index f17bc1b..87ec1c8 100644
--- a/Include/setobject.h
+++ b/Include/setobject.h
@@ -10,12 +10,13 @@ extern "C" {
/* There are three kinds of entries in the table:
-1. Unused: key == NULL
-2. Active: key != NULL and key != dummy
-3. Dummy: key == dummy
+1. Unused: key == NULL and hash == 0
+2. Dummy: key == dummy and hash == -1
+3. Active: key != NULL and key != dummy and hash != -1
-The hash field of Unused slots have no meaning.
-The hash field of Dummny slots are set to -1
+The hash field of Unused slots is always zero.
+
+The hash field of Dummy slots are set to -1
meaning that dummy entries can be detected by
either entry->key==dummy or by entry->hash==-1.
*/
diff --git a/Include/structmember.h b/Include/structmember.h
index 948f690..5da8a46 100644
--- a/Include/structmember.h
+++ b/Include/structmember.h
@@ -49,10 +49,8 @@ typedef struct PyMemberDef {
#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
when the value is NULL, instead of
converting to None. */
-#ifdef HAVE_LONG_LONG
#define T_LONGLONG 17
#define T_ULONGLONG 18
-#endif /* HAVE_LONG_LONG */
#define T_PYSSIZET 19 /* Py_ssize_t */
#define T_NONE 20 /* Value is always None */
diff --git a/Include/symtable.h b/Include/symtable.h
index 1409cd9..86ae3c2 100644
--- a/Include/symtable.h
+++ b/Include/symtable.h
@@ -48,6 +48,7 @@ typedef struct _symtable_entry {
unsigned ste_child_free : 1; /* true if a child block has free vars,
including free refs to globals */
unsigned ste_generator : 1; /* true if namespace is a generator */
+ unsigned ste_coroutine : 1; /* true if namespace is a coroutine */
unsigned ste_varargs : 1; /* true if block has varargs */
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
unsigned ste_returns_value : 1; /* true if namespace uses return with
@@ -91,6 +92,7 @@ PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
#define DEF_FREE 2<<4 /* name used but not defined in nested block */
#define DEF_FREE_CLASS 2<<5 /* free variable from class's method */
#define DEF_IMPORT 2<<6 /* assignment occurred via import */
+#define DEF_ANNOT 2<<7 /* this name is annotated */
#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
diff --git a/Include/sysmodule.h b/Include/sysmodule.h
index cde10ac..c5547ff 100644
--- a/Include/sysmodule.h
+++ b/Include/sysmodule.h
@@ -8,11 +8,11 @@ extern "C" {
#endif
PyAPI_FUNC(PyObject *) PySys_GetObject(const char *);
+PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *);
#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PySys_GetObjectId(_Py_Identifier *key);
-#endif
-PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *);
PyAPI_FUNC(int) _PySys_SetObjectId(_Py_Identifier *key, PyObject *);
+#endif
PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **);
PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int);
diff --git a/Include/traceback.h b/Include/traceback.h
index c3ecbe2..b587410 100644
--- a/Include/traceback.h
+++ b/Include/traceback.h
@@ -31,6 +31,7 @@ PyAPI_FUNC(void) _PyTraceback_Add(const char *, const char *, int);
PyAPI_DATA(PyTypeObject) PyTraceBack_Type;
#define PyTraceBack_Check(v) (Py_TYPE(v) == &PyTraceBack_Type)
+#ifndef Py_LIMITED_API
/* Write the Python traceback into the file 'fd'. For example:
Traceback (most recent call first):
@@ -53,19 +54,64 @@ PyAPI_FUNC(void) _Py_DumpTraceback(
PyThreadState *tstate);
/* Write the traceback of all threads into the file 'fd'. current_thread can be
- NULL. Return NULL on success, or an error message on error.
+ NULL.
+
+ Return NULL on success, or an error message on error.
This function is written for debug purpose only. It calls
_Py_DumpTraceback() for each thread, and so has the same limitations. It
only write the traceback of the first 100 threads: write "..." if there are
more threads.
+ If current_tstate is NULL, the function tries to get the Python thread state
+ of the current thread. It is not an error if the function is unable to get
+ the current Python thread state.
+
+ If interp is NULL, the function tries to get the interpreter state from
+ the current Python thread state, or from
+ _PyGILState_GetInterpreterStateUnsafe() in last resort.
+
+ It is better to pass NULL to interp and current_tstate, the function tries
+ different options to retrieve these informations.
+
This function is signal safe. */
PyAPI_FUNC(const char*) _Py_DumpTracebackThreads(
- int fd, PyInterpreterState *interp,
- PyThreadState *current_thread);
+ int fd,
+ PyInterpreterState *interp,
+ PyThreadState *current_tstate);
+#endif /* !Py_LIMITED_API */
+
+#ifndef Py_LIMITED_API
+
+/* Write a Unicode object into the file descriptor fd. Encode the string to
+ ASCII using the backslashreplace error handler.
+
+ Do nothing if text is not a Unicode object. The function accepts Unicode
+ string which is not ready (PyUnicode_WCHAR_KIND).
+
+ This function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpASCII(int fd, PyObject *text);
+
+/* Format an integer as decimal into the file descriptor fd.
+
+ This function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpDecimal(
+ int fd,
+ unsigned long value);
+
+/* Format an integer as hexadecimal into the file descriptor fd with at least
+ width digits.
+
+ The maximum width is sizeof(unsigned long)*2 digits.
+
+ This function is signal safe. */
+PyAPI_FUNC(void) _Py_DumpHexadecimal(
+ int fd,
+ unsigned long value,
+ Py_ssize_t width);
+#endif /* !Py_LIMITED_API */
#ifdef __cplusplus
}
diff --git a/Include/unicodeobject.h b/Include/unicodeobject.h
index 9308a6a..587cf03 100644
--- a/Include/unicodeobject.h
+++ b/Include/unicodeobject.h
@@ -103,10 +103,6 @@ typedef wchar_t Py_UNICODE;
# endif
#endif
-#if defined(MS_WINDOWS)
-# define HAVE_MBCS
-#endif
-
#ifdef HAVE_WCHAR_H
/* Work around a cosmetic bug in BSDI 4.x wchar.h; thanks to Thomas Wouters */
# ifdef _HAVE_BSDI
@@ -117,21 +113,9 @@ typedef wchar_t Py_UNICODE;
/* Py_UCS4 and Py_UCS2 are typedefs for the respective
unicode representations. */
-#if SIZEOF_INT == 4
-typedef unsigned int Py_UCS4;
-#elif SIZEOF_LONG == 4
-typedef unsigned long Py_UCS4;
-#else
-#error "Could not find a proper typedef for Py_UCS4"
-#endif
-
-#if SIZEOF_SHORT == 2
-typedef unsigned short Py_UCS2;
-#else
-#error "Could not find a proper typedef for Py_UCS2"
-#endif
-
-typedef unsigned char Py_UCS1;
+typedef uint32_t Py_UCS4;
+typedef uint16_t Py_UCS2;
+typedef uint8_t Py_UCS1;
/* --- Internal Unicode Operations ---------------------------------------- */
@@ -172,7 +156,7 @@ typedef unsigned char Py_UCS1;
Py_UNICODE_ISNUMERIC(ch))
#define Py_UNICODE_COPY(target, source, length) \
- Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE))
+ memcpy((target), (source), (length)*sizeof(Py_UNICODE))
#define Py_UNICODE_FILL(target, value, length) \
do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
@@ -734,10 +718,12 @@ PyAPI_FUNC(PyObject*) _PyUnicode_FromASCII(
Py_ssize_t size);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject*) PyUnicode_Substring(
PyObject *str,
Py_ssize_t start,
Py_ssize_t end);
+#endif
#ifndef Py_LIMITED_API
/* Compute the maximum character of the substring unicode[start:end].
@@ -748,6 +734,7 @@ PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar (
Py_ssize_t end);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* Copy the string into a UCS4 buffer including the null character if copy_null
is set. Return NULL and raise an exception on error. Raise a SystemError if
the buffer is smaller than the string. Return buffer on success.
@@ -763,6 +750,7 @@ PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4(
* PyMem_Malloc; if this fails, NULL is returned with a memory error
exception set. */
PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4Copy(PyObject *unicode);
+#endif
/* Return a read-only pointer to the Unicode object's internal
Py_UNICODE buffer.
@@ -787,11 +775,13 @@ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize(
);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* Get the length of the Unicode object. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_GetLength(
PyObject *unicode
);
+#endif
/* Get the number of Py_UNICODE units in the
string representation. */
@@ -800,6 +790,7 @@ PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
PyObject *unicode /* Unicode object */
);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* Read a character from the string. */
PyAPI_FUNC(Py_UCS4) PyUnicode_ReadChar(
@@ -817,6 +808,7 @@ PyAPI_FUNC(int) PyUnicode_WriteChar(
Py_ssize_t index,
Py_UCS4 character
);
+#endif
#ifndef Py_LIMITED_API
/* Get the maximum ordinal for a Unicode character. */
@@ -900,7 +892,7 @@ typedef struct {
/* minimum character (default: 127, ASCII) */
Py_UCS4 min_char;
- /* If non-zero, overallocate the buffer by 25% (default: 0). */
+ /* If non-zero, overallocate the buffer (default: 0). */
unsigned char overallocate;
/* If readonly is 1, buffer is a shared string (cannot be modified)
@@ -934,6 +926,23 @@ PyAPI_FUNC(int)
_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
Py_ssize_t length, Py_UCS4 maxchar);
+/* Prepare the buffer to have at least the kind KIND.
+ For example, kind=PyUnicode_2BYTE_KIND ensures that the writer will
+ support characters in range U+000-U+FFFF.
+
+ Return 0 on success, raise an exception and return -1 on error. */
+#define _PyUnicodeWriter_PrepareKind(WRITER, KIND) \
+ (assert((KIND) != PyUnicode_WCHAR_KIND), \
+ (KIND) <= (WRITER)->kind \
+ ? 0 \
+ : _PyUnicodeWriter_PrepareKindInternal((WRITER), (KIND)))
+
+/* Don't call this function directly, use the _PyUnicodeWriter_PrepareKind()
+ macro instead. */
+PyAPI_FUNC(int)
+_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
+ enum PyUnicode_Kind kind);
+
/* Append a Unicode character.
Return 0 on success, raise an exception and return -1 on error. */
PyAPI_FUNC(int)
@@ -1170,22 +1179,30 @@ PyAPI_FUNC(PyObject*) PyUnicode_Decode(
);
/* Decode a Unicode object unicode and return the result as Python
- object. */
+ object.
+
+ This API is DEPRECATED. The only supported standard encoding is rot13.
+ Use PyCodec_Decode() to decode with rot13 and non-standard codecs
+ that decode from str. */
PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
- );
+ ) Py_DEPRECATED(3.6);
/* Decode a Unicode object unicode and return the result as Unicode
- object. */
+ object.
+
+ This API is DEPRECATED. The only supported standard encoding is rot13.
+ Use PyCodec_Decode() to decode with rot13 and non-standard codecs
+ that decode from str to str. */
PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
- );
+ ) Py_DEPRECATED(3.6);
/* Encodes a Py_UNICODE buffer of the given size and returns a
Python string object. */
@@ -1200,13 +1217,18 @@ PyAPI_FUNC(PyObject*) PyUnicode_Encode(
#endif
/* Encodes a Unicode object and returns the result as Python
- object. */
+ object.
+
+ This API is DEPRECATED. It is superceeded by PyUnicode_AsEncodedString()
+ since all standard encodings (except rot13) encode str to bytes.
+ Use PyCodec_Encode() for encoding with rot13 and non-standard codecs
+ that encode form str to non-bytes. */
PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
- );
+ ) Py_DEPRECATED(3.6);
/* Encodes a Unicode object and returns the result as Python string
object. */
@@ -1218,13 +1240,17 @@ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString(
);
/* Encodes a Unicode object and returns the result as Unicode
- object. */
+ object.
+
+ This API is DEPRECATED. The only supported standard encodings is rot13.
+ Use PyCodec_Encode() to encode with rot13 and non-standard codecs
+ that encode from str to str. */
PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
- );
+ ) Py_DEPRECATED(3.6);
/* Build an encoding map. */
@@ -1468,6 +1494,19 @@ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape(
const char *errors /* error handling */
);
+#ifndef Py_LIMITED_API
+/* Helper for PyUnicode_DecodeUnicodeEscape that detects invalid escape
+ chars. */
+PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscape(
+ const char *string, /* Unicode-Escape encoded string */
+ Py_ssize_t length, /* size of string */
+ const char *errors, /* error handling */
+ const char **first_invalid_escape /* on return, points to first
+ invalid escaped char in
+ string. */
+);
+#endif
+
PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString(
PyObject *unicode /* Unicode object */
);
@@ -1640,13 +1679,13 @@ PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
);
#endif
-#ifdef HAVE_MBCS
+#ifdef MS_WINDOWS
/* --- MBCS codecs for Windows -------------------------------------------- */
PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCS(
const char *string, /* MBCS encoded string */
- Py_ssize_t length, /* size of string */
+ Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
@@ -1657,6 +1696,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCSStateful(
Py_ssize_t *consumed /* bytes consumed */
);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject*) PyUnicode_DecodeCodePageStateful(
int code_page, /* code page number */
const char *string, /* encoded string */
@@ -1664,6 +1704,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_DecodeCodePageStateful(
const char *errors, /* error handling */
Py_ssize_t *consumed /* bytes consumed */
);
+#endif
PyAPI_FUNC(PyObject*) PyUnicode_AsMBCSString(
PyObject *unicode /* Unicode object */
@@ -1677,13 +1718,15 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
);
#endif
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
PyAPI_FUNC(PyObject*) PyUnicode_EncodeCodePage(
int code_page, /* code page number */
PyObject *unicode, /* Unicode object */
const char *errors /* error handling */
);
+#endif
-#endif /* HAVE_MBCS */
+#endif /* MS_WINDOWS */
/* --- Decimal Encoder ---------------------------------------------------- */
@@ -1744,6 +1787,7 @@ PyAPI_FUNC(PyObject*) _PyUnicode_TransformDecimalAndSpaceToASCII(
/* --- Locale encoding --------------------------------------------------- */
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* Decode a string from the current locale encoding. The decoder is strict if
*surrogateescape* is equal to zero, otherwise it uses the 'surrogateescape'
error handler (PEP 383) to escape undecodable bytes. If a byte sequence can
@@ -1773,6 +1817,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeLocale(
PyObject *unicode,
const char *errors
);
+#endif
/* --- File system encoding ---------------------------------------------- */
@@ -1938,6 +1983,14 @@ PyAPI_FUNC(PyObject*) PyUnicode_Join(
PyObject *seq /* Sequence object */
);
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) _PyUnicode_JoinArray(
+ PyObject *separator,
+ PyObject **items,
+ Py_ssize_t seqlen
+ );
+#endif /* Py_LIMITED_API */
+
/* Return 1 if substr matches str[start:end] at the given tail end, 0
otherwise. */
@@ -1961,6 +2014,7 @@ PyAPI_FUNC(Py_ssize_t) PyUnicode_Find(
int direction /* Find direction: +1 forward, -1 backward */
);
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
/* Like PyUnicode_Find, but search for single character only. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_FindChar(
PyObject *str,
@@ -1969,6 +2023,7 @@ PyAPI_FUNC(Py_ssize_t) PyUnicode_FindChar(
Py_ssize_t end,
int direction
);
+#endif
/* Count the number of occurrences of substr in str[start:end]. */
@@ -2000,17 +2055,8 @@ PyAPI_FUNC(int) PyUnicode_Compare(
);
#ifndef Py_LIMITED_API
-/* Compare a string with an identifier and return -1, 0, 1 for less than,
- equal, and greater than, respectively.
- Raise an exception and return -1 on error. */
-
-PyAPI_FUNC(int) _PyUnicode_CompareWithId(
- PyObject *left, /* Left string */
- _Py_Identifier *right /* Right identifier */
- );
-
/* Test whether a unicode is equal to ASCII identifier. Return 1 if true,
- 0 otherwise. Return 0 if any argument contains non-ASCII characters.
+ 0 otherwise. The right argument must be ASCII identifier.
Any error occurs inside will be cleared before return. */
PyAPI_FUNC(int) _PyUnicode_EqualToASCIIId(
@@ -2032,7 +2078,7 @@ PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
#ifndef Py_LIMITED_API
/* Test whether a unicode is equal to ASCII string. Return 1 if true,
- 0 otherwise. Return 0 if any argument contains non-ASCII characters.
+ 0 otherwise. The right argument must be ASCII-encoded string.
Any error occurs inside will be cleared before return. */
PyAPI_FUNC(int) _PyUnicode_EqualToASCIIString(
@@ -2274,11 +2320,17 @@ PyAPI_FUNC(int) _PyUnicode_CheckConsistency(
int check_content);
#endif
+#ifndef Py_LIMITED_API
/* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/
PyAPI_FUNC(PyObject*) _PyUnicode_FromId(_Py_Identifier*);
/* Clear all static strings. */
PyAPI_FUNC(void) _PyUnicode_ClearStaticStrings(void);
+/* Fast equality check when the inputs are known to be exact unicode types
+ and where the hash values are equal (i.e. a very probable match) */
+PyAPI_FUNC(int) _PyUnicode_EQ(PyObject *, PyObject *);
+#endif /* !Py_LIMITED_API */
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/warnings.h b/Include/warnings.h
index effb9fad..a3f83ff 100644
--- a/Include/warnings.h
+++ b/Include/warnings.h
@@ -17,6 +17,15 @@ PyAPI_FUNC(int) PyErr_WarnFormat(
Py_ssize_t stack_level,
const char *format, /* ASCII-encoded string */
...);
+
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
+/* Emit a ResourceWarning warning */
+PyAPI_FUNC(int) PyErr_ResourceWarning(
+ PyObject *source,
+ Py_ssize_t stack_level,
+ const char *format, /* ASCII-encoded string */
+ ...);
+#endif
#ifndef Py_LIMITED_API
PyAPI_FUNC(int) PyErr_WarnExplicitObject(
PyObject *category,
diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py
index 8bebd69..b172f3f 100644
--- a/Lib/_collections_abc.py
+++ b/Lib/_collections_abc.py
@@ -9,9 +9,10 @@ Unit tests are in test_collections.
from abc import ABCMeta, abstractmethod
import sys
-__all__ = ["Awaitable", "Coroutine", "AsyncIterable", "AsyncIterator",
- "Hashable", "Iterable", "Iterator", "Generator",
- "Sized", "Container", "Callable",
+__all__ = ["Awaitable", "Coroutine",
+ "AsyncIterable", "AsyncIterator", "AsyncGenerator",
+ "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
+ "Sized", "Container", "Callable", "Collection",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
@@ -59,10 +60,27 @@ _coro = _coro()
coroutine = type(_coro)
_coro.close() # Prevent ResourceWarning
del _coro
+## asynchronous generator ##
+async def _ag(): yield
+_ag = _ag()
+async_generator = type(_ag)
+del _ag
### ONE-TRICK PONIES ###
+def _check_methods(C, *methods):
+ mro = C.__mro__
+ for method in methods:
+ for B in mro:
+ if method in B.__dict__:
+ if B.__dict__[method] is None:
+ return NotImplemented
+ break
+ else:
+ return NotImplemented
+ return True
+
class Hashable(metaclass=ABCMeta):
__slots__ = ()
@@ -74,11 +92,7 @@ class Hashable(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
- for B in C.__mro__:
- if "__hash__" in B.__dict__:
- if B.__dict__["__hash__"]:
- return True
- break
+ return _check_methods(C, "__hash__")
return NotImplemented
@@ -93,11 +107,7 @@ class Awaitable(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Awaitable:
- for B in C.__mro__:
- if "__await__" in B.__dict__:
- if B.__dict__["__await__"]:
- return True
- break
+ return _check_methods(C, "__await__")
return NotImplemented
@@ -138,14 +148,7 @@ class Coroutine(Awaitable):
@classmethod
def __subclasshook__(cls, C):
if cls is Coroutine:
- mro = C.__mro__
- for method in ('__await__', 'send', 'throw', 'close'):
- for base in mro:
- if method in base.__dict__:
- break
- else:
- return NotImplemented
- return True
+ return _check_methods(C, '__await__', 'send', 'throw', 'close')
return NotImplemented
@@ -163,8 +166,7 @@ class AsyncIterable(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is AsyncIterable:
- if any("__aiter__" in B.__dict__ for B in C.__mro__):
- return True
+ return _check_methods(C, "__aiter__")
return NotImplemented
@@ -183,12 +185,61 @@ class AsyncIterator(AsyncIterable):
@classmethod
def __subclasshook__(cls, C):
if cls is AsyncIterator:
- if (any("__anext__" in B.__dict__ for B in C.__mro__) and
- any("__aiter__" in B.__dict__ for B in C.__mro__)):
- return True
+ return _check_methods(C, "__anext__", "__aiter__")
return NotImplemented
+class AsyncGenerator(AsyncIterator):
+
+ __slots__ = ()
+
+ async def __anext__(self):
+ """Return the next item from the asynchronous generator.
+ When exhausted, raise StopAsyncIteration.
+ """
+ return await self.asend(None)
+
+ @abstractmethod
+ async def asend(self, value):
+ """Send a value into the asynchronous generator.
+ Return next yielded value or raise StopAsyncIteration.
+ """
+ raise StopAsyncIteration
+
+ @abstractmethod
+ async def athrow(self, typ, val=None, tb=None):
+ """Raise an exception in the asynchronous generator.
+ Return next yielded value or raise StopAsyncIteration.
+ """
+ if val is None:
+ if tb is None:
+ raise typ
+ val = typ()
+ if tb is not None:
+ val = val.with_traceback(tb)
+ raise val
+
+ async def aclose(self):
+ """Raise GeneratorExit inside coroutine.
+ """
+ try:
+ await self.athrow(GeneratorExit)
+ except (GeneratorExit, StopAsyncIteration):
+ pass
+ else:
+ raise RuntimeError("asynchronous generator ignored GeneratorExit")
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is AsyncGenerator:
+ return _check_methods(C, '__aiter__', '__anext__',
+ 'asend', 'athrow', 'aclose')
+ return NotImplemented
+
+
+AsyncGenerator.register(async_generator)
+
+
class Iterable(metaclass=ABCMeta):
__slots__ = ()
@@ -201,8 +252,7 @@ class Iterable(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
- if any("__iter__" in B.__dict__ for B in C.__mro__):
- return True
+ return _check_methods(C, "__iter__")
return NotImplemented
@@ -221,9 +271,7 @@ class Iterator(Iterable):
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
- if (any("__next__" in B.__dict__ for B in C.__mro__) and
- any("__iter__" in B.__dict__ for B in C.__mro__)):
- return True
+ return _check_methods(C, '__iter__', '__next__')
return NotImplemented
Iterator.register(bytes_iterator)
@@ -242,6 +290,22 @@ Iterator.register(tuple_iterator)
Iterator.register(zip_iterator)
+class Reversible(Iterable):
+
+ __slots__ = ()
+
+ @abstractmethod
+ def __reversed__(self):
+ while False:
+ yield None
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Reversible:
+ return _check_methods(C, "__reversed__", "__iter__")
+ return NotImplemented
+
+
class Generator(Iterator):
__slots__ = ()
@@ -285,17 +349,10 @@ class Generator(Iterator):
@classmethod
def __subclasshook__(cls, C):
if cls is Generator:
- mro = C.__mro__
- for method in ('__iter__', '__next__', 'send', 'throw', 'close'):
- for base in mro:
- if method in base.__dict__:
- break
- else:
- return NotImplemented
- return True
+ return _check_methods(C, '__iter__', '__next__',
+ 'send', 'throw', 'close')
return NotImplemented
-
Generator.register(generator)
@@ -310,8 +367,7 @@ class Sized(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
- if any("__len__" in B.__dict__ for B in C.__mro__):
- return True
+ return _check_methods(C, "__len__")
return NotImplemented
@@ -326,10 +382,18 @@ class Container(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
- if any("__contains__" in B.__dict__ for B in C.__mro__):
- return True
+ return _check_methods(C, "__contains__")
return NotImplemented
+class Collection(Sized, Iterable, Container):
+
+ __slots__ = ()
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Collection:
+ return _check_methods(C, "__len__", "__iter__", "__contains__")
+ return NotImplemented
class Callable(metaclass=ABCMeta):
@@ -342,15 +406,14 @@ class Callable(metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
- if any("__call__" in B.__dict__ for B in C.__mro__):
- return True
+ return _check_methods(C, "__call__")
return NotImplemented
### SETS ###
-class Set(Sized, Iterable, Container):
+class Set(Collection):
"""A set is a finite, iterable container.
@@ -575,7 +638,7 @@ MutableSet.register(set)
### MAPPINGS ###
-class Mapping(Sized, Iterable, Container):
+class Mapping(Collection):
__slots__ = ()
@@ -623,6 +686,8 @@ class Mapping(Sized, Iterable, Container):
return NotImplemented
return dict(self.items()) == dict(other.items())
+ __reversed__ = None
+
Mapping.register(mappingproxy)
@@ -672,7 +737,7 @@ class ItemsView(MappingView, Set):
except KeyError:
return False
else:
- return v == value
+ return v is value or v == value
def __iter__(self):
for key in self._mapping:
@@ -687,7 +752,8 @@ class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
- if value == self._mapping[key]:
+ v = self._mapping[key]
+ if v is value or v == value:
return True
return False
@@ -796,7 +862,7 @@ MutableMapping.register(dict)
### SEQUENCES ###
-class Sequence(Sized, Iterable, Container):
+class Sequence(Reversible, Collection):
"""All the operations on a read-only sequence.
@@ -822,7 +888,7 @@ class Sequence(Sized, Iterable, Container):
def __contains__(self, value):
for v in self:
- if v == value:
+ if v is value or v == value:
return True
return False
diff --git a/Lib/_compat_pickle.py b/Lib/_compat_pickle.py
index c0e0443..f68496a 100644
--- a/Lib/_compat_pickle.py
+++ b/Lib/_compat_pickle.py
@@ -242,3 +242,10 @@ PYTHON3_OSERROR_EXCEPTIONS = (
for excname in PYTHON3_OSERROR_EXCEPTIONS:
REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError')
+
+PYTHON3_IMPORTERROR_EXCEPTIONS = (
+ 'ModuleNotFoundError',
+)
+
+for excname in PYTHON3_IMPORTERROR_EXCEPTIONS:
+ REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'ImportError')
diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py
index 13fcd8b..eadf06f 100644
--- a/Lib/_osx_support.py
+++ b/Lib/_osx_support.py
@@ -210,7 +210,7 @@ def _remove_universal_flags(_config_vars):
# Do not alter a config var explicitly overridden by env var
if cv in _config_vars and cv not in os.environ:
flags = _config_vars[cv]
- flags = re.sub('-arch\s+\w+\s', ' ', flags, re.ASCII)
+ flags = re.sub(r'-arch\s+\w+\s', ' ', flags, re.ASCII)
flags = re.sub('-isysroot [^ \t]*', ' ', flags)
_save_modified_value(_config_vars, cv, flags)
@@ -232,7 +232,7 @@ def _remove_unsupported_archs(_config_vars):
if 'CC' in os.environ:
return _config_vars
- if re.search('-arch\s+ppc', _config_vars['CFLAGS']) is not None:
+ if re.search(r'-arch\s+ppc', _config_vars['CFLAGS']) is not None:
# NOTE: Cannot use subprocess here because of bootstrap
# issues when building Python itself
status = os.system(
@@ -251,7 +251,7 @@ def _remove_unsupported_archs(_config_vars):
for cv in _UNIVERSAL_CONFIG_VARS:
if cv in _config_vars and cv not in os.environ:
flags = _config_vars[cv]
- flags = re.sub('-arch\s+ppc\w*\s', ' ', flags)
+ flags = re.sub(r'-arch\s+ppc\w*\s', ' ', flags)
_save_modified_value(_config_vars, cv, flags)
return _config_vars
@@ -267,7 +267,7 @@ def _override_all_archs(_config_vars):
for cv in _UNIVERSAL_CONFIG_VARS:
if cv in _config_vars and '-arch' in _config_vars[cv]:
flags = _config_vars[cv]
- flags = re.sub('-arch\s+\w+\s', ' ', flags)
+ flags = re.sub(r'-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_save_modified_value(_config_vars, cv, flags)
@@ -465,7 +465,7 @@ def get_platform_osx(_config_vars, osname, release, machine):
machine = 'fat'
- archs = re.findall('-arch\s+(\S+)', cflags)
+ archs = re.findall(r'-arch\s+(\S+)', cflags)
archs = tuple(sorted(set(archs)))
if len(archs) == 1:
diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py
index a5ea340..0b40928 100644
--- a/Lib/_pydecimal.py
+++ b/Lib/_pydecimal.py
@@ -148,7 +148,7 @@ __xname__ = __name__ # sys.modules lookup (--without-threads)
__name__ = 'decimal' # For pickling
__version__ = '1.70' # Highest version of the spec this complies with
# See http://speleotrove.com/decimal/
-__libmpdec_version__ = "2.4.1" # compatible libmpdec version
+__libmpdec_version__ = "2.4.2" # compatible libmpdec version
import math as _math
import numbers as _numbers
@@ -589,7 +589,7 @@ class Decimal(object):
# From a string
# REs insist on real strings, so we can too.
if isinstance(value, str):
- m = _parser(value.strip())
+ m = _parser(value.strip().replace("_", ""))
if m is None:
if context is None:
context = getcontext()
@@ -1010,6 +1010,56 @@ class Decimal(object):
"""
return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
+ def as_integer_ratio(self):
+ """Express a finite Decimal instance in the form n / d.
+
+ Returns a pair (n, d) of integers. When called on an infinity
+ or NaN, raises OverflowError or ValueError respectively.
+
+ >>> Decimal('3.14').as_integer_ratio()
+ (157, 50)
+ >>> Decimal('-123e5').as_integer_ratio()
+ (-12300000, 1)
+ >>> Decimal('0.00').as_integer_ratio()
+ (0, 1)
+
+ """
+ if self._is_special:
+ if self.is_nan():
+ raise ValueError("cannot convert NaN to integer ratio")
+ else:
+ raise OverflowError("cannot convert Infinity to integer ratio")
+
+ if not self:
+ return 0, 1
+
+ # Find n, d in lowest terms such that abs(self) == n / d;
+ # we'll deal with the sign later.
+ n = int(self._int)
+ if self._exp >= 0:
+ # self is an integer.
+ n, d = n * 10**self._exp, 1
+ else:
+ # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5).
+ d5 = -self._exp
+ while d5 > 0 and n % 5 == 0:
+ n //= 5
+ d5 -= 1
+
+ # (n & -n).bit_length() - 1 counts trailing zeros in binary
+ # representation of n (provided n is nonzero).
+ d2 = -self._exp
+ shift2 = min((n & -n).bit_length() - 1, d2)
+ if shift2:
+ n >>= shift2
+ d2 -= shift2
+
+ d = 5**d5 << d2
+
+ if self._sign:
+ n = -n
+ return n, d
+
def __repr__(self):
"""Represents the number as an instance of Decimal."""
# Invariant: eval(repr(d)) == d
@@ -4075,7 +4125,7 @@ class Context(object):
This will make it round up for that operation.
"""
rounding = self.rounding
- self.rounding= type
+ self.rounding = type
return rounding
def create_decimal(self, num='0'):
@@ -4084,10 +4134,10 @@ class Context(object):
This method implements the to-number operation of the
IBM Decimal specification."""
- if isinstance(num, str) and num != num.strip():
+ if isinstance(num, str) and (num != num.strip() or '_' in num):
return self._raise_error(ConversionSyntax,
- "no trailing or leading whitespace is "
- "permitted.")
+ "trailing or leading whitespace and "
+ "underscores are not permitted.")
d = Decimal(num, context=self)
if d._isnan() and len(d._int) > self.prec - self.clamp:
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index f2fe447..2ebfb05 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -6,7 +6,6 @@ import os
import abc
import codecs
import errno
-import array
import stat
import sys
# Import _thread instead of threading to reduce startup cost
@@ -161,6 +160,8 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
+ if not isinstance(file, int):
+ file = os.fspath(file)
if not isinstance(file, (str, bytes, int)):
raise TypeError("invalid file: %r" % file)
if not isinstance(mode, str):
@@ -182,8 +183,8 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
text = "t" in modes
binary = "b" in modes
if "U" in modes:
- if creating or writing or appending:
- raise ValueError("can't use U and writing mode at once")
+ if creating or writing or appending or updating:
+ raise ValueError("mode U cannot be combined with 'x', 'w', 'a', or '+'")
import warnings
warnings.warn("'U' mode is deprecated",
DeprecationWarning, 2)
@@ -1516,7 +1517,7 @@ class FileIO(RawIOBase):
if self._fd >= 0 and self._closefd and not self.closed:
import warnings
warnings.warn('unclosed file %r' % (self,), ResourceWarning,
- stacklevel=2)
+ stacklevel=2, source=self)
self.close()
def __getstate__(self):
diff --git a/Lib/_strptime.py b/Lib/_strptime.py
index f84227b..fe94361 100644
--- a/Lib/_strptime.py
+++ b/Lib/_strptime.py
@@ -199,12 +199,15 @@ class TimeRE(dict):
'f': r"(?P<f>[0-9]{1,6})",
'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
+ 'G': r"(?P<G>\d\d\d\d)",
'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",
'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
'M': r"(?P<M>[0-5]\d|\d)",
'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
'w': r"(?P<w>[0-6])",
+ 'u': r"(?P<u>[1-7])",
+ 'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",
# W is set below by using 'U'
'y': r"(?P<y>\d\d)",
#XXX: Does 'Y' need to worry about having less or more than
@@ -299,6 +302,22 @@ def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
return 1 + days_to_week + day_of_week
+def _calc_julian_from_V(iso_year, iso_week, iso_weekday):
+ """Calculate the Julian day based on the ISO 8601 year, week, and weekday.
+ ISO weeks start on Mondays, with week 01 being the week containing 4 Jan.
+ ISO week days range from 1 (Monday) to 7 (Sunday).
+ """
+ correction = datetime_date(iso_year, 1, 4).isoweekday() + 3
+ ordinal = (iso_week * 7) + iso_weekday - correction
+ # ordinal may be negative or 0 now, which means the date is in the previous
+ # calendar year
+ if ordinal < 1:
+ ordinal += datetime_date(iso_year, 1, 1).toordinal()
+ iso_year -= 1
+ ordinal -= datetime_date(iso_year, 1, 1).toordinal()
+ return iso_year, ordinal
+
+
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
"""Return a 2-tuple consisting of a time struct and an int containing
the number of microseconds based on the input string and the
@@ -345,15 +364,15 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
raise ValueError("unconverted data remains: %s" %
data_string[found.end():])
- year = None
+ iso_year = year = None
month = day = 1
hour = minute = second = fraction = 0
tz = -1
tzoffset = None
# Default to -1 to signify that values not known; not critical to have,
# though
- week_of_year = -1
- week_of_year_start = -1
+ iso_week = week_of_year = None
+ week_of_year_start = None
# weekday and julian defaulted to None so as to signal need to calculate
# values
weekday = julian = None
@@ -375,6 +394,8 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
year += 1900
elif group_key == 'Y':
year = int(found_dict['Y'])
+ elif group_key == 'G':
+ iso_year = int(found_dict['G'])
elif group_key == 'm':
month = int(found_dict['m'])
elif group_key == 'B':
@@ -420,6 +441,9 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
weekday = 6
else:
weekday -= 1
+ elif group_key == 'u':
+ weekday = int(found_dict['u'])
+ weekday -= 1
elif group_key == 'j':
julian = int(found_dict['j'])
elif group_key in ('U', 'W'):
@@ -430,6 +454,8 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
else:
# W starts week on Monday.
week_of_year_start = 0
+ elif group_key == 'V':
+ iso_week = int(found_dict['V'])
elif group_key == 'z':
z = found_dict['z']
tzoffset = int(z[1:3]) * 60 + int(z[3:5])
@@ -450,32 +476,61 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
else:
tz = value
break
+ # Deal with the cases where ambiguities arize
+ # don't assume default values for ISO week/year
+ if year is None and iso_year is not None:
+ if iso_week is None or weekday is None:
+ raise ValueError("ISO year directive '%G' must be used with "
+ "the ISO week directive '%V' and a weekday "
+ "directive ('%A', '%a', '%w', or '%u').")
+ if julian is not None:
+ raise ValueError("Day of the year directive '%j' is not "
+ "compatible with ISO year directive '%G'. "
+ "Use '%Y' instead.")
+ elif week_of_year is None and iso_week is not None:
+ if weekday is None:
+ raise ValueError("ISO week directive '%V' must be used with "
+ "the ISO year directive '%G' and a weekday "
+ "directive ('%A', '%a', '%w', or '%u').")
+ else:
+ raise ValueError("ISO week directive '%V' is incompatible with "
+ "the year directive '%Y'. Use the ISO year '%G' "
+ "instead.")
+
leap_year_fix = False
if year is None and month == 2 and day == 29:
year = 1904 # 1904 is first leap year of 20th century
leap_year_fix = True
elif year is None:
year = 1900
+
+
# If we know the week of the year and what day of that week, we can figure
# out the Julian day of the year.
- if julian is None and week_of_year != -1 and weekday is not None:
- week_starts_Mon = True if week_of_year_start == 0 else False
- julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
- week_starts_Mon)
- if julian <= 0:
+ if julian is None and weekday is not None:
+ if week_of_year is not None:
+ week_starts_Mon = True if week_of_year_start == 0 else False
+ julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
+ week_starts_Mon)
+ elif iso_year is not None and iso_week is not None:
+ year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1)
+ if julian is not None and julian <= 0:
year -= 1
yday = 366 if calendar.isleap(year) else 365
julian += yday
- # Cannot pre-calculate datetime_date() since can change in Julian
- # calculation and thus could have different value for the day of the week
- # calculation.
+
if julian is None:
+ # Cannot pre-calculate datetime_date() since can change in Julian
+ # calculation and thus could have different value for the day of
+ # the week calculation.
# Need to add 1 to result since first day of the year is 1, not 0.
julian = datetime_date(year, month, day).toordinal() - \
datetime_date(year, 1, 1).toordinal() + 1
- else: # Assume that if they bothered to include Julian day it will
- # be accurate.
- datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
+ else: # Assume that if they bothered to include Julian day (or if it was
+ # calculated above with year/week/weekday) it will be accurate.
+ datetime_result = datetime_date.fromordinal(
+ (julian - 1) +
+ datetime_date(year, 1, 1).toordinal())
year = datetime_result.year
month = datetime_result.month
day = datetime_result.day
diff --git a/Lib/aifc.py b/Lib/aifc.py
index 7ebdbeb..692d0bf 100644
--- a/Lib/aifc.py
+++ b/Lib/aifc.py
@@ -257,6 +257,15 @@ from collections import namedtuple
_aifc_params = namedtuple('_aifc_params',
'nchannels sampwidth framerate nframes comptype compname')
+_aifc_params.nchannels.__doc__ = 'Number of audio channels (1 for mono, 2 for stereo)'
+_aifc_params.sampwidth.__doc__ = 'Sample width in bytes'
+_aifc_params.framerate.__doc__ = 'Sampling frequency'
+_aifc_params.nframes.__doc__ = 'Number of audio frames'
+_aifc_params.comptype.__doc__ = 'Compression type ("NONE" for AIFF files)'
+_aifc_params.compname.__doc__ = ("""\
+A human-readable version of the compression type
+('not compressed' for AIFF files)""")
+
class Aifc_read:
# Variables used in this class:
diff --git a/Lib/argparse.py b/Lib/argparse.py
index 9a06719..209b4e9 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -118,10 +118,16 @@ class _AttributeHolder(object):
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
+ star_args = {}
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
- arg_strings.append('%s=%r' % (name, value))
+ if name.isidentifier():
+ arg_strings.append('%s=%r' % (name, value))
+ else:
+ star_args[name] = value
+ if star_args:
+ arg_strings.append('**%s' % repr(star_args))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
@@ -204,8 +210,6 @@ class HelpFormatter(object):
if self.parent is not None:
self.formatter._indent()
join = self.formatter._join_parts
- for func, args in self.items:
- func(*args)
item_help = join([func(*args) for func, args in self.items])
if self.parent is not None:
self.formatter._dedent()
diff --git a/Lib/ast.py b/Lib/ast.py
index 0170472..156a1f2 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -35,6 +35,8 @@ def parse(source, filename='<unknown>', mode='exec'):
return compile(source, filename, mode, PyCF_ONLY_AST)
+_NUM_TYPES = (int, float, complex)
+
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
@@ -47,7 +49,9 @@ def literal_eval(node_or_string):
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.body
def _convert(node):
- if isinstance(node, (Str, Bytes)):
+ if isinstance(node, Constant):
+ return node.value
+ elif isinstance(node, (Str, Bytes)):
return node.s
elif isinstance(node, Num):
return node.n
@@ -62,24 +66,21 @@ def literal_eval(node_or_string):
in zip(node.keys, node.values))
elif isinstance(node, NameConstant):
return node.value
- elif isinstance(node, UnaryOp) and \
- isinstance(node.op, (UAdd, USub)) and \
- isinstance(node.operand, (Num, UnaryOp, BinOp)):
+ elif isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
operand = _convert(node.operand)
- if isinstance(node.op, UAdd):
- return + operand
- else:
- return - operand
- elif isinstance(node, BinOp) and \
- isinstance(node.op, (Add, Sub)) and \
- isinstance(node.right, (Num, UnaryOp, BinOp)) and \
- isinstance(node.left, (Num, UnaryOp, BinOp)):
+ if isinstance(operand, _NUM_TYPES):
+ if isinstance(node.op, UAdd):
+ return + operand
+ else:
+ return - operand
+ elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
left = _convert(node.left)
right = _convert(node.right)
- if isinstance(node.op, Add):
- return left + right
- else:
- return left - right
+ if isinstance(left, _NUM_TYPES) and isinstance(right, _NUM_TYPES):
+ if isinstance(node.op, Add):
+ return left + right
+ else:
+ return left - right
raise ValueError('malformed node or string: ' + repr(node))
return _convert(node_or_string)
@@ -196,12 +197,19 @@ def get_docstring(node, clean=True):
"""
if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
- if node.body and isinstance(node.body[0], Expr) and \
- isinstance(node.body[0].value, Str):
- if clean:
- import inspect
- return inspect.cleandoc(node.body[0].value.s)
- return node.body[0].value.s
+ if not(node.body and isinstance(node.body[0], Expr)):
+ return
+ node = node.body[0].value
+ if isinstance(node, Str):
+ text = node.s
+ elif isinstance(node, Constant) and isinstance(node.value, str):
+ text = node.value
+ else:
+ return
+ if clean:
+ import inspect
+ text = inspect.cleandoc(text)
+ return text
def walk(node):
diff --git a/Lib/asynchat.py b/Lib/asynchat.py
index f728d1b..fc1146a 100644
--- a/Lib/asynchat.py
+++ b/Lib/asynchat.py
@@ -285,35 +285,6 @@ class simple_producer:
return result
-class fifo:
- def __init__(self, list=None):
- import warnings
- warnings.warn('fifo class will be removed in Python 3.6',
- DeprecationWarning, stacklevel=2)
- if not list:
- self.list = deque()
- else:
- self.list = deque(list)
-
- def __len__(self):
- return len(self.list)
-
- def is_empty(self):
- return not self.list
-
- def first(self):
- return self.list[0]
-
- def push(self, data):
- self.list.append(data)
-
- def pop(self):
- if self.list:
- return (1, self.list.popleft())
- else:
- return (0, None)
-
-
# Given 'haystack', see if any prefix of 'needle' is at its end. This
# assumes an exact match has already been checked. Return the number of
# characters matched.
diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py
index 50153f8..0df58c5 100644
--- a/Lib/asyncio/base_events.py
+++ b/Lib/asyncio/base_events.py
@@ -57,7 +57,7 @@ _FATAL_ERROR_IGNORE = (BrokenPipeError,
def _format_handle(handle):
cb = handle._callback
- if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
+ if isinstance(getattr(cb, '__self__', None), tasks.Task):
# format the task
return repr(cb.__self__)
else:
@@ -505,7 +505,8 @@ class BaseEventLoop(events.AbstractEventLoop):
if compat.PY34:
def __del__(self):
if not self.is_closed():
- warnings.warn("unclosed event loop %r" % self, ResourceWarning)
+ warnings.warn("unclosed event loop %r" % self, ResourceWarning,
+ source=self)
if not self.is_running():
self.close()
diff --git a/Lib/asyncio/base_futures.py b/Lib/asyncio/base_futures.py
new file mode 100644
index 0000000..01259a0
--- /dev/null
+++ b/Lib/asyncio/base_futures.py
@@ -0,0 +1,71 @@
+__all__ = []
+
+import concurrent.futures._base
+import reprlib
+
+from . import events
+
+Error = concurrent.futures._base.Error
+CancelledError = concurrent.futures.CancelledError
+TimeoutError = concurrent.futures.TimeoutError
+
+
+class InvalidStateError(Error):
+ """The operation is not allowed in this state."""
+
+
+# States for Future.
+_PENDING = 'PENDING'
+_CANCELLED = 'CANCELLED'
+_FINISHED = 'FINISHED'
+
+
+def isfuture(obj):
+ """Check for a Future.
+
+ This returns True when obj is a Future instance or is advertising
+ itself as duck-type compatible by setting _asyncio_future_blocking.
+ See comment in Future for more details.
+ """
+ return (hasattr(obj.__class__, '_asyncio_future_blocking') and
+ obj._asyncio_future_blocking is not None)
+
+
+def _format_callbacks(cb):
+ """helper function for Future.__repr__"""
+ size = len(cb)
+ if not size:
+ cb = ''
+
+ def format_cb(callback):
+ return events._format_callback_source(callback, ())
+
+ if size == 1:
+ cb = format_cb(cb[0])
+ elif size == 2:
+ cb = '{}, {}'.format(format_cb(cb[0]), format_cb(cb[1]))
+ elif size > 2:
+ cb = '{}, <{} more>, {}'.format(format_cb(cb[0]),
+ size - 2,
+ format_cb(cb[-1]))
+ return 'cb=[%s]' % cb
+
+
+def _future_repr_info(future):
+ # (Future) -> str
+ """helper function for Future.__repr__"""
+ info = [future._state.lower()]
+ if future._state == _FINISHED:
+ if future._exception is not None:
+ info.append('exception={!r}'.format(future._exception))
+ else:
+ # use reprlib to limit the length of the output, especially
+ # for very long strings
+ result = reprlib.repr(future._result)
+ info.append('result={}'.format(result))
+ if future._callbacks:
+ info.append(_format_callbacks(future._callbacks))
+ if future._source_traceback:
+ frame = future._source_traceback[-1]
+ info.append('created at %s:%s' % (frame[0], frame[1]))
+ return info
diff --git a/Lib/asyncio/base_subprocess.py b/Lib/asyncio/base_subprocess.py
index 23742a1..a00d9d5 100644
--- a/Lib/asyncio/base_subprocess.py
+++ b/Lib/asyncio/base_subprocess.py
@@ -127,7 +127,8 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
if compat.PY34:
def __del__(self):
if not self._closed:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self.close()
def get_pid(self):
diff --git a/Lib/asyncio/base_tasks.py b/Lib/asyncio/base_tasks.py
new file mode 100644
index 0000000..5f34434
--- /dev/null
+++ b/Lib/asyncio/base_tasks.py
@@ -0,0 +1,76 @@
+import linecache
+import traceback
+
+from . import base_futures
+from . import coroutines
+
+
+def _task_repr_info(task):
+ info = base_futures._future_repr_info(task)
+
+ if task._must_cancel:
+ # replace status
+ info[0] = 'cancelling'
+
+ coro = coroutines._format_coroutine(task._coro)
+ info.insert(1, 'coro=<%s>' % coro)
+
+ if task._fut_waiter is not None:
+ info.insert(2, 'wait_for=%r' % task._fut_waiter)
+ return info
+
+
+def _task_get_stack(task, limit):
+ frames = []
+ try:
+ # 'async def' coroutines
+ f = task._coro.cr_frame
+ except AttributeError:
+ f = task._coro.gi_frame
+ if f is not None:
+ while f is not None:
+ if limit is not None:
+ if limit <= 0:
+ break
+ limit -= 1
+ frames.append(f)
+ f = f.f_back
+ frames.reverse()
+ elif task._exception is not None:
+ tb = task._exception.__traceback__
+ while tb is not None:
+ if limit is not None:
+ if limit <= 0:
+ break
+ limit -= 1
+ frames.append(tb.tb_frame)
+ tb = tb.tb_next
+ return frames
+
+
+def _task_print_stack(task, limit, file):
+ extracted_list = []
+ checked = set()
+ for f in task.get_stack(limit=limit):
+ lineno = f.f_lineno
+ co = f.f_code
+ filename = co.co_filename
+ name = co.co_name
+ if filename not in checked:
+ checked.add(filename)
+ linecache.checkcache(filename)
+ line = linecache.getline(filename, lineno, f.f_globals)
+ extracted_list.append((filename, lineno, name, line))
+ exc = task._exception
+ if not extracted_list:
+ print('No stack for %r' % task, file=file)
+ elif exc is not None:
+ print('Traceback for %r (most recent call last):' % task,
+ file=file)
+ else:
+ print('Stack for %r (most recent call last):' % task,
+ file=file)
+ traceback.print_list(extracted_list, file=file)
+ if exc is not None:
+ for line in traceback.format_exception_only(exc.__class__, exc):
+ print(line, file=file, end='')
diff --git a/Lib/asyncio/coroutines.py b/Lib/asyncio/coroutines.py
index 5bdeceb..08e9441 100644
--- a/Lib/asyncio/coroutines.py
+++ b/Lib/asyncio/coroutines.py
@@ -11,7 +11,7 @@ import types
from . import compat
from . import events
-from . import futures
+from . import base_futures
from .log import logger
@@ -208,7 +208,7 @@ def coroutine(func):
@functools.wraps(func)
def coro(*args, **kw):
res = func(*args, **kw)
- if (futures.isfuture(res) or inspect.isgenerator(res) or
+ if (base_futures.isfuture(res) or inspect.isgenerator(res) or
isinstance(res, CoroWrapper)):
res = yield from res
elif _AwaitableABC is not None:
diff --git a/Lib/asyncio/futures.py b/Lib/asyncio/futures.py
index 9ca8d84..d11d289 100644
--- a/Lib/asyncio/futures.py
+++ b/Lib/asyncio/futures.py
@@ -1,33 +1,30 @@
"""A Future class similar to the one in PEP 3148."""
-__all__ = ['CancelledError', 'TimeoutError',
- 'InvalidStateError',
- 'Future', 'wrap_future', 'isfuture',
- ]
+__all__ = ['CancelledError', 'TimeoutError', 'InvalidStateError',
+ 'Future', 'wrap_future', 'isfuture']
-import concurrent.futures._base
+import concurrent.futures
import logging
-import reprlib
import sys
import traceback
+from . import base_futures
from . import compat
from . import events
-# States for Future.
-_PENDING = 'PENDING'
-_CANCELLED = 'CANCELLED'
-_FINISHED = 'FINISHED'
-Error = concurrent.futures._base.Error
-CancelledError = concurrent.futures.CancelledError
-TimeoutError = concurrent.futures.TimeoutError
+CancelledError = base_futures.CancelledError
+InvalidStateError = base_futures.InvalidStateError
+TimeoutError = base_futures.TimeoutError
+isfuture = base_futures.isfuture
-STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
+
+_PENDING = base_futures._PENDING
+_CANCELLED = base_futures._CANCELLED
+_FINISHED = base_futures._FINISHED
-class InvalidStateError(Error):
- """The operation is not allowed in this state."""
+STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
class _TracebackLogger:
@@ -110,17 +107,6 @@ class _TracebackLogger:
self.loop.call_exception_handler({'message': msg})
-def isfuture(obj):
- """Check for a Future.
-
- This returns True when obj is a Future instance or is advertising
- itself as duck-type compatible by setting _asyncio_future_blocking.
- See comment in Future for more details.
- """
- return (hasattr(obj.__class__, '_asyncio_future_blocking') and
- obj._asyncio_future_blocking is not None)
-
-
class Future:
"""This class is *almost* compatible with concurrent.futures.Future.
@@ -173,45 +159,10 @@ class Future:
if self._loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))
- def __format_callbacks(self):
- cb = self._callbacks
- size = len(cb)
- if not size:
- cb = ''
-
- def format_cb(callback):
- return events._format_callback_source(callback, ())
-
- if size == 1:
- cb = format_cb(cb[0])
- elif size == 2:
- cb = '{}, {}'.format(format_cb(cb[0]), format_cb(cb[1]))
- elif size > 2:
- cb = '{}, <{} more>, {}'.format(format_cb(cb[0]),
- size-2,
- format_cb(cb[-1]))
- return 'cb=[%s]' % cb
-
- def _repr_info(self):
- info = [self._state.lower()]
- if self._state == _FINISHED:
- if self._exception is not None:
- info.append('exception={!r}'.format(self._exception))
- else:
- # use reprlib to limit the length of the output, especially
- # for very long strings
- result = reprlib.repr(self._result)
- info.append('result={}'.format(result))
- if self._callbacks:
- info.append(self.__format_callbacks())
- if self._source_traceback:
- frame = self._source_traceback[-1]
- info.append('created at %s:%s' % (frame[0], frame[1]))
- return info
+ _repr_info = base_futures._future_repr_info
def __repr__(self):
- info = self._repr_info()
- return '<%s %s>' % (self.__class__.__name__, ' '.join(info))
+ return '<%s %s>' % (self.__class__.__name__, ' '.join(self._repr_info()))
# On Python 3.3 and older, objects with a destructor part of a reference
# cycle are never destroyed. It's not more the case on Python 3.4 thanks
@@ -385,6 +336,10 @@ class Future:
__await__ = __iter__ # make compatible with 'await' expression
+# Needed for testing purposes.
+_PyFuture = Future
+
+
def _set_result_unless_cancelled(fut, result):
"""Helper setting the result only if the future was not cancelled."""
if fut.cancelled():
@@ -477,3 +432,12 @@ def wrap_future(future, *, loop=None):
new_future = loop.create_future()
_chain_future(future, new_future)
return new_future
+
+
+try:
+ import _asyncio
+except ImportError:
+ pass
+else:
+ # _CFuture is needed for tests.
+ Future = _CFuture = _asyncio.Future
diff --git a/Lib/asyncio/proactor_events.py b/Lib/asyncio/proactor_events.py
index fef3205..ff12877 100644
--- a/Lib/asyncio/proactor_events.py
+++ b/Lib/asyncio/proactor_events.py
@@ -92,7 +92,8 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin,
if compat.PY34:
def __del__(self):
if self._sock is not None:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self.close()
def _fatal_error(self, exc, message='Fatal error on pipe transport'):
diff --git a/Lib/asyncio/selector_events.py b/Lib/asyncio/selector_events.py
index 12d357b..9dbe550 100644
--- a/Lib/asyncio/selector_events.py
+++ b/Lib/asyncio/selector_events.py
@@ -627,7 +627,8 @@ class _SelectorTransport(transports._FlowControlMixin,
if compat.PY34:
def __del__(self):
if self._sock is not None:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self._sock.close()
def _fatal_error(self, exc, message='Fatal error on transport'):
diff --git a/Lib/asyncio/sslproto.py b/Lib/asyncio/sslproto.py
index c2c4b95..7ad28d6 100644
--- a/Lib/asyncio/sslproto.py
+++ b/Lib/asyncio/sslproto.py
@@ -331,7 +331,8 @@ class _SSLProtocolTransport(transports._FlowControlMixin,
if compat.PY34:
def __del__(self):
if not self._closed:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self.close()
def pause_reading(self):
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py
index 8852aa5..5a43ef2 100644
--- a/Lib/asyncio/tasks.py
+++ b/Lib/asyncio/tasks.py
@@ -9,11 +9,10 @@ __all__ = ['Task',
import concurrent.futures
import functools
import inspect
-import linecache
-import traceback
import warnings
import weakref
+from . import base_tasks
from . import compat
from . import coroutines
from . import events
@@ -93,18 +92,7 @@ class Task(futures.Future):
futures.Future.__del__(self)
def _repr_info(self):
- info = super()._repr_info()
-
- if self._must_cancel:
- # replace status
- info[0] = 'cancelling'
-
- coro = coroutines._format_coroutine(self._coro)
- info.insert(1, 'coro=<%s>' % coro)
-
- if self._fut_waiter is not None:
- info.insert(2, 'wait_for=%r' % self._fut_waiter)
- return info
+ return base_tasks._task_repr_info(self)
def get_stack(self, *, limit=None):
"""Return the list of stack frames for this task's coroutine.
@@ -127,31 +115,7 @@ class Task(futures.Future):
For reasons beyond our control, only one stack frame is
returned for a suspended coroutine.
"""
- frames = []
- try:
- # 'async def' coroutines
- f = self._coro.cr_frame
- except AttributeError:
- f = self._coro.gi_frame
- if f is not None:
- while f is not None:
- if limit is not None:
- if limit <= 0:
- break
- limit -= 1
- frames.append(f)
- f = f.f_back
- frames.reverse()
- elif self._exception is not None:
- tb = self._exception.__traceback__
- while tb is not None:
- if limit is not None:
- if limit <= 0:
- break
- limit -= 1
- frames.append(tb.tb_frame)
- tb = tb.tb_next
- return frames
+ return base_tasks._task_get_stack(self, limit)
def print_stack(self, *, limit=None, file=None):
"""Print the stack or traceback for this task's coroutine.
@@ -162,31 +126,7 @@ class Task(futures.Future):
to which the output is written; by default output is written
to sys.stderr.
"""
- extracted_list = []
- checked = set()
- for f in self.get_stack(limit=limit):
- lineno = f.f_lineno
- co = f.f_code
- filename = co.co_filename
- name = co.co_name
- if filename not in checked:
- checked.add(filename)
- linecache.checkcache(filename)
- line = linecache.getline(filename, lineno, f.f_globals)
- extracted_list.append((filename, lineno, name, line))
- exc = self._exception
- if not extracted_list:
- print('No stack for %r' % self, file=file)
- elif exc is not None:
- print('Traceback for %r (most recent call last):' % self,
- file=file)
- else:
- print('Stack for %r (most recent call last):' % self,
- file=file)
- traceback.print_list(extracted_list, file=file)
- if exc is not None:
- for line in traceback.format_exception_only(exc.__class__, exc):
- print(line, file=file, end='')
+ return base_tasks._task_print_stack(self, limit, file)
def cancel(self):
"""Request that this task cancel itself.
@@ -316,6 +256,18 @@ class Task(futures.Future):
self = None # Needed to break cycles when an exception occurs.
+_PyTask = Task
+
+
+try:
+ import _asyncio
+except ImportError:
+ pass
+else:
+ # _CTask is needed for tests.
+ Task = _CTask = _asyncio.Task
+
+
# wait() and as_completed() similar to those in PEP 3148.
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
diff --git a/Lib/asyncio/test_utils.py b/Lib/asyncio/test_utils.py
index 9d32822..99e3839 100644
--- a/Lib/asyncio/test_utils.py
+++ b/Lib/asyncio/test_utils.py
@@ -119,10 +119,10 @@ class SSLWSGIServerMixin:
'test', 'test_asyncio')
keyfile = os.path.join(here, 'ssl_key.pem')
certfile = os.path.join(here, 'ssl_cert.pem')
- ssock = ssl.wrap_socket(request,
- keyfile=keyfile,
- certfile=certfile,
- server_side=True)
+ context = ssl.SSLContext()
+ context.load_cert_chain(certfile, keyfile)
+
+ ssock = context.wrap_socket(request, server_side=True)
try:
self.RequestHandlerClass(ssock, client_address, self)
ssock.close()
diff --git a/Lib/asyncio/unix_events.py b/Lib/asyncio/unix_events.py
index 7790534..2806ea8 100644
--- a/Lib/asyncio/unix_events.py
+++ b/Lib/asyncio/unix_events.py
@@ -419,7 +419,8 @@ class _UnixReadPipeTransport(transports.ReadTransport):
if compat.PY34:
def __del__(self):
if self._pipe is not None:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self._pipe.close()
def _fatal_error(self, exc, message='Fatal error on pipe transport'):
@@ -619,7 +620,8 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
if compat.PY34:
def __del__(self):
if self._pipe is not None:
- warnings.warn("unclosed transport %r" % self, ResourceWarning)
+ warnings.warn("unclosed transport %r" % self, ResourceWarning,
+ source=self)
self._pipe.close()
def abort(self):
diff --git a/Lib/asyncio/windows_events.py b/Lib/asyncio/windows_events.py
index 668fe14..b777dd0 100644
--- a/Lib/asyncio/windows_events.py
+++ b/Lib/asyncio/windows_events.py
@@ -171,8 +171,13 @@ class _WaitCancelFuture(_BaseWaitHandleFuture):
def cancel(self):
raise RuntimeError("_WaitCancelFuture must not be cancelled")
- def _schedule_callbacks(self):
- super(_WaitCancelFuture, self)._schedule_callbacks()
+ def set_result(self, result):
+ super().set_result(result)
+ if self._done_callback is not None:
+ self._done_callback(self)
+
+ def set_exception(self, exception):
+ super().set_exception(exception)
if self._done_callback is not None:
self._done_callback(self)
diff --git a/Lib/asyncio/windows_utils.py b/Lib/asyncio/windows_utils.py
index 870cd13..7c63fb9 100644
--- a/Lib/asyncio/windows_utils.py
+++ b/Lib/asyncio/windows_utils.py
@@ -159,7 +159,8 @@ class PipeHandle:
def __del__(self):
if self._handle is not None:
- warnings.warn("unclosed %r" % self, ResourceWarning)
+ warnings.warn("unclosed %r" % self, ResourceWarning,
+ source=self)
self.close()
def __enter__(self):
diff --git a/Lib/asyncore.py b/Lib/asyncore.py
index 3b51f0f..705e406 100644
--- a/Lib/asyncore.py
+++ b/Lib/asyncore.py
@@ -333,7 +333,7 @@ class dispatcher:
self.connecting = True
err = self.socket.connect_ex(address)
if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \
- or err == EINVAL and os.name in ('nt', 'ce'):
+ or err == EINVAL and os.name == 'nt':
self.addr = address
return
if err in (0, EISCONN):
@@ -595,7 +595,8 @@ if os.name == 'posix':
def __del__(self):
if self.fd >= 0:
- warnings.warn("unclosed file %r" % self, ResourceWarning)
+ warnings.warn("unclosed file %r" % self, ResourceWarning,
+ source=self)
self.close()
def recv(self, *args):
diff --git a/Lib/base64.py b/Lib/base64.py
index adaec1d..58f6ad6 100755
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -55,8 +55,7 @@ def b64encode(s, altchars=None):
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
"""
- # Strip off the trailing newline
- encoded = binascii.b2a_base64(s)[:-1]
+ encoded = binascii.b2a_base64(s, newline=False)
if altchars is not None:
assert len(altchars) == 2, repr(altchars)
return encoded.translate(bytes.maketrans(b'+/', altchars))
@@ -156,7 +155,7 @@ def b32encode(s):
leftover = len(s) % 5
# Pad the last quantum with zero bits if necessary
if leftover:
- s = s + bytes(5 - leftover) # Don't use += !
+ s = s + b'\0' * (5 - leftover) # Don't use += !
encoded = bytearray()
from_bytes = int.from_bytes
b32tab2 = _b32tab2
diff --git a/Lib/bz2.py b/Lib/bz2.py
index bc78c54..6f56328 100644
--- a/Lib/bz2.py
+++ b/Lib/bz2.py
@@ -11,6 +11,7 @@ __author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
from builtins import open as _builtin_open
import io
+import os
import warnings
import _compression
@@ -42,9 +43,9 @@ class BZ2File(_compression.BaseStream):
def __init__(self, filename, mode="r", buffering=None, compresslevel=9):
"""Open a bzip2-compressed file.
- If filename is a str or bytes object, it gives the name
- of the file to be opened. Otherwise, it should be a file object,
- which will be used to read or write the compressed data.
+ If filename is a str, bytes, or PathLike object, it gives the
+ name of the file to be opened. Otherwise, it should be a file
+ object, which will be used to read or write the compressed data.
mode can be 'r' for reading (default), 'w' for (over)writing,
'x' for creating exclusively, or 'a' for appending. These can
@@ -91,7 +92,7 @@ class BZ2File(_compression.BaseStream):
else:
raise ValueError("Invalid mode: %r" % (mode,))
- if isinstance(filename, (str, bytes)):
+ if isinstance(filename, (str, bytes, os.PathLike)):
self._fp = _builtin_open(filename, mode)
self._closefp = True
self._mode = mode_code
@@ -99,7 +100,7 @@ class BZ2File(_compression.BaseStream):
self._fp = filename
self._mode = mode_code
else:
- raise TypeError("filename must be a str or bytes object, or a file")
+ raise TypeError("filename must be a str, bytes, file or PathLike object")
if self._mode == _MODE_READ:
raw = _compression.DecompressReader(self._fp,
@@ -289,8 +290,9 @@ def open(filename, mode="rb", compresslevel=9,
encoding=None, errors=None, newline=None):
"""Open a bzip2-compressed file in binary or text mode.
- The filename argument can be an actual filename (a str or bytes
- object), or an existing file object to read from or write to.
+ The filename argument can be an actual filename (a str, bytes, or
+ PathLike object), or an existing file object to read from or write
+ to.
The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or
"ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode.
diff --git a/Lib/calendar.py b/Lib/calendar.py
index 76cf8de..07594f3 100644
--- a/Lib/calendar.py
+++ b/Lib/calendar.py
@@ -13,7 +13,9 @@ from itertools import repeat
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
"monthcalendar", "prmonth", "month", "prcal", "calendar",
- "timegm", "month_name", "month_abbr", "day_name", "day_abbr"]
+ "timegm", "month_name", "month_abbr", "day_name", "day_abbr",
+ "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar",
+ "LocaleHTMLCalendar", "weekheader"]
# Exception raised for bad input (with string parameter for details)
error = ValueError
@@ -604,51 +606,63 @@ def timegm(tuple):
def main(args):
- import optparse
- parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]")
- parser.add_option(
+ import argparse
+ parser = argparse.ArgumentParser()
+ textgroup = parser.add_argument_group('text only arguments')
+ htmlgroup = parser.add_argument_group('html only arguments')
+ textgroup.add_argument(
"-w", "--width",
- dest="width", type="int", default=2,
- help="width of date column (default 2, text only)"
+ type=int, default=2,
+ help="width of date column (default 2)"
)
- parser.add_option(
+ textgroup.add_argument(
"-l", "--lines",
- dest="lines", type="int", default=1,
- help="number of lines for each week (default 1, text only)"
+ type=int, default=1,
+ help="number of lines for each week (default 1)"
)
- parser.add_option(
+ textgroup.add_argument(
"-s", "--spacing",
- dest="spacing", type="int", default=6,
- help="spacing between months (default 6, text only)"
+ type=int, default=6,
+ help="spacing between months (default 6)"
)
- parser.add_option(
+ textgroup.add_argument(
"-m", "--months",
- dest="months", type="int", default=3,
- help="months per row (default 3, text only)"
+ type=int, default=3,
+ help="months per row (default 3)"
)
- parser.add_option(
+ htmlgroup.add_argument(
"-c", "--css",
- dest="css", default="calendar.css",
- help="CSS to use for page (html only)"
+ default="calendar.css",
+ help="CSS to use for page"
)
- parser.add_option(
+ parser.add_argument(
"-L", "--locale",
- dest="locale", default=None,
+ default=None,
help="locale to be used from month and weekday names"
)
- parser.add_option(
+ parser.add_argument(
"-e", "--encoding",
- dest="encoding", default=None,
- help="Encoding to use for output."
+ default=None,
+ help="encoding to use for output"
)
- parser.add_option(
+ parser.add_argument(
"-t", "--type",
- dest="type", default="text",
+ default="text",
choices=("text", "html"),
help="output type (text or html)"
)
+ parser.add_argument(
+ "year",
+ nargs='?', type=int,
+ help="year number (1-9999)"
+ )
+ parser.add_argument(
+ "month",
+ nargs='?', type=int,
+ help="month number (1-12, text only)"
+ )
- (options, args) = parser.parse_args(args)
+ options = parser.parse_args(args[1:])
if options.locale and not options.encoding:
parser.error("if --locale is specified --encoding is required")
@@ -666,10 +680,10 @@ def main(args):
encoding = sys.getdefaultencoding()
optdict = dict(encoding=encoding, css=options.css)
write = sys.stdout.buffer.write
- if len(args) == 1:
+ if options.year is None:
write(cal.formatyearpage(datetime.date.today().year, **optdict))
- elif len(args) == 2:
- write(cal.formatyearpage(int(args[1]), **optdict))
+ elif options.month is None:
+ write(cal.formatyearpage(options.year, **optdict))
else:
parser.error("incorrect number of arguments")
sys.exit(1)
@@ -679,18 +693,15 @@ def main(args):
else:
cal = TextCalendar()
optdict = dict(w=options.width, l=options.lines)
- if len(args) != 3:
+ if options.month is None:
optdict["c"] = options.spacing
optdict["m"] = options.months
- if len(args) == 1:
+ if options.year is None:
result = cal.formatyear(datetime.date.today().year, **optdict)
- elif len(args) == 2:
- result = cal.formatyear(int(args[1]), **optdict)
- elif len(args) == 3:
- result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
+ elif options.month is None:
+ result = cal.formatyear(options.year, **optdict)
else:
- parser.error("incorrect number of arguments")
- sys.exit(1)
+ result = cal.formatmonth(options.year, options.month, **optdict)
write = sys.stdout.write
if options.encoding:
result = result.encode(options.encoding)
diff --git a/Lib/cgi.py b/Lib/cgi.py
index 189c6d5..233a496 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -45,7 +45,7 @@ import tempfile
__all__ = ["MiniFieldStorage", "FieldStorage",
"parse", "parse_qs", "parse_qsl", "parse_multipart",
- "parse_header", "print_exception", "print_environ",
+ "parse_header", "test", "print_exception", "print_environ",
"print_form", "print_directory", "print_arguments",
"print_environ_usage", "escape"]
diff --git a/Lib/code.py b/Lib/code.py
index 53244e3..23295f4 100644
--- a/Lib/code.py
+++ b/Lib/code.py
@@ -186,7 +186,7 @@ class InteractiveConsole(InteractiveInterpreter):
"""Reset the input buffer."""
self.buffer = []
- def interact(self, banner=None):
+ def interact(self, banner=None, exitmsg=None):
"""Closely emulate the interactive Python console.
The optional banner argument specifies the banner to print
@@ -196,6 +196,11 @@ class InteractiveConsole(InteractiveInterpreter):
to confuse this with the real interpreter -- since it's so
close!).
+ The optional exitmsg argument specifies the exit message
+ printed when exiting. Pass the empty string to suppress
+ printing an exit message. If exitmsg is not given or None,
+ a default message is printed.
+
"""
try:
sys.ps1
@@ -230,6 +235,10 @@ class InteractiveConsole(InteractiveInterpreter):
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
+ if exitmsg is None:
+ self.write('now exiting %s...\n' % self.__class__.__name__)
+ elif exitmsg != '':
+ self.write('%s\n' % exitmsg)
def push(self, line):
"""Push a line to the interpreter.
@@ -267,7 +276,7 @@ class InteractiveConsole(InteractiveInterpreter):
-def interact(banner=None, readfunc=None, local=None):
+def interact(banner=None, readfunc=None, local=None, exitmsg=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
@@ -279,6 +288,7 @@ def interact(banner=None, readfunc=None, local=None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
+ exitmsg -- passed to InteractiveConsole.interact()
"""
console = InteractiveConsole(local)
@@ -289,7 +299,7 @@ def interact(banner=None, readfunc=None, local=None):
import readline
except ImportError:
pass
- console.interact(banner)
+ console.interact(banner, exitmsg)
if __name__ == "__main__":
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index bea811d..85b4c3c 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -356,7 +356,7 @@ _field_template = '''\
{name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
'''
-def namedtuple(typename, field_names, verbose=False, rename=False):
+def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
@@ -396,7 +396,7 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
field_names[index] = '_%d' % index
seen.add(name)
for name in [typename] + field_names:
- if type(name) != str:
+ if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
@@ -437,11 +437,15 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
- # defined for arguments greater than 0 (IronPython).
- try:
- result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
- except (AttributeError, ValueError):
- pass
+ # defined for arguments greater than 0 (IronPython), or where the user has
+ # specified a particular module.
+ if module is None:
+ try:
+ module = _sys._getframe(1).f_globals.get('__name__', '__main__')
+ except (AttributeError, ValueError):
+ pass
+ if module is not None:
+ result.__module__ = module
return result
@@ -845,7 +849,7 @@ class Counter(dict):
########################################################################
-### ChainMap (helper for configparser and string.Template)
+### ChainMap
########################################################################
class ChainMap(MutableMapping):
@@ -972,7 +976,7 @@ class UserDict(MutableMapping):
dict = kwargs.pop('dict')
import warnings
warnings.warn("Passing 'dict' as keyword argument is deprecated",
- PendingDeprecationWarning, stacklevel=2)
+ DeprecationWarning, stacklevel=2)
else:
dict = None
self.data = {}
diff --git a/Lib/collections/__main__.py b/Lib/collections/__main__.py
deleted file mode 100644
index 763e38e..0000000
--- a/Lib/collections/__main__.py
+++ /dev/null
@@ -1,38 +0,0 @@
-################################################################################
-### Simple tests
-################################################################################
-
-# verify that instances can be pickled
-from collections import namedtuple
-from pickle import loads, dumps
-Point = namedtuple('Point', 'x, y', True)
-p = Point(x=10, y=20)
-assert p == loads(dumps(p))
-
-# test and demonstrate ability to override methods
-class Point(namedtuple('Point', 'x y')):
- __slots__ = ()
- @property
- def hypot(self):
- return (self.x ** 2 + self.y ** 2) ** 0.5
- def __str__(self):
- return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
-
-for p in Point(3, 4), Point(14, 5/7.):
- print (p)
-
-class Point(namedtuple('Point', 'x y')):
- 'Point class with optimized _make() and _replace() without error-checking'
- __slots__ = ()
- _make = classmethod(tuple.__new__)
- def _replace(self, _map=map, **kwds):
- return self._make(_map(kwds.get, ('x', 'y'), self))
-
-print(Point(11, 22)._replace(x=100))
-
-Point3D = namedtuple('Point3D', Point._fields + ('z',))
-print(Point3D.__doc__)
-
-import doctest, collections
-TestResults = namedtuple('TestResults', 'failed attempted')
-print(TestResults(*doctest.testmod(collections)))
diff --git a/Lib/compileall.py b/Lib/compileall.py
index 2d4c523..1c9ceb6 100644
--- a/Lib/compileall.py
+++ b/Lib/compileall.py
@@ -25,6 +25,8 @@ from functools import partial
__all__ = ["compile_dir","compile_file","compile_path"]
def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
+ if quiet < 2 and isinstance(dir, os.PathLike):
+ dir = os.fspath(dir)
if not quiet:
print('Listing {!r}...'.format(dir))
try:
@@ -71,7 +73,7 @@ def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
ddir=ddir)
- success = 1
+ success = True
if workers is not None and workers != 1 and ProcessPoolExecutor is not None:
workers = workers or None
with ProcessPoolExecutor(max_workers=workers) as executor:
@@ -81,12 +83,12 @@ def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
legacy=legacy,
optimize=optimize),
files)
- success = min(results, default=1)
+ success = min(results, default=True)
else:
for file in files:
if not compile_file(file, ddir, force, rx, quiet,
legacy, optimize):
- success = 0
+ success = False
return success
def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
@@ -104,7 +106,9 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
optimize: optimization level or -1 for level of the interpreter
"""
- success = 1
+ success = True
+ if quiet < 2 and isinstance(fullname, os.PathLike):
+ fullname = os.fspath(fullname)
name = os.path.basename(fullname)
if ddir is not None:
dfile = os.path.join(ddir, name)
@@ -144,7 +148,7 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
ok = py_compile.compile(fullname, cfile, dfile, True,
optimize=optimize)
except py_compile.PyCompileError as err:
- success = 0
+ success = False
if quiet >= 2:
return success
elif quiet:
@@ -157,7 +161,7 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
msg = msg.decode(sys.stdout.encoding)
print(msg)
except (SyntaxError, UnicodeError, OSError) as e:
- success = 0
+ success = False
if quiet >= 2:
return success
elif quiet:
@@ -167,7 +171,7 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
print(e.__class__.__name__ + ':', e)
else:
if ok == 0:
- success = 0
+ success = False
return success
def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
@@ -183,7 +187,7 @@ def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
legacy: as for compile_dir() (default False)
optimize: as for compile_dir() (default -1)
"""
- success = 1
+ success = True
for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir:
if quiet < 2:
diff --git a/Lib/concurrent/futures/thread.py b/Lib/concurrent/futures/thread.py
index 9c3aec9..03d276b 100644
--- a/Lib/concurrent/futures/thread.py
+++ b/Lib/concurrent/futures/thread.py
@@ -81,12 +81,13 @@ def _worker(executor_reference, work_queue):
_base.LOGGER.critical('Exception in worker', exc_info=True)
class ThreadPoolExecutor(_base.Executor):
- def __init__(self, max_workers=None):
+ def __init__(self, max_workers=None, thread_name_prefix=''):
"""Initializes a new ThreadPoolExecutor instance.
Args:
max_workers: The maximum number of threads that can be used to
execute the given calls.
+ thread_name_prefix: An optional name prefix to give our threads.
"""
if max_workers is None:
# Use this number because ThreadPoolExecutor is often
@@ -100,6 +101,7 @@ class ThreadPoolExecutor(_base.Executor):
self._threads = set()
self._shutdown = False
self._shutdown_lock = threading.Lock()
+ self._thread_name_prefix = thread_name_prefix
def submit(self, fn, *args, **kwargs):
with self._shutdown_lock:
@@ -121,8 +123,11 @@ class ThreadPoolExecutor(_base.Executor):
q.put(None)
# TODO(bquinlan): Should avoid creating new threads if there are more
# idle threads than items in the work queue.
- if len(self._threads) < self._max_workers:
- t = threading.Thread(target=_worker,
+ num_threads = len(self._threads)
+ if num_threads < self._max_workers:
+ thread_name = '%s_%d' % (self._thread_name_prefix or self,
+ num_threads)
+ t = threading.Thread(name=thread_name, target=_worker,
args=(weakref.ref(self, weakref_cb),
self._work_queue))
t.daemon = True
diff --git a/Lib/contextlib.py b/Lib/contextlib.py
index d44edd6..7d94a57 100644
--- a/Lib/contextlib.py
+++ b/Lib/contextlib.py
@@ -1,11 +1,34 @@
"""Utilities for with-statement contexts. See PEP 343."""
-
+import abc
import sys
from collections import deque
from functools import wraps
-__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack",
- "redirect_stdout", "redirect_stderr", "suppress"]
+__all__ = ["contextmanager", "closing", "AbstractContextManager",
+ "ContextDecorator", "ExitStack", "redirect_stdout",
+ "redirect_stderr", "suppress"]
+
+
+class AbstractContextManager(abc.ABC):
+
+ """An abstract base class for context managers."""
+
+ def __enter__(self):
+ """Return `self` upon entering the runtime context."""
+ return self
+
+ @abc.abstractmethod
+ def __exit__(self, exc_type, exc_value, traceback):
+ """Raise any exception triggered within the runtime context."""
+ return None
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is AbstractContextManager:
+ if (any("__enter__" in B.__dict__ for B in C.__mro__) and
+ any("__exit__" in B.__dict__ for B in C.__mro__)):
+ return True
+ return NotImplemented
class ContextDecorator(object):
@@ -31,7 +54,7 @@ class ContextDecorator(object):
return inner
-class _GeneratorContextManager(ContextDecorator):
+class _GeneratorContextManager(ContextDecorator, AbstractContextManager):
"""Helper for @contextmanager decorator."""
def __init__(self, func, args, kwds):
@@ -137,7 +160,7 @@ def contextmanager(func):
return helper
-class closing(object):
+class closing(AbstractContextManager):
"""Context to automatically close something at the end of a block.
Code like this:
@@ -162,7 +185,7 @@ class closing(object):
self.thing.close()
-class _RedirectStream:
+class _RedirectStream(AbstractContextManager):
_stream = None
@@ -202,7 +225,7 @@ class redirect_stderr(_RedirectStream):
_stream = "stderr"
-class suppress:
+class suppress(AbstractContextManager):
"""Context manager to suppress specified exceptions
After the exception is suppressed, execution proceeds with the next
@@ -233,7 +256,7 @@ class suppress:
# Inspired by discussions on http://bugs.python.org/issue13585
-class ExitStack(object):
+class ExitStack(AbstractContextManager):
"""Context manager for dynamic management of a stack of exit callbacks
For example:
@@ -312,9 +335,6 @@ class ExitStack(object):
"""Immediately unwind the context stack"""
self.__exit__(None, None, None)
- def __enter__(self):
- return self
-
def __exit__(self, *exc_details):
received_exc = exc_details[0] is not None
diff --git a/Lib/copy.py b/Lib/copy.py
index 972b94a..f86040a 100644
--- a/Lib/copy.py
+++ b/Lib/copy.py
@@ -51,7 +51,6 @@ __getstate__() and __setstate__(). See the documentation for module
import types
import weakref
from copyreg import dispatch_table
-import builtins
class Error(Exception):
pass
@@ -102,37 +101,33 @@ def copy(x):
else:
raise Error("un(shallow)copyable object of type %s" % cls)
- return _reconstruct(x, rv, 0)
+ if isinstance(rv, str):
+ return x
+ return _reconstruct(x, None, *rv)
_copy_dispatch = d = {}
def _copy_immutable(x):
return x
-for t in (type(None), int, float, bool, str, tuple,
- bytes, frozenset, type, range,
- types.BuiltinFunctionType, type(Ellipsis),
+for t in (type(None), int, float, bool, complex, str, tuple,
+ bytes, frozenset, type, range, slice,
+ types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
t = getattr(types, "CodeType", None)
if t is not None:
d[t] = _copy_immutable
-for name in ("complex", "unicode"):
- t = getattr(builtins, name, None)
- if t is not None:
- d[t] = _copy_immutable
-
-def _copy_with_constructor(x):
- return type(x)(x)
-for t in (list, dict, set):
- d[t] = _copy_with_constructor
-
-def _copy_with_copy_method(x):
- return x.copy()
+
+d[list] = list.copy
+d[dict] = dict.copy
+d[set] = set.copy
+d[bytearray] = bytearray.copy
+
if PyStringMap is not None:
- d[PyStringMap] = _copy_with_copy_method
+ d[PyStringMap] = PyStringMap.copy
-del d
+del d, t
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
@@ -179,7 +174,10 @@ def deepcopy(x, memo=None, _nil=[]):
else:
raise Error(
"un(deep)copyable object of type %s" % cls)
- y = _reconstruct(x, rv, 1, memo)
+ if isinstance(rv, str):
+ y = x
+ else:
+ y = _reconstruct(x, memo, *rv)
# If is its own copy, don't memoize.
if y is not x:
@@ -193,13 +191,11 @@ def _deepcopy_atomic(x, memo):
return x
d[type(None)] = _deepcopy_atomic
d[type(Ellipsis)] = _deepcopy_atomic
+d[type(NotImplemented)] = _deepcopy_atomic
d[int] = _deepcopy_atomic
d[float] = _deepcopy_atomic
d[bool] = _deepcopy_atomic
-try:
- d[complex] = _deepcopy_atomic
-except NameError:
- pass
+d[complex] = _deepcopy_atomic
d[bytes] = _deepcopy_atomic
d[str] = _deepcopy_atomic
try:
@@ -211,15 +207,16 @@ d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic
d[weakref.ref] = _deepcopy_atomic
-def _deepcopy_list(x, memo):
+def _deepcopy_list(x, memo, deepcopy=deepcopy):
y = []
memo[id(x)] = y
+ append = y.append
for a in x:
- y.append(deepcopy(a, memo))
+ append(deepcopy(a, memo))
return y
d[list] = _deepcopy_list
-def _deepcopy_tuple(x, memo):
+def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
y = [deepcopy(a, memo) for a in x]
# We're not going to put the tuple in the memo, but it's still important we
# check for it, in case the tuple contains recursive mutable structures.
@@ -236,7 +233,7 @@ def _deepcopy_tuple(x, memo):
return y
d[tuple] = _deepcopy_tuple
-def _deepcopy_dict(x, memo):
+def _deepcopy_dict(x, memo, deepcopy=deepcopy):
y = {}
memo[id(x)] = y
for key, value in x.items():
@@ -248,7 +245,9 @@ if PyStringMap is not None:
def _deepcopy_method(x, memo): # Copy instance methods
return type(x)(x.__func__, deepcopy(x.__self__, memo))
-_deepcopy_dispatch[types.MethodType] = _deepcopy_method
+d[types.MethodType] = _deepcopy_method
+
+del d
def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
@@ -266,31 +265,15 @@ def _keep_alive(x, memo):
# aha, this is the first one :-)
memo[id(memo)]=[x]
-def _reconstruct(x, info, deep, memo=None):
- if isinstance(info, str):
- return x
- assert isinstance(info, tuple)
- if memo is None:
- memo = {}
- n = len(info)
- assert n in (2, 3, 4, 5)
- callable, args = info[:2]
- if n > 2:
- state = info[2]
- else:
- state = None
- if n > 3:
- listiter = info[3]
- else:
- listiter = None
- if n > 4:
- dictiter = info[4]
- else:
- dictiter = None
+def _reconstruct(x, memo, func, args,
+ state=None, listiter=None, dictiter=None,
+ deepcopy=deepcopy):
+ deep = memo is not None
+ if deep and args:
+ args = (deepcopy(arg, memo) for arg in args)
+ y = func(*args)
if deep:
- args = deepcopy(args, memo)
- y = callable(*args)
- memo[id(x)] = y
+ memo[id(x)] = y
if state is not None:
if deep:
@@ -309,22 +292,22 @@ def _reconstruct(x, info, deep, memo=None):
setattr(y, key, value)
if listiter is not None:
- for item in listiter:
- if deep:
+ if deep:
+ for item in listiter:
item = deepcopy(item, memo)
- y.append(item)
+ y.append(item)
+ else:
+ for item in listiter:
+ y.append(item)
if dictiter is not None:
- for key, value in dictiter:
- if deep:
+ if deep:
+ for key, value in dictiter:
key = deepcopy(key, memo)
value = deepcopy(value, memo)
- y[key] = value
+ y[key] = value
+ else:
+ for key, value in dictiter:
+ y[key] = value
return y
-del d
-
-del types
-
-# Helper for instance creation without calling __init__
-class _EmptyClass:
- pass
+del types, weakref, PyStringMap
diff --git a/Lib/crypt.py b/Lib/crypt.py
index 49ab96e..fbc5f4c 100644
--- a/Lib/crypt.py
+++ b/Lib/crypt.py
@@ -54,9 +54,8 @@ METHOD_SHA256 = _Method('SHA256', '5', 16, 63)
METHOD_SHA512 = _Method('SHA512', '6', 16, 106)
methods = []
-for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5):
+for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5, METHOD_CRYPT):
_result = crypt('', _method)
if _result and len(_result) == _method.total_size:
methods.append(_method)
-methods.append(METHOD_CRYPT)
del _result, _method
diff --git a/Lib/csv.py b/Lib/csv.py
index ca40e5e..0349e0b 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -11,13 +11,15 @@ from _csv import Error, __version__, writer, reader, register_dialect, \
__doc__
from _csv import Dialect as _Dialect
+from collections import OrderedDict
from io import StringIO
-__all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
- "Error", "Dialect", "__doc__", "excel", "excel_tab",
- "field_size_limit", "reader", "writer",
- "register_dialect", "get_dialect", "list_dialects", "Sniffer",
- "unregister_dialect", "__version__", "DictReader", "DictWriter" ]
+__all__ = ["QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
+ "Error", "Dialect", "__doc__", "excel", "excel_tab",
+ "field_size_limit", "reader", "writer",
+ "register_dialect", "get_dialect", "list_dialects", "Sniffer",
+ "unregister_dialect", "__version__", "DictReader", "DictWriter",
+ "unix_dialect"]
class Dialect:
"""Describe a CSV dialect.
@@ -115,7 +117,7 @@ class DictReader:
# values
while row == []:
row = next(self.reader)
- d = dict(zip(self.fieldnames, row))
+ d = OrderedDict(zip(self.fieldnames, row))
lf = len(self.fieldnames)
lr = len(row)
if lf < lr:
@@ -143,7 +145,7 @@ class DictWriter:
def _dict_to_list(self, rowdict):
if self.extrasaction == "raise":
- wrong_fields = [k for k in rowdict if k not in self.fieldnames]
+ wrong_fields = rowdict.keys() - self.fieldnames
if wrong_fields:
raise ValueError("dict contains fields not in fieldnames: "
+ ", ".join([repr(x) for x in wrong_fields]))
@@ -213,10 +215,10 @@ class Sniffer:
"""
matches = []
- for restr in ('(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
- '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
- '(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
- '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space)
+ for restr in (r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
+ r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
+ r'(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
+ r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space)
regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
matches = regexp.findall(data)
if matches:
diff --git a/Lib/ctypes/__init__.py b/Lib/ctypes/__init__.py
index 0d86078..1c9d3a5 100644
--- a/Lib/ctypes/__init__.py
+++ b/Lib/ctypes/__init__.py
@@ -16,7 +16,7 @@ from struct import calcsize as _calcsize
if __version__ != _ctypes_version:
raise Exception("Version number mismatch", __version__, _ctypes_version)
-if _os.name in ("nt", "ce"):
+if _os.name == "nt":
from _ctypes import FormatError
DEFAULT_MODE = RTLD_LOCAL
@@ -103,12 +103,9 @@ def CFUNCTYPE(restype, *argtypes, **kw):
_c_functype_cache[(restype, argtypes, flags)] = CFunctionType
return CFunctionType
-if _os.name in ("nt", "ce"):
+if _os.name == "nt":
from _ctypes import LoadLibrary as _dlopen
from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
- if _os.name == "ce":
- # 'ce' doesn't have the stdcall calling convention
- _FUNCFLAG_STDCALL = _FUNCFLAG_CDECL
_win_functype_cache = {}
def WINFUNCTYPE(restype, *argtypes, **kw):
@@ -262,7 +259,7 @@ class c_wchar(_SimpleCData):
def _reset_cache():
_pointer_type_cache.clear()
_c_functype_cache.clear()
- if _os.name in ("nt", "ce"):
+ if _os.name == "nt":
_win_functype_cache.clear()
# _SimpleCData.c_wchar_p_from_param
POINTER(c_wchar).from_param = c_wchar_p.from_param
@@ -374,7 +371,7 @@ class PyDLL(CDLL):
"""
_func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
-if _os.name in ("nt", "ce"):
+if _os.name == "nt":
class WinDLL(CDLL):
"""This class represents a dll exporting functions using the
@@ -427,7 +424,7 @@ class LibraryLoader(object):
cdll = LibraryLoader(CDLL)
pydll = LibraryLoader(PyDLL)
-if _os.name in ("nt", "ce"):
+if _os.name == "nt":
pythonapi = PyDLL("python dll", None, _sys.dllhandle)
elif _sys.platform == "cygwin":
pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
@@ -435,7 +432,7 @@ else:
pythonapi = PyDLL(None)
-if _os.name in ("nt", "ce"):
+if _os.name == "nt":
windll = LibraryLoader(WinDLL)
oledll = LibraryLoader(OleDLL)
@@ -503,7 +500,7 @@ else:
return _wstring_at(ptr, size)
-if _os.name in ("nt", "ce"): # COM stuff
+if _os.name == "nt": # COM stuff
def DllGetClassObject(rclsid, riid, ppv):
try:
ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py
index b39d82c..c71d71d 100644
--- a/Lib/ctypes/test/test_bitfields.py
+++ b/Lib/ctypes/test/test_bitfields.py
@@ -3,7 +3,6 @@ from ctypes.test import need_symbol
import unittest
import os
-import ctypes
import _ctypes_test
class BITS(Structure):
@@ -197,7 +196,7 @@ class BitFieldTest(unittest.TestCase):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_int, 4)]
- if os.name in ("nt", "ce"):
+ if os.name == "nt":
self.assertEqual(sizeof(X), sizeof(c_int)*2)
else:
self.assertEqual(sizeof(X), sizeof(c_int))
@@ -225,7 +224,7 @@ class BitFieldTest(unittest.TestCase):
# MSVC does NOT combine c_short and c_int into one field, GCC
# does (unless GCC is run with '-mms-bitfields' which
# produces code compatible with MSVC).
- if os.name in ("nt", "ce"):
+ if os.name == "nt":
self.assertEqual(sizeof(X), sizeof(c_int) * 4)
else:
self.assertEqual(sizeof(X), sizeof(c_int) * 2)
diff --git a/Lib/ctypes/test/test_find.py b/Lib/ctypes/test/test_find.py
index 94b0b89..b99fdcb 100644
--- a/Lib/ctypes/test/test_find.py
+++ b/Lib/ctypes/test/test_find.py
@@ -69,5 +69,48 @@ class Test_OpenGL_libs(unittest.TestCase):
self.assertFalse(os.path.lexists(test.support.TESTFN))
self.assertIsNone(result)
+
+@unittest.skipUnless(sys.platform.startswith('linux'),
+ 'Test only valid for Linux')
+class LibPathFindTest(unittest.TestCase):
+ def test_find_on_libpath(self):
+ import subprocess
+ import tempfile
+
+ try:
+ p = subprocess.Popen(['gcc', '--version'], stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL)
+ out, _ = p.communicate()
+ except OSError:
+ raise unittest.SkipTest('gcc, needed for test, not available')
+ with tempfile.TemporaryDirectory() as d:
+ # create an empty temporary file
+ srcname = os.path.join(d, 'dummy.c')
+ libname = 'py_ctypes_test_dummy'
+ dstname = os.path.join(d, 'lib%s.so' % libname)
+ with open(srcname, 'w') as f:
+ pass
+ self.assertTrue(os.path.exists(srcname))
+ # compile the file to a shared library
+ cmd = ['gcc', '-o', dstname, '--shared',
+ '-Wl,-soname,lib%s.so' % libname, srcname]
+ out = subprocess.check_output(cmd)
+ self.assertTrue(os.path.exists(dstname))
+ # now check that the .so can't be found (since not in
+ # LD_LIBRARY_PATH)
+ self.assertIsNone(find_library(libname))
+ # now add the location to LD_LIBRARY_PATH
+ with test.support.EnvironmentVarGuard() as env:
+ KEY = 'LD_LIBRARY_PATH'
+ if KEY not in env:
+ v = d
+ else:
+ v = '%s:%s' % (env[KEY], d)
+ env.set(KEY, v)
+ # now check that the .so can be found (since in
+ # LD_LIBRARY_PATH)
+ self.assertEqual(find_library(libname), 'lib%s.so' % libname)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/ctypes/test/test_funcptr.py b/Lib/ctypes/test/test_funcptr.py
index ff25c8f..f34734b 100644
--- a/Lib/ctypes/test/test_funcptr.py
+++ b/Lib/ctypes/test/test_funcptr.py
@@ -1,4 +1,4 @@
-import os, unittest
+import unittest
from ctypes import *
try:
@@ -39,7 +39,7 @@ class CFuncPtrTestCase(unittest.TestCase):
# possible, as in C, to call cdecl functions with more parameters.
#self.assertRaises(TypeError, c, 1, 2, 3)
self.assertEqual(c(1, 2, 3, 4, 5, 6), 3)
- if not WINFUNCTYPE is CFUNCTYPE and os.name != "ce":
+ if not WINFUNCTYPE is CFUNCTYPE:
self.assertRaises(TypeError, s, 1, 2, 3)
def test_structures(self):
diff --git a/Lib/ctypes/test/test_loading.py b/Lib/ctypes/test/test_loading.py
index 28468c1..45571f3 100644
--- a/Lib/ctypes/test/test_loading.py
+++ b/Lib/ctypes/test/test_loading.py
@@ -11,8 +11,6 @@ def setUpModule():
global libc_name
if os.name == "nt":
libc_name = find_library("c")
- elif os.name == "ce":
- libc_name = "coredll"
elif sys.platform == "cygwin":
libc_name = "cygwin1.dll"
else:
@@ -49,8 +47,8 @@ class LoaderTest(unittest.TestCase):
cdll.LoadLibrary(lib)
CDLL(lib)
- @unittest.skipUnless(os.name in ("nt", "ce"),
- 'test specific to Windows (NT/CE)')
+ @unittest.skipUnless(os.name == "nt",
+ 'test specific to Windows')
def test_load_library(self):
# CRT is no longer directly loadable. See issue23606 for the
# discussion about alternative approaches.
@@ -64,14 +62,9 @@ class LoaderTest(unittest.TestCase):
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
- elif os.name == "ce":
- windll.coredll.GetModuleHandleW
- windll["coredll"].GetModuleHandleW
- windll.LoadLibrary("coredll").GetModuleHandleW
- WinDLL("coredll").GetModuleHandleW
-
- @unittest.skipUnless(os.name in ("nt", "ce"),
- 'test specific to Windows (NT/CE)')
+
+ @unittest.skipUnless(os.name == "nt",
+ 'test specific to Windows')
def test_load_ordinal_functions(self):
import _ctypes_test
dll = WinDLL(_ctypes_test.__file__)
diff --git a/Lib/ctypes/test/test_objects.py b/Lib/ctypes/test/test_objects.py
index ef7b20b..19e3dc1 100644
--- a/Lib/ctypes/test/test_objects.py
+++ b/Lib/ctypes/test/test_objects.py
@@ -54,7 +54,7 @@ of 'x' ('_b_base_' is either None, or the root object owning the memory block):
'''
-import unittest, doctest, sys
+import unittest, doctest
import ctypes.test.test_objects
diff --git a/Lib/ctypes/test/test_parameters.py b/Lib/ctypes/test/test_parameters.py
index e56bccf..363f586 100644
--- a/Lib/ctypes/test/test_parameters.py
+++ b/Lib/ctypes/test/test_parameters.py
@@ -1,4 +1,4 @@
-import unittest, sys
+import unittest
from ctypes.test import need_symbol
class SimpleTypesTestCase(unittest.TestCase):
@@ -49,7 +49,7 @@ class SimpleTypesTestCase(unittest.TestCase):
# XXX Replace by c_char_p tests
def test_cstrings(self):
- from ctypes import c_char_p, byref
+ from ctypes import c_char_p
# c_char_p.from_param on a Python String packs the string
# into a cparam object
@@ -68,7 +68,7 @@ class SimpleTypesTestCase(unittest.TestCase):
@need_symbol('c_wchar_p')
def test_cw_strings(self):
- from ctypes import byref, c_wchar_p
+ from ctypes import c_wchar_p
c_wchar_p.from_param("123")
@@ -98,7 +98,7 @@ class SimpleTypesTestCase(unittest.TestCase):
def test_byref_pointer(self):
# The from_param class method of POINTER(typ) classes accepts what is
# returned by byref(obj), it type(obj) == typ
- from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
+ from ctypes import c_short, c_uint, c_int, c_long, POINTER, byref
LPINT = POINTER(c_int)
LPINT.from_param(byref(c_int(42)))
diff --git a/Lib/ctypes/test/test_pep3118.py b/Lib/ctypes/test/test_pep3118.py
index 32f802c..d68397e 100644
--- a/Lib/ctypes/test/test_pep3118.py
+++ b/Lib/ctypes/test/test_pep3118.py
@@ -1,6 +1,6 @@
import unittest
from ctypes import *
-import re, struct, sys
+import re, sys
if sys.byteorder == "little":
THIS_ENDIAN = "<"
diff --git a/Lib/ctypes/test/test_returnfuncptrs.py b/Lib/ctypes/test/test_returnfuncptrs.py
index 93eba6b..1974f40 100644
--- a/Lib/ctypes/test/test_returnfuncptrs.py
+++ b/Lib/ctypes/test/test_returnfuncptrs.py
@@ -1,6 +1,5 @@
import unittest
from ctypes import *
-import os
import _ctypes_test
diff --git a/Lib/ctypes/test/test_sizes.py b/Lib/ctypes/test/test_sizes.py
index f9b5e97..4ceacbc 100644
--- a/Lib/ctypes/test/test_sizes.py
+++ b/Lib/ctypes/test/test_sizes.py
@@ -2,7 +2,6 @@
from ctypes import *
-import sys
import unittest
diff --git a/Lib/ctypes/test/test_structures.py b/Lib/ctypes/test/test_structures.py
index c4a651c..8f6fe5f 100644
--- a/Lib/ctypes/test/test_structures.py
+++ b/Lib/ctypes/test/test_structures.py
@@ -326,11 +326,8 @@ class StructureTestCase(unittest.TestCase):
cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
self.assertEqual(cls, RuntimeError)
- if issubclass(Exception, object):
- self.assertEqual(msg,
- "(Phone) <class 'TypeError'>: too many initializers")
- else:
- self.assertEqual(msg, "(Phone) TypeError: too many initializers")
+ self.assertEqual(msg,
+ "(Phone) <class 'TypeError'>: too many initializers")
def test_huge_field_name(self):
# issue12881: segfault with large structure field names
diff --git a/Lib/ctypes/test/test_values.py b/Lib/ctypes/test/test_values.py
index 5a3a47f..e71b480 100644
--- a/Lib/ctypes/test/test_values.py
+++ b/Lib/ctypes/test/test_values.py
@@ -79,9 +79,9 @@ class PythonValuesTestCase(unittest.TestCase):
continue
items.append((entry.name.decode("ascii"), entry.size))
- expected = [("__hello__", 161),
- ("__phello__", -161),
- ("__phello__.spam", 161),
+ expected = [("__hello__", 139),
+ ("__phello__", -139),
+ ("__phello__.spam", 139),
]
self.assertEqual(items, expected, "PyImport_FrozenModules example "
"in Doc/library/ctypes.rst may be out of date")
diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py
index 7684eab..339ae8a 100644
--- a/Lib/ctypes/util.py
+++ b/Lib/ctypes/util.py
@@ -67,16 +67,6 @@ if os.name == "nt":
return fname
return None
-if os.name == "ce":
- # search path according to MSDN:
- # - absolute path specified by filename
- # - The .exe launch directory
- # - the Windows directory
- # - ROM dll files (where are they?)
- # - OEM specified search path: HKLM\Loader\SystemPath
- def find_library(name):
- return name
-
if os.name == "posix" and sys.platform == "darwin":
from ctypes.macholib.dyld import dyld_find as _dyld_find
def find_library(name):
@@ -271,8 +261,8 @@ elif os.name == "posix":
abi_type = mach_map.get(machine, 'libc6')
# XXX assuming GLIBC's ldconfig (with option -p)
- regex = os.fsencode(
- '\s+(lib%s\.[^\s]+)\s+\(%s' % (re.escape(name), abi_type))
+ regex = r'\s+(lib%s\.[^\s]+)\s+\(%s'
+ regex = os.fsencode(regex % (re.escape(name), abi_type))
try:
with subprocess.Popen(['/sbin/ldconfig', '-p'],
stdin=subprocess.DEVNULL,
@@ -285,8 +275,32 @@ elif os.name == "posix":
except OSError:
pass
+ def _findLib_ld(name):
+ # See issue #9998 for why this is needed
+ expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
+ cmd = ['ld', '-t']
+ libpath = os.environ.get('LD_LIBRARY_PATH')
+ if libpath:
+ for d in libpath.split(':'):
+ cmd.extend(['-L', d])
+ cmd.extend(['-o', os.devnull, '-l%s' % name])
+ result = None
+ try:
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True)
+ out, _ = p.communicate()
+ res = re.search(expr, os.fsdecode(out))
+ if res:
+ result = res.group(0)
+ except Exception as e:
+ pass # result will be None
+ return result
+
def find_library(name):
- return _findSoname_ldconfig(name) or _get_soname(_findLib_gcc(name))
+ # See issue #9998
+ return _findSoname_ldconfig(name) or \
+ _get_soname(_findLib_gcc(name) or _findLib_ld(name))
################################################################
# test code
diff --git a/Lib/datetime.py b/Lib/datetime.py
index a2178c7..7540109 100644
--- a/Lib/datetime.py
+++ b/Lib/datetime.py
@@ -152,12 +152,26 @@ def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
dnum = _days_before_month(y, m) + d
return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
-def _format_time(hh, mm, ss, us):
- # Skip trailing microseconds when us==0.
- result = "%02d:%02d:%02d" % (hh, mm, ss)
- if us:
- result += ".%06d" % us
- return result
+def _format_time(hh, mm, ss, us, timespec='auto'):
+ specs = {
+ 'hours': '{:02d}',
+ 'minutes': '{:02d}:{:02d}',
+ 'seconds': '{:02d}:{:02d}:{:02d}',
+ 'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}',
+ 'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
+ }
+
+ if timespec == 'auto':
+ # Skip trailing microseconds when us==0.
+ timespec = 'microseconds' if us else 'seconds'
+ elif timespec == 'milliseconds':
+ us //= 1000
+ try:
+ fmt = specs[timespec]
+ except KeyError:
+ raise ValueError('Unknown timespec value')
+ else:
+ return fmt.format(hh, mm, ss, us)
# Correctly substitute for %z and %Z escapes in strftime formats.
def _wrap_strftime(object, format, timetuple):
@@ -236,11 +250,11 @@ def _check_utc_offset(name, offset):
if not isinstance(offset, timedelta):
raise TypeError("tzinfo.%s() must return None "
"or timedelta, not '%s'" % (name, type(offset)))
- if offset % timedelta(minutes=1) or offset.microseconds:
+ if offset.microseconds:
raise ValueError("tzinfo.%s() must return a whole number "
- "of minutes, got %s" % (name, offset))
+ "of seconds, got %s" % (name, offset))
if not -timedelta(1) < offset < timedelta(1):
- raise ValueError("%s()=%s, must be must be strictly between "
+ raise ValueError("%s()=%s, must be strictly between "
"-timedelta(hours=24) and timedelta(hours=24)" %
(name, offset))
@@ -274,7 +288,7 @@ def _check_date_fields(year, month, day):
raise ValueError('day must be in 1..%d' % dim, day)
return year, month, day
-def _check_time_fields(hour, minute, second, microsecond):
+def _check_time_fields(hour, minute, second, microsecond, fold):
hour = _check_int_field(hour)
minute = _check_int_field(minute)
second = _check_int_field(second)
@@ -287,7 +301,9 @@ def _check_time_fields(hour, minute, second, microsecond):
raise ValueError('second must be in 0..59', second)
if not 0 <= microsecond <= 999999:
raise ValueError('microsecond must be in 0..999999', microsecond)
- return hour, minute, second, microsecond
+ if fold not in (0, 1):
+ raise ValueError('fold must be either 0 or 1', fold)
+ return hour, minute, second, microsecond, fold
def _check_tzinfo_arg(tz):
if tz is not None and not isinstance(tz, tzinfo):
@@ -316,6 +332,7 @@ def _divide_and_round(a, b):
return q
+
class timedelta:
"""Represent the difference between two datetime objects.
@@ -932,6 +949,7 @@ date.min = date(1, 1, 1)
date.max = date(9999, 12, 31)
date.resolution = timedelta(days=1)
+
class tzinfo:
"""Abstract base class for time zone info classes.
@@ -1023,11 +1041,11 @@ class time:
dst()
Properties (readonly):
- hour, minute, second, microsecond, tzinfo
+ hour, minute, second, microsecond, tzinfo, fold
"""
- __slots__ = '_hour', '_minute', '_second', '_microsecond', '_tzinfo', '_hashcode'
+ __slots__ = '_hour', '_minute', '_second', '_microsecond', '_tzinfo', '_hashcode', '_fold'
- def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
+ def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0):
"""Constructor.
Arguments:
@@ -1035,15 +1053,16 @@ class time:
hour, minute (required)
second, microsecond (default to zero)
tzinfo (default to None)
+ fold (keyword only, default to True)
"""
- if isinstance(hour, bytes) and len(hour) == 6 and hour[0] < 24:
+ if isinstance(hour, bytes) and len(hour) == 6 and hour[0]&0x7F < 24:
# Pickle support
self = object.__new__(cls)
self.__setstate(hour, minute or None)
self._hashcode = -1
return self
- hour, minute, second, microsecond = _check_time_fields(
- hour, minute, second, microsecond)
+ hour, minute, second, microsecond, fold = _check_time_fields(
+ hour, minute, second, microsecond, fold)
_check_tzinfo_arg(tzinfo)
self = object.__new__(cls)
self._hour = hour
@@ -1052,6 +1071,7 @@ class time:
self._microsecond = microsecond
self._tzinfo = tzinfo
self._hashcode = -1
+ self._fold = fold
return self
# Read-only field accessors
@@ -1080,6 +1100,10 @@ class time:
"""timezone info object"""
return self._tzinfo
+ @property
+ def fold(self):
+ return self._fold
+
# Standard conversions, __hash__ (and helpers)
# Comparisons of time objects with other.
@@ -1145,9 +1169,13 @@ class time:
def __hash__(self):
"""Hash."""
if self._hashcode == -1:
- tzoff = self.utcoffset()
+ if self.fold:
+ t = self.replace(fold=0)
+ else:
+ t = self
+ tzoff = t.utcoffset()
if not tzoff: # zero or None
- self._hashcode = hash(self._getstate()[0])
+ self._hashcode = hash(t._getstate()[0])
else:
h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff,
timedelta(hours=1))
@@ -1171,10 +1199,11 @@ class time:
else:
sign = "+"
hh, mm = divmod(off, timedelta(hours=1))
- assert not mm % timedelta(minutes=1), "whole minute"
- mm //= timedelta(minutes=1)
+ mm, ss = divmod(mm, timedelta(minutes=1))
assert 0 <= hh < 24
off = "%s%02d%s%02d" % (sign, hh, sep, mm)
+ if ss:
+ off += ':%02d' % ss.seconds
return off
def __repr__(self):
@@ -1191,16 +1220,22 @@ class time:
if self._tzinfo is not None:
assert s[-1:] == ")"
s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
+ if self._fold:
+ assert s[-1:] == ")"
+ s = s[:-1] + ", fold=1)"
return s
- def isoformat(self):
+ def isoformat(self, timespec='auto'):
"""Return the time formatted according to ISO.
- This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
- self.microsecond == 0.
+ The full format is 'HH:MM:SS.mmmmmm+zz:zz'. By default, the fractional
+ part is omitted if self.microsecond == 0.
+
+ The optional argument timespec specifies the number of additional
+ terms of the time to include.
"""
s = _format_time(self._hour, self._minute, self._second,
- self._microsecond)
+ self._microsecond, timespec)
tz = self._tzstr()
if tz:
s += tz
@@ -1266,7 +1301,7 @@ class time:
return offset
def replace(self, hour=None, minute=None, second=None, microsecond=None,
- tzinfo=True):
+ tzinfo=True, *, fold=None):
"""Return a new time with new values for the specified fields."""
if hour is None:
hour = self.hour
@@ -1278,14 +1313,19 @@ class time:
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
- return time(hour, minute, second, microsecond, tzinfo)
+ if fold is None:
+ fold = self._fold
+ return time(hour, minute, second, microsecond, tzinfo, fold=fold)
# Pickle support.
- def _getstate(self):
+ def _getstate(self, protocol=3):
us2, us3 = divmod(self._microsecond, 256)
us1, us2 = divmod(us2, 256)
- basestate = bytes([self._hour, self._minute, self._second,
+ h = self._hour
+ if self._fold and protocol > 3:
+ h += 128
+ basestate = bytes([h, self._minute, self._second,
us1, us2, us3])
if self._tzinfo is None:
return (basestate,)
@@ -1295,12 +1335,21 @@ class time:
def __setstate(self, string, tzinfo):
if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class):
raise TypeError("bad tzinfo state arg")
- self._hour, self._minute, self._second, us1, us2, us3 = string
+ h, self._minute, self._second, us1, us2, us3 = string
+ if h > 127:
+ self._fold = 1
+ self._hour = h - 128
+ else:
+ self._fold = 0
+ self._hour = h
self._microsecond = (((us1 << 8) | us2) << 8) | us3
self._tzinfo = tzinfo
+ def __reduce_ex__(self, protocol):
+ return (time, self._getstate(protocol))
+
def __reduce__(self):
- return (time, self._getstate())
+ return self.__reduce_ex__(2)
_time_class = time # so functions w/ args named "time" can get at the class
@@ -1317,16 +1366,16 @@ class datetime(date):
__slots__ = date.__slots__ + time.__slots__
def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
- microsecond=0, tzinfo=None):
- if isinstance(year, bytes) and len(year) == 10 and 1 <= year[2] <= 12:
+ microsecond=0, tzinfo=None, *, fold=0):
+ if isinstance(year, bytes) and len(year) == 10 and 1 <= year[2]&0x7F <= 12:
# Pickle support
self = object.__new__(cls)
self.__setstate(year, month)
self._hashcode = -1
return self
year, month, day = _check_date_fields(year, month, day)
- hour, minute, second, microsecond = _check_time_fields(
- hour, minute, second, microsecond)
+ hour, minute, second, microsecond, fold = _check_time_fields(
+ hour, minute, second, microsecond, fold)
_check_tzinfo_arg(tzinfo)
self = object.__new__(cls)
self._year = year
@@ -1338,6 +1387,7 @@ class datetime(date):
self._microsecond = microsecond
self._tzinfo = tzinfo
self._hashcode = -1
+ self._fold = fold
return self
# Read-only field accessors
@@ -1366,6 +1416,10 @@ class datetime(date):
"""timezone info object"""
return self._tzinfo
+ @property
+ def fold(self):
+ return self._fold
+
@classmethod
def _fromtimestamp(cls, t, utc, tz):
"""Construct a datetime from a POSIX timestamp (like time.time()).
@@ -1384,7 +1438,23 @@ class datetime(date):
converter = _time.gmtime if utc else _time.localtime
y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
ss = min(ss, 59) # clamp out leap seconds if the platform has them
- return cls(y, m, d, hh, mm, ss, us, tz)
+ result = cls(y, m, d, hh, mm, ss, us, tz)
+ if tz is None:
+ # As of version 2015f max fold in IANA database is
+ # 23 hours at 1969-09-30 13:00:00 in Kwajalein.
+ # Let's probe 24 hours in the past to detect a transition:
+ max_fold_seconds = 24 * 3600
+ y, m, d, hh, mm, ss = converter(t - max_fold_seconds)[:6]
+ probe1 = cls(y, m, d, hh, mm, ss, us, tz)
+ trans = result - probe1 - timedelta(0, max_fold_seconds)
+ if trans.days < 0:
+ y, m, d, hh, mm, ss = converter(t + trans // timedelta(0, 1))[:6]
+ probe2 = cls(y, m, d, hh, mm, ss, us, tz)
+ if probe2 == result:
+ result._fold = 1
+ else:
+ result = tz.fromutc(result)
+ return result
@classmethod
def fromtimestamp(cls, t, tz=None):
@@ -1394,10 +1464,7 @@ class datetime(date):
"""
_check_tzinfo_arg(tz)
- result = cls._fromtimestamp(t, tz is not None, tz)
- if tz is not None:
- result = tz.fromutc(result)
- return result
+ return cls._fromtimestamp(t, tz is not None, tz)
@classmethod
def utcfromtimestamp(cls, t):
@@ -1417,15 +1484,17 @@ class datetime(date):
return cls.utcfromtimestamp(t)
@classmethod
- def combine(cls, date, time):
+ def combine(cls, date, time, tzinfo=True):
"Construct a datetime from a given date and a given time."
if not isinstance(date, _date_class):
raise TypeError("date argument must be a date instance")
if not isinstance(time, _time_class):
raise TypeError("time argument must be a time instance")
+ if tzinfo is True:
+ tzinfo = time.tzinfo
return cls(date.year, date.month, date.day,
time.hour, time.minute, time.second, time.microsecond,
- time.tzinfo)
+ tzinfo, fold=time.fold)
def timetuple(self):
"Return local time tuple compatible with time.localtime()."
@@ -1440,12 +1509,46 @@ class datetime(date):
self.hour, self.minute, self.second,
dst)
+ def _mktime(self):
+ """Return integer POSIX timestamp."""
+ epoch = datetime(1970, 1, 1)
+ max_fold_seconds = 24 * 3600
+ t = (self - epoch) // timedelta(0, 1)
+ def local(u):
+ y, m, d, hh, mm, ss = _time.localtime(u)[:6]
+ return (datetime(y, m, d, hh, mm, ss) - epoch) // timedelta(0, 1)
+
+ # Our goal is to solve t = local(u) for u.
+ a = local(t) - t
+ u1 = t - a
+ t1 = local(u1)
+ if t1 == t:
+ # We found one solution, but it may not be the one we need.
+ # Look for an earlier solution (if `fold` is 0), or a
+ # later one (if `fold` is 1).
+ u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold]
+ b = local(u2) - u2
+ if a == b:
+ return u1
+ else:
+ b = t1 - u1
+ assert a != b
+ u2 = t - b
+ t2 = local(u2)
+ if t2 == t:
+ return u2
+ if t1 == t:
+ return u1
+ # We have found both offsets a and b, but neither t - a nor t - b is
+ # a solution. This means t is in the gap.
+ return (max, min)[self.fold](u1, u2)
+
+
def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
- return _time.mktime((self.year, self.month, self.day,
- self.hour, self.minute, self.second,
- -1, -1, -1)) + self.microsecond / 1e6
+ s = self._mktime()
+ return s + self.microsecond / 1e6
else:
return (self - _EPOCH).total_seconds()
@@ -1464,15 +1567,16 @@ class datetime(date):
def time(self):
"Return the time part, with tzinfo None."
- return time(self.hour, self.minute, self.second, self.microsecond)
+ return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold)
def timetz(self):
"Return the time part, with same tzinfo."
return time(self.hour, self.minute, self.second, self.microsecond,
- self._tzinfo)
+ self._tzinfo, fold=self.fold)
def replace(self, year=None, month=None, day=None, hour=None,
- minute=None, second=None, microsecond=None, tzinfo=True):
+ minute=None, second=None, microsecond=None, tzinfo=True,
+ *, fold=None):
"""Return a new datetime with new values for the specified fields."""
if year is None:
year = self.year
@@ -1490,46 +1594,45 @@ class datetime(date):
microsecond = self.microsecond
if tzinfo is True:
tzinfo = self.tzinfo
- return datetime(year, month, day, hour, minute, second, microsecond,
- tzinfo)
+ if fold is None:
+ fold = self.fold
+ return datetime(year, month, day, hour, minute, second,
+ microsecond, tzinfo, fold=fold)
+
+ def _local_timezone(self):
+ if self.tzinfo is None:
+ ts = self._mktime()
+ else:
+ ts = (self - _EPOCH) // timedelta(seconds=1)
+ localtm = _time.localtime(ts)
+ local = datetime(*localtm[:6])
+ try:
+ # Extract TZ data if available
+ gmtoff = localtm.tm_gmtoff
+ zone = localtm.tm_zone
+ except AttributeError:
+ delta = local - datetime(*_time.gmtime(ts)[:6])
+ zone = _time.strftime('%Z', localtm)
+ tz = timezone(delta, zone)
+ else:
+ tz = timezone(timedelta(seconds=gmtoff), zone)
+ return tz
def astimezone(self, tz=None):
if tz is None:
- if self.tzinfo is None:
- raise ValueError("astimezone() requires an aware datetime")
- ts = (self - _EPOCH) // timedelta(seconds=1)
- localtm = _time.localtime(ts)
- local = datetime(*localtm[:6])
- try:
- # Extract TZ data if available
- gmtoff = localtm.tm_gmtoff
- zone = localtm.tm_zone
- except AttributeError:
- # Compute UTC offset and compare with the value implied
- # by tm_isdst. If the values match, use the zone name
- # implied by tm_isdst.
- delta = local - datetime(*_time.gmtime(ts)[:6])
- dst = _time.daylight and localtm.tm_isdst > 0
- gmtoff = -(_time.altzone if dst else _time.timezone)
- if delta == timedelta(seconds=gmtoff):
- tz = timezone(delta, _time.tzname[dst])
- else:
- tz = timezone(delta)
- else:
- tz = timezone(timedelta(seconds=gmtoff), zone)
-
+ tz = self._local_timezone()
elif not isinstance(tz, tzinfo):
raise TypeError("tz argument must be an instance of tzinfo")
mytz = self.tzinfo
if mytz is None:
- raise ValueError("astimezone() requires an aware datetime")
+ mytz = self._local_timezone()
if tz is mytz:
return self
# Convert self to UTC, and attach the new time zone object.
- myoffset = self.utcoffset()
+ myoffset = mytz.utcoffset(self)
if myoffset is None:
raise ValueError("astimezone() requires an aware datetime")
utc = (self - myoffset).replace(tzinfo=tz)
@@ -1549,21 +1652,25 @@ class datetime(date):
self._hour, self._minute, self._second,
self._year)
- def isoformat(self, sep='T'):
+ def isoformat(self, sep='T', timespec='auto'):
"""Return the time formatted according to ISO.
- This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
- self.microsecond == 0.
+ The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
+ By default, the fractional part is omitted if self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
- 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
+ giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
+
+ The optional argument timespec specifies the number of additional
+ terms of the time to include.
"""
s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) +
_format_time(self._hour, self._minute, self._second,
- self._microsecond))
+ self._microsecond, timespec))
+
off = self.utcoffset()
if off is not None:
if off.days < 0:
@@ -1572,9 +1679,11 @@ class datetime(date):
else:
sign = "+"
hh, mm = divmod(off, timedelta(hours=1))
- assert not mm % timedelta(minutes=1), "whole minute"
- mm //= timedelta(minutes=1)
+ mm, ss = divmod(mm, timedelta(minutes=1))
s += "%s%02d:%02d" % (sign, hh, mm)
+ if ss:
+ assert not ss.microseconds
+ s += ":%02d" % ss.seconds
return s
def __repr__(self):
@@ -1591,6 +1700,9 @@ class datetime(date):
if self._tzinfo is not None:
assert s[-1:] == ")"
s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
+ if self._fold:
+ assert s[-1:] == ")"
+ s = s[:-1] + ", fold=1)"
return s
def __str__(self):
@@ -1693,6 +1805,12 @@ class datetime(date):
else:
myoff = self.utcoffset()
otoff = other.utcoffset()
+ # Assume that allow_mixed means that we are called from __eq__
+ if allow_mixed:
+ if myoff != self.replace(fold=not self.fold).utcoffset():
+ return 2
+ if otoff != other.replace(fold=not other.fold).utcoffset():
+ return 2
base_compare = myoff == otoff
if base_compare:
@@ -1760,9 +1878,13 @@ class datetime(date):
def __hash__(self):
if self._hashcode == -1:
- tzoff = self.utcoffset()
+ if self.fold:
+ t = self.replace(fold=0)
+ else:
+ t = self
+ tzoff = t.utcoffset()
if tzoff is None:
- self._hashcode = hash(self._getstate()[0])
+ self._hashcode = hash(t._getstate()[0])
else:
days = _ymd2ord(self.year, self.month, self.day)
seconds = self.hour * 3600 + self.minute * 60 + self.second
@@ -1771,11 +1893,14 @@ class datetime(date):
# Pickle support.
- def _getstate(self):
+ def _getstate(self, protocol=3):
yhi, ylo = divmod(self._year, 256)
us2, us3 = divmod(self._microsecond, 256)
us1, us2 = divmod(us2, 256)
- basestate = bytes([yhi, ylo, self._month, self._day,
+ m = self._month
+ if self._fold and protocol > 3:
+ m += 128
+ basestate = bytes([yhi, ylo, m, self._day,
self._hour, self._minute, self._second,
us1, us2, us3])
if self._tzinfo is None:
@@ -1786,14 +1911,23 @@ class datetime(date):
def __setstate(self, string, tzinfo):
if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class):
raise TypeError("bad tzinfo state arg")
- (yhi, ylo, self._month, self._day, self._hour,
+ (yhi, ylo, m, self._day, self._hour,
self._minute, self._second, us1, us2, us3) = string
+ if m > 127:
+ self._fold = 1
+ self._month = m - 128
+ else:
+ self._fold = 0
+ self._month = m
self._year = yhi * 256 + ylo
self._microsecond = (((us1 << 8) | us2) << 8) | us3
self._tzinfo = tzinfo
+ def __reduce_ex__(self, protocol):
+ return (self.__class__, self._getstate(protocol))
+
def __reduce__(self):
- return (self.__class__, self._getstate())
+ return self.__reduce_ex__(2)
datetime.min = datetime(1, 1, 1)
@@ -1913,6 +2047,8 @@ class timezone(tzinfo):
@staticmethod
def _name_from_offset(delta):
+ if not delta:
+ return 'UTC'
if delta < timedelta(0):
sign = '-'
delta = -delta
diff --git a/Lib/dbm/dumb.py b/Lib/dbm/dumb.py
index e6d6505..2296dbf 100644
--- a/Lib/dbm/dumb.py
+++ b/Lib/dbm/dumb.py
@@ -81,6 +81,11 @@ class _Database(collections.MutableMapping):
try:
f = _io.open(self._datfile, 'r', encoding="Latin-1")
except OSError:
+ if flag not in ('c', 'n'):
+ import warnings
+ warnings.warn("The database file is missing, the "
+ "semantics of the 'c' flag will be used.",
+ DeprecationWarning, stacklevel=4)
with _io.open(self._datfile, 'w', encoding="Latin-1") as f:
self._chmod(self._datfile)
else:
@@ -180,6 +185,10 @@ class _Database(collections.MutableMapping):
f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair))
def __setitem__(self, key, val):
+ if self._readonly:
+ import warnings
+ warnings.warn('The database is opened for reading only',
+ DeprecationWarning, stacklevel=2)
if isinstance(key, str):
key = key.encode('utf-8')
elif not isinstance(key, (bytes, bytearray)):
@@ -215,6 +224,10 @@ class _Database(collections.MutableMapping):
# (so that _commit() never gets called).
def __delitem__(self, key):
+ if self._readonly:
+ import warnings
+ warnings.warn('The database is opened for reading only',
+ DeprecationWarning, stacklevel=2)
if isinstance(key, str):
key = key.encode('utf-8')
self._verify_open()
@@ -304,4 +317,8 @@ def open(file, flag='c', mode=0o666):
else:
# Turn off any bits that are set in the umask
mode = mode & (~um)
+ if flag not in ('r', 'w', 'c', 'n'):
+ import warnings
+ warnings.warn("Flag must be one of 'r', 'w', 'c', or 'n'",
+ DeprecationWarning, stacklevel=2)
return _Database(file, mode, flag=flag)
diff --git a/Lib/difflib.py b/Lib/difflib.py
index 076bbac..2095a5e 100644
--- a/Lib/difflib.py
+++ b/Lib/difflib.py
@@ -1415,7 +1415,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None,
import re
# regular expression for finding intraline change indices
- change_re = re.compile('(\++|\-+|\^+)')
+ change_re = re.compile(r'(\++|\-+|\^+)')
# create the difference iterator to generate the differences
diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
diff --git a/Lib/dis.py b/Lib/dis.py
index f7e3c7f..0794b7f 100644
--- a/Lib/dis.py
+++ b/Lib/dis.py
@@ -16,6 +16,8 @@ del _opcodes_all
_have_code = (types.MethodType, types.FunctionType, types.CodeType,
classmethod, staticmethod, type)
+FORMAT_VALUE = opmap['FORMAT_VALUE']
+
def _try_compile(source, name):
"""Attempts to compile the given source, first as an expression and
then as a statement if the first approach fails.
@@ -87,6 +89,7 @@ COMPILER_FLAG_NAMES = {
64: "NOFREE",
128: "COROUTINE",
256: "ITERABLE_COROUTINE",
+ 512: "ASYNC_GENERATOR",
}
def pretty_flags(flags):
@@ -163,6 +166,15 @@ def show_code(co, *, file=None):
_Instruction = collections.namedtuple("_Instruction",
"opname opcode arg argval argrepr offset starts_line is_jump_target")
+_Instruction.opname.__doc__ = "Human readable name for operation"
+_Instruction.opcode.__doc__ = "Numeric code for operation"
+_Instruction.arg.__doc__ = "Numeric argument to operation (if any), otherwise None"
+_Instruction.argval.__doc__ = "Resolved arg value (if known), otherwise same as arg"
+_Instruction.argrepr.__doc__ = "Human readable description of operation argument"
+_Instruction.offset.__doc__ = "Start index of operation within bytecode sequence"
+_Instruction.starts_line.__doc__ = "Line started by this opcode (if any), otherwise None"
+_Instruction.is_jump_target.__doc__ = "True if other code jumps to here, otherwise False"
+
class Instruction(_Instruction):
"""Details for a bytecode operation
@@ -276,7 +288,6 @@ def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
"""
labels = findlabels(code)
starts_line = None
- free = None
for offset, op, arg in _unpack_opargs(code):
if linestarts is not None:
starts_line = linestarts.get(offset, None)
@@ -296,7 +307,7 @@ def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
elif op in hasname:
argval, argrepr = _get_name_info(arg, names)
elif op in hasjrel:
- argval = offset + 3 + arg
+ argval = offset + 2 + arg
argrepr = "to " + repr(argval)
elif op in haslocal:
argval, argrepr = _get_name_info(arg, varnames)
@@ -305,8 +316,13 @@ def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
argrepr = argval
elif op in hasfree:
argval, argrepr = _get_name_info(arg, cells)
- elif op in hasnargs:
- argrepr = "%d positional, %d keyword pair" % (arg%256, arg//256)
+ elif op == FORMAT_VALUE:
+ argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4))
+ argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3]
+ if argval[1]:
+ if argrepr:
+ argrepr += ', '
+ argrepr += 'with format'
yield Instruction(opname[op], op,
arg, argval, argrepr,
offset, starts_line, is_jump_target)
@@ -343,23 +359,15 @@ def _disassemble_str(source, *, file=None):
disco = disassemble # XXX For backwards compatibility
def _unpack_opargs(code):
- # enumerate() is not an option, since we sometimes process
- # multiple elements on a single pass through the loop
extended_arg = 0
- n = len(code)
- i = 0
- while i < n:
+ for i in range(0, len(code), 2):
op = code[i]
- offset = i
- i = i+1
- arg = None
if op >= HAVE_ARGUMENT:
- arg = code[i] + code[i+1]*256 + extended_arg
- extended_arg = 0
- i = i+2
- if op == EXTENDED_ARG:
- extended_arg = arg*65536
- yield (offset, op, arg)
+ arg = code[i+1] | extended_arg
+ extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
+ else:
+ arg = None
+ yield (i, op, arg)
def findlabels(code):
"""Detect all offsets in a byte code which are jump targets.
@@ -370,14 +378,14 @@ def findlabels(code):
labels = []
for offset, op, arg in _unpack_opargs(code):
if arg is not None:
- label = -1
if op in hasjrel:
- label = offset + 3 + arg
+ label = offset + 2 + arg
elif op in hasjabs:
label = arg
- if label >= 0:
- if label not in labels:
- labels.append(label)
+ else:
+ continue
+ if label not in labels:
+ labels.append(label)
return labels
def findlinestarts(code):
@@ -386,8 +394,8 @@ def findlinestarts(code):
Generate pairs (offset, lineno) as described in Python/compile.c.
"""
- byte_increments = list(code.co_lnotab[0::2])
- line_increments = list(code.co_lnotab[1::2])
+ byte_increments = code.co_lnotab[0::2]
+ line_increments = code.co_lnotab[1::2]
lastlineno = None
lineno = code.co_firstlineno
@@ -398,6 +406,9 @@ def findlinestarts(code):
yield (addr, lineno)
lastlineno = lineno
addr += byte_incr
+ if line_incr >= 0x80:
+ # line_increments is an array of 8-bit signed integers
+ line_incr -= 0x100
lineno += line_incr
if lineno != lastlineno:
yield (addr, lineno)
diff --git a/Lib/distutils/archive_util.py b/Lib/distutils/archive_util.py
index bed1384..78ae575 100644
--- a/Lib/distutils/archive_util.py
+++ b/Lib/distutils/archive_util.py
@@ -171,7 +171,7 @@ def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zip.write(path, path)
- log.info("adding '%s'" % path)
+ log.info("adding '%s'", path)
zip.close()
return zip_filename
diff --git a/Lib/distutils/cmd.py b/Lib/distutils/cmd.py
index c89d5ef..939f795 100644
--- a/Lib/distutils/cmd.py
+++ b/Lib/distutils/cmd.py
@@ -221,7 +221,7 @@ class Command:
self._ensure_stringlike(option, "string", default)
def ensure_string_list(self, option):
- """Ensure that 'option' is a list of strings. If 'option' is
+ r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
@@ -329,8 +329,7 @@ class Command:
# -- External world manipulation -----------------------------------
def warn(self, msg):
- log.warn("warning: %s: %s\n" %
- (self.get_command_name(), msg))
+ log.warn("warning: %s: %s\n", self.get_command_name(), msg)
def execute(self, func, args, msg=None, level=1):
util.execute(func, args, msg, dry_run=self.dry_run)
diff --git a/Lib/distutils/command/bdist_dumb.py b/Lib/distutils/command/bdist_dumb.py
index f1bfb24..e9274d9 100644
--- a/Lib/distutils/command/bdist_dumb.py
+++ b/Lib/distutils/command/bdist_dumb.py
@@ -85,7 +85,7 @@ class bdist_dumb(Command):
install.skip_build = self.skip_build
install.warn_dir = 0
- log.info("installing to %s" % self.bdist_dir)
+ log.info("installing to %s", self.bdist_dir)
self.run_command('install')
# And make an archive relative to the root of the
diff --git a/Lib/distutils/command/bdist_msi.py b/Lib/distutils/command/bdist_msi.py
index b3cfe9c..a4bd5a5 100644
--- a/Lib/distutils/command/bdist_msi.py
+++ b/Lib/distutils/command/bdist_msi.py
@@ -199,7 +199,7 @@ class bdist_msi(Command):
target_version = self.target_version
if not target_version:
assert self.skip_build, "Should have already checked this"
- target_version = sys.version[0:3]
+ target_version = '%d.%d' % sys.version_info[:2]
plat_specifier = ".%s-%s" % (self.plat_name, target_version)
build = self.get_finalized_command('build')
build.build_lib = os.path.join(build.build_base,
@@ -623,7 +623,7 @@ class bdist_msi(Command):
cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title,
"OK", "OK", "OK", bitmap=False)
cost.text("Title", 15, 6, 200, 15, 0x30003,
- "{\DlgFontBold8}Disk Space Requirements")
+ r"{\DlgFontBold8}Disk Space Requirements")
cost.text("Description", 20, 20, 280, 20, 0x30003,
"The disk space required for the installation of the selected features.")
cost.text("Text", 20, 53, 330, 60, 3,
@@ -670,7 +670,7 @@ class bdist_msi(Command):
progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title,
"Cancel", "Cancel", "Cancel", bitmap=False)
progress.text("Title", 20, 15, 200, 15, 0x30003,
- "{\DlgFontBold8}[Progress1] [ProductName]")
+ r"{\DlgFontBold8}[Progress1] [ProductName]")
progress.text("Text", 35, 65, 300, 30, 3,
"Please wait while the Installer [Progress2] [ProductName]. "
"This may take several minutes.")
diff --git a/Lib/distutils/command/bdist_wininst.py b/Lib/distutils/command/bdist_wininst.py
index 0c0e2c1..d3e1d3a 100644
--- a/Lib/distutils/command/bdist_wininst.py
+++ b/Lib/distutils/command/bdist_wininst.py
@@ -141,7 +141,7 @@ class bdist_wininst(Command):
target_version = self.target_version
if not target_version:
assert self.skip_build, "Should have already checked this"
- target_version = sys.version[0:3]
+ target_version = '%d.%d' % sys.version_info[:2]
plat_specifier = ".%s-%s" % (self.plat_name, target_version)
build = self.get_finalized_command('build')
build.build_lib = os.path.join(build.build_base,
diff --git a/Lib/distutils/command/build.py b/Lib/distutils/command/build.py
index 337dd0b..c6f52e6 100644
--- a/Lib/distutils/command/build.py
+++ b/Lib/distutils/command/build.py
@@ -81,7 +81,7 @@ class build(Command):
"--plat-name only supported on Windows (try "
"using './configure --help' on your platform)")
- plat_specifier = ".%s-%s" % (self.plat_name, sys.version[0:3])
+ plat_specifier = ".%s-%d.%d" % (self.plat_name, *sys.version_info[:2])
# Make it so Python 2.x and Python 2.x with --with-pydebug don't
# share the same build directories. Doing so confuses the build
@@ -114,7 +114,7 @@ class build(Command):
'temp' + plat_specifier)
if self.build_scripts is None:
self.build_scripts = os.path.join(self.build_base,
- 'scripts-' + sys.version[0:3])
+ 'scripts-%d.%d' % sys.version_info[:2])
if self.executable is None:
self.executable = os.path.normpath(sys.executable)
diff --git a/Lib/distutils/command/build_ext.py b/Lib/distutils/command/build_ext.py
index 7c278ef..74de782 100644
--- a/Lib/distutils/command/build_ext.py
+++ b/Lib/distutils/command/build_ext.py
@@ -364,9 +364,9 @@ class build_ext(Command):
ext_name, build_info = ext
- log.warn(("old-style (ext_name, build_info) tuple found in "
- "ext_modules for extension '%s'"
- "-- please convert to Extension instance" % ext_name))
+ log.warn("old-style (ext_name, build_info) tuple found in "
+ "ext_modules for extension '%s'"
+ "-- please convert to Extension instance", ext_name)
if not (isinstance(ext_name, str) and
extension_name_re.match(ext_name)):
diff --git a/Lib/distutils/command/build_scripts.py b/Lib/distutils/command/build_scripts.py
index 90a8380..ccc70e6 100644
--- a/Lib/distutils/command/build_scripts.py
+++ b/Lib/distutils/command/build_scripts.py
@@ -51,7 +51,7 @@ class build_scripts(Command):
def copy_scripts(self):
- """Copy each script listed in 'self.scripts'; if it's marked as a
+ r"""Copy each script listed in 'self.scripts'; if it's marked as a
Python script in the Unix way (first line matches 'first_line_re',
ie. starts with "\#!" and contains "python"), then adjust the first
line to refer to the current Python interpreter as we copy.
diff --git a/Lib/distutils/command/config.py b/Lib/distutils/command/config.py
index 847e858..4ae153d 100644
--- a/Lib/distutils/command/config.py
+++ b/Lib/distutils/command/config.py
@@ -9,7 +9,7 @@ configure-like tasks: "try to compile this C code", or "figure out where
this header file lives".
"""
-import sys, os, re
+import os, re
from distutils.core import Command
from distutils.errors import DistutilsExecError
@@ -337,7 +337,7 @@ def dump_file(filename, head=None):
If head is not None, will be dumped before the file content.
"""
if head is None:
- log.info('%s' % filename)
+ log.info('%s', filename)
else:
log.info(head)
file = open(filename)
diff --git a/Lib/distutils/command/install.py b/Lib/distutils/command/install.py
index 67db007..0258d3de 100644
--- a/Lib/distutils/command/install.py
+++ b/Lib/distutils/command/install.py
@@ -175,6 +175,7 @@ class install(Command):
self.compile = None
self.optimize = None
+ # Deprecated
# These two are for putting non-packagized distributions into their
# own directory and creating a .pth file if it makes sense.
# 'extra_path' comes from the setup file; 'install_path_file' can
@@ -290,8 +291,8 @@ class install(Command):
'dist_version': self.distribution.get_version(),
'dist_fullname': self.distribution.get_fullname(),
'py_version': py_version,
- 'py_version_short': py_version[0:3],
- 'py_version_nodot': py_version[0] + py_version[2],
+ 'py_version_short': '%d.%d' % sys.version_info[:2],
+ 'py_version_nodot': '%d%d' % sys.version_info[:2],
'sys_prefix': prefix,
'prefix': prefix,
'sys_exec_prefix': exec_prefix,
@@ -344,6 +345,7 @@ class install(Command):
'scripts', 'data', 'headers',
'userbase', 'usersite')
+ # Deprecated
# Well, we're not actually fully completely finalized yet: we still
# have to deal with 'extra_path', which is the hack for allowing
# non-packagized module distributions (hello, Numerical Python!) to
@@ -385,7 +387,7 @@ class install(Command):
else:
opt_name = opt_name.translate(longopt_xlate)
val = getattr(self, opt_name)
- log.debug(" %s: %s" % (opt_name, val))
+ log.debug(" %s: %s", opt_name, val)
def finalize_unix(self):
"""Finalizes options for posix platforms."""
@@ -490,6 +492,10 @@ class install(Command):
self.extra_path = self.distribution.extra_path
if self.extra_path is not None:
+ log.warn(
+ "Distribution option extra_path is deprecated. "
+ "See issue27919 for details."
+ )
if isinstance(self.extra_path, str):
self.extra_path = self.extra_path.split(',')
diff --git a/Lib/distutils/command/install_egg_info.py b/Lib/distutils/command/install_egg_info.py
index c2a7d64..0ddc736 100644
--- a/Lib/distutils/command/install_egg_info.py
+++ b/Lib/distutils/command/install_egg_info.py
@@ -21,10 +21,10 @@ class install_egg_info(Command):
def finalize_options(self):
self.set_undefined_options('install_lib',('install_dir','install_dir'))
- basename = "%s-%s-py%s.egg-info" % (
+ basename = "%s-%s-py%d.%d.egg-info" % (
to_filename(safe_name(self.distribution.get_name())),
to_filename(safe_version(self.distribution.get_version())),
- sys.version[:3]
+ *sys.version_info[:2]
)
self.target = os.path.join(self.install_dir, basename)
self.outputs = [self.target]
diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py
index 86343c8..0fac94e 100644
--- a/Lib/distutils/command/register.py
+++ b/Lib/distutils/command/register.py
@@ -5,7 +5,7 @@ Implements the Distutils 'register' command (register with the repository).
# created 2002/10/21, Richard Jones
-import os, string, getpass
+import getpass
import io
import urllib.parse, urllib.request
from warnings import warn
@@ -94,7 +94,7 @@ class register(PyPIRCCommand):
'''
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
- log.info('Server response (%s): %s' % (code, result))
+ log.info('Server response (%s): %s', code, result)
def send_metadata(self):
''' Send the metadata to the package index server.
@@ -205,7 +205,7 @@ Your selection [default 1]: ''', log.INFO)
data['email'] = input(' EMail: ')
code, result = self.post_to_server(data)
if code != 200:
- log.info('Server response (%s): %s' % (code, result))
+ log.info('Server response (%s): %s', code, result)
else:
log.info('You will receive an email shortly.')
log.info(('Follow the instructions in it to '
@@ -216,7 +216,7 @@ Your selection [default 1]: ''', log.INFO)
while not data['email']:
data['email'] = input('Your email address: ')
code, result = self.post_to_server(data)
- log.info('Server response (%s): %s' % (code, result))
+ log.info('Server response (%s): %s', code, result)
def build_post_data(self, action):
# figure the data to send - the metadata plus some additional
diff --git a/Lib/distutils/command/sdist.py b/Lib/distutils/command/sdist.py
index 7ea3d5f..4fd1d47 100644
--- a/Lib/distutils/command/sdist.py
+++ b/Lib/distutils/command/sdist.py
@@ -3,7 +3,6 @@
Implements the Distutils 'sdist' command (create a source distribution)."""
import os
-import string
import sys
from types import *
from glob import glob
@@ -92,9 +91,6 @@ class sdist(Command):
negative_opt = {'no-defaults': 'use-defaults',
'no-prune': 'prune' }
- default_format = {'posix': 'gztar',
- 'nt': 'zip' }
-
sub_commands = [('check', checking_metadata)]
def initialize_options(self):
@@ -111,7 +107,7 @@ class sdist(Command):
self.manifest_only = 0
self.force_manifest = 0
- self.formats = None
+ self.formats = ['gztar']
self.keep_temp = 0
self.dist_dir = None
@@ -127,13 +123,6 @@ class sdist(Command):
self.template = "MANIFEST.in"
self.ensure_string_list('formats')
- if self.formats is None:
- try:
- self.formats = [self.default_format[os.name]]
- except KeyError:
- raise DistutilsPlatformError(
- "don't know how to create source distributions "
- "on platform %s" % os.name)
bad_format = archive_util.check_archive_formats(self.formats)
if bad_format:
@@ -423,7 +412,7 @@ class sdist(Command):
log.info(msg)
for file in files:
if not os.path.isfile(file):
- log.warn("'%s' not a regular file -- skipping" % file)
+ log.warn("'%s' not a regular file -- skipping", file)
else:
dest = os.path.join(base_dir, file)
self.copy_file(file, dest, link=link)
diff --git a/Lib/distutils/core.py b/Lib/distutils/core.py
index f05b34b..d603d4a 100644
--- a/Lib/distutils/core.py
+++ b/Lib/distutils/core.py
@@ -204,16 +204,15 @@ def run_setup (script_name, script_args=None, stop_after="run"):
global _setup_stop_after, _setup_distribution
_setup_stop_after = stop_after
- save_argv = sys.argv
+ save_argv = sys.argv.copy()
g = {'__file__': script_name}
- l = {}
try:
try:
sys.argv[0] = script_name
if script_args is not None:
sys.argv[1:] = script_args
with open(script_name, 'rb') as f:
- exec(f.read(), g, l)
+ exec(f.read(), g)
finally:
sys.argv = save_argv
_setup_stop_after = None
diff --git a/Lib/distutils/cygwinccompiler.py b/Lib/distutils/cygwinccompiler.py
index c879646..1c36990 100644
--- a/Lib/distutils/cygwinccompiler.py
+++ b/Lib/distutils/cygwinccompiler.py
@@ -368,7 +368,7 @@ def check_config_h():
return (CONFIG_H_UNCERTAIN,
"couldn't read '%s': %s" % (fn, exc.strerror))
-RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
+RE_VERSION = re.compile(br'(\d+\.\d+(\.\d+)*)')
def _find_exe_version(cmd):
"""Find the version of an executable by running `cmd` in the shell.
diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py
index ffb33ff6..62a2451 100644
--- a/Lib/distutils/dist.py
+++ b/Lib/distutils/dist.py
@@ -1018,8 +1018,7 @@ class DistributionMetadata:
"maintainer", "maintainer_email", "url",
"license", "description", "long_description",
"keywords", "platforms", "fullname", "contact",
- "contact_email", "license", "classifiers",
- "download_url",
+ "contact_email", "classifiers", "download_url",
# PEP 314
"provides", "requires", "obsoletes",
)
diff --git a/Lib/distutils/extension.py b/Lib/distutils/extension.py
index 7efbb74..c507da3 100644
--- a/Lib/distutils/extension.py
+++ b/Lib/distutils/extension.py
@@ -4,7 +4,6 @@ Provides the Extension class, used to describe C/C++ extension
modules in setup scripts."""
import os
-import sys
import warnings
# This class is really only used by the "build_ext" command, so it might
diff --git a/Lib/distutils/filelist.py b/Lib/distutils/filelist.py
index 6522e69..c92d5fd 100644
--- a/Lib/distutils/filelist.py
+++ b/Lib/distutils/filelist.py
@@ -302,21 +302,26 @@ def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
else:
return pattern
+ # ditch start and end characters
+ start, _, end = glob_to_re('_').partition('_')
+
if pattern:
pattern_re = glob_to_re(pattern)
+ assert pattern_re.startswith(start) and pattern_re.endswith(end)
else:
pattern_re = ''
if prefix is not None:
- # ditch end of pattern character
- empty_pattern = glob_to_re('')
- prefix_re = glob_to_re(prefix)[:-len(empty_pattern)]
+ prefix_re = glob_to_re(prefix)
+ assert prefix_re.startswith(start) and prefix_re.endswith(end)
+ prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
sep = os.sep
if os.sep == '\\':
sep = r'\\'
- pattern_re = "^" + sep.join((prefix_re, ".*" + pattern_re))
+ pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
+ pattern_re = r'%s\A%s%s.*%s%s' % (start, prefix_re, sep, pattern_re, end)
else: # no prefix -- respect anchor flag
if anchor:
- pattern_re = "^" + pattern_re
+ pattern_re = r'%s\A%s' % (start, pattern_re[len(start):])
return re.compile(pattern_re)
diff --git a/Lib/distutils/msvc9compiler.py b/Lib/distutils/msvc9compiler.py
index 0b1fd19..2119127 100644
--- a/Lib/distutils/msvc9compiler.py
+++ b/Lib/distutils/msvc9compiler.py
@@ -716,7 +716,7 @@ class MSVCCompiler(CCompiler) :
r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
re.DOTALL)
manifest_buf = re.sub(pattern, "", manifest_buf)
- pattern = "<dependentAssembly>\s*</dependentAssembly>"
+ pattern = r"<dependentAssembly>\s*</dependentAssembly>"
manifest_buf = re.sub(pattern, "", manifest_buf)
# Now see if any other assemblies are referenced - if not, we
# don't want a manifest embedded.
diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py
index 573724d..8bf1a70 100644
--- a/Lib/distutils/sysconfig.py
+++ b/Lib/distutils/sysconfig.py
@@ -70,7 +70,7 @@ def get_python_version():
leaving off the patchlevel. Sample return values could be '1.5'
or '2.2'.
"""
- return sys.version[:3]
+ return '%d.%d' % sys.version_info[:2]
def get_python_inc(plat_specific=0, prefix=None):
@@ -242,6 +242,8 @@ def get_makefile_filename():
return os.path.join(_sys_home or project_base, "Makefile")
lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
config_file = 'config-{}{}'.format(get_python_version(), build_flags)
+ if hasattr(sys.implementation, '_multiarch'):
+ config_file += '-%s' % sys.implementation._multiarch
return os.path.join(lib_dir, config_file, 'Makefile')
@@ -276,7 +278,7 @@ def parse_config_h(fp, g=None):
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
-_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
+_variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
@@ -415,38 +417,18 @@ _config_vars = None
def _init_posix():
"""Initialize the module as appropriate for POSIX systems."""
- g = {}
- # load the installed Makefile:
- try:
- filename = get_makefile_filename()
- parse_makefile(filename, g)
- except OSError as msg:
- my_msg = "invalid Python installation: unable to open %s" % filename
- if hasattr(msg, "strerror"):
- my_msg = my_msg + " (%s)" % msg.strerror
-
- raise DistutilsPlatformError(my_msg)
-
- # load the installed pyconfig.h:
- try:
- filename = get_config_h_filename()
- with open(filename) as file:
- parse_config_h(file, g)
- except OSError as msg:
- my_msg = "invalid Python installation: unable to open %s" % filename
- if hasattr(msg, "strerror"):
- my_msg = my_msg + " (%s)" % msg.strerror
-
- raise DistutilsPlatformError(my_msg)
-
- # On AIX, there are wrong paths to the linker scripts in the Makefile
- # -- these paths are relative to the Python source, but when installed
- # the scripts are in another directory.
- if python_build:
- g['LDSHARED'] = g['BLDSHARED']
-
+ # _sysconfigdata is generated at build time, see the sysconfig module
+ name = os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
+ '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
+ abi=sys.abiflags,
+ platform=sys.platform,
+ multiarch=getattr(sys.implementation, '_multiarch', ''),
+ ))
+ _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
+ build_time_vars = _temp.build_time_vars
global _config_vars
- _config_vars = g
+ _config_vars = {}
+ _config_vars.update(build_time_vars)
def _init_nt():
diff --git a/Lib/distutils/tests/test_bdist_rpm.py b/Lib/distutils/tests/test_bdist_rpm.py
index c5962dd..6453a02 100644
--- a/Lib/distutils/tests/test_bdist_rpm.py
+++ b/Lib/distutils/tests/test_bdist_rpm.py
@@ -9,8 +9,6 @@ from distutils.core import Distribution
from distutils.command.bdist_rpm import bdist_rpm
from distutils.tests import support
from distutils.spawn import find_executable
-from distutils import spawn
-from distutils.errors import DistutilsExecError
SETUP_PY = """\
from distutils.core import setup
diff --git a/Lib/distutils/tests/test_build.py b/Lib/distutils/tests/test_build.py
index 3391f36..b020a5b 100644
--- a/Lib/distutils/tests/test_build.py
+++ b/Lib/distutils/tests/test_build.py
@@ -27,7 +27,7 @@ class BuildTestCase(support.TempdirManager,
# build_platlib is 'build/lib.platform-x.x[-pydebug]'
# examples:
# build/lib.macosx-10.3-i386-2.7
- plat_spec = '.%s-%s' % (cmd.plat_name, sys.version[0:3])
+ plat_spec = '.%s-%d.%d' % (cmd.plat_name, *sys.version_info[:2])
if hasattr(sys, 'gettotalrefcount'):
self.assertTrue(cmd.build_platlib.endswith('-pydebug'))
plat_spec += '-pydebug'
@@ -42,7 +42,8 @@ class BuildTestCase(support.TempdirManager,
self.assertEqual(cmd.build_temp, wanted)
# build_scripts is build/scripts-x.x
- wanted = os.path.join(cmd.build_base, 'scripts-' + sys.version[0:3])
+ wanted = os.path.join(cmd.build_base,
+ 'scripts-%d.%d' % sys.version_info[:2])
self.assertEqual(cmd.build_scripts, wanted)
# executable is os.path.normpath(sys.executable)
diff --git a/Lib/distutils/tests/test_build_clib.py b/Lib/distutils/tests/test_build_clib.py
index acc99e7..85d0990 100644
--- a/Lib/distutils/tests/test_build_clib.py
+++ b/Lib/distutils/tests/test_build_clib.py
@@ -3,7 +3,7 @@ import unittest
import os
import sys
-from test.support import run_unittest
+from test.support import run_unittest, missing_compiler_executable
from distutils.command.build_clib import build_clib
from distutils.errors import DistutilsSetupError
@@ -116,19 +116,11 @@ class BuildCLibTestCase(support.TempdirManager,
cmd.build_temp = build_temp
cmd.build_clib = build_temp
- # before we run the command, we want to make sure
- # all commands are present on the system
- # by creating a compiler and checking its executables
- from distutils.ccompiler import new_compiler
- from distutils.sysconfig import customize_compiler
-
- compiler = new_compiler()
- customize_compiler(compiler)
- for ccmd in compiler.executables.values():
- if ccmd is None:
- continue
- if find_executable(ccmd[0]) is None:
- self.skipTest('The %r command is not found' % ccmd[0])
+ # Before we run the command, we want to make sure
+ # all commands are present on the system.
+ ccmd = missing_compiler_executable()
+ if ccmd is not None:
+ self.skipTest('The %r command is not found' % ccmd)
# this should work
cmd.run()
diff --git a/Lib/distutils/tests/test_build_ext.py b/Lib/distutils/tests/test_build_ext.py
index f3df564..be7f5f3 100644
--- a/Lib/distutils/tests/test_build_ext.py
+++ b/Lib/distutils/tests/test_build_ext.py
@@ -41,6 +41,9 @@ class BuildExtTestCase(TempdirManager,
return build_ext(*args, **kwargs)
def test_build_ext(self):
+ cmd = support.missing_compiler_executable()
+ if cmd is not None:
+ self.skipTest('The %r command is not found' % cmd)
global ALREADY_TESTED
copy_xxmodule_c(self.tmp_dir)
xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
@@ -166,7 +169,6 @@ class BuildExtTestCase(TempdirManager,
cmd = self.build_ext(dist)
cmd.finalize_options()
- from distutils import sysconfig
py_include = sysconfig.get_python_inc()
self.assertIn(py_include, cmd.include_dirs)
@@ -296,6 +298,9 @@ class BuildExtTestCase(TempdirManager,
self.assertEqual(cmd.compiler, 'unix')
def test_get_outputs(self):
+ cmd = support.missing_compiler_executable()
+ if cmd is not None:
+ self.skipTest('The %r command is not found' % cmd)
tmp_dir = self.mkdtemp()
c_file = os.path.join(tmp_dir, 'foo.c')
self.write_file(c_file, 'void PyInit_foo(void) {}\n')
diff --git a/Lib/distutils/tests/test_build_py.py b/Lib/distutils/tests/test_build_py.py
index 18283dc..0712e92 100644
--- a/Lib/distutils/tests/test_build_py.py
+++ b/Lib/distutils/tests/test_build_py.py
@@ -168,7 +168,8 @@ class BuildPyTestCase(support.TempdirManager,
finally:
sys.dont_write_bytecode = old_dont_write_bytecode
- self.assertIn('byte-compiling is disabled', self.logs[0][1])
+ self.assertIn('byte-compiling is disabled',
+ self.logs[0][1] % self.logs[0][2])
def test_suite():
diff --git a/Lib/distutils/tests/test_clean.py b/Lib/distutils/tests/test_clean.py
index b64f300..c605afd 100644
--- a/Lib/distutils/tests/test_clean.py
+++ b/Lib/distutils/tests/test_clean.py
@@ -1,8 +1,6 @@
"""Tests for distutils.command.clean."""
-import sys
import os
import unittest
-import getpass
from distutils.command.clean import clean
from distutils.tests import support
diff --git a/Lib/distutils/tests/test_config.py b/Lib/distutils/tests/test_config.py
index a384497..77ef788 100644
--- a/Lib/distutils/tests/test_config.py
+++ b/Lib/distutils/tests/test_config.py
@@ -1,8 +1,6 @@
"""Tests for distutils.pypirc.pypirc."""
-import sys
import os
import unittest
-import tempfile
from distutils.core import PyPIRCCommand
from distutils.core import Distribution
diff --git a/Lib/distutils/tests/test_config_cmd.py b/Lib/distutils/tests/test_config_cmd.py
index 0c8dbd8..6e566e7 100644
--- a/Lib/distutils/tests/test_config_cmd.py
+++ b/Lib/distutils/tests/test_config_cmd.py
@@ -2,7 +2,7 @@
import unittest
import os
import sys
-from test.support import run_unittest
+from test.support import run_unittest, missing_compiler_executable
from distutils.command.config import dump_file, config
from distutils.tests import support
@@ -39,6 +39,9 @@ class ConfigTestCase(support.LoggingSilencer,
@unittest.skipIf(sys.platform == 'win32', "can't test on Windows")
def test_search_cpp(self):
+ cmd = missing_compiler_executable(['preprocessor'])
+ if cmd is not None:
+ self.skipTest('The %r command is not found' % cmd)
pkg_dir, dist = self.create_dist()
cmd = config(dist)
diff --git a/Lib/distutils/tests/test_core.py b/Lib/distutils/tests/test_core.py
index 654227c..27ce732 100644
--- a/Lib/distutils/tests/test_core.py
+++ b/Lib/distutils/tests/test_core.py
@@ -29,6 +29,21 @@ from distutils.core import setup
setup()
"""
+setup_does_nothing = """\
+from distutils.core import setup
+setup()
+"""
+
+
+setup_defines_subclass = """\
+from distutils.core import setup
+from distutils.command.install import install as _install
+
+class install(_install):
+ sub_commands = _install.sub_commands + ['cmd']
+
+setup(cmdclass={'install': install})
+"""
class CoreTestCase(support.EnvironGuard, unittest.TestCase):
@@ -67,6 +82,21 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
distutils.core.run_setup(
self.write_setup(setup_using___file__))
+ def test_run_setup_preserves_sys_argv(self):
+ # Make sure run_setup does not clobber sys.argv
+ argv_copy = sys.argv.copy()
+ distutils.core.run_setup(
+ self.write_setup(setup_does_nothing))
+ self.assertEqual(sys.argv, argv_copy)
+
+ def test_run_setup_defines_subclass(self):
+ # Make sure the script can use __file__; if that's missing, the test
+ # setup.py script will raise NameError.
+ dist = distutils.core.run_setup(
+ self.write_setup(setup_defines_subclass))
+ install = dist.get_command_obj('install')
+ self.assertIn('cmd', install.sub_commands)
+
def test_run_setup_uses_current_dir(self):
# This tests that the setup script is run with the current directory
# as its own current directory; this was temporarily broken by a
diff --git a/Lib/distutils/tests/test_cygwinccompiler.py b/Lib/distutils/tests/test_cygwinccompiler.py
index 8569216..9dc869d 100644
--- a/Lib/distutils/tests/test_cygwinccompiler.py
+++ b/Lib/distutils/tests/test_cygwinccompiler.py
@@ -3,11 +3,10 @@ import unittest
import sys
import os
from io import BytesIO
-import subprocess
from test.support import run_unittest
from distutils import cygwinccompiler
-from distutils.cygwinccompiler import (CygwinCCompiler, check_config_h,
+from distutils.cygwinccompiler import (check_config_h,
CONFIG_H_OK, CONFIG_H_NOTOK,
CONFIG_H_UNCERTAIN, get_versions,
get_msvcr)
diff --git a/Lib/distutils/tests/test_dep_util.py b/Lib/distutils/tests/test_dep_util.py
index 3e1c366..c6fae39 100644
--- a/Lib/distutils/tests/test_dep_util.py
+++ b/Lib/distutils/tests/test_dep_util.py
@@ -1,7 +1,6 @@
"""Tests for distutils.dep_util."""
import unittest
import os
-import time
from distutils.dep_util import newer, newer_pairwise, newer_group
from distutils.errors import DistutilsFileError
diff --git a/Lib/distutils/tests/test_file_util.py b/Lib/distutils/tests/test_file_util.py
index a6d04f0..03040af 100644
--- a/Lib/distutils/tests/test_file_util.py
+++ b/Lib/distutils/tests/test_file_util.py
@@ -1,7 +1,6 @@
"""Tests for distutils.file_util."""
import unittest
import os
-import shutil
import errno
from unittest.mock import patch
diff --git a/Lib/distutils/tests/test_filelist.py b/Lib/distutils/tests/test_filelist.py
index 391af3c..c71342d 100644
--- a/Lib/distutils/tests/test_filelist.py
+++ b/Lib/distutils/tests/test_filelist.py
@@ -51,14 +51,14 @@ class FileListTestCase(support.LoggingSilencer,
for glob, regex in (
# simple cases
- ('foo*', r'foo[^%(sep)s]*\Z(?ms)'),
- ('foo?', r'foo[^%(sep)s]\Z(?ms)'),
- ('foo??', r'foo[^%(sep)s][^%(sep)s]\Z(?ms)'),
+ ('foo*', r'(?s:foo[^%(sep)s]*)\Z'),
+ ('foo?', r'(?s:foo[^%(sep)s])\Z'),
+ ('foo??', r'(?s:foo[^%(sep)s][^%(sep)s])\Z'),
# special cases
- (r'foo\\*', r'foo\\\\[^%(sep)s]*\Z(?ms)'),
- (r'foo\\\*', r'foo\\\\\\[^%(sep)s]*\Z(?ms)'),
- ('foo????', r'foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s]\Z(?ms)'),
- (r'foo\\??', r'foo\\\\[^%(sep)s][^%(sep)s]\Z(?ms)')):
+ (r'foo\\*', r'(?s:foo\\\\[^%(sep)s]*)\Z'),
+ (r'foo\\\*', r'(?s:foo\\\\\\[^%(sep)s]*)\Z'),
+ ('foo????', r'(?s:foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s])\Z'),
+ (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z')):
regex = regex % {'sep': sep}
self.assertEqual(glob_to_re(glob), regex)
diff --git a/Lib/distutils/tests/test_install.py b/Lib/distutils/tests/test_install.py
index 9313330..287ab19 100644
--- a/Lib/distutils/tests/test_install.py
+++ b/Lib/distutils/tests/test_install.py
@@ -17,6 +17,7 @@ from distutils.errors import DistutilsOptionError
from distutils.extension import Extension
from distutils.tests import support
+from test import support as test_support
def _make_ext_name(modname):
@@ -196,6 +197,9 @@ class InstallTestCase(support.TempdirManager,
self.assertEqual(found, expected)
def test_record_extensions(self):
+ cmd = test_support.missing_compiler_executable()
+ if cmd is not None:
+ self.skipTest('The %r command is not found' % cmd)
install_dir = self.mkdtemp()
project_dir, dist = self.create_dist(ext_modules=[
Extension('xx', ['xxmodule.c'])])
diff --git a/Lib/distutils/tests/test_install_data.py b/Lib/distutils/tests/test_install_data.py
index 4d8c00a..32ab296 100644
--- a/Lib/distutils/tests/test_install_data.py
+++ b/Lib/distutils/tests/test_install_data.py
@@ -1,8 +1,6 @@
"""Tests for distutils.command.install_data."""
-import sys
import os
import unittest
-import getpass
from distutils.command.install_data import install_data
from distutils.tests import support
diff --git a/Lib/distutils/tests/test_install_headers.py b/Lib/distutils/tests/test_install_headers.py
index d953157..2217b32 100644
--- a/Lib/distutils/tests/test_install_headers.py
+++ b/Lib/distutils/tests/test_install_headers.py
@@ -1,8 +1,6 @@
"""Tests for distutils.command.install_headers."""
-import sys
import os
import unittest
-import getpass
from distutils.command.install_headers import install_headers
from distutils.tests import support
diff --git a/Lib/distutils/tests/test_install_lib.py b/Lib/distutils/tests/test_install_lib.py
index 5378aa8..fda6315 100644
--- a/Lib/distutils/tests/test_install_lib.py
+++ b/Lib/distutils/tests/test_install_lib.py
@@ -104,7 +104,8 @@ class InstallLibTestCase(support.TempdirManager,
finally:
sys.dont_write_bytecode = old_dont_write_bytecode
- self.assertIn('byte-compiling is disabled', self.logs[0][1])
+ self.assertIn('byte-compiling is disabled',
+ self.logs[0][1] % self.logs[0][2])
def test_suite():
diff --git a/Lib/distutils/tests/test_spawn.py b/Lib/distutils/tests/test_spawn.py
index 6c7eb20..5edc24a 100644
--- a/Lib/distutils/tests/test_spawn.py
+++ b/Lib/distutils/tests/test_spawn.py
@@ -1,11 +1,11 @@
"""Tests for distutils.spawn."""
import unittest
+import sys
import os
-import time
-from test.support import captured_stdout, run_unittest
+from test.support import run_unittest, unix_shell
from distutils.spawn import _nt_quote_args
-from distutils.spawn import spawn, find_executable
+from distutils.spawn import spawn
from distutils.errors import DistutilsExecError
from distutils.tests import support
@@ -30,9 +30,9 @@ class SpawnTestCase(support.TempdirManager,
# creating something executable
# through the shell that returns 1
- if os.name == 'posix':
+ if sys.platform != 'win32':
exe = os.path.join(tmpdir, 'foo.sh')
- self.write_file(exe, '#!/bin/sh\nexit 1')
+ self.write_file(exe, '#!%s\nexit 1' % unix_shell)
else:
exe = os.path.join(tmpdir, 'foo.bat')
self.write_file(exe, 'exit 1')
@@ -41,9 +41,9 @@ class SpawnTestCase(support.TempdirManager,
self.assertRaises(DistutilsExecError, spawn, [exe])
# now something that works
- if os.name == 'posix':
+ if sys.platform != 'win32':
exe = os.path.join(tmpdir, 'foo.sh')
- self.write_file(exe, '#!/bin/sh\nexit 0')
+ self.write_file(exe, '#!%s\nexit 0' % unix_shell)
else:
exe = os.path.join(tmpdir, 'foo.bat')
self.write_file(exe, 'exit 0')
diff --git a/Lib/distutils/tests/test_sysconfig.py b/Lib/distutils/tests/test_sysconfig.py
index fc4d1de..fe4a299 100644
--- a/Lib/distutils/tests/test_sysconfig.py
+++ b/Lib/distutils/tests/test_sysconfig.py
@@ -39,15 +39,6 @@ class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
self.assertNotEqual(sysconfig.get_python_lib(),
sysconfig.get_python_lib(prefix=TESTFN))
- def test_get_python_inc(self):
- inc_dir = sysconfig.get_python_inc()
- # This is not much of a test. We make sure Python.h exists
- # in the directory returned by get_python_inc() but we don't know
- # it is the correct file.
- self.assertTrue(os.path.isdir(inc_dir), inc_dir)
- python_h = os.path.join(inc_dir, "Python.h")
- self.assertTrue(os.path.isfile(python_h), python_h)
-
def test_get_config_vars(self):
cvars = sysconfig.get_config_vars()
self.assertIsInstance(cvars, dict)
diff --git a/Lib/distutils/tests/test_unixccompiler.py b/Lib/distutils/tests/test_unixccompiler.py
index e171ee9..efba27e 100644
--- a/Lib/distutils/tests/test_unixccompiler.py
+++ b/Lib/distutils/tests/test_unixccompiler.py
@@ -1,5 +1,4 @@
"""Tests for distutils.unixccompiler."""
-import os
import sys
import unittest
from test.support import EnvironmentVarGuard, run_unittest
diff --git a/Lib/distutils/text_file.py b/Lib/distutils/text_file.py
index 478336f..93abad3 100644
--- a/Lib/distutils/text_file.py
+++ b/Lib/distutils/text_file.py
@@ -4,7 +4,7 @@ provides the TextFile class, which gives an interface to text files
that (optionally) takes care of stripping comments, ignoring blank
lines, and joining lines with backslashes."""
-import sys, os, io
+import sys, io
class TextFile:
diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py
index e423325..fdcf6fa 100644
--- a/Lib/distutils/util.py
+++ b/Lib/distutils/util.py
@@ -7,8 +7,8 @@ one of the other *util.py modules.
import os
import re
import importlib.util
-import sys
import string
+import sys
from distutils.errors import DistutilsPlatformError
from distutils.dep_util import newer
from distutils.spawn import spawn
@@ -350,6 +350,11 @@ def byte_compile (py_files,
generated in indirect mode; unless you know what you're doing, leave
it set to None.
"""
+
+ # Late import to fix a bootstrap issue: _posixsubprocess is built by
+ # setup.py, but setup.py uses distutils.
+ import subprocess
+
# nothing is done if sys.dont_write_bytecode is True
if sys.dont_write_bytecode:
raise DistutilsByteCompileError('byte-compiling is disabled.')
@@ -412,11 +417,9 @@ byte_compile(files, optimize=%r, force=%r,
script.close()
- cmd = [sys.executable, script_name]
- if optimize == 1:
- cmd.insert(1, "-O")
- elif optimize == 2:
- cmd.insert(1, "-OO")
+ cmd = [sys.executable]
+ cmd.extend(subprocess._optim_args_from_interpreter_flags())
+ cmd.append(script_name)
spawn(cmd, dry_run=dry_run)
execute(os.remove, (script_name,), "removing %s" % script_name,
dry_run=dry_run)
diff --git a/Lib/distutils/versionpredicate.py b/Lib/distutils/versionpredicate.py
index b0dd9f4..062c98f 100644
--- a/Lib/distutils/versionpredicate.py
+++ b/Lib/distutils/versionpredicate.py
@@ -154,7 +154,7 @@ def split_provision(value):
global _provision_rx
if _provision_rx is None:
_provision_rx = re.compile(
- "([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$",
+ r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$",
re.ASCII)
value = value.strip()
m = _provision_rx.match(value)
diff --git a/Lib/doctest.py b/Lib/doctest.py
index 38fdd80..0b78544 100644
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -381,12 +381,15 @@ class _OutputRedirectingPdb(pdb.Pdb):
sys.stdout = save_stdout
# [XX] Normalize with respect to os.path.pardir?
-def _module_relative_path(module, path):
+def _module_relative_path(module, test_path):
if not inspect.ismodule(module):
raise TypeError('Expected a module: %r' % module)
- if path.startswith('/'):
+ if test_path.startswith('/'):
raise ValueError('Module-relative files may not have absolute paths')
+ # Normalize the path. On Windows, replace "/" with "\".
+ test_path = os.path.join(*(test_path.split('/')))
+
# Find the base directory for the path.
if hasattr(module, '__file__'):
# A normal module/package
@@ -398,13 +401,19 @@ def _module_relative_path(module, path):
else:
basedir = os.curdir
else:
+ if hasattr(module, '__path__'):
+ for directory in module.__path__:
+ fullpath = os.path.join(directory, test_path)
+ if os.path.exists(fullpath):
+ return fullpath
+
# A module w/o __file__ (this includes builtins)
raise ValueError("Can't resolve paths relative to the module "
"%r (it has no __file__)"
% module.__name__)
- # Combine the base directory and the path.
- return os.path.join(basedir, *(path.split('/')))
+ # Combine the base directory and the test path.
+ return os.path.join(basedir, test_path)
######################################################################
## 2. Example & DocTest
@@ -756,7 +765,7 @@ class DocTestParser:
# This regular expression finds the indentation of every non-blank
# line in a string.
- _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
+ _INDENT_RE = re.compile(r'^([ ]*)(?=\S)', re.MULTILINE)
def _min_indent(self, s):
"Return the minimum indentation of any non-blank line in `s`"
@@ -1097,7 +1106,7 @@ class DocTestFinder:
if lineno is not None:
if source_lines is None:
return lineno+1
- pat = re.compile('(^|.*:)\s*\w*("|\')')
+ pat = re.compile(r'(^|.*:)\s*\w*("|\')')
for lineno in range(lineno, len(source_lines)):
if pat.match(source_lines[lineno]):
return lineno
@@ -1599,11 +1608,11 @@ class OutputChecker:
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
if not (optionflags & DONT_ACCEPT_BLANKLINE):
# Replace <BLANKLINE> in want with a blank line.
- want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
+ want = re.sub(r'(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
'', want)
# If a line in got contains only spaces, then remove the
# spaces.
- got = re.sub('(?m)^\s*?$', '', got)
+ got = re.sub(r'(?m)^\s*?$', '', got)
if got == want:
return True
diff --git a/Lib/email/_header_value_parser.py b/Lib/email/_header_value_parser.py
index 5df9511..57d01fb 100644
--- a/Lib/email/_header_value_parser.py
+++ b/Lib/email/_header_value_parser.py
@@ -652,8 +652,8 @@ class Comment(WhiteSpaceTokenList):
if value.token_type == 'comment':
return str(value)
return str(value).replace('\\', '\\\\').replace(
- '(', '\(').replace(
- ')', '\)')
+ '(', r'\(').replace(
+ ')', r'\)')
@property
def content(self):
@@ -1356,15 +1356,15 @@ RouteComponentMarker = ValueTerminal('@', 'route-component-marker')
_wsp_splitter = re.compile(r'([{}]+)'.format(''.join(WSP))).split
_non_atom_end_matcher = re.compile(r"[^{}]+".format(
- ''.join(ATOM_ENDS).replace('\\','\\\\').replace(']','\]'))).match
+ ''.join(ATOM_ENDS).replace('\\','\\\\').replace(']',r'\]'))).match
_non_printable_finder = re.compile(r"[\x00-\x20\x7F]").findall
_non_token_end_matcher = re.compile(r"[^{}]+".format(
- ''.join(TOKEN_ENDS).replace('\\','\\\\').replace(']','\]'))).match
+ ''.join(TOKEN_ENDS).replace('\\','\\\\').replace(']',r'\]'))).match
_non_attribute_end_matcher = re.compile(r"[^{}]+".format(
- ''.join(ATTRIBUTE_ENDS).replace('\\','\\\\').replace(']','\]'))).match
+ ''.join(ATTRIBUTE_ENDS).replace('\\','\\\\').replace(']',r'\]'))).match
_non_extended_attribute_end_matcher = re.compile(r"[^{}]+".format(
''.join(EXTENDED_ATTRIBUTE_ENDS).replace(
- '\\','\\\\').replace(']','\]'))).match
+ '\\','\\\\').replace(']',r'\]'))).match
def _validate_xtext(xtext):
"""If input token contains ASCII non-printables, register a defect."""
@@ -1517,7 +1517,7 @@ def get_unstructured(value):
return unstructured
def get_qp_ctext(value):
- """ctext = <printable ascii except \ ( )>
+ r"""ctext = <printable ascii except \ ( )>
This is not the RFC ctext, since we are handling nested comments in comment
and unquoting quoted-pairs here. We allow anything except the '()'
@@ -1878,7 +1878,7 @@ def get_obs_local_part(value):
return obs_local_part, value
def get_dtext(value):
- """ dtext = <printable ascii except \ [ ]> / obs-dtext
+ r""" dtext = <printable ascii except \ [ ]> / obs-dtext
obs-dtext = obs-NO-WS-CTL / quoted-pair
We allow anything except the excluded characters, but if we find any
diff --git a/Lib/email/_policybase.py b/Lib/email/_policybase.py
index c0d98a4..df46496 100644
--- a/Lib/email/_policybase.py
+++ b/Lib/email/_policybase.py
@@ -154,6 +154,9 @@ class Policy(_PolicyBase, metaclass=abc.ABCMeta):
them. This is used when the message is being
serialized by a generator. Default: True.
+ message_factory -- the class to use to create new message objects.
+ If the value is None, the default is Message.
+
"""
raise_on_defect = False
@@ -161,6 +164,7 @@ class Policy(_PolicyBase, metaclass=abc.ABCMeta):
cte_type = '8bit'
max_line_length = 78
mangle_from_ = False
+ message_factory = None
def handle_defect(self, obj, defect):
"""Based on policy, either raise defect or call register_defect.
diff --git a/Lib/email/contentmanager.py b/Lib/email/contentmanager.py
index b98ce27..b904ded 100644
--- a/Lib/email/contentmanager.py
+++ b/Lib/email/contentmanager.py
@@ -142,7 +142,7 @@ def _encode_base64(data, max_line_length):
def _encode_text(string, charset, cte, policy):
lines = string.encode(charset).splitlines()
linesep = policy.linesep.encode('ascii')
- def embeded_body(lines): return linesep.join(lines) + linesep
+ def embedded_body(lines): return linesep.join(lines) + linesep
def normal_body(lines): return b'\n'.join(lines) + b'\n'
if cte==None:
# Use heuristics to decide on the "best" encoding.
@@ -153,7 +153,7 @@ def _encode_text(string, charset, cte, policy):
if (policy.cte_type == '8bit' and
max(len(x) for x in lines) <= policy.max_line_length):
return '8bit', normal_body(lines).decode('ascii', 'surrogateescape')
- sniff = embeded_body(lines[:10])
+ sniff = embedded_body(lines[:10])
sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'),
policy.max_line_length)
sniff_base64 = binascii.b2a_base64(sniff)
@@ -172,7 +172,7 @@ def _encode_text(string, charset, cte, policy):
data = quoprimime.body_encode(normal_body(lines).decode('latin-1'),
policy.max_line_length)
elif cte == 'base64':
- data = _encode_base64(embeded_body(lines), policy.max_line_length)
+ data = _encode_base64(embedded_body(lines), policy.max_line_length)
else:
raise ValueError("Unknown content transfer encoding {}".format(cte))
return cte, data
diff --git a/Lib/email/feedparser.py b/Lib/email/feedparser.py
index 0b312e5..7c07ca8 100644
--- a/Lib/email/feedparser.py
+++ b/Lib/email/feedparser.py
@@ -24,15 +24,14 @@ __all__ = ['FeedParser', 'BytesFeedParser']
import re
from email import errors
-from email import message
from email._policybase import compat32
from collections import deque
from io import StringIO
-NLCRE = re.compile('\r\n|\r|\n')
-NLCRE_bol = re.compile('(\r\n|\r|\n)')
-NLCRE_eol = re.compile('(\r\n|\r|\n)\Z')
-NLCRE_crack = re.compile('(\r\n|\r|\n)')
+NLCRE = re.compile(r'\r\n|\r|\n')
+NLCRE_bol = re.compile(r'(\r\n|\r|\n)')
+NLCRE_eol = re.compile(r'(\r\n|\r|\n)\Z')
+NLCRE_crack = re.compile(r'(\r\n|\r|\n)')
# RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
# except controls, SP, and ":".
headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])')
@@ -148,13 +147,11 @@ class FeedParser:
self.policy = policy
self._old_style_factory = False
if _factory is None:
- # What this should be:
- #self._factory = policy.default_message_factory
- # but, because we are post 3.4 feature freeze, fix with temp hack:
- if self.policy is compat32:
- self._factory = message.Message
+ if policy.message_factory is None:
+ from email.message import Message
+ self._factory = Message
else:
- self._factory = message.EmailMessage
+ self._factory = policy.message_factory
else:
self._factory = _factory
try:
diff --git a/Lib/email/generator.py b/Lib/email/generator.py
index 256278d..ae670c2 100644
--- a/Lib/email/generator.py
+++ b/Lib/email/generator.py
@@ -448,7 +448,8 @@ class DecodedGenerator(Generator):
Like the Generator base class, except that non-text parts are substituted
with a format string representing the part.
"""
- def __init__(self, outfp, mangle_from_=None, maxheaderlen=78, fmt=None):
+ def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *,
+ policy=None):
"""Like Generator.__init__() except that an additional optional
argument is allowed.
@@ -470,7 +471,8 @@ class DecodedGenerator(Generator):
[Non-text (%(type)s) part of message omitted, filename %(filename)s]
"""
- Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
+ Generator.__init__(self, outfp, mangle_from_, maxheaderlen,
+ policy=policy)
if fmt is None:
self._fmt = _FMT
else:
diff --git a/Lib/email/header.py b/Lib/email/header.py
index 6820ea1..c7b2dd9 100644
--- a/Lib/email/header.py
+++ b/Lib/email/header.py
@@ -49,7 +49,7 @@ fcre = re.compile(r'[\041-\176]+:$')
# Find a header embedded in a putative header value. Used to check for
# header injection attack.
-_embeded_header = re.compile(r'\n[^ \t]+:')
+_embedded_header = re.compile(r'\n[^ \t]+:')
@@ -385,7 +385,7 @@ class Header:
if self._chunks:
formatter.add_transition()
value = formatter._str(linesep)
- if _embeded_header.search(value):
+ if _embedded_header.search(value):
raise HeaderParseError("header value appears to contain "
"an embedded header: {!r}".format(value))
return value
diff --git a/Lib/email/message.py b/Lib/email/message.py
index 4b04283..b6512f2 100644
--- a/Lib/email/message.py
+++ b/Lib/email/message.py
@@ -4,18 +4,17 @@
"""Basic message object for the email package object model."""
-__all__ = ['Message']
+__all__ = ['Message', 'EmailMessage']
import re
import uu
import quopri
-import warnings
from io import BytesIO, StringIO
# Intrapackage imports
from email import utils
from email import errors
-from email._policybase import compat32
+from email._policybase import Policy, compat32
from email import charset as _charset
from email._encoded_words import decode_b
Charset = _charset.Charset
@@ -951,6 +950,26 @@ class MIMEPart(Message):
policy = default
Message.__init__(self, policy)
+
+ def as_string(self, unixfrom=False, maxheaderlen=None, policy=None):
+ """Return the entire formatted message as a string.
+
+ Optional 'unixfrom', when true, means include the Unix From_ envelope
+ header. maxheaderlen is retained for backward compatibility with the
+ base Message class, but defaults to None, meaning that the policy value
+ for max_line_length controls the header maximum length. 'policy' is
+ passed to the Generator instance used to serialize the mesasge; if it
+ is not specified the policy associated with the message instance is
+ used.
+ """
+ policy = self.policy if policy is None else policy
+ if maxheaderlen is None:
+ maxheaderlen = policy.max_line_length
+ return super().as_string(maxheaderlen=maxheaderlen, policy=policy)
+
+ def __str__(self):
+ return self.as_string(policy=self.policy.clone(utf8=True))
+
def is_attachment(self):
c_d = self.get('content-disposition')
return False if c_d is None else c_d.content_disposition == 'attachment'
diff --git a/Lib/email/mime/application.py b/Lib/email/mime/application.py
index f5c5905..6877e55 100644
--- a/Lib/email/mime/application.py
+++ b/Lib/email/mime/application.py
@@ -14,7 +14,7 @@ class MIMEApplication(MIMENonMultipart):
"""Class for generating application/* MIME documents."""
def __init__(self, _data, _subtype='octet-stream',
- _encoder=encoders.encode_base64, **_params):
+ _encoder=encoders.encode_base64, *, policy=None, **_params):
"""Create an application/* type MIME document.
_data is a string containing the raw application data.
@@ -31,6 +31,7 @@ class MIMEApplication(MIMENonMultipart):
"""
if _subtype is None:
raise TypeError('Invalid application MIME subtype')
- MIMENonMultipart.__init__(self, 'application', _subtype, **_params)
+ MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy,
+ **_params)
self.set_payload(_data)
_encoder(self)
diff --git a/Lib/email/mime/audio.py b/Lib/email/mime/audio.py
index fbc1189..4bcd7b2 100644
--- a/Lib/email/mime/audio.py
+++ b/Lib/email/mime/audio.py
@@ -43,7 +43,7 @@ class MIMEAudio(MIMENonMultipart):
"""Class for generating audio/* MIME documents."""
def __init__(self, _audiodata, _subtype=None,
- _encoder=encoders.encode_base64, **_params):
+ _encoder=encoders.encode_base64, *, policy=None, **_params):
"""Create an audio/* type MIME document.
_audiodata is a string containing the raw audio data. If this data
@@ -68,6 +68,7 @@ class MIMEAudio(MIMENonMultipart):
_subtype = _whatsnd(_audiodata)
if _subtype is None:
raise TypeError('Could not find audio MIME subtype')
- MIMENonMultipart.__init__(self, 'audio', _subtype, **_params)
+ MIMENonMultipart.__init__(self, 'audio', _subtype, policy=policy,
+ **_params)
self.set_payload(_audiodata)
_encoder(self)
diff --git a/Lib/email/mime/base.py b/Lib/email/mime/base.py
index ac91925..1a3f9b5 100644
--- a/Lib/email/mime/base.py
+++ b/Lib/email/mime/base.py
@@ -6,6 +6,8 @@
__all__ = ['MIMEBase']
+import email.policy
+
from email import message
@@ -13,14 +15,16 @@ from email import message
class MIMEBase(message.Message):
"""Base class for MIME specializations."""
- def __init__(self, _maintype, _subtype, **_params):
+ def __init__(self, _maintype, _subtype, *, policy=None, **_params):
"""This constructor adds a Content-Type: and a MIME-Version: header.
The Content-Type: header is taken from the _maintype and _subtype
arguments. Additional parameters for this header are taken from the
keyword arguments.
"""
- message.Message.__init__(self)
+ if policy is None:
+ policy = email.policy.compat32
+ message.Message.__init__(self, policy=policy)
ctype = '%s/%s' % (_maintype, _subtype)
self.add_header('Content-Type', ctype, **_params)
self['MIME-Version'] = '1.0'
diff --git a/Lib/email/mime/image.py b/Lib/email/mime/image.py
index 5563823..9272464 100644
--- a/Lib/email/mime/image.py
+++ b/Lib/email/mime/image.py
@@ -17,7 +17,7 @@ class MIMEImage(MIMENonMultipart):
"""Class for generating image/* type MIME documents."""
def __init__(self, _imagedata, _subtype=None,
- _encoder=encoders.encode_base64, **_params):
+ _encoder=encoders.encode_base64, *, policy=None, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
@@ -41,6 +41,7 @@ class MIMEImage(MIMENonMultipart):
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
- MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
+ MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy,
+ **_params)
self.set_payload(_imagedata)
_encoder(self)
diff --git a/Lib/email/mime/message.py b/Lib/email/mime/message.py
index 275dbfd..07e4f2d 100644
--- a/Lib/email/mime/message.py
+++ b/Lib/email/mime/message.py
@@ -14,7 +14,7 @@ from email.mime.nonmultipart import MIMENonMultipart
class MIMEMessage(MIMENonMultipart):
"""Class representing message/* MIME documents."""
- def __init__(self, _msg, _subtype='rfc822'):
+ def __init__(self, _msg, _subtype='rfc822', *, policy=None):
"""Create a message/* type MIME document.
_msg is a message object and must be an instance of Message, or a
@@ -24,7 +24,7 @@ class MIMEMessage(MIMENonMultipart):
default is "rfc822" (this is defined by the MIME standard, even though
the term "rfc822" is technically outdated by RFC 2822).
"""
- MIMENonMultipart.__init__(self, 'message', _subtype)
+ MIMENonMultipart.__init__(self, 'message', _subtype, policy=policy)
if not isinstance(_msg, message.Message):
raise TypeError('Argument is not an instance of Message')
# It's convenient to use this base class method. We need to do it
diff --git a/Lib/email/mime/multipart.py b/Lib/email/mime/multipart.py
index 9661865..2d3f288 100644
--- a/Lib/email/mime/multipart.py
+++ b/Lib/email/mime/multipart.py
@@ -14,6 +14,7 @@ class MIMEMultipart(MIMEBase):
"""Base class for MIME multipart/* type messages."""
def __init__(self, _subtype='mixed', boundary=None, _subparts=None,
+ *, policy=None,
**_params):
"""Creates a multipart/* type message.
@@ -33,7 +34,7 @@ class MIMEMultipart(MIMEBase):
Additional parameters for the Content-Type header are taken from the
keyword arguments (or passed into the _params argument).
"""
- MIMEBase.__init__(self, 'multipart', _subtype, **_params)
+ MIMEBase.__init__(self, 'multipart', _subtype, policy=policy, **_params)
# Initialise _payload to an empty list as the Message superclass's
# implementation of is_multipart assumes that _payload is a list for
diff --git a/Lib/email/mime/text.py b/Lib/email/mime/text.py
index da03086..35b4423 100644
--- a/Lib/email/mime/text.py
+++ b/Lib/email/mime/text.py
@@ -14,7 +14,7 @@ from email.mime.nonmultipart import MIMENonMultipart
class MIMEText(MIMENonMultipart):
"""Class for generating text/* type MIME documents."""
- def __init__(self, _text, _subtype='plain', _charset=None):
+ def __init__(self, _text, _subtype='plain', _charset=None, *, policy=None):
"""Create a text/* type MIME document.
_text is the string for this message object.
@@ -36,7 +36,7 @@ class MIMEText(MIMENonMultipart):
except UnicodeEncodeError:
_charset = 'utf-8'
- MIMENonMultipart.__init__(self, 'text', _subtype,
+ MIMENonMultipart.__init__(self, 'text', _subtype, policy=policy,
**{'charset': str(_charset)})
self.set_payload(_text, _charset)
diff --git a/Lib/email/policy.py b/Lib/email/policy.py
index 35d0e69..5131311ac 100644
--- a/Lib/email/policy.py
+++ b/Lib/email/policy.py
@@ -7,6 +7,7 @@ from email._policybase import Policy, Compat32, compat32, _extend_docstrings
from email.utils import _has_surrogates
from email.headerregistry import HeaderRegistry as HeaderRegistry
from email.contentmanager import raw_data_manager
+from email.message import EmailMessage
__all__ = [
'Compat32',
@@ -82,6 +83,7 @@ class EmailPolicy(Policy):
"""
+ message_factory = EmailMessage
utf8 = False
refold_source = 'long'
header_factory = HeaderRegistry()
diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py
index 8dd7130..aa2fb7c 100644
--- a/Lib/encodings/__init__.py
+++ b/Lib/encodings/__init__.py
@@ -29,6 +29,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
"""#"
import codecs
+import sys
from . import aliases
_cache = {}
@@ -54,6 +55,7 @@ def normalize_encoding(encoding):
"""
if isinstance(encoding, bytes):
encoding = str(encoding, "ascii")
+
chars = []
punct = False
for c in encoding:
@@ -97,6 +99,8 @@ def search_function(encoding):
mod = __import__('encodings.' + modname, fromlist=_import_tail,
level=0)
except ImportError:
+ # ImportError may occur because 'encodings.(modname)' does not exist,
+ # or because it imports a name that does not exist (see mbcs and oem)
pass
else:
break
@@ -150,3 +154,16 @@ def search_function(encoding):
# Register the search_function in the Python codec registry
codecs.register(search_function)
+
+if sys.platform == 'win32':
+ def _alias_mbcs(encoding):
+ try:
+ import _bootlocale
+ if encoding == _bootlocale.getpreferredencoding(False):
+ import encodings.mbcs
+ return encodings.mbcs.getregentry()
+ except ImportError:
+ # Imports may fail while we are shutting down
+ pass
+
+ codecs.register(_alias_mbcs)
diff --git a/Lib/encodings/aliases.py b/Lib/encodings/aliases.py
index 67c828d..2e63c2f 100644
--- a/Lib/encodings/aliases.py
+++ b/Lib/encodings/aliases.py
@@ -458,6 +458,7 @@ aliases = {
'macturkish' : 'mac_turkish',
# mbcs codec
+ 'ansi' : 'mbcs',
'dbcs' : 'mbcs',
# ptcp154 codec
diff --git a/Lib/encodings/oem.py b/Lib/encodings/oem.py
new file mode 100644
index 0000000..2c3426b
--- /dev/null
+++ b/Lib/encodings/oem.py
@@ -0,0 +1,41 @@
+""" Python 'oem' Codec for Windows
+
+"""
+# Import them explicitly to cause an ImportError
+# on non-Windows systems
+from codecs import oem_encode, oem_decode
+# for IncrementalDecoder, IncrementalEncoder, ...
+import codecs
+
+### Codec APIs
+
+encode = oem_encode
+
+def decode(input, errors='strict'):
+ return oem_decode(input, errors, True)
+
+class IncrementalEncoder(codecs.IncrementalEncoder):
+ def encode(self, input, final=False):
+ return oem_encode(input, self.errors)[0]
+
+class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
+ _buffer_decode = oem_decode
+
+class StreamWriter(codecs.StreamWriter):
+ encode = oem_encode
+
+class StreamReader(codecs.StreamReader):
+ decode = oem_decode
+
+### encodings module API
+
+def getregentry():
+ return codecs.CodecInfo(
+ name='oem',
+ encode=encode,
+ decode=decode,
+ incrementalencoder=IncrementalEncoder,
+ incrementaldecoder=IncrementalDecoder,
+ streamreader=StreamReader,
+ streamwriter=StreamWriter,
+ )
diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py
index 25c5567..9f5d151 100644
--- a/Lib/ensurepip/__init__.py
+++ b/Lib/ensurepip/__init__.py
@@ -12,19 +12,6 @@ _SETUPTOOLS_VERSION = "28.8.0"
_PIP_VERSION = "9.0.1"
-# pip currently requires ssl support, so we try to provide a nicer
-# error message when that is missing (http://bugs.python.org/issue19744)
-_MISSING_SSL_MESSAGE = ("pip {} requires SSL/TLS".format(_PIP_VERSION))
-try:
- import ssl
-except ImportError:
- ssl = None
- def _require_ssl_for_pip():
- raise RuntimeError(_MISSING_SSL_MESSAGE)
-else:
- def _require_ssl_for_pip():
- pass
-
_PROJECTS = [
("setuptools", _SETUPTOOLS_VERSION),
("pip", _PIP_VERSION),
@@ -71,7 +58,6 @@ def bootstrap(*, root=None, upgrade=False, user=False,
if altinstall and default_pip:
raise ValueError("Cannot use altinstall and default_pip together")
- _require_ssl_for_pip()
_disable_pip_configuration_settings()
# By default, installing pip and setuptools installs all of the
@@ -133,7 +119,6 @@ def _uninstall_helper(*, verbosity=0):
print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr)
return
- _require_ssl_for_pip()
_disable_pip_configuration_settings()
# Construct the arguments to be passed to the pip command
@@ -145,11 +130,6 @@ def _uninstall_helper(*, verbosity=0):
def _main(argv=None):
- if ssl is None:
- print("Ignoring ensurepip failure: {}".format(_MISSING_SSL_MESSAGE),
- file=sys.stderr)
- return
-
import argparse
parser = argparse.ArgumentParser(prog="python -m ensurepip")
parser.add_argument(
diff --git a/Lib/enum.py b/Lib/enum.py
index b8787d1..e79b038 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -1,8 +1,20 @@
import sys
-from collections import OrderedDict
from types import MappingProxyType, DynamicClassAttribute
+from functools import reduce
+from operator import or_ as _or_
-__all__ = ['Enum', 'IntEnum', 'unique']
+# try _collections first to reduce startup cost
+try:
+ from _collections import OrderedDict
+except ImportError:
+ from collections import OrderedDict
+
+
+__all__ = [
+ 'EnumMeta',
+ 'Enum', 'IntEnum', 'Flag', 'IntFlag',
+ 'auto', 'unique',
+ ]
def _is_descriptor(obj):
@@ -28,7 +40,6 @@ def _is_sunder(name):
name[-2:-1] != '_' and
len(name) > 2)
-
def _make_class_unpicklable(cls):
"""Make the given class un-picklable."""
def _break_on_call_reduce(self, proto):
@@ -36,6 +47,13 @@ def _make_class_unpicklable(cls):
cls.__reduce_ex__ = _break_on_call_reduce
cls.__module__ = '<unknown>'
+_auto_null = object()
+class auto:
+ """
+ Instances are replaced with an appropriate value in Enum class suites.
+ """
+ value = _auto_null
+
class _EnumDict(dict):
"""Track enum member order and ensure member names are not reused.
@@ -47,6 +65,7 @@ class _EnumDict(dict):
def __init__(self):
super().__init__()
self._member_names = []
+ self._last_values = []
def __setitem__(self, key, value):
"""Changes anything not dundered or not a descriptor.
@@ -58,21 +77,32 @@ class _EnumDict(dict):
"""
if _is_sunder(key):
- raise ValueError('_names_ are reserved for future Enum use')
+ if key not in (
+ '_order_', '_create_pseudo_member_',
+ '_generate_next_value_', '_missing_',
+ ):
+ raise ValueError('_names_ are reserved for future Enum use')
+ if key == '_generate_next_value_':
+ setattr(self, '_generate_next_value', value)
elif _is_dunder(key):
- pass
+ if key == '__order__':
+ key = '_order_'
elif key in self._member_names:
# descriptor overwriting an enum?
raise TypeError('Attempted to reuse key: %r' % key)
elif not _is_descriptor(value):
if key in self:
# enum overwriting a descriptor?
- raise TypeError('Key already defined as: %r' % self[key])
+ raise TypeError('%r already defined as: %r' % (key, self[key]))
+ if isinstance(value, auto):
+ if value.value == _auto_null:
+ value.value = self._generate_next_value(key, 1, len(self._member_names), self._last_values[:])
+ value = value.value
self._member_names.append(key)
+ self._last_values.append(value)
super().__setitem__(key, value)
-
# Dummy value for Enum as EnumMeta explicitly checks for it, but of course
# until EnumMeta finishes running the first time the Enum class doesn't exist.
# This is also why there are checks in EnumMeta like `if Enum is not None`
@@ -83,7 +113,13 @@ class EnumMeta(type):
"""Metaclass for Enum"""
@classmethod
def __prepare__(metacls, cls, bases):
- return _EnumDict()
+ # create the namespace dict
+ enum_dict = _EnumDict()
+ # inherit previous flags and _generate_next_value_ function
+ member_type, first_enum = metacls._get_mixins_(bases)
+ if first_enum is not None:
+ enum_dict['_generate_next_value_'] = getattr(first_enum, '_generate_next_value_', None)
+ return enum_dict
def __new__(metacls, cls, bases, classdict):
# an Enum class is final once enumeration items have been defined; it
@@ -96,12 +132,15 @@ class EnumMeta(type):
# save enum items into separate mapping so they don't get baked into
# the new class
- members = {k: classdict[k] for k in classdict._member_names}
+ enum_members = {k: classdict[k] for k in classdict._member_names}
for name in classdict._member_names:
del classdict[name]
+ # adjust the sunders
+ _order_ = classdict.pop('_order_', None)
+
# check for illegal enum names (any others?)
- invalid_names = set(members) & {'mro', }
+ invalid_names = set(enum_members) & {'mro', }
if invalid_names:
raise ValueError('Invalid enum member name: {0}'.format(
','.join(invalid_names)))
@@ -145,7 +184,7 @@ class EnumMeta(type):
# a custom __new__ is doing something funky with the values -- such as
# auto-numbering ;)
for member_name in classdict._member_names:
- value = members[member_name]
+ value = enum_members[member_name]
if not isinstance(value, tuple):
args = (value, )
else:
@@ -159,7 +198,10 @@ class EnumMeta(type):
else:
enum_member = __new__(enum_class, *args)
if not hasattr(enum_member, '_value_'):
- enum_member._value_ = member_type(*args)
+ if member_type is object:
+ enum_member._value_ = value
+ else:
+ enum_member._value_ = member_type(*args)
value = enum_member._value_
enum_member._name_ = member_name
enum_member.__objclass__ = enum_class
@@ -204,6 +246,14 @@ class EnumMeta(type):
if save_new:
enum_class.__new_member__ = __new__
enum_class.__new__ = Enum.__new__
+
+ # py3 support for definition order (helps keep py2/py3 code in sync)
+ if _order_ is not None:
+ if isinstance(_order_, str):
+ _order_ = _order_.replace(',', ' ').split()
+ if _order_ != enum_class._member_names_:
+ raise TypeError('member order does not match _order_')
+
return enum_class
def __bool__(self):
@@ -217,7 +267,7 @@ class EnumMeta(type):
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
- (i.e. Color = Enum('Color', names='red green blue')).
+ (i.e. Color = Enum('Color', names='RED GREEN BLUE')).
When used for the functional API:
@@ -325,13 +375,19 @@ class EnumMeta(type):
"""
metacls = cls.__class__
bases = (cls, ) if type is None else (type, cls)
+ _, first_enum = cls._get_mixins_(bases)
classdict = metacls.__prepare__(class_name, bases)
# special processing needed for names?
if isinstance(names, str):
names = names.replace(',', ' ').split()
if isinstance(names, (tuple, list)) and isinstance(names[0], str):
- names = [(e, i) for (i, e) in enumerate(names, start)]
+ original_names, names = names, []
+ last_values = []
+ for count, name in enumerate(original_names):
+ value = first_enum._generate_next_value_(name, start, count, last_values[:])
+ last_values.append(value)
+ names.append((name, value))
# Here, names is either an iterable of (name, value) or a mapping.
for item in names:
@@ -461,7 +517,7 @@ class Enum(metaclass=EnumMeta):
# without calling this method; this method is called by the metaclass'
# __call__ (i.e. Color(3) ), and by pickle
if type(value) is cls:
- # For lookups like Color(Color.red)
+ # For lookups like Color(Color.RED)
return value
# by-value search for a matching enum member
# see if it's in the reverse mapping (for hashable values)
@@ -473,6 +529,20 @@ class Enum(metaclass=EnumMeta):
for member in cls._member_map_.values():
if member._value_ == value:
return member
+ # still not found -- try _missing_ hook
+ return cls._missing_(value)
+
+ def _generate_next_value_(name, start, count, last_values):
+ for last_value in reversed(last_values):
+ try:
+ return last_value + 1
+ except TypeError:
+ pass
+ else:
+ return start
+
+ @classmethod
+ def _missing_(cls, value):
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
def __repr__(self):
@@ -544,8 +614,21 @@ class Enum(metaclass=EnumMeta):
source = vars(source)
else:
source = module_globals
- members = {name: value for name, value in source.items()
- if filter(name)}
+ # We use an OrderedDict of sorted source keys so that the
+ # _value2member_map is populated in the same order every time
+ # for a consistent reverse mapping of number to name when there
+ # are multiple names for the same number rather than varying
+ # between runs due to hash randomization of the module dictionary.
+ members = [
+ (name, source[name])
+ for name in source.keys()
+ if filter(name)]
+ try:
+ # sort by value
+ members.sort(key=lambda t: (t[1], t[0]))
+ except TypeError:
+ # unless some values aren't comparable, in which case sort by name
+ members.sort(key=lambda t: t[0])
cls = cls(name, members, module=module)
cls.__reduce_ex__ = _reduce_ex_by_name
module_globals.update(cls.__members__)
@@ -560,6 +643,180 @@ class IntEnum(int, Enum):
def _reduce_ex_by_name(self, proto):
return self.name
+class Flag(Enum):
+ """Support for flags"""
+
+ def _generate_next_value_(name, start, count, last_values):
+ """
+ Generate the next value when not given.
+
+ name: the name of the member
+ start: the initital start value or None
+ count: the number of existing members
+ last_value: the last value assigned or None
+ """
+ if not count:
+ return start if start is not None else 1
+ for last_value in reversed(last_values):
+ try:
+ high_bit = _high_bit(last_value)
+ break
+ except Exception:
+ raise TypeError('Invalid Flag value: %r' % last_value) from None
+ return 2 ** (high_bit+1)
+
+ @classmethod
+ def _missing_(cls, value):
+ original_value = value
+ if value < 0:
+ value = ~value
+ possible_member = cls._create_pseudo_member_(value)
+ if original_value < 0:
+ possible_member = ~possible_member
+ return possible_member
+
+ @classmethod
+ def _create_pseudo_member_(cls, value):
+ """
+ Create a composite member iff value contains only members.
+ """
+ pseudo_member = cls._value2member_map_.get(value, None)
+ if pseudo_member is None:
+ # verify all bits are accounted for
+ _, extra_flags = _decompose(cls, value)
+ if extra_flags:
+ raise ValueError("%r is not a valid %s" % (value, cls.__name__))
+ # construct a singleton enum pseudo-member
+ pseudo_member = object.__new__(cls)
+ pseudo_member._name_ = None
+ pseudo_member._value_ = value
+ cls._value2member_map_[value] = pseudo_member
+ return pseudo_member
+
+ def __contains__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+ return other._value_ & self._value_ == other._value_
+
+ def __repr__(self):
+ cls = self.__class__
+ if self._name_ is not None:
+ return '<%s.%s: %r>' % (cls.__name__, self._name_, self._value_)
+ members, uncovered = _decompose(cls, self._value_)
+ return '<%s.%s: %r>' % (
+ cls.__name__,
+ '|'.join([str(m._name_ or m._value_) for m in members]),
+ self._value_,
+ )
+
+ def __str__(self):
+ cls = self.__class__
+ if self._name_ is not None:
+ return '%s.%s' % (cls.__name__, self._name_)
+ members, uncovered = _decompose(cls, self._value_)
+ if len(members) == 1 and members[0]._name_ is None:
+ return '%s.%r' % (cls.__name__, members[0]._value_)
+ else:
+ return '%s.%s' % (
+ cls.__name__,
+ '|'.join([str(m._name_ or m._value_) for m in members]),
+ )
+
+ def __bool__(self):
+ return bool(self._value_)
+
+ def __or__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+ return self.__class__(self._value_ | other._value_)
+
+ def __and__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+ return self.__class__(self._value_ & other._value_)
+
+ def __xor__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+ return self.__class__(self._value_ ^ other._value_)
+
+ def __invert__(self):
+ members, uncovered = _decompose(self.__class__, self._value_)
+ inverted_members = [
+ m for m in self.__class__
+ if m not in members and not m._value_ & self._value_
+ ]
+ inverted = reduce(_or_, inverted_members, self.__class__(0))
+ return self.__class__(inverted)
+
+
+class IntFlag(int, Flag):
+ """Support for integer-based Flags"""
+
+ @classmethod
+ def _missing_(cls, value):
+ if not isinstance(value, int):
+ raise ValueError("%r is not a valid %s" % (value, cls.__name__))
+ new_member = cls._create_pseudo_member_(value)
+ return new_member
+
+ @classmethod
+ def _create_pseudo_member_(cls, value):
+ pseudo_member = cls._value2member_map_.get(value, None)
+ if pseudo_member is None:
+ need_to_create = [value]
+ # get unaccounted for bits
+ _, extra_flags = _decompose(cls, value)
+ # timer = 10
+ while extra_flags:
+ # timer -= 1
+ bit = _high_bit(extra_flags)
+ flag_value = 2 ** bit
+ if (flag_value not in cls._value2member_map_ and
+ flag_value not in need_to_create
+ ):
+ need_to_create.append(flag_value)
+ if extra_flags == -flag_value:
+ extra_flags = 0
+ else:
+ extra_flags ^= flag_value
+ for value in reversed(need_to_create):
+ # construct singleton pseudo-members
+ pseudo_member = int.__new__(cls, value)
+ pseudo_member._name_ = None
+ pseudo_member._value_ = value
+ cls._value2member_map_[value] = pseudo_member
+ return pseudo_member
+
+ def __or__(self, other):
+ if not isinstance(other, (self.__class__, int)):
+ return NotImplemented
+ result = self.__class__(self._value_ | self.__class__(other)._value_)
+ return result
+
+ def __and__(self, other):
+ if not isinstance(other, (self.__class__, int)):
+ return NotImplemented
+ return self.__class__(self._value_ & self.__class__(other)._value_)
+
+ def __xor__(self, other):
+ if not isinstance(other, (self.__class__, int)):
+ return NotImplemented
+ return self.__class__(self._value_ ^ self.__class__(other)._value_)
+
+ __ror__ = __or__
+ __rand__ = __and__
+ __rxor__ = __xor__
+
+ def __invert__(self):
+ result = self.__class__(~self._value_)
+ return result
+
+
+def _high_bit(value):
+ """returns index of highest bit, or -1 if value is zero or negative"""
+ return value.bit_length() - 1
+
def unique(enumeration):
"""Class decorator for enumerations ensuring unique member values."""
duplicates = []
@@ -572,3 +829,40 @@ def unique(enumeration):
raise ValueError('duplicate values found in %r: %s' %
(enumeration, alias_details))
return enumeration
+
+def _decompose(flag, value):
+ """Extract all members from the value."""
+ # _decompose is only called if the value is not named
+ not_covered = value
+ negative = value < 0
+ if negative:
+ # only check for named flags
+ flags_to_check = [
+ (m, v)
+ for v, m in flag._value2member_map_.items()
+ if m.name is not None
+ ]
+ else:
+ # check for named flags and powers-of-two flags
+ flags_to_check = [
+ (m, v)
+ for v, m in flag._value2member_map_.items()
+ if m.name is not None or _power_of_two(v)
+ ]
+ members = []
+ for member, member_value in flags_to_check:
+ if member_value and member_value & value == member_value:
+ members.append(member)
+ not_covered &= ~member_value
+ if not members and value in flag._value2member_map_:
+ members.append(flag._value2member_map_[value])
+ members.sort(key=lambda m: m._value_, reverse=True)
+ if len(members) > 1 and members[0].value == value:
+ # we have the breakdown, don't need the value member itself
+ members.pop(0)
+ return members, not_covered
+
+def _power_of_two(value):
+ if value < 1:
+ return False
+ return value == 2 ** _high_bit(value)
diff --git a/Lib/fileinput.py b/Lib/fileinput.py
index d2b5206..721fe9c 100644
--- a/Lib/fileinput.py
+++ b/Lib/fileinput.py
@@ -75,13 +75,11 @@ XXX Possible additions:
import sys, os
__all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno",
- "isfirstline", "isstdin", "FileInput"]
+ "fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed",
+ "hook_encoded"]
_state = None
-# No longer used
-DEFAULT_BUFSIZE = 8*1024
-
def input(files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
"""Return an instance of the FileInput class, which can be iterated.
@@ -201,6 +199,10 @@ class FileInput:
self._files = files
self._inplace = inplace
self._backup = backup
+ if bufsize:
+ import warnings
+ warnings.warn('bufsize is deprecated and ignored',
+ DeprecationWarning, stacklevel=2)
self._savestdout = None
self._output = None
self._filename = None
@@ -398,9 +400,9 @@ def hook_compressed(filename, mode):
return open(filename, mode)
-def hook_encoded(encoding):
+def hook_encoded(encoding, errors=None):
def openhook(filename, mode):
- return open(filename, mode, encoding=encoding)
+ return open(filename, mode, encoding=encoding, errors=errors)
return openhook
diff --git a/Lib/fnmatch.py b/Lib/fnmatch.py
index 6330b0c..fd3b514 100644
--- a/Lib/fnmatch.py
+++ b/Lib/fnmatch.py
@@ -106,4 +106,4 @@ def translate(pat):
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
- return res + '\Z(?ms)'
+ return r'(?s:%s)\Z' % res
diff --git a/Lib/fractions.py b/Lib/fractions.py
index 9aabab3..8330202 100644
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -81,7 +81,7 @@ class Fraction(numbers.Rational):
__slots__ = ('_numerator', '_denominator')
# We're immutable, so use __new__ not __init__
- def __new__(cls, numerator=0, denominator=None, _normalize=True):
+ def __new__(cls, numerator=0, denominator=None, *, _normalize=True):
"""Constructs a Rational.
Takes a string like '3/2' or '1.5', another Rational instance, a
@@ -125,17 +125,9 @@ class Fraction(numbers.Rational):
self._denominator = numerator.denominator
return self
- elif isinstance(numerator, float):
- # Exact conversion from float
- value = Fraction.from_float(numerator)
- self._numerator = value._numerator
- self._denominator = value._denominator
- return self
-
- elif isinstance(numerator, Decimal):
- value = Fraction.from_decimal(numerator)
- self._numerator = value._numerator
- self._denominator = value._denominator
+ elif isinstance(numerator, (float, Decimal)):
+ # Exact conversion
+ self._numerator, self._denominator = numerator.as_integer_ratio()
return self
elif isinstance(numerator, str):
@@ -210,10 +202,6 @@ class Fraction(numbers.Rational):
elif not isinstance(f, float):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
- if math.isnan(f):
- raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
- if math.isinf(f):
- raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
return cls(*f.as_integer_ratio())
@classmethod
@@ -226,19 +214,7 @@ class Fraction(numbers.Rational):
raise TypeError(
"%s.from_decimal() only takes Decimals, not %r (%s)" %
(cls.__name__, dec, type(dec).__name__))
- if dec.is_infinite():
- raise OverflowError(
- "Cannot convert %s to %s." % (dec, cls.__name__))
- if dec.is_nan():
- raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__))
- sign, digits, exp = dec.as_tuple()
- digits = int(''.join(map(str, digits)))
- if sign:
- digits = -digits
- if exp >= 0:
- return cls(digits * 10 ** exp)
- else:
- return cls(digits, 10 ** -exp)
+ return cls(*dec.as_integer_ratio())
def limit_denominator(self, max_denominator=1000000):
"""Closest Fraction to self with denominator at most max_denominator.
diff --git a/Lib/ftplib.py b/Lib/ftplib.py
index c416d85..8f36f53 100644
--- a/Lib/ftplib.py
+++ b/Lib/ftplib.py
@@ -36,13 +36,12 @@ python ftplib.py -d localhost -l -p -l
# Modified by Giampaolo Rodola' to add TLS support.
#
-import os
import sys
import socket
-import warnings
from socket import _GLOBAL_DEFAULT_TIMEOUT
-__all__ = ["FTP"]
+__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto",
+ "all_errors"]
# Magic number from <socket.h>
MSG_OOB = 0x1 # Process data out of band
@@ -729,6 +728,10 @@ else:
if context is not None and certfile is not None:
raise ValueError("context and certfile arguments are mutually "
"exclusive")
+ if keyfile is not None or certfile is not None:
+ import warnings
+ warnings.warn("keyfile and certfile are deprecated, use a"
+ "custom context instead", DeprecationWarning, 2)
self.keyfile = keyfile
self.certfile = certfile
if context is None:
@@ -822,7 +825,7 @@ def parse150(resp):
if _150_re is None:
import re
_150_re = re.compile(
- "150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
+ r"150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
m = _150_re.match(resp)
if not m:
return None
diff --git a/Lib/functools.py b/Lib/functools.py
index 60cf3c4..45e5f87 100644
--- a/Lib/functools.py
+++ b/Lib/functools.py
@@ -21,6 +21,7 @@ from abc import get_cache_token
from collections import namedtuple
from types import MappingProxyType
from weakref import WeakKeyDictionary
+from reprlib import recursive_repr
try:
from _thread import RLock
except ImportError:
@@ -237,26 +238,83 @@ except ImportError:
################################################################################
# Purely functional, no descriptor behaviour
-def partial(func, *args, **keywords):
+class partial:
"""New function with partial application of the given arguments
and keywords.
"""
- if hasattr(func, 'func'):
- args = func.args + args
- tmpkw = func.keywords.copy()
- tmpkw.update(keywords)
- keywords = tmpkw
- del tmpkw
- func = func.func
-
- def newfunc(*fargs, **fkeywords):
- newkeywords = keywords.copy()
- newkeywords.update(fkeywords)
- return func(*(args + fargs), **newkeywords)
- newfunc.func = func
- newfunc.args = args
- newfunc.keywords = keywords
- return newfunc
+
+ __slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
+
+ def __new__(*args, **keywords):
+ if not args:
+ raise TypeError("descriptor '__new__' of partial needs an argument")
+ if len(args) < 2:
+ raise TypeError("type 'partial' takes at least one argument")
+ cls, func, *args = args
+ if not callable(func):
+ raise TypeError("the first argument must be callable")
+ args = tuple(args)
+
+ if hasattr(func, "func"):
+ args = func.args + args
+ tmpkw = func.keywords.copy()
+ tmpkw.update(keywords)
+ keywords = tmpkw
+ del tmpkw
+ func = func.func
+
+ self = super(partial, cls).__new__(cls)
+
+ self.func = func
+ self.args = args
+ self.keywords = keywords
+ return self
+
+ def __call__(*args, **keywords):
+ if not args:
+ raise TypeError("descriptor '__call__' of partial needs an argument")
+ self, *args = args
+ newkeywords = self.keywords.copy()
+ newkeywords.update(keywords)
+ return self.func(*self.args, *args, **newkeywords)
+
+ @recursive_repr()
+ def __repr__(self):
+ qualname = type(self).__qualname__
+ args = [repr(self.func)]
+ args.extend(repr(x) for x in self.args)
+ args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
+ if type(self).__module__ == "functools":
+ return f"functools.{qualname}({', '.join(args)})"
+ return f"{qualname}({', '.join(args)})"
+
+ def __reduce__(self):
+ return type(self), (self.func,), (self.func, self.args,
+ self.keywords or None, self.__dict__ or None)
+
+ def __setstate__(self, state):
+ if not isinstance(state, tuple):
+ raise TypeError("argument to __setstate__ must be a tuple")
+ if len(state) != 4:
+ raise TypeError(f"expected 4 items in state, got {len(state)}")
+ func, args, kwds, namespace = state
+ if (not callable(func) or not isinstance(args, tuple) or
+ (kwds is not None and not isinstance(kwds, dict)) or
+ (namespace is not None and not isinstance(namespace, dict))):
+ raise TypeError("invalid partial state")
+
+ args = tuple(args) # just in case it's a subclass
+ if kwds is None:
+ kwds = {}
+ elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
+ kwds = dict(kwds)
+ if namespace is None:
+ namespace = {}
+
+ self.__dict__ = namespace
+ self.func = func
+ self.args = args
+ self.keywords = kwds
try:
from _functools import partial
diff --git a/Lib/genericpath.py b/Lib/genericpath.py
index 6714061..303b3b3 100644
--- a/Lib/genericpath.py
+++ b/Lib/genericpath.py
@@ -69,6 +69,12 @@ def getctime(filename):
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
+ # Some people pass in a list of pathname parts to operate in an OS-agnostic
+ # fashion; don't try to translate in that case as that's an abuse of the
+ # API and they are already doing what they need to be OS-agnostic and so
+ # they most likely won't be using an os.PathLike object in the sublists.
+ if not isinstance(m[0], (list, tuple)):
+ m = tuple(map(os.fspath, m))
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
diff --git a/Lib/glob.py b/Lib/glob.py
index 16330d8..002cd92 100644
--- a/Lib/glob.py
+++ b/Lib/glob.py
@@ -30,15 +30,16 @@ def iglob(pathname, *, recursive=False):
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
- it = _iglob(pathname, recursive)
+ it = _iglob(pathname, recursive, False)
if recursive and _isrecursive(pathname):
s = next(it) # skip empty string
assert not s
return it
-def _iglob(pathname, recursive):
+def _iglob(pathname, recursive, dironly):
dirname, basename = os.path.split(pathname)
if not has_magic(pathname):
+ assert not dironly
if basename:
if os.path.lexists(pathname):
yield pathname
@@ -49,47 +50,39 @@ def _iglob(pathname, recursive):
return
if not dirname:
if recursive and _isrecursive(basename):
- yield from glob2(dirname, basename)
+ yield from _glob2(dirname, basename, dironly)
else:
- yield from glob1(dirname, basename)
+ yield from _glob1(dirname, basename, dironly)
return
# `os.path.split()` returns the argument itself as a dirname if it is a
# drive or UNC path. Prevent an infinite recursion if a drive or UNC path
# contains magic characters (i.e. r'\\?\C:').
if dirname != pathname and has_magic(dirname):
- dirs = _iglob(dirname, recursive)
+ dirs = _iglob(dirname, recursive, True)
else:
dirs = [dirname]
if has_magic(basename):
if recursive and _isrecursive(basename):
- glob_in_dir = glob2
+ glob_in_dir = _glob2
else:
- glob_in_dir = glob1
+ glob_in_dir = _glob1
else:
- glob_in_dir = glob0
+ glob_in_dir = _glob0
for dirname in dirs:
- for name in glob_in_dir(dirname, basename):
+ for name in glob_in_dir(dirname, basename, dironly):
yield os.path.join(dirname, name)
# These 2 helper functions non-recursively glob inside a literal directory.
-# They return a list of basenames. `glob1` accepts a pattern while `glob0`
+# They return a list of basenames. _glob1 accepts a pattern while _glob0
# takes a literal basename (so it only has to check for its existence).
-def glob1(dirname, pattern):
- if not dirname:
- if isinstance(pattern, bytes):
- dirname = bytes(os.curdir, 'ASCII')
- else:
- dirname = os.curdir
- try:
- names = os.listdir(dirname)
- except OSError:
- return []
+def _glob1(dirname, pattern, dironly):
+ names = list(_iterdir(dirname, dironly))
if not _ishidden(pattern):
- names = [x for x in names if not _ishidden(x)]
+ names = (x for x in names if not _ishidden(x))
return fnmatch.filter(names, pattern)
-def glob0(dirname, basename):
+def _glob0(dirname, basename, dironly):
if not basename:
# `os.path.split()` returns an empty basename for paths ending with a
# directory separator. 'q*x/' should match only directories.
@@ -100,30 +93,49 @@ def glob0(dirname, basename):
return [basename]
return []
+# Following functions are not public but can be used by third-party code.
+
+def glob0(dirname, pattern):
+ return _glob0(dirname, pattern, False)
+
+def glob1(dirname, pattern):
+ return _glob1(dirname, pattern, False)
+
# This helper function recursively yields relative pathnames inside a literal
# directory.
-def glob2(dirname, pattern):
+def _glob2(dirname, pattern, dironly):
assert _isrecursive(pattern)
yield pattern[:0]
- yield from _rlistdir(dirname)
+ yield from _rlistdir(dirname, dironly)
-# Recursively yields relative pathnames inside a literal directory.
-def _rlistdir(dirname):
+# If dironly is false, yields all file names inside a directory.
+# If dironly is true, yields only directory names.
+def _iterdir(dirname, dironly):
if not dirname:
if isinstance(dirname, bytes):
dirname = bytes(os.curdir, 'ASCII')
else:
dirname = os.curdir
try:
- names = os.listdir(dirname)
- except os.error:
+ with os.scandir(dirname) as it:
+ for entry in it:
+ try:
+ if not dironly or entry.is_dir():
+ yield entry.name
+ except OSError:
+ pass
+ except OSError:
return
+
+# Recursively yields relative pathnames inside a literal directory.
+def _rlistdir(dirname, dironly):
+ names = list(_iterdir(dirname, dironly))
for x in names:
if not _ishidden(x):
yield x
path = os.path.join(dirname, x) if dirname else x
- for y in _rlistdir(path):
+ for y in _rlistdir(path, dironly):
yield os.path.join(x, y)
diff --git a/Lib/gzip.py b/Lib/gzip.py
index da4479e..76ab497 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -49,7 +49,7 @@ def open(filename, mode="rb", compresslevel=9,
raise ValueError("Argument 'newline' not supported in binary mode")
gz_mode = mode.replace("t", "")
- if isinstance(filename, (str, bytes)):
+ if isinstance(filename, (str, bytes, os.PathLike)):
binary_file = GzipFile(filename, gz_mode, compresslevel)
elif hasattr(filename, "read") or hasattr(filename, "write"):
binary_file = GzipFile(None, gz_mode, compresslevel, filename)
@@ -165,6 +165,8 @@ class GzipFile(_compression.BaseStream):
filename = getattr(fileobj, 'name', '')
if not isinstance(filename, (str, bytes)):
filename = ''
+ else:
+ filename = os.fspath(filename)
if mode is None:
mode = getattr(fileobj, 'mode', 'rb')
@@ -357,10 +359,10 @@ class GzipFile(_compression.BaseStream):
if offset < self.offset:
raise OSError('Negative seek in write mode')
count = offset - self.offset
- chunk = bytes(1024)
+ chunk = b'\0' * 1024
for i in range(count // 1024):
self.write(chunk)
- self.write(bytes(count % 1024))
+ self.write(b'\0' * (count % 1024))
elif self.mode == READ:
self._check_not_closed()
return self._buffer.seek(offset, whence)
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
index 316cece..053a7ad 100644
--- a/Lib/hashlib.py
+++ b/Lib/hashlib.py
@@ -4,14 +4,15 @@
__doc__ = """hashlib module - A common interface to many hash functions.
-new(name, data=b'') - returns a new hash object implementing the
- given hash function; initializing the hash
- using the given binary data.
+new(name, data=b'', **kwargs) - returns a new hash object implementing the
+ given hash function; initializing the hash
+ using the given binary data.
Named constructor functions are also available, these are faster
than using new(name):
-md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
+md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(),
+sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256.
More algorithms may be available on your platform but the above are guaranteed
to exist. See the algorithms_guaranteed and algorithms_available attributes
@@ -54,7 +55,11 @@ More condensed:
# This tuple and __get_builtin_constructor() must be modified if a new
# always available algorithm is added.
-__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
+__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
+ 'blake2b', 'blake2s',
+ 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
+ 'shake_128', 'shake_256')
+
algorithms_guaranteed = set(__always_supported)
algorithms_available = set(__always_supported)
@@ -85,6 +90,19 @@ def __get_builtin_constructor(name):
import _sha512
cache['SHA384'] = cache['sha384'] = _sha512.sha384
cache['SHA512'] = cache['sha512'] = _sha512.sha512
+ elif name in ('blake2b', 'blake2s'):
+ import _blake2
+ cache['blake2b'] = _blake2.blake2b
+ cache['blake2s'] = _blake2.blake2s
+ elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
+ 'shake_128', 'shake_256'}:
+ import _sha3
+ cache['sha3_224'] = _sha3.sha3_224
+ cache['sha3_256'] = _sha3.sha3_256
+ cache['sha3_384'] = _sha3.sha3_384
+ cache['sha3_512'] = _sha3.sha3_512
+ cache['shake_128'] = _sha3.shake_128
+ cache['shake_256'] = _sha3.shake_256
except ImportError:
pass # no extension module, this hash is unsupported.
@@ -96,6 +114,9 @@ def __get_builtin_constructor(name):
def __get_openssl_constructor(name):
+ if name in {'blake2b', 'blake2s'}:
+ # Prefer our blake2 implementation.
+ return __get_builtin_constructor(name)
try:
f = getattr(_hashlib, 'openssl_' + name)
# Allow the C module to raise ValueError. The function will be
@@ -107,17 +128,23 @@ def __get_openssl_constructor(name):
return __get_builtin_constructor(name)
-def __py_new(name, data=b''):
- """new(name, data=b'') - Return a new hashing object using the named algorithm;
- optionally initialized with data (which must be bytes).
+def __py_new(name, data=b'', **kwargs):
+ """new(name, data=b'', **kwargs) - Return a new hashing object using the
+ named algorithm; optionally initialized with data (which must be bytes).
"""
- return __get_builtin_constructor(name)(data)
+ return __get_builtin_constructor(name)(data, **kwargs)
-def __hash_new(name, data=b''):
+def __hash_new(name, data=b'', **kwargs):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be bytes).
"""
+ if name in {'blake2b', 'blake2s'}:
+ # Prefer our blake2 implementation.
+ # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s.
+ # It does neither support keyed blake2 nor advanced features like
+ # salt, personal, tree hashing or SSE.
+ return __get_builtin_constructor(name)(data, **kwargs)
try:
return _hashlib.new(name, data)
except ValueError:
@@ -202,6 +229,12 @@ except ImportError:
return dkey[:dklen]
+try:
+ # OpenSSL's scrypt requires OpenSSL 1.1+
+ from _hashlib import scrypt
+except ImportError:
+ pass
+
for __func_name in __always_supported:
# try them all, some may not work due to the OpenSSL
@@ -212,6 +245,7 @@ for __func_name in __always_supported:
import logging
logging.exception('code for hash %s was not found.', __func_name)
+
# Cleanup locals()
del __always_supported, __func_name, __get_hash
del __py_new, __hash_new, __get_openssl_constructor
diff --git a/Lib/hmac.py b/Lib/hmac.py
index 77785a2..121029a 100644
--- a/Lib/hmac.py
+++ b/Lib/hmac.py
@@ -77,7 +77,7 @@ class HMAC:
if len(key) > blocksize:
key = self.digest_cons(key).digest()
- key = key + bytes(blocksize - len(key))
+ key = key.ljust(blocksize, b'\0')
self.outer.update(key.translate(trans_5C))
self.inner.update(key.translate(trans_36))
if msg is not None:
diff --git a/Lib/html/parser.py b/Lib/html/parser.py
index b781c63..ef869bc 100644
--- a/Lib/html/parser.py
+++ b/Lib/html/parser.py
@@ -34,7 +34,7 @@ commentclose = re.compile(r'--\s*>')
# explode, so don't do it.
# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
-tagfind_tolerant = re.compile('([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
+tagfind_tolerant = re.compile(r'([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
attrfind_tolerant = re.compile(
r'((?<=[\'"\s/])[^\s/>][^\s/=>]*)(\s*=+\s*'
r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*')
@@ -56,7 +56,7 @@ locatestarttagend_tolerant = re.compile(r"""
endendtag = re.compile('>')
# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
# </ and the tag name, so maybe this should be fixed
-endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
+endtagfind = re.compile(r'</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
diff --git a/Lib/http/client.py b/Lib/http/client.py
index 352c101..a8e59b9 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -1,4 +1,4 @@
-"""HTTP/1.1 client library
+r"""HTTP/1.1 client library
<intro stuff goes here>
<other stuff, too>
@@ -420,6 +420,7 @@ class HTTPResponse(io.BufferedIOBase):
self.fp.flush()
def readable(self):
+ """Always returns True"""
return True
# End of "raw stream" methods
@@ -467,6 +468,10 @@ class HTTPResponse(io.BufferedIOBase):
return s
def readinto(self, b):
+ """Read up to len(b) bytes into bytearray b and return the number
+ of bytes read.
+ """
+
if self.fp is None:
return 0
@@ -706,6 +711,17 @@ class HTTPResponse(io.BufferedIOBase):
return self.fp.fileno()
def getheader(self, name, default=None):
+ '''Returns the value of the header matching *name*.
+
+ If there are multiple matching headers, the values are
+ combined into a single string separated by commas and spaces.
+
+ If no matching header is found, returns *default* or None if
+ the *default* is not specified.
+
+ If the headers are unknown, raises http.client.ResponseNotReady.
+
+ '''
if self.headers is None:
raise ResponseNotReady()
headers = self.headers.get_all(name) or default
@@ -728,12 +744,45 @@ class HTTPResponse(io.BufferedIOBase):
# For compatibility with old-style urllib responses.
def info(self):
+ '''Returns an instance of the class mimetools.Message containing
+ meta-information associated with the URL.
+
+ When the method is HTTP, these headers are those returned by
+ the server at the head of the retrieved HTML page (including
+ Content-Length and Content-Type).
+
+ When the method is FTP, a Content-Length header will be
+ present if (as is now usual) the server passed back a file
+ length in response to the FTP retrieval request. A
+ Content-Type header will be present if the MIME type can be
+ guessed.
+
+ When the method is local-file, returned headers will include
+ a Date representing the file's last-modified time, a
+ Content-Length giving file size, and a Content-Type
+ containing a guess at the file's type. See also the
+ description of the mimetools module.
+
+ '''
return self.headers
def geturl(self):
+ '''Return the real URL of the page.
+
+ In some cases, the HTTP server redirects a client to another
+ URL. The urlopen() function handles this transparently, but in
+ some cases the caller needs to know which URL the client was
+ redirected to. The geturl() method can be used to get at this
+ redirected URL.
+
+ '''
return self.url
def getcode(self):
+ '''Return the HTTP status code that was sent with the response,
+ or None if the URL is not an HTTP URL.
+
+ '''
return self.status
class HTTPConnection:
@@ -746,6 +795,44 @@ class HTTPConnection:
auto_open = 1
debuglevel = 0
+ @staticmethod
+ def _is_textIO(stream):
+ """Test whether a file-like object is a text or a binary stream.
+ """
+ return isinstance(stream, io.TextIOBase)
+
+ @staticmethod
+ def _get_content_length(body, method):
+ """Get the content-length based on the body.
+
+ If the body is None, we set Content-Length: 0 for methods that expect
+ a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
+ any method if the body is a str or bytes-like object and not a file.
+ """
+ if body is None:
+ # do an explicit check for not None here to distinguish
+ # between unset and set but empty
+ if method.upper() in _METHODS_EXPECTING_BODY:
+ return 0
+ else:
+ return None
+
+ if hasattr(body, 'read'):
+ # file-like object.
+ return None
+
+ try:
+ # does it implement the buffer protocol (bytes, bytearray, array)?
+ mv = memoryview(body)
+ return mv.nbytes
+ except TypeError:
+ pass
+
+ if isinstance(body, str):
+ return len(body)
+
+ return None
+
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
self.timeout = timeout
@@ -884,18 +971,9 @@ class HTTPConnection:
if hasattr(data, "read") :
if self.debuglevel > 0:
print("sendIng a read()able")
- encode = False
- try:
- mode = data.mode
- except AttributeError:
- # io.BytesIO and other file-like objects don't have a `mode`
- # attribute.
- pass
- else:
- if "b" not in mode:
- encode = True
- if self.debuglevel > 0:
- print("encoding file using iso-8859-1")
+ encode = self._is_textIO(data)
+ if encode and self.debuglevel > 0:
+ print("encoding file using iso-8859-1")
while 1:
datablock = data.read(blocksize)
if not datablock:
@@ -921,7 +999,22 @@ class HTTPConnection:
"""
self._buffer.append(s)
- def _send_output(self, message_body=None):
+ def _read_readable(self, readable):
+ blocksize = 8192
+ if self.debuglevel > 0:
+ print("sendIng a read()able")
+ encode = self._is_textIO(readable)
+ if encode and self.debuglevel > 0:
+ print("encoding file using iso-8859-1")
+ while True:
+ datablock = readable.read(blocksize)
+ if not datablock:
+ break
+ if encode:
+ datablock = datablock.encode("iso-8859-1")
+ yield datablock
+
+ def _send_output(self, message_body=None, encode_chunked=False):
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
@@ -930,10 +1023,50 @@ class HTTPConnection:
self._buffer.extend((b"", b""))
msg = b"\r\n".join(self._buffer)
del self._buffer[:]
-
self.send(msg)
+
if message_body is not None:
- self.send(message_body)
+
+ # create a consistent interface to message_body
+ if hasattr(message_body, 'read'):
+ # Let file-like take precedence over byte-like. This
+ # is needed to allow the current position of mmap'ed
+ # files to be taken into account.
+ chunks = self._read_readable(message_body)
+ else:
+ try:
+ # this is solely to check to see if message_body
+ # implements the buffer API. it /would/ be easier
+ # to capture if PyObject_CheckBuffer was exposed
+ # to Python.
+ memoryview(message_body)
+ except TypeError:
+ try:
+ chunks = iter(message_body)
+ except TypeError:
+ raise TypeError("message_body should be a bytes-like "
+ "object or an iterable, got %r"
+ % type(message_body))
+ else:
+ # the object implements the buffer interface and
+ # can be passed directly into socket methods
+ chunks = (message_body,)
+
+ for chunk in chunks:
+ if not chunk:
+ if self.debuglevel > 0:
+ print('Zero length chunk ignored')
+ continue
+
+ if encode_chunked and self._http_vsn == 11:
+ # chunked encoding
+ chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
+ + b'\r\n'
+ self.send(chunk)
+
+ if encode_chunked and self._http_vsn == 11:
+ # end chunked transfer
+ self.send(b'0\r\n\r\n')
def putrequest(self, method, url, skip_host=False,
skip_accept_encoding=False):
@@ -1087,52 +1220,27 @@ class HTTPConnection:
header = header + b': ' + value
self._output(header)
- def endheaders(self, message_body=None):
+ def endheaders(self, message_body=None, *, encode_chunked=False):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
- request. The message body will be sent in the same packet as the
- message headers if it is a string, otherwise it is sent as a separate
- packet.
+ request.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
- self._send_output(message_body)
+ self._send_output(message_body, encode_chunked=encode_chunked)
- def request(self, method, url, body=None, headers={}):
+ def request(self, method, url, body=None, headers={}, *,
+ encode_chunked=False):
"""Send a complete request to the server."""
- self._send_request(method, url, body, headers)
-
- def _set_content_length(self, body, method):
- # Set the content-length based on the body. If the body is "empty", we
- # set Content-Length: 0 for methods that expect a body (RFC 7230,
- # Section 3.3.2). If the body is set for other methods, we set the
- # header provided we can figure out what the length is.
- thelen = None
- method_expects_body = method.upper() in _METHODS_EXPECTING_BODY
- if body is None and method_expects_body:
- thelen = '0'
- elif body is not None:
- try:
- thelen = str(len(body))
- except TypeError:
- # If this is a file-like object, try to
- # fstat its file descriptor
- try:
- thelen = str(os.fstat(body.fileno()).st_size)
- except (AttributeError, OSError):
- # Don't send a length if this failed
- if self.debuglevel > 0: print("Cannot stat!!")
-
- if thelen is not None:
- self.putheader('Content-Length', thelen)
+ self._send_request(method, url, body, headers, encode_chunked)
- def _send_request(self, method, url, body, headers):
+ def _send_request(self, method, url, body, headers, encode_chunked):
# Honor explicitly requested Host: and Accept-Encoding: headers.
- header_names = dict.fromkeys([k.lower() for k in headers])
+ header_names = frozenset(k.lower() for k in headers)
skips = {}
if 'host' in header_names:
skips['skip_host'] = 1
@@ -1141,15 +1249,40 @@ class HTTPConnection:
self.putrequest(method, url, **skips)
+ # chunked encoding will happen if HTTP/1.1 is used and either
+ # the caller passes encode_chunked=True or the following
+ # conditions hold:
+ # 1. content-length has not been explicitly set
+ # 2. the body is a file or iterable, but not a str or bytes-like
+ # 3. Transfer-Encoding has NOT been explicitly set by the caller
+
if 'content-length' not in header_names:
- self._set_content_length(body, method)
+ # only chunk body if not explicitly set for backwards
+ # compatibility, assuming the client code is already handling the
+ # chunking
+ if 'transfer-encoding' not in header_names:
+ # if content-length cannot be automatically determined, fall
+ # back to chunked encoding
+ encode_chunked = False
+ content_length = self._get_content_length(body, method)
+ if content_length is None:
+ if body is not None:
+ if self.debuglevel > 0:
+ print('Unable to determine size of %r' % body)
+ encode_chunked = True
+ self.putheader('Transfer-Encoding', 'chunked')
+ else:
+ self.putheader('Content-Length', str(content_length))
+ else:
+ encode_chunked = False
+
for hdr, value in headers.items():
self.putheader(hdr, value)
if isinstance(body, str):
# RFC 2616 Section 3.7.1 says that text default has a
# default charset of iso-8859-1.
body = _encode(body, 'body')
- self.endheaders(body)
+ self.endheaders(body, encode_chunked=encode_chunked)
def getresponse(self):
"""Get the response from the server.
@@ -1232,6 +1365,12 @@ else:
check_hostname=None):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address)
+ if (key_file is not None or cert_file is not None or
+ check_hostname is not None):
+ import warnings
+ warnings.warn("key_file, cert_file and check_hostname are "
+ "deprecated, use a custom context instead.",
+ DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py
index 6d4572a..adf956d 100644
--- a/Lib/http/cookiejar.py
+++ b/Lib/http/cookiejar.py
@@ -200,7 +200,7 @@ def _str2time(day, mon, yr, hr, min, sec, tz):
STRICT_DATE_RE = re.compile(
r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) "
- "(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII)
+ r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII)
WEEKDAY_RE = re.compile(
r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I | re.ASCII)
LOOSE_HTTP_DATE_RE = re.compile(
@@ -277,7 +277,7 @@ def http2time(text):
return _str2time(day, mon, yr, hr, min, sec, tz)
ISO_DATE_RE = re.compile(
- """^
+ r"""^
(\d{4}) # year
[-\/]?
(\d\d?) # numerical month
@@ -411,7 +411,7 @@ def split_header_words(header_values):
pairs = []
else:
# skip junk
- non_junk, nr_junk_chars = re.subn("^[=\s;]*", "", text)
+ non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text)
assert nr_junk_chars > 0, (
"split_header_words bug: '%s', '%s', %s" %
(orig_text, text, pairs))
diff --git a/Lib/http/cookies.py b/Lib/http/cookies.py
index a73fe38..be3b080 100644
--- a/Lib/http/cookies.py
+++ b/Lib/http/cookies.py
@@ -456,9 +456,8 @@ class Morsel(dict):
#
_LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
-_LegalValueChars = _LegalKeyChars + '\[\]'
+_LegalValueChars = _LegalKeyChars + r'\[\]'
_CookiePattern = re.compile(r"""
- (?x) # This is a verbose pattern
\s* # Optional whitespace at start of cookie
(?P<key> # Start of group 'key'
[""" + _LegalKeyChars + r"""]+? # Any word of at least one letter
@@ -475,7 +474,7 @@ _CookiePattern = re.compile(r"""
)? # End of optional value group
\s* # Any number of spaces.
(\s+|;|$) # Ending either at space, semicolon, or EOS.
- """, re.ASCII) # May be removed if safe.
+ """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe.
# At long last, here is the cookie class. Using this class is almost just like
diff --git a/Lib/http/server.py b/Lib/http/server.py
index 00620d1..e12e45b 100644
--- a/Lib/http/server.py
+++ b/Lib/http/server.py
@@ -87,6 +87,7 @@ __all__ = [
"SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
]
+import email.utils
import html
import http.client
import io
@@ -126,9 +127,6 @@ DEFAULT_ERROR_MESSAGE = """\
DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
-def _quote_html(html):
- return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
-
class HTTPServer(socketserver.TCPServer):
allow_reuse_address = 1 # Seems to make sense in testing environment
@@ -136,7 +134,7 @@ class HTTPServer(socketserver.TCPServer):
def server_bind(self):
"""Override server_bind to store the server name."""
socketserver.TCPServer.server_bind(self)
- host, port = self.socket.getsockname()[:2]
+ host, port = self.server_address[:2]
self.server_name = socket.getfqdn(host)
self.server_port = port
@@ -282,12 +280,9 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
words = requestline.split()
if len(words) == 3:
command, path, version = words
- if version[:5] != 'HTTP/':
- self.send_error(
- HTTPStatus.BAD_REQUEST,
- "Bad request version (%r)" % version)
- return False
try:
+ if version[:5] != 'HTTP/':
+ raise ValueError
base_version_number = version.split('/', 1)[1]
version_number = base_version_number.split(".")
# RFC 2145 section 3.1 says there can be only one "." and
@@ -309,7 +304,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
if version_number >= (2, 0):
self.send_error(
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
- "Invalid HTTP Version (%s)" % base_version_number)
+ "Invalid HTTP version (%s)" % base_version_number)
return False
elif len(words) == 2:
command, path = words
@@ -332,10 +327,11 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
try:
self.headers = http.client.parse_headers(self.rfile,
_class=self.MessageClass)
- except http.client.LineTooLong:
+ except http.client.LineTooLong as err:
self.send_error(
- HTTPStatus.BAD_REQUEST,
- "Line too long")
+ HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
+ "Line too long",
+ str(err))
return False
except http.client.HTTPException as err:
self.send_error(
@@ -465,8 +461,8 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
# (see bug #1100201)
content = (self.error_message_format % {
'code': code,
- 'message': _quote_html(message),
- 'explain': _quote_html(explain)
+ 'message': html.escape(message, quote=False),
+ 'explain': html.escape(explain, quote=False)
})
body = content.encode('UTF-8', 'replace')
self.send_header("Content-Type", self.error_content_type)
@@ -491,12 +487,12 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
def send_response_only(self, code, message=None):
"""Send the response header only."""
- if message is None:
- if code in self.responses:
- message = self.responses[code][0]
- else:
- message = ''
if self.request_version != 'HTTP/0.9':
+ if message is None:
+ if code in self.responses:
+ message = self.responses[code][0]
+ else:
+ message = ''
if not hasattr(self, '_headers_buffer'):
self._headers_buffer = []
self._headers_buffer.append(("%s %d %s\r\n" %
@@ -583,12 +579,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timestamp = time.time()
- year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
- s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
- self.weekdayname[wd],
- day, self.monthname[month], year,
- hh, mm, ss)
- return s
+ return email.utils.formatdate(timestamp, usegmt=True)
def log_date_time_string(self):
"""Return the current time formatted for logging."""
@@ -726,7 +717,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
errors='surrogatepass')
except UnicodeDecodeError:
displaypath = urllib.parse.unquote(path)
- displaypath = html.escape(displaypath)
+ displaypath = html.escape(displaypath, quote=False)
enc = sys.getfilesystemencoding()
title = 'Directory listing for %s' % displaypath
r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
@@ -750,7 +741,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
r.append('<li><a href="%s">%s</a></li>'
% (urllib.parse.quote(linkname,
errors='surrogatepass'),
- html.escape(displayname)))
+ html.escape(displayname, quote=False)))
r.append('</ul>\n<hr>\n</body>\n</html>\n')
encoded = '\n'.join(r).encode(enc, 'surrogateescape')
f = io.BytesIO()
@@ -1191,16 +1182,15 @@ def test(HandlerClass=BaseHTTPRequestHandler,
server_address = (bind, port)
HandlerClass.protocol_version = protocol
- httpd = ServerClass(server_address, HandlerClass)
-
- sa = httpd.socket.getsockname()
- print("Serving HTTP on", sa[0], "port", sa[1], "...")
- try:
- httpd.serve_forever()
- except KeyboardInterrupt:
- print("\nKeyboard interrupt received, exiting.")
- httpd.server_close()
- sys.exit(0)
+ with ServerClass(server_address, HandlerClass) as httpd:
+ sa = httpd.socket.getsockname()
+ serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
+ print(serve_message.format(host=sa[0], port=sa[1]))
+ try:
+ httpd.serve_forever()
+ except KeyboardInterrupt:
+ print("\nKeyboard interrupt received, exiting.")
+ sys.exit(0)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
diff --git a/Lib/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt
index 72905c1..a3fc501 100644
--- a/Lib/idlelib/NEWS.txt
+++ b/Lib/idlelib/NEWS.txt
@@ -1,45 +1,101 @@
-What's New in IDLE 3.5.3?
-=========================
-*Release date: 2017-01-01?*
+What's New in IDLE 3.6.0?
+===========================
+*Release date: 2016-12-16?*
- Issue #15308: Add 'interrupt execution' (^C) to Shell menu.
Patch by Roger Serwy, updated by Bayard Randel.
- Issue #27922: Stop IDLE tests from 'flashing' gui widgets on the screen.
+- Issue #27891: Consistently group and sort imports within idlelib modules.
+
+- Issue #17642: add larger font sizes for classroom projection.
+
- Add version to title of IDLE help window.
- Issue #25564: In section on IDLE -- console differences, mention that
using exec means that __builtins__ is defined for each statement.
+- Issue #27821: Fix 3.6.0a3 regression that prevented custom key sets
+ from being selected when no custom theme was defined.
+
- Issue #27714: text_textview and test_autocomplete now pass when re-run
in the same process. This occurs when test_idle fails when run with the
-w option but without -jn. Fix warning from test_config.
+- Issue #27621: Put query response validation error messages in the query
+ box itself instead of in a separate massagebox. Redo tests to match.
+ Add Mac OSX refinements. Original patch by Mark Roseman.
+
+- Issue #27620: Escape key now closes Query box as cancelled.
+
+- Issue #27609: IDLE: tab after initial whitespace should tab, not
+ autocomplete. This fixes problem with writing docstrings at least
+ twice indented.
+
+- Issue #27609: Explicitly return None when there are also non-None
+ returns. In a few cases, reverse a condition and eliminate a return.
+
- Issue #25507: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.
+- Issue #27173: Add 'IDLE Modern Unix' to the built-in key sets.
+ Make the default key set depend on the platform.
+ Add tests for the changes to the config module.
+
+- Issue #27452: add line counter and crc to IDLE configHandler test dump.
+
+- Issue #27477: IDLE search dialogs now use ttk widgets.
+
+- Issue #27173: Add 'IDLE Modern Unix' to the built-in key sets.
+ Make the default key set depend on the platform.
+ Add tests for the changes to the config module.
+
+- Issue #27452: make command line "idle-test> python test_help.py" work.
+ __file__ is relative when python is started in the file's directory.
+
- Issue #27452: add line counter and crc to IDLE configHandler test dump.
+- Issue #27380: IDLE: add query.py with base Query dialog and ttk widgets.
+ Module had subclasses SectionName, ModuleName, and HelpSource, which are
+ used to get information from users by configdialog and file =>Load Module.
+ Each subclass has itw own validity checks. Using ModuleName allows users
+ to edit bad module names instead of starting over.
+ Add tests and delete the two files combined into the new one.
+
+- Issue #27372: Test_idle no longer changes the locale.
+
- Issue #27365: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.
- Issue #27245: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.
+- Issue #24137: Run IDLE, test_idle, and htest with tkinter default root disabled.
+ Fix code and tests that fail with this restriction.
+ Fix htests to not create a second and redundant root and mainloop.
-What's New in IDLE 3.5.2?
-=========================
-*Release date: 2016-06-26*
+- Issue #27310: Fix IDLE.app failure to launch on OS X due to vestigial import.
- Issue #5124: Paste with text selected now replaces the selection on X11.
This matches how paste works on Windows, Mac, most modern Linux apps,
and ttk widgets. Original patch by Serhiy Storchaka.
+- Issue #24750: Switch all scrollbars in IDLE to ttk versions.
+ Where needed, minimal tests are added to cover changes.
+
+- Issue #24759: IDLE requires tk 8.5 and availability ttk widgets.
+ Delete now unneeded tk version tests and code for older versions.
+ Add test for IDLE syntax colorizer.
+
+- Issue #27239: idlelib.macosx.isXyzTk functions initialize as needed.
+
+- Issue #27262: move Aqua unbinding code, which enable context menus, to maxosx.
+
- Issue #24759: Make clear in idlelib.idle_test.__init__ that the directory
is a private implementation of test.test_idle and tool for maintainers.
-- Issue #27196: Stop 'ThemeChangef' warnings when running IDLE tests.
+- Issue #27196: Stop 'ThemeChanged' warnings when running IDLE tests.
These persisted after other warnings were suppressed in #20567.
Apply Serhiy Storchaka's update_idletasks solution to four test files.
Record this additional advice in idle_test/README.txt
@@ -47,9 +103,26 @@ What's New in IDLE 3.5.2?
- Issue #20567: Revise idle_test/README.txt with advice about avoiding
tk warning messages from tests. Apply advice to several IDLE tests.
+- Issue # 24225: Update idlelib/README.txt with new file names
+ and event handlers.
+
+- Issue #27156: Remove obsolete code not used by IDLE. Replacements:
+ 1. help.txt, replaced by help.html, is out-of-date and should not be used.
+ Its dedicated viewer has be replaced by the html viewer in help.py.
+ 2. 'import idlever; I = idlever.IDLE_VERSION' is the same as
+ 'import sys; I = version[:version.index(' ')]'
+ 3. After 'ob = stackviewer.VariablesTreeItem(*args)',
+ 'ob.keys()' == 'list(ob.object.keys).
+ 4. In macosc, runningAsOSXAPP == isAquaTk; idCarbonAquaTk == isCarbonTk
+
- Issue #27117: Make colorizer htest and turtledemo work with dark themes.
Move code for configuring text widget colors to a new function.
+- Issue #24225: Rename many idlelib/*.py and idle_test/test_*.py files.
+ Edit files to replace old names with new names when the old name
+ referred to the module rather than the class it contained.
+ See the issue and IDLE section in What's New in 3.6 for more.
+
- Issue #26673: When tk reports font size as 0, change to size 10.
Such fonts on Linux prevented the configuration dialog from opening.
@@ -62,8 +135,8 @@ What's New in IDLE 3.5.2?
- Issue #18410: Add test for IDLE's search dialog.
Original patch by Westley Martínez.
-- Issue #21703: Add test for undo delegator.
- Original patch by Saimadhav Heblikar .
+- Issue #21703: Add test for undo delegator. Patch mostly by
+ Saimadhav Heblikar .
- Issue #27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks.
@@ -82,11 +155,6 @@ What's New in IDLE 3.5.2?
MARK in README.txt and open this and NEWS.txt with 'ascii'.
Re-encode CREDITS.txt to utf-8 and open it with 'utf-8'.
-
-What's New in IDLE 3.5.1?
-=========================
-*Release date: 2015-12-06*
-
- Issue 15348: Stop the debugger engine (normally in a user process)
before closing the debugger window (running in the IDLE process).
This prevents the RuntimeErrors that were being caught and ignored.
diff --git a/Lib/idlelib/README.txt b/Lib/idlelib/README.txt
index ff44504..51e8ef5 100644
--- a/Lib/idlelib/README.txt
+++ b/Lib/idlelib/README.txt
@@ -29,61 +29,61 @@ idle.pyw
Implementation
--------------
-AutoComplete.py # Complete attribute names or filenames.
-AutoCompleteWindow.py # Display completions.
-AutoExpand.py # Expand word with previous word in file.
-Bindings.py # Define most of IDLE menu.
-CallTipWindow.py # Display calltip.
-CallTips.py # Create calltip text.
-ClassBrowser.py # Create module browser window.
-CodeContext.py # Show compound statement headers otherwise not visible.
-ColorDelegator.py # Colorize text (nim).
-Debugger.py # Debug code run from editor; show window.
-Delegator.py # Define base class for delegators (nim).
-EditorWindow.py # Define most of editor and utility functions.
-FileList.py # Open files and manage list of open windows (nim).
-FormatParagraph.py# Re-wrap multiline strings and comments.
-GrepDialog.py # Find all occurrences of pattern in multiple files.
-HyperParser.py # Parse code around a given index.
-IOBinding.py # Open, read, and write files
-IdleHistory.py # Get previous or next user input in shell (nim)
-MultiCall.py # Wrap tk widget to allow multiple calls per event (nim).
-MultiStatusBar.py # Define status bar for windows (nim).
-ObjectBrowser.py # Define class used in StackViewer (nim).
-OutputWindow.py # Create window for grep output.
-ParenMatch.py # Match fenceposts: (), [], and {}.
-PathBrowser.py # Create path browser window.
-Percolator.py # Manage delegator stack (nim).
-PyParse.py # Give information on code indentation
-PyShell.py # Start IDLE, manage shell, complete editor window
-RemoteDebugger.py # Debug code run in remote process.
-RemoteObjectBrowser.py # Communicate objects between processes with rpc (nim).
-ReplaceDialog.py # Search and replace pattern in text.
-RstripExtension.py# Strip trailing whitespace
-ScriptBinding.py # Check and run user code.
-ScrolledList.py # Define ScrolledList widget for IDLE (nim).
-SearchDialog.py # Search for pattern in text.
-SearchDialogBase.py # Define base for search, replace, and grep dialogs.
-SearchEngine.py # Define engine for all 3 search dialogs.
-StackViewer.py # View stack after exception.
-TreeWidget.py # Define tree widger, used in browsers (nim).
-UndoDelegator.py # Manage undo stack.
-WidgetRedirector.py # Intercept widget subcommands (for percolator) (nim).
-WindowList.py # Manage window list and define listed top level.
-ZoomHeight.py # Zoom window to full height of screen.
-aboutDialog.py # Display About IDLE dialog.
-configDialog.py # Display user configuration dialogs.
-configHandler.py # Load, fetch, and save configuration (nim).
-configHelpSourceEdit.py # Specify help source.
-configSectionNameDialog.py # Spefify user config section name
-dynOptionMenuWidget.py # define mutable OptionMenu widget (nim).
+autocomplete.py # Complete attribute names or filenames.
+autocomplete_w.py # Display completions.
+autoexpand.py # Expand word with previous word in file.
+browser.py # Create module browser window.
+calltip_w.py # Display calltip.
+calltips.py # Create calltip text.
+codecontext.py # Show compound statement headers otherwise not visible.
+colorizer.py # Colorize text (nim)
+config.py # Load, fetch, and save configuration (nim).
+configdialog.py # Display user configuration dialogs.
+config_help.py # Specify help source in configdialog.
+config_key.py # Change keybindings.
+dynoption.py # Define mutable OptionMenu widget (nim).
+debugobj.py # Define class used in stackviewer.
+debugobj_r.py # Communicate objects between processes with rpc (nim).
+debugger.py # Debug code run from shell or editor; show window.
+debugger_r.py # Debug code run in remote process.
+delegator.py # Define base class for delegators (nim).
+editor.py # Define most of editor and utility functions.
+filelist.py # Open files and manage list of open windows (nim).
+grep.py # Find all occurrences of pattern in multiple files.
help.py # Display IDLE's html doc.
-keybindingDialog.py # Change keybindings.
-macosxSupport.py # Help IDLE run on Macs (nim).
+help_about.py # Display About IDLE dialog.
+history.py # Get previous or next user input in shell (nim)
+hyperparser.py # Parse code around a given index.
+iomenu.py # Open, read, and write files
+macosx.py # Help IDLE run on Macs (nim).
+mainmenu.py # Define most of IDLE menu.
+multicall.py # Wrap tk widget to allow multiple calls per event (nim).
+outwin.py # Create window for grep output.
+paragraph.py # Re-wrap multiline strings and comments.
+parenmatch.py # Match fenceposts: (), [], and {}.
+pathbrowser.py # Create path browser window.
+percolator.py # Manage delegator stack (nim).
+pyparse.py # Give information on code indentation
+pyshell.py # Start IDLE, manage shell, complete editor window
+query.py # Query user for information
+redirector.py # Intercept widget subcommands (for percolator) (nim).
+replace.py # Search and replace pattern in text.
rpc.py # Commuicate between idle and user processes (nim).
+rstrip.py # Strip trailing whitespace.
run.py # Manage user code execution subprocess.
+runscript.py # Check and run user code.
+scrolledlist.py # Define scrolledlist widget for IDLE (nim).
+search.py # Search for pattern in text.
+searchbase.py # Define base for search, replace, and grep dialogs.
+searchengine.py # Define engine for all 3 search dialogs.
+stackviewer.py # View stack after exception.
+statusbar.py # Define status bar for windows (nim).
tabbedpages.py # Define tabbed pages widget (nim).
-textView.py # Define read-only text widget (nim).
+textview.py # Define read-only text widget (nim).
+tree.py # Define tree widger, used in browsers (nim).
+undo.py # Manage undo stack.
+windows.py # Manage window list and define listed top level.
+zoomheight.py # Zoom window to full height of screen.
Configuration
-------------
@@ -104,127 +104,148 @@ help.html # copy of idle.html in docs, displayed by IDLE Help
Subdirectories
--------------
-Icons # small image files
-idle_test # files for human test and automated unit tests
+Icons # small image files
+idle_test # files for human test and automated unit tests
Unused and Deprecated files and objects (nim)
---------------------------------------------
-EditorWindow.py: Helpdialog and helpDialog
-ToolTip.py: unused.
-help.txt
-idlever.py
+tooltip.py # unused
+
IDLE MENUS
-Top level items and most submenu items are defined in Bindings.
+Top level items and most submenu items are defined in mainmenu.
Extenstions add submenu items when active. The names given are
found, quoted, in one of these modules, paired with a '<<pseudoevent>>'.
Each pseudoevent is bound to an event handler. Some event handlers
call another function that does the actual work. The annotations below
are intended to at least give the module where the actual work is done.
+'eEW' = editor.EditorWindow
-File # IOBindig except as noted
- New File
- Open... # IOBinding.open
- Open Module
+File
+ New File # eEW.new_callback
+ Open... # iomenu.open
+ Open Module # eEw.open_module
Recent Files
- Class Browser # Class Browser
- Path Browser # Path Browser
+ Class Browser # eEW.open_class_browser, browser.ClassBrowser
+ Path Browser # eEW.open_path_browser, pathbrowser
---
- Save # IDBinding.save
- Save As... # IOBinding.save_as
- Save Copy As... # IOBindling.save_a_copy
+ Save # iomenu.save
+ Save As... # iomenu.save_as
+ Save Copy As... # iomenu.save_a_copy
---
- Print Window # IOBinding.print_window
+ Print Window # iomenu.print_window
---
- Close
- Exit
+ Close # eEW.close_event
+ Exit # flist.close_all_callback (bound in eEW)
Edit
- Undo # undoDelegator
- Redo # undoDelegator
- ---
- Cut
- Copy
- Paste
- Select All
- --- # Next 5 items use SearchEngine; dialogs use SearchDialogBase
- Find # Search Dialog
- Find Again
- Find Selection
- Find in Files... # GrepDialog
- Replace... # ReplaceDialog
- Go to Line
- Show Completions # AutoComplete extension and AutoCompleteWidow (&HP)
- Expand Word # AutoExpand extension
- Show call tip # Calltips extension and CalltipWindow (& Hyperparser)
- Show surrounding parens # ParenMatch (& Hyperparser)
-
-Shell # PyShell
- View Last Restart # PyShell.PyShell.view_restart_mark
- Restart Shell # PyShell.PyShell.restart_shell
+ Undo # undodelegator
+ Redo # undodelegator
+ --- # eEW.right_menu_event
+ Cut # eEW.cut
+ Copy # eEW.copy
+ Paste # eEW.past
+ Select All # eEW.select_all (+ see eEW.remove_selection)
+ --- # Next 5 items use searchengine; dialogs use searchbase
+ Find # eEW.find_event, search.SearchDialog.find
+ Find Again # eEW.find_again_event, sSD.find_again
+ Find Selection # eEW.find_selection_event, sSD.find_selection
+ Find in Files... # eEW.find_in_files_event, grep
+ Replace... # eEW.replace_event, replace.ReplaceDialog.replace
+ Go to Line # eEW.goto_line_event
+ Show Completions # autocomplete extension and autocompleteWidow (&HP)
+ Expand Word # autoexpand extension
+ Show call tip # Calltips extension and CalltipWindow (& Hyperparser)
+ Show surrounding parens # parenmatch (& Hyperparser)
+
+Shell # pyshell
+ View Last Restart # pyshell.PyShell.view_restart_mark
+ Restart Shell # pyshell.PyShell.restart_shell
Interrupt Execution # pyshell.PyShell.cancel_callback
Debug (Shell only)
Go to File/Line
- Debugger # Debugger, RemoteDebugger, PyShell.toggle_debuger
- Stack Viewer # StackViewer, PyShell.open_stack_viewer
- Auto-open Stack Viewer # StackViewer
+ debugger # debugger, debugger_r, PyShell.toggle_debuger
+ Stack Viewer # stackviewer, PyShell.open_stack_viewer
+ Auto-open Stack Viewer # stackviewer
Format (Editor only)
- Indent Region
- Dedent Region
- Comment Out Region
- Uncomment Region
- Tabify Region
- Untabify Region
- Toggle Tabs
- New Indent Width
- Format Paragraph # FormatParagraph extension
+ Indent Region # eEW.indent_region_event
+ Dedent Region # eEW.dedent_region_event
+ Comment Out Reg. # eEW.comment_region_event
+ Uncomment Region # eEW.uncomment_region_event
+ Tabify Region # eEW.tabify_region_event
+ Untabify Region # eEW.untabify_region_event
+ Toggle Tabs # eEW.toggle_tabs_event
+ New Indent Width # eEW.change_indentwidth_event
+ Format Paragraph # paragraph extension
---
- Strip tailing whitespace # RstripExtension extension
+ Strip tailing whitespace # rstrip extension
Run (Editor only)
- Python Shell # PyShell
+ Python Shell # pyshell
---
- Check Module # ScriptBinding
- Run Module # ScriptBinding
+ Check Module # runscript
+ Run Module # runscript
Options
- Configure IDLE # configDialog
+ Configure IDLE # eEW.config_dialog, configdialog
(tabs in the dialog)
- Font tab # onfig-main.def
- Highlight tab # configSectionNameDialog, config-highlight.def
- Keys tab # keybindingDialog, configSectionNameDialog, onfig-keus.def
- General tab # configHelpSourceEdit, config-main.def
- Configure Extensions # configDialog
- Xyz tab # xyz.py, config-extensions.def
+ Font tab # config-main.def
+ Highlight tab # query, config-highlight.def
+ Keys tab # query, config_key, config_keys.def
+ General tab # config_help, config-main.def
+ Extensions tab # config-extensions.def, corresponding .py
---
- Code Context (editor only) # CodeContext extension
+ Code Context (ed)# codecontext extension
Window
- Zoomheight # ZoomHeight extension
+ Zoomheight # zoomheight extension
---
- <open windows> # WindowList
+ <open windows> # windows
Help
- About IDLE # aboutDialog
+ About IDLE # eEW.about_dialog, help_about.AboutDialog
---
- IDLE Help # help
- Python Doc
- Turtle Demo
+ IDLE Help # eEW.help_dialog, helpshow_idlehelp
+ Python Doc # eEW.python_docs
+ Turtle Demo # eEW.open_turtle_demo
---
<other help sources>
<Context Menu> (right click)
-Defined in EditorWindow, PyShell, Output
- Cut
- Copy
- Paste
- ---
- Go to file/line (shell and output only)
- Set Breakpoint (editor only)
- Clear Breakpoint (editor only)
- Defined in Debugger
- Go to source line
- Show stack frame
+ Defined in editor, PyShelpyshellut
+ Cut
+ Copy
+ Paste
+ ---
+ Go to file/line (shell and output only)
+ Set Breakpoint (editor only)
+ Clear Breakpoint (editor only)
+ Defined in debugger
+ Go to source line
+ Show stack frame
+
+<No menu>
+Center Insert # eEW.center_insert_event
+
+
+CODE STYLE -- Generally PEP 8.
+
+import
+------
+Put import at the top, unless there is a good reason otherwise.
+PEP 8 says to group stdlib, 3rd-party dependencies, and package imports.
+For idlelib, the groups are general stdlib, tkinter, and idlelib.
+Sort modules within each group, except that tkinter.ttk follows tkinter.
+Sort 'from idlelib import mod1' and 'from idlelib.mod2 import object'
+together by module, ignoring within module objects.
+Put 'import __main__' after other idlelib imports.
+
+Imports only needed for testing are put not at the top but in an
+htest function def or "if __name__ == '__main__'" clause.
+
+Within module imports like "from idlelib.mod import class" may cause
+circular imports to deadlock. Even without this, circular imports may
+require at least one of the imports to be delayed until a function call.
diff --git a/Lib/idlelib/__init__.py b/Lib/idlelib/__init__.py
index 711f61b..791ddea 100644
--- a/Lib/idlelib/__init__.py
+++ b/Lib/idlelib/__init__.py
@@ -1,8 +1,10 @@
"""The idlelib package implements the Idle application.
Idle includes an interactive shell and editor.
+Starting with Python 3.6, IDLE requires tcl/tk 8.5 or later.
Use the files named idle.* to start Idle.
The other files are private implementations. Their details are subject to
change. See PEP 434 for more. Import them at your own risk.
"""
+testing = False # Set True by test.test_idle.
diff --git a/Lib/idlelib/__main__.py b/Lib/idlelib/__main__.py
index 2edf5f7..6349ec7 100644
--- a/Lib/idlelib/__main__.py
+++ b/Lib/idlelib/__main__.py
@@ -3,6 +3,6 @@ IDLE main entry point
Run IDLE as python -m idlelib
"""
-import idlelib.PyShell
-idlelib.PyShell.main()
+import idlelib.pyshell
+idlelib.pyshell.main()
# This file does not work for 2.7; See issue 24212.
diff --git a/Lib/idlelib/AutoComplete.py b/Lib/idlelib/autocomplete.py
index ff085d5..1e44fa5 100644
--- a/Lib/idlelib/AutoComplete.py
+++ b/Lib/idlelib/autocomplete.py
@@ -1,29 +1,30 @@
-"""AutoComplete.py - An IDLE extension for automatically completing names.
+"""autocomplete.py - An IDLE extension for automatically completing names.
This extension can complete either attribute names or file names. It can pop
a window with all available names, for the user to select from.
"""
import os
-import sys
import string
+import sys
-from idlelib.configHandler import idleConf
-
-# This string includes all chars that may be in an identifier
-ID_CHARS = string.ascii_letters + string.digits + "_"
-
-# These constants represent the two different types of completions
+# These constants represent the two different types of completions.
+# They must be defined here so autocomple_w can import them.
COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1)
-from idlelib import AutoCompleteWindow
-from idlelib.HyperParser import HyperParser
-
+from idlelib import autocomplete_w
+from idlelib.config import idleConf
+from idlelib.hyperparser import HyperParser
import __main__
+# This string includes all chars that may be in an identifier.
+# TODO Update this here and elsewhere.
+ID_CHARS = string.ascii_letters + string.digits + "_"
+
SEPS = os.sep
if os.altsep: # e.g. '/' on Windows...
SEPS += os.altsep
+
class AutoComplete:
menudefs = [
@@ -37,19 +38,17 @@ class AutoComplete:
def __init__(self, editwin=None):
self.editwin = editwin
- if editwin is None: # subprocess and test
- return
- self.text = editwin.text
- self.autocompletewindow = None
-
- # id of delayed call, and the index of the text insert when the delayed
- # call was issued. If _delayed_completion_id is None, there is no
- # delayed call.
- self._delayed_completion_id = None
- self._delayed_completion_index = None
+ if editwin is not None: # not in subprocess or test
+ self.text = editwin.text
+ self.autocompletewindow = None
+ # id of delayed call, and the index of the text insert when
+ # the delayed call was issued. If _delayed_completion_id is
+ # None, there is no delayed call.
+ self._delayed_completion_id = None
+ self._delayed_completion_index = None
def _make_autocomplete_window(self):
- return AutoCompleteWindow.AutoCompleteWindow(self.text)
+ return autocomplete_w.AutoCompleteWindow(self.text)
def _remove_autocomplete_window(self, event=None):
if self.autocompletewindow:
@@ -80,16 +79,17 @@ class AutoComplete:
open a completion list after that (if there is more than one
completion)
"""
- if hasattr(event, "mc_state") and event.mc_state:
- # A modifier was pressed along with the tab, continue as usual.
- return
+ if hasattr(event, "mc_state") and event.mc_state or\
+ not self.text.get("insert linestart", "insert").strip():
+ # A modifier was pressed along with the tab or
+ # there is only previous whitespace on this line, so tab.
+ return None
if self.autocompletewindow and self.autocompletewindow.is_active():
self.autocompletewindow.complete()
return "break"
else:
opened = self.open_completions(False, True, True)
- if opened:
- return "break"
+ return "break" if opened else None
def _open_completions_later(self, *args):
self._delayed_completion_index = self.text.index("insert")
@@ -101,9 +101,8 @@ class AutoComplete:
def _delayed_open_completions(self, *args):
self._delayed_completion_id = None
- if self.text.index("insert") != self._delayed_completion_index:
- return
- self.open_completions(*args)
+ if self.text.index("insert") == self._delayed_completion_index:
+ self.open_completions(*args)
def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
"""Find the completions and create the AutoCompleteWindow.
@@ -148,17 +147,17 @@ class AutoComplete:
comp_what = hp.get_expression()
if not comp_what or \
(not evalfuncs and comp_what.find('(') != -1):
- return
+ return None
else:
comp_what = ""
else:
- return
+ return None
if complete and not comp_what and not comp_start:
- return
+ return None
comp_lists = self.fetch_completions(comp_what, mode)
if not comp_lists[0]:
- return
+ return None
self.autocompletewindow = self._make_autocomplete_window()
return not self.autocompletewindow.show_window(
comp_lists, "insert-%dc" % len(comp_start),
diff --git a/Lib/idlelib/AutoCompleteWindow.py b/Lib/idlelib/autocomplete_w.py
index 2ee6878..3374c6e 100644
--- a/Lib/idlelib/AutoCompleteWindow.py
+++ b/Lib/idlelib/autocomplete_w.py
@@ -1,9 +1,11 @@
"""
-An auto-completion window for IDLE, used by the AutoComplete extension
+An auto-completion window for IDLE, used by the autocomplete extension
"""
from tkinter import *
-from idlelib.MultiCall import MC_SHIFT
-from idlelib.AutoComplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
+from tkinter.ttk import Scrollbar
+
+from idlelib.autocomplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
+from idlelib.multicall import MC_SHIFT
HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
HIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
@@ -34,8 +36,8 @@ class AutoCompleteWindow:
self.completions = None
# A list with more completions, or None
self.morecompletions = None
- # The completion mode. Either AutoComplete.COMPLETE_ATTRIBUTES or
- # AutoComplete.COMPLETE_FILES
+ # The completion mode. Either autocomplete.COMPLETE_ATTRIBUTES or
+ # autocomplete.COMPLETE_FILES
self.mode = None
# The current completion start, on the text box (a string)
self.start = None
@@ -215,6 +217,7 @@ class AutoCompleteWindow:
self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
self.doubleclick_event)
+ return None
def winconfig_event(self, event):
if not self.is_active():
@@ -238,16 +241,14 @@ class AutoCompleteWindow:
acw.wm_geometry("+%d+%d" % (new_x, new_y))
def hide_event(self, event):
- if not self.is_active():
- return
- self.hide_window()
+ if self.is_active():
+ self.hide_window()
def listselect_event(self, event):
- if not self.is_active():
- return
- self.userwantswindow = True
- cursel = int(self.listbox.curselection()[0])
- self._change_start(self.completions[cursel])
+ if self.is_active():
+ self.userwantswindow = True
+ cursel = int(self.listbox.curselection()[0])
+ self._change_start(self.completions[cursel])
def doubleclick_event(self, event):
# Put the selected completion in the text, and close the list
@@ -257,7 +258,7 @@ class AutoCompleteWindow:
def keypress_event(self, event):
if not self.is_active():
- return
+ return None
keysym = event.keysym
if hasattr(event, "mc_state"):
state = event.mc_state
@@ -282,7 +283,7 @@ class AutoCompleteWindow:
# keysym == "BackSpace"
if len(self.start) == 0:
self.hide_window()
- return
+ return None
self._change_start(self.start[:-1])
self.lasttypedstart = self.start
self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
@@ -292,7 +293,7 @@ class AutoCompleteWindow:
elif keysym == "Return":
self.hide_window()
- return
+ return None
elif (self.mode == COMPLETE_ATTRIBUTES and keysym in
("period", "space", "parenleft", "parenright", "bracketleft",
@@ -308,7 +309,7 @@ class AutoCompleteWindow:
and (self.mode == COMPLETE_ATTRIBUTES or self.start):
self._change_start(self.completions[cursel])
self.hide_window()
- return
+ return None
elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
not state:
@@ -349,12 +350,12 @@ class AutoCompleteWindow:
# first tab; let AutoComplete handle the completion
self.userwantswindow = True
self.lastkey_was_tab = True
- return
+ return None
elif any(s in keysym for s in ("Shift", "Control", "Alt",
"Meta", "Command", "Option")):
# A modifier key, so ignore
- return
+ return None
elif event.char and event.char >= ' ':
# Regular character with a non-length-1 keycode
@@ -368,7 +369,7 @@ class AutoCompleteWindow:
else:
# Unknown event, close the window and let it through.
self.hide_window()
- return
+ return None
def keyrelease_event(self, event):
if not self.is_active():
diff --git a/Lib/idlelib/AutoExpand.py b/Lib/idlelib/autoexpand.py
index 7059054..6b46bee 100644
--- a/Lib/idlelib/AutoExpand.py
+++ b/Lib/idlelib/autoexpand.py
@@ -12,8 +12,8 @@ its state.
This is an extension file and there is only one instance of AutoExpand.
'''
-import string
import re
+import string
###$ event <<expand-word>>
###$ win <Alt-slash>
@@ -31,6 +31,7 @@ class AutoExpand:
def __init__(self, editwin):
self.text = editwin.text
+ self.bell = self.text.bell
self.state = None
def expand_word_event(self, event):
@@ -46,14 +47,14 @@ class AutoExpand:
words = self.getwords()
index = 0
if not words:
- self.text.bell()
+ self.bell()
return "break"
word = self.getprevword()
self.text.delete("insert - %d chars" % len(word), "insert")
newword = words[index]
index = (index + 1) % len(words)
if index == 0:
- self.text.bell() # Warn we cycled around
+ self.bell() # Warn we cycled around
self.text.insert("insert", newword)
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
diff --git a/Lib/idlelib/ClassBrowser.py b/Lib/idlelib/browser.py
index d09c52f..ea05638 100644
--- a/Lib/idlelib/ClassBrowser.py
+++ b/Lib/idlelib/browser.py
@@ -11,16 +11,16 @@ XXX TO DO:
"""
import os
-import sys
import pyclbr
+import sys
-from idlelib import PyShell
-from idlelib.WindowList import ListedToplevel
-from idlelib.TreeWidget import TreeNode, TreeItem, ScrolledCanvas
-from idlelib.configHandler import idleConf
+from idlelib.config import idleConf
+from idlelib import pyshell
+from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
+from idlelib.windows import ListedToplevel
file_open = None # Method...Item and Class...Item use this.
-# Normally PyShell.flist.open, but there is no PyShell.flist for htest.
+# Normally pyshell.flist.open, but there is no pyshell.flist for htest.
class ClassBrowser:
@@ -32,7 +32,7 @@ class ClassBrowser:
"""
global file_open
if not _htest:
- file_open = PyShell.flist.open
+ file_open = pyshell.flist.open
self.name = name
self.file = os.path.join(path[0], self.name + ".py")
self._htest = _htest
@@ -95,7 +95,7 @@ class ModuleBrowserTreeItem(TreeItem):
return
if not os.path.exists(self.file):
return
- PyShell.flist.open(self.file)
+ pyshell.flist.open(self.file)
def IsExpandable(self):
return os.path.normcase(self.file[-3:]) == ".py"
@@ -226,7 +226,7 @@ def _class_browser(parent): #Wrapper for htest
file = sys.argv[0]
dir, file = os.path.split(file)
name = os.path.splitext(file)[0]
- flist = PyShell.PyShellFileList(parent)
+ flist = pyshell.PyShellFileList(parent)
global file_open
file_open = flist.open
ClassBrowser(flist, name, [dir], _htest=True)
diff --git a/Lib/idlelib/CallTipWindow.py b/Lib/idlelib/calltip_w.py
index 9eec175..c7361d1 100644
--- a/Lib/idlelib/CallTipWindow.py
+++ b/Lib/idlelib/calltip_w.py
@@ -1,7 +1,7 @@
"""A CallTip window class for Tkinter/IDLE.
-After ToolTip.py, which uses ideas gleaned from PySol
-Used by the CallTips IDLE extension.
+After tooltip.py, which uses ideas gleaned from PySol
+Used by the calltips IDLE extension.
"""
from tkinter import Toplevel, Label, LEFT, SOLID, TclError
@@ -138,8 +138,8 @@ def _calltip_window(parent): # htest #
top = Toplevel(parent)
top.title("Test calltips")
- top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
- parent.winfo_rooty() + 150))
+ x, y = map(int, parent.geometry().split('+')[1:])
+ top.geometry("200x100+%d+%d" % (x + 250, y + 175))
text = Text(top)
text.pack(side=LEFT, fill=BOTH, expand=1)
text.insert("insert", "string.split")
diff --git a/Lib/idlelib/CallTips.py b/Lib/idlelib/calltips.py
index 81bd5f1..4c5aea2 100644
--- a/Lib/idlelib/CallTips.py
+++ b/Lib/idlelib/calltips.py
@@ -1,19 +1,19 @@
-"""CallTips.py - An IDLE Extension to Jog Your Memory
+"""calltips.py - An IDLE Extension to Jog Your Memory
Call Tips are floating windows which display function, class, and method
parameter and docstring information when you type an opening parenthesis, and
which disappear when you type a closing parenthesis.
"""
-import __main__
import inspect
import re
import sys
import textwrap
import types
-from idlelib import CallTipWindow
-from idlelib.HyperParser import HyperParser
+from idlelib import calltip_w
+from idlelib.hyperparser import HyperParser
+import __main__
class CallTips:
@@ -37,7 +37,7 @@ class CallTips:
def _make_tk_calltip_window(self):
# See __init__ for usage
- return CallTipWindow.CallTip(self.text)
+ return calltip_w.CallTip(self.text)
def _remove_calltip_window(self, event=None):
if self.active_calltip:
@@ -120,7 +120,7 @@ def get_entity(expression):
_MAX_COLS = 85
_MAX_LINES = 5 # enough for bytes
_INDENT = ' '*4 # for wrapped signatures
-_first_param = re.compile('(?<=\()\w*\,?\s*')
+_first_param = re.compile(r'(?<=\()\w*\,?\s*')
_default_callable_argspec = "See source or doc"
diff --git a/Lib/idlelib/CodeContext.py b/Lib/idlelib/codecontext.py
index 7d25ada..f25e1b3 100644
--- a/Lib/idlelib/CodeContext.py
+++ b/Lib/idlelib/codecontext.py
@@ -1,19 +1,21 @@
-"""CodeContext - Extension to display the block context above the edit window
+"""codecontext - Extension to display the block context above the edit window
Once code has scrolled off the top of a window, it can be difficult to
determine which block you are in. This extension implements a pane at the top
of each IDLE edit window which provides block structure hints. These hints are
the lines which contain the block opening keywords, e.g. 'if', for the
enclosing block. The number of hint lines is determined by the numlines
-variable in the CodeContext section of config-extensions.def. Lines which do
+variable in the codecontext section of config-extensions.def. Lines which do
not open blocks are not shown in the context hints pane.
"""
-import tkinter
-from tkinter.constants import TOP, LEFT, X, W, SUNKEN
import re
from sys import maxsize as INFINITY
-from idlelib.configHandler import idleConf
+
+import tkinter
+from tkinter.constants import TOP, LEFT, X, W, SUNKEN
+
+from idlelib.config import idleConf
BLOCKOPENERS = {"class", "def", "elif", "else", "except", "finally", "for",
"if", "try", "while", "with"}
diff --git a/Lib/idlelib/ColorDelegator.py b/Lib/idlelib/colorizer.py
index 02eac47..7a919f1 100644
--- a/Lib/idlelib/ColorDelegator.py
+++ b/Lib/idlelib/colorizer.py
@@ -1,10 +1,10 @@
-import time
-import re
-import keyword
import builtins
-from tkinter import TkVersion
-from idlelib.Delegator import Delegator
-from idlelib.configHandler import idleConf
+import keyword
+import re
+import time
+
+from idlelib.config import idleConf
+from idlelib.delegator import Delegator
DEBUG = False
@@ -21,7 +21,8 @@ def make_pat():
# 1st 'file' colorized normal, 2nd as builtin, 3rd as string
builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b"
comment = any("COMMENT", [r"#[^\n]*"])
- stringprefix = r"(\br|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR|rb|rB|Rb|RB)?"
+ stringprefix = (r"(\br|R|u|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF"
+ "|b|B|br|Br|bR|BR|rb|rB|Rb|RB)?")
sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?'
sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?"
@@ -49,11 +50,8 @@ def color_config(text): # Called from htest, Editor, and Turtle Demo.
insertbackground=cursor_color,
selectforeground=select_colors['foreground'],
selectbackground=select_colors['background'],
- )
- if TkVersion >= 8.5:
- text.config(
- inactiveselectbackground=select_colors['background'])
-
+ inactiveselectbackground=select_colors['background'], # new in 8.5
+ )
class ColorDelegator(Delegator):
@@ -259,13 +257,19 @@ class ColorDelegator(Delegator):
def _color_delegator(parent): # htest #
from tkinter import Toplevel, Text
- from idlelib.Percolator import Percolator
+ from idlelib.percolator import Percolator
top = Toplevel(parent)
top.title("Test ColorDelegator")
- top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
- parent.winfo_rooty() + 150))
- source = "if somename: x = 'abc' # comment\nprint\n"
+ x, y = map(int, parent.geometry().split('+')[1:])
+ top.geometry("600x200+%d+%d" % (x + 100, y + 175))
+ source = ("# Following has syntax errors\n"
+ "if True: then int 1\nelif False: print 0\nelse: float(None)\n"
+ "#unicode and byte strings, valid prefixes should be colored\n"
+ "'x', '''x''', \"x\", \"\"\"x\"\"\"\n"
+ "r'x', u'x', R'x', U'x', f'x', F'x', ur'is invalid'\n"
+ "fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x'\n"
+ "b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x'.rB'x',Rb'x',RB'x'\n")
text = Text(top, background="white")
text.pack(expand=1, fill="both")
text.insert("insert", source)
@@ -277,5 +281,9 @@ def _color_delegator(parent): # htest #
p.insertfilter(d)
if __name__ == "__main__":
+ import unittest
+ unittest.main('idlelib.idle_test.test_colorizer',
+ verbosity=2, exit=False)
+
from idlelib.idle_test.htest import run
run(_color_delegator)
diff --git a/Lib/idlelib/config-keys.def b/Lib/idlelib/config-keys.def
index 3bfcb69..64788f9 100644
--- a/Lib/idlelib/config-keys.def
+++ b/Lib/idlelib/config-keys.def
@@ -109,6 +109,57 @@ change-indentwidth=<Alt-Key-u>
del-word-left=<Alt-Key-BackSpace>
del-word-right=<Alt-Key-d>
+[IDLE Modern Unix]
+copy = <Control-Shift-Key-C> <Control-Key-Insert>
+cut = <Control-Key-x> <Shift-Key-Delete>
+paste = <Control-Key-v> <Shift-Key-Insert>
+beginning-of-line = <Key-Home>
+center-insert = <Control-Key-l>
+close-all-windows = <Control-Key-q>
+close-window = <Control-Key-w> <Control-Shift-Key-W>
+do-nothing = <Control-Key-F12>
+end-of-file = <Control-Key-d>
+history-next = <Alt-Key-n> <Meta-Key-n>
+history-previous = <Alt-Key-p> <Meta-Key-p>
+interrupt-execution = <Control-Key-c>
+view-restart = <Key-F6>
+restart-shell = <Control-Key-F6>
+open-class-browser = <Control-Key-b>
+open-module = <Control-Key-m>
+open-new-window = <Control-Key-n>
+open-window-from-file = <Control-Key-o>
+plain-newline-and-indent = <Control-Key-j>
+print-window = <Control-Key-p>
+python-context-help = <Shift-Key-F1>
+python-docs = <Key-F1>
+redo = <Control-Shift-Key-Z>
+remove-selection = <Key-Escape>
+save-copy-of-window-as-file = <Alt-Shift-Key-S>
+save-window-as-file = <Control-Shift-Key-S>
+save-window = <Control-Key-s>
+select-all = <Control-Key-a>
+toggle-auto-coloring = <Control-Key-slash>
+undo = <Control-Key-z>
+find = <Control-Key-f>
+find-again = <Key-F3>
+find-in-files = <Control-Shift-Key-f>
+find-selection = <Control-Key-h>
+replace = <Control-Key-r>
+goto-line = <Control-Key-g>
+smart-backspace = <Key-BackSpace>
+newline-and-indent = <Key-Return> <Key-KP_Enter>
+smart-indent = <Key-Tab>
+indent-region = <Control-Key-bracketright>
+dedent-region = <Control-Key-bracketleft>
+comment-region = <Control-Key-d>
+uncomment-region = <Control-Shift-Key-D>
+tabify-region = <Alt-Key-5>
+untabify-region = <Alt-Key-6>
+toggle-tabs = <Control-Key-T>
+change-indentwidth = <Alt-Key-u>
+del-word-left = <Control-Key-BackSpace>
+del-word-right = <Control-Key-Delete>
+
[IDLE Classic Mac]
copy=<Command-Key-c>
cut=<Command-Key-x>
diff --git a/Lib/idlelib/config-main.def b/Lib/idlelib/config-main.def
index 8ebbc1b..16f4b09 100644
--- a/Lib/idlelib/config-main.def
+++ b/Lib/idlelib/config-main.def
@@ -4,44 +4,50 @@
# When IDLE starts, it will look in
# the following two sets of files, in order:
#
-# default configuration
-# ---------------------
-# config-main.def the default general config file
-# config-extensions.def the default extension config file
-# config-highlight.def the default highlighting config file
-# config-keys.def the default keybinding config file
+# default configuration files in idlelib
+# --------------------------------------
+# config-main.def default general config file
+# config-extensions.def default extension config file
+# config-highlight.def default highlighting config file
+# config-keys.def default keybinding config file
#
-# user configuration
-# -------------------
-# ~/.idlerc/config-main.cfg the user general config file
-# ~/.idlerc/config-extensions.cfg the user extension config file
-# ~/.idlerc/config-highlight.cfg the user highlighting config file
-# ~/.idlerc/config-keys.cfg the user keybinding config file
+# user configuration files in ~/.idlerc
+# -------------------------------------
+# config-main.cfg user general config file
+# config-extensions.cfg user extension config file
+# config-highlight.cfg user highlighting config file
+# config-keys.cfg user keybinding config file
#
-# On Windows2000 and Windows XP the .idlerc directory is at
-# Documents and Settings\<username>\.idlerc
-#
-# On Windows98 it is at c:\.idlerc
+# On Windows, the default location of the home directory ('~' above)
+# depends on the version. For Windows 10, it is C:\Users\<username>.
#
# Any options the user saves through the config dialog will be saved to
-# the relevant user config file. Reverting any general setting to the
-# default causes that entry to be wiped from the user file and re-read
-# from the default file. User highlighting themes or keybinding sets are
-# retained unless specifically deleted within the config dialog. Choosing
-# one of the default themes or keysets just applies the relevant settings
-# from the default file.
+# the relevant user config file. Reverting any general or extension
+# setting to the default causes that entry to be wiped from the user
+# file and re-read from the default file. This rule applies to each
+# item, except that the three editor font items are saved as a group.
+#
+# User highlighting themes and keybinding sets must have (section) names
+# distinct from the default names. All items are added and saved as a
+# group. They are retained unless specifically deleted within the config
+# dialog. Choosing one of the default themes or keysets just applies the
+# relevant settings from the default file.
+#
+# Additional help sources are listed in the [HelpFiles] section below
+# and should be viewable by a web browser (or the Windows Help viewer in
+# the case of .chm files). These sources will be listed on the Help
+# menu. The pattern, and two examples, are
#
-# Additional help sources are listed in the [HelpFiles] section and must be
-# viewable by a web browser (or the Windows Help viewer in the case of .chm
-# files). These sources will be listed on the Help menu. The pattern is
# <sequence_number = menu item;/path/to/help/source>
-# You can't use a semi-colon in a menu item or path. The path will be platform
-# specific because of path separators, drive specs etc.
+# 1 = IDLE;C:/Programs/Python36/Lib/idlelib/help.html
+# 2 = Pillow;https://pillow.readthedocs.io/en/latest/
#
-# It is best to use the Configuration GUI to set up additional help sources!
-# Example:
-#1 = My Extra Help Source;/usr/share/doc/foo/index.html
-#2 = Another Help Source;/path/to/another.pdf
+# You can't use a semi-colon in a menu item or path. The path will be
+# platform specific because of path separators, drive specs etc.
+#
+# The default files should not be edited except to add new sections to
+# config-extensions.def for added extensions . The user files should be
+# modified through the Settings dialog.
[General]
editor-on-startup= 0
@@ -54,6 +60,8 @@ delete-exitfunc= 1
width= 80
height= 40
font= TkFixedFont
+# For TkFixedFont, the actual size and boldness are obtained from tk
+# and override 10 and 0. See idlelib.config.IdleConf.GetFont
font-size= 10
font-bold= 0
encoding= none
@@ -70,7 +78,9 @@ name2=
[Keys]
default= 1
-name= IDLE Classic Windows
+name=
+name2=
+# name2 set in user config-main.cfg for keys added after 2016 July 1
[History]
cyclic=1
diff --git a/Lib/idlelib/configHandler.py b/Lib/idlelib/config.py
index 8954488..358bee4 100644
--- a/Lib/idlelib/configHandler.py
+++ b/Lib/idlelib/config.py
@@ -1,13 +1,20 @@
-"""Provides access to stored IDLE configuration information.
-
-Refer to the comments at the beginning of config-main.def for a description of
-the available configuration files and the design implemented to update user
-configuration information. In particular, user configuration choices which
-duplicate the defaults will be removed from the user's configuration files,
-and if a file becomes empty, it will be deleted.
-
-The contents of the user files may be altered using the Options/Configure IDLE
-menu to access the configuration GUI (configDialog.py), or manually.
+"""idlelib.config -- Manage IDLE configuration information.
+
+The comments at the beginning of config-main.def describe the
+configuration files and the design implemented to update user
+configuration information. In particular, user configuration choices
+which duplicate the defaults will be removed from the user's
+configuration files, and if a user file becomes empty, it will be
+deleted.
+
+The configuration database maps options to values. Comceptually, the
+database keys are tuples (config-type, section, item). As implemented,
+there are separate dicts for default and user values. Each has
+config-type keys 'main', 'extensions', 'highlight', and 'keys'. The
+value for each key is a ConfigParser instance that maps section and item
+to values. For 'main' and 'extenstons', user values override
+default values. For 'highlight' and 'keys', user sections augment the
+default sections (and must, therefore, have distinct names).
Throughout this module there is an emphasis on returning useable defaults
when a problem occurs in returning a requested configuration value back to
@@ -18,11 +25,10 @@ configuration problem notification and resolution.
"""
# TODOs added Oct 2014, tjr
+from configparser import ConfigParser
import os
import sys
-from configparser import ConfigParser
-from tkinter import TkVersion
from tkinter.font import Font, nametofont
class InvalidConfigType(Exception): pass
@@ -230,15 +236,12 @@ class IdleConf:
return self.userCfg[configType].Get(section, option,
type=type, raw=raw)
except ValueError:
- warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
+ warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
' invalid %r value for configuration option %r\n'
' from section %r: %r' %
(type, option, section,
self.userCfg[configType].Get(section, option, raw=raw)))
- try:
- print(warning, file=sys.stderr)
- except OSError:
- pass
+ _warn(warning, configType, section, option)
try:
if self.defaultCfg[configType].has_option(section,option):
return self.defaultCfg[configType].Get(
@@ -247,15 +250,12 @@ class IdleConf:
pass
#returning default, print warning
if warn_on_default:
- warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
+ warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
' problem retrieving configuration option %r\n'
' from section %r.\n'
' returning default value: %r' %
(option, section, default))
- try:
- print(warning, file=sys.stderr)
- except OSError:
- pass
+ _warn(warning, configType, section, option)
return default
def SetOption(self, configType, section, option, value):
@@ -358,52 +358,73 @@ class IdleConf:
for element in theme:
if not cfgParser.has_option(themeName, element):
# Print warning that will return a default color
- warning = ('\n Warning: configHandler.IdleConf.GetThemeDict'
+ warning = ('\n Warning: config.IdleConf.GetThemeDict'
' -\n problem retrieving theme element %r'
'\n from theme %r.\n'
' returning default color: %r' %
(element, themeName, theme[element]))
- try:
- print(warning, file=sys.stderr)
- except OSError:
- pass
+ _warn(warning, 'highlight', themeName, element)
theme[element] = cfgParser.Get(
themeName, element, default=theme[element])
return theme
def CurrentTheme(self):
- """Return the name of the currently active text color theme.
+ "Return the name of the currently active text color theme."
+ return self.current_colors_and_keys('Theme')
+
+ def CurrentKeys(self):
+ """Return the name of the currently active key set."""
+ return self.current_colors_and_keys('Keys')
+
+ def current_colors_and_keys(self, section):
+ """Return the currently active name for Theme or Keys section.
+
+ idlelib.config-main.def ('default') includes these sections
- idlelib.config-main.def includes this section
[Theme]
default= 1
name= IDLE Classic
name2=
- # name2 set in user config-main.cfg for themes added after 2015 Oct 1
- Item name2 is needed because setting name to a new builtin
- causes older IDLEs to display multiple error messages or quit.
+ [Keys]
+ default= 1
+ name=
+ name2=
+
+ Item 'name2', is used for built-in ('default') themes and keys
+ added after 2015 Oct 1 and 2016 July 1. This kludge is needed
+ because setting 'name' to a builtin not defined in older IDLEs
+ to display multiple error messages or quit.
See https://bugs.python.org/issue25313.
- When default = True, name2 takes precedence over name,
- while older IDLEs will just use name.
+ When default = True, 'name2' takes precedence over 'name',
+ while older IDLEs will just use name. When default = False,
+ 'name2' may still be set, but it is ignored.
"""
- default = self.GetOption('main', 'Theme', 'default',
+ cfgname = 'highlight' if section == 'Theme' else 'keys'
+ default = self.GetOption('main', section, 'default',
type='bool', default=True)
+ name = ''
if default:
- theme = self.GetOption('main', 'Theme', 'name2', default='')
- if default and not theme or not default:
- theme = self.GetOption('main', 'Theme', 'name', default='')
- source = self.defaultCfg if default else self.userCfg
- if source['highlight'].has_section(theme):
- return theme
+ name = self.GetOption('main', section, 'name2', default='')
+ if not name:
+ name = self.GetOption('main', section, 'name', default='')
+ if name:
+ source = self.defaultCfg if default else self.userCfg
+ if source[cfgname].has_section(name):
+ return name
+ return "IDLE Classic" if section == 'Theme' else self.default_keys()
+
+ @staticmethod
+ def default_keys():
+ if sys.platform[:3] == 'win':
+ return 'IDLE Classic Windows'
+ elif sys.platform == 'darwin':
+ return 'IDLE Classic OSX'
else:
- return "IDLE Classic"
+ return 'IDLE Modern Unix'
- def CurrentKeys(self):
- "Return the name of the currently active key set."
- return self.GetOption('main', 'Keys', 'name', default='')
-
- def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
+ def GetExtensions(self, active_only=True,
+ editor_only=False, shell_only=False):
"""Return extensions in default and user config-extensions files.
If active_only True, only return active (enabled) extensions
@@ -423,7 +444,7 @@ class IdleConf:
if self.GetOption('extensions', extn, 'enable', default=True,
type='bool'):
#the extension is enabled
- if editor_only or shell_only: # TODO if both, contradictory
+ if editor_only or shell_only: # TODO both True contradict
if editor_only:
option = "enable_editor"
else:
@@ -528,7 +549,8 @@ class IdleConf:
eventStr - virtual event, including brackets, as in '<<event>>'.
"""
eventName = eventStr[2:-2] #trim off the angle brackets
- binding = self.GetOption('keys', keySetName, eventName, default='').split()
+ binding = self.GetOption('keys', keySetName, eventName, default='',
+ warn_on_default=False).split()
return binding
def GetCurrentKeySet(self):
@@ -639,20 +661,28 @@ class IdleConf:
'<<del-word-right>>': ['<Control-Key-Delete>']
}
if keySetName:
- for event in keyBindings:
- binding = self.GetKeyBinding(keySetName, event)
- if binding:
- keyBindings[event] = binding
- else: #we are going to return a default, print warning
- warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'
- ' -\n problem retrieving key binding for event %r'
- '\n from key set %r.\n'
- ' returning default value: %r' %
- (event, keySetName, keyBindings[event]))
- try:
- print(warning, file=sys.stderr)
- except OSError:
- pass
+ if not (self.userCfg['keys'].has_section(keySetName) or
+ self.defaultCfg['keys'].has_section(keySetName)):
+ warning = (
+ '\n Warning: config.py - IdleConf.GetCoreKeys -\n'
+ ' key set %r is not defined, using default bindings.' %
+ (keySetName,)
+ )
+ _warn(warning, 'keys', keySetName)
+ else:
+ for event in keyBindings:
+ binding = self.GetKeyBinding(keySetName, event)
+ if binding:
+ keyBindings[event] = binding
+ else: #we are going to return a default, print warning
+ warning = (
+ '\n Warning: config.py - IdleConf.GetCoreKeys -\n'
+ ' problem retrieving key binding for event %r\n'
+ ' from key set %r.\n'
+ ' returning default value: %r' %
+ (event, keySetName, keyBindings[event])
+ )
+ _warn(warning, 'keys', keySetName, event)
return keyBindings
def GetExtraHelpSourceList(self, configSet):
@@ -713,16 +743,13 @@ class IdleConf:
bold = self.GetOption(configType, section, 'font-bold', default=0,
type='bool')
if (family == 'TkFixedFont'):
- if TkVersion < 8.5:
- family = 'Courier'
- else:
- f = Font(name='TkFixedFont', exists=True, root=root)
- actualFont = Font.actual(f)
- family = actualFont['family']
- size = actualFont['size']
- if size <= 0:
- size = 10 # if font in pixels, ignore actual size
- bold = actualFont['weight']=='bold'
+ f = Font(name='TkFixedFont', exists=True, root=root)
+ actualFont = Font.actual(f)
+ family = actualFont['family']
+ size = actualFont['size']
+ if size <= 0:
+ size = 10 # if font in pixels, ignore actual size
+ bold = actualFont['weight'] == 'bold'
return (family, size, 'bold' if bold else 'normal')
def LoadCfgFiles(self):
@@ -739,6 +766,18 @@ class IdleConf:
idleConf = IdleConf()
+
+_warned = set()
+def _warn(msg, *key):
+ key = (msg,) + key
+ if key not in _warned:
+ try:
+ print(msg, file=sys.stderr)
+ except OSError:
+ pass
+ _warned.add(key)
+
+
# TODO Revise test output, write expanded unittest
#
if __name__ == '__main__':
diff --git a/Lib/idlelib/configHelpSourceEdit.py b/Lib/idlelib/configHelpSourceEdit.py
deleted file mode 100644
index cde8118..0000000
--- a/Lib/idlelib/configHelpSourceEdit.py
+++ /dev/null
@@ -1,170 +0,0 @@
-"Dialog to specify or edit the parameters for a user configured help source."
-
-import os
-import sys
-
-from tkinter import *
-import tkinter.messagebox as tkMessageBox
-import tkinter.filedialog as tkFileDialog
-
-class GetHelpSourceDialog(Toplevel):
- def __init__(self, parent, title, menuItem='', filePath='', _htest=False):
- """Get menu entry and url/ local file location for Additional Help
-
- User selects a name for the Help resource and provides a web url
- or a local file as its source. The user can enter a url or browse
- for the file.
-
- _htest - bool, change box location when running htest
- """
- Toplevel.__init__(self, parent)
- self.configure(borderwidth=5)
- self.resizable(height=FALSE, width=FALSE)
- self.title(title)
- self.transient(parent)
- self.grab_set()
- self.protocol("WM_DELETE_WINDOW", self.cancel)
- self.parent = parent
- self.result = None
- self.create_widgets()
- self.menu.set(menuItem)
- self.path.set(filePath)
- self.withdraw() #hide while setting geometry
- #needs to be done here so that the winfo_reqwidth is valid
- self.update_idletasks()
- #centre dialog over parent. below parent if running htest.
- self.geometry(
- "+%d+%d" % (
- parent.winfo_rootx() +
- (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
- parent.winfo_rooty() +
- ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
- if not _htest else 150)))
- self.deiconify() #geometry set, unhide
- self.bind('<Return>', self.ok)
- self.wait_window()
-
- def create_widgets(self):
- self.menu = StringVar(self)
- self.path = StringVar(self)
- self.fontSize = StringVar(self)
- self.frameMain = Frame(self, borderwidth=2, relief=GROOVE)
- self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
- labelMenu = Label(self.frameMain, anchor=W, justify=LEFT,
- text='Menu Item:')
- self.entryMenu = Entry(self.frameMain, textvariable=self.menu,
- width=30)
- self.entryMenu.focus_set()
- labelPath = Label(self.frameMain, anchor=W, justify=LEFT,
- text='Help File Path: Enter URL or browse for file')
- self.entryPath = Entry(self.frameMain, textvariable=self.path,
- width=40)
- self.entryMenu.focus_set()
- labelMenu.pack(anchor=W, padx=5, pady=3)
- self.entryMenu.pack(anchor=W, padx=5, pady=3)
- labelPath.pack(anchor=W, padx=5, pady=3)
- self.entryPath.pack(anchor=W, padx=5, pady=3)
- browseButton = Button(self.frameMain, text='Browse', width=8,
- command=self.browse_file)
- browseButton.pack(pady=3)
- frameButtons = Frame(self)
- frameButtons.pack(side=BOTTOM, fill=X)
- self.buttonOk = Button(frameButtons, text='OK',
- width=8, default=ACTIVE, command=self.ok)
- self.buttonOk.grid(row=0, column=0, padx=5,pady=5)
- self.buttonCancel = Button(frameButtons, text='Cancel',
- width=8, command=self.cancel)
- self.buttonCancel.grid(row=0, column=1, padx=5, pady=5)
-
- def browse_file(self):
- filetypes = [
- ("HTML Files", "*.htm *.html", "TEXT"),
- ("PDF Files", "*.pdf", "TEXT"),
- ("Windows Help Files", "*.chm"),
- ("Text Files", "*.txt", "TEXT"),
- ("All Files", "*")]
- path = self.path.get()
- if path:
- dir, base = os.path.split(path)
- else:
- base = None
- if sys.platform[:3] == 'win':
- dir = os.path.join(os.path.dirname(sys.executable), 'Doc')
- if not os.path.isdir(dir):
- dir = os.getcwd()
- else:
- dir = os.getcwd()
- opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes)
- file = opendialog.show(initialdir=dir, initialfile=base)
- if file:
- self.path.set(file)
-
- def menu_ok(self):
- "Simple validity check for a sensible menu item name"
- menu_ok = True
- menu = self.menu.get()
- menu.strip()
- if not menu:
- tkMessageBox.showerror(title='Menu Item Error',
- message='No menu item specified',
- parent=self)
- self.entryMenu.focus_set()
- menu_ok = False
- elif len(menu) > 30:
- tkMessageBox.showerror(title='Menu Item Error',
- message='Menu item too long:'
- '\nLimit 30 characters.',
- parent=self)
- self.entryMenu.focus_set()
- menu_ok = False
- return menu_ok
-
- def path_ok(self):
- "Simple validity check for menu file path"
- path_ok = True
- path = self.path.get()
- path.strip()
- if not path: #no path specified
- tkMessageBox.showerror(title='File Path Error',
- message='No help file path specified.',
- parent=self)
- self.entryPath.focus_set()
- path_ok = False
- elif path.startswith(('www.', 'http')):
- pass
- else:
- if path[:5] == 'file:':
- path = path[5:]
- if not os.path.exists(path):
- tkMessageBox.showerror(title='File Path Error',
- message='Help file path does not exist.',
- parent=self)
- self.entryPath.focus_set()
- path_ok = False
- return path_ok
-
- def ok(self, event=None):
- if self.menu_ok() and self.path_ok():
- self.result = (self.menu.get().strip(),
- self.path.get().strip())
- if sys.platform == 'darwin':
- path = self.result[1]
- if path.startswith(('www', 'file:', 'http:', 'https:')):
- pass
- else:
- # Mac Safari insists on using the URI form for local files
- self.result = list(self.result)
- self.result[1] = "file://" + path
- self.destroy()
-
- def cancel(self, event=None):
- self.result = None
- self.destroy()
-
-if __name__ == '__main__':
- import unittest
- unittest.main('idlelib.idle_test.test_config_help',
- verbosity=2, exit=False)
-
- from idlelib.idle_test.htest import run
- run(GetHelpSourceDialog)
diff --git a/Lib/idlelib/configSectionNameDialog.py b/Lib/idlelib/configSectionNameDialog.py
deleted file mode 100644
index 5137836..0000000
--- a/Lib/idlelib/configSectionNameDialog.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""
-Dialog that allows user to specify a new config file section name.
-Used to get new highlight theme and keybinding set names.
-The 'return value' for the dialog, used two placed in configDialog.py,
-is the .result attribute set in the Ok and Cancel methods.
-"""
-from tkinter import *
-import tkinter.messagebox as tkMessageBox
-
-class GetCfgSectionNameDialog(Toplevel):
- def __init__(self, parent, title, message, used_names, _htest=False):
- """
- message - string, informational message to display
- used_names - string collection, names already in use for validity check
- _htest - bool, change box location when running htest
- """
- Toplevel.__init__(self, parent)
- self.configure(borderwidth=5)
- self.resizable(height=FALSE, width=FALSE)
- self.title(title)
- self.transient(parent)
- self.grab_set()
- self.protocol("WM_DELETE_WINDOW", self.Cancel)
- self.parent = parent
- self.message = message
- self.used_names = used_names
- self.create_widgets()
- self.withdraw() #hide while setting geometry
- self.update_idletasks()
- #needs to be done here so that the winfo_reqwidth is valid
- self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
- self.geometry(
- "+%d+%d" % (
- parent.winfo_rootx() +
- (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
- parent.winfo_rooty() +
- ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
- if not _htest else 100)
- ) ) #centre dialog over parent (or below htest box)
- self.deiconify() #geometry set, unhide
- self.wait_window()
-
- def create_widgets(self):
- self.name = StringVar(self.parent)
- self.fontSize = StringVar(self.parent)
- self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
- self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
- self.messageInfo = Message(self.frameMain, anchor=W, justify=LEFT,
- padx=5, pady=5, text=self.message) #,aspect=200)
- entryName = Entry(self.frameMain, textvariable=self.name, width=30)
- entryName.focus_set()
- self.messageInfo.pack(padx=5, pady=5) #, expand=TRUE, fill=BOTH)
- entryName.pack(padx=5, pady=5)
-
- frameButtons = Frame(self, pady=2)
- frameButtons.pack(side=BOTTOM)
- self.buttonOk = Button(frameButtons, text='Ok',
- width=8, command=self.Ok)
- self.buttonOk.pack(side=LEFT, padx=5)
- self.buttonCancel = Button(frameButtons, text='Cancel',
- width=8, command=self.Cancel)
- self.buttonCancel.pack(side=RIGHT, padx=5)
-
- def name_ok(self):
- ''' After stripping entered name, check that it is a sensible
- ConfigParser file section name. Return it if it is, '' if not.
- '''
- name = self.name.get().strip()
- if not name: #no name specified
- tkMessageBox.showerror(title='Name Error',
- message='No name specified.', parent=self)
- elif len(name)>30: #name too long
- tkMessageBox.showerror(title='Name Error',
- message='Name too long. It should be no more than '+
- '30 characters.', parent=self)
- name = ''
- elif name in self.used_names:
- tkMessageBox.showerror(title='Name Error',
- message='This name is already in use.', parent=self)
- name = ''
- return name
-
- def Ok(self, event=None):
- name = self.name_ok()
- if name:
- self.result = name
- self.destroy()
-
- def Cancel(self, event=None):
- self.result = ''
- self.destroy()
-
-if __name__ == '__main__':
- import unittest
- unittest.main('idlelib.idle_test.test_config_name', verbosity=2, exit=False)
-
- from idlelib.idle_test.htest import run
- run(GetCfgSectionNameDialog)
diff --git a/Lib/idlelib/keybindingDialog.py b/Lib/idlelib/config_key.py
index e6438bf..2602293 100644
--- a/Lib/idlelib/keybindingDialog.py
+++ b/Lib/idlelib/config_key.py
@@ -2,31 +2,35 @@
Dialog for building Tkinter accelerator key bindings
"""
from tkinter import *
+from tkinter.ttk import Scrollbar
import tkinter.messagebox as tkMessageBox
import string
import sys
class GetKeysDialog(Toplevel):
- def __init__(self,parent,title,action,currentKeySequences,_htest=False):
+ def __init__(self, parent, title, action, currentKeySequences,
+ _htest=False, _utest=False):
"""
action - string, the name of the virtual event these keys will be
mapped to
currentKeys - list, a list of all key sequence lists currently mapped
to virtual events, for overlap checking
+ _utest - bool, do not wait when running unittest
_htest - bool, change box location when running htest
"""
Toplevel.__init__(self, parent)
+ self.withdraw() #hide while setting geometry
self.configure(borderwidth=5)
- self.resizable(height=FALSE,width=FALSE)
+ self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.Cancel)
self.parent = parent
self.action=action
- self.currentKeySequences=currentKeySequences
- self.result=''
- self.keyString=StringVar(self)
+ self.currentKeySequences = currentKeySequences
+ self.result = ''
+ self.keyString = StringVar(self)
self.keyString.set('')
self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label
self.modifier_vars = []
@@ -37,7 +41,6 @@ class GetKeysDialog(Toplevel):
self.advanced = False
self.CreateWidgets()
self.LoadFinalKeyList()
- self.withdraw() #hide while setting geometry
self.update_idletasks()
self.geometry(
"+%d+%d" % (
@@ -47,8 +50,9 @@ class GetKeysDialog(Toplevel):
((parent.winfo_height()/2 - self.winfo_reqheight()/2)
if not _htest else 150)
) ) #centre dialog over parent (or below htest box)
- self.deiconify() #geometry set, unhide
- self.wait_window()
+ if not _utest:
+ self.deiconify() #geometry set, unhide
+ self.wait_window()
def CreateWidgets(self):
frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
@@ -261,6 +265,7 @@ class GetKeysDialog(Toplevel):
keysOK = True
return keysOK
+
if __name__ == '__main__':
from idlelib.idle_test.htest import run
run(GetKeysDialog)
diff --git a/Lib/idlelib/configDialog.py b/Lib/idlelib/configdialog.py
index 5f5bd36..8184582 100644
--- a/Lib/idlelib/configDialog.py
+++ b/Lib/idlelib/configdialog.py
@@ -10,18 +10,18 @@ Refer to comments in EditorWindow autoindent code for details.
"""
from tkinter import *
-import tkinter.messagebox as tkMessageBox
+from tkinter.ttk import Scrollbar
import tkinter.colorchooser as tkColorChooser
import tkinter.font as tkFont
+import tkinter.messagebox as tkMessageBox
-from idlelib.configHandler import idleConf
-from idlelib.dynOptionMenuWidget import DynOptionMenu
-from idlelib.keybindingDialog import GetKeysDialog
-from idlelib.configSectionNameDialog import GetCfgSectionNameDialog
-from idlelib.configHelpSourceEdit import GetHelpSourceDialog
+from idlelib.config import idleConf
+from idlelib.config_key import GetKeysDialog
+from idlelib.dynoption import DynOptionMenu
+from idlelib import macosx
+from idlelib.query import SectionName, HelpSource
from idlelib.tabbedpages import TabbedPageSet
-from idlelib.textView import view_text
-from idlelib import macosxSupport
+from idlelib.textview import view_text
class ConfigDialog(Toplevel):
@@ -91,7 +91,7 @@ class ConfigDialog(Toplevel):
self.create_action_buttons().pack(side=BOTTOM)
def create_action_buttons(self):
- if macosxSupport.isAquaTk():
+ if macosx.isAquaTk():
# Changing the default padding on OSX results in unreadable
# text in the buttons
paddingArgs = {}
@@ -341,6 +341,7 @@ class ConfigDialog(Toplevel):
buttonSaveCustomKeys = Button(
frames[1], text='Save as New Custom Key Set',
command=self.SaveAsNewKeySet)
+ self.new_custom_keys = Label(frames[0], bd=2)
##widget packing
#body
@@ -361,6 +362,7 @@ class ConfigDialog(Toplevel):
self.radioKeysCustom.grid(row=1, column=0, sticky=W+NS)
self.optMenuKeysBuiltin.grid(row=0, column=1, sticky=NSEW)
self.optMenuKeysCustom.grid(row=1, column=1, sticky=NSEW)
+ self.new_custom_keys.grid(row=0, column=2, sticky=NSEW, padx=5, pady=5)
self.buttonDeleteCustomKeys.pack(side=LEFT, fill=X, expand=True, padx=2)
buttonSaveCustomKeys.pack(side=LEFT, fill=X, expand=True, padx=2)
frames[0].pack(side=TOP, fill=BOTH, expand=True)
@@ -390,28 +392,28 @@ class ConfigDialog(Toplevel):
text=' Additional Help Sources ')
#frameRun
labelRunChoiceTitle = Label(frameRun, text='At Startup')
- radioStartupEdit = Radiobutton(
+ self.radioStartupEdit = Radiobutton(
frameRun, variable=self.startupEdit, value=1,
- command=self.SetKeysType, text="Open Edit Window")
- radioStartupShell = Radiobutton(
+ text="Open Edit Window")
+ self.radioStartupShell = Radiobutton(
frameRun, variable=self.startupEdit, value=0,
- command=self.SetKeysType, text='Open Shell Window')
+ text='Open Shell Window')
#frameSave
labelRunSaveTitle = Label(frameSave, text='At Start of Run (F5) ')
- radioSaveAsk = Radiobutton(
+ self.radioSaveAsk = Radiobutton(
frameSave, variable=self.autoSave, value=0,
- command=self.SetKeysType, text="Prompt to Save")
- radioSaveAuto = Radiobutton(
+ text="Prompt to Save")
+ self.radioSaveAuto = Radiobutton(
frameSave, variable=self.autoSave, value=1,
- command=self.SetKeysType, text='No Prompt')
+ text='No Prompt')
#frameWinSize
labelWinSizeTitle = Label(
frameWinSize, text='Initial Window Size (in characters)')
labelWinWidthTitle = Label(frameWinSize, text='Width')
- entryWinWidth = Entry(
+ self.entryWinWidth = Entry(
frameWinSize, textvariable=self.winWidth, width=3)
labelWinHeightTitle = Label(frameWinSize, text='Height')
- entryWinHeight = Entry(
+ self.entryWinHeight = Entry(
frameWinSize, textvariable=self.winHeight, width=3)
#frameHelp
frameHelpList = Frame(frameHelp)
@@ -441,17 +443,17 @@ class ConfigDialog(Toplevel):
frameHelp.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
#frameRun
labelRunChoiceTitle.pack(side=LEFT, anchor=W, padx=5, pady=5)
- radioStartupShell.pack(side=RIGHT, anchor=W, padx=5, pady=5)
- radioStartupEdit.pack(side=RIGHT, anchor=W, padx=5, pady=5)
+ self.radioStartupShell.pack(side=RIGHT, anchor=W, padx=5, pady=5)
+ self.radioStartupEdit.pack(side=RIGHT, anchor=W, padx=5, pady=5)
#frameSave
labelRunSaveTitle.pack(side=LEFT, anchor=W, padx=5, pady=5)
- radioSaveAuto.pack(side=RIGHT, anchor=W, padx=5, pady=5)
- radioSaveAsk.pack(side=RIGHT, anchor=W, padx=5, pady=5)
+ self.radioSaveAuto.pack(side=RIGHT, anchor=W, padx=5, pady=5)
+ self.radioSaveAsk.pack(side=RIGHT, anchor=W, padx=5, pady=5)
#frameWinSize
labelWinSizeTitle.pack(side=LEFT, anchor=W, padx=5, pady=5)
- entryWinHeight.pack(side=RIGHT, anchor=E, padx=10, pady=5)
+ self.entryWinHeight.pack(side=RIGHT, anchor=E, padx=10, pady=5)
labelWinHeightTitle.pack(side=RIGHT, anchor=E, pady=5)
- entryWinWidth.pack(side=RIGHT, anchor=E, padx=10, pady=5)
+ self.entryWinWidth.pack(side=RIGHT, anchor=E, padx=10, pady=5)
labelWinWidthTitle.pack(side=RIGHT, anchor=E, pady=5)
#frameHelp
frameHelpListButtons.pack(side=RIGHT, padx=5, pady=5, fill=Y)
@@ -464,24 +466,24 @@ class ConfigDialog(Toplevel):
return frame
def AttachVarCallbacks(self):
- self.fontSize.trace_variable('w', self.VarChanged_font)
- self.fontName.trace_variable('w', self.VarChanged_font)
- self.fontBold.trace_variable('w', self.VarChanged_font)
- self.spaceNum.trace_variable('w', self.VarChanged_spaceNum)
- self.colour.trace_variable('w', self.VarChanged_colour)
- self.builtinTheme.trace_variable('w', self.VarChanged_builtinTheme)
- self.customTheme.trace_variable('w', self.VarChanged_customTheme)
- self.themeIsBuiltin.trace_variable('w', self.VarChanged_themeIsBuiltin)
- self.highlightTarget.trace_variable('w', self.VarChanged_highlightTarget)
- self.keyBinding.trace_variable('w', self.VarChanged_keyBinding)
- self.builtinKeys.trace_variable('w', self.VarChanged_builtinKeys)
- self.customKeys.trace_variable('w', self.VarChanged_customKeys)
- self.keysAreBuiltin.trace_variable('w', self.VarChanged_keysAreBuiltin)
- self.winWidth.trace_variable('w', self.VarChanged_winWidth)
- self.winHeight.trace_variable('w', self.VarChanged_winHeight)
- self.startupEdit.trace_variable('w', self.VarChanged_startupEdit)
- self.autoSave.trace_variable('w', self.VarChanged_autoSave)
- self.encoding.trace_variable('w', self.VarChanged_encoding)
+ self.fontSize.trace_add('write', self.VarChanged_font)
+ self.fontName.trace_add('write', self.VarChanged_font)
+ self.fontBold.trace_add('write', self.VarChanged_font)
+ self.spaceNum.trace_add('write', self.VarChanged_spaceNum)
+ self.colour.trace_add('write', self.VarChanged_colour)
+ self.builtinTheme.trace_add('write', self.VarChanged_builtinTheme)
+ self.customTheme.trace_add('write', self.VarChanged_customTheme)
+ self.themeIsBuiltin.trace_add('write', self.VarChanged_themeIsBuiltin)
+ self.highlightTarget.trace_add('write', self.VarChanged_highlightTarget)
+ self.keyBinding.trace_add('write', self.VarChanged_keyBinding)
+ self.builtinKeys.trace_add('write', self.VarChanged_builtinKeys)
+ self.customKeys.trace_add('write', self.VarChanged_customKeys)
+ self.keysAreBuiltin.trace_add('write', self.VarChanged_keysAreBuiltin)
+ self.winWidth.trace_add('write', self.VarChanged_winWidth)
+ self.winHeight.trace_add('write', self.VarChanged_winHeight)
+ self.startupEdit.trace_add('write', self.VarChanged_startupEdit)
+ self.autoSave.trace_add('write', self.VarChanged_autoSave)
+ self.encoding.trace_add('write', self.VarChanged_encoding)
def remove_var_callbacks(self):
"Remove callbacks to prevent memory leaks."
@@ -492,7 +494,7 @@ class ConfigDialog(Toplevel):
self.keyBinding, self.builtinKeys, self.customKeys,
self.keysAreBuiltin, self.winWidth, self.winHeight,
self.startupEdit, self.autoSave, self.encoding,):
- var.trace_vdelete('w', var.trace_vinfo()[0][1])
+ var.trace_remove('write', var.trace_info()[0][1])
def VarChanged_font(self, *params):
'''When one font attribute changes, save them all, as they are
@@ -514,10 +516,11 @@ class ConfigDialog(Toplevel):
self.OnNewColourSet()
def VarChanged_builtinTheme(self, *params):
+ oldthemes = ('IDLE Classic', 'IDLE New')
value = self.builtinTheme.get()
- if value == 'IDLE Dark':
- if idleConf.GetOption('main', 'Theme', 'name') != 'IDLE New':
- self.AddChangedItem('main', 'Theme', 'name', 'IDLE Classic')
+ if value not in oldthemes:
+ if idleConf.GetOption('main', 'Theme', 'name') not in oldthemes:
+ self.AddChangedItem('main', 'Theme', 'name', oldthemes[0])
self.AddChangedItem('main', 'Theme', 'name2', value)
self.new_custom_theme.config(text='New theme, see Help',
fg='#500000')
@@ -557,8 +560,23 @@ class ConfigDialog(Toplevel):
self.AddChangedItem('extensions', extKeybindSection, event, value)
def VarChanged_builtinKeys(self, *params):
+ oldkeys = (
+ 'IDLE Classic Windows',
+ 'IDLE Classic Unix',
+ 'IDLE Classic Mac',
+ 'IDLE Classic OSX',
+ )
value = self.builtinKeys.get()
- self.AddChangedItem('main', 'Keys', 'name', value)
+ if value not in oldkeys:
+ if idleConf.GetOption('main', 'Keys', 'name') not in oldkeys:
+ self.AddChangedItem('main', 'Keys', 'name', oldkeys[0])
+ self.AddChangedItem('main', 'Keys', 'name2', value)
+ self.new_custom_keys.config(text='New key set, see Help',
+ fg='#500000')
+ else:
+ self.AddChangedItem('main', 'Keys', 'name', value)
+ self.AddChangedItem('main', 'Keys', 'name2', '')
+ self.new_custom_keys.config(text='', fg='black')
self.LoadKeysList(value)
def VarChanged_customKeys(self, *params):
@@ -683,7 +701,7 @@ class ConfigDialog(Toplevel):
def GetNewKeysName(self, message):
usedNames = (idleConf.GetSectionList('user', 'keys') +
idleConf.GetSectionList('default', 'keys'))
- newKeySet = GetCfgSectionNameDialog(
+ newKeySet = SectionName(
self, 'New Custom Key Set', message, usedNames).result
return newKeySet
@@ -767,8 +785,10 @@ class ConfigDialog(Toplevel):
else:
self.optMenuKeysCustom.SetMenu(itemList, itemList[0])
#revert to default key set
- self.keysAreBuiltin.set(idleConf.defaultCfg['main'].Get('Keys', 'default'))
- self.builtinKeys.set(idleConf.defaultCfg['main'].Get('Keys', 'name'))
+ self.keysAreBuiltin.set(idleConf.defaultCfg['main']
+ .Get('Keys', 'default'))
+ self.builtinKeys.set(idleConf.defaultCfg['main'].Get('Keys', 'name')
+ or idleConf.default_keys())
#user can't back out of these changes, they must be applied now
self.SaveAllChangedConfigs()
self.ActivateConfigChanges()
@@ -836,7 +856,7 @@ class ConfigDialog(Toplevel):
def GetNewThemeName(self, message):
usedNames = (idleConf.GetSectionList('user', 'highlight') +
idleConf.GetSectionList('default', 'highlight'))
- newTheme = GetCfgSectionNameDialog(
+ newTheme = SectionName(
self, 'New Custom Theme', message, usedNames).result
return newTheme
@@ -939,7 +959,8 @@ class ConfigDialog(Toplevel):
self.buttonHelpListRemove.config(state=DISABLED)
def HelpListItemAdd(self):
- helpSource = GetHelpSourceDialog(self, 'New Help Source').result
+ helpSource = HelpSource(self, 'New Help Source',
+ ).result
if helpSource:
self.userHelpList.append((helpSource[0], helpSource[1]))
self.listHelp.insert(END, helpSource[0])
@@ -949,16 +970,17 @@ class ConfigDialog(Toplevel):
def HelpListItemEdit(self):
itemIndex = self.listHelp.index(ANCHOR)
helpSource = self.userHelpList[itemIndex]
- newHelpSource = GetHelpSourceDialog(
- self, 'Edit Help Source', menuItem=helpSource[0],
- filePath=helpSource[1]).result
- if (not newHelpSource) or (newHelpSource == helpSource):
- return #no changes
- self.userHelpList[itemIndex] = newHelpSource
- self.listHelp.delete(itemIndex)
- self.listHelp.insert(itemIndex, newHelpSource[0])
- self.UpdateUserHelpChangedItems()
- self.SetHelpListButtonStates()
+ newHelpSource = HelpSource(
+ self, 'Edit Help Source',
+ menuitem=helpSource[0],
+ filepath=helpSource[1],
+ ).result
+ if newHelpSource and newHelpSource != helpSource:
+ self.userHelpList[itemIndex] = newHelpSource
+ self.listHelp.delete(itemIndex)
+ self.listHelp.insert(itemIndex, newHelpSource[0])
+ self.UpdateUserHelpChangedItems()
+ self.SetHelpListButtonStates()
def HelpListItemRemove(self):
itemIndex = self.listHelp.index(ANCHOR)
@@ -996,7 +1018,8 @@ class ConfigDialog(Toplevel):
pass
##font size dropdown
self.optMenuFontSize.SetMenu(('7', '8', '9', '10', '11', '12', '13',
- '14', '16', '18', '20', '22'), fontSize )
+ '14', '16', '18', '20', '22',
+ '25', '29', '34', '40'), fontSize )
##fontWeight
self.fontBold.set(fontBold)
##font sample
@@ -1065,7 +1088,7 @@ class ConfigDialog(Toplevel):
self.optMenuKeysCustom.SetMenu(itemList, currentOption)
itemList = idleConf.GetSectionList('default', 'keys')
itemList.sort()
- self.optMenuKeysBuiltin.SetMenu(itemList, itemList[0])
+ self.optMenuKeysBuiltin.SetMenu(itemList, idleConf.default_keys())
self.SetKeysType()
##load keyset element list
keySetName = idleConf.CurrentKeys()
@@ -1367,12 +1390,18 @@ machine. Some do not take affect until IDLE is restarted.
[Cancel] only cancels changes made since the last save.
'''
help_pages = {
- 'Highlighting':'''
+ 'Highlighting': '''
Highlighting:
The IDLE Dark color theme is new in October 2015. It can only
be used with older IDLE releases if it is saved as a custom
theme, with a different name.
-'''
+''',
+ 'Keys': '''
+Keys:
+The IDLE Modern Unix key set is new in June 2016. It can only
+be used with older IDLE releases if it is saved as a custom
+key set, with a different name.
+''',
}
diff --git a/Lib/idlelib/Debugger.py b/Lib/idlelib/debugger.py
index d5e217d..114d0d1 100644
--- a/Lib/idlelib/Debugger.py
+++ b/Lib/idlelib/debugger.py
@@ -1,9 +1,12 @@
-import os
import bdb
+import os
+
from tkinter import *
-from idlelib.WindowList import ListedToplevel
-from idlelib.ScrolledList import ScrolledList
-from idlelib import macosxSupport
+from tkinter.ttk import Scrollbar
+
+from idlelib import macosx
+from idlelib.scrolledlist import ScrolledList
+from idlelib.windows import ListedToplevel
class Idb(bdb.Bdb):
@@ -34,8 +37,10 @@ class Idb(bdb.Bdb):
return True
else:
prev_frame = frame.f_back
- if prev_frame.f_code.co_filename.count('Debugger.py'):
- # (that test will catch both Debugger.py and RemoteDebugger.py)
+ prev_name = prev_frame.f_code.co_filename
+ if 'idlelib' in prev_name and 'debugger' in prev_name:
+ # catch both idlelib/debugger.py and idlelib/debugger_r.py
+ # on both posix and windows
return False
return self.in_rpc_code(prev_frame)
@@ -370,7 +375,7 @@ class Debugger:
class StackViewer(ScrolledList):
def __init__(self, master, flist, gui):
- if macosxSupport.isAquaTk():
+ if macosx.isAquaTk():
# At least on with the stock AquaTk version on OSX 10.4 you'll
# get a shaking GUI that eventually kills IDLE if the width
# argument is specified.
@@ -502,7 +507,7 @@ class NamespaceViewer:
#
# There is also an obscure bug in sorted(dict) where the
# interpreter gets into a loop requesting non-existing dict[0],
- # dict[1], dict[2], etc from the RemoteDebugger.DictProxy.
+ # dict[1], dict[2], etc from the debugger_r.DictProxy.
###
keys_list = dict.keys()
names = sorted(keys_list)
diff --git a/Lib/idlelib/RemoteDebugger.py b/Lib/idlelib/debugger_r.py
index be2262f..bc97127 100644
--- a/Lib/idlelib/RemoteDebugger.py
+++ b/Lib/idlelib/debugger_r.py
@@ -21,7 +21,7 @@ barrier, in particular frame and traceback objects.
"""
import types
-from idlelib import Debugger
+from idlelib import debugger
debugging = 0
@@ -187,7 +187,7 @@ def start_debugger(rpchandler, gui_adap_oid):
"""
gui_proxy = GUIProxy(rpchandler, gui_adap_oid)
- idb = Debugger.Idb(gui_proxy)
+ idb = debugger.Idb(gui_proxy)
idb_adap = IdbAdapter(idb)
rpchandler.register(idb_adap_oid, idb_adap)
return idb_adap_oid
@@ -362,7 +362,7 @@ def start_remote_debugger(rpcclt, pyshell):
idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\
(gui_adap_oid,), {})
idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid)
- gui = Debugger.Debugger(pyshell, idb_proxy)
+ gui = debugger.Debugger(pyshell, idb_proxy)
gui_adap = GUIAdapter(rpcclt, gui)
rpcclt.register(gui_adap_oid, gui_adap)
return gui
@@ -373,7 +373,7 @@ def close_remote_debugger(rpcclt):
Request that the RPCServer shut down the subprocess debugger and link.
Unregister the GUIAdapter, which will cause a GC on the Idle process
debugger and RPC link objects. (The second reference to the debugger GUI
- is deleted in PyShell.close_remote_debugger().)
+ is deleted in pyshell.close_remote_debugger().)
"""
close_subprocess_debugger(rpcclt)
diff --git a/Lib/idlelib/ObjectBrowser.py b/Lib/idlelib/debugobj.py
index 7b57aa4..b70b13c 100644
--- a/Lib/idlelib/ObjectBrowser.py
+++ b/Lib/idlelib/debugobj.py
@@ -8,13 +8,10 @@
# XXX TO DO:
# - for classes/modules, add "open source" to object browser
-
-import re
-
-from idlelib.TreeWidget import TreeItem, TreeNode, ScrolledCanvas
-
from reprlib import Repr
+from idlelib.tree import TreeItem, TreeNode, ScrolledCanvas
+
myrepr = Repr()
myrepr.maxstring = 100
myrepr.maxother = 100
@@ -122,21 +119,20 @@ def make_objecttreeitem(labeltext, object, setfunction=None):
return c(labeltext, object, setfunction)
-def _object_browser(parent):
+def _object_browser(parent): # htest #
import sys
- from tkinter import Tk
- root = Tk()
- root.title("Test ObjectBrowser")
- width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
- root.geometry("+%d+%d"%(x, y + 150))
- root.configure(bd=0, bg="yellow")
- root.focus_set()
- sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
+ from tkinter import Toplevel
+ top = Toplevel(parent)
+ top.title("Test debug object browser")
+ x, y = map(int, parent.geometry().split('+')[1:])
+ top.geometry("+%d+%d" % (x + 100, y + 175))
+ top.configure(bd=0, bg="yellow")
+ top.focus_set()
+ sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both")
item = make_objecttreeitem("sys", sys)
node = TreeNode(sc.canvas, None, item)
node.update()
- root.mainloop()
if __name__ == '__main__':
from idlelib.idle_test.htest import run
diff --git a/Lib/idlelib/RemoteObjectBrowser.py b/Lib/idlelib/debugobj_r.py
index 8031aae..8031aae 100644
--- a/Lib/idlelib/RemoteObjectBrowser.py
+++ b/Lib/idlelib/debugobj_r.py
diff --git a/Lib/idlelib/Delegator.py b/Lib/idlelib/delegator.py
index dc2a1aa..dc2a1aa 100644
--- a/Lib/idlelib/Delegator.py
+++ b/Lib/idlelib/delegator.py
diff --git a/Lib/idlelib/dynOptionMenuWidget.py b/Lib/idlelib/dynoption.py
index 515b4ba..9c6ffa4 100644
--- a/Lib/idlelib/dynOptionMenuWidget.py
+++ b/Lib/idlelib/dynoption.py
@@ -3,6 +3,7 @@ OptionMenu widget modified to allow dynamic menu reconfiguration
and setting of highlightthickness
"""
import copy
+
from tkinter import OptionMenu, _setit, StringVar, Button
class DynOptionMenu(OptionMenu):
@@ -34,12 +35,12 @@ class DynOptionMenu(OptionMenu):
self.variable.set(value)
def _dyn_option_menu(parent): # htest #
- from tkinter import Toplevel
+ from tkinter import Toplevel # + StringVar, Button
- top = Toplevel()
+ top = Toplevel(parent)
top.title("Tets dynamic option menu")
- top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
- parent.winfo_rooty() + 150))
+ x, y = map(int, parent.geometry().split('+')[1:])
+ top.geometry("200x100+%d+%d" % (x + 250, y + 175))
top.focus_set()
var = StringVar(top)
diff --git a/Lib/idlelib/EditorWindow.py b/Lib/idlelib/editor.py
index 9944da3..ae475cb 100644
--- a/Lib/idlelib/EditorWindow.py
+++ b/Lib/idlelib/editor.py
@@ -6,28 +6,34 @@ import platform
import re
import string
import sys
+import tokenize
+import traceback
+import webbrowser
+
from tkinter import *
+from tkinter.ttk import Scrollbar
import tkinter.simpledialog as tkSimpleDialog
import tkinter.messagebox as tkMessageBox
-import traceback
-import webbrowser
-from idlelib.MultiCall import MultiCallCreator
-from idlelib import WindowList
-from idlelib import SearchDialog
-from idlelib import GrepDialog
-from idlelib import ReplaceDialog
-from idlelib import PyParse
-from idlelib.configHandler import idleConf
-from idlelib import aboutDialog, textView, configDialog
-from idlelib import macosxSupport
+from idlelib.config import idleConf
+from idlelib import configdialog
+from idlelib import grep
from idlelib import help
+from idlelib import help_about
+from idlelib import macosx
+from idlelib.multicall import MultiCallCreator
+from idlelib import pyparse
+from idlelib import query
+from idlelib import replace
+from idlelib import search
+from idlelib import textview
+from idlelib import windows
# The default tab setting for a Text widget, in average-width characters.
TK_TABWIDTH_DEFAULT = 8
-
_py_version = ' (%s)' % platform.python_version()
+
def _sphinx_version():
"Format sys.version_info to produce the Sphinx version string used to install the chm docs"
major, minor, micro, level, serial = sys.version_info
@@ -40,63 +46,16 @@ def _sphinx_version():
return release
-class HelpDialog(object):
-
- def __init__(self):
- self.parent = None # parent of help window
- self.dlg = None # the help window iteself
-
- def display(self, parent, near=None):
- """ Display the help dialog.
-
- parent - parent widget for the help window
-
- near - a Toplevel widget (e.g. EditorWindow or PyShell)
- to use as a reference for placing the help window
- """
- import warnings as w
- w.warn("EditorWindow.HelpDialog is no longer used by Idle.\n"
- "It will be removed in 3.6 or later.\n"
- "It has been replaced by private help.HelpWindow\n",
- DeprecationWarning, stacklevel=2)
- if self.dlg is None:
- self.show_dialog(parent)
- if near:
- self.nearwindow(near)
-
- def show_dialog(self, parent):
- self.parent = parent
- fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt')
- self.dlg = dlg = textView.view_file(parent,'Help',fn, modal=False)
- dlg.bind('<Destroy>', self.destroy, '+')
-
- def nearwindow(self, near):
- # Place the help dialog near the window specified by parent.
- # Note - this may not reposition the window in Metacity
- # if "/apps/metacity/general/disable_workarounds" is enabled
- dlg = self.dlg
- geom = (near.winfo_rootx() + 10, near.winfo_rooty() + 10)
- dlg.withdraw()
- dlg.geometry("=+%d+%d" % geom)
- dlg.deiconify()
- dlg.lift()
-
- def destroy(self, ev=None):
- self.dlg = None
- self.parent = None
-
-helpDialog = HelpDialog() # singleton instance, no longer used
-
-
class EditorWindow(object):
- from idlelib.Percolator import Percolator
- from idlelib.ColorDelegator import ColorDelegator, color_config
- from idlelib.UndoDelegator import UndoDelegator
- from idlelib.IOBinding import IOBinding, filesystemencoding, encoding
- from idlelib import Bindings
+ from idlelib.percolator import Percolator
+ from idlelib.colorizer import ColorDelegator, color_config
+ from idlelib.undo import UndoDelegator
+ from idlelib.iomenu import IOBinding, encoding
+ from idlelib import mainmenu
from tkinter import Toplevel
- from idlelib.MultiStatusBar import MultiStatusBar
+ from idlelib.statusbar import MultiStatusBar
+ filesystemencoding = sys.getfilesystemencoding() # for file names
help_url = None
def __init__(self, flist=None, filename=None, key=None, root=None):
@@ -136,11 +95,11 @@ class EditorWindow(object):
except AttributeError:
sys.ps1 = '>>> '
self.menubar = Menu(root)
- self.top = top = WindowList.ListedToplevel(root, menu=self.menubar)
+ self.top = top = windows.ListedToplevel(root, menu=self.menubar)
if flist:
self.tkinter_vars = flist.vars
#self.top.instance_dict makes flist.inversedict available to
- #configDialog.py so it can access all EditorWindow instances
+ #configdialog.py so it can access all EditorWindow instances
self.top.instance_dict = flist.inversedict
else:
self.tkinter_vars = {} # keys: Tkinter event names
@@ -158,13 +117,10 @@ class EditorWindow(object):
'wrap': 'none',
'highlightthickness': 0,
'width': self.width,
- 'height': idleConf.GetOption('main', 'EditorWindow',
- 'height', type='int')}
- if TkVersion >= 8.5:
- # Starting with tk 8.5 we have to set the new tabstyle option
- # to 'wordprocessor' to achieve the same display of tabs as in
- # older tk versions.
- text_options['tabstyle'] = 'wordprocessor'
+ 'tabstyle': 'wordprocessor', # new in 8.5
+ 'height': idleConf.GetOption(
+ 'main', 'EditorWindow', 'height', type='int'),
+ }
self.text = text = MultiCallCreator(Text)(text_frame, **text_options)
self.top.focused_widget = self.text
@@ -173,7 +129,7 @@ class EditorWindow(object):
self.top.protocol("WM_DELETE_WINDOW", self.close)
self.top.bind("<<close-window>>", self.close_event)
- if macosxSupport.isAquaTk():
+ if macosx.isAquaTk():
# Command-W on editorwindows doesn't work without this.
text.bind('<<close-window>>', self.close_event)
# Some OS X systems have only one mouse button, so use
@@ -309,7 +265,7 @@ class EditorWindow(object):
menu.add_separator()
end = end + 1
self.wmenu_end = end
- WindowList.register_callback(self.postwindowsmenu)
+ windows.register_callback(self.postwindowsmenu)
# Some abstractions so IDLE extensions are cross-IDE
self.askyesno = tkMessageBox.askyesno
@@ -418,7 +374,7 @@ class EditorWindow(object):
underline, label = prepstr(label)
menudict[name] = menu = Menu(mbar, name=name, tearoff=0)
mbar.add_cascade(label=label, menu=menu, underline=underline)
- if macosxSupport.isCarbonTk():
+ if macosx.isCarbonTk():
# Insert the application menu
menudict['application'] = menu = Menu(mbar, name='apple',
tearoff=0)
@@ -439,7 +395,7 @@ class EditorWindow(object):
end = -1
if end > self.wmenu_end:
menu.delete(self.wmenu_end+1, end)
- WindowList.add_windows_to_menu(menu)
+ windows.add_windows_to_menu(menu)
rmenu = None
@@ -507,17 +463,17 @@ class EditorWindow(object):
def about_dialog(self, event=None):
"Handle Help 'About IDLE' event."
- # Synchronize with macosxSupport.overrideRootMenu.about_dialog.
- aboutDialog.AboutDialog(self.top,'About IDLE')
+ # Synchronize with macosx.overrideRootMenu.about_dialog.
+ help_about.AboutDialog(self.top,'About IDLE')
def config_dialog(self, event=None):
"Handle Options 'Configure IDLE' event."
- # Synchronize with macosxSupport.overrideRootMenu.config_dialog.
- configDialog.ConfigDialog(self.top,'Settings')
+ # Synchronize with macosx.overrideRootMenu.config_dialog.
+ configdialog.ConfigDialog(self.top,'Settings')
def help_dialog(self, event=None):
"Handle Help 'IDLE Help' event."
- # Synchronize with macosxSupport.overrideRootMenu.help_dialog.
+ # Synchronize with macosx.overrideRootMenu.help_dialog.
if self.root:
parent = self.root
else:
@@ -590,23 +546,23 @@ class EditorWindow(object):
return "break"
def find_event(self, event):
- SearchDialog.find(self.text)
+ search.find(self.text)
return "break"
def find_again_event(self, event):
- SearchDialog.find_again(self.text)
+ search.find_again(self.text)
return "break"
def find_selection_event(self, event):
- SearchDialog.find_selection(self.text)
+ search.find_selection(self.text)
return "break"
def find_in_files_event(self, event):
- GrepDialog.grep(self.text, self.io, self.flist)
+ grep.grep(self.text, self.io, self.flist)
return "break"
def replace_event(self, event):
- ReplaceDialog.replace(self.text)
+ replace.replace(self.text)
return "break"
def goto_line_event(self, event):
@@ -622,46 +578,27 @@ class EditorWindow(object):
text.see("insert")
def open_module(self, event=None):
- # XXX Shouldn't this be in IOBinding?
+ """Get module name from user and open it.
+
+ Return module path or None for calls by open_class_browser
+ when latter is not invoked in named editor window.
+ """
+ # XXX This, open_class_browser, and open_path_browser
+ # would fit better in iomenu.IOBinding.
try:
- name = self.text.get("sel.first", "sel.last")
+ name = self.text.get("sel.first", "sel.last").strip()
except TclError:
- name = ""
- else:
- name = name.strip()
- name = tkSimpleDialog.askstring("Module",
- "Enter the name of a Python module\n"
- "to search on sys.path and open:",
- parent=self.text, initialvalue=name)
- if name:
- name = name.strip()
- if not name:
- return
- # XXX Ought to insert current file's directory in front of path
- try:
- spec = importlib.util.find_spec(name)
- except (ValueError, ImportError) as msg:
- tkMessageBox.showerror("Import error", str(msg), parent=self.text)
- return
- if spec is None:
- tkMessageBox.showerror("Import error", "module not found",
- parent=self.text)
- return
- if not isinstance(spec.loader, importlib.abc.SourceLoader):
- tkMessageBox.showerror("Import error", "not a source-based module",
- parent=self.text)
- return
- try:
- file_path = spec.loader.get_filename(name)
- except AttributeError:
- tkMessageBox.showerror("Import error",
- "loader does not support get_filename",
- parent=self.text)
- return
- if self.flist:
- self.flist.open(file_path)
- else:
- self.io.loadfile(file_path)
+ name = ''
+ file_path = query.ModuleName(
+ self.text, "Open Module",
+ "Enter the name of a Python module\n"
+ "to search on sys.path and open:",
+ name).result
+ if file_path is not None:
+ if self.flist:
+ self.flist.open(file_path)
+ else:
+ self.io.loadfile(file_path)
return file_path
def open_class_browser(self, event=None):
@@ -673,12 +610,12 @@ class EditorWindow(object):
return
head, tail = os.path.split(filename)
base, ext = os.path.splitext(tail)
- from idlelib import ClassBrowser
- ClassBrowser.ClassBrowser(self.flist, base, [head])
+ from idlelib import browser
+ browser.ClassBrowser(self.flist, base, [head])
def open_path_browser(self, event=None):
- from idlelib import PathBrowser
- PathBrowser.PathBrowser(self.flist)
+ from idlelib import pathbrowser
+ pathbrowser.PathBrowser(self.flist)
def open_turtle_demo(self, event = None):
import subprocess
@@ -739,7 +676,7 @@ class EditorWindow(object):
def ResetColorizer(self):
"Update the color theme"
- # Called from self.filename_change_hook and from configDialog.py
+ # Called from self.filename_change_hook and from configdialog.py
self._rmcolorizer()
self._addcolorizer()
EditorWindow.color_config(self.text)
@@ -759,14 +696,14 @@ class EditorWindow(object):
def ResetFont(self):
"Update the text widgets' font if it is changed"
- # Called from configDialog.py
+ # Called from configdialog.py
self.text['font'] = idleConf.GetFont(self.root, 'main','EditorWindow')
def RemoveKeybindings(self):
"Remove the keybindings before they are changed."
- # Called from configDialog.py
- self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
+ # Called from configdialog.py
+ self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
for event, keylist in keydefs.items():
self.text.event_delete(event, *keylist)
for extensionName in self.get_standard_extension_names():
@@ -777,8 +714,8 @@ class EditorWindow(object):
def ApplyKeybindings(self):
"Update the keybindings after they are changed"
- # Called from configDialog.py
- self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
+ # Called from configdialog.py
+ self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
self.apply_bindings()
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
@@ -786,7 +723,7 @@ class EditorWindow(object):
self.apply_bindings(xkeydefs)
#update menu accelerators
menuEventDict = {}
- for menu in self.Bindings.menudefs:
+ for menu in self.mainmenu.menudefs:
menuEventDict[menu[0]] = {}
for item in menu[1]:
if item:
@@ -813,7 +750,7 @@ class EditorWindow(object):
def set_notabs_indentwidth(self):
"Update the indentwidth if changed and not using tabs in this window"
- # Called from configDialog.py
+ # Called from configdialog.py
if not self.usetabs:
self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
type='int')
@@ -993,7 +930,7 @@ class EditorWindow(object):
def _close(self):
if self.io.filename:
self.update_recent_files_list(new_file=self.io.filename)
- WindowList.unregister_callback(self.postwindowsmenu)
+ windows.unregister_callback(self.postwindowsmenu)
self.unload_extensions()
self.io.close()
self.io = None
@@ -1031,12 +968,25 @@ class EditorWindow(object):
def get_standard_extension_names(self):
return idleConf.GetExtensions(editor_only=True)
+ extfiles = { # map config-extension section names to new file names
+ 'AutoComplete': 'autocomplete',
+ 'AutoExpand': 'autoexpand',
+ 'CallTips': 'calltips',
+ 'CodeContext': 'codecontext',
+ 'FormatParagraph': 'paragraph',
+ 'ParenMatch': 'parenmatch',
+ 'RstripExtension': 'rstrip',
+ 'ScriptBinding': 'runscript',
+ 'ZoomHeight': 'zoomheight',
+ }
+
def load_extension(self, name):
+ fname = self.extfiles.get(name, name)
try:
try:
- mod = importlib.import_module('.' + name, package=__package__)
+ mod = importlib.import_module('.' + fname, package=__package__)
except (ImportError, TypeError):
- mod = importlib.import_module(name)
+ mod = importlib.import_module(fname)
except ImportError:
print("\nFailed to import extension: ", name)
raise
@@ -1060,7 +1010,7 @@ class EditorWindow(object):
def apply_bindings(self, keydefs=None):
if keydefs is None:
- keydefs = self.Bindings.default_keydefs
+ keydefs = self.mainmenu.default_keydefs
text = self.text
text.keydefs = keydefs
for event, keylist in keydefs.items():
@@ -1073,9 +1023,9 @@ class EditorWindow(object):
Menus that are absent or None in self.menudict are ignored.
"""
if menudefs is None:
- menudefs = self.Bindings.menudefs
+ menudefs = self.mainmenu.menudefs
if keydefs is None:
- keydefs = self.Bindings.default_keydefs
+ keydefs = self.mainmenu.default_keydefs
menudict = self.menudict
text = self.text
for mname, entrylist in menudefs:
@@ -1302,7 +1252,7 @@ class EditorWindow(object):
# adjust indentation for continuations and block
# open/close first need to find the last stmt
lno = index2line(text.index('insert'))
- y = PyParse.Parser(self.indentwidth, self.tabwidth)
+ y = pyparse.Parser(self.indentwidth, self.tabwidth)
if not self.context_use_ps1:
for context in self.num_context_lines:
startat = max(lno - context, 1)
@@ -1326,22 +1276,22 @@ class EditorWindow(object):
y.set_lo(0)
c = y.get_continuation_type()
- if c != PyParse.C_NONE:
+ if c != pyparse.C_NONE:
# The current stmt hasn't ended yet.
- if c == PyParse.C_STRING_FIRST_LINE:
+ if c == pyparse.C_STRING_FIRST_LINE:
# after the first line of a string; do not indent at all
pass
- elif c == PyParse.C_STRING_NEXT_LINES:
+ elif c == pyparse.C_STRING_NEXT_LINES:
# inside a string which started before this line;
# just mimic the current indent
text.insert("insert", indent)
- elif c == PyParse.C_BRACKET:
+ elif c == pyparse.C_BRACKET:
# line up with the first (if any) element of the
# last open bracket structure; else indent one
# level beyond the indent of the line with the
# last open bracket
self.reindent_to(y.compute_bracket_indent())
- elif c == PyParse.C_BACKSLASH:
+ elif c == pyparse.C_BACKSLASH:
# if more than one line in this stmt already, just
# mimic the current indent; else if initial line
# has a start on an assignment stmt, indent to
@@ -1569,9 +1519,6 @@ def classifyws(s, tabwidth):
break
return raw, effective
-import tokenize
-_tokenize = tokenize
-del tokenize
class IndentSearcher(object):
@@ -1596,8 +1543,8 @@ class IndentSearcher(object):
return self.text.get(mark, mark + " lineend+1c")
def tokeneater(self, type, token, start, end, line,
- INDENT=_tokenize.INDENT,
- NAME=_tokenize.NAME,
+ INDENT=tokenize.INDENT,
+ NAME=tokenize.NAME,
OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
if self.finished:
pass
@@ -1608,19 +1555,19 @@ class IndentSearcher(object):
self.finished = 1
def run(self):
- save_tabsize = _tokenize.tabsize
- _tokenize.tabsize = self.tabwidth
+ save_tabsize = tokenize.tabsize
+ tokenize.tabsize = self.tabwidth
try:
try:
- tokens = _tokenize.generate_tokens(self.readline)
+ tokens = tokenize.generate_tokens(self.readline)
for token in tokens:
self.tokeneater(*token)
- except (_tokenize.TokenError, SyntaxError):
+ except (tokenize.TokenError, SyntaxError):
# since we cut off the tokenizer early, we can trigger
# spurious errors
pass
finally:
- _tokenize.tabsize = save_tabsize
+ tokenize.tabsize = save_tabsize
return self.blkopenline, self.indentedline
### end autoindent code ###
@@ -1644,7 +1591,7 @@ def get_accelerator(keydefs, eventname):
keylist = keydefs.get(eventname)
# issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5
# if not keylist:
- if (not keylist) or (macosxSupport.isCocoaTk() and eventname in {
+ if (not keylist) or (macosx.isCocoaTk() and eventname in {
"<<open-module>>",
"<<goto-line>>",
"<<change-indentwidth>>"}):
@@ -1679,12 +1626,15 @@ def _editor_window(parent): # htest #
filename = sys.argv[1]
else:
filename = None
- macosxSupport.setupApp(root, None)
+ macosx.setupApp(root, None)
edit = EditorWindow(root=root, filename=filename)
edit.text.bind("<<close-all-windows>>", edit.close_event)
# Does not stop error, neither does following
# edit.text.bind("<<close-window>>", edit.close_event)
if __name__ == '__main__':
+ import unittest
+ unittest.main('idlelib.idle_test.test_editor', verbosity=2, exit=False)
+
from idlelib.idle_test.htest import run
run(_editor_window)
diff --git a/Lib/idlelib/FileList.py b/Lib/idlelib/filelist.py
index a9989a8..f46ad7c 100644
--- a/Lib/idlelib/FileList.py
+++ b/Lib/idlelib/filelist.py
@@ -1,4 +1,5 @@
import os
+
from tkinter import *
import tkinter.messagebox as tkMessageBox
@@ -6,7 +7,7 @@ import tkinter.messagebox as tkMessageBox
class FileList:
# N.B. this import overridden in PyShellFileList.
- from idlelib.EditorWindow import EditorWindow
+ from idlelib.editor import EditorWindow
def __init__(self, root):
self.root = root
@@ -111,7 +112,7 @@ class FileList:
def _test():
- from idlelib.EditorWindow import fixwordbreaks
+ from idlelib.editor import fixwordbreaks
import sys
root = Tk()
fixwordbreaks(root)
diff --git a/Lib/idlelib/GrepDialog.py b/Lib/idlelib/grep.py
index 721b231..64ba28d 100644
--- a/Lib/idlelib/GrepDialog.py
+++ b/Lib/idlelib/grep.py
@@ -1,17 +1,19 @@
-import os
import fnmatch
-import re # for htest
+import os
import sys
-from tkinter import StringVar, BooleanVar, Checkbutton # for GrepDialog
-from tkinter import Tk, Text, Button, SEL, END # for htest
-from idlelib import SearchEngine
-from idlelib.SearchDialogBase import SearchDialogBase
-# Importing OutputWindow fails due to import loop
+
+from tkinter import StringVar, BooleanVar
+from tkinter.ttk import Checkbutton
+
+from idlelib.searchbase import SearchDialogBase
+from idlelib import searchengine
+
+# Importing OutputWindow here fails due to import loop
# EditorWindow -> GrepDialop -> OutputWindow -> EditorWindow
def grep(text, io=None, flist=None):
root = text._root()
- engine = SearchEngine.get(root)
+ engine = searchengine.get(root)
if not hasattr(engine, "_grepdialog"):
engine._grepdialog = GrepDialog(root, engine, flist)
dialog = engine._grepdialog
@@ -47,13 +49,10 @@ class GrepDialog(SearchDialogBase):
self.globent = self.make_entry("In files:", self.globvar)[0]
def create_other_buttons(self):
- f = self.make_frame()[0]
-
- btn = Checkbutton(f, anchor="w",
- variable=self.recvar,
+ btn = Checkbutton(
+ self.make_frame()[0], variable=self.recvar,
text="Recurse down subdirectories")
btn.pack(side="top", fill="both")
- btn.select()
def create_command_buttons(self):
SearchDialogBase.create_command_buttons(self)
@@ -67,7 +66,7 @@ class GrepDialog(SearchDialogBase):
if not path:
self.top.bell()
return
- from idlelib.OutputWindow import OutputWindow # leave here!
+ from idlelib.outwin import OutputWindow # leave here!
save = sys.stdout
try:
sys.stdout = OutputWindow(self.flist)
@@ -131,14 +130,16 @@ class GrepDialog(SearchDialogBase):
def _grep_dialog(parent): # htest #
- from idlelib.PyShell import PyShellFileList
- root = Tk()
- root.title("Test GrepDialog")
- width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
- root.geometry("+%d+%d"%(x, y + 150))
-
- flist = PyShellFileList(root)
- text = Text(root, height=5)
+ from tkinter import Toplevel, Text, SEL, END
+ from tkinter.ttk import Button
+ from idlelib.pyshell import PyShellFileList
+ top = Toplevel(parent)
+ top.title("Test GrepDialog")
+ x, y = map(int, parent.geometry().split('+')[1:])
+ top.geometry("+%d+%d" % (x, y + 175))
+
+ flist = PyShellFileList(top)
+ text = Text(top, height=5)
text.pack()
def show_grep_dialog():
@@ -146,9 +147,8 @@ def _grep_dialog(parent): # htest #
grep(text, flist=flist)
text.tag_remove(SEL, "1.0", END)
- button = Button(root, text="Show GrepDialog", command=show_grep_dialog)
+ button = Button(top, text="Show GrepDialog", command=show_grep_dialog)
button.pack()
- root.mainloop()
if __name__ == "__main__":
import unittest
diff --git a/Lib/idlelib/help.py b/Lib/idlelib/help.py
index a7008e9..77e01a3 100644
--- a/Lib/idlelib/help.py
+++ b/Lib/idlelib/help.py
@@ -4,7 +4,7 @@ Contents are subject to revision at any time, without notice.
Help => About IDLE: diplay About Idle dialog
-<to be moved here from aboutDialog.py>
+<to be moved here from help_about.py>
Help => IDLE Help: Display help.html with proper formatting.
@@ -25,15 +25,14 @@ copy_strip - Copy idle.html to help.html, rstripping each line.
show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog.
"""
from html.parser import HTMLParser
-from os.path import abspath, dirname, isdir, isfile, join
+from os.path import abspath, dirname, isfile, join
from platform import python_version
-from tkinter import Tk, Toplevel, Frame, Text, Scrollbar, Menu, Menubutton
+
+from tkinter import Toplevel, Frame, Text, Menu
+from tkinter.ttk import Menubutton, Scrollbar
from tkinter import font as tkfont
-from idlelib.configHandler import idleConf
-use_ttk = False # until available to import
-if use_ttk:
- from tkinter.ttk import Menubutton
+from idlelib.config import idleConf
## About IDLE ##
@@ -197,15 +196,18 @@ class HelpFrame(Frame):
"Display html text, scrollbar, and toc."
def __init__(self, parent, filename):
Frame.__init__(self, parent)
- text = HelpText(self, filename)
+ # keep references to widgets for test access.
+ self.text = text = HelpText(self, filename)
self['background'] = text['background']
- scroll = Scrollbar(self, command=text.yview)
+ self.toc = toc = self.toc_menu(text)
+ self.scroll = scroll = Scrollbar(self, command=text.yview)
text['yscrollcommand'] = scroll.set
+
self.rowconfigure(0, weight=1)
self.columnconfigure(1, weight=1) # text
- self.toc_menu(text).grid(column=0, row=0, sticky='nw')
- text.grid(column=1, row=0, sticky='nsew')
- scroll.grid(column=2, row=0, sticky='ns')
+ toc.grid(row=0, column=0, sticky='nw')
+ text.grid(row=0, column=1, sticky='nsew')
+ scroll.grid(row=0, column=2, sticky='ns')
def toc_menu(self, text):
"Create table of contents as drop-down menu."
diff --git a/Lib/idlelib/help.txt b/Lib/idlelib/help.txt
deleted file mode 100644
index 89fbe0b..0000000
--- a/Lib/idlelib/help.txt
+++ /dev/null
@@ -1,372 +0,0 @@
-This file, idlelib/help.txt is out-of-date and no longer used by Idle.
-It is deprecated and will be removed in the future, possibly in 3.6
-----------------------------------------------------------------------
-
-[See the end of this file for ** TIPS ** on using IDLE !!]
-
-IDLE is the Python IDE built with the tkinter GUI toolkit.
-
-IDLE has the following features:
--coded in 100% pure Python, using the tkinter GUI toolkit
--cross-platform: works on Windows, Unix, and OS X
--multi-window text editor with multiple undo, Python colorizing, smart indent,
-call tips, and many other features
--Python shell window (a.k.a interactive interpreter)
--debugger (not complete, but you can set breakpoints, view and step)
-
-Menus:
-
-IDLE has two window types the Shell window and the Editor window. It is
-possible to have multiple editor windows simultaneously. IDLE's
-menus dynamically change based on which window is currently selected. Each menu
-documented below indicates which window type it is associated with.
-
-File Menu (Shell and Editor):
-
- New File -- Create a new file editing window
- Open... -- Open an existing file
- Open Module... -- Open an existing module (searches sys.path)
- Recent Files... -- Open a list of recent files
- Class Browser -- Show classes and methods in current file
- Path Browser -- Show sys.path directories, modules, classes,
- and methods
- ---
- Save -- Save current window to the associated file (unsaved
- windows have a * before and after the window title)
-
- Save As... -- Save current window to new file, which becomes
- the associated file
- Save Copy As... -- Save current window to different file
- without changing the associated file
- ---
- Print Window -- Print the current window
- ---
- Close -- Close current window (asks to save if unsaved)
- Exit -- Close all windows, quit (asks to save if unsaved)
-
-Edit Menu (Shell and Editor):
-
- Undo -- Undo last change to current window
- (a maximum of 1000 changes may be undone)
- Redo -- Redo last undone change to current window
- ---
- Cut -- Copy a selection into system-wide clipboard,
- then delete the selection
- Copy -- Copy selection into system-wide clipboard
- Paste -- Insert system-wide clipboard into window
- Select All -- Select the entire contents of the edit buffer
- ---
- Find... -- Open a search dialog box with many options
- Find Again -- Repeat last search
- Find Selection -- Search for the string in the selection
- Find in Files... -- Open a search dialog box for searching files
- Replace... -- Open a search-and-replace dialog box
- Go to Line -- Ask for a line number and show that line
- Expand Word -- Expand the word you have typed to match another
- word in the same buffer; repeat to get a
- different expansion
- Show Calltip -- After an unclosed parenthesis for a function, open
- a small window with function parameter hints
- Show Parens -- Highlight the surrounding parenthesis
- Show Completions -- Open a scroll window allowing selection keywords
- and attributes. (see '*TIPS*', below)
-
-Format Menu (Editor window only):
-
- Indent Region -- Shift selected lines right by the indent width
- (default 4 spaces)
- Dedent Region -- Shift selected lines left by the indent width
- (default 4 spaces)
- Comment Out Region -- Insert ## in front of selected lines
- Uncomment Region -- Remove leading # or ## from selected lines
- Tabify Region -- Turns *leading* stretches of spaces into tabs.
- (Note: We recommend using 4 space blocks to indent Python code.)
- Untabify Region -- Turn *all* tabs into the corrent number of spaces
- Toggle tabs -- Open a dialog to switch between indenting with
- spaces and tabs.
- New Indent Width... -- Open a dialog to change indent width. The
- accepted default by the Python community is 4
- spaces.
- Format Paragraph -- Reformat the current blank-line-separated
- paragraph. All lines in the paragraph will be
- formatted to less than 80 columns.
- ---
- Strip trailing whitespace -- Removed any space characters after the end
- of the last non-space character
-
-Run Menu (Editor window only):
-
- Python Shell -- Open or wake up the Python shell window
- ---
- Check Module -- Check the syntax of the module currently open in the
- Editor window. If the module has not been saved IDLE
- will prompt the user to save the code.
- Run Module -- Restart the shell to clean the environment, then
- execute the currently open module. If the module has
- not been saved IDLE will prompt the user to save the
- code.
-
-Shell Menu (Shell window only):
-
- View Last Restart -- Scroll the shell window to the last Shell restart
- Restart Shell -- Restart the shell to clean the environment
-
-Debug Menu (Shell window only):
-
- Go to File/Line -- Look around the insert point for a filename
- and line number, open the file, and show the line.
- Useful to view the source lines referenced in an
- exception traceback. Available in the context
- menu of the Shell window.
- Debugger (toggle) -- This feature is not complete and considered
- experimental. Run commands in the shell under the
- debugger.
- Stack Viewer -- Show the stack traceback of the last exception
- Auto-open Stack Viewer (toggle) -- Toggle automatically opening the
- stack viewer on unhandled
- exception
-
-Options Menu (Shell and Editor):
-
- Configure IDLE -- Open a configuration dialog. Fonts, indentation,
- keybindings, and color themes may be altered.
- Startup Preferences may be set, and additional Help
- sources can be specified. On OS X, open the
- configuration dialog by selecting Preferences
- in the application menu.
-
- ---
- Code Context (toggle) -- Open a pane at the top of the edit window
- which shows the block context of the section
- of code which is scrolling off the top or the
- window. This is not present in the Shell
- window only the Editor window.
-
-Window Menu (Shell and Editor):
-
- Zoom Height -- Toggles the window between normal size (40x80 initial
- setting) and maximum height. The initial size is in the Configure
- IDLE dialog under the general tab.
- ---
- The rest of this menu lists the names of all open windows;
- select one to bring it to the foreground (deiconifying it if
- necessary).
-
-Help Menu:
-
- About IDLE -- Version, copyright, license, credits
- ---
- IDLE Help -- Display this file which is a help file for IDLE
- detailing the menu options, basic editing and navigation,
- and other tips.
- Python Docs -- Access local Python documentation, if
- installed. Or will start a web browser and open
- docs.python.org showing the latest Python documentation.
- ---
- Additional help sources may be added here with the Configure IDLE
- dialog under the General tab.
-
-Editor context menu (Right-click / Control-click on OS X in Edit window):
-
- Cut -- Copy a selection into system-wide clipboard,
- then delete the selection
- Copy -- Copy selection into system-wide clipboard
- Paste -- Insert system-wide clipboard into window
- Set Breakpoint -- Sets a breakpoint. Breakpoints are only enabled
- when the debugger is open.
- Clear Breakpoint -- Clears the breakpoint on that line
-
-Shell context menu (Right-click / Control-click on OS X in Shell window):
-
- Cut -- Copy a selection into system-wide clipboard,
- then delete the selection
- Copy -- Copy selection into system-wide clipboard
- Paste -- Insert system-wide clipboard into window
- ---
- Go to file/line -- Same as in Debug menu
-
-
-** TIPS **
-==========
-
-Additional Help Sources:
-
- Windows users can Google on zopeshelf.chm to access Zope help files in
- the Windows help format. The Additional Help Sources feature of the
- configuration GUI supports .chm, along with any other filetypes
- supported by your browser. Supply a Menu Item title, and enter the
- location in the Help File Path slot of the New Help Source dialog. Use
- http:// and/or www. to identify external URLs, or download the file and
- browse for its path on your machine using the Browse button.
-
- All users can access the extensive sources of help, including
- tutorials, available at docs.python.org. Selected URLs can be added
- or removed from the Help menu at any time using Configure IDLE.
-
-Basic editing and navigation:
-
- Backspace deletes char to the left; DEL deletes char to the right.
- Control-backspace deletes word left, Control-DEL deletes word right.
- Arrow keys and Page Up/Down move around.
- Control-left/right Arrow moves by words in a strange but useful way.
- Home/End go to begin/end of line.
- Control-Home/End go to begin/end of file.
- Some useful Emacs bindings are inherited from Tcl/Tk:
- Control-a beginning of line
- Control-e end of line
- Control-k kill line (but doesn't put it in clipboard)
- Control-l center window around the insertion point
- Standard keybindings (like Control-c to copy and Control-v to
- paste) may work. Keybindings are selected in the Configure IDLE
- dialog.
-
-Automatic indentation:
-
- After a block-opening statement, the next line is indented by 4 spaces
- (in the Python Shell window by one tab). After certain keywords
- (break, return etc.) the next line is dedented. In leading
- indentation, Backspace deletes up to 4 spaces if they are there. Tab
- inserts spaces (in the Python Shell window one tab), number depends on
- Indent Width. Currently tabs are restricted to four spaces due
- to Tcl/Tk limitations.
-
- See also the indent/dedent region commands in the edit menu.
-
-Completions:
-
- Completions are supplied for functions, classes, and attributes of
- classes, both built-in and user-defined. Completions are also provided
- for filenames.
-
- The AutoCompleteWindow (ACW) will open after a predefined delay
- (default is two seconds) after a '.' or (in a string) an os.sep is
- typed. If after one of those characters (plus zero or more other
- characters) a tab is typed the ACW will open immediately if a possible
- continuation is found.
-
- If there is only one possible completion for the characters entered, a
- tab will supply that completion without opening the ACW.
-
- 'Show Completions' will force open a completions window, by default the
- Control-space keys will open a completions window. In an empty
- string, this will contain the files in the current directory. On a
- blank line, it will contain the built-in and user-defined functions and
- classes in the current name spaces, plus any modules imported. If some
- characters have been entered, the ACW will attempt to be more specific.
-
- If string of characters is typed, the ACW selection will jump to the
- entry most closely matching those characters. Entering a tab will cause
- the longest non-ambiguous match to be entered in the Edit window or
- Shell. Two tabs in a row will supply the current ACW selection, as
- will return or a double click. Cursor keys, Page Up/Down, mouse
- selection, and the scroll wheel all operate on the ACW.
-
- "Hidden" attributes can be accessed by typing the beginning of hidden
- name after a '.', e.g. '_'. This allows access to modules with
- '__all__' set, or to class-private attributes.
-
- Completions and the 'Expand Word' facility can save a lot of typing!
-
- Completions are currently limited to those in the namespaces. Names in
- an Editor window which are not via __main__ or sys.modules will not be
- found. Run the module once with your imports to correct this
- situation. Note that IDLE itself places quite a few modules in
- sys.modules, so much can be found by default, e.g. the re module.
-
- If you don't like the ACW popping up unbidden, simply make the delay
- longer or disable the extension. Or another option is the delay could
- be set to zero. Another alternative to preventing ACW popups is to
- disable the call tips extension.
-
-Python Shell window:
-
- Control-c interrupts executing command.
- Control-d sends end-of-file; closes window if typed at >>> prompt.
- Alt-/ expand word is also useful to reduce typing.
-
- Command history:
-
- Alt-p retrieves previous command matching what you have typed. On OS X
- use Control-p.
- Alt-n retrieves next. On OS X use Control-n.
- Return while cursor is on a previous command retrieves that command.
-
- Syntax colors:
-
- The coloring is applied in a background "thread", so you may
- occasionally see uncolorized text. To change the color
- scheme, use the Configure IDLE / Highlighting dialog.
-
- Python default syntax colors:
-
- Keywords orange
- Builtins royal purple
- Strings green
- Comments red
- Definitions blue
-
- Shell default colors:
-
- Console output brown
- stdout blue
- stderr red
- stdin black
-
-Other preferences:
-
- The font preferences, highlighting, keys, and general preferences can
- be changed via the Configure IDLE menu option. Be sure to note that
- keys can be user defined, IDLE ships with four built in key sets. In
- addition a user can create a custom key set in the Configure IDLE
- dialog under the keys tab.
-
-Command line usage:
-
- Enter idle -h at the command prompt to get a usage message.
-
- idle.py [-c command] [-d] [-e] [-s] [-t title] [arg] ...
-
- -c command run this command
- -d enable debugger
- -e edit mode; arguments are files to be edited
- -s run $IDLESTARTUP or $PYTHONSTARTUP first
- -t title set title of shell window
-
- If there are arguments:
- 1. If -e is used, arguments are files opened for editing and sys.argv
- reflects the arguments passed to IDLE itself.
- 2. Otherwise, if -c is used, all arguments are placed in
- sys.argv[1:...], with sys.argv[0] set to -c.
- 3. Otherwise, if neither -e nor -c is used, the first argument is a
- script which is executed with the remaining arguments in
- sys.argv[1:...] and sys.argv[0] set to the script name. If the
- script name is -, no script is executed but an interactive Python
- session is started; the arguments are still available in sys.argv.
-
-Running without a subprocess: (DEPRECATED in Python 3.4 see Issue 16123)
-
- If IDLE is started with the -n command line switch it will run in a
- single process and will not create the subprocess which runs the RPC
- Python execution server. This can be useful if Python cannot create
- the subprocess or the RPC socket interface on your platform. However,
- in this mode user code is not isolated from IDLE itself. Also, the
- environment is not restarted when Run/Run Module (F5) is selected. If
- your code has been modified, you must reload() the affected modules and
- re-import any specific items (e.g. from foo import baz) if the changes
- are to take effect. For these reasons, it is preferable to run IDLE
- with the default subprocess if at all possible.
-
-Extensions:
-
- IDLE contains an extension facility. See the beginning of
- config-extensions.def in the idlelib directory for further information.
- The default extensions are currently:
-
- FormatParagraph
- AutoExpand
- ZoomHeight
- ScriptBinding
- CallTips
- ParenMatch
- AutoComplete
- CodeContext
diff --git a/Lib/idlelib/aboutDialog.py b/Lib/idlelib/help_about.py
index a8f75d2..071bd3e 100644
--- a/Lib/idlelib/aboutDialog.py
+++ b/Lib/idlelib/help_about.py
@@ -1,11 +1,13 @@
"""About Dialog for IDLE
"""
-
import os
from sys import version
+
from tkinter import *
-from idlelib import textView
+
+from idlelib import textview
+
class AboutDialog(Toplevel):
"""Modal about dialog for idle
@@ -135,17 +137,18 @@ class AboutDialog(Toplevel):
def display_printer_text(self, title, printer):
printer._Printer__setup()
text = '\n'.join(printer._Printer__lines)
- textView.view_text(self, title, text)
+ textview.view_text(self, title, text)
def display_file_text(self, title, filename, encoding=None):
fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)
- textView.view_file(self, title, fn, encoding)
+ textview.view_file(self, title, fn, encoding)
def Ok(self, event=None):
self.destroy()
+
if __name__ == '__main__':
import unittest
- unittest.main('idlelib.idle_test.test_helpabout', verbosity=2, exit=False)
+ unittest.main('idlelib.idle_test.test_help_about', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(AboutDialog)
diff --git a/Lib/idlelib/IdleHistory.py b/Lib/idlelib/history.py
index 078af29..56f53a0 100644
--- a/Lib/idlelib/IdleHistory.py
+++ b/Lib/idlelib/history.py
@@ -1,11 +1,12 @@
"Implement Idle Shell history mechanism with History class"
-from idlelib.configHandler import idleConf
+from idlelib.config import idleConf
+
class History:
''' Implement Idle Shell history mechanism.
- store - Store source statement (called from PyShell.resetoutput).
+ store - Store source statement (called from pyshell.resetoutput).
fetch - Fetch stored statement matching prefix already entered.
history_next - Bound to <<history-next>> event (default Alt-N).
history_prev - Bound to <<history-prev>> event (default Alt-P).
@@ -99,6 +100,7 @@ class History:
self.pointer = None
self.prefix = None
+
if __name__ == "__main__":
from unittest import main
- main('idlelib.idle_test.test_idlehistory', verbosity=2, exit=False)
+ main('idlelib.idle_test.test_history', verbosity=2, exit=False)
diff --git a/Lib/idlelib/HyperParser.py b/Lib/idlelib/hyperparser.py
index 77cb057..450a709 100644
--- a/Lib/idlelib/HyperParser.py
+++ b/Lib/idlelib/hyperparser.py
@@ -4,11 +4,10 @@ HyperParser uses PyParser. PyParser mostly gives information on the
proper indentation of code. HyperParser gives additional information on
the structure of code.
"""
-
-import string
from keyword import iskeyword
-from idlelib import PyParse
+import string
+from idlelib import pyparse
# all ASCII chars that may be in an identifier
_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + "_")
@@ -30,7 +29,7 @@ class HyperParser:
self.editwin = editwin
self.text = text = editwin.text
- parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth)
+ parser = pyparse.Parser(editwin.indentwidth, editwin.tabwidth)
def index2line(index):
return int(float(index))
diff --git a/Lib/idlelib/idle.py b/Lib/idlelib/idle.py
index 141534d..485d5a7 100644
--- a/Lib/idlelib/idle.py
+++ b/Lib/idlelib/idle.py
@@ -1,6 +1,7 @@
import os.path
import sys
+
# Enable running IDLE with idlelib in a non-standard location.
# This was once used to run development versions of IDLE.
# Because PEP 434 declared idle.py a public interface,
@@ -9,5 +10,5 @@ idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if idlelib_dir not in sys.path:
sys.path.insert(0, idlelib_dir)
-from idlelib.PyShell import main # This is subject to change
+from idlelib.pyshell import main # This is subject to change
main()
diff --git a/Lib/idlelib/idle.pyw b/Lib/idlelib/idle.pyw
index 142cb32..e73c049 100644
--- a/Lib/idlelib/idle.pyw
+++ b/Lib/idlelib/idle.pyw
@@ -1,10 +1,10 @@
try:
- import idlelib.PyShell
+ import idlelib.pyshell
except ImportError:
- # IDLE is not installed, but maybe PyShell is on sys.path:
- from . import PyShell
+ # IDLE is not installed, but maybe pyshell is on sys.path:
+ from . import pyshell
import os
- idledir = os.path.dirname(os.path.abspath(PyShell.__file__))
+ idledir = os.path.dirname(os.path.abspath(pyshell.__file__))
if idledir != os.getcwd():
# We're not in the IDLE directory, help the subprocess find run.py
pypath = os.environ.get('PYTHONPATH', '')
@@ -12,6 +12,6 @@ except ImportError:
os.environ['PYTHONPATH'] = pypath + ':' + idledir
else:
os.environ['PYTHONPATH'] = idledir
- PyShell.main()
+ pyshell.main()
else:
- idlelib.PyShell.main()
+ idlelib.pyshell.main()
diff --git a/Lib/idlelib/idle_test/__init__.py b/Lib/idlelib/idle_test/__init__.py
index 845c92d..ad067b4 100644
--- a/Lib/idlelib/idle_test/__init__.py
+++ b/Lib/idlelib/idle_test/__init__.py
@@ -1,6 +1,8 @@
'''idlelib.idle_test is a private implementation of test.test_idle,
which tests the IDLE application as part of the stdlib test suite.
Run IDLE tests alone with "python -m test.test_idle".
+Starting with Python 3.6, IDLE requires tcl/tk 8.5 or later.
+
This package and its contained modules are subject to change and
any direct use is at your own risk.
'''
diff --git a/Lib/idlelib/idle_test/htest.py b/Lib/idlelib/idle_test/htest.py
index 58e62cb..6f676ae 100644
--- a/Lib/idlelib/idle_test/htest.py
+++ b/Lib/idlelib/idle_test/htest.py
@@ -59,19 +59,20 @@ msg: master window hints about testing the widget.
Modules and classes not being tested at the moment:
-PyShell.PyShellEditorWindow
-Debugger.Debugger
-AutoCompleteWindow.AutoCompleteWindow
-OutputWindow.OutputWindow (indirectly being tested with grep test)
+pyshell.PyShellEditorWindow
+debugger.Debugger
+autocomplete_w.AutoCompleteWindow
+outwin.OutputWindow (indirectly being tested with grep test)
'''
from importlib import import_module
-from idlelib.macosxSupport import _initializeTkVariantTests
import tkinter as tk
+from tkinter.ttk import Scrollbar
+tk.NoDefaultRoot()
AboutDialog_spec = {
- 'file': 'aboutDialog',
- 'kwds': {'title': 'aboutDialog test',
+ 'file': 'help_about',
+ 'kwds': {'title': 'help_about test',
'_htest': True,
},
'msg': "Test every button. Ensure Python, TK and IDLE versions "
@@ -79,14 +80,14 @@ AboutDialog_spec = {
}
_calltip_window_spec = {
- 'file': 'CallTipWindow',
+ 'file': 'calltip_w',
'kwds': {},
'msg': "Typing '(' should display a calltip.\n"
"Typing ') should hide the calltip.\n"
}
_class_browser_spec = {
- 'file': 'ClassBrowser',
+ 'file': 'browser',
'kwds': {},
'msg': "Inspect names of module, class(with superclass if "
"applicable), methods and functions.\nToggle nested items.\n"
@@ -95,7 +96,7 @@ _class_browser_spec = {
}
_color_delegator_spec = {
- 'file': 'ColorDelegator',
+ 'file': 'colorizer',
'kwds': {},
'msg': "The text is sample Python code.\n"
"Ensure components like comments, keywords, builtins,\n"
@@ -104,7 +105,7 @@ _color_delegator_spec = {
}
ConfigDialog_spec = {
- 'file': 'configDialog',
+ 'file': 'configdialog',
'kwds': {'title': 'ConfigDialogTest',
'_htest': True,},
'msg': "IDLE preferences dialog.\n"
@@ -121,7 +122,7 @@ ConfigDialog_spec = {
# TODO Improve message
_dyn_option_menu_spec = {
- 'file': 'dynOptionMenuWidget',
+ 'file': 'dynoption',
'kwds': {},
'msg': "Select one of the many options in the 'old option set'.\n"
"Click the button to change the option set.\n"
@@ -130,39 +131,15 @@ _dyn_option_menu_spec = {
# TODO edit wrapper
_editor_window_spec = {
- 'file': 'EditorWindow',
+ 'file': 'editor',
'kwds': {},
'msg': "Test editor functions of interest.\n"
"Best to close editor first."
}
-GetCfgSectionNameDialog_spec = {
- 'file': 'configSectionNameDialog',
- 'kwds': {'title':'Get Name',
- 'message':'Enter something',
- 'used_names': {'abc'},
- '_htest': True},
- 'msg': "After the text entered with [Ok] is stripped, <nothing>, "
- "'abc', or more that 30 chars are errors.\n"
- "Close 'Get Name' with a valid entry (printed to Shell), "
- "[Cancel], or [X]",
- }
-
-GetHelpSourceDialog_spec = {
- 'file': 'configHelpSourceEdit',
- 'kwds': {'title': 'Get helpsource',
- '_htest': True},
- 'msg': "Enter menu item name and help file path\n "
- "<nothing> and more than 30 chars are invalid menu item names.\n"
- "<nothing>, file does not exist are invalid path items.\n"
- "Test for incomplete web address for help file path.\n"
- "A valid entry will be printed to shell with [0k].\n"
- "[Cancel] will print None to shell",
- }
-
# Update once issue21519 is resolved.
GetKeysDialog_spec = {
- 'file': 'keybindingDialog',
+ 'file': 'config_key',
'kwds': {'title': 'Test keybindings',
'action': 'find-again',
'currentKeySequences': [''] ,
@@ -177,7 +154,7 @@ GetKeysDialog_spec = {
}
_grep_dialog_spec = {
- 'file': 'GrepDialog',
+ 'file': 'grep',
'kwds': {},
'msg': "Click the 'Show GrepDialog' button.\n"
"Test the various 'Find-in-files' functions.\n"
@@ -186,8 +163,24 @@ _grep_dialog_spec = {
"should open that file \nin a new EditorWindow."
}
+HelpSource_spec = {
+ 'file': 'query',
+ 'kwds': {'title': 'Help name and source',
+ 'menuitem': 'test',
+ 'filepath': __file__,
+ 'used_names': {'abc'},
+ '_htest': True},
+ 'msg': "Enter menu item name and help file path\n"
+ "'', > than 30 chars, and 'abc' are invalid menu item names.\n"
+ "'' and file does not exist are invalid path items.\n"
+ "Any url ('www...', 'http...') is accepted.\n"
+ "Test Browse with and without path, as cannot unittest.\n"
+ "[Ok] or <Return> prints valid entry to shell\n"
+ "[Cancel] or <Escape> prints None to shell"
+ }
+
_io_binding_spec = {
- 'file': 'IOBinding',
+ 'file': 'iomenu',
'kwds': {},
'msg': "Test the following bindings.\n"
"<Control-o> to open file from dialog.\n"
@@ -200,7 +193,7 @@ _io_binding_spec = {
}
_multi_call_spec = {
- 'file': 'MultiCall',
+ 'file': 'multicall',
'kwds': {},
'msg': "The following actions should trigger a print to console or IDLE"
" Shell.\nEntering and leaving the text area, key entry, "
@@ -210,14 +203,14 @@ _multi_call_spec = {
}
_multistatus_bar_spec = {
- 'file': 'MultiStatusBar',
+ 'file': 'statusbar',
'kwds': {},
'msg': "Ensure presence of multi-status bar below text area.\n"
"Click 'Update Status' to change the multi-status text"
}
_object_browser_spec = {
- 'file': 'ObjectBrowser',
+ 'file': 'debugobj',
'kwds': {},
'msg': "Double click on items upto the lowest level.\n"
"Attributes of the objects and related information "
@@ -225,7 +218,7 @@ _object_browser_spec = {
}
_path_browser_spec = {
- 'file': 'PathBrowser',
+ 'file': 'pathbrowser',
'kwds': {},
'msg': "Test for correct display of all paths in sys.path.\n"
"Toggle nested items upto the lowest level.\n"
@@ -234,7 +227,7 @@ _path_browser_spec = {
}
_percolator_spec = {
- 'file': 'Percolator',
+ 'file': 'percolator',
'kwds': {},
'msg': "There are two tracers which can be toggled using a checkbox.\n"
"Toggling a tracer 'on' by checking it should print tracer"
@@ -244,8 +237,20 @@ _percolator_spec = {
"Test for actions like text entry, and removal."
}
+Query_spec = {
+ 'file': 'query',
+ 'kwds': {'title': 'Query',
+ 'message': 'Enter something',
+ 'text0': 'Go',
+ '_htest': True},
+ 'msg': "Enter with <Return> or [Ok]. Print valid entry to Shell\n"
+ "Blank line, after stripping, is ignored\n"
+ "Close dialog with valid entry, <Escape>, [Cancel], [X]"
+ }
+
+
_replace_dialog_spec = {
- 'file': 'ReplaceDialog',
+ 'file': 'replace',
'kwds': {},
'msg': "Click the 'Replace' button.\n"
"Test various replace options in the 'Replace dialog'.\n"
@@ -253,15 +258,22 @@ _replace_dialog_spec = {
}
_search_dialog_spec = {
- 'file': 'SearchDialog',
+ 'file': 'search',
'kwds': {},
'msg': "Click the 'Search' button.\n"
"Test various search options in the 'Search dialog'.\n"
"Click [Close] or [X] to close the 'Search Dialog'."
}
+_searchbase_spec = {
+ 'file': 'searchbase',
+ 'kwds': {},
+ 'msg': "Check the appearance of the base search dialog\n"
+ "Its only action is to close."
+ }
+
_scrolled_list_spec = {
- 'file': 'ScrolledList',
+ 'file': 'scrolledlist',
'kwds': {},
'msg': "You should see a scrollable list of items\n"
"Selecting (clicking) or double clicking an item "
@@ -277,7 +289,7 @@ show_idlehelp_spec = {
}
_stack_viewer_spec = {
- 'file': 'StackViewer',
+ 'file': 'stackviewer',
'kwds': {},
'msg': "A stacktrace for a NameError exception.\n"
"Expand 'idlelib ...' and '<locals>'.\n"
@@ -295,8 +307,8 @@ _tabbed_pages_spec = {
}
TextViewer_spec = {
- 'file': 'textView',
- 'kwds': {'title': 'Test textView',
+ 'file': 'textview',
+ 'kwds': {'title': 'Test textview',
'text':'The quick brown fox jumps over the lazy dog.\n'*35,
'_htest': True},
'msg': "Test for read-only property of text.\n"
@@ -304,21 +316,21 @@ TextViewer_spec = {
}
_tooltip_spec = {
- 'file': 'ToolTip',
+ 'file': 'tooltip',
'kwds': {},
'msg': "Place mouse cursor over both the buttons\n"
"A tooltip should appear with some text."
}
_tree_widget_spec = {
- 'file': 'TreeWidget',
+ 'file': 'tree',
'kwds': {},
'msg': "The canvas is scrollable.\n"
"Click on folders upto to the lowest level."
}
_undo_delegator_spec = {
- 'file': 'UndoDelegator',
+ 'file': 'undo',
'kwds': {},
'msg': "Click [Undo] to undo any action.\n"
"Click [Redo] to redo any action.\n"
@@ -327,7 +339,7 @@ _undo_delegator_spec = {
}
_widget_redirector_spec = {
- 'file': 'WidgetRedirector',
+ 'file': 'redirector',
'kwds': {},
'msg': "Every text insert should be printed to the console."
"or the IDLE shell."
@@ -337,14 +349,13 @@ def run(*tests):
root = tk.Tk()
root.title('IDLE htest')
root.resizable(0, 0)
- _initializeTkVariantTests(root)
# a scrollable Label like constant width text widget.
frameLabel = tk.Frame(root, padx=10)
frameLabel.pack()
text = tk.Text(frameLabel, wrap='word')
text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70)
- scrollbar = tk.Scrollbar(frameLabel, command=text.yview)
+ scrollbar = Scrollbar(frameLabel, command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(side='right', fill='y', expand=False)
text.pack(side='left', fill='both', expand=True)
@@ -365,11 +376,11 @@ def run(*tests):
test = getattr(mod, test_name)
test_list.append((test_spec, test))
- test_name = tk.StringVar('')
+ test_name = tk.StringVar(root)
callable_object = None
test_kwds = None
- def next():
+ def next_test():
nonlocal test_name, callable_object, test_kwds
if len(test_list) == 1:
@@ -384,20 +395,26 @@ def run(*tests):
text.insert("1.0",test_spec['msg'])
text.configure(state='disabled') # preserve read-only property
- def run_test():
+ def run_test(_=None):
widget = callable_object(**test_kwds)
try:
print(widget.result)
except AttributeError:
pass
- button = tk.Button(root, textvariable=test_name, command=run_test)
+ def close(_=None):
+ root.destroy()
+
+ button = tk.Button(root, textvariable=test_name,
+ default='active', command=run_test)
+ next_button = tk.Button(root, text="Next", command=next_test)
button.pack()
- next_button = tk.Button(root, text="Next", command=next)
next_button.pack()
+ next_button.focus_set()
+ root.bind('<Key-Return>', run_test)
+ root.bind('<Key-Escape>', close)
- next()
-
+ next_test()
root.mainloop()
if __name__ == '__main__':
diff --git a/Lib/idlelib/idle_test/mock_idle.py b/Lib/idlelib/idle_test/mock_idle.py
index 1672a34..c7b49ef 100644
--- a/Lib/idlelib/idle_test/mock_idle.py
+++ b/Lib/idlelib/idle_test/mock_idle.py
@@ -33,7 +33,7 @@ class Func:
class Editor:
- '''Minimally imitate EditorWindow.EditorWindow class.
+ '''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None):
self.text = Text()
@@ -46,7 +46,7 @@ class Editor:
class UndoDelegator:
- '''Minimally imitate UndoDelegator,UndoDelegator class.
+ '''Minimally imitate undo.UndoDelegator class.
'''
# A real undo block is only needed for user interaction.
def undo_block_start(*args):
diff --git a/Lib/idlelib/idle_test/test_autocomplete.py b/Lib/idlelib/idle_test/test_autocomplete.py
index 5fc899d..f3f2dea 100644
--- a/Lib/idlelib/idle_test/test_autocomplete.py
+++ b/Lib/idlelib/idle_test/test_autocomplete.py
@@ -1,9 +1,13 @@
+''' Test autocomplete and autocomple_w
+
+Coverage of autocomple: 56%
+'''
import unittest
from test.support import requires
from tkinter import Tk, Text
-import idlelib.AutoComplete as ac
-import idlelib.AutoCompleteWindow as acw
+import idlelib.autocomplete as ac
+import idlelib.autocomplete_w as acw
from idlelib.idle_test.mock_idle import Func
from idlelib.idle_test.mock_tk import Event
@@ -91,6 +95,11 @@ class AutoCompleteTest(unittest.TestCase):
self.assertIsNone(autocomplete.autocomplete_event(ev))
del ev.mc_state
+ # Test that tab after whitespace is ignored.
+ self.text.insert('1.0', ' """Docstring.\n ')
+ self.assertIsNone(autocomplete.autocomplete_event(ev))
+ self.text.delete('1.0', 'end')
+
# If autocomplete window is open, complete() method is called
self.text.insert('1.0', 're.')
# This must call autocomplete._make_autocomplete_window()
diff --git a/Lib/idlelib/idle_test/test_autoexpand.py b/Lib/idlelib/idle_test/test_autoexpand.py
index d2a3156..ae8186c 100644
--- a/Lib/idlelib/idle_test/test_autoexpand.py
+++ b/Lib/idlelib/idle_test/test_autoexpand.py
@@ -1,9 +1,9 @@
-"""Unit tests for idlelib.AutoExpand"""
+"""Unit tests for idlelib.autoexpand"""
import unittest
from test.support import requires
from tkinter import Text, Tk
#from idlelib.idle_test.mock_tk import Text
-from idlelib.AutoExpand import AutoExpand
+from idlelib.autoexpand import AutoExpand
class Dummy_Editwin:
@@ -22,6 +22,7 @@ class AutoExpandTest(unittest.TestCase):
else:
cls.text = Text()
cls.auto_expand = AutoExpand(Dummy_Editwin(cls.text))
+ cls.auto_expand.bell = lambda: None
@classmethod
def tearDownClass(cls):
@@ -137,5 +138,6 @@ class AutoExpandTest(unittest.TestCase):
new_state = self.auto_expand.state
self.assertNotEqual(initial_state, new_state)
+
if __name__ == '__main__':
unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_calltips.py b/Lib/idlelib/idle_test/test_calltips.py
index b2a733c..0b11602 100644
--- a/Lib/idlelib/idle_test/test_calltips.py
+++ b/Lib/idlelib/idle_test/test_calltips.py
@@ -1,5 +1,5 @@
import unittest
-import idlelib.CallTips as ct
+import idlelib.calltips as ct
import textwrap
import types
diff --git a/Lib/idlelib/idle_test/test_colorizer.py b/Lib/idlelib/idle_test/test_colorizer.py
new file mode 100644
index 0000000..238bc3e
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_colorizer.py
@@ -0,0 +1,56 @@
+'''Test idlelib/colorizer.py
+
+Perform minimal sanity checks that module imports and some things run.
+
+Coverage 22%.
+'''
+from idlelib import colorizer # always test import
+from test.support import requires
+from tkinter import Tk, Text
+import unittest
+
+
+class FunctionTest(unittest.TestCase):
+
+ def test_any(self):
+ self.assertTrue(colorizer.any('test', ('a', 'b')))
+
+ def test_make_pat(self):
+ self.assertTrue(colorizer.make_pat())
+
+
+class ColorConfigTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+ cls.root = Tk()
+ cls.text = Text(cls.root)
+
+ @classmethod
+ def tearDownClass(cls):
+ del cls.text
+ cls.root.destroy()
+ del cls.root
+
+ def test_colorizer(self):
+ colorizer.color_config(self.text)
+
+class ColorDelegatorTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+ cls.root = Tk()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.destroy()
+ del cls.root
+
+ def test_colorizer(self):
+ colorizer.ColorDelegator()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_config.py b/Lib/idlelib/idle_test/test_config.py
new file mode 100644
index 0000000..a3fa1a3
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_config.py
@@ -0,0 +1,160 @@
+'''Test idlelib.config.
+
+Much is tested by opening config dialog live or in test_configdialog.
+Coverage: 27%
+'''
+from sys import modules
+from test.support import captured_stderr
+from tkinter import Tk
+import unittest
+from idlelib import config
+
+# Tests should not depend on fortuitous user configurations.
+# They must not affect actual user .cfg files.
+# Replace user parsers with empty parsers that cannot be saved.
+
+idleConf = config.idleConf
+usercfg = idleConf.userCfg
+testcfg = {}
+usermain = testcfg['main'] = config.IdleUserConfParser('') # filename
+userhigh = testcfg['highlight'] = config.IdleUserConfParser('')
+userkeys = testcfg['keys'] = config.IdleUserConfParser('')
+
+def setUpModule():
+ idleConf.userCfg = testcfg
+
+def tearDownModule():
+ idleConf.userCfg = usercfg
+
+
+class CurrentColorKeysTest(unittest.TestCase):
+ """ Test colorkeys function with user config [Theme] and [Keys] patterns.
+
+ colorkeys = config.IdleConf.current_colors_and_keys
+ Test all patterns written by IDLE and some errors
+ Item 'default' should really be 'builtin' (versus 'custom).
+ """
+ colorkeys = idleConf.current_colors_and_keys
+ default_theme = 'IDLE Classic'
+ default_keys = idleConf.default_keys()
+
+ def test_old_builtin_theme(self):
+ # On initial installation, user main is blank.
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
+ # For old default, name2 must be blank.
+ usermain.read_string('''
+ [Theme]
+ default = True
+ ''')
+ # IDLE omits 'name' for default old builtin theme.
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
+ # IDLE adds 'name' for non-default old builtin theme.
+ usermain['Theme']['name'] = 'IDLE New'
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE New')
+ # Erroneous non-default old builtin reverts to default.
+ usermain['Theme']['name'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
+ usermain.remove_section('Theme')
+
+ def test_new_builtin_theme(self):
+ # IDLE writes name2 for new builtins.
+ usermain.read_string('''
+ [Theme]
+ default = True
+ name2 = IDLE Dark
+ ''')
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
+ # Leftover 'name', not removed, is ignored.
+ usermain['Theme']['name'] = 'IDLE New'
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
+ # Erroneous non-default new builtin reverts to default.
+ usermain['Theme']['name2'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
+ usermain.remove_section('Theme')
+
+ def test_user_override_theme(self):
+ # Erroneous custom name (no definition) reverts to default.
+ usermain.read_string('''
+ [Theme]
+ default = False
+ name = Custom Dark
+ ''')
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
+ # Custom name is valid with matching Section name.
+ userhigh.read_string('[Custom Dark]\na=b')
+ self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
+ # Name2 is ignored.
+ usermain['Theme']['name2'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
+ usermain.remove_section('Theme')
+ userhigh.remove_section('Custom Dark')
+
+ def test_old_builtin_keys(self):
+ # On initial installation, user main is blank.
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
+ # For old default, name2 must be blank, name is always used.
+ usermain.read_string('''
+ [Keys]
+ default = True
+ name = IDLE Classic Unix
+ ''')
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix')
+ # Erroneous non-default old builtin reverts to default.
+ usermain['Keys']['name'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
+ usermain.remove_section('Keys')
+
+ def test_new_builtin_keys(self):
+ # IDLE writes name2 for new builtins.
+ usermain.read_string('''
+ [Keys]
+ default = True
+ name2 = IDLE Modern Unix
+ ''')
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
+ # Leftover 'name', not removed, is ignored.
+ usermain['Keys']['name'] = 'IDLE Classic Unix'
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
+ # Erroneous non-default new builtin reverts to default.
+ usermain['Keys']['name2'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
+ usermain.remove_section('Keys')
+
+ def test_user_override_keys(self):
+ # Erroneous custom name (no definition) reverts to default.
+ usermain.read_string('''
+ [Keys]
+ default = False
+ name = Custom Keys
+ ''')
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
+ # Custom name is valid with matching Section name.
+ userkeys.read_string('[Custom Keys]\na=b')
+ self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
+ # Name2 is ignored.
+ usermain['Keys']['name2'] = 'non-existent'
+ self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
+ usermain.remove_section('Keys')
+ userkeys.remove_section('Custom Keys')
+
+
+class WarningTest(unittest.TestCase):
+
+ def test_warn(self):
+ Equal = self.assertEqual
+ config._warned = set()
+ with captured_stderr() as stderr:
+ config._warn('warning', 'key')
+ Equal(config._warned, {('warning','key')})
+ Equal(stderr.getvalue(), 'warning'+'\n')
+ with captured_stderr() as stderr:
+ config._warn('warning', 'key')
+ Equal(stderr.getvalue(), '')
+ with captured_stderr() as stderr:
+ config._warn('warn2', 'yek')
+ Equal(config._warned, {('warning','key'), ('warn2','yek')})
+ Equal(stderr.getvalue(), 'warn2'+'\n')
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_config_help.py b/Lib/idlelib/idle_test/test_config_help.py
deleted file mode 100644
index 664f8ed..0000000
--- a/Lib/idlelib/idle_test/test_config_help.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Unittests for idlelib.configHelpSourceEdit"""
-import unittest
-from idlelib.idle_test.mock_tk import Var, Mbox, Entry
-from idlelib import configHelpSourceEdit as help_dialog_module
-
-help_dialog = help_dialog_module.GetHelpSourceDialog
-
-
-class Dummy_help_dialog:
- # Mock for testing the following methods of help_dialog
- menu_ok = help_dialog.menu_ok
- path_ok = help_dialog.path_ok
- ok = help_dialog.ok
- cancel = help_dialog.cancel
- # Attributes, constant or variable, needed for tests
- menu = Var()
- entryMenu = Entry()
- path = Var()
- entryPath = Entry()
- result = None
- destroyed = False
-
- def destroy(self):
- self.destroyed = True
-
-
-# menu_ok and path_ok call Mbox.showerror if menu and path are not ok.
-orig_mbox = help_dialog_module.tkMessageBox
-showerror = Mbox.showerror
-
-
-class ConfigHelpTest(unittest.TestCase):
- dialog = Dummy_help_dialog()
-
- @classmethod
- def setUpClass(cls):
- help_dialog_module.tkMessageBox = Mbox
-
- @classmethod
- def tearDownClass(cls):
- help_dialog_module.tkMessageBox = orig_mbox
-
- def test_blank_menu(self):
- self.dialog.menu.set('')
- self.assertFalse(self.dialog.menu_ok())
- self.assertEqual(showerror.title, 'Menu Item Error')
- self.assertIn('No', showerror.message)
-
- def test_long_menu(self):
- self.dialog.menu.set('hello' * 10)
- self.assertFalse(self.dialog.menu_ok())
- self.assertEqual(showerror.title, 'Menu Item Error')
- self.assertIn('long', showerror.message)
-
- def test_good_menu(self):
- self.dialog.menu.set('help')
- showerror.title = 'No Error' # should not be called
- self.assertTrue(self.dialog.menu_ok())
- self.assertEqual(showerror.title, 'No Error')
-
- def test_blank_path(self):
- self.dialog.path.set('')
- self.assertFalse(self.dialog.path_ok())
- self.assertEqual(showerror.title, 'File Path Error')
- self.assertIn('No', showerror.message)
-
- def test_invalid_file_path(self):
- self.dialog.path.set('foobar' * 100)
- self.assertFalse(self.dialog.path_ok())
- self.assertEqual(showerror.title, 'File Path Error')
- self.assertIn('not exist', showerror.message)
-
- def test_invalid_url_path(self):
- self.dialog.path.set('ww.foobar.com')
- self.assertFalse(self.dialog.path_ok())
- self.assertEqual(showerror.title, 'File Path Error')
- self.assertIn('not exist', showerror.message)
-
- self.dialog.path.set('htt.foobar.com')
- self.assertFalse(self.dialog.path_ok())
- self.assertEqual(showerror.title, 'File Path Error')
- self.assertIn('not exist', showerror.message)
-
- def test_good_path(self):
- self.dialog.path.set('https://docs.python.org')
- showerror.title = 'No Error' # should not be called
- self.assertTrue(self.dialog.path_ok())
- self.assertEqual(showerror.title, 'No Error')
-
- def test_ok(self):
- self.dialog.destroyed = False
- self.dialog.menu.set('help')
- self.dialog.path.set('https://docs.python.org')
- self.dialog.ok()
- self.assertEqual(self.dialog.result, ('help',
- 'https://docs.python.org'))
- self.assertTrue(self.dialog.destroyed)
-
- def test_cancel(self):
- self.dialog.destroyed = False
- self.dialog.cancel()
- self.assertEqual(self.dialog.result, None)
- self.assertTrue(self.dialog.destroyed)
-
-if __name__ == '__main__':
- unittest.main(verbosity=2, exit=False)
diff --git a/Lib/idlelib/idle_test/test_config_key.py b/Lib/idlelib/idle_test/test_config_key.py
new file mode 100644
index 0000000..ee3f2c8
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_config_key.py
@@ -0,0 +1,33 @@
+''' Test idlelib.config_key.
+
+Coverage: 56% from creating and closing dialog.
+'''
+from idlelib import config_key
+from test.support import requires
+requires('gui')
+import unittest
+from tkinter import Tk, Text
+
+
+class GetKeysTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.root = Tk()
+ cls.root.withdraw()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.update() # Stop "can't run event command" warning.
+ cls.root.destroy()
+ del cls.root
+
+
+ def test_init(self):
+ dia = config_key.GetKeysDialog(
+ self.root, 'test', '<<Test>>', ['<Key-F12>'], _utest=True)
+ dia.Cancel()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_config_name.py b/Lib/idlelib/idle_test/test_config_name.py
deleted file mode 100644
index 40e72b9..0000000
--- a/Lib/idlelib/idle_test/test_config_name.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""Unit tests for idlelib.configSectionNameDialog"""
-import unittest
-from idlelib.idle_test.mock_tk import Var, Mbox
-from idlelib import configSectionNameDialog as name_dialog_module
-
-name_dialog = name_dialog_module.GetCfgSectionNameDialog
-
-class Dummy_name_dialog:
- # Mock for testing the following methods of name_dialog
- name_ok = name_dialog.name_ok
- Ok = name_dialog.Ok
- Cancel = name_dialog.Cancel
- # Attributes, constant or variable, needed for tests
- used_names = ['used']
- name = Var()
- result = None
- destroyed = False
- def destroy(self):
- self.destroyed = True
-
-# name_ok calls Mbox.showerror if name is not ok
-orig_mbox = name_dialog_module.tkMessageBox
-showerror = Mbox.showerror
-
-class ConfigNameTest(unittest.TestCase):
- dialog = Dummy_name_dialog()
-
- @classmethod
- def setUpClass(cls):
- name_dialog_module.tkMessageBox = Mbox
-
- @classmethod
- def tearDownClass(cls):
- name_dialog_module.tkMessageBox = orig_mbox
-
- def test_blank_name(self):
- self.dialog.name.set(' ')
- self.assertEqual(self.dialog.name_ok(), '')
- self.assertEqual(showerror.title, 'Name Error')
- self.assertIn('No', showerror.message)
-
- def test_used_name(self):
- self.dialog.name.set('used')
- self.assertEqual(self.dialog.name_ok(), '')
- self.assertEqual(showerror.title, 'Name Error')
- self.assertIn('use', showerror.message)
-
- def test_long_name(self):
- self.dialog.name.set('good'*8)
- self.assertEqual(self.dialog.name_ok(), '')
- self.assertEqual(showerror.title, 'Name Error')
- self.assertIn('too long', showerror.message)
-
- def test_good_name(self):
- self.dialog.name.set(' good ')
- showerror.title = 'No Error' # should not be called
- self.assertEqual(self.dialog.name_ok(), 'good')
- self.assertEqual(showerror.title, 'No Error')
-
- def test_ok(self):
- self.dialog.destroyed = False
- self.dialog.name.set('good')
- self.dialog.Ok()
- self.assertEqual(self.dialog.result, 'good')
- self.assertTrue(self.dialog.destroyed)
-
- def test_cancel(self):
- self.dialog.destroyed = False
- self.dialog.Cancel()
- self.assertEqual(self.dialog.result, '')
- self.assertTrue(self.dialog.destroyed)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2, exit=False)
diff --git a/Lib/idlelib/idle_test/test_configdialog.py b/Lib/idlelib/idle_test/test_configdialog.py
index 5c09790..3f94493 100644
--- a/Lib/idlelib/idle_test/test_configdialog.py
+++ b/Lib/idlelib/idle_test/test_configdialog.py
@@ -1,32 +1,127 @@
-'''Test idlelib.configDialog.
+"""Test idlelib.configdialog.
-Coverage: 46% just by creating dialog.
-The other half is code for working with user customizations.
-'''
-from idlelib.configDialog import ConfigDialog # always test import
+Half the class creates dialog, half works with user customizations.
+Coverage: 46% just by creating dialog, 56% with current tests.
+"""
+from idlelib.configdialog import ConfigDialog, idleConf # test import
from test.support import requires
requires('gui')
from tkinter import Tk
import unittest
-from idlelib import macosxSupport as macosx
+import idlelib.config as config
-class ConfigDialogTest(unittest.TestCase):
+# Tests should not depend on fortuitous user configurations.
+# They must not affect actual user .cfg files.
+# Use solution from test_config: empty parsers with no filename.
+usercfg = idleConf.userCfg
+testcfg = {
+ 'main': config.IdleUserConfParser(''),
+ 'highlight': config.IdleUserConfParser(''),
+ 'keys': config.IdleUserConfParser(''),
+ 'extensions': config.IdleUserConfParser(''),
+}
- @classmethod
- def setUpClass(cls):
- cls.root = Tk()
- cls.root.withdraw()
- macosx._initializeTkVariantTests(cls.root)
+# ConfigDialog.changedItems is a 3-level hierarchical dictionary of
+# pending changes that mirrors the multilevel user config dict.
+# For testing, record args in a list for comparison with expected.
+changes = []
+class TestDialog(ConfigDialog):
+ def AddChangedItem(self, *args):
+ changes.append(args)
- @classmethod
- def tearDownClass(cls):
- cls.root.update_idletasks()
- cls.root.destroy()
- del cls.root
+def setUpModule():
+ global root, configure
+ idleConf.userCfg = testcfg
+ root = Tk()
+ root.withdraw()
+ configure = TestDialog(root, 'Test', _utest=True)
- def test_dialog(self):
- d = ConfigDialog(self.root, 'Test', _utest=True)
- d.remove_var_callbacks()
+
+def tearDownModule():
+ global root, configure
+ idleConf.userCfg = testcfg
+ configure.remove_var_callbacks()
+ del configure
+ root.update_idletasks()
+ root.destroy()
+ del root
+
+
+class FontTabTest(unittest.TestCase):
+
+
+ def setUp(self):
+ changes.clear()
+
+ def test_font(self):
+ # Set values guaranteed not to be defaults.
+ dfont = idleConf.GetFont(root, 'main', 'EditorWindow')
+ dsize = str(dfont[1])
+ dbold = dfont[2] == 'bold'
+ configure.fontName.set('Test Font')
+ expected = [
+ ('main', 'EditorWindow', 'font', 'Test Font'),
+ ('main', 'EditorWindow', 'font-size', dsize),
+ ('main', 'EditorWindow', 'font-bold', dbold)]
+ self.assertEqual(changes, expected)
+ changes.clear()
+ configure.fontSize.set(20)
+ expected = [
+ ('main', 'EditorWindow', 'font', 'Test Font'),
+ ('main', 'EditorWindow', 'font-size', '20'),
+ ('main', 'EditorWindow', 'font-bold', dbold)]
+ self.assertEqual(changes, expected)
+ changes.clear()
+ configure.fontBold.set(not dbold)
+ expected = [
+ ('main', 'EditorWindow', 'font', 'Test Font'),
+ ('main', 'EditorWindow', 'font-size', '20'),
+ ('main', 'EditorWindow', 'font-bold', not dbold)]
+ self.assertEqual(changes, expected)
+
+ #def test_sample(self): pass # TODO
+
+ def test_tabspace(self):
+ configure.spaceNum.set(6)
+ self.assertEqual(changes, [('main', 'Indent', 'num-spaces', 6)])
+
+
+class HighlightTest(unittest.TestCase):
+
+ def setUp(self):
+ changes.clear()
+
+ #def test_colorchoose(self): pass # TODO
+
+
+class KeysTest(unittest.TestCase):
+
+ def setUp(self):
+ changes.clear()
+
+
+class GeneralTest(unittest.TestCase):
+
+ def setUp(self):
+ changes.clear()
+
+ def test_startup(self):
+ configure.radioStartupEdit.invoke()
+ self.assertEqual(changes,
+ [('main', 'General', 'editor-on-startup', 1)])
+
+ def test_autosave(self):
+ configure.radioSaveAuto.invoke()
+ self.assertEqual(changes, [('main', 'General', 'autosave', 1)])
+
+ def test_editor_size(self):
+ configure.entryWinHeight.insert(0, '1')
+ self.assertEqual(changes, [('main', 'EditorWindow', 'height', '140')])
+ changes.clear()
+ configure.entryWinWidth.insert(0, '1')
+ self.assertEqual(changes, [('main', 'EditorWindow', 'width', '180')])
+
+ #def test_help_sources(self): pass # TODO
if __name__ == '__main__':
diff --git a/Lib/idlelib/idle_test/test_debugger.py b/Lib/idlelib/idle_test/test_debugger.py
new file mode 100644
index 0000000..bcba9a4
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_debugger.py
@@ -0,0 +1,29 @@
+''' Test idlelib.debugger.
+
+Coverage: 19%
+'''
+from idlelib import debugger
+from test.support import requires
+requires('gui')
+import unittest
+from tkinter import Tk
+
+
+class NameSpaceTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.root = Tk()
+ cls.root.withdraw()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.destroy()
+ del cls.root
+
+ def test_init(self):
+ debugger.NamespaceViewer(self.root, 'Test')
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_delegator.py b/Lib/idlelib/idle_test/test_delegator.py
index 1f0baa9..85624fb 100644
--- a/Lib/idlelib/idle_test/test_delegator.py
+++ b/Lib/idlelib/idle_test/test_delegator.py
@@ -1,5 +1,5 @@
import unittest
-from idlelib.Delegator import Delegator
+from idlelib.delegator import Delegator
class DelegatorTest(unittest.TestCase):
diff --git a/Lib/idlelib/idle_test/test_editmenu.py b/Lib/idlelib/idle_test/test_editmenu.py
index a258e29..17eb25c 100644
--- a/Lib/idlelib/idle_test/test_editmenu.py
+++ b/Lib/idlelib/idle_test/test_editmenu.py
@@ -5,8 +5,9 @@ Edit modules have their own test files files
from test.support import requires
requires('gui')
import tkinter as tk
+from tkinter import ttk
import unittest
-from idlelib import PyShell
+from idlelib import pyshell
class PasteTest(unittest.TestCase):
'''Test pasting into widgets that allow pasting.
@@ -16,17 +17,18 @@ class PasteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = root = tk.Tk()
- root.withdraw()
- PyShell.fix_x11_paste(root)
+ cls.root.withdraw()
+ pyshell.fix_x11_paste(root)
cls.text = tk.Text(root)
cls.entry = tk.Entry(root)
+ cls.tentry = ttk.Entry(root)
cls.spin = tk.Spinbox(root)
root.clipboard_clear()
root.clipboard_append('two')
@classmethod
def tearDownClass(cls):
- del cls.text, cls.entry, cls.spin
+ del cls.text, cls.entry, cls.tentry
cls.root.clipboard_clear()
cls.root.update_idletasks()
cls.root.destroy()
@@ -44,16 +46,16 @@ class PasteTest(unittest.TestCase):
def test_paste_entry(self):
"Test pasting into an entry with and without a selection."
- # On 3.6, generated <<Paste>> fails without empty select range
- # for 'no selection'. Live widget works fine.
- entry = self.entry
- for end, ans in (0, 'onetwo'), ('end', 'two'):
- with self.subTest(entry=entry, end=end, ans=ans):
- entry.delete(0, 'end')
- entry.insert(0, 'one')
- entry.select_range(0, end) # see note
- entry.event_generate('<<Paste>>')
- self.assertEqual(entry.get(), ans)
+ # Generated <<Paste>> fails for tk entry without empty select
+ # range for 'no selection'. Live widget works fine.
+ for entry in self.entry, self.tentry:
+ for end, ans in (0, 'onetwo'), ('end', 'two'):
+ with self.subTest(entry=entry, end=end, ans=ans):
+ entry.delete(0, 'end')
+ entry.insert(0, 'one')
+ entry.select_range(0, end)
+ entry.event_generate('<<Paste>>')
+ self.assertEqual(entry.get(), ans)
def test_paste_spin(self):
"Test pasting into a spinbox with and without a selection."
diff --git a/Lib/idlelib/idle_test/test_editor.py b/Lib/idlelib/idle_test/test_editor.py
index a31d26d..e9d29d4 100644
--- a/Lib/idlelib/idle_test/test_editor.py
+++ b/Lib/idlelib/idle_test/test_editor.py
@@ -1,6 +1,6 @@
import unittest
from tkinter import Tk, Text
-from idlelib.EditorWindow import EditorWindow
+from idlelib.editor import EditorWindow
from test.support import requires
class Editor_func_test(unittest.TestCase):
diff --git a/Lib/idlelib/idle_test/test_grep.py b/Lib/idlelib/idle_test/test_grep.py
index 0d8ff0d..6b54c13 100644
--- a/Lib/idlelib/idle_test/test_grep.py
+++ b/Lib/idlelib/idle_test/test_grep.py
@@ -1,5 +1,5 @@
""" !Changing this line will break Test_findfile.test_found!
-Non-gui unit tests for idlelib.GrepDialog methods.
+Non-gui unit tests for grep.GrepDialog methods.
dummy_command calls grep_it calls findfiles.
An exception raised in one method will fail callers.
Otherwise, tests are mostly independent.
@@ -8,7 +8,7 @@ Otherwise, tests are mostly independent.
import unittest
from test.support import captured_stdout
from idlelib.idle_test.mock_tk import Var
-from idlelib.GrepDialog import GrepDialog
+from idlelib.grep import GrepDialog
import re
class Dummy_searchengine:
@@ -72,7 +72,7 @@ class Grep_itTest(unittest.TestCase):
self.assertTrue(lines[4].startswith('(Hint:'))
class Default_commandTest(unittest.TestCase):
- # To write this, mode OutputWindow import to top of GrepDialog
+ # To write this, move outwin import to top of GrepDialog
# so it can be replaced by captured_stdout in class setup/teardown.
pass
diff --git a/Lib/idlelib/idle_test/test_help.py b/Lib/idlelib/idle_test/test_help.py
new file mode 100644
index 0000000..2c68e23
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_help.py
@@ -0,0 +1,34 @@
+'''Test idlelib.help.
+
+Coverage: 87%
+'''
+from idlelib import help
+from test.support import requires
+requires('gui')
+from os.path import abspath, dirname, join
+from tkinter import Tk
+import unittest
+
+class HelpFrameTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ "By itself, this tests that file parsed without exception."
+ cls.root = root = Tk()
+ root.withdraw()
+ helpfile = join(dirname(dirname(abspath(__file__))), 'help.html')
+ cls.frame = help.HelpFrame(root, helpfile)
+
+ @classmethod
+ def tearDownClass(cls):
+ del cls.frame
+ cls.root.update_idletasks()
+ cls.root.destroy()
+ del cls.root
+
+ def test_line1(self):
+ text = self.frame.text
+ self.assertEqual(text.get('1.0', '1.end'), ' IDLE ')
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_help_about.py b/Lib/idlelib/idle_test/test_help_about.py
index d0a0127..843efb9 100644
--- a/Lib/idlelib/idle_test/test_help_about.py
+++ b/Lib/idlelib/idle_test/test_help_about.py
@@ -2,10 +2,10 @@
Coverage:
'''
-from idlelib import aboutDialog as help_about
-from idlelib import textView as textview
+from idlelib import help_about
+from idlelib import textview
from idlelib.idle_test.mock_idle import Func
-from idlelib.idle_test.mock_tk import Mbox
+from idlelib.idle_test.mock_tk import Mbox_func
import unittest
About = help_about.AboutDialog
@@ -19,33 +19,33 @@ class Dummy_about_dialog():
class DisplayFileTest(unittest.TestCase):
- "Test that .txt files are found and properly decoded."
dialog = Dummy_about_dialog()
@classmethod
def setUpClass(cls):
- cls.orig_mbox = textview.tkMessageBox
+ cls.orig_error = textview.showerror
cls.orig_view = textview.view_text
- cls.mbox = Mbox()
+ cls.error = Mbox_func()
cls.view = Func()
- textview.tkMessageBox = cls.mbox
+ textview.showerror = cls.error
textview.view_text = cls.view
cls.About = Dummy_about_dialog()
@classmethod
def tearDownClass(cls):
- textview.tkMessageBox = cls.orig_mbox
+ textview.showerror = cls.orig_error
textview.view_text = cls.orig_view
def test_file_isplay(self):
for handler in (self.dialog.idle_credits,
self.dialog.idle_readme,
self.dialog.idle_news):
- self.mbox.showerror.message = ''
+ self.error.message = ''
self.view.called = False
- handler()
- self.assertEqual(self.mbox.showerror.message, '')
- self.assertEqual(self.view.called, True)
+ with self.subTest(handler=handler):
+ handler()
+ self.assertEqual(self.error.message, '')
+ self.assertEqual(self.view.called, True)
if __name__ == '__main__':
diff --git a/Lib/idlelib/idle_test/test_idlehistory.py b/Lib/idlelib/idle_test/test_history.py
index 6e7c6c3..b278010 100644
--- a/Lib/idlelib/idle_test/test_idlehistory.py
+++ b/Lib/idlelib/idle_test/test_history.py
@@ -4,8 +4,8 @@ from test.support import requires
import tkinter as tk
from tkinter import Text as tkText
from idlelib.idle_test.mock_tk import Text as mkText
-from idlelib.IdleHistory import History
-from idlelib.configHandler import idleConf
+from idlelib.history import History
+from idlelib.config import idleConf
line1 = 'a = 7'
line2 = 'b = a'
diff --git a/Lib/idlelib/idle_test/test_hyperparser.py b/Lib/idlelib/idle_test/test_hyperparser.py
index 9ce3f2c..73c8281 100644
--- a/Lib/idlelib/idle_test/test_hyperparser.py
+++ b/Lib/idlelib/idle_test/test_hyperparser.py
@@ -1,9 +1,9 @@
-"""Unittest for idlelib.HyperParser"""
+"""Unittest for idlelib.hyperparser.py."""
import unittest
from test.support import requires
from tkinter import Tk, Text
-from idlelib.EditorWindow import EditorWindow
-from idlelib.HyperParser import HyperParser
+from idlelib.editor import EditorWindow
+from idlelib.hyperparser import HyperParser
class DummyEditwin:
def __init__(self, text):
diff --git a/Lib/idlelib/idle_test/test_io.py b/Lib/idlelib/idle_test/test_iomenu.py
index e0e3b98..65bf593 100644
--- a/Lib/idlelib/idle_test/test_io.py
+++ b/Lib/idlelib/idle_test/test_iomenu.py
@@ -1,6 +1,7 @@
import unittest
import io
-from idlelib.PyShell import PseudoInputFile, PseudoOutputFile
+
+from idlelib.run import PseudoInputFile, PseudoOutputFile
class S(str):
@@ -230,4 +231,4 @@ class PseudeInputFilesTest(unittest.TestCase):
if __name__ == '__main__':
- unittest.main()
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_macosx.py b/Lib/idlelib/idle_test/test_macosx.py
new file mode 100644
index 0000000..fae75d8
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_macosx.py
@@ -0,0 +1,103 @@
+'''Test idlelib.macosx.py.
+
+Coverage: 71% on Windows.
+'''
+from idlelib import macosx
+from test.support import requires
+import sys
+import tkinter as tk
+import unittest
+import unittest.mock as mock
+from idlelib.filelist import FileList
+
+mactypes = {'carbon', 'cocoa', 'xquartz'}
+nontypes = {'other'}
+alltypes = mactypes | nontypes
+
+
+class InitTktypeTest(unittest.TestCase):
+ "Test _init_tk_type."
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+ cls.root = tk.Tk()
+ cls.root.withdraw()
+ cls.orig_platform = macosx.platform
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.update_idletasks()
+ cls.root.destroy()
+ del cls.root
+ macosx.platform = cls.orig_platform
+
+ def test_init_sets_tktype(self):
+ "Test that _init_tk_type sets _tk_type according to platform."
+ for platform, types in ('darwin', alltypes), ('other', nontypes):
+ with self.subTest(platform=platform):
+ macosx.platform = platform
+ macosx._tk_type == None
+ macosx._init_tk_type()
+ self.assertIn(macosx._tk_type, types)
+
+
+class IsTypeTkTest(unittest.TestCase):
+ "Test each of the four isTypeTk predecates."
+ isfuncs = ((macosx.isAquaTk, ('carbon', 'cocoa')),
+ (macosx.isCarbonTk, ('carbon')),
+ (macosx.isCocoaTk, ('cocoa')),
+ (macosx.isXQuartz, ('xquartz')),
+ )
+
+ @mock.patch('idlelib.macosx._init_tk_type')
+ def test_is_calls_init(self, mockinit):
+ "Test that each isTypeTk calls _init_tk_type when _tk_type is None."
+ macosx._tk_type = None
+ for func, whentrue in self.isfuncs:
+ with self.subTest(func=func):
+ func()
+ self.assertTrue(mockinit.called)
+ mockinit.reset_mock()
+
+ def test_isfuncs(self):
+ "Test that each isTypeTk return correct bool."
+ for func, whentrue in self.isfuncs:
+ for tktype in alltypes:
+ with self.subTest(func=func, whentrue=whentrue, tktype=tktype):
+ macosx._tk_type = tktype
+ (self.assertTrue if tktype in whentrue else self.assertFalse)\
+ (func())
+
+
+class SetupTest(unittest.TestCase):
+ "Test setupApp."
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+ cls.root = tk.Tk()
+ cls.root.withdraw()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.update_idletasks()
+ cls.root.destroy()
+ del cls.root
+
+ @mock.patch('idlelib.macosx.overrideRootMenu') #27312
+ def test_setupapp(self, overrideRootMenu):
+ "Call setupApp with each possible graphics type."
+ root = self.root
+ flist = FileList(root)
+ for tktype in alltypes:
+ with self.subTest(tktype=tktype):
+ macosx._tk_type = tktype
+ macosx.setupApp(root, flist)
+ if tktype in ('carbon', 'cocoa'):
+ self.assertTrue(overrideRootMenu.called)
+ overrideRootMenu.reset_mock()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_formatparagraph.py b/Lib/idlelib/idle_test/test_paragraph.py
index b6eb2f3..ba350c9 100644
--- a/Lib/idlelib/idle_test/test_formatparagraph.py
+++ b/Lib/idlelib/idle_test/test_paragraph.py
@@ -1,7 +1,7 @@
-# Test the functions and main class method of FormatParagraph.py
+# Test the functions and main class method of paragraph.py
import unittest
-from idlelib import FormatParagraph as fp
-from idlelib.EditorWindow import EditorWindow
+from idlelib import paragraph as fp
+from idlelib.editor import EditorWindow
from tkinter import Tk, Text
from test.support import requires
@@ -38,7 +38,7 @@ class Is_Get_Test(unittest.TestCase):
class FindTest(unittest.TestCase):
- """Test the find_paragraph function in FormatParagraph.
+ """Test the find_paragraph function in paragraph module.
Using the runcase() function, find_paragraph() is called with 'mark' set at
multiple indexes before and inside the test paragraph.
diff --git a/Lib/idlelib/idle_test/test_parenmatch.py b/Lib/idlelib/idle_test/test_parenmatch.py
index 95cc22c..051f7ea 100644
--- a/Lib/idlelib/idle_test/test_parenmatch.py
+++ b/Lib/idlelib/idle_test/test_parenmatch.py
@@ -1,4 +1,4 @@
-'''Test idlelib.ParenMatch.
+'''Test idlelib.parenmatch.
This must currently be a gui test because ParenMatch methods use
several text methods not defined on idlelib.idle_test.mock_tk.Text.
@@ -9,7 +9,7 @@ requires('gui')
import unittest
from unittest.mock import Mock
from tkinter import Tk, Text
-from idlelib.ParenMatch import ParenMatch
+from idlelib.parenmatch import ParenMatch
class DummyEditwin:
def __init__(self, text):
@@ -38,12 +38,17 @@ class ParenMatchTest(unittest.TestCase):
def tearDown(self):
self.text.delete('1.0', 'end')
+ def get_parenmatch(self):
+ pm = ParenMatch(self.editwin)
+ pm.bell = lambda: None
+ return pm
+
def test_paren_expression(self):
"""
Test ParenMatch with 'expression' style.
"""
text = self.text
- pm = ParenMatch(self.editwin)
+ pm = self.get_parenmatch()
pm.set_style('expression')
text.insert('insert', 'def foobar(a, b')
@@ -66,7 +71,7 @@ class ParenMatchTest(unittest.TestCase):
Test ParenMatch with 'default' style.
"""
text = self.text
- pm = ParenMatch(self.editwin)
+ pm = self.get_parenmatch()
pm.set_style('default')
text.insert('insert', 'def foobar(a, b')
@@ -86,7 +91,7 @@ class ParenMatchTest(unittest.TestCase):
These cases force conditional expression and alternate paths.
"""
text = self.text
- pm = ParenMatch(self.editwin)
+ pm = self.get_parenmatch()
text.insert('insert', '# this is a commen)')
self.assertIsNone(pm.paren_closed_event('event'))
@@ -99,7 +104,7 @@ class ParenMatchTest(unittest.TestCase):
self.assertIsNone(pm.paren_closed_event('event'))
def test_handle_restore_timer(self):
- pm = ParenMatch(self.editwin)
+ pm = self.get_parenmatch()
pm.restore_event = Mock()
pm.handle_restore_timer(0)
self.assertTrue(pm.restore_event.called)
diff --git a/Lib/idlelib/idle_test/test_pathbrowser.py b/Lib/idlelib/idle_test/test_pathbrowser.py
index afb886f..813cbcc 100644
--- a/Lib/idlelib/idle_test/test_pathbrowser.py
+++ b/Lib/idlelib/idle_test/test_pathbrowser.py
@@ -2,13 +2,13 @@ import unittest
import os
import sys
import idlelib
-from idlelib import PathBrowser
+from idlelib import pathbrowser
class PathBrowserTest(unittest.TestCase):
def test_DirBrowserTreeItem(self):
# Issue16226 - make sure that getting a sublist works
- d = PathBrowser.DirBrowserTreeItem('')
+ d = pathbrowser.DirBrowserTreeItem('')
d.GetSubList()
self.assertEqual('', d.GetText())
@@ -17,11 +17,11 @@ class PathBrowserTest(unittest.TestCase):
self.assertEqual(d.ispackagedir(dir + '/Icons'), False)
def test_PathBrowserTreeItem(self):
- p = PathBrowser.PathBrowserTreeItem()
+ p = pathbrowser.PathBrowserTreeItem()
self.assertEqual(p.GetText(), 'sys.path')
sub = p.GetSubList()
self.assertEqual(len(sub), len(sys.path))
- self.assertEqual(type(sub[0]), PathBrowser.DirBrowserTreeItem)
+ self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem)
if __name__ == '__main__':
unittest.main(verbosity=2, exit=False)
diff --git a/Lib/idlelib/idle_test/test_percolator.py b/Lib/idlelib/idle_test/test_percolator.py
index 4c0a7ad..573b9a1 100644
--- a/Lib/idlelib/idle_test/test_percolator.py
+++ b/Lib/idlelib/idle_test/test_percolator.py
@@ -1,10 +1,10 @@
-'''Test Percolator'''
+'''Test percolator.py.'''
from test.support import requires
requires('gui')
import unittest
from tkinter import Text, Tk, END
-from idlelib.Percolator import Percolator, Delegator
+from idlelib.percolator import Percolator, Delegator
class MyFilter(Delegator):
diff --git a/Lib/idlelib/idle_test/test_query.py b/Lib/idlelib/idle_test/test_query.py
new file mode 100644
index 0000000..66af8eb
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_query.py
@@ -0,0 +1,353 @@
+"""Test idlelib.query.
+
+Non-gui tests for Query, SectionName, ModuleName, and HelpSource use
+dummy versions that extract the non-gui methods and add other needed
+attributes. GUI tests create an instance of each class and simulate
+entries and button clicks. Subclass tests only target the new code in
+the subclass definition.
+
+The appearance of the widgets is checked by the Query and
+HelpSource htests. These are run by running query.py.
+
+Coverage: 94% (100% for Query and SectionName).
+6 of 8 missing are ModuleName exceptions I don't know how to trigger.
+"""
+from test.support import requires
+import sys
+from tkinter import Tk
+import unittest
+from unittest import mock
+from idlelib.idle_test.mock_tk import Var
+from idlelib import query
+
+
+# NON-GUI TESTS
+
+class QueryTest(unittest.TestCase):
+ "Test Query base class."
+
+ class Dummy_Query:
+ # Test the following Query methods.
+ entry_ok = query.Query.entry_ok
+ ok = query.Query.ok
+ cancel = query.Query.cancel
+ # Add attributes and initialization needed for tests.
+ entry = Var()
+ entry_error = {}
+ def __init__(self, dummy_entry):
+ self.entry.set(dummy_entry)
+ self.entry_error['text'] = ''
+ self.result = None
+ self.destroyed = False
+ def showerror(self, message):
+ self.entry_error['text'] = message
+ def destroy(self):
+ self.destroyed = True
+
+ def test_entry_ok_blank(self):
+ dialog = self.Dummy_Query(' ')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertEqual((dialog.result, dialog.destroyed), (None, False))
+ self.assertIn('blank line', dialog.entry_error['text'])
+
+ def test_entry_ok_good(self):
+ dialog = self.Dummy_Query(' good ')
+ Equal = self.assertEqual
+ Equal(dialog.entry_ok(), 'good')
+ Equal((dialog.result, dialog.destroyed), (None, False))
+ Equal(dialog.entry_error['text'], '')
+
+ def test_ok_blank(self):
+ dialog = self.Dummy_Query('')
+ dialog.entry.focus_set = mock.Mock()
+ self.assertEqual(dialog.ok(), None)
+ self.assertTrue(dialog.entry.focus_set.called)
+ del dialog.entry.focus_set
+ self.assertEqual((dialog.result, dialog.destroyed), (None, False))
+
+ def test_ok_good(self):
+ dialog = self.Dummy_Query('good')
+ self.assertEqual(dialog.ok(), None)
+ self.assertEqual((dialog.result, dialog.destroyed), ('good', True))
+
+ def test_cancel(self):
+ dialog = self.Dummy_Query('does not matter')
+ self.assertEqual(dialog.cancel(), None)
+ self.assertEqual((dialog.result, dialog.destroyed), (None, True))
+
+
+class SectionNameTest(unittest.TestCase):
+ "Test SectionName subclass of Query."
+
+ class Dummy_SectionName:
+ entry_ok = query.SectionName.entry_ok # Function being tested.
+ used_names = ['used']
+ entry = Var()
+ entry_error = {}
+ def __init__(self, dummy_entry):
+ self.entry.set(dummy_entry)
+ self.entry_error['text'] = ''
+ def showerror(self, message):
+ self.entry_error['text'] = message
+
+ def test_blank_section_name(self):
+ dialog = self.Dummy_SectionName(' ')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('no name', dialog.entry_error['text'])
+
+ def test_used_section_name(self):
+ dialog = self.Dummy_SectionName('used')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('use', dialog.entry_error['text'])
+
+ def test_long_section_name(self):
+ dialog = self.Dummy_SectionName('good'*8)
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('longer than 30', dialog.entry_error['text'])
+
+ def test_good_section_name(self):
+ dialog = self.Dummy_SectionName(' good ')
+ self.assertEqual(dialog.entry_ok(), 'good')
+ self.assertEqual(dialog.entry_error['text'], '')
+
+
+class ModuleNameTest(unittest.TestCase):
+ "Test ModuleName subclass of Query."
+
+ class Dummy_ModuleName:
+ entry_ok = query.ModuleName.entry_ok # Function being tested.
+ text0 = ''
+ entry = Var()
+ entry_error = {}
+ def __init__(self, dummy_entry):
+ self.entry.set(dummy_entry)
+ self.entry_error['text'] = ''
+ def showerror(self, message):
+ self.entry_error['text'] = message
+
+ def test_blank_module_name(self):
+ dialog = self.Dummy_ModuleName(' ')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('no name', dialog.entry_error['text'])
+
+ def test_bogus_module_name(self):
+ dialog = self.Dummy_ModuleName('__name_xyz123_should_not_exist__')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('not found', dialog.entry_error['text'])
+
+ def test_c_source_name(self):
+ dialog = self.Dummy_ModuleName('itertools')
+ self.assertEqual(dialog.entry_ok(), None)
+ self.assertIn('source-based', dialog.entry_error['text'])
+
+ def test_good_module_name(self):
+ dialog = self.Dummy_ModuleName('idlelib')
+ self.assertTrue(dialog.entry_ok().endswith('__init__.py'))
+ self.assertEqual(dialog.entry_error['text'], '')
+
+
+# 3 HelpSource test classes each test one function.
+
+orig_platform = query.platform
+
+class HelpsourceBrowsefileTest(unittest.TestCase):
+ "Test browse_file method of ModuleName subclass of Query."
+
+ class Dummy_HelpSource:
+ browse_file = query.HelpSource.browse_file
+ pathvar = Var()
+
+ def test_file_replaces_path(self):
+ dialog = self.Dummy_HelpSource()
+ # Path is widget entry, either '' or something.
+ # Func return is file dialog return, either '' or something.
+ # Func return should override widget entry.
+ # We need all 4 combination to test all (most) code paths.
+ for path, func, result in (
+ ('', lambda a,b,c:'', ''),
+ ('', lambda a,b,c: __file__, __file__),
+ ('htest', lambda a,b,c:'', 'htest'),
+ ('htest', lambda a,b,c: __file__, __file__)):
+ with self.subTest():
+ dialog.pathvar.set(path)
+ dialog.askfilename = func
+ dialog.browse_file()
+ self.assertEqual(dialog.pathvar.get(), result)
+
+
+class HelpsourcePathokTest(unittest.TestCase):
+ "Test path_ok method of HelpSource subclass of Query."
+
+ class Dummy_HelpSource:
+ path_ok = query.HelpSource.path_ok
+ path = Var()
+ path_error = {}
+ def __init__(self, dummy_path):
+ self.path.set(dummy_path)
+ self.path_error['text'] = ''
+ def showerror(self, message, widget=None):
+ self.path_error['text'] = message
+
+ @classmethod
+ def tearDownClass(cls):
+ query.platform = orig_platform
+
+ def test_path_ok_blank(self):
+ dialog = self.Dummy_HelpSource(' ')
+ self.assertEqual(dialog.path_ok(), None)
+ self.assertIn('no help file', dialog.path_error['text'])
+
+ def test_path_ok_bad(self):
+ dialog = self.Dummy_HelpSource(__file__ + 'bad-bad-bad')
+ self.assertEqual(dialog.path_ok(), None)
+ self.assertIn('not exist', dialog.path_error['text'])
+
+ def test_path_ok_web(self):
+ dialog = self.Dummy_HelpSource('')
+ Equal = self.assertEqual
+ for url in 'www.py.org', 'http://py.org':
+ with self.subTest():
+ dialog.path.set(url)
+ self.assertEqual(dialog.path_ok(), url)
+ self.assertEqual(dialog.path_error['text'], '')
+
+ def test_path_ok_file(self):
+ dialog = self.Dummy_HelpSource('')
+ for platform, prefix in ('darwin', 'file://'), ('other', ''):
+ with self.subTest():
+ query.platform = platform
+ dialog.path.set(__file__)
+ self.assertEqual(dialog.path_ok(), prefix + __file__)
+ self.assertEqual(dialog.path_error['text'], '')
+
+
+class HelpsourceEntryokTest(unittest.TestCase):
+ "Test entry_ok method of HelpSource subclass of Query."
+
+ class Dummy_HelpSource:
+ entry_ok = query.HelpSource.entry_ok
+ entry_error = {}
+ path_error = {}
+ def item_ok(self):
+ return self.name
+ def path_ok(self):
+ return self.path
+
+ def test_entry_ok_helpsource(self):
+ dialog = self.Dummy_HelpSource()
+ for name, path, result in ((None, None, None),
+ (None, 'doc.txt', None),
+ ('doc', None, None),
+ ('doc', 'doc.txt', ('doc', 'doc.txt'))):
+ with self.subTest():
+ dialog.name, dialog.path = name, path
+ self.assertEqual(dialog.entry_ok(), result)
+
+
+# GUI TESTS
+
+class QueryGuiTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+ cls.root = root = Tk()
+ cls.root.withdraw()
+ cls.dialog = query.Query(root, 'TEST', 'test', _utest=True)
+ cls.dialog.destroy = mock.Mock()
+
+ @classmethod
+ def tearDownClass(cls):
+ del cls.dialog
+ cls.root.destroy()
+ del cls.root
+
+ def setUp(self):
+ self.dialog.entry.delete(0, 'end')
+ self.dialog.result = None
+ self.dialog.destroy.reset_mock()
+
+ def test_click_ok(self):
+ dialog = self.dialog
+ dialog.entry.insert(0, 'abc')
+ dialog.button_ok.invoke()
+ self.assertEqual(dialog.result, 'abc')
+ self.assertTrue(dialog.destroy.called)
+
+ def test_click_blank(self):
+ dialog = self.dialog
+ dialog.button_ok.invoke()
+ self.assertEqual(dialog.result, None)
+ self.assertFalse(dialog.destroy.called)
+
+ def test_click_cancel(self):
+ dialog = self.dialog
+ dialog.entry.insert(0, 'abc')
+ dialog.button_cancel.invoke()
+ self.assertEqual(dialog.result, None)
+ self.assertTrue(dialog.destroy.called)
+
+
+class SectionnameGuiTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+
+ def test_click_section_name(self):
+ root = Tk()
+ root.withdraw()
+ dialog = query.SectionName(root, 'T', 't', {'abc'}, _utest=True)
+ Equal = self.assertEqual
+ self.assertEqual(dialog.used_names, {'abc'})
+ dialog.entry.insert(0, 'okay')
+ dialog.button_ok.invoke()
+ self.assertEqual(dialog.result, 'okay')
+ del dialog
+ root.destroy()
+ del root
+
+
+class ModulenameGuiTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+
+ def test_click_module_name(self):
+ root = Tk()
+ root.withdraw()
+ dialog = query.ModuleName(root, 'T', 't', 'idlelib', _utest=True)
+ self.assertEqual(dialog.text0, 'idlelib')
+ self.assertEqual(dialog.entry.get(), 'idlelib')
+ dialog.button_ok.invoke()
+ self.assertTrue(dialog.result.endswith('__init__.py'))
+ del dialog
+ root.destroy()
+ del root
+
+
+class HelpsourceGuiTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ requires('gui')
+
+ def test_click_help_source(self):
+ root = Tk()
+ root.withdraw()
+ dialog = query.HelpSource(root, 'T', menuitem='__test__',
+ filepath=__file__, _utest=True)
+ Equal = self.assertEqual
+ Equal(dialog.entry.get(), '__test__')
+ Equal(dialog.path.get(), __file__)
+ dialog.button_ok.invoke()
+ prefix = "file://" if sys.platform == 'darwin' else ''
+ Equal(dialog.result, ('__test__', prefix + __file__))
+ del dialog
+ root.destroy()
+ del root
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2, exit=False)
diff --git a/Lib/idlelib/idle_test/test_widgetredir.py b/Lib/idlelib/idle_test/test_redirector.py
index baa975d..b0385fa 100644
--- a/Lib/idlelib/idle_test/test_widgetredir.py
+++ b/Lib/idlelib/idle_test/test_redirector.py
@@ -1,4 +1,4 @@
-'''Test idlelib.WidgetRedirector.
+'''Test idlelib.redirector.
100% coverage
'''
@@ -6,7 +6,7 @@ from test.support import requires
import unittest
from idlelib.idle_test.mock_idle import Func
from tkinter import Tk, Text, TclError
-from idlelib.WidgetRedirector import WidgetRedirector
+from idlelib.redirector import WidgetRedirector
class InitCloseTest(unittest.TestCase):
@@ -120,6 +120,5 @@ class WidgetRedirectorTest(unittest.TestCase):
self.assertEqual(self.root.call(self.text._w, 'insert', 'boo'), '')
-
if __name__ == '__main__':
unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_replacedialog.py b/Lib/idlelib/idle_test/test_replace.py
index ff44820..9913ed2 100644
--- a/Lib/idlelib/idle_test/test_replacedialog.py
+++ b/Lib/idlelib/idle_test/test_replace.py
@@ -1,4 +1,4 @@
-"""Unittest for idlelib.ReplaceDialog"""
+"""Unittest for idlelib.replace.py"""
from test.support import requires
requires('gui')
@@ -6,8 +6,8 @@ import unittest
from unittest.mock import Mock
from tkinter import Tk, Text
from idlelib.idle_test.mock_tk import Mbox
-import idlelib.SearchEngine as se
-import idlelib.ReplaceDialog as rd
+import idlelib.searchengine as se
+from idlelib.replace import ReplaceDialog
orig_mbox = se.tkMessageBox
showerror = Mbox.showerror
@@ -21,7 +21,8 @@ class ReplaceDialogTest(unittest.TestCase):
cls.root.withdraw()
se.tkMessageBox = Mbox
cls.engine = se.SearchEngine(cls.root)
- cls.dialog = rd.ReplaceDialog(cls.root, cls.engine)
+ cls.dialog = ReplaceDialog(cls.root, cls.engine)
+ cls.dialog.bell = lambda: None
cls.dialog.ok = Mock()
cls.text = Text(cls.root)
cls.text.undo_block_start = Mock()
@@ -70,7 +71,6 @@ class ReplaceDialogTest(unittest.TestCase):
# text found and replaced
pv.set('a')
rv.set('asdf')
- self.dialog.open(self.text)
replace()
equal(text.get('1.8', '1.12'), 'asdf')
@@ -91,7 +91,7 @@ class ReplaceDialogTest(unittest.TestCase):
text.mark_set('insert', 'end')
text.insert('insert', '\nline42:')
before_text = text.get('1.0', 'end')
- pv.set('[a-z][\d]+')
+ pv.set(r'[a-z][\d]+')
replace()
after_text = text.get('1.0', 'end')
equal(before_text, after_text)
@@ -192,7 +192,7 @@ class ReplaceDialogTest(unittest.TestCase):
self.engine.revar.set(True)
before_text = text.get('1.0', 'end')
- pv.set('[a-z][\d]+')
+ pv.set(r'[a-z][\d]+')
rv.set('hello')
replace()
after_text = text.get('1.0', 'end')
@@ -207,7 +207,7 @@ class ReplaceDialogTest(unittest.TestCase):
self.assertIn('error', showerror.title)
self.assertIn('Empty', showerror.message)
- pv.set('[\d')
+ pv.set(r'[\d')
replace()
self.assertIn('error', showerror.title)
self.assertIn('Pattern', showerror.message)
diff --git a/Lib/idlelib/idle_test/test_rstrip.py b/Lib/idlelib/idle_test/test_rstrip.py
index 1c90b93..130e6be 100644
--- a/Lib/idlelib/idle_test/test_rstrip.py
+++ b/Lib/idlelib/idle_test/test_rstrip.py
@@ -1,5 +1,5 @@
import unittest
-import idlelib.RstripExtension as rs
+import idlelib.rstrip as rs
from idlelib.idle_test.mock_idle import Editor
class rstripTest(unittest.TestCase):
@@ -21,7 +21,7 @@ class rstripTest(unittest.TestCase):
def test_rstrip_multiple(self):
editor = Editor()
# Uncomment following to verify that test passes with real widgets.
-## from idlelib.EditorWindow import EditorWindow as Editor
+## from idlelib.editor import EditorWindow as Editor
## from tkinter import Tk
## editor = Editor(root=Tk())
text = editor.text
diff --git a/Lib/idlelib/idle_test/test_scrolledlist.py b/Lib/idlelib/idle_test/test_scrolledlist.py
new file mode 100644
index 0000000..56aabfe
--- /dev/null
+++ b/Lib/idlelib/idle_test/test_scrolledlist.py
@@ -0,0 +1,29 @@
+''' Test idlelib.scrolledlist.
+
+Coverage: 39%
+'''
+from idlelib import scrolledlist
+from test.support import requires
+requires('gui')
+import unittest
+from tkinter import Tk
+
+
+class ScrolledListTest(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.root = Tk()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.root.destroy()
+ del cls.root
+
+
+ def test_init(self):
+ scrolledlist.ScrolledList(self.root)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/Lib/idlelib/idle_test/test_searchdialog.py b/Lib/idlelib/idle_test/test_search.py
index 190c866..80fa93a 100644
--- a/Lib/idlelib/idle_test/test_searchdialog.py
+++ b/Lib/idlelib/idle_test/test_search.py
@@ -1,4 +1,4 @@
-"""Test SearchDialog class in SearchDialogue.py"""
+"""Test SearchDialog class in idlelib.search.py"""
# Does not currently test the event handler wrappers.
# A usage test should simulate clicks and check hilighting.
@@ -11,8 +11,8 @@ requires('gui')
import unittest
import tkinter as tk
from tkinter import BooleanVar
-import idlelib.SearchEngine as se
-import idlelib.SearchDialog as sd
+import idlelib.searchengine as se
+import idlelib.search as sd
class SearchDialogTest(unittest.TestCase):
@@ -29,6 +29,7 @@ class SearchDialogTest(unittest.TestCase):
def setUp(self):
self.engine = se.SearchEngine(self.root)
self.dialog = sd.SearchDialog(self.root, self.engine)
+ self.dialog.bell = lambda: None
self.text = tk.Text(self.root)
self.text.insert('1.0', 'Hello World!')
@@ -38,6 +39,7 @@ class SearchDialogTest(unittest.TestCase):
self.engine.setpat('')
self.assertFalse(self.dialog.find_again(text))
+ self.dialog.bell = lambda: None
self.engine.setpat('Hello')
self.assertTrue(self.dialog.find_again(text))
diff --git a/Lib/idlelib/idle_test/test_searchdialogbase.py b/Lib/idlelib/idle_test/test_searchbase.py
index 8036b91..d769fa2 100644
--- a/Lib/idlelib/idle_test/test_searchdialogbase.py
+++ b/Lib/idlelib/idle_test/test_searchbase.py
@@ -1,14 +1,13 @@
-'''Unittests for idlelib/SearchDialogBase.py
+'''tests idlelib.searchbase.
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
-
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame ##, BooleanVar, StringVar
-from idlelib import SearchEngine as se
-from idlelib import SearchDialogBase as sdb
+from idlelib import searchengine as se
+from idlelib import searchbase as sdb
from idlelib.idle_test.mock_idle import Func
## from idlelib.idle_test.mock_tk import Var
@@ -74,7 +73,7 @@ class SearchDialogBaseTest(unittest.TestCase):
def test_make_entry(self):
equal = self.assertEqual
self.dialog.row = 0
- self.dialog.top = Toplevel(self.root)
+ self.dialog.top = self.root
entry, label = self.dialog.make_entry("Test:", 'hello')
equal(label['text'], 'Test:')
@@ -87,6 +86,7 @@ class SearchDialogBaseTest(unittest.TestCase):
equal(self.dialog.row, 1)
def test_create_entries(self):
+ self.dialog.top = self.root
self.dialog.row = 0
self.engine.setpat('hello')
self.dialog.create_entries()
@@ -94,7 +94,7 @@ class SearchDialogBaseTest(unittest.TestCase):
def test_make_frame(self):
self.dialog.row = 0
- self.dialog.top = Toplevel(self.root)
+ self.dialog.top = self.root
frame, label = self.dialog.make_frame()
self.assertEqual(label, '')
self.assertIsInstance(frame, Frame)
@@ -104,7 +104,7 @@ class SearchDialogBaseTest(unittest.TestCase):
self.assertIsInstance(frame, Frame)
def btn_test_setup(self, meth):
- self.dialog.top = Toplevel(self.root)
+ self.dialog.top = self.root
self.dialog.row = 0
return meth()
@@ -119,11 +119,6 @@ class SearchDialogBaseTest(unittest.TestCase):
var, label = spec
self.assertEqual(button['text'], label)
self.assertEqual(var.get(), state)
- if state == 1:
- button.deselect()
- else:
- button.select()
- self.assertEqual(var.get(), 1 - state)
def test_create_other_buttons(self):
for state in (False, True):
@@ -139,18 +134,15 @@ class SearchDialogBaseTest(unittest.TestCase):
# hit other button, then this one
# indexes depend on button order
self.assertEqual(var.get(), state)
- buttons[val].select()
- self.assertEqual(var.get(), 1 - state)
- buttons[1-val].select()
- self.assertEqual(var.get(), state)
def test_make_button(self):
- self.dialog.top = Toplevel(self.root)
+ self.dialog.top = self.root
self.dialog.buttonframe = Frame(self.dialog.top)
btn = self.dialog.make_button('Test', self.dialog.close)
self.assertEqual(btn['text'], 'Test')
def test_create_command_buttons(self):
+ self.dialog.top = self.root
self.dialog.create_command_buttons()
# Look for close button command in buttonframe
closebuttoncommand = ''
@@ -160,6 +152,5 @@ class SearchDialogBaseTest(unittest.TestCase):
self.assertIn('close', closebuttoncommand)
-
if __name__ == '__main__':
unittest.main(verbosity=2, exit=2)
diff --git a/Lib/idlelib/idle_test/test_searchengine.py b/Lib/idlelib/idle_test/test_searchengine.py
index edbd558..b3aa8eb 100644
--- a/Lib/idlelib/idle_test/test_searchengine.py
+++ b/Lib/idlelib/idle_test/test_searchengine.py
@@ -1,4 +1,4 @@
-'''Test functions and SearchEngine class in SearchEngine.py.'''
+'''Test functions and SearchEngine class in idlelib.searchengine.py.'''
# With mock replacements, the module does not use any gui widgets.
# The use of tk.Text is avoided (for now, until mock Text is improved)
@@ -10,7 +10,7 @@ import unittest
# from test.support import requires
from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text
import tkinter.messagebox as tkMessageBox
-from idlelib import SearchEngine as se
+from idlelib import searchengine as se
from idlelib.idle_test.mock_tk import Var, Mbox
from idlelib.idle_test.mock_tk import Text as mockText
@@ -139,10 +139,10 @@ class SearchEngineTest(unittest.TestCase):
def test_setcookedpat(self):
engine = self.engine
- engine.setcookedpat('\s')
- self.assertEqual(engine.getpat(), '\s')
+ engine.setcookedpat(r'\s')
+ self.assertEqual(engine.getpat(), r'\s')
engine.revar.set(1)
- engine.setcookedpat('\s')
+ engine.setcookedpat(r'\s')
self.assertEqual(engine.getpat(), r'\\s')
def test_getcookedpat(self):
@@ -156,10 +156,10 @@ class SearchEngineTest(unittest.TestCase):
Equal(engine.getcookedpat(), r'\bhello\b')
engine.wordvar.set(False)
- engine.setpat('\s')
+ engine.setpat(r'\s')
Equal(engine.getcookedpat(), r'\\s')
engine.revar.set(True)
- Equal(engine.getcookedpat(), '\s')
+ Equal(engine.getcookedpat(), r'\s')
def test_getprog(self):
engine = self.engine
@@ -282,7 +282,7 @@ class ForwardBackwardTest(unittest.TestCase):
cls.pat = re.compile('target')
cls.res = (2, (10, 16)) # line, slice indexes of 'target'
cls.failpat = re.compile('xyz') # not in text
- cls.emptypat = re.compile('\w*') # empty match possible
+ cls.emptypat = re.compile(r'\w*') # empty match possible
def make_search(self, func):
def search(pat, line, col, wrap, ok=0):
diff --git a/Lib/idlelib/idle_test/test_text.py b/Lib/idlelib/idle_test/test_text.py
index 7e823df..a5ba7bb 100644
--- a/Lib/idlelib/idle_test/test_text.py
+++ b/Lib/idlelib/idle_test/test_text.py
@@ -1,17 +1,19 @@
-# Test mock_tk.Text class against tkinter.Text class by running same tests with both.
+''' Test mock_tk.Text class against tkinter.Text class
+
+Run same tests with both by creating a mixin class.
+'''
import unittest
from test.support import requires
-
from _tkinter import TclError
class TextTest(object):
+ "Define items common to both sets of tests."
- hw = 'hello\nworld' # usual initial insert after initialization
+ hw = 'hello\nworld' # Several tests insert this after after initialization.
hwn = hw+'\n' # \n present at initialization, before insert
- Text = None
- def setUp(self):
- self.text = self.Text()
+ # setUpClass defines cls.Text and maybe cls.root.
+ # setUp defines self.text from Text and maybe root.
def test_init(self):
self.assertEqual(self.text.get('1.0'), '\n')
@@ -196,6 +198,10 @@ class MockTextTest(TextTest, unittest.TestCase):
from idlelib.idle_test.mock_tk import Text
cls.Text = Text
+ def setUp(self):
+ self.text = self.Text()
+
+
def test_decode(self):
# test endflags (-1, 0) not tested by test_index (which uses +1)
decode = self.text._decode
@@ -222,6 +228,9 @@ class TkTextTest(TextTest, unittest.TestCase):
cls.root.destroy()
del cls.root
+ def setUp(self):
+ self.text = self.Text(self.root)
+
if __name__ == '__main__':
unittest.main(verbosity=2, exit=False)
diff --git a/Lib/idlelib/idle_test/test_textview.py b/Lib/idlelib/idle_test/test_textview.py
index 5d2e600..f018f5e 100644
--- a/Lib/idlelib/idle_test/test_textview.py
+++ b/Lib/idlelib/idle_test/test_textview.py